diff --git a/.github/workflows/build-net6.0.yml b/.github/workflows/build-net6.0.yml deleted file mode 100644 index 06fe7b933..000000000 --- a/.github/workflows/build-net6.0.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: .NET Core 6.0 - -on: - push: - branches: - - main - pull_request: - branches: - - main - - sdk-automation/models - - promote/main - workflow_dispatch: {} - -jobs: - dotnet6-build-and-unit-test: - name: Build and Test on .NET 6.0 - runs-on: ${{ matrix.os }} - - strategy: - matrix: - os: [ ubuntu-latest, windows-latest ] - - steps: - - uses: actions/checkout@v4 - - - name: Setup .NET 6.0 and .NET 8.0 - uses: actions/setup-dotnet@v4 - with: - dotnet-version: | - 6.0.x - 8.0.x - - - name: Restore dependencies - run: dotnet restore - - - name: Build (debug) in .NET 6.0 - run: dotnet build --configuration Debug --framework net6.0 --no-restore - - - name: Run unit tests on .NET 6.0 - run: dotnet test --no-build --configuration Debug --framework net6.0 --no-restore Adyen.Test/Adyen.Test.csproj \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 908e4e64c..471e4fe42 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,8 +33,8 @@ jobs: with: token: ${{ secrets.ADYEN_AUTOMATION_BOT_ACCESS_TOKEN }} develop-branch: main - version-files: Adyen/Adyen.csproj Adyen.Test/Adyen.Test.csproj Adyen/Constants/ClientConfig.cs - release-title: Adyen .net API Library + version-files: Adyen/Adyen.csproj Adyen.Test/Adyen.Test.csproj Adyen/Core/Client/Extensions/HttpRequestMessageExtensions.cs + release-title: Adyen .NET API Library pre-release: ${{ inputs.pre-release || false }} github-release: ${{ inputs.github-release || false }} separator: .pre.beta diff --git a/.gitignore b/.gitignore index 0e77af4de..95d7e0da0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.DS_Store **/.DS_Store .vs/ TestResults/ diff --git a/Adyen.IntegrationTest/Adyen.IntegrationTest.csproj b/Adyen.IntegrationTest/Adyen.IntegrationTest.csproj index 7662e15c7..826f66510 100644 --- a/Adyen.IntegrationTest/Adyen.IntegrationTest.csproj +++ b/Adyen.IntegrationTest/Adyen.IntegrationTest.csproj @@ -1,7 +1,7 @@ - net8.0;net6.0 + net8.0 12 enable disable diff --git a/Adyen.IntegrationTest/BaseTest.cs b/Adyen.IntegrationTest/BaseTest.cs deleted file mode 100644 index 1fcb4e960..000000000 --- a/Adyen.IntegrationTest/BaseTest.cs +++ /dev/null @@ -1,272 +0,0 @@ -using System; -using System.Collections.Generic; - -using System.Threading.Tasks; -using Adyen.Model; -using Adyen.Model.BinLookup; -using Adyen.Model.Checkout; -using Adyen.Model.Payment; -using Adyen.Service; -using Adyen.Service.Checkout; -using Amount = Adyen.Model.Checkout; -using PaymentRequest = Adyen.Model.Payment.PaymentRequest; -using PaymentResult = Adyen.Model.Payment.PaymentResult; -using Environment = Adyen.Model.Environment; -using ExternalPlatform = Adyen.Model.ApplicationInformation.ExternalPlatform; -using Recurring = Adyen.Model.Payment.Recurring; - -namespace Adyen.IntegrationTest -{ - public class BaseTest - { - public PaymentResult CreatePaymentResult() - { - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - var paymentRequest = CreateFullPaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest); - - return paymentResult; - } - - public async Task CreatePaymentResultAsync() - { - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - var paymentRequest = CreateFullPaymentRequest(); - var paymentResult = await payment.AuthoriseAsync(paymentRequest); - - return paymentResult; - } - - public PaymentResult CreatePaymentResultWithApiKeyAuthentication() - { - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - var paymentRequest = CreateFullPaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest); - - return paymentResult; - } - - public PaymentResult CreatePaymentResultWithIdempotency(string idempotency) - { - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - var paymentRequest = CreateFullPaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest, new RequestOptions{ IdempotencyKey=idempotency}); - - return paymentResult; - } - - public PaymentResult CreatePaymentResultWithRecurring(Recurring.ContractEnum contract) - { - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - var paymentRequest = CreateFullPaymentRequestWithRecurring(contract); - var paymentResult = payment.Authorise(paymentRequest); - - return paymentResult; - } - - - /// - /// Creates a payment and returns the psp result - /// - /// - public string GetTestPspReference() - { - //Do test payment - var paymentResult = CreatePaymentResult(); - //Get the psp referense - var paymentResultPspReference = paymentResult.PspReference; - return paymentResultPspReference; - } - - #region Modification objects - - protected CaptureRequest CreateCaptureTestRequest(string pspReference) - { - var captureRequest = new CaptureRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - ModificationAmount = new Adyen.Model.Payment.Amount("EUR", 150), - Reference = "capture - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return captureRequest; - } - - protected CancelOrRefundRequest CreateCancelOrRefundTestRequest(string pspReference) - { - var cancelOrRefundRequest = new CancelOrRefundRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - Reference = "cancelOrRefund - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return cancelOrRefundRequest; - } - - protected RefundRequest CreateRefundTestRequest(string pspReference) - { - var refundRequest = new RefundRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - ModificationAmount = new Adyen.Model.Payment.Amount("EUR", 150), - Reference = "refund - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return refundRequest; - } - - protected CancelRequest CreateCancelTestRequest(string pspReference) - { - var cancelRequest = new CancelRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - Reference = "cancel - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return cancelRequest; - } - protected AdjustAuthorisationRequest CreateAdjustAuthorisationtestRequest(string pspReference) - { - var adjustAuthorisationRequest = new AdjustAuthorisationRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - ModificationAmount = new Adyen.Model.Payment.Amount("EUR", 150), - Reference = "adjust authorisation - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return adjustAuthorisationRequest; - } - - #endregion - - protected Client CreateApiKeyTestClient() - { - var config = new Config() - { - XApiKey = ClientConstants.Xapikey, - Environment = Environment.Test - }; - return new Client(config); - } - - private PaymentRequest CreateFullPaymentRequest() - { - PaymentRequest paymentRequest = new PaymentRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - Amount = new Model.Payment.Amount("EUR", 1500), - Card = CreateTestCard(), - Reference = "payment - " + DateTime.Now.ToString("yyyyMMdd"), - AdditionalData = CreateAdditionalData(), - ApplicationInfo = new Model.Payment.ApplicationInfo() - { - ExternalPlatform = new Model.Payment.ExternalPlatform() - { - Integrator = "test merchant", - Name = "merchant name", - Version = "2.8" - } - } - - }; - paymentRequest.ApplicationInfo.ExternalPlatform = new Model.Payment.ExternalPlatform("test merchant", "merchant name", "2.8"); - return paymentRequest; - } - - private PaymentRequest CreateFullPaymentRequestWithRecurring(Recurring.ContractEnum contract) - { - var paymentRequest = new PaymentRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - Amount = new Model.Payment.Amount("EUR", 1500), - Card = CreateTestCard(), - Reference = "payment - " + DateTime.Now.ToString("yyyyMMdd"), - ShopperReference = "test-1234", - AdditionalData = CreateAdditionalData(), - Recurring = new Recurring { Contract = contract }, - ApplicationInfo = new Model.Payment.ApplicationInfo() - { - ExternalPlatform = new Model.Payment.ExternalPlatform() - { - Integrator = "test merchant", - Name = "merchant name", - Version = "2.8" - } - } - }; - - paymentRequest.ApplicationInfo.ExternalPlatform = new Adyen.Model.Payment.ExternalPlatform("test merchant", "merchant name", "2.8"); - return paymentRequest; - } - - /// - /// Check out payment request - /// - /// - /// - public Model.Checkout.PaymentRequest CreatePaymentRequestCheckout() - { - var amount = new Model.Checkout.Amount("USD", 1000); - var paymentsRequest = new Model.Checkout.PaymentRequest - { - Reference = "Your order number from e2e", - Amount = amount, - ReturnUrl = @"https://your-company.com/...", - MerchantAccount = ClientConstants.MerchantAccount, - }; - var cardDetails = new Model.Checkout.CardDetails() - { - Number = "4111111111111111", - ExpiryMonth = "10", - ExpiryYear = "2020", - HolderName = "John Smith", - Cvc = "737" - }; - paymentsRequest.PaymentMethod = new CheckoutPaymentMethod(cardDetails); - return paymentsRequest; - } - - /// - /// Check out payment IDeal request - /// - /// - /// - public Model.Checkout.PaymentRequest CreatePaymentRequestIDealCheckout() - { - var amount = new Model.Checkout.Amount("EUR", 1000); - var paymentsRequest = new Model.Checkout.PaymentRequest - { - Reference = "Your order number from e2e", - Amount = amount, - PaymentMethod= new Model.Checkout.CheckoutPaymentMethod(new IdealDetails(type: IdealDetails.TypeEnum.Ideal, issuer: "1121")), - ReturnUrl = @"https://your-company.com/...", - MerchantAccount = ClientConstants.MerchantAccount, - }; - - return paymentsRequest; - } - - protected Model.Payment.Card CreateTestCard() - { - return new Model.Payment.Card(number: "4111111111111111", expiryMonth: "03", expiryYear: "2030", cvc: "737", - holderName: "John Smith"); - } - - /// - /// Returns additional data object - /// - /// - private Dictionary CreateAdditionalData() - { - return new Dictionary - { - {"fraudOffset", "0"}, - }; - } - } -} diff --git a/Adyen.IntegrationTest/CancellationTokenTest.cs b/Adyen.IntegrationTest/CancellationTokenTest.cs deleted file mode 100644 index 594f25938..000000000 --- a/Adyen.IntegrationTest/CancellationTokenTest.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Adyen.HttpClient; -using Adyen.HttpClient.Interfaces; -using Adyen.Model; -using Adyen.Service.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class CancellationTokenTest : BaseTest - { - - [TestMethod] - public void CancellationTokenDelayTest() - { - var client = new Client(new Config()) - { - HttpClient = new MyDelayedClient(new Config(), new System.Net.Http.HttpClient()) - }; - var cancellationTokenSource = new CancellationTokenSource(); - cancellationTokenSource.CancelAfter(1000); - - try - { - var service = new PaymentLinksService(client); - var response = service.GetPaymentLinkAsync("linkId", null, cancellationTokenSource.Token).Result; - } - catch (System.AggregateException e) - { - Assert.AreEqual(e.Message, "One or more errors occurred. (A task was canceled.)"); - } - } - } - - public class MyDelayedClient : IClient - { - private readonly System.Net.Http.HttpClient _httpClient; - - public MyDelayedClient(Config config, System.Net.Http.HttpClient httpClient) - { - _httpClient = httpClient; - } - - public string Request(string endpoint, string json, RequestOptions requestOptions = null, - HttpMethod httpMethod = null) - { - throw new NotImplementedException(); - } - - public async Task RequestAsync(string endpoint, string json, RequestOptions requestOptions = null, - HttpMethod httpMethod = null, CancellationToken cancellationToken = default(CancellationToken)) - { - using var response = await _httpClient.SendAsync( - new HttpRequestMessage(httpMethod, "https://httpstat.us/504?sleep=60000"), cancellationToken); - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - return responseText; - } - - public void Dispose() - { - _httpClient?.Dispose(); - } - } -} \ No newline at end of file diff --git a/Adyen.IntegrationTest/Checkout/PaymentsServiceIntegrationTest.cs b/Adyen.IntegrationTest/Checkout/PaymentsServiceIntegrationTest.cs new file mode 100644 index 000000000..d452d13fb --- /dev/null +++ b/Adyen.IntegrationTest/Checkout/PaymentsServiceIntegrationTest.cs @@ -0,0 +1,273 @@ +using System.Diagnostics.Tracing; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using Adyen.Core.Options; +using Microsoft.Extensions.Logging; + +namespace Adyen.IntegrationTest.Checkout +{ + [TestClass] + public class PaymentsServiceIntegrationTest + { + private readonly IPaymentsService _paymentsApiService; + + public PaymentsServiceIntegrationTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout( + (context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _paymentsApiService = host.Services.GetRequiredService(); + + // Example how to do logging for IPaymentsService and the PaymensServiceEvents. + ILogger logger = host.Services.GetRequiredService>(); + + PaymentsServiceEvents events = host.Services.GetRequiredService(); + + // On /payments + events.OnPayments += (sender, eventArgs) => + { + ApiResponse apiResponse = eventArgs.ApiResponse; + logger.LogInformation("{TotalSeconds,-9} | {Path} | {StatusCode} |", (apiResponse.DownloadedAt - apiResponse.RequestedAt).TotalSeconds, apiResponse.StatusCode, apiResponse.Path); + }; + + // OnError /payments. + events.OnErrorPayments += (sender, eventArgs) => + { + logger.LogError(eventArgs.Exception, "An error occurred after sending the request to the server."); + }; + + } + + [TestMethod] + public async Task Given_Payments_When_CardDetails_Provided_Returns_OK() + { + // Arrange + var request = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "reference", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + IPaymentsApiResponse response = await _paymentsApiService.PaymentsAsync(request); + + response.TryDeserializeOkResponse(out var result); + Assert.AreEqual(result?.MerchantReference, "reference"); + } + + [TestMethod] + public async Task Given_Payments_When_CardDetails_With_Empty_RequestOptions_Succeeds() + { + // Test when no idempotency key is provided + var request = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "ref1-original-request-1", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + IPaymentsApiResponse response = await _paymentsApiService.PaymentsAsync(request, new RequestOptions()); + + response.TryDeserializeOkResponse(out PaymentResponse result); + Assert.AreEqual(result?.MerchantReference, "ref1-original-request-1"); + } + + + [TestMethod] + public async Task Given_Payments_When_CardDetails_Without_Idempotency_Key_Provided_Returns_DifferentRefs() + { + // Test when no idempotency key is provided + var request = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "ref1-original-request-1", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + IPaymentsApiResponse response = await _paymentsApiService.PaymentsAsync(paymentRequest: request); + + response.TryDeserializeOkResponse(out PaymentResponse result); + Assert.AreEqual(result?.MerchantReference, "ref1-original-request-1"); + + + // Test when no idempotency key is provided + var request2 = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "ref2-should-be-different", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + IPaymentsApiResponse response2 = await _paymentsApiService.PaymentsAsync(paymentRequest: request2); + + response2.TryDeserializeOkResponse(out PaymentResponse result2); + Assert.AreEqual(result2?.MerchantReference, "ref2-should-be-different"); + + // Test when null is explicitly provided. + var request3 = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "ref3-should-be-very-different", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + IPaymentsApiResponse response3 = await _paymentsApiService.PaymentsAsync(request3); + response3.TryDeserializeOkResponse(out PaymentResponse result3); + Assert.AreEqual(result3?.MerchantReference, "ref3-should-be-very-different"); + } + + [TestMethod] + public void HttpClientBuilderExtensions_Polly_Retry_CircuitBreaker_Timeout_Example() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout( + (context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }, + httpClientBuilderOptions: (IHttpClientBuilder builder) => + { + builder.AddRetryPolicy(5); + builder.AddCircuitBreakerPolicy(3, TimeSpan.FromSeconds(30)); + builder.AddTimeoutPolicy(TimeSpan.FromMinutes(5)); + }) + .Build(); + } + + [TestMethod] + public void HttpClientBuilderExtensions_Regular_Timeout_Modify_HttpClient_Example() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout( + (context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }, client => + { + client.Timeout = TimeSpan.FromMinutes(1); + }) + .Build(); + } + + [TestMethod] + public async Task PaymentsServiceEvents_Override_Delegates_Example() + { + // Arrange + IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout( + (context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + var request = new PaymentRequest( + amount: new Amount("EUR", 1999), + merchantAccount: "HeapUnderflowECOM", + reference: "reference", + returnUrl: "https://adyen.com/", + paymentMethod: new CheckoutPaymentMethod( + new CardDetails( + type: CardDetails.TypeEnum.Scheme, + encryptedCardNumber: "test_4111111111111111", + encryptedExpiryMonth: "test_03", + encryptedExpiryYear: "test_2030", + encryptedSecurityCode: "test_737", + holderName: "John Smith" + ) + ) + ); + + + PaymentsServiceEvents paymentsServiceEvents = host.Services.GetRequiredService(); + IPaymentsService paymentsApiService = host.Services.GetRequiredService(); + + int isCalledOnce = 0; + + // Example override using a delegate: + paymentsServiceEvents.OnPayments += (sender, args) => + { + Console.WriteLine("OnPayments event received - IsSuccessStateCode: " + args.ApiResponse.IsSuccessStatusCode); + isCalledOnce++; + }; + + // Act + await paymentsApiService.PaymentsAsync(request, new RequestOptions().AddIdempotencyKey(Guid.NewGuid().ToString())); + + // Assert + Assert.IsTrue(isCalledOnce == 1); + } + } +} \ No newline at end of file diff --git a/Adyen.IntegrationTest/CheckoutTest.cs b/Adyen.IntegrationTest/CheckoutTest.cs deleted file mode 100644 index 1ca9a9c6f..000000000 --- a/Adyen.IntegrationTest/CheckoutTest.cs +++ /dev/null @@ -1,313 +0,0 @@ - -using Adyen.Model.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using Adyen.HttpClient; -using Adyen.Service.Checkout; -using CreateCheckoutSessionRequest = Adyen.Model.Checkout.CreateCheckoutSessionRequest; -using Environment = Adyen.Model.Environment; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class CheckoutTest : BaseTest - { - private Client _client; - private PaymentsService _checkout; - private RecurringService _recurring; - private ModificationsService _modifications; - private PaymentLinksService _paymentLinksService; - private PaymentsService _paymentsService; - private static readonly string MerchantAccount = ClientConstants.MerchantAccount; - - [TestInitialize] - public void Init() - { - _client = CreateApiKeyTestClient(); - _checkout = new PaymentsService(_client); - _recurring = new RecurringService(_client); - _modifications = new ModificationsService(_client); - _paymentLinksService = new PaymentLinksService(_client); - // _classicCheckoutSdkService = new ClassicCheckoutSDKService(_client); - _paymentsService = new PaymentsService(_client); - } - - [TestMethod] - public void PaymentsFlowWithInvalidApiKey() - { - _client.Config.XApiKey = "InvalidKey"; - try - { - var paymentResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - } - catch (HttpClientException ex) - { - Assert.AreEqual(401, ex.Code); - } - } - - [TestMethod] - public void PaymentsFlowWithEmptyApiKey() - { - _client.Config.XApiKey = null; - try - { - var paymentResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - } - catch (HttpClientException ex) - { - Assert.AreEqual(401, ex.Code); - } - } - - [TestMethod] - public void PaymentsFlowWithPartiallyCorrectKeyApiKey() - { - var key = _client.Config.XApiKey; - _client.Config.XApiKey = "1" + key; - try - { - var paymentResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - } - catch (HttpClientException ex) - { - Assert.AreEqual(401, ex.Code); - } - } - - [TestMethod] - public void PaymentsTest() - { - var paymentResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - Assert.IsNotNull(paymentResponse.AdditionalData); - Assert.AreEqual("1111", paymentResponse.AdditionalData["cardSummary"]); - Assert.IsNotNull(paymentResponse.AdditionalData["avsResult"]); - Assert.AreEqual("1 Matches", paymentResponse.AdditionalData["cvcResult"]); - Assert.AreEqual("visa", paymentResponse.AdditionalData["paymentMethod"]); - } - - [TestMethod] - public void PaymentMethodsTest() - { - var amount = new Amount("EUR", 1000); - var paymentMethodsRequest = new PaymentMethodsRequest(merchantAccount: MerchantAccount) - { - CountryCode = "NL", - Amount = amount, - Channel = PaymentMethodsRequest.ChannelEnum.Web - }; - var paymentMethodsResponse = _checkout.PaymentMethods(paymentMethodsRequest); - Assert.IsTrue(paymentMethodsResponse.PaymentMethods.Count != 0); - Assert.IsTrue(!string.IsNullOrEmpty(paymentMethodsResponse.PaymentMethods[0].Name)); - } - - [TestMethod] - public void PaymentWithIdealTest() - { - var paymentResponse = _checkout.Payments(CreatePaymentRequestIDealCheckout()); - var paymentResponseResult = paymentResponse.Action.GetCheckoutRedirectAction(); - Assert.AreEqual(paymentResponse.ResultCode, PaymentResponse.ResultCodeEnum.RedirectShopper); - Assert.AreEqual(paymentResponseResult.PaymentMethodType, "ideal"); - Assert.IsNotNull(paymentResponseResult.Url); - Assert.AreEqual(paymentResponse.ResultCode, PaymentResponse.ResultCodeEnum.RedirectShopper); - } - - [TestMethod] - public void PaymentLinksSuccessTest() - { - var amount = new Amount("EUR", 1000); - var address = new Address(country: "NL", city: "Amsterdam", houseNumberOrName: "11", postalCode: "1234AB", street: "ams"); - var createPaymentLinkRequest = new PaymentLinkRequest(amount: amount, merchantAccount: ClientConstants.MerchantAccount, reference: "Reference") - { - CountryCode = "NL", - ShopperReference = "Unique_shopper_reference", - ShopperEmail = "test@shopperEmail.com", - BillingAddress = address, - DeliveryAddress = address, - ExpiresAt = DateTime.Now.AddHours(4) - }; - var createPaymentLinkResponse = _paymentLinksService.PaymentLinks(createPaymentLinkRequest); - PaymentLinksGetSuccessTest(createPaymentLinkResponse.Id); - PaymentLinksPatchSuccessTest(createPaymentLinkResponse.Id); - Assert.IsNotNull(createPaymentLinkResponse); - Assert.IsNotNull(createPaymentLinkResponse.Url); - Assert.IsNotNull(createPaymentLinkResponse.Amount); - Assert.IsNotNull(createPaymentLinkResponse.Reference); - Assert.IsNotNull(createPaymentLinkResponse.ExpiresAt); - } - - private void PaymentLinksGetSuccessTest(string Id) - { - - var createPaymentLinkResponse = _paymentLinksService.GetPaymentLink(Id); - Assert.IsNotNull(createPaymentLinkResponse); - Assert.IsNotNull(createPaymentLinkResponse.Url); - Assert.IsNotNull(createPaymentLinkResponse.Amount); - Assert.IsNotNull(createPaymentLinkResponse.Reference); - Assert.IsNotNull(createPaymentLinkResponse.ExpiresAt); - } - - private void PaymentLinksPatchSuccessTest(string Id) - { - var updatePaymentLinksRequest = new UpdatePaymentLinkRequest(status: UpdatePaymentLinkRequest.StatusEnum.Expired); - - var createPaymentLinkResponse = _paymentLinksService.UpdatePaymentLink(Id, updatePaymentLinksRequest); - Assert.IsNotNull(createPaymentLinkResponse); - Assert.IsNotNull(createPaymentLinkResponse.Url); - Assert.IsNotNull(createPaymentLinkResponse.Amount); - Assert.IsNotNull(createPaymentLinkResponse.Reference); - Assert.IsNotNull(createPaymentLinkResponse.ExpiresAt); - } - - - /// - /// Test success sessions - /// POST /sessions - /// - [TestMethod] - public void CheckoutSessionSuccessTest() - { - var checkoutSessionRequest = new CreateCheckoutSessionRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - Reference = "TestReference", - ReturnUrl = "http://test-url.com", - Amount = new Amount("EUR", 10000L) - }; - var createCheckoutSessionResponse = _checkout.Sessions(checkoutSessionRequest); - Assert.AreEqual(MerchantAccount, createCheckoutSessionResponse.MerchantAccount); - Assert.AreEqual("TestReference", createCheckoutSessionResponse.Reference); - Assert.AreEqual("http://test-url.com", createCheckoutSessionResponse.ReturnUrl); - Assert.AreEqual("EUR", createCheckoutSessionResponse.Amount.Currency); - Assert.AreEqual("10000", createCheckoutSessionResponse.Amount.Value.ToString()); - Assert.IsNotNull(createCheckoutSessionResponse.SessionData); - } - - /// - /// Test success sessions - /// POST /sessions - /// - [TestMethod] - public void CheckoutSessionSuccessWithClientTest() - { - var config = new Config - { - Environment = Environment.Test, - XApiKey = ClientConstants.Xapikey - }; - - var checkoutSessionRequest = new CreateCheckoutSessionRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - Reference = "TestReference", - ReturnUrl = "http://test-url.com", - Amount = new Amount("EUR", 10000L) - }; - var createCheckoutSessionResponse = _paymentsService.Sessions(checkoutSessionRequest); - Assert.AreEqual(MerchantAccount, createCheckoutSessionResponse.MerchantAccount); - Assert.AreEqual("TestReference", createCheckoutSessionResponse.Reference); - Assert.AreEqual("http://test-url.com", createCheckoutSessionResponse.ReturnUrl); - Assert.AreEqual("EUR", createCheckoutSessionResponse.Amount.Currency); - Assert.AreEqual("10000", createCheckoutSessionResponse.Amount.Value.ToString()); - Assert.IsNotNull(createCheckoutSessionResponse.SessionData); - } - - /// - /// Test success capture - /// POST /payments/{paymentPspReference}/captures - /// - [TestMethod] - public void ModificationsCapturesTest() - { - var paymentsResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - var createPaymentCaptureRequest = new Model.Checkout.PaymentCaptureRequest( - amount: new Model.Checkout.Amount(currency: "EUR", value: 500L), reference: "my_capture_reference", - merchantAccount: MerchantAccount); - var paymentCaptureResource = - _modifications.CaptureAuthorisedPayment(paymentsResponse.PspReference, createPaymentCaptureRequest); - Assert.AreEqual(paymentsResponse.PspReference, paymentCaptureResource.PaymentPspReference); - Assert.AreEqual(paymentCaptureResource.Reference, "my_capture_reference"); - } - - /// - /// Test success payments cancels - /// POST /payments/{paymentPspReference}/cancels - /// - [TestMethod] - public void ModificationsCancelsTest() - { - var paymentsResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - var createPaymentCancelRequest = new Model.Checkout.PaymentCancelRequest(reference: "my_cancel_reference", - merchantAccount: MerchantAccount); - var paymentCancelResource = - _modifications.CancelAuthorisedPaymentByPspReference(paymentsResponse.PspReference, createPaymentCancelRequest); - Assert.AreEqual(paymentsResponse.PspReference, paymentCancelResource.PaymentPspReference); - Assert.AreEqual(paymentCancelResource.Reference, "my_cancel_reference"); - } - - /// - /// Test success payments reversals - /// POST /payments/{paymentPspReference}/reversals - /// - [TestMethod] - public void ModificationReversalsTest() - { - var paymentsResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - var createPaymentReversalRequest = new Model.Checkout.PaymentReversalRequest(reference: "my_reversal_reference", - merchantAccount: MerchantAccount); - var paymentReversalResource = - _modifications.RefundOrCancelPayment(paymentsResponse.PspReference, createPaymentReversalRequest); - Assert.AreEqual(paymentsResponse.PspReference, paymentReversalResource.PaymentPspReference); - Assert.AreEqual(paymentReversalResource.Reference, "my_reversal_reference"); - } - - /// - /// Test success payments reversals - /// POST /payments/{paymentPspReference}/reversals - /// - [TestMethod] - public void ModificationsRefundsTest() - { - var paymentsResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - var createPaymentRefundRequest = new Model.Checkout.PaymentRefundRequest( - amount: new Model.Checkout.Amount(currency: "EUR", value: 500L), reference: "my_refund_reference", - merchantAccount: MerchantAccount); - var paymentRefundResource = - _modifications.RefundCapturedPayment(paymentsResponse.PspReference, createPaymentRefundRequest); - Assert.AreEqual(paymentsResponse.PspReference, paymentRefundResource.PaymentPspReference); - Assert.AreEqual(paymentRefundResource.Reference, "my_refund_reference"); - } - - /// - /// Test success payments cancels - /// POST /payments/{paymentPspReference}/amountUpdates - /// - [TestMethod] - public void ModificationsAmountUpdatesTest() - { - var paymentsResponse = _checkout.Payments(CreatePaymentRequestCheckout()); - var createPaymentAmountUpdateRequest = new Model.Checkout.PaymentAmountUpdateRequest( - amount: new Model.Checkout.Amount(currency: "EUR", value: 500L), reference: "my_updates_reference", - merchantAccount: MerchantAccount); - var paymentAmountUpdateResource = - _modifications.UpdateAuthorisedAmount(paymentsResponse.PspReference, createPaymentAmountUpdateRequest); - Assert.AreEqual(paymentsResponse.PspReference, paymentAmountUpdateResource.PaymentPspReference); - Assert.AreEqual(paymentAmountUpdateResource.Reference, "my_updates_reference"); - } - - /// - /// Test success orders cancel - /// GET /storedPaymentMethods - /// - [TestMethod] - public void GetStoredPaymentMethodsTest() - { - // First execute RecurringTest - var test = new RecurringTest(); - test.TestListRecurringDetails(); - var listStoredPaymentMethodsResponse = _recurring.GetTokensForStoredPaymentDetails("test-1234", ClientConstants.MerchantAccount); - Assert.AreEqual("scheme", listStoredPaymentMethodsResponse.StoredPaymentMethods[0].Type); - Assert.AreEqual(ClientConstants.MerchantAccount, listStoredPaymentMethodsResponse.MerchantAccount); - } - } -} diff --git a/Adyen.IntegrationTest/ClientConstants.cs b/Adyen.IntegrationTest/ClientConstants.cs deleted file mode 100644 index 18ef54efc..000000000 --- a/Adyen.IntegrationTest/ClientConstants.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Adyen.IntegrationTest -{ - public class ClientConstants - { - public static readonly string MerchantAccount = Environment.GetEnvironmentVariable("INTEGRATION_MERCHANT_ACCOUNT"); - public static readonly string Xapikey = Environment.GetEnvironmentVariable("INTEGRATION_X_API_KEY"); - - public static readonly string CaUsername = Environment.GetEnvironmentVariable("INTEGRATION_CA_USERNAME"); - public static readonly string CaPassword = Environment.GetEnvironmentVariable("INTEGRATION_CA_PASSWORD"); - } -} \ No newline at end of file diff --git a/Adyen.IntegrationTest/ErrorTest.cs b/Adyen.IntegrationTest/ErrorTest.cs deleted file mode 100644 index f803087cf..000000000 --- a/Adyen.IntegrationTest/ErrorTest.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Net.Http; -using Adyen.HttpClient; -using Adyen.Model.Checkout; -using Adyen.Service; -using Adyen.Service.Checkout; - -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Amount = Adyen.Model.Payment.Amount; -using Card = Adyen.Model.Payment.Card; -using Environment = Adyen.Model.Environment; -using PaymentRequest = Adyen.Model.Payment.PaymentRequest; -using Recurring = Adyen.Model.Payment.Recurring; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class ErrorTest : BaseTest - { - private Client _client; - private static readonly string MerchantAccount = ClientConstants.MerchantAccount; - private HttpClientWrapper _httpClientWrapper; - - [TestInitialize] - public void Init() - { - _client = CreateApiKeyTestClient(); - _httpClientWrapper = - new HttpClientWrapper(new Config() { Environment = Environment.Test, XApiKey = ClientConstants.Xapikey }, - new System.Net.Http.HttpClient()); - } - - [TestMethod] - public void TestClassicPaymentErrorHandling() - { - var payments = new PaymentService(_client); - var request = new PaymentRequest { - Amount = new Amount(){ - Value = 1500, - Currency = "EUR" - }, - Card = new Card(){ - Number = "4111111111111111", - ExpiryMonth = "03", - ExpiryYear = "2030", - Cvc = "737", - HolderName = "John Smith" - }, - ShopperEmail = "s.hopper@test.com", - ShopperIP = "61.294.12.12", - ShopperReference = "test-1234", - Recurring = new Recurring() - { - Contract = Recurring.ContractEnum.RECURRING - }, - ShopperInteraction = PaymentRequest.ShopperInteractionEnum.Ecommerce, - MerchantAccount = MerchantAccount - }; - try - { - payments.Authorise(request); - } - catch(HttpClientException ex) - { - Assert.AreEqual(ex.ResponseBody, "{\"status\":422,\"errorCode\":\"130\",\"message\":\"Required field 'reference' is not provided.\",\"errorType\":\"validation\"}"); - } - } - - [TestMethod] - public void TestCheckoutErrorHandling() - { - var payments = new PaymentsService(_client); - var request = new Model.Checkout.PaymentRequest { - Amount = new Model.Checkout.Amount(){ - Value = 1500, - Currency = "EUR" - }, - CountryCode = "NL", - PaymentMethod = new CheckoutPaymentMethod( new ApplePayDetails(type: ApplePayDetails.TypeEnum.Applepay)), - Reference = "123456789", - ShopperReference = "Test-Payment1234", - ReturnUrl = "https://your-company.com/...", - MerchantAccount = MerchantAccount - }; - try - { - payments.Payments(request); - } - catch(HttpClientException ex) - { - Assert.IsTrue(ex.ResponseBody.Contains("{\"status\":422,\"errorCode\":\"14_004\",\"message\":\"Missing payment method details\",\"errorType\":\"validation\"")); - } - } - - [TestMethod] - public void TestManagementInvalidParametersHandling() - { - var request = @"{""merchantId"": """+ MerchantAccount + @""", - ""description"": ""City centre store"", - ""shopperStatement"": ""Springfield Shop"", - ""phoneNumber"": ""+1813702551707653"", - ""reference"": ""Spring_store_2"", - ""address"": { - ""country"": ""US"", - ""line1"": ""200 Main Street"", - ""line2"": ""Building 5A"", - ""line3"": ""Suite 3"", - ""city"": ""Springfield"", - ""stateOrProvince"": ""NY"", - ""postalCode"": ""20250"" - }}"; - try - { - _httpClientWrapper.RequestAsync("https://management-test.adyen.com/v1/stores", request, null, HttpMethod.Post).GetAwaiter().GetResult(); - } - catch (HttpClientException ex) - { - Assert.IsTrue(ex.ResponseBody.Contains(@"""title"":""Invalid parameters"",""status"":422,")); - } - } - - [TestMethod] - public void TestManagementBadRequestHandling() - { - try - { - _httpClientWrapper.RequestAsync("https://management-test.adyen.com/v1/stores", "{}", null, HttpMethod.Post).GetAwaiter().GetResult(); - } - catch (HttpClientException ex) - { - Assert.IsTrue(ex.ResponseBody.Contains(@"""title"":""Bad request"",""status"":400,""detail""")); - } - } - } -} - diff --git a/Adyen.IntegrationTest/MarketPayFundTest.cs b/Adyen.IntegrationTest/MarketPayFundTest.cs deleted file mode 100644 index d4c29bcc5..000000000 --- a/Adyen.IntegrationTest/MarketPayFundTest.cs +++ /dev/null @@ -1,112 +0,0 @@ -using Adyen.Model.MarketPay; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class MarketPayFundTest : BaseTest - { - private Client _client; - private Fund _fund; - - [TestInitialize] - public void Init() - { - _client = new Client(ClientConstants.CaUsername, ClientConstants.CaPassword, Model.Enum.Environment.Test); - _fund = new Fund(_client); - } - - /// - /// test /accountHoldertransactionList - /// - [TestMethod] - public void AccountHoldertransactionListResponseSuccess() - { - var accountHolderTransactionListRequest = new AccountHolderTransactionListRequest(accountHolderCode: "LiableAccountHolderPluginDemoMirakl"); - var accountHolderTransactionListResponse = _fund.AccountHolderTransactionList(accountHolderTransactionListRequest); - Assert.IsNotNull(accountHolderTransactionListResponse.PspReference); - Assert.AreEqual("Success", accountHolderTransactionListResponse.ResultCode); - Assert.AreEqual(3, accountHolderTransactionListResponse.AccountTransactionLists.Count); - } - /// - /// test /accountHolderBalance - /// - [TestMethod] - public void AccountHolderBalanceResponse() - { - var accountHolderBalanceRequest = new AccountHolderBalanceRequest(accountHolderCode: "LiableAccountHolderPluginDemoMirakl"); - var accountHolderBalanceResponse = _fund.AccountHolderBalance(accountHolderBalanceRequest); - Assert.IsNotNull(accountHolderBalanceResponse.PspReference); - Assert.AreEqual("112548519", accountHolderBalanceResponse.BalancePerAccount[0].AccountCode); - Assert.AreEqual("128653506", accountHolderBalanceResponse.BalancePerAccount[1].AccountCode); - Assert.AreEqual("162991090", accountHolderBalanceResponse.BalancePerAccount[2].AccountCode); - } - - /// - /// test /refundNotPaidOutTransfers - /// - [TestMethod] - public void TestRefundNotPaidOutTransfersSuccess() - { - var refundNotPaidOutTransfersRequest = new RefundNotPaidOutTransfersRequest(accountCode: "112548519", accountHolderCode: "LiableAccountHolderPluginDemoMirakl"); - var refundNotPaidOutTransfersResponse = _fund.RefundNotPaidOutTransfers(refundNotPaidOutTransfersRequest); - Assert.IsNotNull(refundNotPaidOutTransfersResponse.PspReference); - Assert.AreEqual("Received", refundNotPaidOutTransfersResponse.ResultCode); - } - - /// - /// test /transferFunds - /// Account holder 138423083 has beneficiary setup. Fund transfer is not allowed. it can - /// - public void TestTransferFundsSuccess() - { - var amount = new Amount("EUR", 1000); - var transferFundsRequest = new TransferFundsRequest(amount: amount, destinationAccountCode: "112548519", merchantReference: "merchantReference", sourceAccountCode: "138423083", transferCode: "SUBSCRIPTION"); - var transferFundsResponse = _fund.TransferFunds(transferFundsRequest); - Assert.IsNotNull( transferFundsResponse.PspReference); - Assert.AreEqual("merchantReference", transferFundsResponse.MerchantReference); - Assert.AreEqual("Received", transferFundsResponse.ResultCode); - } - - /// - /// test /setup beneficiary - /// it can be done only once - /// - public void TestSetupBeneficiary() - { - var setupBeneficiaryRequest = new SetupBeneficiaryRequest(destinationAccountCode: "128653506", merchantReference: "LiableAccountHolderPluginDemoMirakl", sourceAccountCode: "138423083"); - var setupBeneficiaryResponse = _fund.SetupBeneficiary(setupBeneficiaryRequest); - Assert.IsNotNull(setupBeneficiaryResponse.PspReference); - Assert.AreEqual("Received", setupBeneficiaryResponse.ResultCode); - } - - /// - /// test /payoutAccountHolder - /// - [TestMethod] - public void TestPayoutAccountHolderSuccess() - { - var amount = new Amount("EUR", 5700); - var payoutAccountHolderRequest = new PayoutAccountHolderRequest( - accountCode: "128653506", accountHolderCode: "LiableAccountHolderPluginDemoMirakl", amount: amount); - var payoutAccountHolderResponse = _fund.PayoutAccountHolder(payoutAccountHolderRequest); - Assert.IsNotNull(payoutAccountHolderResponse.PspReference); - Assert.AreEqual("Received", payoutAccountHolderResponse.ResultCode); - } - - /// - /// test /refundFundsTransfer - /// - [TestMethod] - public void TestRefundFundsTransferSuccess() - { - var amount = new Amount("EUR", 5700); - var refundFundsTransferRequest = new RefundFundsTransferRequest( - originalReference:"reference", amount: amount); - var payoutAccountHolderResponse = _fund.RefundFundsTransfer(refundFundsTransferRequest); - Assert.IsNotNull(payoutAccountHolderResponse.PspReference); - Assert.AreEqual("Received", payoutAccountHolderResponse.ResultCode); - } - } -} diff --git a/Adyen.IntegrationTest/MarketpayAccountTest.cs b/Adyen.IntegrationTest/MarketpayAccountTest.cs deleted file mode 100644 index 9fdf82168..000000000 --- a/Adyen.IntegrationTest/MarketpayAccountTest.cs +++ /dev/null @@ -1,278 +0,0 @@ -using Adyen.Model.MarketPay; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using Account = Adyen.Service.Account; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class MarketpayAccountTest - { - private Client _client; - private Account _account; - - [TestInitialize] - public void Init() - { - _client = new Client(ClientConstants.CaUsername, ClientConstants.CaPassword, Model.Enum.Environment.Test); - _account = new Account(_client); - } - - /// - /// Test /createAccount API call/ - /// Test /closeAccount API call/ - /// - [TestMethod] - public void TestCreateCloseAccountSuccess() - { - var createAccountRequest = new CreateAccountRequest(accountHolderCode: GenerateUniqueAccountHolder()); - var createAccountResponse = _account.CreateAccount(createAccountRequest); - Assert.IsNotNull(createAccountResponse.PspReference); - Assert.IsNotNull(createAccountResponse.AccountCode); - Assert.IsNotNull(createAccountResponse.AccountHolderCode); - - var closeAccountRequest = new CloseAccountRequest(accountCode: createAccountResponse.AccountCode); - var closeAccountResponse = _account.CloseAccount(closeAccountRequest); - Assert.IsNotNull(closeAccountResponse); - Assert.IsNotNull(closeAccountResponse.PspReference); - } - - /// - /// Test /createAccount API call/ - /// Test /closeAccount API call/ - /// - [TestMethod] - public void TestCreateAccountHolderSuccess() - { - var accountHolderResponse = GetCreateAccountHolderResponse(); - Assert.IsNotNull(accountHolderResponse.PspReference); - Assert.IsNotNull(accountHolderResponse.AccountCode); - Assert.IsNotNull(accountHolderResponse.AccountHolderCode); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: accountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - Assert.IsNotNull(closeAccountResponse); - Assert.IsNotNull(closeAccountResponse.PspReference); - } - - /// - /// Test /createAccount API call/ - /// Test /closeAccount API call/ - /// - [TestMethod] - public void TestCreateAccountHolderDeleteBankAccountSuccess() - { - var accountHolderResponse = GetCreateAccountHolderResponse(); - Assert.IsNotNull(accountHolderResponse.PspReference); - Assert.IsNotNull(accountHolderResponse.AccountCode); - Assert.IsNotNull(accountHolderResponse.AccountHolderCode); - - var bankAccountUID = accountHolderResponse.AccountHolderDetails.BankAccountDetails[0].BankAccountUUID; - var bankAccountUIDs = new List {{bankAccountUID}}; - var deletePayoutMethodRequest = new DeleteBankAccountRequest( - accountHolderCode: accountHolderResponse.AccountHolderCode, bankAccountUUIDs: bankAccountUIDs); - var genericResponse = _account.DeleteBankAccount(deletePayoutMethodRequest); - Assert.IsNotNull(genericResponse.PspReference); - - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: accountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - Assert.IsNotNull(closeAccountResponse); - Assert.IsNotNull(closeAccountResponse.PspReference); - } - - /// - /// Test /getAccountHolder API call/ - /// - [TestMethod] - public void TestGetAccountHolders() - { - var getAccountHolderRequest = new GetAccountHolderRequest(accountHolderCode: "TestAccountHolder01"); - var getAccountHolderResponse = _account.GetAccountHolder(getAccountHolderRequest); - Assert.IsNotNull(getAccountHolderResponse.PspReference); - Assert.IsNotNull(getAccountHolderResponse.AccountHolderCode); - Assert.IsNotNull(getAccountHolderResponse.AccountHolderDetails.Email); - } - - /// - /// Test /getUploadedDocuments API call/ - /// - [TestMethod] - public void TestGetUploadDocumentsSuccess() - { - var getUploadDocumentsRequest = new GetUploadedDocumentsRequest(accountHolderCode: "TestAccountHolder01"); - var getUploadDocumentsResponse = _account.GetUploadedDocuments(getUploadDocumentsRequest); - Assert.IsNotNull(getUploadDocumentsResponse.PspReference); - } - - /// - /// Test /updateAccountHolder API call - /// - [TestMethod] - public void TestUpdateAccountHolderSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - Thread.Sleep(3000); - var accountHolderDetails = createAccountHolderResponse.AccountHolderDetails; - var updateAccountHolderRequest = new UpdateAccountHolderRequest( - accountHolderCode: createAccountHolderResponse.AccountHolderCode, - accountHolderDetails: accountHolderDetails); - updateAccountHolderRequest.LegalEntity = UpdateAccountHolderRequest.LegalEntityEnum.Business; - var updateAccountHolderResponse = _account.UpdateAccountHolder(updateAccountHolderRequest); - Assert.IsNotNull(updateAccountHolderResponse.PspReference); - Thread.Sleep(3000); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - } - - - /// - /// Test /updateAccountHolderState API call - /// - [TestMethod] - public void TestUpdateAccountHolderStateSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - Thread.Sleep(3000); - var updateAccountHolderStateRequest = new UpdateAccountHolderStateRequest( - accountHolderCode: createAccountHolderResponse.AccountHolderCode, reason: "test reason payout", - stateType: UpdateAccountHolderStateRequest.StateTypeEnum.Payout, disable: false); - var updateAccountHolderStateResponse = _account.UpdateAccountHolderState(updateAccountHolderStateRequest); - Assert.IsNotNull(updateAccountHolderStateResponse.PspReference); - Assert.IsNotNull(updateAccountHolderStateResponse.AccountHolderCode); - Thread.Sleep(3000); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - } - - /// - /// Test /deletePayoutMethods API call - /// - [TestMethod] - public void TestDeletePayoutMethodsSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - Thread.Sleep(3000); - var deletePayoutMethodRequest = new DeletePayoutMethodRequest( - accountHolderCode: createAccountHolderResponse.AccountHolderCode, - payoutMethodCodes: new List() {"6026a526-7863-f943-d8ca-f8fadc47473e"}); - var genericResponse = _account.DeletePayoutMethods(deletePayoutMethodRequest); - Assert.IsNotNull(genericResponse.PspReference); - Thread.Sleep(3000); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - } - - /// - /// Test /deletePayoutMethods API call - /// - [TestMethod] - public void TestDeleteShareHolderListsSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - var shareHolderCode = createAccountHolderResponse.Verification.Shareholders[0].ShareholderCode; - var deleteShareholderRequest = new DeleteShareholderRequest( - accountHolderCode: createAccountHolderResponse.AccountHolderCode, - shareholderCodes: new List {{shareHolderCode}}); - var genericResponse = _account.DeleteShareHolder(deleteShareholderRequest); - Assert.IsNotNull(genericResponse.PspReference); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - } - - /// - /// Test /checkoutAccountHolder API call - /// - [TestMethod] - public void TestCheckAccountHolderSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - Thread.Sleep(5000); - Assert.IsNotNull(createAccountHolderResponse.PspReference); - Assert.IsNotNull(createAccountHolderResponse.AccountCode); - Assert.IsNotNull(createAccountHolderResponse.AccountHolderCode); - var performVerificationRequest = new PerformVerificationRequest( - accountHolderCode: createAccountHolderResponse.AccountHolderCode, - accountStateType: PerformVerificationRequest.AccountStateTypeEnum.Processing, tier: 1); - var genericResponse = _account.CheckAccountholder(performVerificationRequest); - Assert.IsNotNull(genericResponse.PspReference); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - Assert.IsNotNull(closeAccountResponse); - Assert.IsNotNull(closeAccountResponse.PspReference); - } - - /// - /// Test /suspendAccountHolder API call/ - /// - [TestMethod] - public void TestSuspendAccountHolderSuccess() - { - var createAccountHolderResponse = GetCreateAccountHolderResponse(); - Thread.Sleep(5000); - var suspendAccountHolderRequest = - new SuspendAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var suspendAccountHolderResponse = _account.SuspendAccountHolder(suspendAccountHolderRequest); - Assert.IsNotNull(suspendAccountHolderResponse.PspReference); - Thread.Sleep(3000); - var closeAccountRequest = - new CloseAccountHolderRequest(accountHolderCode: createAccountHolderResponse.AccountHolderCode); - var closeAccountResponse = _account.CloseAccountHolder(closeAccountRequest); - } - - private CreateAccountHolderResponse GetCreateAccountHolderResponse() - { - var accountHolderCode = GenerateUniqueAccountHolder(); - var viasAddress = new ViasAddress(country: "NL"); - var bankAccountsDetails = new List - { - { - new BankAccountDetail(bankName: "testBank", iban: "NL64INGB0004053953", countryCode: "NL", - currencyCode: "EUR", ownerCountryCode: "NL", ownerCity: "Amsterdam", - ownerDateOfBirth: "1990-1-1", - ownerHouseNumberOrName: "9", ownerName: "John Smoith", ownerNationality: "NL", - ownerPostalCode: "1010js", ownerStreet: "Delfandplein", primaryAccount: true) - } - }; - var name = new ViasName(firstName: "John", lastName: "Smith", gender: ViasName.GenderEnum.MALE); - var phone = "+31061111111112"; - var personalData = new ViasPersonalData(nationality: "NL", dateOfBirth: "1980-01-01"); - var shareholderContract = new List - { - { - new ShareholderContact(address: viasAddress, email: "test@test.com", name: name, - fullPhoneNumber: phone, - personalData: personalData) - }, - { - new ShareholderContact(address: viasAddress, email: "test1@test1.com", name: name, - fullPhoneNumber: phone, personalData: personalData) - } - }; - var businessDetails = new BusinessDetails(doingBusinessAs: "TestBusiness05", - legalBusinessName: "TestBusiness05", shareholders: shareholderContract, taxId: "NL853416084"); - var accountHolderDetails = new AccountHolderDetails(address: viasAddress, - bankAccountDetails: bankAccountsDetails, businessDetails: businessDetails, email: "test@test.com", - webAddress: "http://test.com"); - var createAccountRequest = new CreateAccountHolderRequest(accountHolderCode: accountHolderCode, - accountHolderDetails: accountHolderDetails); - createAccountRequest.CreateDefaultAccount = true; - - createAccountRequest.LegalEntity = CreateAccountHolderRequest.LegalEntityEnum.Business; - return _account.CreateAccountHolder(createAccountRequest); - } - - private string GenerateUniqueAccountHolder() - { - return string.Format("TestAccountHolder" + Guid.NewGuid().ToString().Substring(0, 6)); - } - } -} \ No newline at end of file diff --git a/Adyen.IntegrationTest/Modificationtest.cs b/Adyen.IntegrationTest/Modificationtest.cs deleted file mode 100644 index 23fec99f7..000000000 --- a/Adyen.IntegrationTest/Modificationtest.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Net.Http; -using Adyen.HttpClient; -using Adyen.Model.Payment; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class ModificationTest : BaseTest - { - [TestMethod] - public void TestCaptureSuccess() - { - var paymentResultPspReference = GetTestPspReference(); - //Call authorization test - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - //Send capture call with psp refernce - var captureRequest = base.CreateCaptureTestRequest(paymentResultPspReference); - var captureResult = modification.Capture(captureRequest); - Assert.AreEqual(captureResult.Response, ModificationResult.ResponseEnum.CaptureReceived); - } - - [TestMethod] - public void TestCancelOrRefundReceived() - { - var paymentResultPspReference = GetTestPspReference(); - //Call authorization test - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var cancelOrRefundRequest = base.CreateCancelOrRefundTestRequest(pspReference: paymentResultPspReference); - var cancelOrRefundResult = modification.CancelOrRefund(cancelOrRefundRequest); - Assert.AreEqual(cancelOrRefundResult.Response, ModificationResult.ResponseEnum.CancelOrRefundReceived); - } - - [TestMethod] - public void TestRefundReceived() - { - var paymentResultPspReference = GetTestPspReference(); - //Call authorization test - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var refundRequest = base.CreateRefundTestRequest(pspReference: paymentResultPspReference); - var refundResult = modification.Refund(refundRequest); - Assert.AreEqual(refundResult.Response, ModificationResult.ResponseEnum.RefundReceived); - } - - [TestMethod] - public void TestCancelReceived() - { - var paymentResultPspReference = GetTestPspReference(); - //Call authorization test - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var cancelRequest = base.CreateCancelTestRequest(pspReference: paymentResultPspReference); - var refundResult = modification.Cancel(cancelRequest); - Assert.AreEqual(refundResult.Response, ModificationResult.ResponseEnum.CancelReceived); - } - - [TestMethod] - public void TestAdjustAuthorisationReceived() - { - var paymentResultPspReference = GetTestPspReference(); - //Call authorization test - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var adjustAuthorisationtestRequest = base.CreateAdjustAuthorisationtestRequest(pspReference: paymentResultPspReference); - var adjustAuthorisationtestResult = modification.AdjustAuthorisation(adjustAuthorisationtestRequest); - Assert.AreEqual(adjustAuthorisationtestResult.Response, ModificationResult.ResponseEnum.AdjustAuthorisationReceived); - } - - [TestMethod] - public void TestTechnicalCancelReceived() - { - var pspRef = GetTestPspReference(); - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var technicalCancelRequest = new TechnicalCancelRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - OriginalMerchantReference = pspRef, - Reference = "reference123" - }; - var techCancelResponse = modification.TechnicalCancel(technicalCancelRequest); - Assert.AreEqual(techCancelResponse.Response, ModificationResult.ResponseEnum.TechnicalCancelReceived); - } - - [TestMethod] - public void TestDonationReceived() - { - var pspRef = GetTestPspReference(); - var client = base.CreateApiKeyTestClient(); - var modification = new PaymentService(client); - var donationRequest = new DonationRequest() - { - MerchantAccount = ClientConstants.MerchantAccount, - OriginalReference = pspRef, - Reference = "reference123", - ModificationAmount = new Amount("EUR",1), - DonationAccount = "MyCharity_Giving_TEST" - - }; - try - { - modification.DonateAsync(donationRequest).GetAwaiter().GetResult(); - } - catch (HttpClientException e) - { - Assert.AreEqual(403, e.Code); - } - } - } -} diff --git a/Adyen.IntegrationTest/PaymentTest.cs b/Adyen.IntegrationTest/PaymentTest.cs deleted file mode 100644 index e4c0dcbb9..000000000 --- a/Adyen.IntegrationTest/PaymentTest.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System; -using Adyen.Model.Payment; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Collections.Generic; -using System.Threading.Tasks; -using Adyen.HttpClient; -using Adyen.Model.StoredValue; -using Environment = Adyen.Model.Environment; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class PaymentTest : BaseTest - { - [TestMethod] - public void BasicAuthenticationAuthoriseSuccessTest() - { - var paymentResult = CreatePaymentResult(); - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.AreEqual("1111", GetAdditionalData(paymentResult.AdditionalData, "cardSummary")); - Assert.IsNotNull(GetAdditionalData(paymentResult.AdditionalData, "avsResult")); - Assert.AreEqual("1 Matches", GetAdditionalData(paymentResult.AdditionalData, "cvcResult")); - Assert.AreEqual("H167852639363479", GetAdditionalData(paymentResult.AdditionalData, "alias")); - Assert.AreEqual("visa", GetAdditionalData(paymentResult.AdditionalData, "paymentMethodVariant")); - Assert.AreEqual("Default", GetAdditionalData(paymentResult.AdditionalData, "aliasType")); - } - - [TestMethod] - public async Task BasicAuthenticationAuthoriseAsyncSuccessTest() - { - var paymentResult = await CreatePaymentResultAsync(); - - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.AreEqual("1111", GetAdditionalData(paymentResult.AdditionalData, "cardSummary")); - Assert.IsNotNull(GetAdditionalData(paymentResult.AdditionalData, "avsResult")); - Assert.AreEqual("1 Matches", GetAdditionalData(paymentResult.AdditionalData, "cvcResult")); - Assert.AreEqual("H167852639363479", GetAdditionalData(paymentResult.AdditionalData, "alias")); - Assert.AreEqual("visa", GetAdditionalData(paymentResult.AdditionalData, "paymentMethodVariant")); - Assert.AreEqual("Default", GetAdditionalData(paymentResult.AdditionalData, "aliasType")); - } - - [TestMethod] - public void ApiKeyAuthoriseSuccessTest() - { - var paymentResult = CreatePaymentResultWithApiKeyAuthentication(); - - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.AreEqual("1111", GetAdditionalData(paymentResult.AdditionalData, "cardSummary")); - Assert.IsNotNull(GetAdditionalData(paymentResult.AdditionalData, "avsResult")); - Assert.AreEqual("1 Matches", GetAdditionalData(paymentResult.AdditionalData, "cvcResult")); - Assert.AreEqual("H167852639363479", GetAdditionalData(paymentResult.AdditionalData, "alias")); - Assert.AreEqual("visa", GetAdditionalData(paymentResult.AdditionalData, "paymentMethodVariant")); - Assert.AreEqual("Default", GetAdditionalData(paymentResult.AdditionalData, "aliasType")); - } - - [TestMethod] - public void ApiIdemptotencyKeySuccessTest() - { - var paymentResult1 = CreatePaymentResultWithIdempotency("AUTH_IDEMPOTENCY_KEY_AUTHOR"); - var paymentResult2 = CreatePaymentResultWithIdempotency("AUTH_IDEMPOTENCY_KEY_AUTHOR"); - Assert.AreEqual(paymentResult1.PspReference, paymentResult2.PspReference); - } - - [TestMethod] - public void StoredValueIssueFailIntegrationTest() - { - var client = new Client(new Config() - { - Environment = Environment.Test, - XApiKey = ClientConstants.Xapikey - }); - var service = new StoredValueService(client); - var ex = Assert.ThrowsException(() => service.Issue(new StoredValueIssueRequest())); - Assert.AreEqual(ex.Code, 422); - } - - [TestMethod] - public void ApiIdemptotencyKeyFailTest() - { - try - { - //This key is used by another Merchant account - var paymentResult1 = CreatePaymentResultWithIdempotency("AUTH_IDEMPOTENCY_KEY_AUTHOR"); - var paymentResult2 = CreatePaymentResultWithIdempotency("AUTH_IDEMPOTENCY_KEY_AUTHOR"); - } - catch (HttpClientException ex) - { - Assert.AreEqual(ex.Code, 403); - } - } - - [TestMethod] - public void AuthenticationResult() - { - var authenticationResultRequest = new AuthenticationResultRequest - { - MerchantAccount = ClientConstants.MerchantAccount, - PspReference = GetTestPspReference() - }; - var client = CreateApiKeyTestClient(); - var payment = new PaymentService(client); - try - { - payment.GetAuthenticationResult(authenticationResultRequest); - } - catch (HttpClientException ex) - { - Assert.AreEqual(422, ex.Code); - } - } - - private string GetAdditionalData(Dictionary additionalData, string assertKey) - { - string result = ""; - if (additionalData.ContainsKey(assertKey)) - { - result = additionalData[assertKey]; - } - return result; - } - } -} diff --git a/Adyen.IntegrationTest/PayoutTest.cs b/Adyen.IntegrationTest/PayoutTest.cs deleted file mode 100644 index f4a8e593a..000000000 --- a/Adyen.IntegrationTest/PayoutTest.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Adyen.Service; -using Adyen.Model.Payout; -using Adyen.Model; -using Adyen.HttpClient; -using Adyen.Service.Payout; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class PayoutTest : BaseTest - { - private Client _client; - private InstantPayoutsService _instantPayoutsService; - private InitializationService _initializationService; - private ReviewingService _reviewingService; - - [TestInitialize] - public void Init() - { - _client = this.CreateApiKeyTestClient(); - _instantPayoutsService = new InstantPayoutsService(_client); - _initializationService = new InitializationService(_client); - _reviewingService = new ReviewingService(_client); - } - - [TestMethod] - public void PayoutSuccessTest() - { - var payoutRequest = CreatePayoutRequest(ClientConstants.MerchantAccount); - var result = _instantPayoutsService.Payout(payoutRequest); - Assert.AreEqual(result.ResultCode, PayoutResponse.ResultCodeEnum.Refused); - } - - - [TestMethod] - public void PayoutErrorMissingMerchantTest() - { - var payoutRequest = CreatePayoutRequest(""); - var ex = Assert.ThrowsException(() => _instantPayoutsService.Payout(payoutRequest)); - Assert.AreEqual(ex.Code, 403); - } - - [TestMethod] - public void PayoutErrorMissingReferenceTest() - { - var payoutRequest = CreatePayoutRequest(ClientConstants.MerchantAccount); - payoutRequest.Reference = ""; - var ex = Assert.ThrowsException(() => _instantPayoutsService.Payout(payoutRequest)); - Assert.AreEqual("{\"status\":422,\"errorCode\":\"130\",\"message\":\"Required field 'reference' is not provided.\",\"errorType\":\"validation\"}",ex.ResponseBody); - Assert.AreEqual(422, ex.Code); - } - - private PayoutRequest CreatePayoutRequest(string merchantAccount) - { - var payoutRequest = new PayoutRequest - { - Amount = new Model.Payout.Amount { Currency = "EUR", Value = 10 }, - Card = new Model.Payout.Card - { - Number = "4111111111111111", - ExpiryMonth = "03", - ExpiryYear = "2030", - HolderName = "John Smith", - Cvc = "737" - }, - MerchantAccount = merchantAccount, - Reference = "Your order number from e2e", - ShopperReference = "reference", - }; - return payoutRequest; - } - } -} diff --git a/Adyen.IntegrationTest/RecurringTest.cs b/Adyen.IntegrationTest/RecurringTest.cs deleted file mode 100644 index 42726c666..000000000 --- a/Adyen.IntegrationTest/RecurringTest.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using Adyen.Model.Recurring; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Linq; -using static Adyen.Model.Recurring.Recurring; - -namespace Adyen.IntegrationTest -{ - [TestClass] - public class RecurringTest : BaseTest - { - - [TestMethod] - public void TestListRecurringDetails() - { - var paymentResult = base.CreatePaymentResultWithRecurring(Model.Payment.Recurring.ContractEnum.RECURRING); - var client = CreateApiKeyTestClient(); - var recurring = new Service.RecurringService(client); - var recurringDetailsRequest = this.CreateRecurringDetailsRequest(); - var recurringDetailsResult = recurring.ListRecurringDetails(recurringDetailsRequest); - var recurringDetail = recurringDetailsResult.Details[0].RecurringDetail; - Assert.AreEqual(recurringDetail.PaymentMethodVariant, "visa"); - } - - [TestMethod] - public void TestDisable() - { - var paymentResult = base.CreatePaymentResultWithRecurring(Model.Payment.Recurring.ContractEnum.ONECLICK); - var client = CreateApiKeyTestClient(); - var recurring = new Service.RecurringService(client); - var disableRequest = this.CreateDisableRequest(); - var disableResult = recurring.Disable(disableRequest); - Assert.AreEqual("[all-details-successfully-disabled]", disableResult.Response); - } - - private RecurringDetailsRequest CreateRecurringDetailsRequest() - { - var request = new RecurringDetailsRequest - { - ShopperReference = "test-1234", - MerchantAccount = ClientConstants.MerchantAccount, - Recurring = new Recurring { Contract = ContractEnum.RECURRING } - }; - return request; - } - - private DisableRequest CreateDisableRequest() - { - var request = new DisableRequest - { - ShopperReference = "test-1234", - MerchantAccount = ClientConstants.MerchantAccount - }; - return request; - } - } -} diff --git a/Adyen.Test/AcsWebhooks/AcsWebhooksTest.cs b/Adyen.Test/AcsWebhooks/AcsWebhooksTest.cs new file mode 100644 index 000000000..820a61934 --- /dev/null +++ b/Adyen.Test/AcsWebhooks/AcsWebhooksTest.cs @@ -0,0 +1,143 @@ +using Adyen.AcsWebhooks.Extensions; +using Adyen.AcsWebhooks.Models; +using Adyen.AcsWebhooks.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using Adyen.AcsWebhooks.Handlers; + +namespace Adyen.Test.AcsWebhooks +{ + [TestClass] + public class AcsWebhooksTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly IAcsWebhooksHandler _acsWebhooksHandler; + + public AcsWebhooksTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureAcsWebhooks((context, services, config) => + { + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + _acsWebhooksHandler = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_Authentication_Webhook_WHen_OOB_TRIGGER_FL_Returns_Correct_Challenge_Flow() + { + // Arrange + string json = @" +{ + ""data"": { + ""authentication"": { + ""acsTransId"": ""6a4c1709-a42e-4c7f-96c7-1043adacfc97"", + ""challenge"": { + ""flow"": ""OOB_TRIGGER_FL"", + ""lastInteraction"": ""2022-12-22T15:49:03+01:00"" + }, + ""challengeIndicator"": ""01"", + ""createdAt"": ""2022-12-22T15:45:03+01:00"", + ""deviceChannel"": ""app"", + ""dsTransID"": ""a3b86754-444d-46ca-95a2-ada351d3f42c"", + ""exemptionIndicator"": ""lowValue"", + ""inPSD2Scope"": true, + ""messageCategory"": ""payment"", + ""messageVersion"": ""2.2.0"", + ""riskScore"": 0, + ""threeDSServerTransID"": ""6edcc246-23ee-4e94-ac5d-8ae620bea7d9"", + ""transStatus"": ""Y"", + ""type"": ""challenge"" + }, + ""balancePlatform"": ""YOUR_BALANCE_PLATFORM"", + ""id"": ""497f6eca-6276-4993-bfeb-53cbbbba6f08"", + ""paymentInstrumentId"": ""PI3227C223222B5BPCMFXD2XG"", + ""purchase"": { + ""date"": ""2022-12-22T15:49:03+01:00"", + ""merchantName"": ""MyShop"", + ""originalAmount"": { + ""currency"": ""EUR"", + ""value"": 1000 + } + }, + ""status"": ""authenticated"" + }, + ""environment"": ""test"", + ""timestamp"": ""2022-12-22T15:42:03+01:00"", + ""type"": ""balancePlatform.authentication.created"" +}"; + + // Act + AuthenticationNotificationRequest r = _acsWebhooksHandler.DeserializeAuthenticationNotificationRequest(json); + + // Assert + Assert.IsNotNull(r); + Assert.AreEqual(AuthenticationNotificationRequest.TypeEnum.BalancePlatformAuthenticationCreated, r.Type); + Assert.AreEqual("test", r.Environment); + Assert.AreEqual(DateTime.Parse("2022-12-22T15:42:03+01:00"), r.Timestamp); + + Assert.IsNotNull(r.Data); + Assert.AreEqual("497f6eca-6276-4993-bfeb-53cbbbba6f08", r.Data.Id); + Assert.AreEqual("YOUR_BALANCE_PLATFORM", r.Data.BalancePlatform); + Assert.AreEqual("PI3227C223222B5BPCMFXD2XG", r.Data.PaymentInstrumentId); + Assert.AreEqual(AuthenticationNotificationData.StatusEnum.Authenticated, r.Data.Status); + + Assert.IsNotNull(r.Data.Purchase); + Assert.AreEqual("2022-12-22T15:49:03+01:00", r.Data.Purchase.Date); + Assert.AreEqual("MyShop", r.Data.Purchase.MerchantName); + Assert.AreEqual("EUR", r.Data.Purchase.OriginalAmount.Currency); + Assert.AreEqual(1000, r.Data.Purchase.OriginalAmount.Value); + + Assert.IsNotNull(r.Data.Authentication); + Assert.AreEqual("6a4c1709-a42e-4c7f-96c7-1043adacfc97", r.Data.Authentication.AcsTransId); + Assert.AreEqual(AuthenticationInfo.ChallengeIndicatorEnum._01, r.Data.Authentication.ChallengeIndicator); + Assert.AreEqual(DateTime.Parse("2022-12-22T15:45:03+01:00"), r.Data.Authentication.CreatedAt); + Assert.AreEqual(AuthenticationInfo.DeviceChannelEnum.App, r.Data.Authentication.DeviceChannel); + Assert.AreEqual("a3b86754-444d-46ca-95a2-ada351d3f42c", r.Data.Authentication.DsTransID); + Assert.AreEqual(AuthenticationInfo.ExemptionIndicatorEnum.LowValue, r.Data.Authentication.ExemptionIndicator); + Assert.IsTrue(r.Data.Authentication.InPSD2Scope); + Assert.AreEqual(AuthenticationInfo.MessageCategoryEnum.Payment, r.Data.Authentication.MessageCategory); + Assert.AreEqual("2.2.0", r.Data.Authentication.MessageVersion); + Assert.AreEqual(0, r.Data.Authentication.RiskScore); + Assert.AreEqual("6edcc246-23ee-4e94-ac5d-8ae620bea7d9", r.Data.Authentication.ThreeDSServerTransID); + Assert.AreEqual(AuthenticationInfo.TransStatusEnum.Y, r.Data.Authentication.TransStatus); + Assert.AreEqual(AuthenticationInfo.TypeEnum.Challenge, r.Data.Authentication.Type); + + Assert.IsNotNull(r.Data.Authentication.Challenge); + Assert.AreEqual(ChallengeInfo.FlowEnum.OOBTRIGGERFL, r.Data.Authentication.Challenge.Flow); + Assert.AreEqual(DateTime.Parse("2022-12-22T15:49:03+01:00"), r.Data.Authentication.Challenge.LastInteraction); + } + + [TestMethod] + public void Given_AccountHolder_Webhook_When_Required_Fields_Are_Unspecified_Result_Should_Throw_ArgumentException() + { + // Arrange + string json = @"{ ""type"": ""unknowntype"" }"; // No Data, no Environment values (which are required)! + + // Act + // Assert + Assert.Throws(() => + { + _acsWebhooksHandler.DeserializeAuthenticationNotificationRequest(json); + }); + } + + [TestMethod] + public void Given_AccountHolder_Webhook_When_Invalid_Json_Result_Should_Throw_JsonException() + { + // Arrange + string json = "{ invalid,.json; }"; + + // Act + // Assert + Assert.Throws(() => + { + _acsWebhooksHandler.DeserializeAuthenticationNotificationRequest(json); + }); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Adyen.Test.csproj b/Adyen.Test/Adyen.Test.csproj index ac0cc226d..0f160fee1 100644 --- a/Adyen.Test/Adyen.Test.csproj +++ b/Adyen.Test/Adyen.Test.csproj @@ -1,7 +1,7 @@  - net8.0;net6.0 + net8.0 12 enable disable diff --git a/Adyen.Test/BalanceControl/BalanceControlTest.cs b/Adyen.Test/BalanceControl/BalanceControlTest.cs new file mode 100644 index 000000000..a71c543fa --- /dev/null +++ b/Adyen.Test/BalanceControl/BalanceControlTest.cs @@ -0,0 +1,72 @@ +using Adyen.BalanceControl.Client; +using Adyen.BalanceControl.Extensions; +using Adyen.BalanceControl.Models; +using Adyen.BalanceControl.Services; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.BalanceControl +{ + [TestClass] + public class BalanceControlTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public BalanceControlTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalanceControl((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_BalanceControlTransfer_Returns_Correct_Status() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/balance-control-transfer.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.CreatedAt, new DateTime(2022,01, 24)); + Assert.AreEqual(response.Status, BalanceTransferResponse.StatusEnum.Transferred); + } + + [TestMethod] + public async Task Given_IBalanceControlService_When_Live_Url_And_Prefix_Are_Set_Returns_Correct_Live_Url_Endpoint() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureBalanceControl((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "your-live-api-key"; + options.Environment = AdyenEnvironment.Live; + options.LiveEndpointUrlPrefix = "prefix"; + }); + }) + .Build(); + + // Act + var balanceControlService = liveHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://prefix-pal-live.adyenpayments.com/pal/servlet/BalanceControl/v1", balanceControlService.HttpClient.BaseAddress.ToString()); + } + + } +} \ No newline at end of file diff --git a/Adyen.Test/BalanceControlTest.cs b/Adyen.Test/BalanceControlTest.cs deleted file mode 100644 index 64d3e92dd..000000000 --- a/Adyen.Test/BalanceControlTest.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using Adyen.Model.BalanceControl; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class BalanceControlTest : BaseTest - { - [TestMethod] - public void BalanceTransferTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balance-control-transfer.json"); - var service = new BalanceControlService(client); - var response = service.BalanceTransfer(new BalanceTransferRequest()); - Assert.AreEqual(response.CreatedAt, new DateTime(2022,01, 24)); - Assert.AreEqual(response.Status, BalanceTransferResponse.StatusEnum.Transferred); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/AccountHolders/AccountHolderTest.cs b/Adyen.Test/BalancePlatform/AccountHolders/AccountHolderTest.cs new file mode 100644 index 000000000..3e31dd17f --- /dev/null +++ b/Adyen.Test/BalancePlatform/AccountHolders/AccountHolderTest.cs @@ -0,0 +1,100 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.BalancePlatform.AccountHolders +{ + [TestClass] + public class AccountHolderTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public AccountHolderTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + + [TestMethod] + public async Task Given_AccountHolder_When_Unknown_Enum_Then_Result_Deserialize_To_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/AccountHolderWithUnknownEnum.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response); + Assert.IsNull(response.Status); + } + + [TestMethod] + public async Task Given_AccountHolder_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/AccountHolder.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, AccountHolder.StatusEnum.Active); + Assert.AreEqual(response.Id, "AH32272223222B5CM4MWJ892H"); + } + + [TestMethod] + public async Task Given_PaginatedBalanceAccountsResponse_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/PaginatedAccountHoldersResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Arrange + Assert.AreEqual(response.AccountHolders[0].Id, "AH32272223222B5GFSNSXFFL9"); + Assert.AreEqual(response.AccountHolders[0].Status, AccountHolder.StatusEnum.Active); + } + + [TestMethod] + public async Task Given_IAccountHolderService_When_Live_Url_And_Prefix_Are_Set_Returns_Correct_Live_Url_Endpoint_And_No_Prefix() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "your-live-api-key"; + options.Environment = AdyenEnvironment.Live; + options.LiveEndpointUrlPrefix = "prefix"; + }); + }) + .Build(); + + // Act + var accountHoldersService = liveHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://balanceplatform-api-live.adyen.com/bcl/v2", accountHoldersService.HttpClient.BaseAddress.ToString()); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/BalanceAccounts/BalanceAccountTest.cs b/Adyen.Test/BalancePlatform/BalanceAccounts/BalanceAccountTest.cs new file mode 100644 index 000000000..2c24c10b5 --- /dev/null +++ b/Adyen.Test/BalancePlatform/BalanceAccounts/BalanceAccountTest.cs @@ -0,0 +1,108 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.BalancePlatform.BalanceAccounts +{ + [TestClass] + public class BalanceAccountTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public BalanceAccountTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_BalanceAccounts_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/BalanceAccount.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, BalanceAccount.StatusEnum.Active); + Assert.AreEqual(response.Id, "BA3227C223222H5J4DCGQ9V9L"); + } + + [TestMethod] + public async Task Given_SweepConfigurationV2_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/SweepConfiguration.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, SweepConfigurationV2.StatusEnum.Active); + Assert.AreEqual(response.Type, SweepConfigurationV2.TypeEnum.Pull); + Assert.AreEqual(response.Id, "SWPC4227C224555B5FTD2NT2JV4WN5"); + } + + [TestMethod] + public async Task Given_BalanceSweepConfigurationsResponse_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/BalanceSweepConfigurationsResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Sweeps[0].Status, SweepConfigurationV2.StatusEnum.Active); + Assert.AreEqual(response.Sweeps[0].Id, "SWPC4227C224555B5FTD2NT2JV4WN5"); + Assert.AreEqual(response.Sweeps[0].Schedule.Type, SweepSchedule.TypeEnum.Daily); + } + + [TestMethod] + public async Task Given_UpdateSweepConfigurationV2_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/SweepConfiguration.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, SweepConfigurationV2.StatusEnum.Active); + Assert.AreEqual(response.Type, SweepConfigurationV2.TypeEnum.Pull); + Assert.AreEqual(response.Id, "SWPC4227C224555B5FTD2NT2JV4WN5"); + } + + [TestMethod] + public async Task Given_Deserialize_When_PaginatedPaymentInstrumentsResponse_Returns_Correct_Object() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.PaymentInstruments[0].Status, PaymentInstrument.StatusEnum.Active); + Assert.AreEqual(response.PaymentInstruments[0].Id, "PI32272223222B59M5TM658DT"); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/BalancePlatformTest.cs b/Adyen.Test/BalancePlatform/BalancePlatformTest.cs new file mode 100644 index 000000000..e3056971a --- /dev/null +++ b/Adyen.Test/BalancePlatform/BalancePlatformTest.cs @@ -0,0 +1,61 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.BalancePlatform +{ + [TestClass] + public class BalancePlatformTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public BalancePlatformTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_BalancePlatform_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/BalancePlatform.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, "Active"); + Assert.AreEqual(response.Id, "YOUR_BALANCE_PLATFORM"); + } + + [TestMethod] + public async Task Given_PaginatedAccountHoldersResponse_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/PaginatedBalanceAccountsResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("BA32272223222B5CTDNB66W2Z", response.BalanceAccounts[0].Id); + Assert.AreEqual(BalanceAccountBase.StatusEnum.Active, response.BalanceAccounts[1].Status); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/PaymentInstrumentGroups/PaymentInstrumentGroupTest.cs b/Adyen.Test/BalancePlatform/PaymentInstrumentGroups/PaymentInstrumentGroupTest.cs new file mode 100644 index 000000000..f7cc1f109 --- /dev/null +++ b/Adyen.Test/BalancePlatform/PaymentInstrumentGroups/PaymentInstrumentGroupTest.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.BalancePlatform.PaymentInstrumentGroups +{ + [TestClass] + public class PaymentInstrumentGroupTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public PaymentInstrumentGroupTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_PaymentInstrumentGroup_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/PaymentInstrumentGroup.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Id, "PG3227C223222B5CMD3FJFKGZ"); + Assert.AreEqual(response.BalancePlatform, "YOUR_BALANCE_PLATFORM"); + } + + [TestMethod] + public async Task Given_TransactionRulesResponse_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransactionRulesResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Arrange + Assert.AreEqual(response.TransactionRules[0].Type, TransactionRule.TypeEnum.Velocity); + Assert.AreEqual(response.TransactionRules[0].Id, "TR3227C223222C5GXR3XP596N"); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/PaymentInstruments/PaymentInstrumentTest.cs b/Adyen.Test/BalancePlatform/PaymentInstruments/PaymentInstrumentTest.cs new file mode 100644 index 000000000..2e8ccd257 --- /dev/null +++ b/Adyen.Test/BalancePlatform/PaymentInstruments/PaymentInstrumentTest.cs @@ -0,0 +1,49 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.BalancePlatform.PaymentInstruments +{ + [TestClass] + public class PaymentInstrumentTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public PaymentInstrumentTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_PaymentInstrument_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/PaymentInstrument.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.BalanceAccountId, "BA3227C223222B5CTBLR8BWJB"); + Assert.AreEqual(response.Type, PaymentInstrument.TypeEnum.BankAccount); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/TransactionRules/TransactionRuleTest.cs b/Adyen.Test/BalancePlatform/TransactionRules/TransactionRuleTest.cs new file mode 100644 index 000000000..82b13cf91 --- /dev/null +++ b/Adyen.Test/BalancePlatform/TransactionRules/TransactionRuleTest.cs @@ -0,0 +1,112 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.BalancePlatform.TransactionRules +{ + [TestClass] + public class TransactionRuleTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public TransactionRuleTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_TransactionRule_Serialize_Correctly() + { + // Arrange + var target = new TransactionRule( + description: "Allow only point-of-sale transactions", + reference: "YOUR_REFERENCE_4F7346", + entityKey: new TransactionRuleEntityKey(entityType: "paymentInstrument", entityReference: "PI3227C223222B5BPCMFXD2XG"), + status: TransactionRule.StatusEnum.Active, + interval: new TransactionRuleInterval("perTransaction"), + ruleRestrictions: new TransactionRuleRestrictions( + processingTypes: new ProcessingTypesRestriction( + operation: "noneMatch", + value: new List + { + ProcessingTypesRestriction.ValueEnum.Pos, + ProcessingTypesRestriction.ValueEnum.Ecommerce + }) + ), + type: "blockList" + ); + + // Act + string result = JsonSerializer.Serialize(target, _jsonSerializerOptionsProvider.Options); + + // Assert + JsonDocument jsonDoc = JsonDocument.Parse(result); + JsonElement root = jsonDoc.RootElement; + + Assert.AreEqual("Allow only point-of-sale transactions", root.GetProperty("description").GetString()); + Assert.AreEqual("YOUR_REFERENCE_4F7346", root.GetProperty("reference").GetString()); + + JsonElement entityKey = root.GetProperty("entityKey"); + Assert.AreEqual("paymentInstrument", entityKey.GetProperty("entityType").GetString()); + Assert.AreEqual("PI3227C223222B5BPCMFXD2XG", entityKey.GetProperty("entityReference").GetString()); + Assert.AreEqual("active", root.GetProperty("status").GetString()); + + JsonElement interval = root.GetProperty("interval"); + Assert.AreEqual("perTransaction", interval.GetProperty("type").GetString()); + + JsonElement processingTypes = root.GetProperty("ruleRestrictions").GetProperty("processingTypes"); + Assert.AreEqual("noneMatch", processingTypes.GetProperty("operation").GetString()); + + JsonElement.ArrayEnumerator values = processingTypes.GetProperty("value").EnumerateArray(); + Assert.IsTrue(values.Any(v => v.GetString() == "pos") && values.Any(v => v.GetString() == "ecommerce")); + Assert.AreEqual("blockList", root.GetProperty("type").GetString()); + } + + [TestMethod] + public async Task Given_TransactionRule_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransactionRule.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.EntityKey.EntityReference, "PI3227C223222B5BPCMFXD2XG"); + Assert.AreEqual(response.EntityKey.EntityType, "paymentInstrument"); + Assert.AreEqual(response.Interval.Type, TransactionRuleInterval.TypeEnum.PerTransaction); + Assert.AreEqual(response.RuleRestrictions.ProcessingTypes.Operation, "noneMatch"); + } + + [TestMethod] + public async Task Given_TransactionRuleResponse_Deserialize_Correctly() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransactionRuleResponse.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.TransactionRule.Id, "TR32272223222B5GFSGFLFCHM"); + Assert.AreEqual(response.TransactionRule.Interval.Type, TransactionRuleInterval.TypeEnum.PerTransaction); + Assert.AreEqual(response.TransactionRule.RuleRestrictions.ProcessingTypes.Operation, "noneMatch"); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalanceAccountLevelTest.cs b/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalanceAccountLevelTest.cs new file mode 100644 index 000000000..f745e6e50 --- /dev/null +++ b/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalanceAccountLevelTest.cs @@ -0,0 +1,88 @@ +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.BalancePlatform.TransferLimits +{ + [TestClass] + public class TransferLimitsBalanceAccountLevelTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public TransferLimitsBalanceAccountLevelTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public void GetTransferLimitDeserializes() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransferLimit.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(10000, response.Amount.Value); + Assert.AreEqual("EUR", response.Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000001", response.Id); + Assert.AreEqual(Scope.PerTransaction, response.Scope); + Assert.AreEqual("Your reference for the transfer limit", response.Reference); + Assert.AreEqual(ScaStatus.Pending, response.ScaInformation.Status); + Assert.AreEqual(LimitStatus.PendingSCA, response.LimitStatus); + Assert.AreEqual(TransferType.All, response.TransferType); + } + + [TestMethod] + public void GetTransferLimitsListDeserializes() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransferLimits.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(2, response.TransferLimits.Count); + + Assert.AreEqual(10000, response.TransferLimits[0].Amount.Value); + Assert.AreEqual("EUR", response.TransferLimits[0].Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000001", response.TransferLimits[0].Id); + Assert.AreEqual(Scope.PerTransaction, response.TransferLimits[0].Scope); + Assert.AreEqual("Your reference for the transfer limit", response.TransferLimits[0].Reference); + Assert.AreEqual(ScaExemption.InitialLimit, response.TransferLimits[0].ScaInformation.Exemption); + Assert.AreEqual(ScaStatus.NotPerformed, response.TransferLimits[0].ScaInformation.Status); + Assert.AreEqual(LimitStatus.Active, response.TransferLimits[0].LimitStatus); + Assert.AreEqual(TransferType.Instant, response.TransferLimits[0].TransferType); + + Assert.AreEqual(20000, response.TransferLimits[1].Amount.Value); + Assert.AreEqual("EUR", response.TransferLimits[1].Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000002", response.TransferLimits[1].Id); + Assert.AreEqual(Scope.PerTransaction, response.TransferLimits[1].Scope); + Assert.AreEqual("Your reference for the transfer limit", response.TransferLimits[1].Reference); + Assert.AreEqual(ScaExemption.InitialLimit, response.TransferLimits[1].ScaInformation.Exemption); + Assert.AreEqual(ScaStatus.NotPerformed, response.TransferLimits[1].ScaInformation.Status); + Assert.AreEqual(LimitStatus.Active, response.TransferLimits[1].LimitStatus); + Assert.AreEqual(TransferType.All, response.TransferLimits[1].TransferType); + } + } +} diff --git a/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalancePlatformLevelTest.cs b/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalancePlatformLevelTest.cs new file mode 100644 index 000000000..00fdbe218 --- /dev/null +++ b/Adyen.Test/BalancePlatform/TransferLimits/TransferLimitsBalancePlatformLevelTest.cs @@ -0,0 +1,125 @@ +using System.Net; +using System.Text.Json; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.BalancePlatform.TransferLimits +{ + [TestClass] + public class TransferLimitsBalancePlatformLevelTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly ITransferLimitsBalanceAccountLevelService _transferLimitsBalanceAccountLevelService; + + + public TransferLimitsBalancePlatformLevelTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + _transferLimitsBalanceAccountLevelService = Substitute.For(); + + } + + [TestMethod] + public void GetTransferLimitDeserializes() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransferLimit.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(10000, response.Amount.Value); + Assert.AreEqual("EUR", response.Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000001", response.Id); + Assert.AreEqual(Scope.PerTransaction, response.Scope); + Assert.AreEqual("Your reference for the transfer limit", response.Reference); + Assert.AreEqual(ScaStatus.Pending, response.ScaInformation.Status); + Assert.AreEqual(LimitStatus.PendingSCA, response.LimitStatus); + Assert.AreEqual(TransferType.All, response.TransferType); + } + + [TestMethod] + public void GetTransferLimitsListDeserializes() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransferLimits.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(2, response.TransferLimits.Count); + + Assert.AreEqual(10000, response.TransferLimits[0].Amount.Value); + Assert.AreEqual("EUR", response.TransferLimits[0].Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000001", response.TransferLimits[0].Id); + Assert.AreEqual(Scope.PerTransaction, response.TransferLimits[0].Scope); + Assert.AreEqual("Your reference for the transfer limit", response.TransferLimits[0].Reference); + Assert.AreEqual(ScaExemption.InitialLimit, response.TransferLimits[0].ScaInformation.Exemption); + Assert.AreEqual(ScaStatus.NotPerformed, response.TransferLimits[0].ScaInformation.Status); + Assert.AreEqual(LimitStatus.Active, response.TransferLimits[0].LimitStatus); + Assert.AreEqual(TransferType.Instant, response.TransferLimits[0].TransferType); + + Assert.AreEqual(20000, response.TransferLimits[1].Amount.Value); + Assert.AreEqual("EUR", response.TransferLimits[1].Amount.Currency); + Assert.AreEqual("TRLI00000000000000000000000002", response.TransferLimits[1].Id); + Assert.AreEqual(Scope.PerTransaction, response.TransferLimits[1].Scope); + Assert.AreEqual("Your reference for the transfer limit", response.TransferLimits[1].Reference); + Assert.AreEqual(ScaExemption.InitialLimit, response.TransferLimits[1].ScaInformation.Exemption); + Assert.AreEqual(ScaStatus.NotPerformed, response.TransferLimits[1].ScaInformation.Status); + Assert.AreEqual(LimitStatus.Active, response.TransferLimits[1].LimitStatus); + Assert.AreEqual(TransferType.All, response.TransferLimits[1].TransferType); + } + + /// + /// Test GetLegalEntity + /// + [TestMethod] + public async Task GetSpecificTransferLimitAsync() + { + string json = TestUtilities.GetTestFileContent("mocks/balanceplatform/TransferLimit.json"); + + _transferLimitsBalanceAccountLevelService.GetSpecificTransferLimitAsync(Arg.Any(), Arg.Any()) + .Returns( + Task.FromResult( + new TransferLimitsBalanceAccountLevelService.GetSpecificTransferLimitApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage(), + json, + "/balanceAccounts/BA1234567890/transferLimits/TRLI00000000000000000000000001", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + IGetSpecificTransferLimitApiResponse response = await _transferLimitsBalanceAccountLevelService.GetSpecificTransferLimitAsync("BA1234567890","TRLI00000000000000000000000001"); + + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual("TRLI00000000000000000000000001", response.Ok().Id); + } + + } +} diff --git a/Adyen.Test/BalancePlatformTest.cs b/Adyen.Test/BalancePlatformTest.cs deleted file mode 100644 index 81e489e9f..000000000 --- a/Adyen.Test/BalancePlatformTest.cs +++ /dev/null @@ -1,428 +0,0 @@ -using System; -using System.Net.Http; -using System.Threading; -using Adyen.Model.BalancePlatform; -using Adyen.Service.BalancePlatform; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; - -namespace Adyen.Test -{ - [TestClass] - public class BalancePlatformTest : BaseTest - { - #region AccountHolders - - /// - /// Test GetAccountHoldersId - /// - [TestMethod] - public void GetAccountHoldersIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/AccountHolder.json"); - var service = new AccountHoldersService(client); - - var response = service.GetAccountHolder("AH32272223222B5CM4MWJ892H"); - Assert.AreEqual(response.Status, AccountHolder.StatusEnum.Active); - Assert.AreEqual(response.Id, "AH32272223222B5CM4MWJ892H"); - } - - /// - /// Test PostAccountHolders - /// - [TestMethod] - public void PostAccountHoldersTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/AccountHolder.json"); - var service = new AccountHoldersService(client); - var accountHolder = new AccountHolderInfo() - { - BalancePlatform = "balance" - }; - var response = service.CreateAccountHolder(accountHolder); - Assert.AreEqual(response.Status, AccountHolder.StatusEnum.Active); - Assert.AreEqual(response.Id, "AH32272223222B5CM4MWJ892H"); - } - - /// - /// Test PatchAccountHoldersId - /// - [TestMethod] - public void PatchAccountHoldersIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/AccountHolder.json"); - var service = new AccountHoldersService(client); - var accountHolder = new AccountHolderUpdateRequest() - { - BalancePlatform = "balance" - }; - var response = service.UpdateAccountHolder("AH32272223222B5CM4MWJ892H", accountHolder); - Assert.AreEqual(response.Status, AccountHolder.StatusEnum.Active); - Assert.AreEqual(response.Id, "AH32272223222B5CM4MWJ892H"); - } - - /// - /// Test GetAccountHoldersIdBalanceAccountsAsync - /// - [TestMethod] - public void GetAccountHoldersIdBalanceAccountsAsyncTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaginatedBalanceAccountsResponse.json"); - var service = new AccountHoldersService(client); - - var response = service.GetAllBalanceAccountsOfAccountHolderAsync("id", offset: 1, limit: 3).Result; - Assert.AreEqual("BA32272223222B59K6ZXHBFN6", response.BalanceAccounts[0].Id); - Assert.AreEqual(BalanceAccountBase.StatusEnum.Closed, response.BalanceAccounts[1].Status); - ClientInterfaceSubstitute.Received() - .RequestAsync( - "https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders/id/balanceAccounts?offset=1&limit=3", - null, null, HttpMethod.Get, default); - } - - #endregion - - #region BalanceAccounts - - /// - /// Test GetBalanceAccountsId - /// - [TestMethod] - public void GetBalanceAccountsIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/BalanceAccount.json"); - var service = new BalanceAccountsService(client); - - var response = service.GetBalanceAccount("AH32272223222B5CM4MWJ892H"); - Assert.AreEqual(response.Status, BalanceAccount.StatusEnum.Active); - Assert.AreEqual(response.Id, "BA3227C223222B5BLP6JQC3FD"); - } - - /// - /// Test GetBalanceAccountsId - /// - [TestMethod] - public void PostBalanceAccountsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/BalanceAccount.json"); - var service = new BalanceAccountsService(client); - var balanceAccountInfo = new BalanceAccountInfo() - { - AccountHolderId = "accountHolderId" - }; - var response = service.CreateBalanceAccount(balanceAccountInfo); - Assert.AreEqual(response.Status, BalanceAccount.StatusEnum.Active); - Assert.AreEqual(response.Id, "BA3227C223222B5BLP6JQC3FD"); - } - - /// - /// Test PatchBalanceAccountsIdAsync - /// - [TestMethod] - public void PatchBalanceAccountsIdAsyncTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/BalanceAccount.json"); - var service = new BalanceAccountsService(client); - var response = service.UpdateBalanceAccountAsync("BA3227C223222B5BLP6JQC3FD", new BalanceAccountUpdateRequest()).Result; - Assert.AreEqual(response.Status, BalanceAccount.StatusEnum.Active); - Assert.AreEqual(response.Id, "BA3227C223222B5BLP6JQC3FD"); - } - - /// - /// Test PostBalanceAccountsBalanceAccountIdSweeps - /// - [TestMethod] - public void PostBalanceAccountsBalanceAccountIdSweepsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/SweepConfiguration.json"); - var service = new BalanceAccountsService(client); - - var response = service.CreateSweep("1245yhgeswkrw", new CreateSweepConfigurationV2()); - Assert.AreEqual(response.Status, SweepConfigurationV2.StatusEnum.Active); - Assert.AreEqual(response.Type, SweepConfigurationV2.TypeEnum.Pull); - } - - /// - /// Test GetBalanceAccountsBalanceAccountIdSweeps - /// - [TestMethod] - public void GetBalanceAccountsBalanceAccountIdSweepsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/BalanceSweepConfigurationsResponse.json"); - var service = new BalanceAccountsService(client); - - var response = service.GetAllSweepsForBalanceAccount("balanceAccountId"); - Assert.AreEqual(response.Sweeps[0].Status, SweepConfigurationV2.StatusEnum.Active); - Assert.AreEqual(response.Sweeps[0].Id, "SWPC4227C224555B5FTD2NT2JV4WN5"); - var schedule = response.Sweeps[0].Schedule.Type; - Assert.AreEqual(schedule, SweepSchedule.TypeEnum.Daily); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://balanceplatform-api-test.adyen.com/bcl/v2/balanceAccounts/balanceAccountId/sweeps", - null, - null, HttpMethod.Get, new CancellationToken()); - } - - /// - /// Test PatchBalanceAccountsBalanceAccountIdSweepsSweepId - /// - [TestMethod] - public void PatchBalanceAccountsBalanceAccountIdSweepsSweepIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/SweepConfiguration.json"); - var service = new BalanceAccountsService(client); - - var response = service.UpdateSweep("balanceID", "sweepId",new UpdateSweepConfigurationV2()); - Assert.AreEqual(response.Status, SweepConfigurationV2.StatusEnum.Active); - Assert.AreEqual(response.Type, SweepConfigurationV2.TypeEnum.Pull); - } - - /// - /// Test DeleteBalanceAccountsBalanceAccountIdSweepsSweepId - /// - [TestMethod] - public void DeleteBalanceAccountsBalanceAccountIdSweepsSweepIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/SweepConfiguration.json"); - var service = new BalanceAccountsService(client); - service.DeleteSweep("balanceID", "sweepId"); - } - - /// - /// Test PatchBalanceAccountsBalanceAccountIdSweepsSweepId - /// - [TestMethod] - public void GetBalanceAccountsIdPaymentInstrumentsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json"); - var service = new BalanceAccountsService(client); - - var response = service.GetPaymentInstrumentsLinkedToBalanceAccount("balanceID"); - Assert.AreEqual(response.PaymentInstruments[0].Status, PaymentInstrument.StatusEnum.Active); - Assert.AreEqual(response.PaymentInstruments[0].Id, "PI32272223222B59M5TM658DT"); - } - #endregion - - #region General - - /// - /// Test GetBalancePlatformsId - /// - [TestMethod] - public void GetBalancePlatformsIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/BalancePlatform.json"); - var service = new PlatformService(client); - - var response = service.GetBalancePlatform("uniqueIdentifier"); - Assert.AreEqual(response.Status, "Active"); - Assert.AreEqual(response.Id, "YOUR_BALANCE_PLATFORM"); - } - - /// - /// Test GetBalancePlatformsIdAccountHolders - /// - [TestMethod] - public void GetBalancePlatformsIdAccountHoldersTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaginatedAccountHoldersResponse.json"); - var service = new PlatformService(client); - - var response = service.GetAllAccountHoldersUnderBalancePlatform("uniqueIdentifier"); - Assert.AreEqual(response.AccountHolders[0].Id, "AH32272223222B59DDWSCCMP7"); - Assert.AreEqual(response.AccountHolders[0].Status, AccountHolder.StatusEnum.Active); - } - - #endregion - - #region PaymentInstrumentGroups - - /// - /// Test GetPaymentInstrumentGroupsId - /// - [TestMethod] - public void GetPaymentInstrumentGroupsIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaymentInstrumentGroup.json"); - var service = new PaymentInstrumentGroupsService(client); - - var response = service.GetPaymentInstrumentGroup("uniqueIdentifier"); - Assert.AreEqual(response.Id, "PG3227C223222B5CMD3FJFKGZ"); - Assert.AreEqual(response.BalancePlatform, "YOUR_BALANCE_PLATFORM"); - } - - /// - /// Test PostPaymentInstrumentGroups - /// - [TestMethod] - public void PostPaymentInstrumentGroupsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaymentInstrumentGroup.json"); - var service = new PaymentInstrumentGroupsService(client); - - var response = service.CreatePaymentInstrumentGroup(new PaymentInstrumentGroupInfo()); - Assert.AreEqual(response.Id, "PG3227C223222B5CMD3FJFKGZ"); - Assert.AreEqual(response.BalancePlatform, "YOUR_BALANCE_PLATFORM"); - } - - /// - /// Test GetPaymentInstrumentGroupsIdTransactionRules - /// - [TestMethod] - public void GetPaymentInstrumentGroupsIdTransactionRulesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRulesResponse.json"); - var service = new PaymentInstrumentGroupsService(client); - - var response = service.GetAllTransactionRulesForPaymentInstrumentGroup("id"); - Assert.AreEqual(response.TransactionRules[0].Type, TransactionRule.TypeEnum.Velocity); - Assert.AreEqual(response.TransactionRules[0].Id, "TR32272223222B5CMDGMC9F4F"); - } - - #endregion - - #region PaymenInstruments - - /// - /// Test GetPaymentInstrumentGroupsId - /// - [TestMethod] - public void PostPaymentInstrumentsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaymentInstrument.json"); - var service = new PaymentInstrumentsService(client); - - var response = service.CreatePaymentInstrument(new PaymentInstrumentInfo()); - Assert.AreEqual(response.BalanceAccountId, "BA3227C223222B5CTBLR8BWJB"); - Assert.AreEqual(response.Type, PaymentInstrument.TypeEnum.BankAccount); - } - - /// - /// Test PatchPaymentInstrumentsId - /// - [TestMethod] - public void PatchPaymentInstrumentsIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaymentInstrument.json"); - var service = new PaymentInstrumentsService(client); - - var response = service.UpdatePaymentInstrument("id", new PaymentInstrumentUpdateRequest()); - Assert.AreEqual(response.BalanceAccountId, "BA3227C223222B5CTBLR8BWJB"); - Assert.AreEqual(response.Type, UpdatePaymentInstrument.TypeEnum.BankAccount); - } - - /// - /// Test GetPaymentInstrumentsId - /// - [TestMethod] - public void GetPaymentInstrumentsIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/PaymentInstrument.json"); - var service = new PaymentInstrumentsService(client); - - var response = service.GetPaymentInstrument("id"); - Assert.AreEqual(response.BalanceAccountId, "BA3227C223222B5CTBLR8BWJB"); - Assert.AreEqual(response.Type, PaymentInstrument.TypeEnum.BankAccount); - } - - /// - /// Test GetPaymentInstrumentsIdTransactionRules - /// - [TestMethod] - public void GetPaymentInstrumentsIdTransactionRulesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRulesResponse.json"); - var service = new PaymentInstrumentsService(client); - - var response = service.GetAllTransactionRulesForPaymentInstrument("id"); - Assert.AreEqual(response.TransactionRules[0].Id, "TR32272223222B5CMDGMC9F4F"); - Assert.AreEqual(response.TransactionRules[0].Type, TransactionRule.TypeEnum.Velocity); - } - - #endregion - - #region TransactionRules - - /// - /// Test PostTransactionRules - /// - [TestMethod] - public void PostTransactionRulesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRule.json"); - var service = new TransactionRulesService(client); - - var response = service.CreateTransactionRule(new TransactionRuleInfo()); - Assert.AreEqual(response.EntityKey.EntityReference, "PI3227C223222B5BPCMFXD2XG"); - Assert.AreEqual(response.EntityKey.EntityType, "paymentInstrument"); - Assert.AreEqual(response.Interval.Type, TransactionRuleInterval.TypeEnum.PerTransaction); - } - - /// - /// Test PatchTransactionRulesTransactionRuleId - /// - [TestMethod] - public void PatchTransactionRulesTransactionRuleIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRule.json"); - var service = new TransactionRulesService(client); - - var response = service.UpdateTransactionRule("transactionRuleId", new TransactionRuleInfo()); - Assert.AreEqual(response.EntityKey.EntityReference, "PI3227C223222B5BPCMFXD2XG"); - Assert.AreEqual(response.EntityKey.EntityType, "paymentInstrument"); - Assert.AreEqual(response.Interval.Type, TransactionRuleInterval.TypeEnum.PerTransaction); - } - - /// - /// Test GetTransactionRulesTransactionRuleId - /// - [TestMethod] - public void GetTransactionRulesTransactionRuleIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRuleResponse.json"); - var service = new TransactionRulesService(client); - - var response = service.GetTransactionRule("transactionRuleId"); - Assert.AreEqual(response.TransactionRule.Id, "TR32272223222B5CMD3V73HXG"); - Assert.AreEqual(response.TransactionRule.Interval.Type, TransactionRuleInterval.TypeEnum.Monthly); - } - - /// - /// Test DeleteTransactionRulesTransactionRuleId - /// - [TestMethod] - public void DeleteTransactionRulesTransactionRuleIdTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRuleResponse.json"); - var service = new TransactionRulesService(client); - var response = service.DeleteTransactionRule("transactionRuleId"); - - } - #endregion - - #region BankAccountValidation - /// - /// Test /validateBankAccountIdentification - /// - [TestMethod] - public void ValidateBankAccountTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/balanceplatform/TransactionRuleResponse.json"); - var service = new BankAccountValidationService(client); - var bankAccountIdentificationValidationRequest = new BankAccountIdentificationValidationRequest - { - AccountIdentification = new BankAccountIdentificationValidationRequestAccountIdentification( - new CZLocalAccountIdentification - { - AccountNumber = "123456789", - BankCode = "bankCode", - Type = CZLocalAccountIdentification.TypeEnum.CzLocal - }) - }; - service.ValidateBankAccountIdentification(bankAccountIdentificationValidationRequest); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://balanceplatform-api-test.adyen.com/bcl/v2/validateBankAccountIdentification", - Arg.Any(), - null, HttpMethod.Post, new CancellationToken()); - } - #endregion - } -} \ No newline at end of file diff --git a/Adyen.Test/BalancePlatformWebhookHandlerTest.cs b/Adyen.Test/BalancePlatformWebhookHandlerTest.cs new file mode 100644 index 000000000..e7a08d13e --- /dev/null +++ b/Adyen.Test/BalancePlatformWebhookHandlerTest.cs @@ -0,0 +1,504 @@ +// using System; +// using System.Text.Json; +// using Adyen.AcsWebhooks.Extensions; +// using Adyen.AcsWebhooks.Handlers; +// using Adyen.ConfigurationWebhooks.Client; +// using Adyen.ConfigurationWebhooks.Handlers; +// using Adyen.Model.AcsWebhooks; +// using Adyen.Model.ConfigurationWebhooks; +// using Adyen.Model.NegativeBalanceWarningWebhooks; +// using Adyen.Model.ReportWebhooks; +// using Adyen.Model.TransactionWebhooks; +// using Adyen.Webhooks; +// using Microsoft.Extensions.DependencyInjection; +// using Microsoft.Extensions.Hosting; +// using Microsoft.VisualStudio.TestTools.UnitTesting; +// using Newtonsoft.Json; +// using CapabilityProblemEntity = Adyen.Model.ConfigurationWebhooks.CapabilityProblemEntity; +// +// namespace Adyen.Test.ConfigurationWebhooks +// { +// [TestClass] +// public class ConfigurationWebhookHandlerTest +// { +// private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; +// private readonly IConfigurationWebhooksHandler _configurationWebhooksHandler; +// +// public ConfigurationWebhookHandlerTest() +// { +// IHost host = Host.CreateDefaultBuilder() +// .ConfigureAcsWebhooks((context, services, config) => +// { +// }) +// .Build(); +// +// _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); +// _configurationWebhooksHandler = host.Services.GetRequiredService(); +// } +// +// +// [TestMethod] +// +// public void Test_BalancePlatform_AccountHolderUpdated_LEM_V3() +// { +// // Note: We're using double-quotes here as some descriptions in the JSON payload contain single quotes ' +// // Assert +// const string jsonPayload = @" +// { +// ""data"": { +// ""balancePlatform"": ""YOUR_BALANCE_PLATFORM"", +// ""accountHolder"": { +// ""legalEntityId"": ""LE00000000000000000001"", +// ""reference"": ""YOUR_REFERENCE-2412C"", +// ""capabilities"": { +// ""sendToTransferInstrument"": { +// ""enabled"": true, +// ""requested"": true, +// ""allowed"": false, +// ""problems"": [ +// { +// ""entity"": { +// ""id"": ""LE00000000000000000001"", +// ""type"": ""LegalEntity"" +// }, +// ""verificationErrors"": [ +// { +// ""code"": ""2_902"", +// ""message"": ""Terms Of Service forms are not accepted."", +// ""remediatingActions"": [ +// { +// ""code"": ""2_902"", +// ""message"": ""Accept TOS"" +// } +// ], +// ""type"": ""invalidInput"" +// } +// ] +// }, +// { +// ""entity"": { +// ""id"": ""SE00000000000000000001"", +// ""type"": ""BankAccount"" +// }, +// ""verificationErrors"": [ +// { +// ""code"": ""2_8037"", +// ""message"": ""'bankStatement' was missing."", +// ""remediatingActions"": [ +// { +// ""code"": ""1_703"", +// ""message"": ""Upload a bank statement"" +// } +// ], +// ""type"": ""dataMissing"" +// } +// ] +// }, +// { +// ""entity"": { +// ""id"": ""SE00000000000000000002"", +// ""type"": ""BankAccount"" +// }, +// ""verificationErrors"": [ +// { +// ""code"": ""2_8037"", +// ""message"": ""'bankStatement' was missing."", +// ""remediatingActions"": [ +// { +// ""code"": ""1_703"", +// ""message"": ""Upload a bank statement"" +// } +// ], +// ""type"": ""dataMissing"" +// } +// ] +// }, +// { +// ""entity"": { +// ""id"": ""LE00000000000000000001"", +// ""type"": ""LegalEntity"" +// }, +// ""verificationErrors"": [ +// { +// ""code"": ""2_8189"", +// ""message"": ""'UBO through control' was missing."", +// ""remediatingActions"": [ +// { +// ""code"": ""2_151"", +// ""message"": ""Add 'organization.entityAssociations' of type 'uboThroughControl' to legal entity"" +// } +// ], +// ""type"": ""dataMissing"" +// }, +// { +// ""code"": ""1_50"", +// ""message"": ""Organization details couldn't be verified"", +// ""subErrors"": [ +// { +// ""code"": ""1_5016"", +// ""message"": ""The tax ID number couldn't be verified"", +// ""remediatingActions"": [ +// { +// ""code"": ""1_500"", +// ""message"": ""Update organization details"" +// }, +// { +// ""code"": ""1_501"", +// ""message"": ""Upload a registration document"" +// } +// ], +// ""type"": ""invalidInput"" +// } +// ], +// ""type"": ""invalidInput"" +// }, +// { +// ""code"": ""2_8067"", +// ""message"": ""'Signatory' was missing."", +// ""remediatingActions"": [ +// { +// ""code"": ""2_124"", +// ""message"": ""Add 'organization.entityAssociations' of type 'signatory' to legal entity"" +// } +// ], +// ""type"": ""dataMissing"" +// } +// ] +// } +// ], +// ""transferInstruments"": [ +// { +// ""enabled"": true, +// ""requested"": true, +// ""allowed"": false, +// ""id"": ""SE00000000000000000001"", +// ""verificationStatus"": ""pending"" +// }, +// { +// ""enabled"": true, +// ""requested"": true, +// ""allowed"": false, +// ""id"": ""SE00000000000000000002"", +// ""verificationStatus"": ""pending"" +// } +// ], +// ""verificationStatus"": ""pending"" +// } +// }, +// ""id"": ""AH00000000000000000001"", +// ""status"": ""active"" +// } +// }, +// ""environment"": ""live"", +// ""timestamp"": ""2024-12-15T15:42:03+01:00"", +// ""type"": ""balancePlatform.accountHolder.updated"" +// }"; +// +// _balancePlatformWebhookHandler.GetAccountHolderNotificationRequest(jsonPayload, out AccountHolderNotificationRequest accountHolderUpdatedWebhook); +// +// Assert.IsNotNull(accountHolderUpdatedWebhook); +// Assert.AreEqual(accountHolderUpdatedWebhook.Type, AccountHolderNotificationRequest.TypeEnum.Updated); +// Assert.AreEqual("YOUR_BALANCE_PLATFORM", accountHolderUpdatedWebhook.Data.BalancePlatform); +// Assert.AreEqual("AH00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Id); +// Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.LegalEntityId); +// Assert.AreEqual("YOUR_REFERENCE-2412C", accountHolderUpdatedWebhook.Data.AccountHolder.Reference); +// Assert.AreEqual(AccountHolder.StatusEnum.Active, accountHolderUpdatedWebhook.Data.AccountHolder.Status); +// Assert.IsTrue(accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities.TryGetValue("sendToTransferInstrument", out AccountHolderCapability capabilitiesData)); +// Assert.AreEqual(true, capabilitiesData.Enabled); +// Assert.AreEqual(true, capabilitiesData.Requested); +// Assert.AreEqual(false, capabilitiesData.Allowed); +// Assert.AreEqual(AccountHolderCapability.VerificationStatusEnum.Pending, capabilitiesData.VerificationStatus); +// Assert.AreEqual(4, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems.Count); +// Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].Entity.Id); +// Assert.AreEqual(CapabilityProblemEntity.TypeEnum.LegalEntity, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].Entity.Type); +// Assert.AreEqual("2_902", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].Code); +// Assert.AreEqual("Terms Of Service forms are not accepted.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].Message); +// Assert.AreEqual("Accept TOS", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].RemediatingActions[0].Message); +// Assert.AreEqual("SE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].Entity.Id); +// Assert.AreEqual(CapabilityProblemEntity.TypeEnum.BankAccount, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].Entity.Type); +// Assert.AreEqual("2_8037", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].Code); +// Assert.AreEqual("'bankStatement' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].Message); +// Assert.AreEqual("Upload a bank statement", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].RemediatingActions[0].Message); +// Assert.AreEqual("SE00000000000000000002", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].Entity.Id); +// Assert.AreEqual(CapabilityProblemEntity.TypeEnum.BankAccount, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].Entity.Type); +// Assert.AreEqual("2_8037", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].Code); +// Assert.AreEqual("'bankStatement' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].Message); +// Assert.AreEqual("Upload a bank statement", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].RemediatingActions[0].Message); +// Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].Entity.Id); +// Assert.AreEqual(CapabilityProblemEntity.TypeEnum.LegalEntity, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].Entity.Type); +// Assert.AreEqual("2_8189", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].Code); +// Assert.AreEqual("'UBO through control' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].Message); +// Assert.AreEqual("Add 'organization.entityAssociations' of type 'uboThroughControl' to legal entity", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].RemediatingActions[0].Message); +// Assert.AreEqual("live", accountHolderUpdatedWebhook.Environment); +// Assert.AreEqual(DateTime.Parse("2024-12-15T15:42:03+01:00"), accountHolderUpdatedWebhook.Timestamp); +// } +// +// [TestMethod] +// public void Test_POC_Integration() +// { +// string jsonPayload = @" +// { +// 'data': { +// 'balancePlatform': 'YOUR_BALANCE_PLATFORM', +// 'accountHolder': { +// 'contactDetails': { +// 'address': { +// 'country': 'NL', +// 'houseNumberOrName': '274', +// 'postalCode': '1020CD', +// 'street': 'Brannan Street' +// }, +// 'email': 's.hopper@example.com', +// 'phone': { +// 'number': '+315551231234', +// 'type': 'Mobile' +// } +// }, +// 'description': 'S.Hopper - Staff 123', +// 'id': 'AH00000000000000000000001', +// 'status': 'Active' +// } +// }, +// 'environment': 'test', +// 'type': 'balancePlatform.accountHolder.created' +// }"; +// +// var handler = new BalancePlatformWebhookHandler(); +// var response = handler.GetGenericBalancePlatformWebhook(jsonPayload); +// try +// { +// if (response.GetType() == typeof(AccountHolderNotificationRequest)) +// { +// var accountHolderNotificationRequest = (AccountHolderNotificationRequest)response; +// Assert.AreEqual(accountHolderNotificationRequest.Environment, "test"); +// } +// +// if (response.GetType() == typeof(BalanceAccountNotificationRequest)) +// { +// var balanceAccountNotificationRequest = (BalanceAccountNotificationRequest)response; +// Assert.Fail(balanceAccountNotificationRequest.Data.BalancePlatform); +// } +// } +// catch (System.Exception e) +// { +// Assert.Fail(); +// throw new System.Exception(e.ToString()); +// } +// } +// +// [TestMethod] +// public void Test_TransactionWebhook_V4() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'data': { +// 'id': 'EVJN42272224222B5JB8BRC84N686ZEUR', +// 'amount': { +// 'value': 7000, +// 'currency': 'EUR' +// }, +// 'status': 'booked', +// 'transfer': { +// 'id': 'JN4227222422265', +// 'reference': 'Split_item_1', +// }, +// 'valueDate': '2023-03-01T00:00:00+02:00', +// 'bookingDate': '2023-02-28T13:30:20+02:00', +// 'creationDate': '2023-02-28T13:30:05+02:00', +// 'accountHolder': { +// 'id': 'AH00000000000000000000001', +// 'description': 'Your description for the account holder', +// 'reference': 'Your reference for the account holder' +// }, +// 'balanceAccount': { +// 'id': 'BA00000000000000000000001', +// 'description': 'Your description for the balance account', +// 'reference': 'Your reference for the balance account' +// }, +// 'balancePlatform': 'YOUR_BALANCE_PLATFORM' +// }, +// 'type': 'balancePlatform.transaction.created', +// 'environment': 'test' +// }"; +// Assert.IsFalse(_balancePlatformWebhookHandler.GetPaymentNotificationRequest(jsonPayload, out var _)); +// +// // Act +// _balancePlatformWebhookHandler.GetTransactionNotificationRequestV4(jsonPayload, out TransactionNotificationRequestV4 target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(TransactionNotificationRequestV4.TypeEnum.BalancePlatformTransactionCreated, target.Type); +// Assert.AreEqual(Transaction.StatusEnum.Booked, target.Data.Status); +// Assert.AreEqual("BA00000000000000000000001", target.Data.BalanceAccount.Id); +// Assert.IsTrue(target.Data.ValueDate.Equals(DateTime.Parse("2023-03-01T00:00:00+02:00"))); +// Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); +// Assert.AreEqual("AH00000000000000000000001", target.Data.AccountHolder.Id); +// Assert.AreEqual("Your description for the account holder", target.Data.AccountHolder.Description); +// Assert.AreEqual("Your reference for the account holder", target.Data.AccountHolder.Reference); +// Assert.AreEqual("JN4227222422265", target.Data.Transfer.Id); +// Assert.AreEqual("Split_item_1", target.Data.Transfer.Reference); +// Assert.AreEqual(DateTime.Parse("2023-02-28T13:30:05+02:00"), target.Data.CreationDate); +// Assert.AreEqual(DateTime.Parse("2023-02-28T13:30:20+02:00"), target.Data.BookingDate); +// Assert.AreEqual(7000, target.Data.Amount.Value); +// Assert.AreEqual("EUR", target.Data.Amount.Currency); +// Assert.AreEqual("test", target.Environment); +// } +// +// [TestMethod] +// public void Test_ReportCreatedWebhook() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'data': { +// 'balancePlatform': 'YOUR_BALANCE_PLATFORM', +// 'creationDate': '2024-07-02T02:01:08+02:00', +// 'id': 'balanceplatform_accounting_report_2024_07_01.csv', +// 'downloadUrl': 'https://balanceplatform-test.adyen.com/balanceplatform/.../.../.../balanceplatform_accounting_report_2024_07_01.csv', +// 'fileName': 'balanceplatform_accounting_report_2024_07_01.csv', +// 'reportType': 'balanceplatform_accounting_report' +// }, +// 'environment': 'test', +// 'timestamp': '2024-07-02T02:01:05+02:00', +// 'type': 'balancePlatform.report.created' +// }"; +// +// // Act +// _balancePlatformWebhookHandler.GetReportNotificationRequest(jsonPayload, out ReportNotificationRequest target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(target.Type, ReportNotificationRequest.TypeEnum.BalancePlatformReportCreated); +// Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); +// Assert.AreEqual("balanceplatform_accounting_report_2024_07_01.csv", target.Data.Id); +// Assert.AreEqual("balanceplatform_accounting_report_2024_07_01.csv", target.Data.FileName); +// Assert.AreEqual("balanceplatform_accounting_report", target.Data.ReportType); +// Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:08+02:00"), target.Data.CreationDate); +// Assert.AreEqual("https://balanceplatform-test.adyen.com/balanceplatform/.../.../.../balanceplatform_accounting_report_2024_07_01.csv", target.Data.DownloadUrl); +// Assert.AreEqual("test", target.Environment); +// Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:05+02:00"), target.Timestamp); +// } +// +// [TestMethod] +// public void Test_AuthenticationCreatedWebhook() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'data': { +// 'authentication': { +// 'acsTransId': '6a4c1709-a42e-4c7f-96c7-1043adacfc97', +// 'challenge': { +// 'flow': 'OOB_TRIGGER_FL', +// 'lastInteraction': '2022-12-22T15:49:03+01:00' +// }, +// 'challengeIndicator': '01', +// 'createdAt': '2022-12-22T15:45:03+01:00', +// 'deviceChannel': 'app', +// 'dsTransID': 'a3b86754-444d-46ca-95a2-ada351d3f42c', +// 'exemptionIndicator': 'lowValue', +// 'inPSD2Scope': true, +// 'messageCategory': 'payment', +// 'messageVersion': '2.2.0', +// 'riskScore': 0, +// 'threeDSServerTransID': '6edcc246-23ee-4e94-ac5d-8ae620bea7d9', +// 'transStatus': 'Y', +// 'type': 'challenge' +// }, +// 'balancePlatform': 'YOUR_BALANCE_PLATFORM', +// 'id': '497f6eca-6276-4993-bfeb-53cbbbba6f08', +// 'paymentInstrumentId': 'PI3227C223222B5BPCMFXD2XG', +// 'purchase': { +// 'date': '2022-12-22T15:49:03+01:00', +// 'merchantName': 'MyShop', +// 'originalAmount': { +// 'currency': 'EUR', +// 'value': 1000 +// } +// }, +// 'status': 'authenticated' +// }, +// 'environment': 'test', +// 'timestamp': '2022-12-22T15:42:03+01:00', +// 'type': 'balancePlatform.authentication.created' +// }"; +// +// // Act +// _balancePlatformWebhookHandler.GetAuthenticationNotificationRequest(jsonPayload, out AuthenticationNotificationRequest target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(target.Type, AuthenticationNotificationRequest.TypeEnum.BalancePlatformAuthenticationCreated); +// Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); +// Assert.AreEqual("497f6eca-6276-4993-bfeb-53cbbbba6f08", target.Data.Id); +// Assert.AreEqual("PI3227C223222B5BPCMFXD2XG", target.Data.PaymentInstrumentId); +// Assert.AreEqual(AuthenticationNotificationData.StatusEnum.Authenticated, target.Data.Status); +// Assert.AreEqual("MyShop", target.Data.Purchase.MerchantName); +// Assert.AreEqual("2022-12-22T15:49:03+01:00", target.Data.Purchase.Date); +// Assert.AreEqual("EUR", target.Data.Purchase.OriginalAmount.Currency); +// Assert.AreEqual(1000, target.Data.Purchase.OriginalAmount.Value); +// Assert.AreEqual(DateTime.Parse("2022-12-22T15:45:03+01:00"), target.Data.Authentication.CreatedAt); +// Assert.AreEqual(AuthenticationInfo.DeviceChannelEnum.App, target.Data.Authentication.DeviceChannel); +// Assert.AreEqual(ChallengeInfo.FlowEnum.OOBTRIGGERFL, target.Data.Authentication.Challenge.Flow); +// Assert.AreEqual(DateTime.Parse("2022-12-22T15:49:03+01:00"), target.Data.Authentication.Challenge.LastInteraction); +// Assert.AreEqual(AuthenticationInfo.ChallengeIndicatorEnum._01, target.Data.Authentication.ChallengeIndicator); +// Assert.AreEqual(AuthenticationInfo.ExemptionIndicatorEnum.LowValue, target.Data.Authentication.ExemptionIndicator); +// Assert.AreEqual(true, target.Data.Authentication.InPSD2Scope); +// Assert.AreEqual(AuthenticationInfo.MessageCategoryEnum.Payment, target.Data.Authentication.MessageCategory); +// Assert.AreEqual("2.2.0", target.Data.Authentication.MessageVersion); +// Assert.AreEqual(0, target.Data.Authentication.RiskScore); +// Assert.AreEqual("6edcc246-23ee-4e94-ac5d-8ae620bea7d9", target.Data.Authentication.ThreeDSServerTransID); +// Assert.AreEqual(AuthenticationInfo.TransStatusEnum.Y, target.Data.Authentication.TransStatus); +// Assert.AreEqual("test", target.Environment); +// Assert.AreEqual(DateTime.Parse("2022-12-22T15:42:03+01:00"), target.Timestamp); +// } +// +// [TestMethod] +// public void Test_NegativeBalanceCompensationWarningWebhook() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'data': { +// 'balancePlatform': 'YOUR_BALANCE_PLATFORM', +// 'creationDate': '2024-07-02T02:01:08+02:00', +// 'id': 'BA00000000000000000001', +// 'accountHolder': { +// 'description': 'Description for the account holder.', +// 'reference': 'YOUR_REFERENCE', +// 'id': 'AH00000000000000000001' +// }, +// 'amount': { +// 'currency': 'EUR', +// 'value': -145050 +// }, +// 'liableBalanceAccountId': 'BA11111111111111111111', +// 'negativeBalanceSince': '2024-10-19T00:33:13+02:00', +// 'scheduledCompensationAt': '2024-12-01T01:00:00+01:00' +// }, +// 'environment': 'test', +// 'timestamp': '2024-10-22T00:00:00+02:00', +// 'type': 'balancePlatform.negativeBalanceCompensationWarning.scheduled' +// }"; +// +// // Act +// _balancePlatformWebhookHandler.GetNegativeBalanceCompensationWarningNotificationRequest(jsonPayload, out NegativeBalanceCompensationWarningNotificationRequest target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(NegativeBalanceCompensationWarningNotificationRequest.TypeEnum.BalancePlatformNegativeBalanceCompensationWarningScheduled, target.Type); +// Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); +// Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:08+02:00"), target.Data.CreationDate); +// Assert.AreEqual("BA00000000000000000001", target.Data.Id); +// Assert.AreEqual("YOUR_REFERENCE", target.Data.AccountHolder.Reference); +// Assert.AreEqual("EUR", target.Data.Amount.Currency); +// Assert.AreEqual(-145050, target.Data.Amount.Value); +// Assert.AreEqual("BA11111111111111111111", target.Data.LiableBalanceAccountId); +// Assert.AreEqual(DateTime.Parse("2024-10-19T00:33:13+02:00"), target.Data.NegativeBalanceSince); +// Assert.AreEqual(DateTime.Parse("2024-12-01T01:00:00+01:00"), target.Data.ScheduledCompensationAt); +// Assert.AreEqual("test", target.Environment); +// Assert.AreEqual(DateTime.Parse("2024-10-22T00:00:00+02:00"), target.Timestamp); +// } +// } +// } \ No newline at end of file diff --git a/Adyen.Test/BinLookup/BinLookupTest.cs b/Adyen.Test/BinLookup/BinLookupTest.cs new file mode 100644 index 000000000..335b68430 --- /dev/null +++ b/Adyen.Test/BinLookup/BinLookupTest.cs @@ -0,0 +1,82 @@ +using System.Text.Json; +using Adyen.BinLookup.Client; +using Adyen.BinLookup.Extensions; +using Adyen.BinLookup.Models; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.BinLookup +{ + [TestClass] + public class BinLookupTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public BinLookupTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureBinLookup((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_ThreeDSAvailabilityResponse_Result_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/binlookup/get3dsavailability-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("F013371337", response.DsPublicKeys[0].DirectoryServerId); + Assert.AreEqual("visa", response.DsPublicKeys[0].Brand); + Assert.AreEqual("411111111111", response.ThreeDS2CardRangeDetails[0].StartRange); + Assert.AreEqual("411111111111", response.ThreeDS2CardRangeDetails[0].EndRange); + Assert.AreEqual("2.1.0", response.ThreeDS2CardRangeDetails[0].ThreeDS2Versions.FirstOrDefault()); + Assert.AreEqual("https://pal-test.adyen.com/threeds2simulator/acs/startMethod.shtml", response.ThreeDS2CardRangeDetails[0].ThreeDSMethodURL); + Assert.IsTrue(response.ThreeDS1Supported); + Assert.IsTrue(response.ThreeDS2supported); + } + + [TestMethod] + public async Task Given_Deserialize_When_CostEstimateResponse_Result_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/binlookup/getcostestimate-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("1111", response.CardBin.Summary); + Assert.AreEqual("Unsupported", response.ResultCode); + } + + [TestMethod] + public async Task Given_Serialize_When_CostEstimateRequest_ShopperInteractionEnums_Result_Should_Return_Correct_String() + { + // Arrange + // Act + string ecommerce = JsonSerializer.Serialize(CostEstimateRequest.ShopperInteractionEnum.Ecommerce, _jsonSerializerOptionsProvider.Options); + string contAuth = JsonSerializer.Serialize(CostEstimateRequest.ShopperInteractionEnum.ContAuth, _jsonSerializerOptionsProvider.Options); + string moto = JsonSerializer.Serialize(CostEstimateRequest.ShopperInteractionEnum.Moto, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(@"""Ecommerce""", ecommerce); + Assert.AreEqual(@"""ContAuth""", contAuth); + Assert.AreEqual(@"""Moto""", moto); + } + } +} diff --git a/Adyen.Test/BinLookupTest.cs b/Adyen.Test/BinLookupTest.cs deleted file mode 100644 index 59d8e4bc8..000000000 --- a/Adyen.Test/BinLookupTest.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Linq; -using Adyen.Model.BinLookup; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class BinLookupTest : BaseTest - { - [TestMethod] - public void Get3dsAvailabilitySuccessMockedTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/binlookup/get3dsavailability-success.json"); - var binLookup = new BinLookupService(client); - var threeDsAvailabilityRequest = new ThreeDSAvailabilityRequest - { - MerchantAccount = "merchantAccount", - CardNumber = "4111111111111111" - }; - var threeDsAvailabilityResponse = binLookup.Get3dsAvailability(threeDsAvailabilityRequest); - Assert.AreEqual("F013371337", threeDsAvailabilityResponse.DsPublicKeys[0].DirectoryServerId); - Assert.AreEqual("visa", threeDsAvailabilityResponse.DsPublicKeys[0].Brand); - Assert.AreEqual("411111111111", threeDsAvailabilityResponse.ThreeDS2CardRangeDetails[0].StartRange); - Assert.AreEqual("411111111111", threeDsAvailabilityResponse.ThreeDS2CardRangeDetails[0].EndRange); - Assert.AreEqual("2.1.0", threeDsAvailabilityResponse.ThreeDS2CardRangeDetails[0].ThreeDS2Versions.FirstOrDefault()); - Assert.AreEqual("https://pal-test.adyen.com/threeds2simulator/acs/startMethod.shtml", threeDsAvailabilityResponse.ThreeDS2CardRangeDetails[0].ThreeDSMethodURL); - Assert.AreEqual(true, threeDsAvailabilityResponse.ThreeDS1Supported); - Assert.AreEqual(true, threeDsAvailabilityResponse.ThreeDS2supported); - } - - [TestMethod] - public void GetCostEstimateSuccessMockedTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/binlookup/getcostestimate-success.json"); - var binLookup = new BinLookupService(client); - var costEstimateRequest = new CostEstimateRequest(); - var amount = new Amount - { - Currency = "EUR", - Value = 1000 - }; - costEstimateRequest.Amount = amount; - var costEstimateAssumptions = new CostEstimateAssumptions - { - AssumeLevel3Data = true, - Assume3DSecureAuthenticated = true - }; - costEstimateRequest.Assumptions = costEstimateAssumptions; - costEstimateRequest.CardNumber = "4111111111111111"; - costEstimateRequest.MerchantAccount = "merchantAccount"; - var merchantDetails = new MerchantDetails - { - CountryCode = "NL", - Mcc = "7411", - EnrolledIn3DSecure = true - }; - costEstimateRequest.MerchantDetails = (merchantDetails); - costEstimateRequest.ShopperInteraction = CostEstimateRequest.ShopperInteractionEnum.Ecommerce; - var costEstimateResponse = binLookup.GetCostEstimate(costEstimateRequest); - Assert.AreEqual("1111", costEstimateResponse.CardBin.Summary); - Assert.AreEqual("Unsupported", costEstimateResponse.ResultCode); - } - - [TestMethod] - public void GetCostEstimateSuccessGenerateShopperInteractionFromEnum() - { - var ecommerce = Util.JsonOperation.SerializeRequest(CostEstimateRequest.ShopperInteractionEnum.Ecommerce); - var contAuth = Util.JsonOperation.SerializeRequest(CostEstimateRequest.ShopperInteractionEnum.ContAuth); - var moto = Util.JsonOperation.SerializeRequest(CostEstimateRequest.ShopperInteractionEnum.Moto); - Assert.AreEqual("\"Ecommerce\"", ecommerce); - Assert.AreEqual("\"ContAuth\"", contAuth); - Assert.AreEqual("\"Moto\"", moto); - } - } -} diff --git a/Adyen.Test/Checkout/ApiTokenTest.cs b/Adyen.Test/Checkout/ApiTokenTest.cs new file mode 100644 index 000000000..fe586c60b --- /dev/null +++ b/Adyen.Test/Checkout/ApiTokenTest.cs @@ -0,0 +1,53 @@ +using Adyen.Checkout.Extensions; +using Adyen.BalancePlatform.Extensions; +using Adyen.Core.Auth; +using Adyen.Core.Options; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class ApiKeyTokenTest + { + [TestMethod] + public async Task Given_Multiple_Api_Tokens_When_Injected_Then_Correct_TokenProvider_Is_Used_To_Provide_Correct_ApiKeyToken() + { + // Arrange + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "adyen-api-key"; + options.Environment = AdyenEnvironment.Test; + }); + }) + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "balanceplatform-adyen-api-key"; + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + // Act + ITokenProvider balancePlatformApiKey = testHost.Services.GetRequiredService>(); + ITokenProvider checkoutApiKey = testHost.Services.GetRequiredService>(); + + using var balancePlatformMessage = new HttpRequestMessage(HttpMethod.Get, "/dummy/endpoint"); + balancePlatformApiKey.Get().AddTokenToHttpRequestMessageHeader(balancePlatformMessage); + + using var checkoutMessage = new HttpRequestMessage(HttpMethod.Get, "/dummy/endpoint"); + checkoutApiKey.Get().AddTokenToHttpRequestMessageHeader(checkoutMessage); + + // Assert + Assert.AreEqual(balancePlatformMessage.Headers.First().Value.First(), "balanceplatform-adyen-api-key"); + Assert.AreEqual(checkoutMessage.Headers.First().Value.First(), "adyen-api-key"); + } + + } +} \ No newline at end of file diff --git a/Adyen.Test/Checkout/CheckoutTest.cs b/Adyen.Test/Checkout/CheckoutTest.cs new file mode 100644 index 000000000..ece797cef --- /dev/null +++ b/Adyen.Test/Checkout/CheckoutTest.cs @@ -0,0 +1,457 @@ +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class CheckoutTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public CheckoutTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public void Given_Deserialize_When_Payment_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payments-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("8535296650153317", response.PspReference); + Assert.AreEqual(PaymentResponse.ResultCodeEnum.Authorised, response.ResultCode); + Assert.IsNotNull(response.AdditionalData); + Assert.AreEqual(9, response.AdditionalData.Count); + Assert.AreEqual("8/2018", response.AdditionalData["expiryDate"]); + Assert.AreEqual("GREEN", response.AdditionalData["fraudResultType"]); + Assert.AreEqual("411111", response.AdditionalData["cardBin"]); + Assert.AreEqual("1111", response.AdditionalData["cardSummary"]); + Assert.AreEqual("false", response.AdditionalData["fraudManualReview"]); + Assert.AreEqual("Default", response.AdditionalData["aliasType"]); + Assert.AreEqual("H167852639363479", response.AdditionalData["alias"]); + Assert.AreEqual("visa", response.AdditionalData["cardPaymentMethod"]); + Assert.AreEqual("NL", response.AdditionalData["cardIssuingCountry"]); + } + + [TestMethod] + public void Given_Deserialize_When_Payment3DS2_CheckoutThreeDS2Action_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payments-3DS2-IdentifyShopper.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentResponse.ResultCodeEnum.IdentifyShopper, response.ResultCode); + Assert.AreEqual("threeDS2", response.Action.CheckoutThreeDS2Action.Type.ToString()); + Assert.IsNotNull(response.Action.CheckoutThreeDS2Action.PaymentData); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentError_Result_ServiceError_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payments-error-invalid-data-422.json"); + + // Act + var serviceErrorResponse = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNull(serviceErrorResponse.PspReference); + Assert.AreEqual("Reference Missing", serviceErrorResponse.Message); + Assert.AreEqual("validation", serviceErrorResponse.ErrorType); + Assert.AreEqual("130", serviceErrorResponse.ErrorCode); + Assert.AreEqual(422, serviceErrorResponse.Status); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentDetailsResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentsdetails-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("8515232733321252", response.PspReference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentDetailsActionResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentsdetails-action-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("8515232733321252", response.PspReference); + Assert.AreEqual(PaymentDetailsResponse.ResultCodeEnum.Authorised, response.ResultCode); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentMethods_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentmethods-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.PaymentMethods.Count, 32); + Assert.IsNotNull(response.PaymentMethods[12].Issuers); + Assert.AreEqual(response.PaymentMethods[12].Issuers[0].Id, "66"); + Assert.AreEqual(response.PaymentMethods[12].Issuers[0].Name, "Bank Nowy BFG S.A."); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentMethods__Result_Brands_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentmethods-brands-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(7, response.PaymentMethods.Count); + Assert.AreEqual(5, response.PaymentMethods[0].Brands.Count); + Assert.AreEqual("visa", response.PaymentMethods[0].Brands[0]); + Assert.AreEqual("mc", response.PaymentMethods[0].Brands[1]); + Assert.AreEqual("amex", response.PaymentMethods[0].Brands[2]); + Assert.AreEqual("bcmc", response.PaymentMethods[0].Brands[3]); + Assert.AreEqual("maestro", response.PaymentMethods[0].Brands[4]); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentMethods_Result_Without_Brands_Is_Exactly_50() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentmethods-without-brands-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.PaymentMethods.Count, 50); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentLinks_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payment-links-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("your-id", response.Id); + Assert.AreEqual(PaymentLinkResponse.StatusEnum.Active, response.Status); + Assert.AreEqual("https://checkoutshopper-test.adyen.com/checkoutshopper/payByLink.shtml?d=YW1vdW50TWlub3JW...JRA", response.Url); + Assert.AreEqual(new DateTimeOffset(2019, 12, 17, 10, 05, 29, TimeSpan.Zero), response.ExpiresAt); + Assert.AreEqual("YOUR_ORDER_NUMBER", response.Reference); + Assert.AreEqual(1250, response.Amount.Value); + Assert.AreEqual("BRL", response.Amount.Currency); + } + + [TestMethod] + public void Given_Deserialize_When_Payments_PayPal_Result_CheckoutSDKAction_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payments-success-paypal.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response.Action.CheckoutSDKAction); + Assert.AreEqual("EC-42N19135GM6949000", response.Action.CheckoutSDKAction.SdkData["orderID"]); + Assert.AreEqual("Ab02b4c0!BQABAgARb1TvUJa4nwS0Z1nOmxoYfD9+z...", response.Action.CheckoutSDKAction.PaymentData); + Assert.AreEqual("paypal", response.Action.CheckoutSDKAction.PaymentMethodType); + } + + [TestMethod] + public void Given_Deserialize_When_ApplePayDetails_Result_Is_Not_Null() + { + // Arrange + string json = "{\"type\": \"applepay\",\"applePayToken\": \"VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...\"}"; + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual( ApplePayDetails.TypeEnum.Applepay, response.Type); + Assert.AreEqual("VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...", response.ApplePayToken); + } + + [TestMethod] + public void Given_Deserialize_When_ApplePayDetails_With_Unknown_Value_Result_Is_Not_Null() + { + // Arrange + string json = "{\"type\": \"applepay\",\"someValue\": \"notInSpec\",\"applePayToken\": \"VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...\"}"; + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(ApplePayDetails.TypeEnum.Applepay, response.Type); + Assert.AreEqual("VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...", response.ApplePayToken); + } + + [TestMethod] + public void Given_Deserialize_When_PayWithGoogleDetails_Returns_Not_Null() + { + // Arrange + string json = "{\"type\": \"paywithgoogle\",\"someValue\": \"notInSpec\",\"googlePayToken\": \"==Payload as retrieved from Google Pay response==\"}"; + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PayWithGoogleDetails.TypeEnum.Paywithgoogle, response.Type); + Assert.AreEqual(response.GooglePayToken, "==Payload as retrieved from Google Pay response=="); + } + + [TestMethod] + public void Given_Deserialize_When_BlikCode_Result_Is_Not_Null() + { + // Arrange + string json = "{\"type\":\"blik\",\"blikCode\":\"blikCode\"}"; + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(BlikDetails.TypeEnum.Blik, response.Type); + Assert.AreEqual("blikCode", response.BlikCode); + } + + [TestMethod] + public void Given_Deserialize_When_DragonpayDetails_Result_Is_Not_Null() + { + // Arrange + string json = "{\"issuer\":\"issuer\",\"shopperEmail\":\"test@adyen.com\",\"type\":\"dragonpay_ebanking\"}"; + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(DragonpayDetails.TypeEnum.DragonpayEbanking, result.Type); + Assert.AreEqual("issuer", result.Issuer); + Assert.AreEqual("test@adyen.com", result.ShopperEmail); + } + + [TestMethod] + public void Given_Deserialize_When_AfterPayDetails_Result_Is_Not_Null() + { + // Arrange + string json = @" +{ + ""resultCode"":""RedirectShopper"", + ""action"":{ + ""paymentMethodType"":""afterpaytouch"", + ""method"":""GET"", + ""url"":""https://checkoutshopper-test.adyen.com/checkoutshopper/checkoutPaymentRedirect?redirectData=..."", + ""type"":""redirect"" + } +}"; + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentResponse.ResultCodeEnum.RedirectShopper, result.ResultCode); + Assert.AreEqual("afterpaytouch", result.Action.CheckoutRedirectAction.PaymentMethodType); + Assert.AreEqual(CheckoutRedirectAction.TypeEnum.Redirect, result.Action.CheckoutRedirectAction.Type); + Assert.AreEqual("https://checkoutshopper-test.adyen.com/checkoutshopper/checkoutPaymentRedirect?redirectData=...", result.Action.CheckoutRedirectAction.Url); + Assert.AreEqual("GET", result.Action.CheckoutRedirectAction.Method); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResponse_3DS_ChallengeShopper_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentResponse-3DS-ChallengeShopper.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(CheckoutThreeDS2Action.TypeEnum.ThreeDS2, response.Action.CheckoutThreeDS2Action.Type); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentMethodsResponse_StoredPaymentMethods_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentmethods-storedpaymentmethods.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(4, response.StoredPaymentMethods.Count); + Assert.AreEqual("NL32ABNA0515071439", response.StoredPaymentMethods[0].Iban); + Assert.AreEqual("Adyen", response.StoredPaymentMethods[0].OwnerName); + Assert.AreEqual("sepadirectdebit", response.StoredPaymentMethods[0].Type); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResponse_3DS2_IdentifyShopper_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentResponse-3DS2-Action.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentResponse.ResultCodeEnum.IdentifyShopper, response.ResultCode); + Assert.AreEqual(CheckoutThreeDS2Action.TypeEnum.ThreeDS2, response.Action.CheckoutThreeDS2Action.Type); + } + + [TestMethod] + public void Given_Serialize_When_CheckoutSessionRequest_Result_Contains_DateOnly_And_DateTimeOffset() + { + // Arrange + CreateCheckoutSessionRequest checkoutSessionRequest = new CreateCheckoutSessionRequest( + merchantAccount: "TestMerchant", + reference: "TestReference", + returnUrl: "http://test-url.com", + amount: new Amount("EUR", 10000L), + dateOfBirth: new DateOnly(1998, 1, 1), + expiresAt: new DateTimeOffset(2023, 4, 1, 1, 1, 1, TimeSpan.Zero) + ); + + // Act + string target = JsonSerializer.Serialize(checkoutSessionRequest, _jsonSerializerOptionsProvider.Options); + + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + + Assert.AreEqual("TestMerchant", root.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("TestReference", root.GetProperty("reference").GetString()); + Assert.AreEqual("http://test-url.com", root.GetProperty("returnUrl").GetString()); + Assert.AreEqual("1998-01-01", root.GetProperty("dateOfBirth").GetString()); + Assert.AreEqual("2023-04-01T01:01:01.0000000+00:00", root.GetProperty("expiresAt").GetString()); + // does not serialise null fields + Assert.IsFalse(target.Contains(":null")); + Assert.IsFalse(target.Contains("threeDSAuthenticationOnly")); + } + + [TestMethod] + public void Given_Serialize_When_CheckoutSessionRequest_Is_Filled_Result_Returns_No_Null_Values() + { + // Arrange + CreateCheckoutSessionRequest checkoutSessionRequest = new CreateCheckoutSessionRequest( + merchantAccount: "TestMerchant", + reference: "TestReference", + returnUrl: "http://test-url.com", + amount: new Amount("EUR", 10000L), + dateOfBirth: new DateOnly(1998, 1, 1), + expiresAt: new DateTimeOffset(2023, 4, 1, 1, 1, 1, TimeSpan.Zero) + ); + + // Act + string target = JsonSerializer.Serialize(checkoutSessionRequest, _jsonSerializerOptionsProvider.Options); + + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + + // Ensure that no elements contain null + foreach (JsonProperty property in root.EnumerateObject()) + { + Assert.AreNotEqual(JsonValueKind.Null, property.Value.ValueKind, $"Property {property.Name} is null"); + } + } + + [TestMethod] + public void Given_Deserialize_When_PaymentMethodsBalance_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/paymentmethods-balance-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(BalanceCheckResponse.ResultCodeEnum.Success, response.ResultCode); + Assert.AreEqual("EUR", response.Balance.Currency); + Assert.AreEqual("2500", response.Balance.Value.ToString()); + } + + [TestMethod] + public void Given_Deserialize_When_CreateOrderResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/orders-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(CreateOrderResponse.ResultCodeEnum.Success, response.ResultCode); + Assert.AreEqual("8515930288670953", response.PspReference); + Assert.AreEqual("Ab02b4c0!BQABAgBqxSuFhuXUF7IvIRvSw5bDPHN...", response.OrderData); + Assert.AreEqual("EUR", response.RemainingAmount.Currency); + Assert.AreEqual("2500", response.RemainingAmount.Value.ToString()); + } + + [TestMethod] + public void Given_Deserialize_When_CancelOrderResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/orders-cancel-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("Received", response.ResultCode.ToString()); + Assert.AreEqual("8515931182066678", response.PspReference); + } + + [TestMethod] + public void Given_Deserialize_When_GetStoredPaymentMethods_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/get-storedPaymentMethod-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("string", response.StoredPaymentMethods[0].Type); + Assert.AreEqual("merchantAccount", response.MerchantAccount); + } + } +} diff --git a/Adyen.Test/Checkout/DonationsTest.cs b/Adyen.Test/Checkout/DonationsTest.cs new file mode 100644 index 000000000..41cc3398f --- /dev/null +++ b/Adyen.Test/Checkout/DonationsTest.cs @@ -0,0 +1,46 @@ +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class DonationsTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public DonationsTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public void Given_Deserialize_When_Donations_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/donations-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(DonationPaymentResponse.StatusEnum.Completed, response.Status); + Assert.AreEqual("10720de4-7c5d-4a17-9161-fa4abdcaa5c4", response.Reference); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Checkout/ModificationTest.cs b/Adyen.Test/Checkout/ModificationTest.cs new file mode 100644 index 000000000..15b30d7de --- /dev/null +++ b/Adyen.Test/Checkout/ModificationTest.cs @@ -0,0 +1,116 @@ +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class ModificationTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public ModificationTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentCaptureResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/captures-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentCaptureResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("my_reference", response.Reference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentCancelResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/cancels-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentCancelResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("my_reference", response.Reference); + } + + [TestMethod] + public void Given_Deserialize_When_StandalonePaymentCancelResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/standalone-cancels-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(StandalonePaymentCancelResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("861633338418518C", response.PspReference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentRefundResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/refunds-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentRefundResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("my_reference", response.Reference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentReversalResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/reversals-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentReversalResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("my_reference", response.Reference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentAmountUpdateResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/reversals-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentAmountUpdateResponse.StatusEnum.Received, response.Status); + Assert.AreEqual("my_reference", response.Reference); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Checkout/PaymentsTest.cs b/Adyen.Test/Checkout/PaymentsTest.cs new file mode 100644 index 000000000..e4a13e62c --- /dev/null +++ b/Adyen.Test/Checkout/PaymentsTest.cs @@ -0,0 +1,642 @@ +using System.Net; +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; +using Adyen.Checkout.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Client; +using NSubstitute; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class PaymentsTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly IPaymentsService _paymentsService; + + public PaymentsTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _paymentsService = Substitute.For(); + } + + [TestMethod] + public async Task Given_PaymentMethodsResponse_When_Deserialized_Then_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payment-methods-response.json"); + // Act + PaymentMethodsResponse result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result.PaymentMethods); + Assert.IsNull(result.StoredPaymentMethods); + Assert.AreEqual(29, result.PaymentMethods.Count); + } + + [TestMethod] + public async Task Given_CreateCheckoutSessionRequest_When_Serialize_Long__Result_Contains_Zeros() + { + // Arrange + CreateCheckoutSessionRequest checkoutSessionRequest = new CreateCheckoutSessionRequest( + amount: new Amount("EUR", 10000L), + merchantAccount: "merchantAccount", + reference: "TestReference", + returnUrl: "http://test-url.com", + channel: CreateCheckoutSessionRequest.ChannelEnum.Web, + countryCode: "NL", + lineItems: new List() { + new LineItem(quantity: 1, amountIncludingTax: 5000, description: "description1", amountExcludingTax: 0), + new LineItem(quantity: 1, amountIncludingTax: 5000, description: "description2", taxAmount: 0) + } + ); + + // Act + string result = JsonSerializer.Serialize(checkoutSessionRequest, _jsonSerializerOptionsProvider.Options); + + // Assert + using JsonDocument json = JsonDocument.Parse(result); + JsonElement lineItems = json.RootElement.GetProperty("lineItems"); + + lineItems[0].TryGetProperty("amountExcludingTax", out JsonElement amountExcludingTax); + lineItems[1].TryGetProperty("taxAmount", out JsonElement taxAmount); + + Assert.AreEqual(0, amountExcludingTax.GetInt32()); + Assert.AreEqual(0, taxAmount.GetInt32()); + } + + [TestMethod] + public async Task Given_CreateCheckoutSessionResponse_When_Deserialize_Returns_Not_Null() + { + // Arrange + string json = @"{""mode"": ""embedded"",""amount"": {""currency"": ""EUR"",""value"": 10000},""expiresAt"": ""2023-04-06T17:11:15+02:00"",""id"": ""CS0068299CB8DA273A"",""merchantAccount"": ""TestMerchantAccount"",""reference"": ""TestReference"",""returnUrl"": ""http://test-url.com"",""sessionData"": ""Ab02b4c0!BQABAgBoacRJuRbNM/typUKATopkZ3V+cINm0WTAvwl9uQJ2e8I00P2KFemlwp4nb1bOqqYh1zx48gDAHt0QDs2JTiQIqDQRizqopLFRk/wAJHFoCuam/GvOHflg9vwS3caHbkBToIolxcYcJoJheIN9o1fGmNIHZb9VrWfiKsXMgmYsSUifenayS2tkKCTquF7vguaAwk7q5ES1GDwzP/J2mChJGH04jGrVL4szPHGmznr897wIcFQyBSZe4Uifqoe0fpiIxZLNWadLMya6SnvQYNAQL1V6ti+7F4wHHyLwHWTCua993sttue70TE4918EV80HcAWx0LE1+uW6J5KBHCKdYNi9ESlGSZreRwLCpdNbmumB6MlyHZlz2umLiw0ZZJAEpdrwXA2NiyHzJDKDKfbAhd8uoTSACrbgwbrAXI1cvb1WjiOQjLn9MVW++fuJCq6vIeX+rUKMeltBAHMeBZyC54ndAucw9nS03uyckjphunE4tl4WTT475VkfUiyJCTT3S2IOVYS9V9M8pMQ1/GlDVNCLBJJfrYlVXoC8VX68QW1HERkhNYQbTgLQ9kI3cDeMP5d4TuUL3XR2Q6sNiOMdIPGDYQ9QFKFdOE3OQ5X9wxUYbX6j88wR2gRGJcS5agqFHOR1ZTNrjumOYrEkjL8ehFXEs/KluhURllfi0POUPGAwlUWBjDCZcKaeeR0kASnsia2V5IjoiQUYwQUFBMTAzQ0E1MzdFQUVEODdDMjRERDUzOTA5QjgwQTc4QTkyM0UzODIzRDY4REFDQzk0QjlGRjgzMDVEQyJ9E0Gs1T0RaO7NluuXP59fegcW6SQKq4BhC3ZzEKPm1vJuwAJ2gZUaicaXbRPW3IyadavKRlfGdFeAYt2B3ik8fGiK3ZkKU0CrZ0qL0IO5rrWrOg74HMnpxRAn1RhAHRHfGEk67FFPNjr0aLBJXSia7xZWiyKA+i4QU63roY2sxMI/q41mvJjRUz0rPKT3SbVDt1Of7K7BP8cmiboBkWexFBD/mkJyMOpYAOoFp/tKOUHTWZYcc1GpbyV1jInXVfEUhHROYCtS4p/xwF6DdT3bI0+HRU35/xNBTZH2yJN55u9i42Vb0ddCyhzOLZYQ3JVgglty6hLgVeQzuN4b2MoalhfTl11HsElJT1kB0mznVX8CL7UMTUp/2uSgL8DN6kB4owEZ45nWRxIR/2sCidMJ1tnSI1uSqkeqXRf1vat5qPq+BzpYE0Urn2ZZEmgJyb2u0ZLn2x1tfJyPtv+hqBoT7iqJ224dSbuB4HMT49YtcheUtR0jnrImJXm+M1TeIjWB3XWOScrNV8sWEJMAiIU="",""shopperLocale"": ""en-US""}"; + + // Act + CreateCheckoutSessionResponse response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(response.Id); + } + + [TestMethod] + public async Task Given_Serialize_When_DeviceRenderOptions_Returns_MultiSelect_And_OtherHtml() + { + // Arrange + DeviceRenderOptions deviceRenderOptions = new DeviceRenderOptions + { + SdkInterface = DeviceRenderOptions.SdkInterfaceEnum.Native, + SdkUiType = new List() + { + DeviceRenderOptions.SdkUiTypeEnum.MultiSelect, + DeviceRenderOptions.SdkUiTypeEnum.OtherHtml + } + }; + + // Act + string result = JsonSerializer.Serialize(deviceRenderOptions, _jsonSerializerOptionsProvider.Options); + + // Assert + using JsonDocument json = JsonDocument.Parse(result); + JsonElement root = json.RootElement; + + JsonElement sdkInterface = root.GetProperty("sdkInterface"); + Assert.AreEqual("native", sdkInterface.GetString()); + + JsonElement sdkUiTypes = root.GetProperty("sdkUiType"); + Assert.AreEqual("multiSelect", sdkUiTypes[0].GetString()); + Assert.AreEqual("otherHtml", sdkUiTypes[1].GetString()); + } + + [TestMethod] + public async Task Given_Byte_Array_When_Serialize_Returns_Not_Null() + { + // Arrange + byte[] plainTextBytes = Encoding.ASCII.GetBytes("Bytes-To-Be-Encoded"); + string base64String = System.Convert.ToBase64String(plainTextBytes); + byte[] base64Bytes = Encoding.ASCII.GetBytes(base64String); + var threeDSecure = new ThreeDSecureData + { + Cavv = base64Bytes, + Xid = base64Bytes + }; + + // Act + string jsonRequest = JsonSerializer.Serialize(threeDSecure, _jsonSerializerOptionsProvider.Options); + + // Assert + string json = "{\"cavv\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\",\"xid\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\"}"; + Assert.AreEqual(json, jsonRequest); + } + + [TestMethod] + public async Task Given_Byte_Array_When_Deserialize_Result_ThreeDSecureData_Should_Deserialize_Correctly() + { + // Arrange + string json = "{\"cavv\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\",\"xid\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\"}"; + + // Act + ThreeDSecureData jsonRequest = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + string xid = Encoding.ASCII.GetString(jsonRequest.Xid); + string cavv = Encoding.ASCII.GetString(jsonRequest.Cavv); + string jsonElementBase64 = "Qnl0ZXMtVG8tQmUtRW5jb2RlZA=="; + Assert.AreEqual(jsonElementBase64, xid); + Assert.AreEqual(jsonElementBase64, cavv); + } + + [TestMethod] + public async Task Given_ConfigureCheckout_When_Timeout_Is_Provided_Then_Timeout_Is_Set() + { + // Arrange + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }, client => + { + client.Timeout = TimeSpan.FromSeconds(42); + }) + .Build(); + + // Act + var httpClient = testHost.Services.GetService().HttpClient; + + // Assert + Assert.AreEqual(httpClient.Timeout, TimeSpan.FromSeconds(42)); + } + + [TestMethod] + public async Task Given_Empty_ConfigureCheckout_When_No_AdyenOptions_Provided_Then_IPaymentService_Should_Throw_InvalidOperationException() + { + // Arrange + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + // Empty + }) + .Build(); + + // Act + // Assert + Assert.Throws(() => + { + // No ApiKey provided, cannot instantiate the ApiKeyToken object + testHost.Services.GetRequiredService(); + }); + } + + [TestMethod] + public async Task Given_IPaymentsService_When_Live_Url_And_Prefix_Are_Set_Returns_Correct_Live_Url_Endpoint_And_No_Prefix() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "your-live-api-key"; + options.Environment = AdyenEnvironment.Live; + options.LiveEndpointUrlPrefix = "prefix"; + }); + }) + .Build(); + + // Act + var paymentsService = liveHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://prefix-checkout-live.adyenpayments.com/checkout/v71", paymentsService.HttpClient.BaseAddress.ToString()); + } + + [TestMethod] + public async Task Given_IPaymentsService_When_Test_Url_Returns_Correct_Test_Url_Endpoint_And_No_Prefix() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + // Act + var paymentsService = liveHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://checkout-test.adyen.com/v71", paymentsService.HttpClient.BaseAddress.ToString()); + } + + [TestMethod] + public async Task Given_IPaymentsService_When_Live_Url_And_Prefix_Not_Set_Throws_InvalidOperationException() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.AdyenApiKey = "your-live-api-key"; + options.Environment = AdyenEnvironment.Live; + }); + }) + .Build(); + + // Act + // Assert + Assert.ThrowsException(() => + { + liveHost.Services.GetRequiredService(); + }); + } + + [TestMethod] + public async Task Given_ConfigureCheckout_When_Live_Url_And_Prefix_Not_Set_Throws_InvalidOperationException() + { + // Arrange + IHost liveHost = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Live; + }); + }) + .Build(); + + // Act + // Assert + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + + Assert.Throws(() => + liveHost.Services.GetRequiredService() + ); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentRequest_AccountInfo_Is_Set_To_Null_Explicitly_Result_Is_Null() + { + // Arrange + var cardDetails = new CardDetails + { + Type = CardDetails.TypeEnum.Card + }; + + var accountInfoNullObject = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), reference: "ACH test", + paymentMethod: new CheckoutPaymentMethod(cardDetails), + shopperIP: "192.0.2.1", + channel: PaymentRequest.ChannelEnum.Web, origin: "https://your-company.com", + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy..", + accountInfo: null // Set `AccountInfo` explicitly to null + ); + + + var accountInfoNotPresentObject = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), reference: "ACH test", + paymentMethod: new CheckoutPaymentMethod(cardDetails), + shopperIP: "192.0.2.1", + channel: PaymentRequest.ChannelEnum.Web, origin: "https://your-company.com", + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy.." + //accountInfo: ... // AccountInfo (key) is not present + ); + + // Act + string accountInfoNullSerializedObject = JsonSerializer.Serialize(accountInfoNullObject, _jsonSerializerOptionsProvider.Options); + string accountInfoNotPresentSerializedObject = JsonSerializer.Serialize(accountInfoNotPresentObject, _jsonSerializerOptionsProvider.Options); + using var accountInfoNull = JsonDocument.Parse(accountInfoNullSerializedObject); + using var accountInfoNotPresent = JsonDocument.Parse(accountInfoNotPresentSerializedObject); + + // Assert + // AccountInfo is set, so the key `accountInfo` should have the value of { "accountInfo": null } + Assert.AreEqual(null, accountInfoNull.RootElement.GetProperty("accountInfo").GetString()); + + // AccountInfo is not set, so the key `accountInfo` should not be present in the serialized result. + Assert.IsFalse(accountInfoNotPresent.RootElement.TryGetProperty("accountInfo", out _)); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_AchDetails_Result_Is_Not_Null() + { + // Arrange + var achDetails = new AchDetails + { + Type = AchDetails.TypeEnum.Ach, + BankAccountNumber = "1234567", + BankLocationId = "1234567", + EncryptedBankAccountNumber = "1234asdfg", + OwnerName = "John Smith" + }; + + var paymentRequest = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), reference: "ACH test", + paymentMethod: new CheckoutPaymentMethod(achDetails), + shopperIP: "192.0.2.1", + channel: PaymentRequest.ChannelEnum.Web, origin: "https://your-company.com", + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy.." + ); + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + Assert.AreEqual("ach", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("type").GetString()); + Assert.AreEqual("1234567", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("bankAccountNumber").GetString()); + Assert.AreEqual("1234567", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("bankLocationId").GetString()); + Assert.AreEqual("1234asdfg", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("encryptedBankAccountNumber").GetString()); + Assert.AreEqual("John Smith", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("ownerName").GetString()); + + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("ACH test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_ApplePayDetails_Result_Is_Not_Null() + { + // Arrange + var applePay = new ApplePayDetails( + type: ApplePayDetails.TypeEnum.Applepay, + applePayToken: "VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU..." + ); + + var paymentRequest = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), + reference: "apple pay test", + paymentMethod: new CheckoutPaymentMethod(applePay), + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy.." + ); + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + Assert.AreEqual("applepay", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("type").GetString()); + Assert.AreEqual("VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("applePayToken").GetString()); + + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("apple pay test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_GooglePayDetails_Result_Is_Not_Null() + { + // Arrange + var paymentRequest = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), + reference: "google pay test", + paymentMethod: new CheckoutPaymentMethod( + new GooglePayDetails( + type: GooglePayDetails.TypeEnum.Googlepay, + googlePayToken: "==Payload as retrieved from Google Pay response==", + fundingSource: GooglePayDetails.FundingSourceEnum.Debit + ) + ), + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy.."); + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + Assert.AreEqual("googlepay", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("type").GetString()); + Assert.AreEqual("==Payload as retrieved from Google Pay response==", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("googlePayToken").GetString()); + Assert.AreEqual("debit", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("fundingSource").GetString()); + + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("google pay test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_iDEAL_Result_Is_Not_Null() + { + // Arrange + var paymentRequest = new PaymentRequest( + merchantAccount: "YOUR_MERCHANT_ACCOUNT", + amount: new Amount("EUR", 1000), + reference: "ideal test", + paymentMethod: new CheckoutPaymentMethod(new IdealDetails( + type: IdealDetails.TypeEnum.Ideal, + issuer: "1121") + ), + returnUrl: "https://your-company.com/checkout?shopperOrder=12xy.."); + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + Assert.AreEqual("ideal", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("type").GetString()); + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("ideal test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + Assert.IsFalse(jsonDoc.RootElement.TryGetProperty("accountInfo", out _)); // null + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_BacsDirectDebitDetails_Result_Is_Not_Null() + { + // Arrange + var paymentRequest = new PaymentRequest + { + MerchantAccount = "YOUR_MERCHANT_ACCOUNT", + Amount = new Amount("GBP", 1000), + Reference = "bacs direct debit test", + PaymentMethod = new CheckoutPaymentMethod(new BacsDirectDebitDetails + { + Type = BacsDirectDebitDetails.TypeEnum.DirectdebitGB, + BankAccountNumber = "NL0123456789", + BankLocationId = "121000358", + HolderName = "John Smith" + }), + ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." + }; + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + JsonElement element = jsonDoc.RootElement.GetProperty("paymentMethod"); + Assert.AreEqual("directdebit_GB", element.GetProperty("type").GetString()); + Assert.AreEqual("NL0123456789", element.GetProperty("bankAccountNumber").GetString()); + Assert.AreEqual("121000358", element.GetProperty("bankLocationId").GetString()); + Assert.AreEqual("John Smith", element.GetProperty("holderName").GetString()); + + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("bacs direct debit test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_PayPalDetails_Result_Is_Not_Null() + { + // Arrange + var paymentRequest = new PaymentRequest + { + MerchantAccount = "YOUR_MERCHANT_ACCOUNT", + Amount = new Amount("USD", 1000), + Reference = "paypal test", + PaymentMethod = new CheckoutPaymentMethod(new PayPalDetails + { + Type = PayPalDetails.TypeEnum.Paypal, + Subtype = PayPalDetails.SubtypeEnum.Sdk, + StoredPaymentMethodId = "2345654212345432345" + }), + ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." + }; + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + JsonElement element = jsonDoc.RootElement.GetProperty("paymentMethod"); + + Assert.AreEqual("paypal", element.GetProperty("type").GetString()); + Assert.AreEqual("sdk", element.GetProperty("subtype").GetString()); + } + + [TestMethod] + public async Task Given_Serialize_When_PaymentMethod_Is_ZipDetails_Result_Is_Not_Null() + { + // Arrange + var paymentRequest = new PaymentRequest + { + MerchantAccount = "YOUR_MERCHANT_ACCOUNT", + Amount = new Amount("USD", 1000), + Reference = "zip test", + PaymentMethod = new CheckoutPaymentMethod(new ZipDetails + { + Type = ZipDetails.TypeEnum.Zip + }), + ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy..", + }; + + // Act + string serialized = JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptionsProvider.Options); + using var jsonDoc = JsonDocument.Parse(serialized); + + // Assert + Assert.AreEqual("zip", jsonDoc.RootElement.GetProperty("paymentMethod").GetProperty("type").GetString()); + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT", jsonDoc.RootElement.GetProperty("merchantAccount").GetString()); + Assert.AreEqual("zip test", jsonDoc.RootElement.GetProperty("reference").GetString()); + Assert.AreEqual("https://your-company.com/checkout?shopperOrder=12xy..", jsonDoc.RootElement.GetProperty("returnUrl").GetString()); + } + + // test oneOf deserialization in CheckoutPaymentRequest + [TestMethod] + public async Task Given_Deserialize_When_PaymentRequest_OneOf_Then_Result_Is_PaymentRequestIdeal() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/payment-request-ideal.json"); + + // Act + PaymentRequest result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Act + Assert.IsNotNull(result.PaymentMethod); + Assert.IsNotNull(result.PaymentMethod.IdealDetails); + Assert.AreEqual(IdealDetails.TypeEnum.Ideal, result.PaymentMethod.IdealDetails.Type); + } + + [TestMethod] + public async Task SessionsAsyncTest() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/sessions-success.json"); + + var createCheckoutSessionRequest = new CreateCheckoutSessionRequest( + amount: new Amount("EUR", 10000L), + merchantAccount: "TestMerchantAccount", + reference: "TestReference", + returnUrl: "http://test-url.com", + channel: CreateCheckoutSessionRequest.ChannelEnum.Web, + countryCode: "NL" + ); + + _paymentsService.SessionsAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PaymentsService.SessionsApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.Created }, + json, + "/sessions", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + ISessionsApiResponse response = await _paymentsService.SessionsAsync(createCheckoutSessionRequest, new RequestOptions().AddIdempotencyKey("idempotencyKey")); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); + Assert.IsTrue(response.IsCreated); + CreateCheckoutSessionResponse sessionResponse = response.Created(); + Assert.IsNotNull(sessionResponse); + Assert.AreEqual("CS0068299CB8DA273A", sessionResponse.Id); + } + + } + +} \ No newline at end of file diff --git a/Adyen.Test/Checkout/UtilityServiceTest.cs b/Adyen.Test/Checkout/UtilityServiceTest.cs new file mode 100644 index 000000000..b4aca2758 --- /dev/null +++ b/Adyen.Test/Checkout/UtilityServiceTest.cs @@ -0,0 +1,79 @@ +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Models; +using Adyen.Checkout.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using Adyen.Core.Options; +using System.Text.Json; + +namespace Adyen.Test.Checkout +{ + [TestClass] + public class UtilityServiceTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public UtilityServiceTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_UtilityResponse_For_OriginKeys_Returns_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkoututility/originkeys-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4xLmNvbQ.UEwIBmW9-c_uXo5wSEr2w8Hz8hVIpujXPHjpcEse3xI", response.OriginKeys["https://www.your-domain1.com"]); + } + + [TestMethod] + public void Given_Deserialize_When_CardDetailsResponse_Returns_Not_Null() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/checkout/card-details-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsFalse(response.IsCardCommercial); + Assert.AreEqual("CREDIT", response.FundingSource); + Assert.AreEqual("FR", response.IssuingCountryCode); + + Assert.AreEqual("visa", response.Brands[0].Type); + Assert.IsTrue(response.Brands[0].Supported); + + Assert.AreEqual("cartebancaire", response.Brands[1].Type); + Assert.IsFalse(response.Brands[1].Supported); + } + + [TestMethod] + public void Given_Deserialize_When_ApplePaySessionResponse_Result_Is_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/checkout/apple-pay-sessions-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("eyJ2Z...340278gdflkaswer", response.Data); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/CheckoutTest.cs b/Adyen.Test/CheckoutTest.cs deleted file mode 100644 index ccdb78961..000000000 --- a/Adyen.Test/CheckoutTest.cs +++ /dev/null @@ -1,1090 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Adyen.HttpClient.Interfaces; -using Adyen.Model; -using Adyen.Model.Checkout; -using Adyen.Service.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NSubstitute; -using static Adyen.Model.Checkout.PaymentResponse; -using ApplicationInfo = Adyen.Model.ApplicationInformation.ApplicationInfo; -using Environment = Adyen.Model.Environment; -using IRecurringService = Adyen.Service.Checkout.IRecurringService; -using RecurringService = Adyen.Service.Checkout.RecurringService; - -namespace Adyen.Test -{ - [TestClass] - public class CheckoutTest : BaseTest - { - /// - /// Tests successful checkout client Test URL generation. - /// - [TestMethod] - public void CheckoutEndpointTestEnvironmentSuccessTest() - { - var client = CreateMockForAdyenClientTest(new Config()); - client.SetEnvironment(Environment.Test, "companyUrl"); - var checkout = new PaymentsService(client); - checkout.PaymentsAsync(new PaymentRequest()).GetAwaiter(); - - ClientInterfaceSubstitute.Received().RequestAsync("https://checkout-test.adyen.com/v71/payments", - Arg.Any(), null, new HttpMethod("POST"), default); - } - - /// - /// Tests successful checkout client Live URL generation. - /// - [TestMethod] - public void CheckoutEndpointLiveEnvironmentSuccessTest() - { - var client = CreateMockForAdyenClientTest(new Config()); - client.SetEnvironment(Environment.Live, "companyUrl"); - var checkout = new PaymentsService(client); - checkout.PaymentsAsync(new PaymentRequest()).GetAwaiter(); - - ClientInterfaceSubstitute.Received().RequestAsync( - "https://companyUrl-checkout-live.adyenpayments.com/checkout/v71/payments", - Arg.Any(), null, new HttpMethod("POST"), Arg.Any()); - } - - /// - /// Tests unsuccessful checkout client Live URL generation. - /// - [TestMethod] - public void CheckoutEndpointLiveErrorTest() - { - var config = new Config(); - var client = new Client(config); - client.SetEnvironment(Environment.Live, null); - Assert.ThrowsException(() => new PaymentsService(client)); - } - - /// - /// Tests unsuccessful checkout client Live URL generation. - /// - [TestMethod] - public void CheckoutEndpointLiveWithBasicAuthErrorTest() - { - var client = new Client(new Config() - { - Username = "ws_*******", - Password = "*******", - Environment = Environment.Live - - }); - Assert.ThrowsException( - () => new PaymentsService(client)); - } - - /// - /// Tests successful checkout client Live URL generation with basic auth. - /// - [TestMethod] - public void CheckoutEndpointLiveWithBasicAuthTest() - { - var client = CreateMockForAdyenClientTest( - new Config - { - Username = "ws_*******", - Password = "******", - Environment = Environment.Live, - LiveEndpointUrlPrefix = "live-url" - }); - var checkout = new PaymentsService(client); - checkout.PaymentsAsync(new PaymentRequest()).GetAwaiter(); - ClientInterfaceSubstitute.Received().RequestAsync("https://live-url-checkout-live.adyenpayments.com/checkout/v71/payments", - Arg.Any(), null, new HttpMethod("POST"), default); - } - - /// - /// Tests successful checkout client Live URL generation with API key. - /// - [TestMethod] - public void CheckoutEndpointLiveWithAPIKeyTest() - { - var client = CreateMockForAdyenClientTest( - new Config - { - XApiKey = "xapikey", - Environment = Environment.Live, - LiveEndpointUrlPrefix = "live-url" - }); - var checkout = new PaymentsService(client); - checkout.PaymentsAsync(new PaymentRequest()).GetAwaiter(); - ClientInterfaceSubstitute.Received().RequestAsync("https://live-url-checkout-live.adyenpayments.com/checkout/v71/payments", - Arg.Any(), null, new HttpMethod("POST"), Arg.Any()); - } - - /// - /// Test success flow for - /// POST /payments - /// - [TestMethod] - public void PaymentsAdditionalDataParsingTest() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payments-success.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.Payments(paymentRequest); - Assert.AreEqual("8535296650153317", paymentResponse.PspReference); - Assert.AreEqual(ResultCodeEnum.Authorised, paymentResponse.ResultCode); - Assert.IsNotNull(paymentResponse.AdditionalData); - Assert.AreEqual(9, paymentResponse.AdditionalData.Count); - Assert.AreEqual("8/2018", paymentResponse.AdditionalData["expiryDate"]); - Assert.AreEqual("GREEN", paymentResponse.AdditionalData["fraudResultType"]); - Assert.AreEqual("411111", paymentResponse.AdditionalData["cardBin"]); - Assert.AreEqual("1111", paymentResponse.AdditionalData["cardSummary"]); - Assert.AreEqual("false", paymentResponse.AdditionalData["fraudManualReview"]); - Assert.AreEqual("Default", paymentResponse.AdditionalData["aliasType"]); - Assert.AreEqual("H167852639363479", paymentResponse.AdditionalData["alias"]); - Assert.AreEqual("visa", paymentResponse.AdditionalData["cardPaymentMethod"]); - Assert.AreEqual("NL", paymentResponse.AdditionalData["cardIssuingCountry"]); - } - - /// - /// Test success flow for async - /// POST /payments - /// - [TestMethod] - public async Task PaymentsAsyncAdditionalDataParsingTest() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payments-success.json"); - var checkout = new PaymentsService(client); - var paymentResponse = await checkout.PaymentsAsync(paymentRequest); - Assert.AreEqual("8535296650153317", paymentResponse.PspReference); - Assert.AreEqual(ResultCodeEnum.Authorised, paymentResponse.ResultCode); - Assert.IsNotNull(paymentResponse.AdditionalData); - Assert.AreEqual(9, paymentResponse.AdditionalData.Count); - Assert.AreEqual("8/2018", paymentResponse.AdditionalData["expiryDate"]); - Assert.AreEqual("GREEN", paymentResponse.AdditionalData["fraudResultType"]); - Assert.AreEqual("411111", paymentResponse.AdditionalData["cardBin"]); - Assert.AreEqual("1111", paymentResponse.AdditionalData["cardSummary"]); - Assert.AreEqual("false", paymentResponse.AdditionalData["fraudManualReview"]); - Assert.AreEqual("Default", paymentResponse.AdditionalData["aliasType"]); - Assert.AreEqual("H167852639363479", paymentResponse.AdditionalData["alias"]); - Assert.AreEqual("visa", paymentResponse.AdditionalData["cardPaymentMethod"]); - Assert.AreEqual("NL", paymentResponse.AdditionalData["cardIssuingCountry"]); - } - - /// - /// Test success flow for 3DS2 - /// POST /payments - /// - [TestMethod] - public void Payments3DS2Test() - { - var payment3DS2Request = CreatePaymentRequest3DS2(); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payments-3DS2-IdentifyShopper.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.Payments(payment3DS2Request); - Assert.AreEqual(paymentResponse.ResultCode, ResultCodeEnum.IdentifyShopper); - Assert.AreEqual(paymentResponse.Action.GetCheckoutThreeDS2Action().Type.ToString(), "ThreeDS2"); - Assert.IsNotNull(paymentResponse.Action.GetCheckoutThreeDS2Action().PaymentData); - } - - /// - /// Test error flow for - /// POST /payments - /// - [TestMethod] - public void PaymentsErrorTest() - { - var paymentMethodsRequest = CreatePaymentRequestCheckout(); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payments-error-invalid-data-422.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.Payments(paymentMethodsRequest); - Assert.IsNull(paymentResponse.PspReference); - } - - /// - /// Test success flow for - /// POST /payments/details - /// - [TestMethod] - public void PaymentDetailsTest() - { - var detailsRequest = CreateDetailsRequest(); - detailsRequest.Details = - new PaymentCompletionDetails( - payload: "Ab02b4c0!BQABAgBQn96RxfJHpp2RXhqQBuhQFWgE...gfGHb4IZSP4IpoCC2==RXhqQBuhQ"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentsdetails-success.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.PaymentsDetails(detailsRequest); - Assert.AreEqual("8515232733321252", paymentResponse.PspReference); - } - - /// - /// Test success flow for async - /// POST /payments/details - /// - [TestMethod] - public async Task PaymentDetailsAsyncTest() - { - var detailsRequest = CreateDetailsRequest(); - detailsRequest.Details = - new PaymentCompletionDetails( - payload: "Ab02b4c0!BQABAgBQn96RxfJHpp2RXhqQBuhQFWgE...gfGHb4IZSP4IpoCC2==RXhqQBuhQ"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentsdetails-success.json"); - var checkout = new PaymentsService(client); - var paymentResponse = await checkout.PaymentsDetailsAsync(detailsRequest); - Assert.AreEqual("8515232733321252", paymentResponse.PspReference); - } - - /// - /// Test error flow for - /// POST /payments/details - /// - [TestMethod] - public void PaymentDetailsErrorTest() - { - var detailsRequest = CreateDetailsRequest(); - detailsRequest.Details = - new PaymentCompletionDetails( - payload: "Ab02b4c0!BQABAgBQn96RxfJHpp2RXhqQBuhQFWgE...gfGHb4IZSP4IpoCC2==RXhqQBuhQ"); - var client = - CreateMockTestClientApiKeyBasedRequestAsync( - "mocks/checkout/paymentsdetails-error-invalid-data-422.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.PaymentsDetails(detailsRequest); - Assert.IsNull(paymentResponse.ResultCode); - } - - /// - /// Test success deserialization for - /// POST /payments/details - /// - [TestMethod] - public void PaymentDetailsResponseDeserializeTest() - { - var detailsRequest = CreateDetailsRequest(); - detailsRequest.Details = - new PaymentCompletionDetails( - payload: "Ab02b4c0!BQABAgBQn96RxfJHpp2RXhqQBuhQFWgE...gfGHb4IZSP4IpoCC2==RXhqQBuhQ"); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentsdetails-action-success.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.PaymentsDetails(detailsRequest); - Assert.AreEqual(paymentResponse.PspReference, "8515232733321252"); - Assert.AreEqual(paymentResponse.ResultCode, PaymentDetailsResponse.ResultCodeEnum.Authorised); - } - - /// - /// Test success flow for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-success.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods.Count, 32); - } - - /// - /// Test success flow for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsIssuersTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-success.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.IsNotNull(paymentMethodsResponse.PaymentMethods[12].Issuers); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[12].Issuers[0].Id, "66"); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[12].Issuers[0].Name, "Bank Nowy BFG S.A."); - } - - /// - /// Test success flow for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsStoreValueTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - paymentMethodsRequest.Store = "MerchantStore"; - Assert.AreEqual(paymentMethodsRequest.Store, "MerchantStore"); - } - - /// - /// Test success flow for async - /// POST /paymentMethods - /// - [TestMethod] - public async Task PaymentMethodsAsyncTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-success.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = await checkout.PaymentMethodsAsync(paymentMethodsRequest); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods.Count, 32); - } - - /// - /// Test error flow for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsErrorTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-error-forbidden-403.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.IsNull(paymentMethodsResponse.PaymentMethods); - } - - /// - /// Test success flow including brands check for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsWithBrandsTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-brands-success.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods.Count, 7); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands.Count, 5); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands[0], "visa"); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands[1], "mc"); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands[2], "amex"); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands[3], "bcmc"); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods[0].Brands[4], "maestro"); - } - - /// - /// Test flow without including brands check for - /// POST /paymentMethods - /// - [TestMethod] - public void PaymentMethodsWithoutBrandsTest() - { - var paymentMethodsRequest = CreatePaymentMethodRequest("YourMerchantAccount"); - var client = - CreateMockTestClientApiKeyBasedRequestAsync( - "mocks/checkout/paymentmethods-without-brands-success.json"); - var checkout = new PaymentsService(client); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.AreEqual(paymentMethodsResponse.PaymentMethods.Count, 50); - } - - [TestMethod] - public void ApplicationInfoTest() - { - ApplicationInfo applicationInfo = new ApplicationInfo(); - Assert.AreEqual(applicationInfo.AdyenLibrary.Name, Constants.ClientConfig.LibName); - Assert.AreEqual(applicationInfo.AdyenLibrary.Version, Constants.ClientConfig.LibVersion); - } - - [Ignore] // The adyen library info will not be added anymore by default, let's investigate if we should. - [TestMethod] - public void PaymentRequestApplicationInfoTest() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var name = paymentRequest.ApplicationInfo.AdyenLibrary.Name; - var version = paymentRequest.ApplicationInfo.AdyenLibrary.Version; - Assert.AreEqual(version, Constants.ClientConfig.LibVersion); - Assert.AreEqual(name, Constants.ClientConfig.LibName); - } - - [TestMethod] - public void PaymentRequestAppInfoExternalTest() - { - var externalPlatform = new ExternalPlatform(); - var merchantApplication = new CommonField(); - externalPlatform.Integrator = "TestExternalPlatformIntegration"; - externalPlatform.Name = "TestExternalPlatformName"; - externalPlatform.Version = "TestExternalPlatformVersion"; - merchantApplication.Name = "MerchantApplicationName"; - merchantApplication.Version = "MerchantApplicationVersion"; - var paymentRequest = CreatePaymentRequestCheckout(); - paymentRequest.ApplicationInfo = new Model.Checkout.ApplicationInfo - { - ExternalPlatform = externalPlatform, - MerchantApplication = merchantApplication - }; - Assert.AreEqual(paymentRequest.ApplicationInfo.ExternalPlatform.Integrator, - "TestExternalPlatformIntegration"); - Assert.AreEqual(paymentRequest.ApplicationInfo.ExternalPlatform.Name, "TestExternalPlatformName"); - Assert.AreEqual(paymentRequest.ApplicationInfo.ExternalPlatform.Version, "TestExternalPlatformVersion"); - Assert.AreEqual(paymentRequest.ApplicationInfo.MerchantApplication.Name, "MerchantApplicationName"); - Assert.AreEqual(paymentRequest.ApplicationInfo.MerchantApplication.Version, "MerchantApplicationVersion"); - } - - - [TestMethod] - public void PaymentsOriginTest() - { - var paymentMethodsRequest = CreatePaymentRequestCheckout(); - paymentMethodsRequest.Origin = "https://localhost:8080"; - Assert.AreEqual(paymentMethodsRequest.Origin, "https://localhost:8080"); - } - - /// - /// Test CreatePaymentLinkRequest - /// POST /payments/result - /// - [TestMethod] - public void CreatePaymentLinkSuccess() - { - var createPaymentLinkRequest = new PaymentLinkRequest(store: "TheDemoStore", - amount: new Amount(currency: "EUR", 1000), merchantAccount: "MerchantAccount", reference: "reference"); - Assert.AreEqual(createPaymentLinkRequest.Store, "TheDemoStore"); - } - - /// - /// Test success flow for - /// POST /payments/result - /// - [TestMethod] - public void PaymentLinksSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payment-links-success.json"); - var checkout = new PaymentLinksService(client); - var createPaymentLinkRequest = new PaymentLinkRequest(amount: new Amount(currency: "EUR", 1000), - merchantAccount: "MerchantAccount", reference: "YOUR_ORDER_NUMBER"); - var paymentLinksResponse = checkout.PaymentLinks(createPaymentLinkRequest); - Assert.AreEqual(paymentLinksResponse.Url, - "https://checkoutshopper-test.adyen.com/checkoutshopper/payByLink.shtml?d=YW1vdW50TWlub3JW...JRA"); - Assert.AreEqual(paymentLinksResponse.ExpiresAt, new DateTime(2019,12,17,10,05,29)); - Assert.AreEqual(paymentLinksResponse.Reference, "YOUR_ORDER_NUMBER"); - Assert.IsNotNull(paymentLinksResponse.Amount); - } - - /// - /// Test success flow for creation of a payment link with recurring payment - /// POST /paymentLinks - /// - [TestMethod] - public void CreateRecurringPaymentLinkSuccessTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync( - "mocks/checkout/paymentlinks-recurring-payment-success.json"); - var checkout = new PaymentLinksService(client); - - var createPaymentLinkRequest = new PaymentLinkRequest(amount: new Amount(currency: "EUR", 100), - merchantAccount: "MerchantAccount", reference: "REFERENCE_NUMBER") - { - CountryCode = "GR", - ShopperLocale = "GR", - ShopperReference = "ShopperReference", - StorePaymentMethodMode = PaymentLinkRequest.StorePaymentMethodModeEnum.Enabled, - RecurringProcessingModel = PaymentLinkRequest.RecurringProcessingModelEnum.Subscription - }; - - var paymentLinksResponse = checkout.PaymentLinks(createPaymentLinkRequest); - - Assert.AreEqual(createPaymentLinkRequest.Reference, paymentLinksResponse.Reference); - Assert.AreEqual( - "https://checkoutshopper-test.adyen.com/checkoutshopper/payByLink.shtml?d=YW1vdW50TWlub3JW...JRA", - paymentLinksResponse.Url); - Assert.AreEqual(createPaymentLinkRequest.Amount.Currency, paymentLinksResponse.Amount.Currency); - Assert.AreEqual(createPaymentLinkRequest.Amount.Value, paymentLinksResponse.Amount.Value); - } - - /// - /// Test success flow for multibanco - /// Post /payments - /// - [Ignore] - [TestMethod] - public void MultibancoPaymentSuccessMockedTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentsresult-multibanco-success.json"); - var checkout = new PaymentsService(client); - var paymentRequest = CreatePaymentRequestCheckout(); - var paymentResponse = checkout.Payments(paymentRequest); - var paymentResponseAction = paymentResponse.Action.GetCheckoutVoucherAction(); - Assert.AreEqual(paymentResponseAction.PaymentMethodType, "multibanco"); - Assert.AreEqual(paymentResponseAction.ExpiresAt, "01/12/2020 09:37:49"); - Assert.AreEqual(paymentResponseAction.Reference, "501 422 944"); - Assert.AreEqual(paymentResponseAction.Entity, "12101"); - } - - /// - /// Test RiskData - Clientdata flow for - /// POST /payments - /// - [TestMethod] - public void PaymentClientdataParsingTest() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var riskdata = new RiskData - { - ClientData = "IOfW3k9G2PvXFu2j" - }; - paymentRequest.RiskData = riskdata; - Assert.AreEqual(paymentRequest.RiskData.ClientData, "IOfW3k9G2PvXFu2j"); - } - - /// - /// Test success flow for paypal - /// Post /payments - /// - [TestMethod] - public void PaypalPaymentSuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/payments-success-paypal.json"); - var checkout = new PaymentsService(client); - var paymentRequest = CreatePaymentRequestCheckout(); - var paymentResponse = checkout.Payments(paymentRequest); - var result = paymentResponse.Action.GetCheckoutSDKAction(); - Assert.IsNotNull(result); - Assert.AreEqual("EC-42N19135GM6949000", result.SdkData["orderID"]); - Assert.AreEqual("Ab02b4c0!BQABAgARb1TvUJa4nwS0Z1nOmxoYfD9+z...", result.PaymentData); - Assert.AreEqual("paypal", result.PaymentMethodType); - } - - [TestMethod] - public void ApplePayDetailsDeserializationTest() - { - var json = "{\"type\": \"applepay\",\"applePayToken\": \"VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...\"}"; - var result = CheckoutPaymentMethod.FromJson(json); - Assert.IsInstanceOfType(result.ActualInstance); - Assert.AreEqual(result.GetApplePayDetails().Type, ApplePayDetails.TypeEnum.Applepay); - } - - [TestMethod] - public void CheckoutPaymentMethodDeserializationWithUnknownValuesTest() - { - var json = "{\"type\": \"applepay\",\"someValue\": \"notInSpec\",\"applePayToken\": \"VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU...\"}"; - var result = CheckoutPaymentMethod.FromJson(json); - var json2 = "{\"type\": \"paywithgoogle\",\"someValue\": \"notInSpec\",\"googlePayToken\": \"==Payload as retrieved from Google Pay response==\"}"; - var result2 = CheckoutPaymentMethod.FromJson(json2); - Assert.IsInstanceOfType(result.ActualInstance); - Assert.IsInstanceOfType(result2.ActualInstance); - Assert.AreEqual(result2.GetPayWithGoogleDetails().GooglePayToken, "==Payload as retrieved from Google Pay response=="); - } - - [TestMethod] - public void BlikDetailsDeserializationTest() - { - var json = "{\"type\":\"blik\",\"blikCode\":\"blikCode\"}"; - var result = JsonConvert.DeserializeObject(json); - Assert.IsInstanceOfType(result); - Assert.AreEqual(result.Type, BlikDetails.TypeEnum.Blik); - } - - [TestMethod] - public void DragonpayDetailsDeserializationTest() - { - var json = - "{\"issuer\":\"issuer\",\"shopperEmail\":\"test@test.com\",\"type\":\"dragonpay_ebanking\"}"; - var result = Util.JsonOperation.Deserialize(json); - Assert.IsInstanceOfType(result); - Assert.AreEqual(result.Type, DragonpayDetails.TypeEnum.Ebanking); - } - - [TestMethod] - public void AfterPayDetailsDeserializationTest() - { - var json = @"{ - 'resultCode':'RedirectShopper', - 'action':{ - 'paymentMethodType':'afterpaytouch', - 'method':'GET', - 'url':'https://checkoutshopper-test.adyen.com/checkoutshopper/checkoutPaymentRedirect?redirectData=...', - 'type':'redirect' - } - }"; - var result = JsonConvert.DeserializeObject(json); - Assert.IsInstanceOfType(result.Action.GetCheckoutRedirectAction()); - Assert.AreEqual(result.Action.GetCheckoutRedirectAction().PaymentMethodType, "afterpaytouch"); - } - - [TestMethod] - public void AfterPayDetailsSerializationTest() - { - var json = @"{ - 'paymentMethod':{ - 'type':'afterpaytouch' - }, - 'amount':{ - 'value':1000, - 'currency':'AUD' - }, - 'shopperName':{ - 'firstName':'Simon', - 'lastName':'Hopper' - }, - 'shopperEmail':'s.hopper@example.com', - 'shopperReference':'YOUR_UNIQUE_SHOPPER_ID', - 'reference':'YOUR_ORDER_REFERENCE', - 'merchantAccount':'YOUR_MERCHANT_ACCOUNT', - 'returnUrl':'https://your-company.com/checkout?shopperOrder=12xy..', - 'countryCode':'AU', - 'telephoneNumber':'+61 2 8520 3890', - 'billingAddress':{ - 'city':'Sydney', - 'country':'AU', - 'houseNumberOrName':'123', - 'postalCode':'2000', - 'stateOrProvince':'NSW', - 'street':'Happy Street' - }, - 'deliveryAddress':{ - 'city':'Sydney', - 'country':'AU', - 'houseNumberOrName':'123', - 'postalCode':'2000', - 'stateOrProvince':'NSW', - 'street':'Happy Street' - }, - 'lineItems':[ - { - 'description':'Shoes', - 'quantity':'1', - 'amountIncludingTax':'400', - 'amountExcludingTax': '331', - 'taxAmount': '69', - 'id':'Item #1' - }, - { - 'description':'Socks', - 'quantity':'2', - 'amountIncludingTax':'300', - 'amountExcludingTax': '248', - 'taxAmount': '52', - 'id':'Item #2' - } - ] - }"; - - var result = JsonConvert.DeserializeObject(json); - Assert.IsInstanceOfType(result.PaymentMethod.GetAfterpayDetails()); - Assert.AreEqual(result.PaymentMethod.GetAfterpayDetails().Type, AfterpayDetails.TypeEnum.Afterpaytouch); - } - - /// - /// Test toJson() that includes the type in the action - /// - [TestMethod] - public void PaymentsResponseToJsonTest() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentResponse-3DS-ChallengeShopper.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.Payments(paymentRequest); - var paymentResponseToJson = paymentResponse.ToJson(); - var jObject = JObject.Parse(paymentResponseToJson); - Assert.AreEqual(jObject["action"]["type"], "threeDS2"); - } - - [TestMethod] - public void StoredPaymentMethodsTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-storedpaymentmethods.json"); - var checkout = new PaymentsService(client); - var paymentMethodsRequest = new PaymentMethodsRequest(merchantAccount: "TestMerchant"); - var paymentMethodsResponse = checkout.PaymentMethods(paymentMethodsRequest); - Assert.AreEqual(4, paymentMethodsResponse.StoredPaymentMethods.Count); - Assert.AreEqual("NL32ABNA0515071439", paymentMethodsResponse.StoredPaymentMethods[0].Iban); - Assert.AreEqual("Adyen", paymentMethodsResponse.StoredPaymentMethods[0].OwnerName); - Assert.AreEqual("sepadirectdebit", paymentMethodsResponse.StoredPaymentMethods[0].Type); - } - - /// - /// Test if the fraud result are properly deseriazed - /// POST /payments - /// - [TestMethod] - public void ThreeDS2Test() - { - var paymentRequest = CreatePaymentRequestCheckout(); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentResponse-3DS2-Action.json"); - var checkout = new PaymentsService(client); - var paymentResponse = checkout.Payments(paymentRequest); - var paymentResponseThreeDs2Action = paymentResponse.Action.GetCheckoutThreeDS2Action(); - Assert.AreEqual(ResultCodeEnum.IdentifyShopper, paymentResponse.ResultCode); - Assert.AreEqual(CheckoutThreeDS2Action.TypeEnum.ThreeDS2, paymentResponseThreeDs2Action.Type); - } - - [TestMethod] - public void CheckoutLocalDateSerializationTest() - { - var checkoutSessionRequest = new CreateCheckoutSessionRequest - { - MerchantAccount = "merchant", - Reference = "TestReference", - ReturnUrl = "http://test-url.com", - Amount = new Amount("EUR", 10000L), - DateOfBirth = new DateTime(1998, 1, 1, 1, 1, 1), - ExpiresAt = new DateTime(2023, 4, 1, 1, 1, 1) - }; - // Create a DateTime object with minutes and seconds and verify it gets omitted - Assert.IsTrue(checkoutSessionRequest.ToJson().Contains("1998-01-01")); - // Opposite; check that it keeps full ISO string for other Date parameters - Assert.IsTrue(checkoutSessionRequest.ToJson().Contains("2023-04-01T01:01:01")); - } - - /// - /// Test success sessions - /// POST /sessions - /// - [TestMethod] - public void CheckoutSessionSuccessTest() - { - var checkoutSessionRequest = new CreateCheckoutSessionRequest - { - MerchantAccount = "TestMerchant", - Reference = "TestReference", - ReturnUrl = "http://test-url.com", - Amount = new Amount("EUR", 10000L), - Store = "My Store" - }; - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/sessions-success.json"); - var checkout = new PaymentsService(client); - var checkoutSessionResponse = checkout.Sessions(checkoutSessionRequest); - Assert.AreEqual("TestMerchant", checkoutSessionResponse.MerchantAccount); - Assert.AreEqual("TestReference", checkoutSessionResponse.Reference); - Assert.AreEqual("http://test-url.com", checkoutSessionResponse.ReturnUrl); - Assert.AreEqual("EUR", checkoutSessionResponse.Amount.Currency); - Assert.AreEqual("1000", checkoutSessionResponse.Amount.Value.ToString()); - Assert.AreEqual("My Store", checkoutSessionResponse.Store); - - } - - /// - /// Test success orders - /// POST /paymentMethods/balance - /// - [TestMethod] - public void CheckoutPaymentMethodsBalanceSuccessTest() - { - var checkoutBalanceCheckRequest = new BalanceCheckRequest - (amount: new Amount("EUR", 10000L), - merchantAccount: "TestMerchant", - reference: "TestReference", - paymentMethod: new Dictionary - { - { "type", "givex" }, - { "number", "4126491073027401" }, - { "cvc", "737" } - }); - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/paymentmethods-balance-success.json"); - var checkout = new OrdersService(client); - var checkoutBalanceCheckResponse = checkout.GetBalanceOfGiftCard(checkoutBalanceCheckRequest); - Assert.AreEqual(BalanceCheckResponse.ResultCodeEnum.Success, - checkoutBalanceCheckResponse.ResultCode); - Assert.AreEqual("EUR", checkoutBalanceCheckResponse.Balance.Currency); - Assert.AreEqual("2500", checkoutBalanceCheckResponse.Balance.Value.ToString()); - } - - /// - /// Test success orders - /// POST /orders - /// - [TestMethod] - public void CheckoutOrderSuccessTest() - { - var checkoutCreateOrderRequest = new CreateOrderRequest - (amount: new Amount("EUR", 10000L), - merchantAccount: "TestMerchant", - reference: "TestReference"); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/orders-success.json"); - var checkout = new OrdersService(client); - var checkoutOrdersResponse = checkout.Orders(checkoutCreateOrderRequest); - Assert.AreEqual(CreateOrderResponse.ResultCodeEnum.Success, checkoutOrdersResponse.ResultCode); - Assert.AreEqual("8515930288670953", checkoutOrdersResponse.PspReference); - Assert.AreEqual("Ab02b4c0!BQABAgBqxSuFhuXUF7IvIRvSw5bDPHN...", checkoutOrdersResponse.OrderData); - Assert.AreEqual("EUR", checkoutOrdersResponse.RemainingAmount.Currency); - Assert.AreEqual("2500", checkoutOrdersResponse.RemainingAmount.Value.ToString()); - } - - /// - /// Test success orders cancel - /// POST /orders/cancel - /// - [TestMethod] - public void CheckoutOrdersCancelSuccessTest() - { - var checkoutCancelOrderRequest = new CancelOrderRequest - (merchantAccount: "TestMerchant", - order: new EncryptedOrderData(orderData: "823fh892f8f18f4...148f13f9f3f", pspReference: "8815517812932012")); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/orders-cancel-success.json"); - var checkout = new OrdersService(client); - var checkoutOrdersCancelResponse = checkout.CancelOrder(checkoutCancelOrderRequest); - Assert.AreEqual("Received", checkoutOrdersCancelResponse.ResultCode.ToString()); - Assert.AreEqual("8515931182066678", checkoutOrdersCancelResponse.PspReference); - } - - /// - /// Test success orders cancel - /// GET /storedPaymentMethods - /// - [TestMethod] - public void GetStoredPaymentMethodsTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/get-storedPaymentMethod-success.json"); - var checkout = new RecurringService(client); - var listStoredPaymentMethodsResponse = - checkout.GetTokensForStoredPaymentDetails("shopperRef", "merchantAccount"); - Assert.AreEqual("string", listStoredPaymentMethodsResponse.StoredPaymentMethods[0].Type); - Assert.AreEqual("merchantAccount", listStoredPaymentMethodsResponse.MerchantAccount); - } - - /// - /// Test success orders cancel - /// GET /storedPaymentMethods - /// - [TestMethod] - public void DeleteStoredPaymentMethodsTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/get-storedPaymentMethod-success.json"); - var checkout = new RecurringService(client); - checkout.DeleteTokenForStoredPaymentDetails("recurringId","shopperRef", "merchantAccount"); - } - - #region Modification endpoints tests - - /// - /// Test success capture - /// POST /payments/{paymentPspReference}/captures - /// - [TestMethod] - public void PaymentsCapturesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/captures-success.json"); - var checkout = new ModificationsService(client); - var createPaymentCaptureRequest = new PaymentCaptureRequest(amount: new Amount("EUR", 1000L), - merchantAccount: "test_merchant_account"); - var paymentCaptureResource = checkout.CaptureAuthorisedPayment("12321A", createPaymentCaptureRequest); - Assert.AreEqual(PaymentCaptureResponse.StatusEnum.Received, paymentCaptureResource.Status); - Assert.AreEqual("my_reference", paymentCaptureResource.Reference); - } - - /// - /// Test success payments cancels - /// POST /payments/{paymentPspReference}/cancels - /// - [TestMethod] - public void PaymentsCancelsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/cancels-success.json"); - var checkout = new ModificationsService(client); - var createPaymentCancelRequest = new PaymentCancelRequest(merchantAccount: "test_merchant_account"); - var paymentCancelResource = - checkout.CancelAuthorisedPaymentByPspReference("12321A", createPaymentCancelRequest); - Assert.AreEqual(PaymentCancelResponse.StatusEnum.Received, paymentCancelResource.Status); - Assert.AreEqual("my_reference", paymentCancelResource.Reference); - } - - /// - /// Test success cancels - /// POST /cancels - /// - [TestMethod] - public void CancelsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/standalone-cancels-success.json"); - var checkout = new ModificationsService(client); - var createStandalonePaymentCancelRequest = - new StandalonePaymentCancelRequest(merchantAccount: "test_merchant_account"); - var standalonePaymentCancelResource = - checkout.CancelAuthorisedPayment(createStandalonePaymentCancelRequest); - Assert.AreEqual(StandalonePaymentCancelResponse.StatusEnum.Received, - standalonePaymentCancelResource.Status); - Assert.AreEqual("861633338418518C", standalonePaymentCancelResource.PspReference); - } - - /// - /// Test success payments refunds - /// POST /payments/{paymentPspReference}/refunds - /// - [TestMethod] - public void TestPaymentsRefunds() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/refunds-success.json"); - var checkout = new ModificationsService(client); - var createPaymentRefundRequest = new PaymentRefundRequest(amount: new Amount("EUR", 1000L), - merchantAccount: "test_merchant_account"); - var paymentRefundResource = checkout.RefundCapturedPayment("12321A", createPaymentRefundRequest); - Assert.AreEqual(PaymentRefundResponse.StatusEnum.Received, paymentRefundResource.Status); - Assert.AreEqual("my_reference", paymentRefundResource.Reference); - } - - /// - /// Test success payments reversals - /// POST /payments/{paymentPspReference}/reversals - /// - [TestMethod] - public void PaymentsReversalsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/reversals-success.json"); - var checkout = new ModificationsService(client); - var createPaymentReversalRequest = - new PaymentReversalRequest(merchantAccount: "test_merchant_account"); - var paymentReversalResource = checkout.RefundOrCancelPayment("12321A", createPaymentReversalRequest); - Assert.AreEqual(PaymentReversalResponse.StatusEnum.Received, paymentReversalResource.Status); - Assert.AreEqual("my_reference", paymentReversalResource.Reference); - } - - /// - /// Test success payments cancels - /// POST /payments/{paymentPspReference}/amountUpdates - /// - [TestMethod] - public void PaymentsAmountUpdatesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/amount-updates-success.json"); - var checkout = new ModificationsService(client); - var createPaymentAmountUpdateRequest = new PaymentAmountUpdateRequest( - amount: new Amount("EUR", 1000L), - merchantAccount: "test_merchant_account"); - var paymentAmountUpdateResource = - checkout.UpdateAuthorisedAmount("12321A", createPaymentAmountUpdateRequest); - Assert.AreEqual(PaymentAmountUpdateResponse.StatusEnum.Received, paymentAmountUpdateResource.Status); - Assert.AreEqual("my_reference", paymentAmountUpdateResource.Reference); - } - - /// - /// Test success donations - /// POST /donations - /// - [TestMethod] - public void DonationsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/donations-success.json"); - var checkout = new DonationsService(client); - var paymentDonationRequest = - new DonationPaymentRequest( - merchantAccount: "test_merchant_account", - amount: new Amount("USD", 5), - donationAccount: "Charity_TEST", - paymentMethod: new DonationPaymentMethod(new CardDonations()), - reference: "179761FE-1913-4226-9F43-E475DE634BBA", - returnUrl: "https://your-company.com/..."); - var donationResponse = checkout.Donations(paymentDonationRequest); - Assert.AreEqual(DonationPaymentResponse.StatusEnum.Completed, - donationResponse.Status); - Assert.AreEqual("10720de4-7c5d-4a17-9161-fa4abdcaa5c4", donationResponse.Reference); - } - - /// - /// Test success donations - /// POST /donations - /// - [TestMethod] - public void CardDetailsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/card-details-success.json"); - var checkout = new PaymentsService(client); - var cardDetailRequest = - new CardDetailsRequest - { - MerchantAccount = "TestMerchant", - CardNumber = "1234567890", - CountryCode = "NL" - }; - var cardDetailResponse = checkout.CardDetails(cardDetailRequest); - Assert.AreEqual("visa", cardDetailResponse.Brands[0].Type); - Assert.AreEqual("cartebancaire", cardDetailResponse.Brands[1].Type); - } - - /// - /// Test success donations - /// POST /donations - /// - [TestMethod] - public void ApplePaySessionsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/apple-pay-sessions-success.json"); - var checkout = new UtilityService(client); - var applePaySessionRequest = new ApplePaySessionRequest() - { - DisplayName = "YOUR_MERCHANT_NAME", - DomainName = "domainName", - MerchantIdentifier = "234tvsadh34fsghlker3..w35sgfs" - - }; - var applePayResponse = checkout.GetApplePaySessionAsync(applePaySessionRequest).Result; - Assert.AreEqual("eyJ2Z...340278gdflkaswer", applePayResponse.Data); - } - - #endregion - - /// - /// Test success orders cancel - /// GET /storedPaymentMethods - /// - [TestMethod] - public void CheckoutServiceInterfaceTest() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkout/get-storedPaymentMethod-success.json"); - var checkout = new MyRecurringService(client); - checkout.DeleteTokenForStoredPaymentDetails("shopperRef", "merchantAccount"); - } - } - - // Implementation to test the Recurring Service Interface - public class MyRecurringService : IRecurringService - { - private readonly IClient _client; - public MyRecurringService(Client client) - { - _client = client.HttpClient; - } - - public void DeleteTokenForStoredPaymentDetails(string recurringId, string shopperReference = default, - string merchantAccount = default, RequestOptions requestOptions = default) - { - var response = _client.Request("", "json", requestOptions, HttpMethod.Delete); - } - - public Task DeleteTokenForStoredPaymentDetailsAsync(string recurringId, string shopperReference = default, - string merchantAccount = default, RequestOptions requestOptions = default, - CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } - - public ListStoredPaymentMethodsResponse GetTokensForStoredPaymentDetails(string shopperReference = default, - string merchantAccount = default, RequestOptions requestOptions = default) - { - throw new NotImplementedException(); - } - - public Task GetTokensForStoredPaymentDetailsAsync(string shopperReference = default, string merchantAccount = default, - RequestOptions requestOptions = default, CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } - - public StoredPaymentMethodResource StoredPaymentMethods(StoredPaymentMethodRequest storedPaymentMethodRequest = default, - RequestOptions requestOptions = default) - { - throw new NotImplementedException(); - } - - public Task StoredPaymentMethodsAsync(StoredPaymentMethodRequest storedPaymentMethodRequest = default, - RequestOptions requestOptions = default, CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } - } -} diff --git a/Adyen.Test/CheckoutUtilityTest.cs b/Adyen.Test/CheckoutUtilityTest.cs deleted file mode 100644 index 70515889c..000000000 --- a/Adyen.Test/CheckoutUtilityTest.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using Adyen.Model.Checkout; -using Adyen.Service.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class CheckoutUtilityTest : BaseTest - { - /// - /// Test success flow for - ///POST /originKeys - /// - [TestMethod] - public void OriginKeysSuccessTest() - { - var checkoutUtilityRequest = new UtilityRequest(originDomains: new List { "www.test.com", "https://www.your-domain2.com" }); - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/checkoututility/originkeys-success.json"); - var _checkout = new UtilityService(client); - var originKeysResponse = _checkout.OriginKeys(checkoutUtilityRequest); - Assert.AreEqual("pub.v2.7814286629520534.aHR0cHM6Ly93d3cueW91ci1kb21haW4xLmNvbQ.UEwIBmW9-c_uXo5wSEr2w8Hz8hVIpujXPHjpcEse3xI", originKeysResponse.OriginKeys["https://www.your-domain1.com"]); - } - } -} diff --git a/Adyen.Test/Core/Auth/TokenProviderTest.cs b/Adyen.Test/Core/Auth/TokenProviderTest.cs new file mode 100644 index 000000000..db8862722 --- /dev/null +++ b/Adyen.Test/Core/Auth/TokenProviderTest.cs @@ -0,0 +1,49 @@ +using Adyen.Core.Auth; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Auth +{ + [TestClass] + public class TokenProviderTest + { + internal sealed class TestToken : TokenBase + { + public string Value { get; } + + internal TestToken(string value) + { + Value = value; + } + } + + [TestMethod] + public async Task Given_TokenProviderWithToken_When_GetCalled_Then_SameInstanceAndValueAreReturned() + { + // Arrange + var token = new TestToken("apikey"); + var provider = new TokenProvider(token); + + // Act + var result = provider.Get(); + + // Assert + Assert.AreSame(token, result); + Assert.AreEqual("apikey", result.Value); + } + + [TestMethod] + public async Task Given_TokenProvider_When_GetCalledMultipleTimes_Then_SameInstanceReturnedEachTime() + { + // Arrange + var token = new TestToken("apikey"); + var provider = new TokenProvider(token); + + // Act + var first = provider.Get(); + var second = provider.Get(); + + // Assert + Assert.AreSame(first, second); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Client/ApiResponseTest.cs b/Adyen.Test/Core/Client/ApiResponseTest.cs new file mode 100644 index 000000000..d89d88f50 --- /dev/null +++ b/Adyen.Test/Core/Client/ApiResponseTest.cs @@ -0,0 +1,173 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Adyen.Core.Client; + +namespace Adyen.Test.Core.Client +{ + [TestClass] + public class ApiResponseTests + { + private HttpRequestMessage CreateRequest(string? uri = "https://adyen.com") + => new HttpRequestMessage(HttpMethod.Get, uri); + + private HttpResponseMessage CreateResponse(HttpStatusCode statusCode, string reasonPhrase = "") + => new HttpResponseMessage(statusCode) + { + ReasonPhrase = reasonPhrase + }; + + [TestMethod] + [DataRow(HttpStatusCode.OK, true)] + [DataRow(HttpStatusCode.Created, true)] + [DataRow(HttpStatusCode.Accepted, true)] + [DataRow(HttpStatusCode.BadRequest, false)] + [DataRow(HttpStatusCode.Unauthorized, false)] + [DataRow(HttpStatusCode.Forbidden, false)] + [DataRow(HttpStatusCode.NotFound, false)] + [DataRow(HttpStatusCode.TooManyRequests, false)] + [DataRow(HttpStatusCode.UnprocessableEntity, false)] + [DataRow(HttpStatusCode.InternalServerError, false)] + public async Task Given_ApiResponse_When_SuccessStatusCode_Then_Result_ShouldMatchHttpResponseMessage(HttpStatusCode code, bool expected) + { + // Arrange + // Act + var response = new ApiResponse(CreateRequest(), CreateResponse(code), "", "/", DateTime.UtcNow, new JsonSerializerOptions()); + // Assert + Assert.AreEqual(expected, response.IsSuccessStatusCode); + } + + [TestMethod] + public async Task Given_ApiResponse_When_Properties_Are_Set_Then_Object_Should_Return_Correct_Values() + { + // Arrange + var request = CreateRequest("https://adyen.com/"); + + // Act + var responseMessage = CreateResponse(HttpStatusCode.Accepted, "Accepted"); + var apiResponse = new ApiResponse(request, responseMessage, "{\"key\":\"value\"}", "/path", DateTime.UtcNow, new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(responseMessage.StatusCode, apiResponse.StatusCode); + Assert.AreEqual(responseMessage.ReasonPhrase, apiResponse.ReasonPhrase); + Assert.AreEqual(request.RequestUri, apiResponse.RequestUri); + Assert.AreEqual("/path", apiResponse.Path); + Assert.IsNotNull(apiResponse.Headers); + Assert.AreEqual("{\"key\":\"value\"}", apiResponse.RawContent); + Assert.IsNull(apiResponse.ContentStream); + } + + [TestMethod] + public async Task Given_ApiResponse_When_ContentStream_Is_Set_Then_Return_ContentStream_And_Empty_RawContent() + { + // Arrange + var request = CreateRequest(); + var responseMessage = CreateResponse(HttpStatusCode.OK); + + // Act + var stream = new MemoryStream(new byte[] { 1, 2, 3 }); + var apiResponse = new ApiResponse(request, responseMessage, stream, "/stream", DateTime.UtcNow, new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(stream, apiResponse.ContentStream); + Assert.AreEqual(string.Empty, apiResponse.RawContent); + } + + private class TestApiResponse : ApiResponse, + IOk, ICreated, IAccepted, + IBadRequest, IUnauthorized, IForbidden, ITooManyRequests, INotFound, IUnprocessableContent, IInternalServerError + { + public TestApiResponse(HttpRequestMessage message, HttpResponseMessage response, string raw, string path, DateTime requested, JsonSerializerOptions opts) + : base(message, response, raw, path, requested, opts) { } + + private T DeserializeRaw() => JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions)!; + + public T Ok() => DeserializeRaw(); + public bool TryDeserializeOkResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T Created() => DeserializeRaw(); + public bool TryDeserializeCreatedResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T Accepted() => DeserializeRaw(); + public bool TryDeserializeAcceptedResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T BadRequest() => DeserializeRaw(); + public bool TryDeserializeBadRequestResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T Unauthorized() => DeserializeRaw(); + public bool TryDeserializeUnauthorizedResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T Forbidden() => DeserializeRaw(); + public bool TryDeserializeForbiddenResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T TooManyRequests() => DeserializeRaw(); + public bool TryDeserializeTooManyRequestsResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T NotFound() => DeserializeRaw(); + public bool TryDeserializeNotFoundResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T UnprocessableContent() => DeserializeRaw(); + public bool TryDeserializeUnprocessableContentResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + + public T InternalServerError() => DeserializeRaw(); + public bool TryDeserializeInternalServerErrorResponse(out T? result) { result = string.IsNullOrEmpty(RawContent) ? default : DeserializeRaw(); return result != null; } + } + + private record TestModel(string Foo); + + [TestMethod] + public async Task Given_ApiResponse_When_TypedResponses_Then_Deserialize_Correctly() + { + // Arrange + var model = new TestModel("adyen"); + + // Act + string json = JsonSerializer.Serialize(model, new JsonSerializerOptions()); + var response = new TestApiResponse(CreateRequest(), CreateResponse(HttpStatusCode.OK), json, "/path", DateTime.UtcNow, new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(model, response.Ok()); + Assert.IsTrue(response.TryDeserializeOkResponse(out var okResult)); + Assert.AreEqual(model, okResult); + + Assert.AreEqual(model, response.Created()); + Assert.IsTrue(response.TryDeserializeCreatedResponse(out var createdResult)); + Assert.AreEqual(model, createdResult); + + Assert.AreEqual(model, response.Accepted()); + Assert.IsTrue(response.TryDeserializeAcceptedResponse(out var acceptedResult)); + Assert.AreEqual(model, acceptedResult); + + Assert.AreEqual(model, response.BadRequest()); + Assert.IsTrue(response.TryDeserializeBadRequestResponse(out var badResult)); + Assert.AreEqual(model, badResult); + + Assert.AreEqual(model, response.Unauthorized()); + Assert.IsTrue(response.TryDeserializeUnauthorizedResponse(out var unAuthResult)); + Assert.AreEqual(model, unAuthResult); + + Assert.AreEqual(model, response.Forbidden()); + Assert.IsTrue(response.TryDeserializeForbiddenResponse(out var forbiddenResult)); + Assert.AreEqual(model, forbiddenResult); + + Assert.AreEqual(model, response.TooManyRequests()); + Assert.IsTrue(response.TryDeserializeTooManyRequestsResponse(out var tooManyResult)); + Assert.AreEqual(model, tooManyResult); + + Assert.AreEqual(model, response.NotFound()); + Assert.IsTrue(response.TryDeserializeNotFoundResponse(out var notFoundResult)); + Assert.AreEqual(model, notFoundResult); + + Assert.AreEqual(model, response.UnprocessableContent()); + Assert.IsTrue(response.TryDeserializeUnprocessableContentResponse(out var unprocessableResult)); + Assert.AreEqual(model, unprocessableResult); + + Assert.AreEqual(model, response.InternalServerError()); + Assert.IsTrue(response.TryDeserializeInternalServerErrorResponse(out var internalResult)); + Assert.AreEqual(model, internalResult); + } + } +} diff --git a/Adyen.Test/Core/Client/HttpRequestMessageExtensions.cs b/Adyen.Test/Core/Client/HttpRequestMessageExtensions.cs new file mode 100644 index 000000000..a7652c36e --- /dev/null +++ b/Adyen.Test/Core/Client/HttpRequestMessageExtensions.cs @@ -0,0 +1,95 @@ +using Adyen.Core.Client.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Client +{ + [TestClass] + public class HttpRequestMessageExtensionsTest + { + [TestMethod] + public void Given_AddUserAgentToHeaders_When_ApplicationName_Is_Null_Returns_adyen_dotnet_api_library_And_AdyenLibraryVersion() + { + // Arrange + HttpRequestMessageExtensions.ApplicationName = null; + var request = new HttpRequestMessage(); + + // Act + request.AddUserAgentToHeaders(); + + // Assert + string target = request.Headers.GetValues("UserAgent").First(); + Assert.AreEqual($"adyen-dotnet-api-library/{HttpRequestMessageExtensions.AdyenLibraryVersion}", target); + } + + [TestMethod] + public void Given_AddUserAgentToHeaders_When_ApplicationName_Is_Set_Returns_MyApp_adyen_dotnet_api_library_And_AdyenLibraryVersion() + { + // Arrange + var request = new HttpRequestMessage(); + HttpRequestMessageExtensions.ApplicationName = "MyApp"; + + // Act + request.AddUserAgentToHeaders(); + + // Assert + string target = request.Headers.GetValues("UserAgent").First(); + Assert.AreEqual($"MyApp adyen-dotnet-api-library/{HttpRequestMessageExtensions.AdyenLibraryVersion}", target); + } + + [TestMethod] + public void Given_AddLibraryNameToHeader_When_Provided_Returns_adyen_dotnet_api_library() + { + // Arrange + HttpRequestMessageExtensions.ApplicationName = null; + var request = new HttpRequestMessage(); + + // Act + request.AddLibraryNameToHeader(); + + // Assert + string target = request.Headers.GetValues("adyen-library-name").First(); + Assert.AreEqual("adyen-dotnet-api-library", target); + } + + [TestMethod] + public void Given_AddLibraryNameToHeader_When_Provided_Returns_AdyenLibraryVersion() + { + // Arrange + HttpRequestMessageExtensions.ApplicationName = null; + var request = new HttpRequestMessage(); + + // Act + request.AddLibraryVersionToHeader(); + + // Assert + string target = request.Headers.GetValues("adyen-library-version").First(); + Assert.AreEqual(HttpRequestMessageExtensions.AdyenLibraryVersion, target); + } + + [TestMethod] + public void Given_AddUserAgentToHeaders_When_Called_MultipleTimes_Should_Not_Throw_Any_Exceptions() + { + // Arrange + HttpRequestMessageExtensions.ApplicationName = null; + var request = new HttpRequestMessage(); + + // Act + // Assert + try + { + request.AddUserAgentToHeaders(); + request.AddUserAgentToHeaders(); + + request.AddLibraryNameToHeader(); + request.AddLibraryNameToHeader(); + + request.AddLibraryVersionToHeader(); + request.AddLibraryVersionToHeader(); + } + catch (Exception e) + { + Assert.Fail(); + } + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Client/UrlBuilderExtensionsTest.cs b/Adyen.Test/Core/Client/UrlBuilderExtensionsTest.cs new file mode 100644 index 000000000..aeadc3c3a --- /dev/null +++ b/Adyen.Test/Core/Client/UrlBuilderExtensionsTest.cs @@ -0,0 +1,154 @@ +using Adyen.Core.Client; +using Adyen.Core.Options; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Client +{ + [TestClass] + public class UrlBuilderExtensionsTest + { + #region Checkout && POS-SDK + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_Then_CheckoutUrl_Contains_Prefix_And_Live_String() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = "prefix", + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://checkout-test.adyen.com/v71"); + + // Assert + Assert.AreEqual("https://prefix-checkout-live.adyenpayments.com/checkout/v71", target); + } + + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_And_No_Prefix_For_Checkout_Throws_InvalidOperationException() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = null + }; + + // Act + // Assert + Assert.Throws(() => UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://checkout-test.adyen.com/v71")); + } + + #endregion + + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_Then_Checkout_POS_SDK_Contains_Prefix_And_Live_String_Without_Checkout() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = "prefix", + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://checkout-test.adyen.com/checkout/possdk/v68"); + + // Assert + Assert.AreEqual("https://prefix-checkout-live.adyenpayments.com/checkout/possdk/v68", target); + } + + + #region Pal + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_Then_PalUrl_Contains_Prefix_And_Live_String() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = "prefix", + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://pal-test.adyen.com/pal/servlet/Payment/v68"); + + // Assert + Assert.AreEqual("https://prefix-pal-live.adyenpayments.com/pal/servlet/Payment/v68", target); + } + + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_And_No_Prefix_For_Pal_Throws_InvalidOperationException() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = null + }; + + // Act + // Assert + Assert.Throws(() => UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://pal-test.adyen.com/pal/servlet/Payment/v68")); + } + + #endregion + + + #region SessionAuthentication + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_Then_SessionAuthentication_Url_Contains_Prefix_And_Live_String() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = "prefix", + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://test.adyen.com/authe/api/v1"); + + // Assert + Assert.AreEqual("https://authe-live.adyen.com/authe/api/v1", target); + } + + #endregion + + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Test_And_Prefix_Given_Then_Url_Does_Not_Contain_Prefix() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Test, + LiveEndpointUrlPrefix = "prefix", + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://test.adyen.com"); + + // Assert + Assert.IsFalse(target.Contains("prefix")); + } + + [TestMethod] + public async Task Given_ConstructHostUrl_When_Environment_Is_Live_And_No_Prefix_Does_Not_Throw_InvalidOperationException_And_Contains_String_Value_Test() + { + // Arrange + AdyenOptions adyenOptions = new AdyenOptions() + { + Environment = AdyenEnvironment.Live, + LiveEndpointUrlPrefix = null + }; + + // Act + string target = UrlBuilderExtensions.ConstructHostUrl(adyenOptions, "https://test.adyen.com/"); + + // Assert + Assert.IsTrue(target.Contains("test")); + } + + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Converters/ByteArrayTest.cs b/Adyen.Test/Core/Converters/ByteArrayTest.cs new file mode 100644 index 000000000..542775b8e --- /dev/null +++ b/Adyen.Test/Core/Converters/ByteArrayTest.cs @@ -0,0 +1,114 @@ +using System.Text; +using System.Text.Json; +using Adyen.Core.Converters; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Converters +{ + [TestClass] + public class ByteArrayTest + { + private readonly ByteArrayConverter _converter = new ByteArrayConverter(); + + [TestMethod] + public void Given_ByteArray_When_Write_Then_Result_Should_Write_UTF8_String() + { + // Arrange + byte[] bytes = Encoding.UTF8.GetBytes("adyen"); + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + // Act + _converter.Write(writer, bytes, new JsonSerializerOptions()); + writer.Flush(); + string target = Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual("\"adyen\"", target); + } + + [TestMethod] + public void Given_ByteArray_Null_When_Write_Then_Result_Returns_Null() + { + // Arrange + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + // Act + _converter.Write(writer, null, new JsonSerializerOptions()); + writer.Flush(); + string json = Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual("null", json); + } + + [TestMethod] + public void Given_Json_When_Read_And_Decoded_Then_Should_Return_ByteArray() + { + // Arrange + string json = "\"adyen\""; + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + + // Act + byte[] result = _converter.Read(ref reader, typeof(byte[]), new JsonSerializerOptions()); + string decoded = Encoding.UTF8.GetString(result); + + // Assert + Assert.AreEqual("adyen", decoded); + } + + [TestMethod] + public void Given_Json_Null_When_Read_Then_Returns_Null() + { + // Arrange + string json = "null"; + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + + // Act + byte[] result = _converter.Read(ref reader, typeof(byte[]), new JsonSerializerOptions()); + + // Assert + Assert.IsNull(result); + } + + [TestMethod] + public void Given_ByteArray_When_Write_And_Read_Then_Result_Returns_Original_Bytes() + { + // Arrange + byte[] original = Encoding.UTF8.GetBytes("adyen"); + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + _converter.Write(writer, original, new JsonSerializerOptions()); + writer.Flush(); + string json = Encoding.UTF8.GetString(stream.ToArray()); + + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + + // Act + byte[] result = _converter.Read(ref reader, typeof(byte[]), new JsonSerializerOptions()); + + // Assert + CollectionAssert.AreEqual(original, result); + } + + [TestMethod] + public void Given_EmptyString_When_Read_Then_ShouldReturnEmptyByteArray() + { + // Arrange + string json = "\"\""; + Utf8JsonReader reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + + // Act + byte[] result = _converter.Read(ref reader, typeof(byte[]), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(Array.Empty(), result); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Converters/DateOnlyJsonConverterTest.cs b/Adyen.Test/Core/Converters/DateOnlyJsonConverterTest.cs new file mode 100644 index 000000000..1c7013897 --- /dev/null +++ b/Adyen.Test/Core/Converters/DateOnlyJsonConverterTest.cs @@ -0,0 +1,105 @@ +using System.Text.Json; +using Adyen.Core.Converters; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Converters +{ + [TestClass] + public class DateOnlyJsonConverterTests + { + private readonly DateOnlyJsonConverter _converter = new DateOnlyJsonConverter(); + + [TestMethod] + public void Given_DateWithDashes_yyyy_MM_dd_When_Read_Then_ReturnsCorrectDate() + { + // Arrange + string json = "\"2025-12-25\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(new DateOnly(2025, 12, 25), result); + } + + [TestMethod] + public void Given_Date_yyyyMMdd_When_Read_Then_ReturnsCorrectDate() + { + // Arrange + string json = "\"20251225\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(new DateOnly(2025, 12, 25), result); + } + + [TestMethod] + public void Given_WrongFormatDateOnlyString_When_Read_Then_ThrowsNotSupportedException() + { + // Arrange + string json = "\"25-12-2025\""; // Incorrect format dd-MM-yyyy + + // Act + // Assert + Assert.ThrowsException(() => + { + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + }); + } + [TestMethod] + public void Given_InvalidDateOnlyString_When_Read_Then_ThrowsJsonException() + { + // Arrange + string json = "invalid-date"; + + // Act + // Assert + Assert.Throws(() => + { + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + }); + } + + [TestMethod] + public void Given_NullToken_When_Read_Then_ThrowsNotSupportedException() + { + // Arrange + string json = "null"; + + // Act + // Assert + Assert.ThrowsException(() => { + Utf8JsonReader reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + }); + } + + [TestMethod] + public void Given_DateOnlyValue_When_Write_Then_WritesCorrectDateOnlyValue() + { + // Arrange + var date = new DateOnly(2025, 12, 25); + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + // Act + _converter.Write(writer, date, new JsonSerializerOptions()); + writer.Flush(); + string json = System.Text.Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual("\"2025-12-25\"", json); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Converters/DateOnlyNullableJsonConverterTest.cs b/Adyen.Test/Core/Converters/DateOnlyNullableJsonConverterTest.cs new file mode 100644 index 000000000..8f75f6470 --- /dev/null +++ b/Adyen.Test/Core/Converters/DateOnlyNullableJsonConverterTest.cs @@ -0,0 +1,106 @@ +using System.Text.Json; +using Adyen.Core.Converters; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Converters +{ + [TestClass] + public class DateOnlyNullableJsonConverterTest + { + private readonly DateOnlyNullableJsonConverter _converter = new DateOnlyNullableJsonConverter(); + + [TestMethod] + public void Given_DateWithDashes_yyyy_MM_dd_When_Read_Then_ReturnsCorrectDate() + { + // Arrange + string json = "\"2025-12-25\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(new DateOnly(2025, 12, 25), result); + } + + [TestMethod] + public void Given_Date_yyyyMMdd_When_Read_Then_ReturnsCorrectDate() + { + // Arrange + string json = "\"20251225\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(new DateOnly(2025, 12, 25), result); + } + + [TestMethod] + public void Given_WrongFormatDateOnlyString_When_Read_Then_ThrowsNotSupportedException() + { + // Arrange + string json = "\"25-12-2025\""; // Incorrect format dd-MM-yyyy + + // Act + // Assert + Assert.ThrowsException(() => + { + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + }); + } + + [TestMethod] + public void Given_InvalidDateOnlyString_When_Read_Then_ThrowsJsonException() + { + // Arrange + string json = "invalid-date"; + + // Act + // Assert + Assert.Throws(() => + { + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + }); + } + + [TestMethod] + public void Given_NullToken_When_Read_Then_ThrowsNotSupportedException() + { + // Arrange + string json = "null"; + + // Act + Utf8JsonReader reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateOnly), new JsonSerializerOptions()); + + // Assert + Assert.IsNull(result); + } + + [TestMethod] + public void Given_DateOnlyValue_When_Write_Then_WritesCorrectDateOnlyValue() + { + // Arrange + DateOnly? dateOnly = null; + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + // Act + _converter.Write(writer, dateOnly, new JsonSerializerOptions()); + writer.Flush(); + string json = System.Text.Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual("null", json); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Core/Converters/DateTimeJsonConverterTest.cs b/Adyen.Test/Core/Converters/DateTimeJsonConverterTest.cs new file mode 100644 index 000000000..68938e00c --- /dev/null +++ b/Adyen.Test/Core/Converters/DateTimeJsonConverterTest.cs @@ -0,0 +1,76 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Text.Json; +using Adyen.Core.Converters; + +namespace Adyen.Test.Core.Converters +{ + [TestClass] + public class DateTimeJsonConverterTest + { + private readonly DateTimeJsonConverter _converter = new DateTimeJsonConverter(); + + [TestMethod] + public void Given_ValidDateTimeWithFraction_When_Read_Then_ReturnsCorrectDateTime() + { + // Arrange + string json = "\"2025-12-25T14:30:15.1234567Z\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(DateTime.Parse("2025-12-25T14:30:15.1234567Z").ToUniversalTime(), result); + } + + [TestMethod] + public void Given_ValidDateTimeWithoutFraction_When_Read_Then_ReturnsCorrectDateTime() + { + // Arrange + string json = "\"2025-12-25T14:30:15Z\""; + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + + // Act + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(DateTime.Parse("2025-12-25T14:30:15Z").ToUniversalTime(), result); + } + + [TestMethod] + public void Given_InvalidDateTime_When_Read_Then_ThrowsNotSupportedException() + { + // Arrange + string json = "\"invalid-datetime\""; + + // Act + // Assert + Assert.ThrowsException(() => + { + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + _converter.Read(ref reader, typeof(DateTime), new JsonSerializerOptions()); + }); + } + + [TestMethod] + public void Given_DateTimeValue_When_Write_Then_WritesCorrectJson() + { + // Arrange + var dateTime = new DateTime(2025, 12, 25, 14, 30, 15, 123, DateTimeKind.Utc).AddTicks(4567); + + // Act + using var stream = new MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + _converter.Write(writer, dateTime, new JsonSerializerOptions()); + writer.Flush(); + string json = System.Text.Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual($"\"{dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", System.Globalization.CultureInfo.InvariantCulture)}\"", json); + } + } +} diff --git a/Adyen.Test/Core/Converters/DateTimeNullableJsonConverterTest.cs b/Adyen.Test/Core/Converters/DateTimeNullableJsonConverterTest.cs new file mode 100644 index 000000000..a116094e8 --- /dev/null +++ b/Adyen.Test/Core/Converters/DateTimeNullableJsonConverterTest.cs @@ -0,0 +1,111 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Globalization; +using System.Text; +using System.Text.Json; +using Adyen.Core.Converters; + +namespace Adyen.Test.Core.Converters +{ + [TestClass] + public class DateTimeNullableJsonConverterTests + { + private readonly DateTimeNullableJsonConverter _converter = new(); + + [TestMethod] + public void Given_ValidDateTimeWithFraction_When_Read_Then_ReturnsCorrectDateTime() + { + // Arrange + string json = "\"2025-12-25T14:30:15.1234567Z\""; + + // Act + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime?), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(DateTime.Parse("2025-12-25T14:30:15.1234567Z").ToUniversalTime(), result); + } + + [TestMethod] + public void Given_ValidDateTimeWithoutFraction_When_Read_Then_ReturnsCorrectDateTime() + { + // Arrange + string json = "\"2025-12-25T14:30:15Z\""; + + // Act + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime?), new JsonSerializerOptions()); + + // Assert + Assert.AreEqual(DateTime.Parse("2025-12-25T14:30:15Z").ToUniversalTime(), result); + } + + [TestMethod] + public void Given_NullJson_When_Read_Then_ReturnsNull() + { + // Arrange + string json = "null"; + + // Act + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime?), new JsonSerializerOptions()); + + // Assert + Assert.IsNull(result); + } + + [TestMethod] + public void Given_InvalidDateTime_When_Read_Then_Returns_Null() + { + // Arrange + string json = "\"invalid-datetime\""; + + // Act + var reader = new Utf8JsonReader(System.Text.Encoding.UTF8.GetBytes(json)); + reader.Read(); + var result = _converter.Read(ref reader, typeof(DateTime?), new JsonSerializerOptions()); + + // Assert + Assert.IsNull(result); + } + + [TestMethod] + public void Given_DateTimeValue_When_Write_Then_WritesCorrectJson() + { + // Arrange + var dateTime = new DateTime(2025, 12, 25, 14, 30, 15, 123, DateTimeKind.Utc).AddTicks(4567); + + // Act + using var stream = new System.IO.MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + _converter.Write(writer, dateTime, new JsonSerializerOptions()); + writer.Flush(); + string json = Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual($"\"{dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)}\"", json); + } + + [TestMethod] + public void Given_NullDateTime_When_Write_Then_WritesNullJson() + { + // Arrange + DateTime? dateTime = null; + + // Act + using var stream = new System.IO.MemoryStream(); + using var writer = new Utf8JsonWriter(stream); + + _converter.Write(writer, dateTime, new JsonSerializerOptions()); + writer.Flush(); + string json = Encoding.UTF8.GetString(stream.ToArray()); + + // Assert + Assert.AreEqual("null", json); + } + } +} diff --git a/Adyen.Test/Core/IEnumTest.cs b/Adyen.Test/Core/IEnumTest.cs new file mode 100644 index 000000000..7002b1950 --- /dev/null +++ b/Adyen.Test/Core/IEnumTest.cs @@ -0,0 +1,359 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Adyen.Core; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core +{ + [TestClass] + public class IEnumTest + { + [TestMethod] + public async Task Given_Enums_When_Equal_Returns_Correct_True() + { + ExampleEnum? nullEnum = null; + + Assert.AreEqual(nullEnum, nullEnum); + Assert.AreEqual(ExampleEnum.A, ExampleEnum.A); + Assert.AreEqual(ExampleEnum.B, ExampleEnum.B); + } + + [TestMethod] + public async Task Given_Enums_When_NotEqual_Returns_Correct_False() + { + ExampleEnum? nullEnum = null; + + Assert.AreNotEqual(ExampleEnum.A, ExampleEnum.B); + Assert.AreNotEqual(ExampleEnum.B, nullEnum); + Assert.AreNotEqual(ExampleEnum.A, nullEnum); + } + + [TestMethod] + public async Task Given_ImplicitConversion_When_Initialized_Then_Returns_Correct_Values() + { + ExampleEnum? resultA = "a"; + ExampleEnum? resultB = "b"; + + Assert.AreEqual(ExampleEnum.A, resultA); + Assert.AreEqual(ExampleEnum.B, resultB); + } + + [TestMethod] + public async Task Given_ImplicitConversion_When_Null_Then_Returns_Null() + { + ExampleEnum? input = null; + string? result = input; + + Assert.IsNull(result); + } + + [TestMethod] + public async Task Given_ToString_When_Called_Then_Returns_Correct_Value() + { + Assert.AreEqual("a", ExampleEnum.A.ToString()); + Assert.AreEqual("b", ExampleEnum.B.ToString()); + } + + [TestMethod] + public async Task Given_FromStringOrDefault_When_Enum_Not_In_List_Then_Returns_Null() + { + ExampleEnum result = ExampleEnum.FromStringOrDefault("this-is-not-a-valid-enum"); + + Assert.IsNull(result); + } + + [TestMethod] + public async Task Given_Equals_When_ComparingCaseInsensitive_Then_Returns_True() + { + ExampleEnum result = ExampleEnum.A; + + Assert.IsTrue(result.Equals(ExampleEnum.A)); + Assert.IsFalse(result.Equals(ExampleEnum.B)); + } + + [TestMethod] + public async Task Given_FromStringOrDefault_When_InvalidString_Then_Returns_Null() + { + Assert.IsNull(ExampleEnum.FromStringOrDefault("this-is-not-a-valid-enum")); + } + + [TestMethod] + public async Task Given_EqualityOperator_When_ComparingValues_Then_Returns_Correct_Values() + { + ExampleEnum target = ExampleEnum.A; + ExampleEnum otherA = ExampleEnum.A; + ExampleEnum otherB = ExampleEnum.B; + + Assert.IsTrue(target == otherA); + Assert.IsFalse(target == otherB); + Assert.IsTrue(target != otherB); + Assert.IsFalse(target != otherA); + } + + [TestMethod] + public async Task Given_FromStringOrDefault_When_ValidStrings_Then_Returns_Correct_Enum() + { + Assert.AreEqual(ExampleEnum.A, ExampleEnum.FromStringOrDefault("a")); + Assert.AreEqual(ExampleEnum.B, ExampleEnum.FromStringOrDefault("b")); + } + + [TestMethod] + public async Task Given_ToJsonValue_When_KnownEnum_Then_Returns_String() + { + Assert.AreEqual("a", ExampleEnum.ToJsonValue(ExampleEnum.A)); + Assert.AreEqual("b", ExampleEnum.ToJsonValue(ExampleEnum.B)); + } + + [TestMethod] + public async Task Given_ToJsonValue_When_Null_Then_Returns_Null() + { + Assert.IsNull(ExampleEnum.ToJsonValue(null)); + } + + [TestMethod] + public async Task Given_ToJsonValue_When_CustomEnum_Then_Returns_Null() + { + ExampleEnum custom = ExampleEnum.FromStringOrDefault("this-is-not-a-valid-enum"); + Assert.IsNull(ExampleEnum.ToJsonValue(custom)); + } + + [TestMethod] + public async Task Given_JsonSerialization_When_KnownEnum_Then_Serialize_and_Deserialize_Correctly() + { + JsonSerializerOptions options = new JsonSerializerOptions(); + options.Converters.Add(new ExampleEnum.ExampleJsonConverter()); + + string serializedA = JsonSerializer.Serialize(ExampleEnum.A, options); + string serializedB = JsonSerializer.Serialize(ExampleEnum.B, options); + + Assert.AreEqual("\"a\"", serializedA); + Assert.AreEqual("\"b\"", serializedB); + + ExampleEnum? deserializedA = JsonSerializer.Deserialize(serializedA, options); + ExampleEnum? deserializedB = JsonSerializer.Deserialize(serializedB, options); + + Assert.AreEqual(ExampleEnum.A, deserializedA); + Assert.AreEqual(ExampleEnum.B, deserializedB); + } + + [TestMethod] + public async Task Given_JsonSerialization_When_EnumNotInList_Then_Returns_Null() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new ExampleEnum.ExampleJsonConverter()); + + ExampleEnum? value = ExampleEnum.FromStringOrDefault("not-in-list"); + string serialized = JsonSerializer.Serialize(value, options); + Assert.AreEqual("null", serialized); + + ExampleEnum? deserialized = JsonSerializer.Deserialize(serialized, options); + Assert.AreEqual(null, deserialized); + } + + [TestMethod] + public async Task Given_JsonSerialization_When_Null_Value_Then_Serialize_And_Deserialize_Correctly() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new ExampleEnum.ExampleJsonConverter()); + + ExampleEnum? value = null; + string serialized = JsonSerializer.Serialize(value, options); + Assert.AreEqual("null", serialized); + + ExampleEnum? deserialized = JsonSerializer.Deserialize("null", options); + Assert.IsNull(deserialized); + } + + + #region Arrange ExampleModelResponse for testing (an example) model deserialization + + [TestMethod] + public async Task Given_JsonDeserialization_When_ExampleEnum_Is_Null_Then_Deserialize_Correctly_And_Not_Throw_Exception() + { + // Arrange + string json = @" +{ + ""exampleEnum"": null +}"; + var options = new JsonSerializerOptions(); + options.Converters.Add(new ExampleEnum.ExampleJsonConverter()); + options.Converters.Add(new ExampleModelResponse.ExampleModelResponseJsonConverter()); + + // Act + ExampleModelResponse result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.IsNull(result.ExampleEnum); + } + + [TestMethod] + public async Task Given_JsonDeserialization_When_ExampleEnum_Is_A_Then_Deserialize_Correctly_To_A() + { + // Arrange + string json = @" +{ + ""exampleEnum"": ""a"" +}"; + var options = new JsonSerializerOptions(); + options.Converters.Add(new ExampleEnum.ExampleJsonConverter()); + options.Converters.Add(new ExampleModelResponse.ExampleModelResponseJsonConverter()); + + // Act + ExampleModelResponse result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.AreEqual(ExampleEnum.A, result.ExampleEnum); + } + + internal class ExampleModelResponse + { + /// + /// The optional enum to test. + /// + [JsonPropertyName("exampleEnum")] + public ExampleEnum? ExampleEnum + { + get { return this._ExampleEnumOption; } + set { this._ExampleEnumOption = new(value); } + } + + /// + /// Used to track if an optional field is set. If so, set the . + /// + [JsonIgnore] + public Option _ExampleEnumOption { get; private set; } + + [JsonConstructor] + public ExampleModelResponse(Option exampleEnum) + { + this._ExampleEnumOption = exampleEnum; + } + + internal class ExampleModelResponseJsonConverter : JsonConverter + { + public override ExampleModelResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option exampleEnum = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "exampleEnum": + exampleEnum = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + return new ExampleModelResponse(exampleEnum); + } + + public override void Write(Utf8JsonWriter writer, ExampleModelResponse response, JsonSerializerOptions jsonSerializerOptions) + { + writer.WritePropertyName("exampleEnum"); + JsonSerializer.Serialize(writer, response.ExampleEnum, jsonSerializerOptions); + } + } + } + + #endregion + } + + #region Arrange ExampleEnum for testing + + [JsonConverter(typeof(ExampleJsonConverter))] + internal class ExampleEnum : IEnum + { + public string? Value { get; set; } + + /// + /// ExampleEnum.A: a + /// + public static readonly ExampleEnum A = new("a"); + + /// + /// ExampleEnum.B: b + /// + public static readonly ExampleEnum B = new("b"); + + private ExampleEnum(string? value) + { + Value = value; + } + + public static implicit operator ExampleEnum?(string? value) => value == null ? null : new ExampleEnum(value); + + public static implicit operator string?(ExampleEnum? option) => option?.Value; + + public override string ToString() => Value ?? string.Empty; + + public override bool Equals(object? obj) => obj is ExampleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public static bool operator ==(ExampleEnum? left, ExampleEnum? right) => + string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ExampleEnum? left, ExampleEnum? right) => + !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static ExampleEnum? FromStringOrDefault(string value) + { + return value switch { + "a" => ExampleEnum.A, + "b" => ExampleEnum.B, + _ => null, + }; + } + + public static string? ToJsonValue(ExampleEnum? value) + { + if (value == null) + return null; + + if (value == ExampleEnum.A) + return "a"; + + if (value == ExampleEnum.B) + return "b"; + + return null; + } + + public class ExampleJsonConverter : JsonConverter + { + public override ExampleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string str = reader.GetString(); + return str == null ? null : ExampleEnum.FromStringOrDefault(str) ?? new ExampleEnum(str); + } + + public override void Write(Utf8JsonWriter writer, ExampleEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ExampleEnum.ToJsonValue(value)); + } + } + } + #endregion +} \ No newline at end of file diff --git a/Adyen.Test/Core/Utilities/HmacValidatorUtilityTest.cs b/Adyen.Test/Core/Utilities/HmacValidatorUtilityTest.cs new file mode 100644 index 000000000..a8027f630 --- /dev/null +++ b/Adyen.Test/Core/Utilities/HmacValidatorUtilityTest.cs @@ -0,0 +1,103 @@ +using System.Text; +using Adyen.Core.Utilities; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Core.Utilities +{ + [TestClass] + public class HmacValidatorUtilityTest + { + private const string _targetPayload = "{\"test\":\"value\"}"; + private const string _hmacKey = "00112233445566778899AABBCCDDEEFF"; + + /// + /// Helper function that computes expected HMAC. + /// + private string ComputeExpectedHmac(string payload, string hexKey) + { + byte[] key = new byte[hexKey.Length / 2]; + for (int i = 0; i < hexKey.Length; i += 2) + { + key[i / 2] = Convert.ToByte(hexKey.Substring(i, 2), 16); + } + + byte[] data = Encoding.UTF8.GetBytes(payload); + using var hmac = new System.Security.Cryptography.HMACSHA256(key); + var raw = hmac.ComputeHash(data); + return Convert.ToBase64String(raw); + } + + + [TestMethod] + public void Given_GenerateBase64Sha256HmacSignature_When_Hmac_Provided_Returns_Correct_Signature() + { + // Arrange + string expected = ComputeExpectedHmac(_targetPayload, _hmacKey); + + // Act + string actual = HmacValidatorUtility.GenerateBase64Sha256HmacSignature(_targetPayload, _hmacKey); + + // Assert + Assert.AreEqual(expected, actual); + } + + [TestMethod] + public void Given_GenerateBase64Sha256HmacSignature__When_Odd_Length_HmacKey_Returns_Correct_Signature() + { + // Arrange + string paddedKey = "ABC0"; // Expected padded version + string expected = ComputeExpectedHmac(_targetPayload, paddedKey); + + // Act + string actual = HmacValidatorUtility.GenerateBase64Sha256HmacSignature(_targetPayload, "ABC"); // Will be padded to "ABC0" + + // Assert + Assert.AreEqual(expected, actual); + } + + + [TestMethod] + public void Given_IsHmacSignatureValid_When_Signature_Is_NotEqual_Returns_False() + { + // Arrange + string invalidSignature = "InvalidSignature123=="; + + // Act + // Assert + Assert.IsFalse(HmacValidatorUtility.IsHmacSignatureValid(invalidSignature, _hmacKey, _targetPayload)); + } + + + [TestMethod] + public void TestBalancePlatformHmac() + { + // Arrange + string notification = + "{\"data\":{\"balancePlatform\":\"Integration_tools_test\",\"accountId\":\"BA32272223222H5HVKTBK4MLB\",\"sweep\":{\"id\":\"SWPC42272223222H5HVKV6H8C64DP5\",\"schedule\":{\"type\":\"balance\"},\"status\":\"active\",\"targetAmount\":{\"currency\":\"EUR\",\"value\":0},\"triggerAmount\":{\"currency\":\"EUR\",\"value\":0},\"type\":\"pull\",\"counterparty\":{\"balanceAccountId\":\"BA3227C223222H5HVKT3H9WLC\"},\"currency\":\"EUR\"}},\"environment\":\"test\",\"type\":\"balancePlatform.balanceAccountSweep.updated\"}"; + string hmacKey = "D7DD5BA6146493707BF0BE7496F6404EC7A63616B7158EC927B9F54BB436765F"; + string hmacSignature = "9Qz9S/0xpar1klkniKdshxpAhRKbiSAewPpWoxKefQA="; + + // Act + bool isValidSignature = HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, hmacKey, notification); + + // Assert + Assert.IsTrue(isValidSignature); + } + + [TestMethod] + public void Given_GenerateBase64Sha256HmacSignature_When_BalancePlatform_Webhook_Returns_Correct_Signature() + { + // Arrange + string notification = + "{\"data\":{\"balancePlatform\":\"Integration_tools_test\",\"accountId\":\"BA32272223222H5HVKTBK4MLB\",\"sweep\":{\"id\":\"SWPC42272223222H5HVKV6H8C64DP5\",\"schedule\":{\"type\":\"balance\"},\"status\":\"active\",\"targetAmount\":{\"currency\":\"EUR\",\"value\":0},\"triggerAmount\":{\"currency\":\"EUR\",\"value\":0},\"type\":\"pull\",\"counterparty\":{\"balanceAccountId\":\"BA3227C223222H5HVKT3H9WLC\"},\"currency\":\"EUR\"}},\"environment\":\"test\",\"type\":\"balancePlatform.balanceAccountSweep.updated\"}"; + string hmacKey = "D7DD5BA6146493707BF0BE7496F6404EC7A63616B7158EC927B9F54BB436765F"; + string expectedHmacSignature = "9Qz9S/0xpar1klkniKdshxpAhRKbiSAewPpWoxKefQA="; + + // Act + string generatedHmacSignature = HmacValidatorUtility.GenerateBase64Sha256HmacSignature(notification, hmacKey); + + // Assert + Assert.AreEqual(expectedHmacSignature, generatedHmacSignature); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/DataProtection/DataProtectionTest.cs b/Adyen.Test/DataProtection/DataProtectionTest.cs new file mode 100644 index 000000000..d120b20e2 --- /dev/null +++ b/Adyen.Test/DataProtection/DataProtectionTest.cs @@ -0,0 +1,41 @@ +using Adyen.Core.Options; +using Adyen.DataProtection.Client; +using Adyen.DataProtection.Models; +using Adyen.DataProtection.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.DataProtection +{ + [TestClass] + public class DataProtectionTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public DataProtectionTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureDataProtection((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_SubjectErasureResponse_Returns_Not_Null_And_Correct_Enum() + { + string json = TestUtilities.GetTestFileContent("mocks/data-protection-response.json"); + + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + Assert.AreEqual(response.Result, SubjectErasureResponse.ResultEnum.ACTIVERECURRINGTOKENEXISTS); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/DataProtectionTest.cs b/Adyen.Test/DataProtectionTest.cs deleted file mode 100644 index 84d5eca6f..000000000 --- a/Adyen.Test/DataProtectionTest.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Adyen.Model.DataProtection; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class DataProtectionTest : BaseTest - { - [TestMethod] - public void TestRequestSubjectErasure() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/data-protection-response.json"); - var service = new DataProtectionService(client); - var response = service.RequestSubjectErasure(new SubjectErasureByPspReferenceRequest()); - Assert.AreEqual(response.Result, SubjectErasureResponse.ResultEnum.ACTIVERECURRINGTOKENEXISTS); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/Disputes/DisputesTest.cs b/Adyen.Test/Disputes/DisputesTest.cs new file mode 100644 index 000000000..9bcff9e7c --- /dev/null +++ b/Adyen.Test/Disputes/DisputesTest.cs @@ -0,0 +1,106 @@ +using System.Text.Json; +using Adyen.Core.Options; +using Adyen.Disputes.Client; +using Adyen.Disputes.Extensions; +using Adyen.Disputes.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.Disputes +{ + [TestClass] + public class DisputesTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public DisputesTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureDisputes((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_AcceptDispute_Returns_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/disputes/accept-dispute.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsTrue(response.DisputeServiceResult.Success); + } + + [TestMethod] + public async Task Given_Deserialize_DefendDispute_Returns_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/disputes/defend-dispute.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsTrue(response.DisputeServiceResult.Success); + } + + [TestMethod] + public async Task Given_Deserialize_DeleteDefenseDocumentResponse_Returns_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/disputes/delete-dispute.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsTrue(response.DisputeServiceResult.Success); + } + + [TestMethod] + public async Task Given_Deserialize_DefenseReasonsResponse_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/disputes/retrieve-applicable-defense-reasons.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsTrue(response.DisputeServiceResult.Success); + Assert.IsTrue(response.DefenseReasons.Count!=0); + Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[0].DefenseDocumentTypeCode, "TIDorInvoice"); + Assert.IsFalse(response.DefenseReasons[0].DefenseDocumentTypes[0].Available); + Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[0].RequirementLevel, "Optional"); + Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[1].DefenseDocumentTypeCode, "GoodsNotReturned"); + Assert.IsFalse(response.DefenseReasons[0].DefenseDocumentTypes[1].Available); + Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[1].RequirementLevel, "Required"); + Assert.AreEqual(response.DefenseReasons[0].DefenseReasonCode, "GoodsNotReturned"); + Assert.IsFalse(response.DefenseReasons[0].Satisfied); + } + + [TestMethod] + public async Task Given_Deserialize_SupplyDefenceDocumentResponse_Returns_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/disputes/supply-dispute-defense-document.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsTrue(response.DisputeServiceResult.Success); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/DisputesTest.cs b/Adyen.Test/DisputesTest.cs deleted file mode 100644 index e7cf1594c..000000000 --- a/Adyen.Test/DisputesTest.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Adyen.Model.Disputes; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class DisputesTest: BaseTest - { - [TestMethod] - public void AcceptDisputesSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/disputes/accept-disputes.json"); - var disputes = new DisputesService(client); - var response = disputes.AcceptDispute(new AcceptDisputeRequest()); - Assert.IsTrue(response.DisputeServiceResult.Success); - } - - [TestMethod] - public void DefendDisputesSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/disputes/defend-dispute.json"); - var disputes = new DisputesService(client); - var response = disputes.DefendDispute(new DefendDisputeRequest()); - Assert.IsTrue(response.DisputeServiceResult.Success); - } - - [TestMethod] - public void DeleteDisputesSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/disputes/delete-dispute.json"); - var disputes = new DisputesService(client); - var response = disputes.DeleteDisputeDefenseDocument(new DeleteDefenseDocumentRequest()); - Assert.IsTrue(response.DisputeServiceResult.Success); - } - - [TestMethod] - public void RetrieveApplicableDefenseReasonsSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/disputes/retrieve-appicable-defense-reasons.json"); - var disputes = new DisputesService(client); - var response = disputes.RetrieveApplicableDefenseReasons(new DefenseReasonsRequest()); - Assert.IsTrue(response.DisputeServiceResult.Success); - Assert.IsTrue(response.DefenseReasons.Count!=0); - Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[0].DefenseDocumentTypeCode, "TIDorInvoice"); - Assert.IsFalse(response.DefenseReasons[0].DefenseDocumentTypes[0].Available); - Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[0].RequirementLevel, "Optional"); - Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[1].DefenseDocumentTypeCode, "GoodsNotReturned"); - Assert.IsFalse(response.DefenseReasons[0].DefenseDocumentTypes[1].Available); - Assert.AreEqual(response.DefenseReasons[0].DefenseDocumentTypes[1].RequirementLevel, "Required"); - Assert.AreEqual(response.DefenseReasons[0].DefenseReasonCode, "GoodsNotReturned"); - Assert.IsFalse(response.DefenseReasons[0].Satisfied); - } - - [TestMethod] - public void SupplyDisputesDefenceDocumentSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/disputes/supply-dispute-defense-document.json"); - var disputes = new DisputesService(client); - var response = disputes.SupplyDefenseDocument(new SupplyDefenseDocumentRequest()); - Assert.IsTrue(response.DisputeServiceResult.Success); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/ExtensionsTest.cs b/Adyen.Test/ExtensionsTest.cs deleted file mode 100644 index defc01802..000000000 --- a/Adyen.Test/ExtensionsTest.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections.Generic; -using System.Net.Http; -using Adyen.Model.BalanceControl; -using Adyen.Model.Checkout; -using Adyen.Service; -using Adyen.Service.BalancePlatform; -using Adyen.Service.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; -using Environment = Adyen.Model.Environment; - -namespace Adyen.Test -{ - [TestClass] - public class ExtensionsTest : BaseTest - { - private Client _client; - - [TestInitialize] - public void Init() - { - _client = CreateMockTestClientApiKeyBasedRequestAsync(""); - _client.Config.Environment = Environment.Live; - _client.Config.LiveEndpointUrlPrefix = "prefix"; - } - - [TestMethod] - public void TestDeviceRenderOptionsObjectListToString() - { - var deviceRenderOptions = new DeviceRenderOptions - { - SdkInterface = DeviceRenderOptions.SdkInterfaceEnum.Native, - SdkUiType = new List - { DeviceRenderOptions.SdkUiTypeEnum.MultiSelect, DeviceRenderOptions.SdkUiTypeEnum.OtherHtml } - }; - var expected = "\"multiSelect\""; - Assert.IsTrue(deviceRenderOptions.ToJson().Contains(expected)); - } - - [TestMethod] - public void TestPalLiveEndPoint() - { - var service = new BalanceControlService(_client); - service.BalanceTransfer(new BalanceTransferRequest()); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://prefix-pal-live.adyenpayments.com/pal/servlet/BalanceControl/v1/balanceTransfer", - "{}", null, HttpMethod.Post, default); - } - - [TestMethod] - public void TestCheckoutLiveEndPoint() - { - var service = new DonationsService(_client); - service.Donations(new DonationPaymentRequest()); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://prefix-checkout-live.adyenpayments.com/checkout/v71/donations", - Arg.Any(), null, HttpMethod.Post, default); - } - - [TestMethod] - public void TestBclLiveEndPoint() - { - var service = new AccountHoldersService(_client); - service.GetAllBalanceAccountsOfAccountHolder("id", offset: 3, limit: 5); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://balanceplatform-api-live.adyen.com/bcl/v2/accountHolders/id/balanceAccounts?offset=3&limit=5", - null, null, HttpMethod.Get, default); - } - } -} diff --git a/Adyen.Test/GrantsTest.cs b/Adyen.Test/GrantsTest.cs deleted file mode 100644 index 3728fcc48..000000000 --- a/Adyen.Test/GrantsTest.cs +++ /dev/null @@ -1,22 +0,0 @@ - -using Adyen.Model.Transfers; -using Adyen.Service.Transfers; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - public class GrantsTest : BaseTest - { - [TestMethod] - public void StoredValueIssueTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/grants/post-grants-success.json"); - var service = new CapitalService(client); - var response = service.RequestGrantPayout(new CapitalGrantInfo()); - Assert.AreEqual(response.Id, "CG00000000000000000000001"); - Assert.AreEqual(response.GrantAccountId, "CG00000000000000000000001"); - Assert.AreEqual(response.Status, CapitalGrant.StatusEnum.Pending); - Assert.IsNotNull(response.Balances); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/HttpClientWrapperTest.cs b/Adyen.Test/HttpClientWrapperTest.cs deleted file mode 100644 index 0704beec8..000000000 --- a/Adyen.Test/HttpClientWrapperTest.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Adyen.HttpClient; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class HttpClientWrapperTest : BaseTest - { - [TestMethod] - public void EmptyRequestBodyPostTest() - { - var configWithApiKey = new Config - { - Environment = Model.Environment.Test, - XApiKey = "AQEyhmfxK....LAG84XwzP5pSpVd" - }; - var mockHttpMessageHandler = new MockHttpMessageHandler("{}", System.Net.HttpStatusCode.OK); - var httpClient = new System.Net.Http.HttpClient(mockHttpMessageHandler); - var httpClientWrapper = new HttpClientWrapper(configWithApiKey, httpClient); - var _ = httpClientWrapper.Request("https://test.com/testpath", null, null, HttpMethod.Post); - Assert.AreEqual("{}", mockHttpMessageHandler.Input); - } - - } -} \ No newline at end of file diff --git a/Adyen.Test/LegalEntityManagement/BusinessLines/BusinessLineTest.cs b/Adyen.Test/LegalEntityManagement/BusinessLines/BusinessLineTest.cs new file mode 100644 index 000000000..3ec95bbd9 --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/BusinessLines/BusinessLineTest.cs @@ -0,0 +1,49 @@ +using System.Text.Json; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Adyen.Test.LegalEntityManagement.BusinessLines +{ + [TestClass] + public class BusinessLineTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public BusinessLineTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + /// + /// Test DeserializeBusinessLine + /// + [TestMethod] + public void DeserializeBusinessLine() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/BusinessLine.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result); + } + + + } +} diff --git a/Adyen.Test/LegalEntityManagement/Documents/DocumentTest.cs b/Adyen.Test/LegalEntityManagement/Documents/DocumentTest.cs new file mode 100644 index 000000000..6d86f1257 --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/Documents/DocumentTest.cs @@ -0,0 +1,157 @@ +using System.Net; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Adyen.LegalEntityManagement.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.Documents +{ + [TestClass] + public class DocumentTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly IDocumentsService _documentsService; + + public DocumentTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _documentsService = Substitute.For(); + } + + /// + /// Test deserializeDocument + /// + [TestMethod] + public async Task DeserializeDocument() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/Document.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result); + } + + /// + /// Test UpdateDocument + /// + [TestMethod] + public async Task UpdateDocument() + { + + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/Document.json"); + var document = new Document + { + Attachment = new Attachment() + }; + + _documentsService.UpdateDocumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new DocumentsService.UpdateDocumentApiResponse( + NullLogger.Instance, + new HttpRequestMessage(), + new HttpResponseMessage(), + json, + "/documents/DOC01234", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + IUpdateDocumentApiResponse response = await _documentsService.UpdateDocumentAsync("DOC01234", null, new RequestOptions(), CancellationToken.None); + + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(Document.TypeEnum.DriversLicense, response.Ok().Type); + } + + /// + /// Test UploadDocumentForVerificationChecksAsync + /// + [TestMethod] + public async Task UploadDocumentForVerificationChecksAsyncTest() + { + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/Document.json"); + var document = new Document + { + Attachment = new Attachment() + }; + _documentsService.UploadDocumentForVerificationChecksAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new DocumentsService.UploadDocumentForVerificationChecksApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage(), + json, + "/documents", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + IUploadDocumentForVerificationChecksApiResponse response = await _documentsService.UploadDocumentForVerificationChecksAsync(new Option(document), new RequestOptions().AddxRequestedVerificationCodeHeader("xRequestedVerificationCode"), CancellationToken.None); + + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(Document.TypeEnum.DriversLicense, response.Ok().Type); + } + + /// + /// Test DeleteDocumentAsync + /// + [TestMethod] + public async Task DeleteDocumentAsyncTest() + { + var documentId = "DOC01234"; + _documentsService.DeleteDocumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new DocumentsService.DeleteDocumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent }, + "", // Empty content for 204 No Content + $"/documents/{documentId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + IDeleteDocumentApiResponse response = await _documentsService.DeleteDocumentAsync(documentId); + + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + Assert.IsTrue(response.IsNoContent); + } + + } +} diff --git a/Adyen.Test/LegalEntityManagement/HostedOnboarding/HostedOnboardingTest.cs b/Adyen.Test/LegalEntityManagement/HostedOnboarding/HostedOnboardingTest.cs new file mode 100644 index 000000000..44d18f2e5 --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/HostedOnboarding/HostedOnboardingTest.cs @@ -0,0 +1,140 @@ +using System.Net; +using Adyen.Core; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.HostedOnboarding +{ + [TestClass] + public class HostedOnboardingTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly IHostedOnboardingService _hostedOnboardingService; + + public HostedOnboardingTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _hostedOnboardingService = Substitute.For(); + } + + [TestMethod] + public async Task GetLinkToAdyenHostedOnboardingPageAsyncTest() + { + // Arrange + var json = "{\"url\":\"https://test.adyen.com/checkout/123\",\"expiresAt\":\"2025-12-31T23:59:59Z\"}"; + var legalEntityId = "LE12345"; + var onboardingLinkInfo = new OnboardingLinkInfo(); + + _hostedOnboardingService.GetLinkToAdyenhostedOnboardingPageAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new HostedOnboardingService.GetLinkToAdyenhostedOnboardingPageApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/onboardingLinks", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _hostedOnboardingService.GetLinkToAdyenhostedOnboardingPageAsync(legalEntityId, new Option(onboardingLinkInfo), null, CancellationToken.None); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var onboardingLink = response.Ok(); + Assert.IsNotNull(onboardingLink); + Assert.AreEqual("https://test.adyen.com/checkout/123", onboardingLink.Url); + } + + [TestMethod] + public async Task GetOnboardingLinkThemeAsyncTest() + { + // Arrange + var json = "{\"createdAt\":\"2022-10-31T01:30:00+01:00\",\"description\":\"string\",\"id\":\"SE322KT223222D5FJ7TJN2986\",\"properties\":{\"sample\":\"string\"},\"updatedAt\":\"2022-10-31T01:30:00+01:00\"}"; + var themeId = "SE322KT223222D5FJ7TJN2986"; + + _hostedOnboardingService.GetOnboardingLinkThemeAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new HostedOnboardingService.GetOnboardingLinkThemeApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/themes/{themeId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _hostedOnboardingService.GetOnboardingLinkThemeAsync(themeId); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var onboardingTheme = response.Ok(); + Assert.IsNotNull(onboardingTheme); + Assert.AreEqual(themeId, onboardingTheme.Id); + } + + [TestMethod] + public async Task ListHostedOnboardingPageThemesAsyncTest() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/OnboardingThemes.json"); + + _hostedOnboardingService.ListHostedOnboardingPageThemesAsync( + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new HostedOnboardingService.ListHostedOnboardingPageThemesApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + "/themes", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _hostedOnboardingService.ListHostedOnboardingPageThemesAsync(); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var onboardingThemes = response.Ok(); + Assert.IsNotNull(onboardingThemes); + Assert.AreEqual(1, onboardingThemes.Themes.Count); + Assert.AreEqual("SE322KT223222D5FJ7TJN2986", onboardingThemes.Themes[0].Id); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/LegalEntityManagement/LegalEntities/LegalEntityTest.cs b/Adyen.Test/LegalEntityManagement/LegalEntities/LegalEntityTest.cs new file mode 100644 index 000000000..5d1e5067b --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/LegalEntities/LegalEntityTest.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.LegalEntities +{ + [TestClass] + public class LegalEntityTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly ILegalEntitiesService _legalEntitiesService; + + public LegalEntityTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _legalEntitiesService = Substitute.For(); + + } + + /// + /// Test DeserializeLegalEntity + /// + [TestMethod] + public async Task DeserializeLegalEntity() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/LegalEntity.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual("LE322JV223222D5GG42KN6869", result.Id); + } + + /// + /// Test DeserializeLegalEntityBusinessLines + /// + [TestMethod] + public async Task DeserializeLegalEntityBusinessLines() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/LegalEntityBusinessLines.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result); + Assert.AreEqual(2, result.VarBusinessLines.Count); + } + + /// + /// Test GetLegalEntity + /// + [TestMethod] + public async Task GetLegalEntity() + { + string json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/LegalEntity.json"); + + _legalEntitiesService.GetLegalEntityAsync(Arg.Any()) + .Returns( + Task.FromResult( + new LegalEntitiesService.GetLegalEntityApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage(), + json, + "/documents/DOC01234", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + IGetLegalEntityApiResponse response = await _legalEntitiesService.GetLegalEntityAsync("LE322JV223222D5GG42KN6869"); + + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual("LE322JV223222D5GG42KN6869", response.Ok().Id); + } + + } +} diff --git a/Adyen.Test/LegalEntityManagement/PCIQuestionnaires/PCIQuestionnairesTest.cs b/Adyen.Test/LegalEntityManagement/PCIQuestionnaires/PCIQuestionnairesTest.cs new file mode 100644 index 000000000..f22283aec --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/PCIQuestionnaires/PCIQuestionnairesTest.cs @@ -0,0 +1,217 @@ +using System.Net; +using Adyen.Core; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.PCIQuestionnaires +{ + [TestClass] + public class PCIQuestionnairesTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly IPCIQuestionnairesService _pciQuestionnairesService; + + public PCIQuestionnairesTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _pciQuestionnairesService = Substitute.For(); + } + + [TestMethod] + public async Task CalculatePciStatusOfLegalEntityAsyncTest() + { + // Arrange + var json = "{\"signingRequired\": true}"; + var legalEntityId = "LE123"; + var request = new CalculatePciStatusRequest(); + + _pciQuestionnairesService.CalculatePciStatusOfLegalEntityAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PCIQuestionnairesService.CalculatePciStatusOfLegalEntityApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/pciQuestionnaires/signingRequired", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _pciQuestionnairesService.CalculatePciStatusOfLegalEntityAsync(legalEntityId, new Option(request)); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.IsTrue(result.SigningRequired); + } + + [TestMethod] + public async Task GeneratePciQuestionnaireAsyncTest() + { + // Arrange + var json = "{\n \"content\": \"JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBv+f/ub0j6JPRX+E3EmC==\",\n \"language\": \"fr\",\n \"pciTemplateReferences\": [\n \"PCIT-T7KC6VGL\",\n \"PCIT-PKB6DKS4\"\n ]\n}"; + var legalEntityId = "LE123"; + var request = new GeneratePciDescriptionRequest(); + + _pciQuestionnairesService.GeneratePciQuestionnaireAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PCIQuestionnairesService.GeneratePciQuestionnaireApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/pciQuestionnaires/generatePciTemplates", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _pciQuestionnairesService.GeneratePciQuestionnaireAsync(legalEntityId, new Option(request)); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual("fr", result.Language); + Assert.AreEqual(2, result.PciTemplateReferences.Count); + } + + [TestMethod] + public async Task GetPciQuestionnaireAsyncTest() + { + // Arrange + var json = "{\n \"content\": \"JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBv+f/ub0j6JPRX+E3EmC==\",\n \"createdAt\": \"2023-03-02T17:54:19.538365Z\",\n \"id\": \"PCID422GZ22322565HHMH48CW63CPH\",\n \"validUntil\": \"2024-03-01T17:54:19.538365Z\"\n}"; + var legalEntityId = "LE123"; + var pciId = "PCI123"; + + _pciQuestionnairesService.GetPciQuestionnaireAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PCIQuestionnairesService.GetPciQuestionnaireApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/pciQuestionnaires/{pciId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _pciQuestionnairesService.GetPciQuestionnaireAsync(legalEntityId, pciId); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual("PCID422GZ22322565HHMH48CW63CPH", result.Id); + } + + [TestMethod] + public async Task GetPciQuestionnaireDetailsAsyncTest() + { + // Arrange + var json = "{\n \"data\": [\n {\n \"createdAt\": \"2023-03-02T17:54:19.538365Z\",\n \"id\": \"PCID422GZ22322565HHMH48CW63CPH\",\n \"validUntil\": \"2024-03-01T17:54:19.538365Z\"\n },\n {\n \"createdAt\": \"2023-03-02T17:54:19.538365Z\",\n \"id\": \"PCID422GZ22322565HHMH49CW75Z9H\",\n \"validUntil\": \"2024-03-01T17:54:19.538365Z\"\n }\n ]\n}"; + var legalEntityId = "LE123"; + + _pciQuestionnairesService.GetPciQuestionnaireDetailsAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PCIQuestionnairesService.GetPciQuestionnaireDetailsApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/pciQuestionnaires", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _pciQuestionnairesService.GetPciQuestionnaireDetailsAsync(legalEntityId); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.IsNotNull(result.Data); + Assert.AreEqual(2, result.Data.Count); + } + + [TestMethod] + public async Task SignPciQuestionnaireAsyncTest() + { + // Arrange + var json = "{\n \"pciQuestionnaireIds\": [\n \"PCID422GZ22322565HHMH48CW63CPH\",\n \"PCID422GZ22322565HHMH49CW75Z9H\"\n ]\n}"; + var legalEntityId = "LE123"; + var request = new PciSigningRequest(); + + _pciQuestionnairesService.SignPciQuestionnaireAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new PCIQuestionnairesService.SignPciQuestionnaireApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/pciQuestionnaires/signPciTemplates", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _pciQuestionnairesService.SignPciQuestionnaireAsync(legalEntityId, new Option(request)); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual(2, result.PciQuestionnaireIds.Count); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/LegalEntityManagement/TermsOfService/TermsOfServiceTest.cs b/Adyen.Test/LegalEntityManagement/TermsOfService/TermsOfServiceTest.cs new file mode 100644 index 000000000..5bdc75f02 --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/TermsOfService/TermsOfServiceTest.cs @@ -0,0 +1,216 @@ +using System.Net; +using Adyen.Core; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.TermsOfService +{ + [TestClass] + public class TermsOfServiceTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly ITermsOfServiceService _termsOfServiceService; + + public TermsOfServiceTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _termsOfServiceService = Substitute.For(); + } + + [TestMethod] + public async Task AcceptTermsOfServiceAsyncTest() + { + // Arrange + var json = "{\"id\":\"TOS123\",\"type\":\"adyenIssuing\",\"acceptedBy\":\"user\",\"acceptedFor\":\"LE123\"}"; + var legalEntityId = "LE123"; + var tosDocumentId = "TOSDOC123"; + var request = new AcceptTermsOfServiceRequest(); + + _termsOfServiceService.AcceptTermsOfServiceAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TermsOfServiceService.AcceptTermsOfServiceApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/termsOfService/{tosDocumentId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _termsOfServiceService.AcceptTermsOfServiceAsync(legalEntityId, tosDocumentId, new Option(request)); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual("TOS123", result.Id); + } + + [TestMethod] + public async Task GetAcceptedTermsOfServiceDocumentAsyncTest() + { + // Arrange + var json = "{\"id\":\"LE123\", \"document\":\"document-content\"}"; + var legalEntityId = "LE123"; + var tosAcceptanceRef = "TOSREF123"; + + _termsOfServiceService.GetAcceptedTermsOfServiceDocumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any>(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TermsOfServiceService.GetAcceptedTermsOfServiceDocumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/acceptedTermsOfServiceDocument/{tosAcceptanceRef}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _termsOfServiceService.GetAcceptedTermsOfServiceDocumentAsync(legalEntityId, tosAcceptanceRef, "JSON"); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual("LE123", result.Id); + } + + [TestMethod] + public async Task GetTermsOfServiceDocumentAsyncTest() + { + // Arrange + var json = "{\"id\":\"LE123\", \"document\":\"document-content\"}"; + var legalEntityId = "LE123"; + var request = new GetTermsOfServiceDocumentRequest(); + + _termsOfServiceService.GetTermsOfServiceDocumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TermsOfServiceService.GetTermsOfServiceDocumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/termsOfService", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _termsOfServiceService.GetTermsOfServiceDocumentAsync(legalEntityId, new Option(request)); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual("LE123", result.Id); + } + + [TestMethod] + public async Task GetTermsOfServiceInformationForLegalEntityAsyncTest() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/TermsOfServiceStatus.json"); + var legalEntityId = "LE123"; + + _termsOfServiceService.GetTermsOfServiceInformationForLegalEntityAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TermsOfServiceService.GetTermsOfServiceInformationForLegalEntityApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/termsOfServiceAcceptanceInfos", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _termsOfServiceService.GetTermsOfServiceInformationForLegalEntityAsync(legalEntityId); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual(1, result.Data.Count); + } + + [TestMethod] + public async Task GetTermsOfServiceStatusAsyncTest() + { + // Arrange + var json = "{\"termsOfServiceTypes\":[\"adyenIssuing\"]}"; + var legalEntityId = "LE123"; + + _termsOfServiceService.GetTermsOfServiceStatusAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TermsOfServiceService.GetTermsOfServiceStatusApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/legalEntities/{legalEntityId}/termsOfServiceStatus", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = await _termsOfServiceService.GetTermsOfServiceStatusAsync(legalEntityId); + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var result = response.Ok(); + Assert.IsNotNull(result); + Assert.AreEqual(1, response.Ok().TermsOfServiceTypes.Count); + } + } +} diff --git a/Adyen.Test/LegalEntityManagement/TransferInstruments/TransferInstrumentsTest.cs b/Adyen.Test/LegalEntityManagement/TransferInstruments/TransferInstrumentsTest.cs new file mode 100644 index 000000000..e22c3fddd --- /dev/null +++ b/Adyen.Test/LegalEntityManagement/TransferInstruments/TransferInstrumentsTest.cs @@ -0,0 +1,173 @@ +using System.Net; +using Adyen.Core; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; + +namespace Adyen.Test.LegalEntityManagement.TransferInstruments +{ + [TestClass] + public class TransferInstrumentsTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + private readonly ITransferInstrumentsService _transferInstrumentsService; + + public TransferInstrumentsTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + _transferInstrumentsService = Substitute.For(); + } + + [TestMethod] + public void CreateTransferInstrumentAsyncTest() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/TransferInstrument.json"); + var transferInstrumentInfo = new TransferInstrumentInfo(); + + _transferInstrumentsService.CreateTransferInstrumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TransferInstrumentsService.CreateTransferInstrumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + "/transferInstruments", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = _transferInstrumentsService.CreateTransferInstrumentAsync(new Option(transferInstrumentInfo), new RequestOptions().AddxRequestedVerificationCodeHeader("x-requested-verification-code"), CancellationToken.None).Result; + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var transferInstrument = response.Ok(); + Assert.IsNotNull(transferInstrument); + Assert.AreEqual("SE576BH223222F5GJVKHH6BDT", transferInstrument.Id); + Assert.AreEqual("LE322KH223222D5GG4C9J83RN", transferInstrument.LegalEntityId); + } + + [TestMethod] + public void GetTransferInstrumentAsyncTest() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/TransferInstrument.json"); + var transferInstrumentId = "SE576BH223222F5GJVKHH6BDT"; + + _transferInstrumentsService.GetTransferInstrumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TransferInstrumentsService.GetTransferInstrumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/transferInstruments/{transferInstrumentId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = _transferInstrumentsService.GetTransferInstrumentAsync(transferInstrumentId, new RequestOptions(), CancellationToken.None).Result; + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var transferInstrument = response.Ok(); + Assert.IsNotNull(transferInstrument); + Assert.AreEqual(transferInstrumentId, transferInstrument.Id); + } + + [TestMethod] + public void UpdateTransferInstrumentAsyncTest() + { + // Arrange + var json = TestUtilities.GetTestFileContent("mocks/legalentitymanagement/TransferInstrument.json"); + var transferInstrumentId = "SE576BH223222F5GJVKHH6BDT"; + var transferInstrumentInfo = new TransferInstrumentInfo(); + + _transferInstrumentsService.UpdateTransferInstrumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TransferInstrumentsService.UpdateTransferInstrumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.OK }, + json, + $"/transferInstruments/{transferInstrumentId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = _transferInstrumentsService.UpdateTransferInstrumentAsync(transferInstrumentId, new Option(transferInstrumentInfo), new RequestOptions().AddxRequestedVerificationCodeHeader("x-requested-verification-code"), CancellationToken.None).Result; + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var transferInstrument = response.Ok(); + Assert.IsNotNull(transferInstrument); + Assert.AreEqual(transferInstrumentId, transferInstrument.Id); + } + + [TestMethod] + public void DeleteTransferInstrumentAsyncTest() + { + // Arrange + var transferInstrumentId = "SE576BH223222F5GJVKHH6BDT"; + + _transferInstrumentsService.DeleteTransferInstrumentAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns( + Task.FromResult( + new TransferInstrumentsService.DeleteTransferInstrumentApiResponse( + Substitute.For>(), + new HttpRequestMessage(), + new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent }, + "", + $"/transferInstruments/{transferInstrumentId}", + DateTime.UtcNow, + _jsonSerializerOptionsProvider.Options) + )); + + // Act + var response = _transferInstrumentsService.DeleteTransferInstrumentAsync(transferInstrumentId).Result; + + // Assert + Assert.IsNotNull(response); + Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + Assert.IsTrue(response.IsNoContent); + } + } +} diff --git a/Adyen.Test/LegalEntityManagementTest.cs b/Adyen.Test/LegalEntityManagementTest.cs deleted file mode 100644 index aeee74d93..000000000 --- a/Adyen.Test/LegalEntityManagementTest.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using Adyen.Model.LegalEntityManagement; -using Adyen.Service.LegalEntityManagement; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; - -namespace Adyen.Test -{ - [TestClass] - public class LegalEntityManagementTest : BaseTest - { - #region Document - /// - /// Test createDocument - /// - [TestMethod] - public void CreateDocument() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/Document.json"); - var service = new DocumentsService(client); - var document = new Document - { - Attachment = new Attachment() - }; - var response = service.UploadDocumentForVerificationChecks(document); - Assert.AreEqual(Encoding.ASCII.GetString(response.Attachments[0].Content), "This is a string"); - Assert.AreEqual(response.Id, "SE322KT223222D5FJ7TJN2986"); - } - - /// - /// Test createDocument - /// - [TestMethod] - public void UpdateDocument() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/Document.json"); - var service = new DocumentsService(client); - var document = new Document - { - Attachment = new Attachment() - }; - var response = service.UpdateDocument("SE322KT223222D5FJ7TJN2986",document); - Assert.AreEqual(Encoding.ASCII.GetString(response.Attachments[0].Content), "This is a string"); - Assert.AreEqual(response.Id, "SE322KT223222D5FJ7TJN2986"); - - } - - /// - /// Test deleteDocument - /// - [TestMethod] - public void DeleteDocumentTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/Document.json"); - var service = new DocumentsService(client); - service.DeleteDocument("SE322KT223222D5FJ7TJN2986"); - - } - #endregion - - #region TransferInstruments - /// - /// Test createTransferInstruments - /// - [TestMethod] - public void CreateTransferInstrumentsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/TransferInstrument.json"); - var service = new TransferInstrumentsService(client); - var transferInstrumentInfo = new TransferInstrumentInfo - { - LegalEntityId = "", - Type = TransferInstrumentInfo.TypeEnum.BankAccount - }; - var response = service.CreateTransferInstrument(transferInstrumentInfo); - Assert.AreEqual(response.LegalEntityId, "LE322KH223222D5GG4C9J83RN"); - Assert.AreEqual(response.Id, "SE576BH223222F5GJVKHH6BDT"); - } - /// - /// Test updateTransferInstruments - /// - [TestMethod] - public void UpdateTransferInstrumentsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/TransferInstrument.json"); - var service = new TransferInstrumentsService(client); - var transferInstrumentInfo = new TransferInstrumentInfo - { - LegalEntityId = "", - Type = TransferInstrumentInfo.TypeEnum.BankAccount - }; - var task = service.UpdateTransferInstrumentAsync("SE576BH223222F5GJVKHH6BDT", transferInstrumentInfo); - var response = task.Result; - Assert.AreEqual(response.LegalEntityId, "LE322KH223222D5GG4C9J83RN"); - Assert.AreEqual(response.Id, "SE576BH223222F5GJVKHH6BDT"); - } - #endregion - - #region HostedOnboarding - /// - /// Test hostedOnboarding - /// - [TestMethod] - public void ListThemesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/OnboardingThemes.json"); - var service = new HostedOnboardingService(client); - var task = service.ListHostedOnboardingPageThemesAsync(); - var response = task.Result; - Assert.AreEqual(response.Themes[0].Id, "SE322KT223222D5FJ7TJN2986"); - Assert.AreEqual(response.Themes[0].CreatedAt, DateTime.Parse("2022-10-31T01:30:00+01:00")); - } - #endregion - - #region LegalEntities - /// - /// Test update LegalEntities - /// - [TestMethod] - public void UpdateLegalEntitiesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/LegalEntity.json"); - var service = new LegalEntitiesService(client); - var legalEntityInfo = new LegalEntityInfo - { - Organization = new Organization(), - Type = LegalEntityInfo.TypeEnum.Individual, - EntityAssociations = new List(), - SoleProprietorship = new SoleProprietorship() - }; - var response = service.UpdateLegalEntity("LE322JV223222D5GG42KN6869", legalEntityInfo); - Assert.AreEqual(response.Id, "LE322JV223222D5GG42KN6869"); - Assert.AreEqual(response.Type, LegalEntity.TypeEnum.Individual); - } - #endregion - - #region LegalEntities - /// - /// Test update BusinessLines - /// - [TestMethod] - public void UpdateBusinessLinesTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/BusinessLine.json"); - var service = new BusinessLinesService(client); - var businessLine = new BusinessLineInfoUpdate - { - IndustryCode = "124rrdfer", - SourceOfFunds = new SourceOfFunds() - }; - var response = service.UpdateBusinessLine("SE322KT223222D5FJ7TJN2986", businessLine); - Assert.AreEqual(response.Id, "SE322KT223222D5FJ7TJN2986"); - Assert.AreEqual(response.IndustryCode, "55"); - } - #endregion - - #region TermsOfService - /// - /// Test get TermsOfService Status - /// - [TestMethod] - public void GetTermsOfServiceStatus() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/legalentitymanagement/TermsOfServiceStatus.json"); - var service = new TermsOfServiceService(client); - var response = service.GetTermsOfServiceInformationForLegalEntity("id123"); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://kyc-test.adyen.com/lem/v3/legalEntities/id123/termsOfServiceAcceptanceInfos", - null, - null, - new HttpMethod("GET"), default); - Assert.AreEqual(response.Data[0].Type, TermsOfServiceAcceptanceInfo.TypeEnum.AdyenIssuing); - } - #endregion - } -} diff --git a/Adyen.Test/Management/ManagementTest.cs b/Adyen.Test/Management/ManagementTest.cs new file mode 100644 index 000000000..5e22a69d9 --- /dev/null +++ b/Adyen.Test/Management/ManagementTest.cs @@ -0,0 +1,113 @@ +using Adyen.Core.Options; +using Adyen.Management.Client; +using Adyen.Management.Extensions; +using Adyen.Management.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.Management +{ + [TestClass] + public class ManagementTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public ManagementTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_MeApiCredential_Result_Return_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/management/me.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("S2-6262224667", response.Id); + Assert.IsTrue(response.Active); + Assert.AreEqual("Management API - Users read and write", response.Roles[0]); + } + + [TestMethod] + public async Task Given_Deserialize_When_ListMerchantResponse_Returns_Correct_Data() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/management/list-merchant-accounts.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(22, response.ItemsTotal); + Assert.AreEqual("YOUR_MERCHANT_ACCOUNT_1", response.Data[0].Id); + } + + [TestMethod] + public async Task Given_Deserialize_When_UpdateResource_Returns_Data_String() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/management/logo.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("BASE-64_ENCODED_STRING_FROM_THE_REQUEST", response.Data); + } + + [TestMethod] + public async Task Given_Deserialize_When_ListTerminalsResponse_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/management/list-terminals.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(2, response.Data.Count); + Assert.AreEqual("V400m-080020970", response.Data.First(o => o.SerialNumber == "080-020-970").Id); + } + + [TestMethod] + public void Given_Serialize_When_TerminalSettings_Includes_Null_Surcharge() + { + // Arrange + TerminalSettings terminalSettings = new TerminalSettings( + localization: new Localization("it"), + surcharge: null + ); + + // Act + string target = JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptionsProvider.Options); + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + + Assert.IsNotNull(terminalSettings.Localization); + JsonElement localizationElement = root.GetProperty("localization"); + Assert.AreEqual("it", localizationElement.GetProperty("language").GetString()); + + // must include surcharge as null + Assert.IsTrue(target.Contains("\"surcharge\":null")); + // must not include gratuities + Assert.IsFalse(target.Contains("gratuities")); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/ManagementTest.cs b/Adyen.Test/ManagementTest.cs deleted file mode 100644 index 010c79ba1..000000000 --- a/Adyen.Test/ManagementTest.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using Adyen.Model.Management; -using Adyen.Service.Management; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; - -namespace Adyen.Test -{ - [TestClass] - public class ManagementTest : BaseTest - { - [TestMethod] - public void Me() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/management/me.json"); - var service = new MyAPICredentialService(client); - - var response = service.GetApiCredentialDetails(); - - Assert.AreEqual("S2-6262224667", response.Id); - Assert.IsTrue(response.Active); - Assert.AreEqual("Management API - Users read and write", response.Roles[0]); - } - - [TestMethod] - public void ListMerchantAccounts() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/management/list-merchant-accounts.json"); - var service = new AccountCompanyLevelService(client); - - var response = service.ListMerchantAccounts("ABC123", 1, 10); - - Assert.AreEqual(22, response.ItemsTotal); - Assert.AreEqual("YOUR_MERCHANT_ACCOUNT_1", response.Data[0].Id); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://management-test.adyen.com/v3/companies/ABC123/merchants?pageNumber=1&pageSize=10", null, null, - HttpMethod.Get, default); - } - - [TestMethod] - public async Task UpdateResource() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/management/logo.json"); - var service = new TerminalSettingsCompanyLevelService(client); - - var logo = await service.UpdateTerminalLogoAsync("123ABC", "E355", new Logo("base64")); - - Assert.AreEqual("BASE-64_ENCODED_STRING_FROM_THE_REQUEST", logo.Data); - await ClientInterfaceSubstitute.Received().RequestAsync( - "https://management-test.adyen.com/v3/companies/123ABC/terminalLogos?model=E355", - Arg.Any(), - null, - new HttpMethod("PATCH"), default); - } - - [TestMethod] - public void ListTerminals() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/management/list-terminals.json"); - var service = new TerminalsTerminalLevelService(client); - - var terminals = service.ListTerminals(searchQuery: "ABC OR 123", pageSize: 2); - - Assert.AreEqual(2, terminals.Data.Count); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://management-test.adyen.com/v3/terminals?searchQuery=ABC+OR+123&pageSize=2", - null, null, new HttpMethod("GET"), default); - var terminal = - from o in terminals.Data - where o.SerialNumber == "080-020-970" - select o; - Assert.AreEqual("V400m-080020970", terminal.First().Id); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/ManagementWebhookHandlerTest.cs b/Adyen.Test/ManagementWebhookHandlerTest.cs new file mode 100644 index 000000000..0c891d80f --- /dev/null +++ b/Adyen.Test/ManagementWebhookHandlerTest.cs @@ -0,0 +1,124 @@ +// using System; +// using Adyen.Model.ManagementWebhooks; +// using Adyen.Webhooks; +// using Microsoft.VisualStudio.TestTools.UnitTesting; +// +// namespace Adyen.Test.WebhooksTests +// { +// [TestClass] +// public class ManagementWebhookHandlerTest : BaseTest +// { +// private readonly ManagementWebhookHandler _managementWebhookHandler = new ManagementWebhookHandler(); +// +// [TestMethod] +// public void Test_Management_Webhook_PaymentMethodCreated() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'createdAt': '2022-01-24T14:59:11+01:00', +// 'data': { +// 'id': 'PM3224R223224K5FH4M2K9B86', +// 'merchantId': 'MERCHANT_ACCOUNT', +// 'status': 'SUCCESS', +// 'storeId': 'ST322LJ223223K5F4SQNR9XL5', +// 'type': 'visa' +// }, +// 'environment': 'test', +// 'type': 'paymentMethod.created' +// }"; +// // Act +// _managementWebhookHandler.GetPaymentMethodCreatedNotificationRequest(jsonPayload, out PaymentMethodCreatedNotificationRequest paymentMethodCreatedWebhook); +// +// // Assert +// Assert.IsNotNull(paymentMethodCreatedWebhook); +// Assert.AreEqual(PaymentMethodCreatedNotificationRequest.TypeEnum.PaymentMethodCreated, paymentMethodCreatedWebhook.Type); +// Assert.AreEqual(paymentMethodCreatedWebhook.Data.Id, "PM3224R223224K5FH4M2K9B86"); +// Assert.AreEqual(paymentMethodCreatedWebhook.Data.MerchantId, "MERCHANT_ACCOUNT"); +// Assert.AreEqual(paymentMethodCreatedWebhook.Data.Status, MidServiceNotificationData.StatusEnum.Success); +// Assert.AreEqual(paymentMethodCreatedWebhook.Data.StoreId, "ST322LJ223223K5F4SQNR9XL5"); +// Assert.AreEqual(paymentMethodCreatedWebhook.Data.Type, "visa"); +// Assert.AreEqual(DateTime.Parse("2022-01-24T14:59:11+01:00"), paymentMethodCreatedWebhook.CreatedAt); +// Assert.AreEqual("test", paymentMethodCreatedWebhook.Environment); +// } +// +// [TestMethod] +// public void Test_Management_Webhook_MerchantUpdated() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'type': 'merchant.updated', +// 'environment': 'test', +// 'createdAt': '2022-09-20T13:42:31+02:00', +// 'data': { +// 'capabilities': { +// 'receivePayments': { +// 'allowed': true, +// 'requested': true, +// 'requestedLevel': 'notApplicable', +// 'verificationStatus': 'valid' +// } +// }, +// 'legalEntityId': 'LE322KH223222F5GNNW694PZN', +// 'merchantId': 'YOUR_MERCHANT_ID', +// 'status': 'PreActive' +// } +// }"; +// // Act +// _managementWebhookHandler.GetMerchantUpdatedNotificationRequest(jsonPayload, out MerchantUpdatedNotificationRequest target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(target.Type, MerchantUpdatedNotificationRequest.TypeEnum.MerchantUpdated); +// Assert.AreEqual("LE322KH223222F5GNNW694PZN", target.Data.LegalEntityId); +// Assert.AreEqual("YOUR_MERCHANT_ID", target.Data.MerchantId); +// Assert.AreEqual("PreActive", target.Data.Status); +// Assert.AreEqual(DateTime.Parse("2022-09-20T13:42:31+02:00"), target.CreatedAt); +// Assert.AreEqual("test", target.Environment); +// +// Assert.IsTrue(target.Data.Capabilities.TryGetValue("receivePayments", out AccountCapabilityData accountCapabilityData)); +// Assert.AreEqual(true, accountCapabilityData.Requested); +// Assert.AreEqual("notApplicable", accountCapabilityData.RequestedLevel); +// } +// +// [TestMethod] +// public void Test_Management_Webhook_MerchantCreated() +// { +// // Arrange +// const string jsonPayload = @" +// { +// 'type': 'merchant.created', +// 'environment': 'test', +// 'createdAt': '2022-08-12T10:50:01+02:00', +// 'data': { +// 'capabilities': { +// 'sendToTransferInstrument': { +// 'requested': true, +// 'requestedLevel': 'notApplicable' +// } +// }, +// 'companyId': 'YOUR_COMPANY_ID', +// 'merchantId': 'MC3224X22322535GH8D537TJR', +// 'status': 'PreActive' +// } +// }"; +// Assert.IsFalse(_managementWebhookHandler.GetMerchantUpdatedNotificationRequest(jsonPayload, out _)); +// +// // Act +// _managementWebhookHandler.GetMerchantCreatedNotificationRequest(jsonPayload, out MerchantCreatedNotificationRequest target); +// +// // Assert +// Assert.IsNotNull(target); +// Assert.AreEqual(MerchantCreatedNotificationRequest.TypeEnum.MerchantCreated, target.Type); +// Assert.AreEqual("test", target.Environment); +// Assert.AreEqual("YOUR_COMPANY_ID", target.Data.CompanyId); +// Assert.AreEqual("MC3224X22322535GH8D537TJR", target.Data.MerchantId); +// Assert.AreEqual("PreActive", target.Data.Status); +// Assert.AreEqual(DateTime.Parse("2022-08-12T10:50:01+02:00"), target.CreatedAt); +// Assert.IsTrue(target.Data.Capabilities.TryGetValue("sendToTransferInstrument", out AccountCapabilityData data)); +// Assert.AreEqual("notApplicable", data.RequestedLevel); +// Assert.AreEqual(true, data.Requested); +// } +// } +// } \ No newline at end of file diff --git a/Adyen.Test/MockOpenInvoicePayment.cs b/Adyen.Test/MockOpenInvoicePayment.cs deleted file mode 100644 index 36549db78..000000000 --- a/Adyen.Test/MockOpenInvoicePayment.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using Adyen.Model.Payment; - -namespace Adyen.Test -{ - public class MockOpenInvoicePayment - { - public static PaymentRequest CreateOpenInvoicePaymentRequest() - { - - DateTime dateOfBirth = DateTime.Parse("1970-07-10"); - - PaymentRequest paymentRequest = MockPaymentData.CreateFullPaymentRequest(); - - // Set Shopper Data - paymentRequest.ShopperEmail = "youremail@email.com"; - paymentRequest.DateOfBirth = dateOfBirth; - paymentRequest.TelephoneNumber = "0612345678"; - paymentRequest.ShopperReference = "4"; - - // Set Shopper Info - Name shopperName = new Name - { - FirstName = "Testperson-nl", - LastName = "Approved" - }; - paymentRequest.ShopperName = shopperName; - - // Set Billing and Delivery address - Address address = new Address - { - City = "Gravenhage", - Country = "NL", - HouseNumberOrName = "1", - PostalCode = "2521VA", - StateOrProvince = "Zuid-Holland", - Street = "Neherkade" - }; - paymentRequest.DeliveryAddress = address; - paymentRequest.BillingAddress = address; - - // Use OpenInvoice Provider (klarna, ratepay) - paymentRequest.SelectedBrand = "klarna"; - - long itemAmount = long.Parse("9000"); - long itemVatAmount = long.Parse("1000"); - long itemVatPercentage = long.Parse("1000"); - - List invoiceLines = new List(); - - // invoiceLine1 - AdditionalDataOpenInvoice invoiceLine = new AdditionalDataOpenInvoice - { - OpeninvoicedataLineItemNrCurrencyCode = ("EUR"), - OpeninvoicedataLineItemNrDescription = ("Test product"), - OpeninvoicedataLineItemNrItemVatAmount = ("1000"), - OpeninvoicedataLineItemNrItemAmount = (itemAmount).ToString(), - OpeninvoicedataLineItemNrItemVatPercentage = (itemVatPercentage).ToString(), - OpeninvoicedataLineItemNrNumberOfItems = (1).ToString(), - OpeninvoicedataLineItemNrItemId = ("1234") - }; - - // invoiceLine2 - // invoiceLine1 - AdditionalDataOpenInvoice invoiceLine2 = new AdditionalDataOpenInvoice - { - OpeninvoicedataLineItemNrCurrencyCode = ("EUR"), - OpeninvoicedataLineItemNrDescription = ("Test product2"), - OpeninvoicedataLineItemNrItemVatAmount = (itemVatAmount).ToString(), - OpeninvoicedataLineItemNrItemAmount = (itemAmount).ToString(), - OpeninvoicedataLineItemNrItemVatPercentage = (itemVatPercentage).ToString(), - OpeninvoicedataLineItemNrNumberOfItems = (1).ToString(), - OpeninvoicedataLineItemNrItemId = ("456") - }; - - invoiceLines.Add(invoiceLine); - invoiceLines.Add(invoiceLine2); - - /*paymentRequest.AdditionalData(invoiceLines);*/ - - return paymentRequest; - } - - } -} diff --git a/Adyen.Test/MockPaymentData.cs b/Adyen.Test/MockPaymentData.cs deleted file mode 100644 index 687c0ef98..000000000 --- a/Adyen.Test/MockPaymentData.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using Adyen.Constants; -using Adyen.Model.Payment; -using Environment = Adyen.Model.Environment; - -namespace Adyen.Test -{ - internal class MockPaymentData - { - #region Mock payment data - - public static Config CreateConfigApiKeyBasedMock() - { - return new Config - { - Environment = Environment.Test, - XApiKey = "AQEyhmfxK....LAG84XwzP5pSpVd"//mock api key - }; - } - - public static PaymentRequest CreateFullPaymentRequest() - { - var paymentRequest = new PaymentRequest - { - ApplicationInfo = new ApplicationInfo - { - AdyenLibrary = new CommonField(name: ClientConfig.LibName, version: ClientConfig.LibVersion) - }, - MerchantAccount = "MerchantAccount", - Amount = new Amount("EUR", 1500), - Card = CreateTestCard(), - Reference = "payment - " + DateTime.Now.ToString("yyyyMMdd"), - AdditionalData = CreateAdditionalData() - }; - return paymentRequest; - } - - public static PaymentRequest3ds2 CreateFullPaymentRequest3DS2() - { - var paymentRequest = new PaymentRequest3ds2 - { - MerchantAccount = "MerchantAccount", - Amount = new Amount("EUR", 1500), - Reference = "payment - " + DateTime.Now.ToString("yyyyMMdd"), - AdditionalData = CreateAdditionalData(), - ThreeDS2RequestData = new ThreeDS2RequestData(threeDSCompInd: "Y", - deviceChannel: "browser"), - BrowserInfo = CreateMockBrowserInfo(), - }; - return paymentRequest; - } - - public static PaymentRequest CreateFullPaymentRequestWithShopperInteraction(PaymentRequest.ShopperInteractionEnum shopperInteraction) - { - var paymentRequest = CreateFullPaymentRequest(); - paymentRequest.ShopperInteraction = shopperInteraction; - return paymentRequest; - } - - protected static Dictionary CreateAdditionalData() - { - return new Dictionary - { - { "liabilityShift", "true"}, - { "fraudResultType", "GREEN"}, - { "authCode", "43733"}, - { "avsResult", "4 AVS not supported for this card type"} - }; - } - - public static PaymentRequest3d CreateFullPaymentRequest3D() - { - var paymentRequest = new PaymentRequest3d - { - ApplicationInfo = new ApplicationInfo - { - AdyenLibrary = new CommonField(name: ClientConfig.LibName, version: ClientConfig.LibVersion) - }, - MerchantAccount = "MerchantAccount", - BrowserInfo = CreateMockBrowserInfo(), - Reference = "payment - " + DateTime.Now.ToString("yyyyMMdd"), - CaptureDelayHours = 0 - }; - return paymentRequest; - } - - - public static BrowserInfo CreateMockBrowserInfo() - { - return new BrowserInfo - { - UserAgent = "User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36", - AcceptHeader = "*/*" - }; - } - - public static Card CreateTestCard() - { - return new Card(number: "4111111111111111", expiryMonth: "08", expiryYear: "2018", cvc: "737", holderName: "John Smith"); - } - - public static Card CreateTestCard3D() - { - return new Card(number: "5212345678901234", expiryMonth: "08", expiryYear: "2018", cvc: "737", holderName: "John Smith"); - } - - public static string GetTestPspReferenceMocked() - { - return "8514836072314693"; - } - #endregion - } -} diff --git a/Adyen.Test/ModificationTest.cs b/Adyen.Test/ModificationTest.cs deleted file mode 100644 index b1864bd42..000000000 --- a/Adyen.Test/ModificationTest.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Adyen.Model.Payment; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class ModificationTest : BaseTest - { - [TestMethod] - public void TestCaptureMockedSuccess() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - //Call authorization test - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/capture-success.json"); - var modification = new PaymentService(client); - //Send capture call with psp refernce - var captureRequest = CreateCaptureTestRequest(paymentResultPspReference); - var captureResult = modification.Capture(captureRequest); - Assert.AreEqual(captureResult.Response, ModificationResult.ResponseEnum.CaptureReceived); - Assert.AreEqual(captureRequest.AdditionalData["authorisationType"],"PreAuth"); - } - - [TestMethod] - public void TestCancelOrRefundReceivedMocked() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - //Call authorization test - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/cancelOrRefund-received.json"); - var modification = new PaymentService(client); - var cancelOrRefundRequest = CreateCancelOrRefundTestRequest(pspReference: paymentResultPspReference); - var cancelOrRefundResult = modification.CancelOrRefund(cancelOrRefundRequest); - Assert.AreEqual(cancelOrRefundResult.Response, ModificationResult.ResponseEnum.CancelOrRefundReceived); - } - - [TestMethod] - public void TestRefundReceivedMocked() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - //Call authorization test - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/refund-received.json"); - var modification = new PaymentService(client); - var refundRequest = CreateRefundTestRequest(pspReference: paymentResultPspReference); - var refundResult = modification.Refund(refundRequest); - Assert.AreEqual(refundResult.Response, ModificationResult.ResponseEnum.RefundReceived); - } - - [TestMethod] - public void TestCancelReceivedMocked() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - //Call authorization test - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/cancel-received.json"); - var modification = new PaymentService(client); - var cancelRequest = CreateCancelTestRequest(pspReference: paymentResultPspReference); - var cancelResult = modification.Cancel(cancelRequest); - Assert.AreEqual(cancelResult.Response, ModificationResult.ResponseEnum.CancelReceived); - } - - [TestMethod] - public void TestAdjustAuthorisationReceivedMocked() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - //Call authorization test - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/adjustAuthorisation-received.json"); - var modification = new PaymentService(client); - var authorisationRequest = CreateAdjustAuthorisationRequest(pspReference: paymentResultPspReference); - var adjustAuthorisationResult = modification.AdjustAuthorisation(authorisationRequest); - Assert.AreEqual(adjustAuthorisationResult.Response, ModificationResult.ResponseEnum.AdjustAuthorisationReceived); - Assert.AreEqual(adjustAuthorisationResult.PspReference, "853569123456789D"); - Assert.AreEqual(adjustAuthorisationResult.AdditionalData["merchantReference"], "payment - 20190901"); - } - - [TestMethod] - public void TestCaptureRequest() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - var captureRequest = CreateCaptureTestRequest(paymentResultPspReference); - Assert.IsNotNull(captureRequest.AdditionalData); - } - - [TestMethod] - public void TestCancelOrRefundRequest() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - var cancelOrRefundRequest = CreateCancelOrRefundTestRequest(pspReference: paymentResultPspReference); - Assert.IsNull(cancelOrRefundRequest.AdditionalData); - Assert.AreEqual(cancelOrRefundRequest.MerchantAccount, "MerchantAccount"); - } - - [TestMethod] - public void TestRefundRequest() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - var refundRequest = CreateRefundTestRequest(pspReference: paymentResultPspReference); - Assert.IsNull(refundRequest.AdditionalData); - Assert.AreEqual(refundRequest.MerchantAccount, "MerchantAccount"); - } - - [TestMethod] - public void TestAdjustAuthorisationRequest() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - var authorisationRequest = CreateAdjustAuthorisationRequest(pspReference: paymentResultPspReference); - Assert.IsNull(authorisationRequest.AdditionalData); - Assert.AreEqual(authorisationRequest.ModificationAmount, new Amount("EUR",150)); - } - - [TestMethod] - public void TestCancelRequest() - { - var paymentResultPspReference = MockPaymentData.GetTestPspReferenceMocked(); - var cancelRequest = CreateCancelTestRequest(pspReference: paymentResultPspReference); - Assert.IsNull(cancelRequest.AdditionalData); - Assert.AreEqual(cancelRequest.MerchantAccount, "MerchantAccount"); - } - - [TestMethod] - public void TestPendingRefundReceived() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/voidPendingRefund-received.json"); - var modification = new PaymentService(client); - var voidPendingRefundRequest = new VoidPendingRefundRequest(); - var modificationResult = modification.VoidPendingRefund(voidPendingRefundRequest); - Assert.AreEqual(modificationResult.Response, ModificationResult.ResponseEnum.VoidPendingRefundReceived); - } - } -} diff --git a/Adyen.Test/Payment/ModificationTest.cs b/Adyen.Test/Payment/ModificationTest.cs new file mode 100644 index 000000000..6e70f9a10 --- /dev/null +++ b/Adyen.Test/Payment/ModificationTest.cs @@ -0,0 +1,119 @@ +using Adyen.Core.Options; +using Adyen.Payment.Extensions; +using Adyen.Payment.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using Adyen.Constants; +using Adyen.Core; +using Adyen.Payment.Models; + +namespace Adyen.Test.Payment +{ + /// + /// ClassicPayments - Modification. + /// + [TestClass] + public class ModificationTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public ModificationTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigurePayment((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_CaptureReceived() + { + //Assert.AreEqual(json.Contains(AdditionalData["authorisationType"],"PreAuth"); + + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/capture-success.json"); + + // Act + var captureResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(captureResult.Response, ModificationResult.ResponseEnum.CaptureReceived); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_CancelOrRefundReceived() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/cancelOrRefund-received.json"); + + // Act + var cancelOrRefundResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(cancelOrRefundResult.Response, ModificationResult.ResponseEnum.CancelOrRefundReceived); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_RefundReceived() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/refund-received.json"); + + // Act + var refundResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(refundResult.Response, ModificationResult.ResponseEnum.RefundReceived); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_CancelReceived() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/cancel-received.json"); + + // Act + var cancelResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(cancelResult.Response, ModificationResult.ResponseEnum.CancelReceived); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_AdjustAuthorisationReceived() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/adjustAuthorisation-received.json"); + + // Act + var adjustAuthorisationResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(adjustAuthorisationResult.Response, ModificationResult.ResponseEnum.AdjustAuthorisationReceived); + Assert.AreEqual(adjustAuthorisationResult.PspReference, "853569123456789D"); + Assert.AreEqual(adjustAuthorisationResult.AdditionalData["merchantReference"], "payment - 20190901"); + } + + [TestMethod] + public void Given_Deserialize_When_ModificationResult_Result_Is_VoidPendingRefundReceived() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/voidPendingRefund-received.json"); + + // Act + var modificationResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(modificationResult.Response, ModificationResult.ResponseEnum.VoidPendingRefundReceived); + } + } +} diff --git a/Adyen.Test/Payment/PaymentTest.cs b/Adyen.Test/Payment/PaymentTest.cs new file mode 100644 index 000000000..b436efe2c --- /dev/null +++ b/Adyen.Test/Payment/PaymentTest.cs @@ -0,0 +1,379 @@ +using Adyen.Core.Options; +using Adyen.Payment.Extensions; +using Adyen.Payment.Client; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using Adyen.Constants; +using Adyen.Payment.Models; + +namespace Adyen.Test.Payment +{ + /// + /// Classic Payments - Payment. + /// + [TestClass] + public class PaymentTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public PaymentTest() + { + IHost testHost = Host.CreateDefaultBuilder() + .ConfigurePayment((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = testHost.Services.GetRequiredService(); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_Result_Is_Authorised() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authorise-success.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(result.ResultCode, PaymentResult.ResultCodeEnum.Authorised); + Assert.AreEqual("411111", GetAdditionalData(result.AdditionalData, "cardBin")); + Assert.AreEqual("43733", GetAdditionalData(result.AdditionalData, "authCode")); + Assert.AreEqual("4 AVS not supported for this card type", GetAdditionalData(result.AdditionalData, "avsResult")); + Assert.AreEqual("1 Matches", GetAdditionalData(result.AdditionalData, "cvcResult")); + Assert.AreEqual("visa", GetAdditionalData(result.AdditionalData, "paymentMethod")); + } + + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_3D_Result_Is_Authorise_Success() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authorise-success-3d.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(result.Md); + Assert.IsNotNull(result.IssuerUrl); + Assert.IsNotNull(result.PaRequest); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_3DS_IdentifyShopper_Result_Is_IdentifyShopper() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/threedsecure2/authorise-response-identifyshopper.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(result.ResultCode, PaymentResult.ResultCodeEnum.IdentifyShopper); + Assert.IsNotNull(result.PspReference); + Assert.AreEqual("74044f6c-7d79-4dd1-9859-3b2879a32fb0", GetAdditionalData(result.AdditionalData, "threeds2.threeDSServerTransID")); + Assert.AreEqual(@"https://pal-test.adyen.com/threeds2simulator/acs/startMethod.shtml", GetAdditionalData(result.AdditionalData, "threeds2.threeDSMethodURL")); + Assert.AreEqual("[token]", GetAdditionalData(result.AdditionalData, "threeds2.threeDS2Token")); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_3DS2_ChallengeShopper_Result_Is_ChallengerShopper() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/threedsecure2/authorise3ds2-response-challengeshopper.json"); + + // Act + var paymentResult = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.ChallengeShopper); + Assert.IsNotNull(paymentResult.PspReference); + + Assert.AreEqual("C", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.transStatus")); + Assert.AreEqual("Y", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsChallengeMandated")); + Assert.AreEqual("https://pal-test.adyen.com/threeds2simulator/acs/challenge.shtml", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsURL")); + Assert.AreEqual("74044f6c-7d79-4dd1-9859-3b2879a32fb1", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.threeDSServerTransID")); + Assert.AreEqual("01", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.authenticationType")); + Assert.AreEqual("2.1.0", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.messageVersion")); + Assert.AreEqual("[token]", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2Token")); + Assert.AreEqual("ba961c4b-33f2-4830-3141-744b8586aeb0", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsTransID")); + Assert.AreEqual("ADYEN-ACS-SIMULATOR", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsReferenceNumber")); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_Authorise_3DS2_Result_Is_Authorised() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/threedsecure2/authorise3ds2-success.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(result.ResultCode, PaymentResult.ResultCodeEnum.Authorised); + Assert.IsNotNull(result.PspReference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_Authorise_3D_Result_Is_Authorised() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authorise3d-success.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(result.ResultCode, PaymentResult.ResultCodeEnum.Authorised); + Assert.IsNotNull(result.PspReference); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_CVC_Declined_Result_Is_Refused() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authorise-error-cvc-declined.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentResult.ResultCodeEnum.Refused, result.ResultCode); + } + + [TestMethod] + public void Given_Deserialize_When_PaymentResult_CSE_Result_Is_Authorised() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authorise-success-cse.json"); + + // Act + var result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(PaymentResult.ResultCodeEnum.Authorised, result.ResultCode); + } + + [TestMethod] + public void Given_CreatePaymentRequest_When_AdyenLibraryName_And_AdyenLibraryVersion_Are_Set_Returns_ApplicationInfo() + { + // Arrange + // Act + var paymentRequest = MockPaymentData.CreateFullPaymentRequest(); + + // Assert + Assert.IsNotNull(paymentRequest.ApplicationInfo); + Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Name, Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName); + Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Version, Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion); + } + + [TestMethod] + public void Given_CreatePaymentRequest3D_When_AdyenLibraryName_And_AdyenLibraryVersion_Are_Set_Returns_ApplicationInfo() + { + // Arrange + // Act + PaymentRequest3d paymentRequest = MockPaymentData.CreateFullPaymentRequest3D(); + + // Assert + Assert.IsNotNull(paymentRequest.ApplicationInfo); + Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Name, Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName); + Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Version, Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion); + } + + [TestMethod] + public void Given_Serialize_When_PaymentRequest3D_With_CaptureDelaysHours_And_FraudOffSet_Result_Should_Contain_0() + { + // Arrange + var paymentRequest = MockPaymentData.CreateFullPaymentRequest3D(); + + // Act + string target = JsonSerializer.Serialize(paymentRequest); + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + Assert.AreEqual(0, root.GetProperty("captureDelayHours").GetInt32()); + Assert.AreEqual(0, root.GetProperty("fraudOffset").GetInt32()); + } + + [TestMethod] + public void Given_Deserialize_When_AuthenticationResultResponse_Result_3DS1_Success_And_3DS2_Is_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authentication-result-success-3ds1.json"); + + // Act + var authenticationResultResponse = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Arrange + Assert.IsNotNull(authenticationResultResponse); + Assert.IsNotNull(authenticationResultResponse.ThreeDS1Result); + Assert.IsNull(authenticationResultResponse.ThreeDS2Result); + } + + [TestMethod] + public void Given_Deserialize_When_AuthenticationResultResponse_Result_3DS2_Is_Success_And_3DS1_Is_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/authentication-result-success-3ds2.json"); + + // Act + var authenticationResultResponse = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(authenticationResultResponse); + Assert.IsNull(authenticationResultResponse.ThreeDS1Result); + Assert.IsNotNull(authenticationResultResponse.ThreeDS2Result); + } + + [TestMethod] + public void Given_Deserialize_When_AuthenticationResultResponse_Result_ThreeDSServerTransId_And_Ds_TransID_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/ThreeDS2Result.json"); + + // Act + var threeDs2Result = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(threeDs2Result); + Assert.AreEqual("f04ec32b-f46b-46ef-9ccd-44be42fb0d7e", threeDs2Result.ThreeDS2Result.ThreeDSServerTransID); + Assert.AreEqual("80a16fa0-4eea-43c9-8de5-b0470d09d14d", threeDs2Result.ThreeDS2Result.DsTransID); + } + + [TestMethod] + public void Given_Serialize_When_PaymentRequest_With_ShopperInteraction_Moto_Result_Should_Be_Moto() + { + // Arrange + var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(PaymentRequest.ShopperInteractionEnum.Moto); + + // Act + string target = JsonSerializer.Serialize(paymentRequest); + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + Assert.AreEqual("Moto", root.GetProperty("shopperInteraction").GetString()); + } + + [TestMethod] + public void Given_Serialize_When_PaymentRequest_With_ShopperInteraction_Result_Should_Be_Null() + { + // Arrange + var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(null); + + // Act + string target = JsonSerializer.Serialize(paymentRequest); + + // Assert + using var jsonDoc = JsonDocument.Parse(target); + JsonElement root = jsonDoc.RootElement; + Assert.IsNull(root.GetProperty("shopperInteraction").GetString()); + } + + private string GetAdditionalData(Dictionary additionalData, string assertKey) + { + string result = ""; + if (additionalData.ContainsKey(assertKey)) + { + result = additionalData[assertKey]; + } + return result; + } + } + + internal class MockPaymentData + { + #region Mock payment data + + public static PaymentRequest CreateFullPaymentRequest() + { + PaymentRequest paymentRequest = new PaymentRequest( + applicationInfo: new ApplicationInfo(adyenLibrary: new CommonField(name: Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName, version: Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion)), + merchantAccount: "MerchantAccount", + amount: new Amount("EUR", 1500), card: CreateTestCard(), + reference: "payment - " + DateTime.Now.ToString("yyyyMMdd"), + additionalData: CreateAdditionalData()); + return paymentRequest; + } + + public static PaymentRequest3ds2 CreateFullPaymentRequest3DS2() + { + PaymentRequest3ds2 paymentRequest = new PaymentRequest3ds2( + amount: new Amount("EUR", 1500), + merchantAccount: "MerchantAccount", + reference: "payment - " + DateTime.Now.ToString("yyyyMMdd"), + additionalData: CreateAdditionalData(), + threeDS2RequestData: new ThreeDS2RequestData(threeDSCompInd: "Y", + deviceChannel: "browser"), + browserInfo: CreateMockBrowserInfo() ); + return paymentRequest; + } + + public static PaymentRequest CreateFullPaymentRequestWithShopperInteraction(PaymentRequest.ShopperInteractionEnum shopperInteraction) + { + PaymentRequest paymentRequest = CreateFullPaymentRequest(); + paymentRequest.ShopperInteraction = shopperInteraction; + return paymentRequest; + } + + protected static Dictionary CreateAdditionalData() + { + return new Dictionary + { + { "liabilityShift", "true"}, + { "fraudResultType", "GREEN"}, + { "authCode", "43733"}, + { "avsResult", "4 AVS not supported for this card type"} + }; + } + + public static PaymentRequest3d CreateFullPaymentRequest3D() + { + PaymentRequest3d paymentRequest = new PaymentRequest3d( + md: "md", + merchantAccount: "MerchantAccount", + paResponse: "paResponse", + applicationInfo: new ApplicationInfo(adyenLibrary: new CommonField(name: Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName, version: Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion)), + browserInfo: CreateMockBrowserInfo(), + reference: "payment - " + DateTime.Now.ToString("yyyyMMdd"), + captureDelayHours: 0, + fraudOffset: 0); + return paymentRequest; + } + + + public static BrowserInfo CreateMockBrowserInfo() + { + return new BrowserInfo + { + UserAgent = "User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36", + AcceptHeader = "*/*" + }; + } + + public static Card CreateTestCard() + { + return new Card(number: "4111111111111111", expiryMonth: "08", expiryYear: "2018", cvc: "737", holderName: "John Smith"); + } + + public static Card CreateTestCard3D() + { + return new Card(number: "5212345678901234", expiryMonth: "08", expiryYear: "2018", cvc: "737", holderName: "John Smith"); + } + + public static string GetTestPspReferenceMocked() + { + return "8514836072314693"; + } + #endregion + } +} diff --git a/Adyen.Test/PaymentMethodDetailsTest.cs b/Adyen.Test/PaymentMethodDetailsTest.cs deleted file mode 100644 index 2612d880d..000000000 --- a/Adyen.Test/PaymentMethodDetailsTest.cs +++ /dev/null @@ -1,180 +0,0 @@ -using Adyen.Model.Checkout; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class PaymentMethodDetailsTest - { - [TestMethod] - public void TestAchPaymentMethod() - { - var achDetails = new AchDetails - { - BankAccountNumber = "1234567", - BankLocationId = "1234567", - EncryptedBankAccountNumber = "1234asdfg", - OwnerName = "John Smith" - }; - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("EUR", 1000), - Reference = "ACH test", - PaymentMethod = new CheckoutPaymentMethod(achDetails), - ShopperIP = "192.0.2.1", - Channel = PaymentRequest.ChannelEnum.Web, - Origin = "https://your-company.com", - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy..", - - }; - var paymentMethodDetails = paymentRequest.PaymentMethod.GetAchDetails(); - Assert.AreEqual(paymentMethodDetails.Type, AchDetails.TypeEnum.Ach); - Assert.AreEqual(paymentMethodDetails.BankAccountNumber, "1234567"); - Assert.AreEqual(paymentMethodDetails.BankLocationId, "1234567"); - Assert.AreEqual(paymentMethodDetails.EncryptedBankAccountNumber, "1234asdfg"); - Assert.AreEqual(paymentMethodDetails.OwnerName, "John Smith"); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "ACH test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - - - [TestMethod] - public void TestApplePayPaymentMethod() - { - var applePay = new ApplePayDetails - { - ApplePayToken = "VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU..." - }; - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("EUR", 1000), - Reference = "apple pay test", - PaymentMethod = new CheckoutPaymentMethod(applePay), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." - }; - var paymentMethodDetails = paymentRequest.PaymentMethod.GetApplePayDetails(); - Assert.AreEqual(paymentMethodDetails.Type, ApplePayDetails.TypeEnum.Applepay); - Assert.AreEqual(paymentMethodDetails.ApplePayToken, "VNRWtuNlNEWkRCSm1xWndjMDFFbktkQU..."); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "apple pay test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - - [TestMethod] - public void TestGooglePayPaymentMethod() - { - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("EUR", 1000), - Reference = "google pay test", - PaymentMethod = new CheckoutPaymentMethod(new GooglePayDetails - { - GooglePayToken = "==Payload as retrieved from Google Pay response==", - FundingSource = GooglePayDetails.FundingSourceEnum.Debit - }), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." - }; - var paymentMethodDetails = (GooglePayDetails)paymentRequest.PaymentMethod.ActualInstance; - Assert.AreEqual(paymentMethodDetails.Type, GooglePayDetails.TypeEnum.Googlepay); - Assert.AreEqual(paymentMethodDetails.GooglePayToken, "==Payload as retrieved from Google Pay response=="); - Assert.AreEqual(paymentMethodDetails.FundingSource, GooglePayDetails.FundingSourceEnum.Debit); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "google pay test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - - [TestMethod] - public void TestIdealPaymentMethod() - { - - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("EUR", 1000), - Reference = "ideal test", - PaymentMethod = new CheckoutPaymentMethod(new IdealDetails - { - Issuer = "1121" - }), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." - }; - var paymentMethodDetails = paymentRequest.PaymentMethod.GetIdealDetails(); - Assert.AreEqual(paymentMethodDetails.Type, IdealDetails.TypeEnum.Ideal); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "ideal test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - - [TestMethod] - public void TestBacsDirectDebitDetails() - { - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("GBP", 1000), - Reference = "bacs direct debit test", - PaymentMethod = new CheckoutPaymentMethod(new BacsDirectDebitDetails - { - BankAccountNumber = "NL0123456789", - BankLocationId = "121000358", - HolderName = "John Smith" - }), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." - }; - var paymentMethodDetails = paymentRequest.PaymentMethod.GetBacsDirectDebitDetails(); - Assert.AreEqual(paymentMethodDetails.Type, BacsDirectDebitDetails.TypeEnum.DirectdebitGB); - Assert.AreEqual(paymentMethodDetails.BankAccountNumber, "NL0123456789"); - Assert.AreEqual(paymentMethodDetails.BankLocationId, "121000358"); - Assert.AreEqual(paymentMethodDetails.HolderName, "John Smith"); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "bacs direct debit test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - - - [TestMethod] - public void TestPaypalSuccess() - { - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("USD", 1000), - Reference = "paypal test", - PaymentMethod = new CheckoutPaymentMethod( new PayPalDetails - { - Subtype = PayPalDetails.SubtypeEnum.Sdk, - StoredPaymentMethodId = "2345654212345432345" - }), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy.." - }; - var paymentMethodDetails = (PayPalDetails)paymentRequest.PaymentMethod.ActualInstance; - Assert.AreEqual(paymentMethodDetails.Type, PayPalDetails.TypeEnum.Paypal); - Assert.AreEqual(paymentMethodDetails.Subtype, PayPalDetails.SubtypeEnum.Sdk); - } - - [TestMethod] - public void TestZipSuccess() - { - var paymentRequest = new PaymentRequest - { - MerchantAccount = "YOUR_MERCHANT_ACCOUNT", - Amount = new Amount("USD", 1000), - Reference = "zip test", - PaymentMethod = new CheckoutPaymentMethod(new ZipDetails - { - Type = ZipDetails.TypeEnum.Zip - }), - ReturnUrl = "https://your-company.com/checkout?shopperOrder=12xy..", - }; - var paymentMethodDetails = (ZipDetails)paymentRequest.PaymentMethod.ActualInstance; - Assert.AreEqual(paymentMethodDetails.Type, ZipDetails.TypeEnum.Zip); - Assert.AreEqual(paymentRequest.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentRequest.Reference, "zip test"); - Assert.AreEqual(paymentRequest.ReturnUrl, "https://your-company.com/checkout?shopperOrder=12xy.."); - } - } -} diff --git a/Adyen.Test/PaymentTest.cs b/Adyen.Test/PaymentTest.cs deleted file mode 100644 index 0e2ea1b7c..000000000 --- a/Adyen.Test/PaymentTest.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System.Collections.Generic; -using Adyen.Constants; -using Adyen.Model.Payment; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class PaymentTest : BaseTest - { - [TestMethod] - public void TestAuthoriseBasicAuthenticationSuccessMockedResponse() - { - var paymentResult = CreatePaymentResultFromFile("mocks/authorise-success.json"); - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.AreEqual("411111", GetAdditionalData(paymentResult.AdditionalData, "cardBin")); - Assert.AreEqual("43733", GetAdditionalData(paymentResult.AdditionalData, "authCode")); - Assert.AreEqual("4 AVS not supported for this card type", GetAdditionalData(paymentResult.AdditionalData, "avsResult")); - Assert.AreEqual("1 Matches", GetAdditionalData(paymentResult.AdditionalData, "cvcResult")); - Assert.AreEqual("visa", GetAdditionalData(paymentResult.AdditionalData, "paymentMethod")); - } - - [TestMethod] - public void TestAuthoriseApiKeyBasedSuccessMockedResponse() - { - var paymentResult = CreatePaymentApiKeyBasedResultFromFile("mocks/authorise-success.json"); - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.AreEqual("411111", GetAdditionalData(paymentResult.AdditionalData, "cardBin")); - Assert.AreEqual("43733", GetAdditionalData(paymentResult.AdditionalData, "authCode")); - Assert.AreEqual("4 AVS not supported for this card type", GetAdditionalData(paymentResult.AdditionalData, "avsResult")); - Assert.AreEqual("1 Matches", GetAdditionalData(paymentResult.AdditionalData, "cvcResult")); - Assert.AreEqual("visa", GetAdditionalData(paymentResult.AdditionalData, "paymentMethod")); - } - - [TestMethod] - public void TestAuthoriseSuccess3DMocked() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/authorise-success-3d.json"); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest); - Assert.IsNotNull(paymentResult.Md); - Assert.IsNotNull(paymentResult.IssuerUrl); - Assert.IsNotNull(paymentResult.PaRequest); - } - - [TestMethod] - public void TestAuthorise3DS2IdentifyShopperMocked() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/threedsecure2/authorise-response-identifyshopper.json"); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3DS2(); - var paymentResult = payment.Authorise3ds2(paymentRequest); - - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.IdentifyShopper); - Assert.IsNotNull(paymentResult.PspReference); - - Assert.AreEqual("74044f6c-7d79-4dd1-9859-3b2879a32fb0", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDSServerTransID")); - Assert.AreEqual(@"https://pal-test.adyen.com/threeds2simulator/acs/startMethod.shtml", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDSMethodURL")); - Assert.AreEqual("[token]", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2Token")); - } - - [TestMethod] - public void TestAuthorise3DS2ChallengeShopperMocked() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/threedsecure2/authorise3ds2-response-challengeshopper.json"); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3DS2(); - var paymentResult = payment.Authorise3ds2(paymentRequest); - - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.ChallengeShopper); - Assert.IsNotNull(paymentResult.PspReference); - - Assert.AreEqual("C", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.transStatus")); - Assert.AreEqual("Y", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsChallengeMandated")); - Assert.AreEqual("https://pal-test.adyen.com/threeds2simulator/acs/challenge.shtml", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsURL")); - Assert.AreEqual("74044f6c-7d79-4dd1-9859-3b2879a32fb1", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.threeDSServerTransID")); - Assert.AreEqual("01", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.authenticationType")); - Assert.AreEqual("2.1.0", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.messageVersion")); - Assert.AreEqual("[token]", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2Token")); - Assert.AreEqual("ba961c4b-33f2-4830-3141-744b8586aeb0", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsTransID")); - Assert.AreEqual("ADYEN-ACS-SIMULATOR", GetAdditionalData(paymentResult.AdditionalData, "threeds2.threeDS2ResponseData.acsReferenceNumber")); - } - - [TestMethod] - public void TestAuthorise3DS2SuccessMocked() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/threedsecure2/authorise3ds2-success.json"); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3DS2(); - var paymentResult = payment.Authorise3ds2(paymentRequest); - - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.IsNotNull(paymentResult.PspReference); - } - - [TestMethod] - public void TestAuthorise3DSuccessMocked() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/authorise3d-success.json"); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3D(); - var paymentResult = payment.Authorise3d(paymentRequest); - Assert.AreEqual(paymentResult.ResultCode, PaymentResult.ResultCodeEnum.Authorised); - Assert.IsNotNull(paymentResult.PspReference); - } - - [TestMethod] - public void TestAuthoriseErrorCvcDeclinedMocked() - { - var paymentResult = CreatePaymentResultFromFile("mocks/authorise-error-cvc-declined.json"); - Assert.AreEqual(PaymentResult.ResultCodeEnum.Refused, paymentResult.ResultCode); - } - - [TestMethod] - public void TestAuthoriseCseSuccessMocked() - { - var paymentResult = CreatePaymentResultFromFile("mocks/authorise-success-cse.json"); - Assert.AreEqual(PaymentResult.ResultCodeEnum.Authorised, paymentResult.ResultCode); - } - [Ignore] // Fix this test -> not sure how to add additionalDataOpenInvoice class to paymentrequest - [TestMethod] - public void TestOpenInvoice() - { - var client = CreateMockTestClientRequest("mocks/authorise-success-klarna.json"); - var payment = new PaymentService(client); - var paymentRequest = MockOpenInvoicePayment.CreateOpenInvoicePaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest); - Assert.AreEqual("2374421290", paymentResult.AdditionalData["additionalData.acquirerReference"]); - Assert.AreEqual("klarna", paymentResult.AdditionalData["paymentMethodVariant"]); - } - - [TestMethod] - public void TestPaymentRequestApplicationInfo() - { - var paymentRequest = MockPaymentData.CreateFullPaymentRequest(); - Assert.IsNotNull(paymentRequest.ApplicationInfo); - Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Name, ClientConfig.LibName); - Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Version, ClientConfig.LibVersion); - } - - [TestMethod] - public void TestPaymentRequest3DApplicationInfo() - { - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3D(); - Assert.IsNotNull(paymentRequest.ApplicationInfo); - Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Name, ClientConfig.LibName); - Assert.AreEqual(paymentRequest.ApplicationInfo.AdyenLibrary.Version, ClientConfig.LibVersion); - } - - [TestMethod] - public void TestCaptureDelaySerialization() - { - var paymentRequest = MockPaymentData.CreateFullPaymentRequest3D(); - string jsonString = paymentRequest.ToJson(); - Assert.IsTrue(jsonString.Contains("\"captureDelayHours\": 0,")); - Assert.IsFalse(jsonString.Contains("\"fraudOffset\": 0")); - } - - [TestMethod] - public void TestAuthenticationResult3ds1Success() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/authentication-result-success-3ds1.json"); - var payment = new PaymentService(client); - var authenticationResultRequest = new AuthenticationResultRequest(); - var authenticationResultResponse = payment.GetAuthenticationResult(authenticationResultRequest); - Assert.IsNotNull(authenticationResultResponse); - Assert.IsNotNull(authenticationResultResponse.ThreeDS1Result); - Assert.IsNull(authenticationResultResponse.ThreeDS2Result); - } - - [TestMethod] - public void TestAuthenticationResult3ds2Success() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/authentication-result-success-3ds2.json"); - var payment = new PaymentService(client); - var authenticationResultRequest = new AuthenticationResultRequest(); - var authenticationResultResponse = payment.GetAuthenticationResult(authenticationResultRequest); - Assert.IsNotNull(authenticationResultResponse); - Assert.IsNull(authenticationResultResponse.ThreeDS1Result); - Assert.IsNotNull(authenticationResultResponse.ThreeDS2Result); - } - - [TestMethod] - public void TestRetrieve3ds2ResultSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/ThreeDS2Result.json"); - var payment = new PaymentService(client); - var authenticationResultRequest = new AuthenticationResultRequest(); - var ThreeDSTwoResult = payment.GetAuthenticationResult(authenticationResultRequest); - Assert.AreEqual("f04ec32b-f46b-46ef-9ccd-44be42fb0d7e", ThreeDSTwoResult.ThreeDS2Result.ThreeDSServerTransID); - Assert.AreEqual("80a16fa0-4eea-43c9-8de5-b0470d09d14d", ThreeDSTwoResult.ThreeDS2Result.DsTransID); - Assert.IsNotNull(ThreeDSTwoResult); - } - - private string GetAdditionalData(Dictionary additionalData, string assertKey) - { - string result = ""; - if (additionalData.ContainsKey(assertKey)) - { - result = additionalData[assertKey]; - } - return result; - } - } -} diff --git a/Adyen.Test/PaymentsApp/PaymentsAppServiceTest.cs b/Adyen.Test/PaymentsApp/PaymentsAppServiceTest.cs new file mode 100644 index 000000000..3553dd343 --- /dev/null +++ b/Adyen.Test/PaymentsApp/PaymentsAppServiceTest.cs @@ -0,0 +1,80 @@ +using Adyen.Core.Options; +using Adyen.PaymentsApp.Client; +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; +using Adyen.PaymentsApp.Services; + +namespace Adyen.Test.PaymentsApp +{ + [TestClass] + public class PaymentsAppTest + { + [TestMethod] + public async Task Given_PaymentsAppService_When_Initialized_Result_Should_Return_Management_Test_Url() + { + // Arrange + // Act + IHost testHost = Host.CreateDefaultBuilder() + .ConfigurePaymentsApp((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + var paymentsAppService = testHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://management-test.adyen.com/v1", paymentsAppService.HttpClient.BaseAddress.ToString()); + } + + [TestMethod] + public void Given_PaymentsAppService_When_Initialized_Result_Should_Return_Management_Live_Url() + { + // Arrange + // Act + IHost testHost = Host.CreateDefaultBuilder() + .ConfigurePaymentsApp((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Live; + }); + }) + .Build(); + + var paymentsAppService = testHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://management-live.adyen.com/v1", paymentsAppService.HttpClient.BaseAddress.ToString()); + } + + [TestMethod] + public void Given_PaymentsAppService_When_Initialized_Result_Should_Return_Management_Live_Url_And_No_Prefix() + { + // Arrange + // Act + IHost testHost = Host.CreateDefaultBuilder() + .ConfigurePaymentsApp((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Live; + options.LiveEndpointUrlPrefix = "prefix"; + }); + }) + .Build(); + + var paymentsAppService = testHost.Services.GetRequiredService(); + + // Assert + Assert.AreEqual("https://management-live.adyen.com/v1", paymentsAppService.HttpClient.BaseAddress.ToString()); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/PaymentsAppServiceTest.cs b/Adyen.Test/PaymentsAppServiceTest.cs deleted file mode 100644 index b9b412296..000000000 --- a/Adyen.Test/PaymentsAppServiceTest.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Net.Http; -using Adyen.Model; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; -using Environment = Adyen.Model.Environment; - -namespace Adyen.Test -{ - [TestClass] - public class PaymentsAppServiceTest : BaseTest - { - [TestMethod] - public void PaymentsAppServiceTESTUrlTest() - { - var client = CreateMockForAdyenClientTest(new Config()); - client.SetEnvironment(Environment.Test, "companyUrl"); - var checkout = new PaymentsAppService(client); - checkout.RevokePaymentsAppAsync("{merchantId}", "{installationId}").GetAwaiter(); - - ClientInterfaceSubstitute.Received().RequestAsync("https://management-test.adyen.com/v1/merchants/{merchantId}/paymentsApps/{installationId}/revoke", - Arg.Any(), null, new HttpMethod("POST"), default); - } - - [TestMethod] - public void PaymentsAppServiceLIVEUrlTest() - { - var client = CreateMockForAdyenClientTest(new Config()); - client.SetEnvironment(Environment.Live, "companyUrl"); - var checkout = new PaymentsAppService(client); - checkout.RevokePaymentsAppAsync("{merchantId}", "{installationId}").GetAwaiter(); - - ClientInterfaceSubstitute.Received().RequestAsync("https://management-live.adyen.com/v1/merchants/{merchantId}/paymentsApps/{installationId}/revoke", - Arg.Any(), null, new HttpMethod("POST"), default); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/Payout/PayoutTest.cs b/Adyen.Test/Payout/PayoutTest.cs new file mode 100644 index 000000000..ac764d4c0 --- /dev/null +++ b/Adyen.Test/Payout/PayoutTest.cs @@ -0,0 +1,122 @@ +using Adyen.Core.Options; +using Adyen.Payout.Client; +using Adyen.Payout.Models; +using Adyen.Payout.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test +{ + [TestClass] + public class PayoutTest : BaseTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public PayoutTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigurePayout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoreDetailAndSubmitThirdParty_Returns_Not_Null() + { + // Arrange + string client = TestUtilities.GetTestFileContent("mocks/payout/storeDetailAndSubmitThirdParty-success.json"); + + // Act + var response = JsonSerializer.Deserialize(client, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("[payout-submit-received]", response.ResultCode); + Assert.AreEqual("8515131751004933", response.PspReference); + Assert.AreEqual("GREEN", response.AdditionalData["fraudResultType"]); + Assert.AreEqual("false", response.AdditionalData["fraudManualReview"]); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoreDetail_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/payout/storeDetail-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("Success", response.ResultCode); + Assert.AreEqual("8515136787207087", response.PspReference); + Assert.AreEqual("8415088571022720", response.RecurringDetailReference); + } + + [TestMethod] + public async Task Given_Deserialize_When_ConfirmThirdParty_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/payout/modifyResponse-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("[payout-confirm-received]", response.Response); + Assert.AreEqual("8815131762537886", response.PspReference); + } + + [TestMethod] + public async Task Given_Deserialize_When_SubmitThirdParty_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/payout/submitResponse-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("[payout-submit-received]", response.ResultCode); + Assert.AreEqual("8815131768219992", response.PspReference); + Assert.AreEqual("GREEN", response.AdditionalData["fraudResultType"]); + Assert.AreEqual("false", response.AdditionalData["fraudManualReview"]); + } + + [TestMethod] + public async Task Given_Deserialize_When_DeclineThirdParty_ModifyResponse_Then_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/payout/modifyResponse-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("[payout-confirm-received]", response.Response); + Assert.AreEqual("8815131762537886", response.PspReference); + } + + [TestMethod] + public async Task PayoutSuccessTest() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/payout/payout-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("8814689190961342", response.PspReference); + Assert.AreEqual("12345", response.AuthCode); + } + } +} + diff --git a/Adyen.Test/PayoutTest.cs b/Adyen.Test/PayoutTest.cs deleted file mode 100644 index 08ed3c12e..000000000 --- a/Adyen.Test/PayoutTest.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Adyen.Model.Payout; -using Adyen.Service.Payout; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class PayoutTest : BaseTest - { - [TestMethod] - public void StoreDetailAndSubmitThirdPartySuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/storeDetailAndSubmitThirdParty-success.json"); - var payout = new InitializationService(client); - - var request = new StoreDetailAndSubmitRequest(); - var result = payout.StoreDetailAndSubmitThirdParty(request); - - Assert.AreEqual("[payout-submit-received]", result.ResultCode); - Assert.AreEqual("8515131751004933", result.PspReference); - Assert.AreEqual("GREEN", result.AdditionalData["fraudResultType"]); - Assert.AreEqual("false", result.AdditionalData["fraudManualReview"]); - } - - [TestMethod] - public void StoreDetailSuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/storeDetail-success.json"); - var payout = new InitializationService(client); - - var request = new StoreDetailRequest(); - var result = payout.StoreDetail(request); - - Assert.AreEqual("Success", result.ResultCode); - Assert.AreEqual("8515136787207087", result.PspReference); - Assert.AreEqual("8415088571022720", result.RecurringDetailReference); - } - - [TestMethod] - public void ConfirmThirdPartySuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/modifyResponse-success.json"); - var payout = new ReviewingService(client); - - var request = new ModifyRequest(); - var result = payout.ConfirmThirdParty(request); - - Assert.AreEqual("[payout-confirm-received]", result.Response); - Assert.AreEqual("8815131762537886", result.PspReference); - } - - [TestMethod] - public void SubmitThirdPartySuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/submitResponse-success.json"); - var payout = new InitializationService(client); - var request = new SubmitRequest(); - var result = payout.SubmitThirdParty(request); - Assert.AreEqual("[payout-submit-received]", result.ResultCode); - Assert.AreEqual("8815131768219992", result.PspReference); - Assert.AreEqual("GREEN", result.AdditionalData["fraudResultType"]); - Assert.AreEqual("false", result.AdditionalData["fraudManualReview"]); - } - - [TestMethod] - public void DeclineThirdPartySuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/modifyResponse-success.json"); - var payout = new ReviewingService(client); - var request = new ModifyRequest(); - var result = payout.DeclineThirdParty(request); - Assert.AreEqual("[payout-confirm-received]", result.Response); - Assert.AreEqual("8815131762537886", result.PspReference); - } - - [TestMethod] - public void PayoutSuccessTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/payout/payout-success.json"); - var payout = new InstantPayoutsService(client); - var request = new PayoutRequest(); - var result = payout.Payout(request); - Assert.AreEqual("8814689190961342", result.PspReference); - Assert.AreEqual("12345", result.AuthCode); - } - } -} - diff --git a/Adyen.Test/PosMobile/PosMobileTest.cs b/Adyen.Test/PosMobile/PosMobileTest.cs new file mode 100644 index 000000000..a47c88fac --- /dev/null +++ b/Adyen.Test/PosMobile/PosMobileTest.cs @@ -0,0 +1,45 @@ +using Adyen.Core.Options; +using Adyen.PosMobile.Models; +using Adyen.PosMobile.Client; +using Adyen.PosMobile.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.PosMobile +{ + [TestClass] + public class PosMobileTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public PosMobileTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigurePosMobile((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_CreateSessionResponse_Returns_Correct_Id() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/posmobile/create-session.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Id, "CS451F2AB1ED897A94"); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/PosMobileTest.cs b/Adyen.Test/PosMobileTest.cs deleted file mode 100644 index fb038a8e8..000000000 --- a/Adyen.Test/PosMobileTest.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Net.Http; -using Adyen.Model.PosMobile; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; -using Environment = Adyen.Model.Environment; - -namespace Adyen.Test -{ - [TestClass] - public class PosMobileTest : BaseTest - { - [TestMethod] - public void TestPosMobileCreateSession() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/posmobile/create-session.json"); - client.Config.Environment = Environment.Live; - client.Config.LiveEndpointUrlPrefix = "prefix"; - var service = new PosMobileService(client); - var response = service.CreateCommunicationSession(new CreateSessionRequest()); - Assert.AreEqual(response.Id, "CS451F2AB1ED897A94"); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://prefix-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions", - Arg.Any(), null, new HttpMethod("POST"), default); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/PosTerminalManagementTest.cs b/Adyen.Test/PosTerminalManagementTest.cs deleted file mode 100644 index 6dc9c511b..000000000 --- a/Adyen.Test/PosTerminalManagementTest.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Collections.Generic; -using Adyen.Model.PosTerminalManagement; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class PosTerminalManagementTest : BaseTest - { - /// - /// Test post /findTerminals - /// - [TestMethod] - public void FindTerminalSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/pos-terminal-management/find-terminals-success.json"); - var posTerminalManagement = new PosTerminalManagementService(client); - var findTerminalRequest = new FindTerminalRequest - { - Terminal = "V400m-123456789" - }; - var findTerminalResponse = posTerminalManagement.FindTerminal(findTerminalRequest); - Assert.AreEqual(findTerminalResponse.Terminal, "V400m-123456789"); - Assert.AreEqual(findTerminalResponse.CompanyAccount, "TestCompany"); - Assert.AreEqual(findTerminalResponse.MerchantAccount, "TestMerchant"); - Assert.AreEqual(findTerminalResponse.Store, "MyStore"); - Assert.AreEqual(findTerminalResponse.MerchantInventory, false); - } - /// - /// Test post /assignTerminals - /// - [TestMethod] - public void AssignTerminalsSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/pos-terminal-management/assing-terminals-success.json"); - var posTerminalManagement = new PosTerminalManagementService(client); - var assignTerminalsRequest = new AssignTerminalsRequest - { - MerchantAccount = "TestMerchant", - CompanyAccount = "TestMerchantAccount", - MerchantInventory = true, - Terminals = new List { "P400Plus-123456789" } - }; - var assignTerminalsResponse = posTerminalManagement.AssignTerminals(assignTerminalsRequest); - Assert.AreEqual(assignTerminalsResponse.Results["V400m-123456789"], "ActionScheduled"); - Assert.AreEqual(assignTerminalsResponse.Results["P400Plus-123456789"], "Done"); - } - - /// - /// Test post /getTerminalsUnderAccountResponse - /// - [TestMethod] - public void GetTerminalsUnderAccountSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/pos-terminal-management/get-terminals-under-account-success.json"); - var posTerminalManagement = new PosTerminalManagementService(client); - var getTerminalsUnderAccountRequest = new GetTerminalsUnderAccountRequest - { - CompanyAccount = "TestCompany", - }; - var getTerminalsUnderAccountResponse = posTerminalManagement.GetTerminalsUnderAccount(getTerminalsUnderAccountRequest); - Assert.AreEqual(getTerminalsUnderAccountResponse.CompanyAccount, "TestCompany"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0]._MerchantAccount, "TestMerchantPOS_EU"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[1]._MerchantAccount, "TestMerchantPOS_US"); - Assert.AreEqual(getTerminalsUnderAccountResponse.InventoryTerminals[0], "V400m-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.InventoryTerminals[1], "P400Plus-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0]._MerchantAccount, "TestMerchantPOS_EU"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].InventoryTerminals[0], "M400-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].InventoryTerminals[1], "VX820-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].InStoreTerminals[0], "E355-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].InStoreTerminals[1], "V240mPlus-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].Stores[0]._Store, "TestStore"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[0].Stores[0].InStoreTerminals[0], "MX925-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[1].InStoreTerminals[0], "VX820-123456789"); - Assert.AreEqual(getTerminalsUnderAccountResponse.MerchantAccounts[1].InStoreTerminals[1], "VX690-123456789"); - } - - /// - /// Test post /getTerminalDetails - /// - [TestMethod] - public void GetTerminalDetailsSuccess() - { - var client = - CreateMockTestClientApiKeyBasedRequestAsync( - "mocks/pos-terminal-management/get-terminals-details-success.json"); - var posTerminalManagement = new PosTerminalManagementService(client); - var getTerminalDetailsRequest = new GetTerminalDetailsRequest - { - Terminal = "P400Plus-275479597", - }; - var getTerminalDetailsResponse = - posTerminalManagement.GetTerminalDetails(getTerminalDetailsRequest); - Assert.AreEqual(getTerminalDetailsResponse.CompanyAccount, "YOUR_COMPANY_ACCOUNT"); - Assert.AreEqual(getTerminalDetailsResponse.MerchantAccount, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(getTerminalDetailsResponse.MerchantInventory, false); - Assert.AreEqual(getTerminalDetailsResponse.Terminal, "P400Plus-275479597"); - Assert.AreEqual(getTerminalDetailsResponse.DeviceModel, "P400Plus"); - Assert.AreEqual(getTerminalDetailsResponse.SerialNumber, "275-479-597"); - Assert.AreEqual(getTerminalDetailsResponse.PermanentTerminalId, "12000000"); - Assert.AreEqual(getTerminalDetailsResponse.FirmwareVersion, "Verifone_VOS 1.50.7"); - Assert.AreEqual(getTerminalDetailsResponse.TerminalStatus, GetTerminalDetailsResponse.TerminalStatusEnum.ReAssignToInventoryPending); - Assert.AreEqual(getTerminalDetailsResponse.Country, "NETHERLANDS"); - Assert.AreEqual(getTerminalDetailsResponse.DhcpEnabled, false); - } - - /// - /// Test post /getStoresUnderAccount - /// - [TestMethod] - public void GetStoresUnderAccountSuccess() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync( - "mocks/pos-terminal-management/get-stores-under-account-success.json"); - var posTerminalManagement = new PosTerminalManagementService(client); - var getStoresUnderAccountSuccessRequest = new GetStoresUnderAccountRequest - { - CompanyAccount = "MockCompanyAccount", - MerchantAccount = "TestMerchantAccount", - }; - var getStoresUnderAccountSuccessResponse = - posTerminalManagement.GetStoresUnderAccount(getStoresUnderAccountSuccessRequest); - Assert.AreEqual(getStoresUnderAccountSuccessResponse.Stores[0].MerchantAccountCode, "YOUR_MERCHANT_ACCOUNT"); - Assert.AreEqual(getStoresUnderAccountSuccessResponse.Stores[0]._Store, "YOUR_STORE"); - Assert.AreEqual(getStoresUnderAccountSuccessResponse.Stores[0].Description, "YOUR_STORE"); - Assert.AreEqual(getStoresUnderAccountSuccessResponse.Stores[0].Status, "Active"); - - } - } -} diff --git a/Adyen.Test/ReadmeTest.cs b/Adyen.Test/ReadmeTest.cs deleted file mode 100644 index 414c693b9..000000000 --- a/Adyen.Test/ReadmeTest.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Adyen; -using Adyen.Model.Checkout; -using Adyen.Service.Checkout; -using Environment = Adyen.Model.Environment; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class ReadmeTest - { - //Only test if compiles properly. It is not an integration test - [TestMethod] - public void PaymentTest() - { - var config = new Config() - { - XApiKey = "your-api-key", - Environment = Environment.Test - }; - var client = new Client(config); - var paymentsService = new PaymentsService(client); - var amount = new Model.Checkout.Amount("USD", 1000); - var cardDetails = new CardDetails - { - EncryptedCardNumber = "test_4111111111111111", - EncryptedSecurityCode = "test_737", - EncryptedExpiryMonth = "test_03", - EncryptedExpiryYear = "test_2030", - HolderName = "John Smith", - Type = CardDetails.TypeEnum.Card - }; - var paymentsRequest = new Model.Checkout.PaymentRequest - { - Reference = "Your order number ", - ReturnUrl = @"https://your-company.com/...", - MerchantAccount = "your-merchant-account", - Amount = amount, - PaymentMethod = new CheckoutPaymentMethod(cardDetails) - }; - } - } -} \ No newline at end of file diff --git a/Adyen.Test/Recurring/RecurringTest.cs b/Adyen.Test/Recurring/RecurringTest.cs new file mode 100644 index 000000000..c642b98df --- /dev/null +++ b/Adyen.Test/Recurring/RecurringTest.cs @@ -0,0 +1,126 @@ +using Adyen.Core.Options; +using Adyen.Recurring.Client; +using Adyen.Recurring.Models; +using Adyen.Recurring.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.Recurring +{ + [TestClass] + public class RecurringTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public RecurringTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureRecurring((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_ListRecurringDetails_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/listRecurringDetails-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(3L, response.Details.Count); + + Assert.AreEqual("BFXCHLC5L6KXWD82", response.Details[0].RecurringDetail.RecurringDetailReference); + Assert.AreEqual("K652534298119846", response.Details[0].RecurringDetail.Alias); + Assert.AreEqual("0002", response.Details[0].RecurringDetail.Card.Number); + + Assert.AreEqual("JW6RTP5PL6KXWD82", response.Details[1].RecurringDetail.RecurringDetailReference); + Assert.AreEqual("Wirecard", response.Details[1].RecurringDetail.Bank.BankName); + Assert.AreEqual("sepadirectdebit", response.Details[1].RecurringDetail.Variant); + } + + [TestMethod] + public async Task Given_Deserialize_When_Disable_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/disable-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("[detail-successfully-disabled]", response.Response); + } + + [TestMethod] + public async Task Given_Deserialize_When_NotifyShopper_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/notifyShopper-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("Example displayed reference", response.DisplayedReference); + Assert.AreEqual("8516167336214570", response.PspReference); + Assert.AreEqual("Request processed successfully", response.Message); + Assert.AreEqual("Example reference", response.Reference); + Assert.AreEqual("Success", response.ResultCode); + Assert.AreEqual("IA0F7500002462", response.ShopperNotificationReference); + } + + [TestMethod] + public async Task Given_Deserialize_When_CreatePermit_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/createPermit-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("string", response.PspReference); + Assert.AreEqual(1, response.PermitResultList.Count); + } + + [TestMethod] + public async Task Given_Deserialize_When_DisablePermit_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/disablePermit-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("string", response.PspReference); + Assert.AreEqual("disabled",response.Status); + } + + [TestMethod] + public async Task Given_Deserialize_When_ScheduleAccountUpdater_Result_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/recurring/scheduleAccountUpdater-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual("string", response.PspReference); + Assert.AreEqual("string", response.Result); + } + } +} diff --git a/Adyen.Test/RecurringTest.cs b/Adyen.Test/RecurringTest.cs deleted file mode 100644 index 101fc6fa2..000000000 --- a/Adyen.Test/RecurringTest.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Threading.Tasks; -using Adyen.Model.Recurring; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class RecurringTest : BaseTest - { - - [TestMethod] - public void TestListRecurringDetails() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/listRecurringDetails-success.json"); - var recurring = new Service.RecurringService(client); - var recurringDetailsRequest = CreateRecurringDetailsRequest(); - var recurringDetailsResult = recurring.ListRecurringDetails(recurringDetailsRequest); - Assert.AreEqual(3L, recurringDetailsResult.Details.Count); - var recurringDetail = recurringDetailsResult.Details[0].RecurringDetail; - - Assert.AreEqual("BFXCHLC5L6KXWD82", recurringDetail.RecurringDetailReference); - Assert.AreEqual("K652534298119846", recurringDetail.Alias); - Assert.AreEqual("0002", recurringDetail.Card.Number); - } - - [TestMethod] - public async Task TestListRecurringDetailsAsync() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/listRecurringDetails-success.json"); - var recurring = new Service.RecurringService(client); - var recurringDetailsRequest = CreateRecurringDetailsRequest(); - var recurringDetailsResult = await recurring.ListRecurringDetailsAsync(recurringDetailsRequest); - Assert.AreEqual(3L, recurringDetailsResult.Details.Count); - var recurringDetail = recurringDetailsResult.Details[1].RecurringDetail; - Assert.AreEqual("JW6RTP5PL6KXWD82", recurringDetail.RecurringDetailReference); - Assert.AreEqual("Wirecard", recurringDetail.Bank.BankName); - Assert.AreEqual("sepadirectdebit", recurringDetail.Variant); - } - - [TestMethod] - public void TestDisable() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/disable-success.json"); - var recurring = new Service.RecurringService(client); - var disableRequest = CreateDisableRequest(); - var disableResult = recurring.Disable(disableRequest); - Assert.AreEqual("[detail-successfully-disabled]", disableResult.Response); - } - - [TestMethod] - public async Task TestDisableAsync() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/disable-success.json"); - var recurring = new Service.RecurringService(client); - var disableRequest = CreateDisableRequest(); - var disableResult = await recurring.DisableAsync(disableRequest); - Assert.AreEqual("[detail-successfully-disabled]", disableResult.Response); - } - - [TestMethod] - public void NotifyShopperTest() - { - Client client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/notifyShopper-success.json"); - var recurring = new Service.RecurringService(client); - NotifyShopperRequest request = CreateNotifyShopperRequest(); - NotifyShopperResult result = recurring.NotifyShopper(request); - Assert.IsNotNull(result); - Assert.AreEqual("Example displayed reference", result.DisplayedReference); - Assert.AreEqual("8516167336214570", result.PspReference); - Assert.AreEqual("Request processed successfully", result.Message); - Assert.AreEqual("Example reference", result.Reference); - Assert.AreEqual("Success", result.ResultCode); - Assert.AreEqual("IA0F7500002462", result.ShopperNotificationReference); - } - - [TestMethod] - public void CreatePermitTest() - { - Client client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/createPermit-success.json"); - var recurring = new Service.RecurringService(client); - var createPermitResult = recurring.CreatePermit(new CreatePermitRequest()); - Assert.IsNotNull(createPermitResult); - Assert.AreEqual("string", createPermitResult.PspReference); - Assert.AreEqual(1,createPermitResult.PermitResultList.Count); - } - - [TestMethod] - public void DisablePermitTest() - { - Client client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/disablePermit-success.json"); - var recurring = new Service.RecurringService(client); - var disablePermitResult = recurring.DisablePermit(new DisablePermitRequest()); - Assert.IsNotNull(disablePermitResult); - Assert.AreEqual("string", disablePermitResult.PspReference); - Assert.AreEqual("disabled",disablePermitResult.Status); - } - - [TestMethod] - public void ScheduleAccountUpdaterTest() - { - Client client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/recurring/scheduleAccountUpdater-success.json"); - var recurring = new Service.RecurringService(client); - var scheduleAccountUpdaterResult = recurring.ScheduleAccountUpdater(new ScheduleAccountUpdaterRequest()); - Assert.IsNotNull(scheduleAccountUpdaterResult); - Assert.AreEqual("string", scheduleAccountUpdaterResult.PspReference); - Assert.AreEqual("string",scheduleAccountUpdaterResult.Result); - } - - private RecurringDetailsRequest CreateRecurringDetailsRequest() - { - var request = new RecurringDetailsRequest - { - ShopperReference = "test-123", - MerchantAccount = "DotNetAlexandros", - Recurring = new Recurring(Recurring.ContractEnum.RECURRING) - }; - return request; - } - - private DisableRequest CreateDisableRequest() - { - var request = new DisableRequest - { - ShopperReference = "test-123", - MerchantAccount = "DotNetAlexandros" - }; - return request; - } - - private NotifyShopperRequest CreateNotifyShopperRequest() - { - return new NotifyShopperRequest - { - MerchantAccount = "TestMerchant", - RecurringDetailReference = "8316158654144897", - Reference = "Example reference", - ShopperReference = "1234567", - BillingDate = "2021-03-31", - DisplayedReference = "Example displayed reference" - }; - } - } -} diff --git a/Adyen.Test/StoredValue/StoredValueTest.cs b/Adyen.Test/StoredValue/StoredValueTest.cs new file mode 100644 index 000000000..95a9f4286 --- /dev/null +++ b/Adyen.Test/StoredValue/StoredValueTest.cs @@ -0,0 +1,116 @@ +using Adyen.Core.Options; +using Adyen.StoredValue.Client; +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.StoredValue +{ + [TestClass] + public class StoredValueTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public StoredValueTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureStoredValue((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoredValueIssue_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/issue-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueIssueResponse.ResultCodeEnum.Success); + Assert.AreEqual(response.AuthCode, "authCode"); + } + + [TestMethod] + public async Task Given_Deserialize_When_ChangeStatus_StoredValueStatusChange_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/changeStatus-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueStatusChangeResponse.ResultCodeEnum.Refused); + Assert.AreEqual(response.AuthCode, "authCode"); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoredValueLoad_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/load-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueLoadResponse.ResultCodeEnum.Success); + Assert.AreEqual(response.AuthCode, "authCode"); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoredValueBalanceCheck_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/checkBalance-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueBalanceCheckResponse.ResultCodeEnum.Success); + Assert.AreEqual(response.CurrentBalance.Value, 0); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoredValueBalanceMerge_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/mergeBalance-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueBalanceMergeResponse.ResultCodeEnum.Success); + Assert.AreEqual(response.CurrentBalance.Value, 0); + } + + [TestMethod] + public async Task Given_Deserialize_When_StoredValueVoid_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/storedvalue/mergeBalance-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.ResultCode, StoredValueVoidResponse.ResultCodeEnum.Success); + Assert.AreEqual(response.CurrentBalance.Value, 0); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/StoredValueTest.cs b/Adyen.Test/StoredValueTest.cs deleted file mode 100644 index cb0f0e3d3..000000000 --- a/Adyen.Test/StoredValueTest.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Adyen.Model.StoredValue; -using Adyen.Service; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test -{ - [TestClass] - public class StoredValueTest : BaseTest - { - [TestMethod] - public void StoredValueIssueTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/issue-success.json"); - var service = new StoredValueService(client); - var response = service.Issue(new StoredValueIssueRequest()); - Assert.AreEqual(response.ResultCode, StoredValueIssueResponse.ResultCodeEnum.Success); - Assert.AreEqual(response.AuthCode, "authCode"); - } - - [TestMethod] - public void StoredValueChangeStatusTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/changeStatus-success.json"); - var service = new StoredValueService(client); - var response = service.ChangeStatus(new StoredValueStatusChangeRequest()); - Assert.AreEqual(response.ResultCode, StoredValueStatusChangeResponse.ResultCodeEnum.Refused); - Assert.AreEqual(response.AuthCode, "authCode"); - } - - [TestMethod] - public void StoredValueLoadTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/load-success.json"); - var service = new StoredValueService(client); - var response = service.Load(new StoredValueLoadRequest()); - Assert.AreEqual(response.ResultCode, StoredValueLoadResponse.ResultCodeEnum.Success); - Assert.AreEqual(response.AuthCode, "authCode"); - } - - [TestMethod] - public void StoredValueCheckBalanceTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/checkBalance-success.json"); - var service = new StoredValueService(client); - var response = service.CheckBalance(new StoredValueBalanceCheckRequest()); - Assert.AreEqual(response.ResultCode, StoredValueBalanceCheckResponse.ResultCodeEnum.Success); - Assert.AreEqual(response.CurrentBalance.Value, 0); - } - - [TestMethod] - public void StoredValueMergeBalanceTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/mergeBalance-success.json"); - var service = new StoredValueService(client); - var response = service.MergeBalance(new StoredValueBalanceMergeRequest()); - Assert.AreEqual(response.ResultCode, StoredValueBalanceMergeResponse.ResultCodeEnum.Success); - Assert.AreEqual(response.CurrentBalance.Value, 0); - } - - [TestMethod] - public void StoredValueVoidTransactionTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/storedvalue/mergeBalance-success.json"); - var service = new StoredValueService(client); - var response = service.VoidTransactionAsync(new StoredValueVoidRequest()).Result; - Assert.AreEqual(response.ResultCode, StoredValueVoidResponse.ResultCodeEnum.Success); - Assert.AreEqual(response.CurrentBalance.Value, 0); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/BaseTest.cs b/Adyen.Test/TerminalApi/BaseTest.cs similarity index 91% rename from Adyen.Test/BaseTest.cs rename to Adyen.Test/TerminalApi/BaseTest.cs index f9e195846..7c1911280 100644 --- a/Adyen.Test/BaseTest.cs +++ b/Adyen.Test/TerminalApi/BaseTest.cs @@ -1,439 +1,413 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Adyen.Constants; -using Adyen.HttpClient.Interfaces; -using Adyen.Model; -using Adyen.Model.TerminalApi; -using Adyen.Model.Payment; -using Adyen.Service; -using NSubstitute; -using Amount = Adyen.Model.Checkout; -using Environment = System.Environment; -using PaymentResult = Adyen.Model.Payment.PaymentResult; - -namespace Adyen.Test -{ - public class BaseTest - { - private protected IClient ClientInterfaceSubstitute; - - #region Payment request - /// - /// Payment with basic authentication - /// - /// - /// - protected PaymentResult CreatePaymentResultFromFile(string fileName) - { - var client = CreateMockTestClientApiKeyBasedRequestAsync(fileName); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest(); - var paymentResult = payment.Authorise(paymentRequest); - return paymentResult; - } - - protected PaymentResult CreatePaymentApiKeyBasedResultFromFile(string fileName) - { - var client = CreateMockTestClientApiKeyBasedRequestAsync(fileName); - var payment = new PaymentService(client); - var paymentRequest = MockPaymentData.CreateFullPaymentRequest(); - - var paymentResult = payment.Authorise(paymentRequest); - return paymentResult; - } - #endregion - - #region Modification objects - - protected CaptureRequest CreateCaptureTestRequest(string pspReference) - { - var captureRequest = new CaptureRequest - { - MerchantAccount = "MerchantAccount", - ModificationAmount = new Model.Payment.Amount("EUR", 150), - Reference = "capture - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference, - AdditionalData = new Dictionary {{"authorisationType", "PreAuth"}} - }; - return captureRequest; - } - - - protected CancelOrRefundRequest CreateCancelOrRefundTestRequest(string pspReference) - { - var cancelOrRefundRequest = new CancelOrRefundRequest - { - MerchantAccount = "MerchantAccount", - Reference = "cancelOrRefund - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return cancelOrRefundRequest; - } - - protected RefundRequest CreateRefundTestRequest(string pspReference) - { - var refundRequest = new RefundRequest - { - MerchantAccount = "MerchantAccount", - ModificationAmount = new Model.Payment.Amount("EUR", 150), - Reference = "refund - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return refundRequest; - } - - protected CancelRequest CreateCancelTestRequest(string pspReference) - { - var cancelRequest = new CancelRequest - { - MerchantAccount = "MerchantAccount", - Reference = "cancel - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference - }; - return cancelRequest; - } - - protected AdjustAuthorisationRequest CreateAdjustAuthorisationRequest(string pspReference) - { - var adjustAuthorisationRequest = new AdjustAuthorisationRequest - { - MerchantAccount = "MerchantAccount", - ModificationAmount = new Model.Payment.Amount("EUR", 150), - Reference = "adjustAuthorisationRequest - " + DateTime.Now.ToString("yyyyMMdd"), - OriginalReference = pspReference, - }; - return adjustAuthorisationRequest; - } - #endregion - - #region Checkout - /// - /// Check out payment request - /// - /// - /// - public Model.Checkout.PaymentRequest CreatePaymentRequestCheckout() - { - var amount = new Model.Checkout.Amount("USD", 1000); - var paymentsRequest = new Model.Checkout.PaymentRequest - { - Reference = "Your order number ", - ReturnUrl = @"https://your-company.com/...", - MerchantAccount = "MerchantAccount", - CaptureDelayHours = 0 - }; - var cardDetails = new Amount.CardDetails - { - Number = "4111111111111111", - ExpiryMonth = "10", - ExpiryYear = "2020", - HolderName = "John Smith" - }; - paymentsRequest.Amount = amount; - paymentsRequest.PaymentMethod = new Amount.CheckoutPaymentMethod(cardDetails); - paymentsRequest.ApplicationInfo = new Model.Checkout.ApplicationInfo(adyenLibrary: new Amount.CommonField()); - return paymentsRequest; - } - - - /// - /// 3DS2 payments request - /// - /// - public Model.Checkout.PaymentRequest CreatePaymentRequest3DS2() - { - var amount = new Model.Checkout.Amount("USD", 1000); - var paymentsRequest = new Model.Checkout.PaymentRequest - { - Reference = "Your order number ", - Amount = amount, - ReturnUrl = @"https://your-company.com/...", - MerchantAccount = "MerchantAccount", - Channel = Model.Checkout.PaymentRequest.ChannelEnum.Web - }; - var cardDetails = new Amount.CardDetails - { - Number = "4111111111111111", - ExpiryMonth = "10", - ExpiryYear = "2020", - HolderName = "John Smith" - }; - paymentsRequest.PaymentMethod = new Amount.CheckoutPaymentMethod(cardDetails); - return paymentsRequest; - } - - /// - ///Checkout Details request - /// - /// Returns a sample PaymentsDetailsRequest object with test data - protected Amount.PaymentDetailsRequest CreateDetailsRequest() - { - var paymentData = "Ab02b4c0!BQABAgCJN1wRZuGJmq8dMncmypvknj9s7l5Tj..."; - var details = new Amount.PaymentCompletionDetails - { - MD= "sdfsdfsdf...", - PaReq = "sdfsdfsdf..." - }; - var paymentsDetailsRequest = new Amount.PaymentDetailsRequest(details: details, paymentData: paymentData); - - return paymentsDetailsRequest; - } - - /// - /// Checkout paymentMethodsRequest - /// - /// - protected Amount.PaymentMethodsRequest CreatePaymentMethodRequest(string merchantAccount) - { - return new Amount.PaymentMethodsRequest(merchantAccount: merchantAccount); - } - - #endregion - - /// - /// Creates mock test client without any response - /// - /// IClient implementation - protected Client CreateMockForAdyenClientTest(Config config) - { - //Create a mock interface - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()).Returns(Task.FromResult("")); - - var clientMock = new Client(config) - { - HttpClient = ClientInterfaceSubstitute, - Config = config - }; - return clientMock; - } - - /// - /// Creates mock test client - /// - /// The file that is returned - /// IClient implementation - protected Client CreateMockTestClientRequest(string fileName) - { - var mockPath = GetMockFilePath(fileName); - var response = MockFileToString(mockPath); - - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()).Returns(response); - - var config = new Config - { - Environment = Model.Environment.Test - }; - var clientMock = new Client(config) - { - HttpClient = ClientInterfaceSubstitute, - Config = new Config - { - Username = "Username", - Password = "Password", - ApplicationName = "Appname" - } - }; - return clientMock; - } - - /// - /// Creates mock test client - /// - /// The file that is returned - /// IClient implementation - protected Client CreateMockTestClientApiKeyBasedRequestAsync(string fileName) - { - var mockPath = GetMockFilePath(fileName); - var response = MockFileToString(mockPath); - //Create a mock interface - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()).Returns(response); - var config = new Config - { - Environment = Model.Environment.Test - }; - var clientMock = new Client(config) - { - HttpClient = ClientInterfaceSubstitute, - Config = new Config - { - Username = "Username", - Password = "Password", - ApplicationName = "Appname" - } - }; - return clientMock; - } - - /// - /// Creates async mock test client - /// - /// The file that is returned - /// IClient implementation - protected Client CreateAsyncMockTestClientApiKeyBasedRequest(string fileName) - { - var mockPath = GetMockFilePath(fileName); - var response = MockFileToString(mockPath); - - var configWithApiKey = new Config - { - Environment = Model.Environment.Test, - XApiKey = "AQEyhmfxK....LAG84XwzP5pSpVd" - }; - - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()).Returns(response); - - var config = new Config - { - Environment = Model.Environment.Test - }; - var clientMock = new Client(config) - { - HttpClient = ClientInterfaceSubstitute, - Config = configWithApiKey - }; - return clientMock; - } - - /// - /// Creates mock test client for POS cloud. In case of cloud api the xapi should be included - /// - /// The file that is returned - /// IClient implementation - protected Client CreateMockTestClientPosCloudApiRequest(string fileName) - { - var config = new Config { CloudApiEndPoint = ClientConfig.CloudApiEndPointTest }; - var mockPath = GetMockFilePath(fileName); - var response = MockFileToString(mockPath); - - //Create a mock interface - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.Request(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any()).Returns(response); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.FromResult(response)); - - var anyConfig = new Config - { - Environment = Model.Environment.Test - }; - var clientMock = new Client(anyConfig) - { - HttpClient = ClientInterfaceSubstitute, - Config = config - }; - return clientMock; - } - - /// - /// Creates mock test client for terminal api. - /// - /// The file that is returned - /// IClient implementation - protected Client CreateMockTestClientPosLocalApiRequest(string fileName) - { - var config = new Config - { - Environment = Model.Environment.Test, - LocalTerminalApiEndpoint = @"https://_terminal_:8443/nexo/" - }; - var mockPath = GetMockFilePath(fileName); - var response = MockFileToString(mockPath); - //Create a mock interface - ClientInterfaceSubstitute = Substitute.For(); - - ClientInterfaceSubstitute.Request(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any()).Returns(response); - - ClientInterfaceSubstitute.RequestAsync(Arg.Any(), - Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.FromResult(response)); - - - var anyConfig = new Config - { - Environment = Model.Environment.Test - }; - var clientMock = new Client(anyConfig) - { - HttpClient = ClientInterfaceSubstitute, - Config = config - }; - return clientMock; - } - - protected string MockFileToString(string fileName) - { - string text = ""; - - if (String.IsNullOrEmpty(fileName)) - { - return text; - } - try - { - using (var streamReader = new StreamReader(fileName, Encoding.UTF8)) - { - text = streamReader.ReadToEnd(); - } - } - catch (Exception exception) - { - throw exception; - } - - return text; - } - - /// - /// Create dummy Nexo message header - /// - /// - protected MessageHeader MockNexoMessageHeaderRequest() - { - var header = new MessageHeader - { - MessageType = MessageType.Request, - MessageClass = MessageClassType.Service, - MessageCategory = MessageCategoryType.Payment, - SaleID = "POSSystemID12345", - POIID = "MX915-284251016", - - ServiceID = (new Random()).Next(1, 9999).ToString() - }; - return header; - } - - protected static string GetMockFilePath(string fileName) - { - if (string.IsNullOrEmpty(fileName)) - { - return ""; - } - var projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName; - var mockPath = Path.Combine(projectPath, fileName); - return mockPath; - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Adyen.Constants; +using Adyen.HttpClient.Interfaces; +using Adyen.Model; +using Adyen.Model.TerminalApi; +using Adyen.Model.Payment; +using Adyen.Service; +using NSubstitute; +using Amount = Adyen.Model.Checkout; +using Environment = System.Environment; +using PaymentResult = Adyen.Model.Payment.PaymentResult; + +namespace Adyen.Test +{ + public class BaseTest + { + private protected IClient ClientInterfaceSubstitute; + + #region Modification objects + + protected CaptureRequest CreateCaptureTestRequest(string pspReference) + { + var captureRequest = new CaptureRequest + { + MerchantAccount = "MerchantAccount", + ModificationAmount = new Model.Payment.Amount("EUR", 150), + Reference = "capture - " + DateTime.Now.ToString("yyyyMMdd"), + OriginalReference = pspReference, + AdditionalData = new Dictionary {{"authorisationType", "PreAuth"}} + }; + return captureRequest; + } + + + protected CancelOrRefundRequest CreateCancelOrRefundTestRequest(string pspReference) + { + var cancelOrRefundRequest = new CancelOrRefundRequest + { + MerchantAccount = "MerchantAccount", + Reference = "cancelOrRefund - " + DateTime.Now.ToString("yyyyMMdd"), + OriginalReference = pspReference + }; + return cancelOrRefundRequest; + } + + protected RefundRequest CreateRefundTestRequest(string pspReference) + { + var refundRequest = new RefundRequest + { + MerchantAccount = "MerchantAccount", + ModificationAmount = new Model.Payment.Amount("EUR", 150), + Reference = "refund - " + DateTime.Now.ToString("yyyyMMdd"), + OriginalReference = pspReference + }; + return refundRequest; + } + + protected CancelRequest CreateCancelTestRequest(string pspReference) + { + var cancelRequest = new CancelRequest + { + MerchantAccount = "MerchantAccount", + Reference = "cancel - " + DateTime.Now.ToString("yyyyMMdd"), + OriginalReference = pspReference + }; + return cancelRequest; + } + + protected AdjustAuthorisationRequest CreateAdjustAuthorisationRequest(string pspReference) + { + var adjustAuthorisationRequest = new AdjustAuthorisationRequest + { + MerchantAccount = "MerchantAccount", + ModificationAmount = new Model.Payment.Amount("EUR", 150), + Reference = "adjustAuthorisationRequest - " + DateTime.Now.ToString("yyyyMMdd"), + OriginalReference = pspReference, + }; + return adjustAuthorisationRequest; + } + #endregion + + #region Checkout + /// + /// Check out payment request + /// + /// + /// + public Model.Checkout.PaymentRequest CreatePaymentRequestCheckout() + { + var amount = new Model.Checkout.Amount("USD", 1000); + var paymentsRequest = new Model.Checkout.PaymentRequest + { + Reference = "Your order number ", + ReturnUrl = @"https://your-company.com/...", + MerchantAccount = "MerchantAccount", + CaptureDelayHours = 0 + }; + var cardDetails = new Amount.CardDetails + { + Number = "4111111111111111", + ExpiryMonth = "10", + ExpiryYear = "2020", + HolderName = "John Smith" + }; + paymentsRequest.Amount = amount; + paymentsRequest.PaymentMethod = new Amount.CheckoutPaymentMethod(cardDetails); + paymentsRequest.ApplicationInfo = new Model.Checkout.ApplicationInfo(adyenLibrary: new Amount.CommonField()); + return paymentsRequest; + } + + + /// + /// 3DS2 payments request + /// + /// + public Model.Checkout.PaymentRequest CreatePaymentRequest3DS2() + { + var amount = new Model.Checkout.Amount("USD", 1000); + var paymentsRequest = new Model.Checkout.PaymentRequest + { + Reference = "Your order number ", + Amount = amount, + ReturnUrl = @"https://your-company.com/...", + MerchantAccount = "MerchantAccount", + Channel = Model.Checkout.PaymentRequest.ChannelEnum.Web + }; + var cardDetails = new Amount.CardDetails + { + Number = "4111111111111111", + ExpiryMonth = "10", + ExpiryYear = "2020", + HolderName = "John Smith" + }; + paymentsRequest.PaymentMethod = new Amount.CheckoutPaymentMethod(cardDetails); + return paymentsRequest; + } + + /// + ///Checkout Details request + /// + /// Returns a sample PaymentsDetailsRequest object with test data + protected Amount.PaymentDetailsRequest CreateDetailsRequest() + { + var paymentData = "Ab02b4c0!BQABAgCJN1wRZuGJmq8dMncmypvknj9s7l5Tj..."; + var details = new Amount.PaymentCompletionDetails + { + MD= "sdfsdfsdf...", + PaReq = "sdfsdfsdf..." + }; + var paymentsDetailsRequest = new Amount.PaymentDetailsRequest(details: details, paymentData: paymentData); + + return paymentsDetailsRequest; + } + + /// + /// Checkout paymentMethodsRequest + /// + /// + protected Amount.PaymentMethodsRequest CreatePaymentMethodRequest(string merchantAccount) + { + return new Amount.PaymentMethodsRequest(merchantAccount: merchantAccount); + } + + #endregion + + /// + /// Creates mock test client without any response + /// + /// IClient implementation + protected Client CreateMockForAdyenClientTest(Config config) + { + //Create a mock interface + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any()).Returns(Task.FromResult("")); + + var clientMock = new Client(config) + { + HttpClient = ClientInterfaceSubstitute, + Config = config + }; + return clientMock; + } + + /// + /// Creates mock test client + /// + /// The file that is returned + /// IClient implementation + protected Client CreateMockTestClientRequest(string fileName) + { + var mockPath = GetMockFilePath(fileName); + var response = MockFileToString(mockPath); + + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any()).Returns(response); + + var config = new Config + { + Environment = Model.Environment.Test + }; + var clientMock = new Client(config) + { + HttpClient = ClientInterfaceSubstitute, + Config = new Config + { + Username = "Username", + Password = "Password", + ApplicationName = "Appname" + } + }; + return clientMock; + } + + /// + /// Creates mock test client + /// + /// The file that is returned + /// IClient implementation + protected Client CreateMockTestClientApiKeyBasedRequestAsync(string fileName) + { + var mockPath = GetMockFilePath(fileName); + var response = MockFileToString(mockPath); + //Create a mock interface + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any()).Returns(response); + var config = new Config + { + Environment = Model.Environment.Test + }; + var clientMock = new Client(config) + { + HttpClient = ClientInterfaceSubstitute, + Config = new Config + { + Username = "Username", + Password = "Password", + ApplicationName = "Appname" + } + }; + return clientMock; + } + + /// + /// Creates async mock test client + /// + /// The file that is returned + /// IClient implementation + protected Client CreateAsyncMockTestClientApiKeyBasedRequest(string fileName) + { + var mockPath = GetMockFilePath(fileName); + var response = MockFileToString(mockPath); + + var configWithApiKey = new Config + { + Environment = Model.Environment.Test, + XApiKey = "AQEyhmfxK....LAG84XwzP5pSpVd" + }; + + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any()).Returns(response); + + var config = new Config + { + Environment = Model.Environment.Test + }; + var clientMock = new Client(config) + { + HttpClient = ClientInterfaceSubstitute, + Config = configWithApiKey + }; + return clientMock; + } + + /// + /// Creates mock test client for POS cloud. In case of cloud api the xapi should be included + /// + /// The file that is returned + /// IClient implementation + protected Client CreateMockTestClientPosCloudApiRequest(string fileName) + { + var config = new Config { CloudApiEndPoint = ClientConfig.CloudApiEndPointTest }; + var mockPath = GetMockFilePath(fileName); + var response = MockFileToString(mockPath); + + //Create a mock interface + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.Request(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(response); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.FromResult(response)); + + var anyConfig = new Config + { + Environment = Model.Environment.Test + }; + var clientMock = new Client(anyConfig) + { + HttpClient = ClientInterfaceSubstitute, + Config = config + }; + return clientMock; + } + + /// + /// Creates mock test client for terminal api. + /// + /// The file that is returned + /// IClient implementation + protected Client CreateMockTestClientPosLocalApiRequest(string fileName) + { + var config = new Config + { + Environment = Model.Environment.Test, + LocalTerminalApiEndpoint = @"https://_terminal_:8443/nexo/" + }; + var mockPath = GetMockFilePath(fileName); + var response = MockFileToString(mockPath); + //Create a mock interface + ClientInterfaceSubstitute = Substitute.For(); + + ClientInterfaceSubstitute.Request(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(response); + + ClientInterfaceSubstitute.RequestAsync(Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.FromResult(response)); + + + var anyConfig = new Config + { + Environment = Model.Environment.Test + }; + var clientMock = new Client(anyConfig) + { + HttpClient = ClientInterfaceSubstitute, + Config = config + }; + return clientMock; + } + + protected string MockFileToString(string fileName) + { + string text = ""; + + if (String.IsNullOrEmpty(fileName)) + { + return text; + } + try + { + using (var streamReader = new StreamReader(fileName, Encoding.UTF8)) + { + text = streamReader.ReadToEnd(); + } + } + catch (Exception exception) + { + throw exception; + } + + return text; + } + + /// + /// Create dummy Nexo message header + /// + /// + protected MessageHeader MockNexoMessageHeaderRequest() + { + var header = new MessageHeader + { + MessageType = MessageType.Request, + MessageClass = MessageClassType.Service, + MessageCategory = MessageCategoryType.Payment, + SaleID = "POSSystemID12345", + POIID = "MX915-284251016", + + ServiceID = (new Random()).Next(1, 9999).ToString() + }; + return header; + } + + protected static string GetMockFilePath(string fileName) + { + if (string.IsNullOrEmpty(fileName)) + { + return ""; + } + var projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName; + var mockPath = Path.Combine(projectPath, fileName); + return mockPath; + } + } +} diff --git a/Adyen.Test/ClientTest.cs b/Adyen.Test/TerminalApi/ClientTest.cs similarity index 96% rename from Adyen.Test/ClientTest.cs rename to Adyen.Test/TerminalApi/ClientTest.cs index 99a712e62..a592d91e0 100644 --- a/Adyen.Test/ClientTest.cs +++ b/Adyen.Test/TerminalApi/ClientTest.cs @@ -32,14 +32,14 @@ public void TestSetEnvironment() Assert.AreEqual("https://terminal-api-test.adyen.com", client.Config.CloudApiEndPoint); } - Client testClient; + Client _testClient; String logLine; [TestInitialize] public void TestSetup() { - testClient = new Client(new Config()); - testClient.LogCallback += new Client.CallbackLogHandler((message) => { + _testClient = new Client(new Config()); + _testClient.LogCallback += new Client.CallbackLogHandler((message) => { logLine = message; }); @@ -47,7 +47,7 @@ public void TestSetup() [TestMethod] public void TestLogLine() { - testClient.LogLine("testMessage"); + _testClient.LogLine("testMessage"); Assert.AreEqual("testMessage", logLine); } diff --git a/Adyen.Test/DeserializerTest.cs b/Adyen.Test/TerminalApi/DeserializerTest.cs similarity index 100% rename from Adyen.Test/DeserializerTest.cs rename to Adyen.Test/TerminalApi/DeserializerTest.cs diff --git a/Adyen.Test/HeaderRequestTest.cs b/Adyen.Test/TerminalApi/HeaderRequestTest.cs similarity index 90% rename from Adyen.Test/HeaderRequestTest.cs rename to Adyen.Test/TerminalApi/HeaderRequestTest.cs index 5b9282498..ac8b1cf7f 100644 --- a/Adyen.Test/HeaderRequestTest.cs +++ b/Adyen.Test/TerminalApi/HeaderRequestTest.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Net.Http; using Adyen.Constants; +using Adyen.Core.Client.Extensions; using Adyen.HttpClient; using Adyen.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -165,7 +166,7 @@ public void UserAgentPresentWhenApplicationNameIsProvidedTest() var client = new HttpClientWrapper(config, new System.Net.Http.HttpClient()); HttpRequestMessage httpWebRequest = client.GetHttpRequestMessage(_endpoint, "requestBody", null, null); - Assert.AreEqual(httpWebRequest.Headers.GetValues("UserAgent").FirstOrDefault(), $"YourApplicationName {ClientConfig.LibName}/{ClientConfig.LibVersion}"); + Assert.AreEqual(httpWebRequest.Headers.GetValues("UserAgent").FirstOrDefault(), $"YourApplicationName {HttpRequestMessageExtensions.AdyenLibraryName}/{HttpRequestMessageExtensions.AdyenLibraryVersion}"); } [TestMethod] @@ -181,7 +182,7 @@ public void UserAgentPresentWhenApplicationNameIsNotProvidedTest() var client = new HttpClientWrapper(config, new System.Net.Http.HttpClient()); HttpRequestMessage httpWebRequest = client.GetHttpRequestMessage(_endpoint, "requestBody", null, null); - Assert.AreEqual(httpWebRequest.Headers.GetValues("UserAgent").FirstOrDefault(), $"{ClientConfig.LibName}/{ClientConfig.LibVersion}"); + Assert.AreEqual(httpWebRequest.Headers.GetValues("UserAgent").FirstOrDefault(), $"{HttpRequestMessageExtensions.AdyenLibraryName}/{HttpRequestMessageExtensions.AdyenLibraryVersion}"); } [TestMethod] @@ -197,10 +198,10 @@ public void LibraryAnalysisConstantsInHeaderTest() var client = new HttpClientWrapper(config, new System.Net.Http.HttpClient()); HttpRequestMessage httpWebRequest = client.GetHttpRequestMessage(_endpoint, "requestBody", null, null); - Assert.IsNotNull(httpWebRequest.Headers.GetValues(ApiConstants.AdyenLibraryName)); - Assert.AreEqual(ClientConfig.LibName, httpWebRequest.Headers.GetValues(ApiConstants.AdyenLibraryName).FirstOrDefault()); - Assert.IsNotNull(httpWebRequest.Headers.GetValues(ApiConstants.AdyenLibraryVersion)); - Assert.AreEqual(ClientConfig.LibVersion, httpWebRequest.Headers.GetValues(ApiConstants.AdyenLibraryVersion).FirstOrDefault()); + Assert.IsNotNull(httpWebRequest.Headers.GetValues("adyen-library-name")); + Assert.AreEqual(HttpRequestMessageExtensions.AdyenLibraryName, httpWebRequest.Headers.GetValues("adyen-library-name").FirstOrDefault()); + Assert.IsNotNull(httpWebRequest.Headers.GetValues("adyen-library-version")); + Assert.AreEqual(HttpRequestMessageExtensions.AdyenLibraryVersion, httpWebRequest.Headers.GetValues("adyen-library-version").FirstOrDefault()); } } } diff --git a/Adyen.Test/MockPosApiRequest.cs b/Adyen.Test/TerminalApi/MockPosApiRequest.cs similarity index 100% rename from Adyen.Test/MockPosApiRequest.cs rename to Adyen.Test/TerminalApi/MockPosApiRequest.cs diff --git a/Adyen.Test/NotificationDecryptionTest.cs b/Adyen.Test/TerminalApi/NotificationDecryptionTest.cs similarity index 100% rename from Adyen.Test/NotificationDecryptionTest.cs rename to Adyen.Test/TerminalApi/NotificationDecryptionTest.cs diff --git a/Adyen.Test/ProxyTest.cs b/Adyen.Test/TerminalApi/ProxyTest.cs similarity index 100% rename from Adyen.Test/ProxyTest.cs rename to Adyen.Test/TerminalApi/ProxyTest.cs diff --git a/Adyen.Test/RegionTest.cs b/Adyen.Test/TerminalApi/RegionTest.cs similarity index 100% rename from Adyen.Test/RegionTest.cs rename to Adyen.Test/TerminalApi/RegionTest.cs diff --git a/Adyen.Test/Terminal/SaleToAcquirerDataTest.cs b/Adyen.Test/TerminalApi/SaleToAcquirerDataTest.cs similarity index 98% rename from Adyen.Test/Terminal/SaleToAcquirerDataTest.cs rename to Adyen.Test/TerminalApi/SaleToAcquirerDataTest.cs index dea0b56fd..4c7248eb6 100644 --- a/Adyen.Test/Terminal/SaleToAcquirerDataTest.cs +++ b/Adyen.Test/TerminalApi/SaleToAcquirerDataTest.cs @@ -15,13 +15,13 @@ public class SaleToAcquirerDataTest { private readonly string json = "{\"metadata\":{\"key\":\"value\"},\"shopperEmail\":\"myemail@mail.com\",\"shopperReference\":\"13164308\",\"recurringProcessingModel\":\"Subscription\",\"recurringContract\":\"RECURRING,ONECLICK\",\"shopperStatement\":\"YOUR SHOPPER STATEMENT\",\"recurringDetailName\":\"VALUE\",\"recurringTokenService\":\"VALUE\",\"store\":\"store value\",\"scc\":null,\"merchantAccount\":\"merchantAccount\",\"currency\":\"EUR\",\"applicationInfo\":{\"adyenLibrary\":{\"name\":\"adyen-dotnet-api-library\",\"version\":\"" + - ClientConfig.LibVersion + + Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion + "\"},\"externalPlatform\":{\"integrator\":\"externalPlatformIntegrator\",\"name\":\"externalPlatformName\",\"version\":\"2.0.0\"},\"merchantDevice\":{\"os\":\"merchantDeviceOS\",\"osVersion\":\"10.12.6\",\"reference\":\"4c32759faaa7\"}},\"tenderOption\":\"ReceiptHandler,AllowPartialAuthorisation,AskGratuity\",\"authorisationType\":\"PreAuth\",\"additionalData\":{\"key.key\":\"value\",\"key.keyTwo\":\"value2\"}}"; private readonly string splitJson = "{\"metadata\":{\"key\":\"value\"},\"shopperEmail\":\"myemail@mail.com\",\"shopperReference\":\"13164308\",\"recurringProcessingModel\":\"Subscription\",\"recurringContract\":\"RECURRING,ONECLICK\",\"shopperStatement\":\"YOUR SHOPPER STATEMENT\",\"recurringDetailName\":\"VALUE\",\"recurringTokenService\":\"VALUE\",\"store\":\"store value\",\"scc\":null,\"merchantAccount\":\"merchantAccount\",\"currency\":\"EUR\",\"applicationInfo\":{\"adyenLibrary\":{\"name\":\"adyen-dotnet-api-library\",\"version\":\"" + - ClientConfig.LibVersion + + Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion + "\"},\"externalPlatform\":{\"integrator\":\"externalPlatformIntegrator\",\"name\":\"externalPlatformName\",\"version\":\"2.0.0\"},\"merchantDevice\":{\"os\":\"merchantDeviceOS\",\"osVersion\":\"10.12.6\",\"reference\":\"4c32759faaa7\"}},\"tenderOption\":\"ReceiptHandler,AllowPartialAuthorisation,AskGratuity\",\"authorisationType\":\"PreAuth\"," + "\"additionalData\":{\"key.key\":\"value\",\"key.keyTwo\":\"value2\",\"split.api\":\"1\",\"split.nrOfItems\":\"3\",\"split.totalAmount\":\"62000\",\"split.currencyCode\":\"EUR\",\"split.item1.amount\":\"60000\",\"split.item1.type\":\"BalanceAccount\",\"split.item1.account\":\"BA00000000000000000000001\",\"split.item1.reference\":\"reference_split_1\",\"split.item1.description\":\"description_split_1\",\"split.item2.amount\":\"2000\",\"split.item2.type\":\"Commission\",\"split.item2.reference\":\"reference_commission\",\"split.item2.description\":\"description_commission\",\"split.item3.type\":\"PaymentFee\",\"split.item3.account\":\"BA00000000000000000000001\",\"split.item3.reference\":\"reference_PaymentFee\",\"split.item3.description\":\"description_PaymentFee\"}}"; diff --git a/Adyen.Test/Terminal/SplitTest.cs b/Adyen.Test/TerminalApi/SplitTest.cs similarity index 100% rename from Adyen.Test/Terminal/SplitTest.cs rename to Adyen.Test/TerminalApi/SplitTest.cs diff --git a/Adyen.Test/TerminalApiAsyncServiceTest.cs b/Adyen.Test/TerminalApi/TerminalApiAsyncServiceTest.cs similarity index 100% rename from Adyen.Test/TerminalApiAsyncServiceTest.cs rename to Adyen.Test/TerminalApi/TerminalApiAsyncServiceTest.cs diff --git a/Adyen.Test/TerminalApiCloudRequestTest.cs b/Adyen.Test/TerminalApi/TerminalApiCloudRequestTest.cs similarity index 100% rename from Adyen.Test/TerminalApiCloudRequestTest.cs rename to Adyen.Test/TerminalApi/TerminalApiCloudRequestTest.cs diff --git a/Adyen.Test/TerminalApiInputTest.cs b/Adyen.Test/TerminalApi/TerminalApiInputTest.cs similarity index 100% rename from Adyen.Test/TerminalApiInputTest.cs rename to Adyen.Test/TerminalApi/TerminalApiInputTest.cs diff --git a/Adyen.Test/TerminalApiLocalServiceTest.cs b/Adyen.Test/TerminalApi/TerminalApiLocalServiceTest.cs similarity index 100% rename from Adyen.Test/TerminalApiLocalServiceTest.cs rename to Adyen.Test/TerminalApi/TerminalApiLocalServiceTest.cs diff --git a/Adyen.Test/TerminalApiPosRequestTest.cs b/Adyen.Test/TerminalApi/TerminalApiPosRequestTest.cs similarity index 100% rename from Adyen.Test/TerminalApiPosRequestTest.cs rename to Adyen.Test/TerminalApi/TerminalApiPosRequestTest.cs diff --git a/Adyen.Test/TerminalApiPosSecurityTest.cs b/Adyen.Test/TerminalApi/TerminalApiPosSecurityTest.cs similarity index 100% rename from Adyen.Test/TerminalApiPosSecurityTest.cs rename to Adyen.Test/TerminalApi/TerminalApiPosSecurityTest.cs diff --git a/Adyen.Test/SerializerTest.cs b/Adyen.Test/TerminalApi/TerminalApiSerializerTest.cs similarity index 66% rename from Adyen.Test/SerializerTest.cs rename to Adyen.Test/TerminalApi/TerminalApiSerializerTest.cs index 26819b1c5..86e9264d7 100644 --- a/Adyen.Test/SerializerTest.cs +++ b/Adyen.Test/TerminalApi/TerminalApiSerializerTest.cs @@ -3,7 +3,6 @@ using System.Text; using Adyen.ApiSerialization; using Adyen.Constants; -using Adyen.Model.Checkout; using Adyen.Model.Terminal; using Adyen.Model.TerminalApi; using Adyen.Model.TerminalApi.Message; @@ -21,34 +20,6 @@ namespace Adyen.Test [TestClass] public class SerializerTest { - [TestMethod] - public void SerializeByteArrayTest() - { - var plainTextBytes = Encoding.ASCII.GetBytes("Bytes-To-Be-Encoded"); - string base64String = System.Convert.ToBase64String(plainTextBytes); - var base64Bytes = Encoding.ASCII.GetBytes(base64String); - var threeDSecure = new ThreeDSecureData - { - Cavv = base64Bytes, - Xid = base64Bytes - }; - var jsonRequest = Util.JsonOperation.SerializeRequest(threeDSecure); - var json = "{\"cavv\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\",\"xid\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\"}"; - Assert.AreEqual(json, jsonRequest); - } - - [TestMethod] - public void DeserializeByteArrayTest() - { - var json = "{\"cavv\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\",\"xid\":\"Qnl0ZXMtVG8tQmUtRW5jb2RlZA==\"}"; - var jsonRequest = Util.JsonOperation.Deserialize(json); - var xid = Encoding.ASCII.GetString(jsonRequest.Xid); - var cavv = Encoding.ASCII.GetString(jsonRequest.Cavv); - var jsonElementBase64 = "Qnl0ZXMtVG8tQmUtRW5jb2RlZA=="; - Assert.AreEqual(jsonElementBase64, xid); - Assert.AreEqual(jsonElementBase64, cavv); - } - [TestMethod] public void EnumSerializerTest() { @@ -60,40 +31,7 @@ public void EnumSerializerTest() Assert.AreEqual(paymentResponseOnline.PaymentResult.AuthenticationMethod[0], AuthenticationMethodType.OnLinePIN); Assert.AreEqual(paymentResponseOnLine.PaymentResult.AuthenticationMethod[0], AuthenticationMethodType.OnLinePIN); } - - [TestMethod] - public void CheckoutLongSerializationTest() - { - var checkoutSessionRequest = new CreateCheckoutSessionRequest - { - MerchantAccount = "merchantAccount", - Reference = "TestReference", - ReturnUrl = "http://test-url.com", - Amount = new Model.Checkout.Amount("EUR", 10000L), - Channel = CreateCheckoutSessionRequest.ChannelEnum.Web, - CountryCode = "NL", - LineItems = new List() - { - new LineItem(quantity: 1, amountIncludingTax: 5000, description: "description1", - amountExcludingTax: 0), - new LineItem(quantity: 1, amountIncludingTax: 5000, description: "description2", taxAmount: 0) - } - }.ToJson(); - // Assert that Long parameters set to zero are actually serialised (just like Int) - Assert.IsTrue(checkoutSessionRequest.Contains("amountExcludingTax\": 0,")); - Assert.IsTrue(checkoutSessionRequest.Contains("taxAmount\": 0")); - } - [TestMethod] - public void CheckoutSessionResponseCheckForIdTest() - { - var sessionResponse = @"{""mode"": ""embedded"",""amount"": {""currency"": ""EUR"",""value"": 10000},""expiresAt"": ""2023-04-06T17:11:15+02:00"",""id"": ""CS0068299CB8DA273A"",""merchantAccount"": ""TestMerchantAccount"",""reference"": ""TestReference"",""returnUrl"": ""http://test-url.com"",""sessionData"": ""Ab02b4c0!BQABAgBoacRJuRbNM/typUKATopkZ3V+cINm0WTAvwl9uQJ2e8I00P2KFemlwp4nb1bOqqYh1zx48gDAHt0QDs2JTiQIqDQRizqopLFRk/wAJHFoCuam/GvOHflg9vwS3caHbkBToIolxcYcJoJheIN9o1fGmNIHZb9VrWfiKsXMgmYsSUifenayS2tkKCTquF7vguaAwk7q5ES1GDwzP/J2mChJGH04jGrVL4szPHGmznr897wIcFQyBSZe4Uifqoe0fpiIxZLNWadLMya6SnvQYNAQL1V6ti+7F4wHHyLwHWTCua993sttue70TE4918EV80HcAWx0LE1+uW6J5KBHCKdYNi9ESlGSZreRwLCpdNbmumB6MlyHZlz2umLiw0ZZJAEpdrwXA2NiyHzJDKDKfbAhd8uoTSACrbgwbrAXI1cvb1WjiOQjLn9MVW++fuJCq6vIeX+rUKMeltBAHMeBZyC54ndAucw9nS03uyckjphunE4tl4WTT475VkfUiyJCTT3S2IOVYS9V9M8pMQ1/GlDVNCLBJJfrYlVXoC8VX68QW1HERkhNYQbTgLQ9kI3cDeMP5d4TuUL3XR2Q6sNiOMdIPGDYQ9QFKFdOE3OQ5X9wxUYbX6j88wR2gRGJcS5agqFHOR1ZTNrjumOYrEkjL8ehFXEs/KluhURllfi0POUPGAwlUWBjDCZcKaeeR0kASnsia2V5IjoiQUYwQUFBMTAzQ0E1MzdFQUVEODdDMjRERDUzOTA5QjgwQTc4QTkyM0UzODIzRDY4REFDQzk0QjlGRjgzMDVEQyJ9E0Gs1T0RaO7NluuXP59fegcW6SQKq4BhC3ZzEKPm1vJuwAJ2gZUaicaXbRPW3IyadavKRlfGdFeAYt2B3ik8fGiK3ZkKU0CrZ0qL0IO5rrWrOg74HMnpxRAn1RhAHRHfGEk67FFPNjr0aLBJXSia7xZWiyKA+i4QU63roY2sxMI/q41mvJjRUz0rPKT3SbVDt1Of7K7BP8cmiboBkWexFBD/mkJyMOpYAOoFp/tKOUHTWZYcc1GpbyV1jInXVfEUhHROYCtS4p/xwF6DdT3bI0+HRU35/xNBTZH2yJN55u9i42Vb0ddCyhzOLZYQ3JVgglty6hLgVeQzuN4b2MoalhfTl11HsElJT1kB0mznVX8CL7UMTUp/2uSgL8DN6kB4owEZ45nWRxIR/2sCidMJ1tnSI1uSqkeqXRf1vat5qPq+BzpYE0Urn2ZZEmgJyb2u0ZLn2x1tfJyPtv+hqBoT7iqJ224dSbuB4HMT49YtcheUtR0jnrImJXm+M1TeIjWB3XWOScrNV8sWEJMAiIU="",""shopperLocale"": ""en-US""}"; - // Assert that readonly parameters like ID are actually deserialised and can be serialised again. - var deserializedResponse = JsonConvert.DeserializeObject(sessionResponse); - Assert.IsNotNull(deserializedResponse.Id); - Assert.IsTrue(deserializedResponse.ToJson().Contains("\"id\": \"CS0068299CB8DA273A\",")); - } - [TestMethod] public void SaleToPoiMessageSerializationTest() { diff --git a/Adyen.Test/TerminalApiSyncServiceTest.cs b/Adyen.Test/TerminalApi/TerminalApiSyncServiceTest.cs similarity index 100% rename from Adyen.Test/TerminalApiSyncServiceTest.cs rename to Adyen.Test/TerminalApi/TerminalApiSyncServiceTest.cs diff --git a/Adyen.Test/TerminalCommonNameValidatorTest.cs b/Adyen.Test/TerminalApi/TerminalCommonNameValidatorTest.cs similarity index 100% rename from Adyen.Test/TerminalCommonNameValidatorTest.cs rename to Adyen.Test/TerminalApi/TerminalCommonNameValidatorTest.cs diff --git a/Adyen.Test/TestUtilities.cs b/Adyen.Test/TestUtilities.cs new file mode 100644 index 000000000..26d4a3748 --- /dev/null +++ b/Adyen.Test/TestUtilities.cs @@ -0,0 +1,18 @@ +namespace Adyen.Test +{ + internal static class TestUtilities + { + /// + /// Utility function, used to read (mock json) files. + /// + /// The relative file to the file. + /// The file contents in string. + public static string GetTestFileContent(string relativePath) + { + string rootPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../")); + string absolutePath = Path.Combine(rootPath, relativePath); + + return File.ReadAllText(absolutePath); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/TransferWebhooks/TransferWebhooksTest.cs b/Adyen.Test/TransferWebhooks/TransferWebhooksTest.cs new file mode 100644 index 000000000..73d21c340 --- /dev/null +++ b/Adyen.Test/TransferWebhooks/TransferWebhooksTest.cs @@ -0,0 +1,173 @@ +using Adyen.TransferWebhooks.Client; +using Adyen.TransferWebhooks.Extensions; +using Adyen.TransferWebhooks.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Hosting; +using System.Text.Json; + +namespace Adyen.Test.TransferWebhooks +{ + [TestClass] + public class TransferWebhooksTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public TransferWebhooksTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureTransferWebhooks((context, services, config) => + { + + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_Transfer_Webhook_Notification_Of_Chargeback_Returns_Not_Null() + { + // Arrange + string json = @" +{ + ""data"": { + ""balancePlatform"": ""YOUR_BALANCE_PLATFORM"", + ""creationDate"": ""2025-06-02T13:46:27+02:00"", + ""id"": ""01234"", + ""accountHolder"": { + ""description"": ""The Account Holder"", + ""id"": ""AH1234567890"" + }, + ""amount"": { + ""currency"": ""EUR"", + ""value"": 22700 + }, + ""balanceAccount"": { + ""description"": ""The Liable Balance Account"", + ""id"": ""BA1234567890"" + }, + ""category"": ""platformPayment"", + ""categoryData"": { + ""modificationMerchantReference"": """", + ""modificationPspReference"": ""ZX1234567890"", + ""paymentMerchantReference"": ""pv-test"", + ""platformPaymentType"": ""Remainder"", + ""pspPaymentReference"": ""PSP01234"", + ""type"": ""platformPayment"" + }, + ""description"": ""Remainder Fee for pv-test"", + ""direction"": ""incoming"", + ""reason"": ""approved"", + ""reference"": """", + ""status"": ""authorised"", + ""type"": ""capture"", + ""balances"": [ + { + ""currency"": ""EUR"", + ""received"": 0, + ""reserved"": 22700 + } + ], + ""eventId"": ""EV1234567890"", + ""events"": [ + { + ""bookingDate"": ""2025-06-02T13:46:27+02:00"", + ""id"": ""EV1234567890"", + ""mutations"": [ + { + ""currency"": ""EUR"", + ""received"": 22700 + } + ], + ""status"": ""received"", + ""type"": ""accounting"" + }, + { + ""bookingDate"": ""2025-06-02T13:46:27+02:00"", + ""id"": ""EV1234567890-2"", + ""mutations"": [ + { + ""currency"": ""EUR"", + ""received"": -22700, + ""reserved"": 22700 + } + ], + ""status"": ""authorised"", + ""type"": ""accounting"" + } + ], + ""sequenceNumber"": 2 + }, + ""environment"": ""test"", + ""timestamp"": ""2025-06-02T11:46:28.635Z"", + ""type"": ""balancePlatform.transfer.updated"" +} +"; + // Act + TransferNotificationRequest r = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.IsNotNull(r); + Assert.AreEqual("test", r.Environment); + Assert.AreEqual(TransferNotificationRequest.TypeEnum.BalancePlatformTransferUpdated, r.Type); + + Assert.AreEqual("YOUR_BALANCE_PLATFORM", r.Data.BalancePlatform); + Assert.AreEqual(DateTimeOffset.Parse("2025-06-02T13:46:27+02:00"), r.Data.CreationDate); + Assert.AreEqual("01234", r.Data.Id); + + Assert.AreEqual("The Account Holder", r.Data.AccountHolder.Description); + Assert.AreEqual("AH1234567890", r.Data.AccountHolder.Id); + + Assert.AreEqual("EUR", r.Data.Amount.Currency); + Assert.AreEqual(22700, r.Data.Amount.Value); + Assert.IsNotNull(r.Data.BalanceAccount); + Assert.AreEqual("The Liable Balance Account", r.Data.BalanceAccount.Description); + Assert.AreEqual("BA1234567890", r.Data.BalanceAccount.Id); + Assert.AreEqual(TransferData.CategoryEnum.PlatformPayment, r.Data.Category); + + Assert.AreEqual("", r.Data.CategoryData.PlatformPayment.ModificationMerchantReference); + Assert.AreEqual("ZX1234567890", r.Data.CategoryData.PlatformPayment.ModificationPspReference); + Assert.AreEqual("pv-test", r.Data.CategoryData.PlatformPayment.PaymentMerchantReference); + Assert.AreEqual(PlatformPayment.PlatformPaymentTypeEnum.Remainder, r.Data.CategoryData.PlatformPayment.PlatformPaymentType); + Assert.AreEqual("PSP01234", r.Data.CategoryData.PlatformPayment.PspPaymentReference); + Assert.AreEqual("Remainder Fee for pv-test", r.Data.Description); + Assert.AreEqual(TransferData.DirectionEnum.Incoming, r.Data.Direction); + Assert.AreEqual(TransferData.ReasonEnum.Approved, r.Data.Reason); + Assert.AreEqual("", r.Data.Reference); + Assert.AreEqual(TransferData.StatusEnum.Authorised, r.Data.Status); + Assert.AreEqual(TransferData.TypeEnum.Capture, r.Data.Type); + + Assert.AreEqual(1, r.Data.Balances.Count); + Assert.AreEqual("EUR", r.Data.Balances[0].Currency); + Assert.AreEqual(0, r.Data.Balances[0].Received); + Assert.AreEqual(22700, r.Data.Balances[0].Reserved); + Assert.AreEqual("EV1234567890", r.Data.EventId); + + Assert.AreEqual(2, r.Data.Events.Count); + + Assert.AreEqual(DateTimeOffset.Parse("2025-06-02T13:46:27+02:00"), r.Data.Events[0].BookingDate); + Assert.AreEqual("EV1234567890", r.Data.Events[0].Id); + Assert.AreEqual(TransferEvent.StatusEnum.Received, r.Data.Events[0].Status); + Assert.AreEqual(TransferEvent.TypeEnum.Accounting, r.Data.Events[0].Type); + + Assert.AreEqual(1, r.Data.Events[0].Mutations.Count); + Assert.AreEqual("EUR", r.Data.Events[0].Mutations[0].Currency); + Assert.AreEqual(22700, r.Data.Events[0].Mutations[0].Received); + + Assert.AreEqual(DateTimeOffset.Parse("2025-06-02T13:46:27+02:00"), r.Data.Events[1].BookingDate); + Assert.AreEqual("EV1234567890-2", r.Data.Events[1].Id); + Assert.AreEqual(TransferEvent.StatusEnum.Authorised, r.Data.Events[1].Status); + Assert.AreEqual(TransferEvent.TypeEnum.Accounting, r.Data.Events[1].Type); + + Assert.IsNotNull(r.Data.Events[1].Mutations); + Assert.AreEqual(1, r.Data.Events[1].Mutations.Count); + Assert.AreEqual("EUR", r.Data.Events[1].Mutations[0].Currency); + Assert.AreEqual(-22700, r.Data.Events[1].Mutations[0].Received); + Assert.AreEqual(22700, r.Data.Events[1].Mutations[0].Reserved); + + Assert.AreEqual(2, r.Data.SequenceNumber); + Assert.AreEqual(DateTimeOffset.Parse("2025-06-02T11:46:28.635Z"), r.Timestamp); + } + } +} \ No newline at end of file diff --git a/Adyen.Test/Transfers/TransfersTest.cs b/Adyen.Test/Transfers/TransfersTest.cs new file mode 100644 index 000000000..a3f6e51d9 --- /dev/null +++ b/Adyen.Test/Transfers/TransfersTest.cs @@ -0,0 +1,93 @@ +using Adyen.Core.Options; +using Adyen.Transfers.Models; +using Adyen.Transfers.Client; +using Adyen.Transfers.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +namespace Adyen.Test.Transfers +{ + [TestClass] + public class TransfersTest + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public TransfersTest() + { + IHost host = Host.CreateDefaultBuilder() + .ConfigureTransfers((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + + [TestMethod] + public async Task Given_Deserialize_When_TransactionSearchResponse_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/transfers/get-all-transactions.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Links.Next.Href, "https://balanceplatform-api-test.adyen.com/btl/v4/transactions?balancePlatform=TestBalancePlatform&createdUntil=2023-08-20T13%3A07%3A40Z&createdSince=2023-08-10T10%3A50%3A40Z&cursor=S2B-c0p1N0tdN0l6RGhYK1YpM0lgOTUyMDlLXElyKE9LMCtyaFEuMj1NMHgidCsrJi1ZNnhqXCtqVi5JPGpRK1F2fCFqWzU33JTojSVNJc1J1VXhncS10QDd6JX9FQFl5Zn0uNyUvSXJNQTo"); + } + + [TestMethod] + public async Task Given_Deserialize_When_TransferTransaction_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/transfers/get-transaction.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, Transaction.StatusEnum.Booked); + Assert.AreEqual(response.Transfer.Id, "48TYZO5ZVURJ2FCW"); + } + + [TestMethod] + public async Task Given_Deserialize_When_Transfer_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/transfers/transfer-funds.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Status, Transfer.StatusEnum.Authorised); + Assert.AreEqual(response.Category, Transfer.CategoryEnum.Bank); + } + + #region Grants + + [TestMethod] + public async Task Given_Deserialize_When_CapitalGrant_Returns_Not_Null() + { + // Arrange + string json = TestUtilities.GetTestFileContent("mocks/grants/post-grants-success.json"); + + // Act + var response = JsonSerializer.Deserialize(json, _jsonSerializerOptionsProvider.Options); + + // Assert + Assert.AreEqual(response.Id, "GR00000000000000000000001"); + Assert.AreEqual(response.GrantAccountId, "CG00000000000000000000001"); + Assert.AreEqual(response.Status, CapitalGrant.StatusEnum.Pending); + Assert.IsNotNull(response.Balances); + } + + #endregion + } +} \ No newline at end of file diff --git a/Adyen.Test/TransfersTest.cs b/Adyen.Test/TransfersTest.cs deleted file mode 100644 index 8656af648..000000000 --- a/Adyen.Test/TransfersTest.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Net.Http; -using System.Threading; -using Adyen.Model; -using Adyen.Model.Transfers; -using Adyen.Service.Transfers; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; - -namespace Adyen.Test -{ - [TestClass] - public class TransfersTest : BaseTest - { - [TestMethod] - public void GetAllTransactionsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/transfers/get-all-transactions.json"); - var service = new TransactionsService(client); - var response = service.GetAllTransactions(new DateTime(), new DateTime(), balancePlatform:"balance", accountHolderId:"id"); - ClientInterfaceSubstitute.Received().RequestAsync( - "https://balanceplatform-api-test.adyen.com/btl/v4/transactions?balancePlatform=balance&accountHolderId=id&createdSince=0001-01-01T00%3a00%3a00Z&createdUntil=0001-01-01T00%3a00%3a00Z", - null, null, HttpMethod.Get, CancellationToken.None); - Assert.AreEqual(response.Links.Next.Href, "https://balanceplatform-api-test.adyen.com/btl/v2/transactions?balancePlatform=Bastronaut&createdUntil=2022-03-21T00%3A00%3A00Z&createdSince=2022-03-11T00%3A00%3A00Z&limit=3&cursor=S2B-TSAjOkIrYlIlbjdqe0RreHRyM32lKRSxubXBHRkhHL2E32XitQQz5SfzpucD5HbHwpM1p6NDR1eXVQLFF6MmY33J32sobDxQYT90MHIud1hwLnd6JitcX32xJ"); - } - - [TestMethod] - public void GetSpecificTransactionTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/transfers/get-transaction.json"); - var service = new TransactionsService(client); - var response = service.GetTransaction("id"); - Assert.AreEqual(response.Status, Transaction.StatusEnum.Booked); - Assert.AreEqual(response.Transfer.Id, "48TYZO5ZVURJ2FCW"); - } - - [TestMethod] - public void PostTransferFundsTest() - { - var client = CreateMockTestClientApiKeyBasedRequestAsync("mocks/transfers/transfer-funds.json"); - var service = new TransfersService(client); - var response = service.TransferFunds(new TransferInfo()); - Assert.AreEqual(response.Status, Transfer.StatusEnum.Authorised); - Assert.AreEqual(response.Category, Transfer.CategoryEnum.Bank); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/UtilTest.cs b/Adyen.Test/Webhooks/HmacValidatorTest.cs similarity index 65% rename from Adyen.Test/UtilTest.cs rename to Adyen.Test/Webhooks/HmacValidatorTest.cs index 8bea2e2cb..4e89c2bc6 100644 --- a/Adyen.Test/UtilTest.cs +++ b/Adyen.Test/Webhooks/HmacValidatorTest.cs @@ -1,212 +1,181 @@ -using System.Collections.Generic; -using Adyen.Model.Notification; -using Adyen.Model.Payment; -using Adyen.Util; -using Adyen.Util.TerminalApi; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; - -namespace Adyen.Test -{ - [TestClass] - public class UtilTest : BaseTest - { - [TestMethod] - public void TestHmac() - { - var data = "countryCode:currencyCode:merchantAccount:merchantReference:paymentAmount:sessionValidity:skinCode:NL:EUR:MagentoMerchantTest2:TEST-PAYMENT-2017-02-01-14\\:02\\:05:199:2017-02-02T14\\:02\\:05+01\\:00:PKz2KML1"; - var hmacKey = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; - var hmacValidator = new HmacValidator(); - var hmacSignature = hmacValidator.CalculateHmac(data, hmacKey); - Assert.IsTrue(string.Equals(hmacSignature, "34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=")); - } - - [TestMethod] - public void TestBalancePlatformHmac() - { - var notification = - "{\"data\":{\"balancePlatform\":\"Integration_tools_test\",\"accountId\":\"BA32272223222H5HVKTBK4MLB\",\"sweep\":{\"id\":\"SWPC42272223222H5HVKV6H8C64DP5\",\"schedule\":{\"type\":\"balance\"},\"status\":\"active\",\"targetAmount\":{\"currency\":\"EUR\",\"value\":0},\"triggerAmount\":{\"currency\":\"EUR\",\"value\":0},\"type\":\"pull\",\"counterparty\":{\"balanceAccountId\":\"BA3227C223222H5HVKT3H9WLC\"},\"currency\":\"EUR\"}},\"environment\":\"test\",\"type\":\"balancePlatform.balanceAccountSweep.updated\"}"; - var hmacKey = "D7DD5BA6146493707BF0BE7496F6404EC7A63616B7158EC927B9F54BB436765F"; - var hmacSignature = "9Qz9S/0xpar1klkniKdshxpAhRKbiSAewPpWoxKefQA="; - var hmacValidator = new HmacValidator(); - bool response = hmacValidator.IsValidWebhook(hmacSignature, hmacKey, notification); - Assert.IsTrue(response); - } - - [TestMethod] - public void TestSerializationShopperInteractionDefaultIsZero() - { - var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(default); - var serializedPaymentRequest = paymentRequest.ToJson(); - Assert.IsTrue(serializedPaymentRequest.Contains("\"shopperInteraction\": 0,")); - } - - [TestMethod] - public void TestNotificationRequestItemHmac() - { - var hmacKey = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; - var expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc="; - var additionalData = new Dictionary - { - { "hmacSignature", expectedSign } - }; - var notificationRequestItem = new NotificationRequestItem - { - PspReference = "pspReference", - OriginalReference = "originalReference", - MerchantAccountCode = "merchantAccount", - MerchantReference = "reference", - Amount = new Model.Checkout.Amount("EUR", 1000), - EventCode = "EVENT", - Success = true, - AdditionalData = additionalData - }; - var hmacValidator = new HmacValidator(); - var data = hmacValidator.GetDataToSign(notificationRequestItem); - Assert.AreEqual("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true", data); - var encrypted = hmacValidator.CalculateHmac(notificationRequestItem, hmacKey); - Assert.AreEqual(expectedSign, encrypted); - Assert.IsTrue(hmacValidator.IsValidHmac(notificationRequestItem, hmacKey)); - notificationRequestItem.AdditionalData["hmacSignature"] = "notValidSign"; - Assert.IsFalse(hmacValidator.IsValidHmac(notificationRequestItem, hmacKey)); - } - - [TestMethod] - public void TestHmacCalculationNotificationRequestWithSpecialChars() - { - string hmacKey = "66B61474A0AA3736BA8789EDC6D6CD9EBA0C4F414A554E32A407F849C045C69D"; - var mockPath = GetMockFilePath("mocks/notification-response-refund-fail.json"); - var response = MockFileToString(mockPath); - var hmacValidator = new HmacValidator(); - var notificationRequest = JsonOperation.Deserialize(response); - var notificationItem = notificationRequest.NotificationItemContainers[0].NotificationItem; - var isValidHmac = hmacValidator.IsValidHmac(notificationItem, hmacKey); - Assert.IsTrue(isValidHmac); - } - - [TestMethod] - public void TestSerializationShopperInteractionMoto() - { - var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(PaymentRequest.ShopperInteractionEnum.Moto); - var serializedPaymentRequest = JsonOperation.SerializeRequest(paymentRequest); - StringAssert.Contains(serializedPaymentRequest, nameof(PaymentRequest.ShopperInteractionEnum.Moto)); - } - - [TestMethod] - public void TestNullHmacValidator() - { - var hmacValidator = new HmacValidator(); - var notificationRequestItem = new NotificationRequestItem - { - PspReference = "pspReference", - OriginalReference = "originalReference", - MerchantAccountCode = "merchantAccount", - MerchantReference = "reference", - Amount = new Model.Checkout.Amount("EUR", 1000), - EventCode = "EVENT", - Success = true, - AdditionalData = null - }; - var isValidHmacAdditionalDataNull = hmacValidator.IsValidHmac(notificationRequestItem, "hmacKey"); - Assert.IsFalse(isValidHmacAdditionalDataNull); - notificationRequestItem.AdditionalData = new Dictionary(); - var isValidHmacAdditionalDataEmpty = hmacValidator.IsValidHmac(notificationRequestItem, "hmacKey"); - Assert.IsFalse(isValidHmacAdditionalDataEmpty); - } - - [TestMethod] - public void TestColonAndBackslashHmacValidator() - { - var hmacValidator = new HmacValidator(); - var jsonNotification = @"{ - 'additionalData': { - 'acquirerCode': 'TestPmmAcquirer', - 'acquirerReference': 'J8DXDJ2PV6P', - 'authCode': '052095', - 'avsResult': '5 No AVS data provided', - 'avsResultRaw': '5', - 'cardSummary': '1111', - 'checkout.cardAddedBrand': 'visa', - 'cvcResult': '1 Matches', - 'cvcResultRaw': 'M', - 'expiryDate': '03/2030', - 'hmacSignature': 'CZErGCNQaSsxbaQfZaJlakqo7KPP+mIa8a+wx3yNs9A=', - 'paymentMethod': 'visa', - 'refusalReasonRaw': 'AUTHORISED', - 'retry.attempt1.acquirer': 'TestPmmAcquirer', - 'retry.attempt1.acquirerAccount': 'TestPmmAcquirerAccount', - 'retry.attempt1.avsResultRaw': '5', - 'retry.attempt1.rawResponse': 'AUTHORISED', - 'retry.attempt1.responseCode': 'Approved', - 'retry.attempt1.scaExemptionRequested': 'lowValue', - 'scaExemptionRequested': 'lowValue' - }, - 'amount': { - 'currency': 'EUR', - 'value': 1000 - }, - 'eventCode': 'AUTHORISATION', - 'eventDate': '2023-01-10T13:42:29+01:00', - 'merchantAccountCode': 'AntoniStroinski', - 'merchantReference': '\\:/\\/slashes are fun', - 'operations': [ - 'CANCEL', - 'CAPTURE', - 'REFUND' - ], - 'paymentMethod': 'visa', - 'pspReference': 'ZVWN7D3WSMK2WN82', - 'reason': '052095:1111:03/2030', - 'success': 'true' - }"; - var notificationRequestItem = JsonConvert.DeserializeObject(jsonNotification); - var isValidHmac = hmacValidator.IsValidHmac(notificationRequestItem, "74F490DD33F7327BAECC88B2947C011FC02D014A473AAA33A8EC93E4DC069174"); - Assert.IsTrue(isValidHmac); - } - - [TestMethod] - public void TestCardAcquisitionAdditionalResponse() - { - string jsonString = @"{ - ""additionalData"": { - ""PaymentAccountReference"": ""Yv6zs1234567890ASDFGHJKL"", - ""alias"": ""G12345678"", - ""aliasType"": ""Default"", - ""applicationLabel"": ""ASDFGHJKL"", - ""applicationPreferredName"": ""ASDFGHJKL"", - ""backendGiftcardIndicator"": ""false"", - ""cardBin"": ""4111111"", - ""cardHolderName"": ""John Smith"" - }, - ""message"": ""CARD_ACQ_COMPLETED"", - ""store"": ""NL"" - }"; - string responseBased64 = "ewoiYWRkaXRpb25hbERhdGEiOnsKICJQYXltZW50QWNjb3VudFJlZmVyZW5jZSI6Ill2NnpzMTIzNDU2Nzg5MEFTREZHSEpLTCIsCiJhbGlhcyI6IkcxMjM0NTY3OCIsCiJhbGlhc1R5cGUiOiJEZWZhdWx0IiwKImFwcGxpY2F0aW9uTGFiZWwiOiJBU0RGR0hKS0wiLAoiYXBwbGljYXRpb25QcmVmZXJyZWROYW1lIjoiQVNERkdISktMIiwKICJiYWNrZW5kR2lmdGNhcmRJbmRpY2F0b3IiOiJmYWxzZSIsCiJjYXJkQmluIjoiNDExMTExMSIsCiJjYXJkSG9sZGVyTmFtZSI6IkpvaG4gU21pdGgiCgp9LAoibWVzc2FnZSI6IkNBUkRfQUNRX0NPTVBMRVRFRCIsCiJzdG9yZSI6Ik5MIgp9"; - var additionalResponse = CardAcquisitionUtil.AdditionalResponse(responseBased64); - Assert.AreEqual(additionalResponse.Message,"CARD_ACQ_COMPLETED"); - Assert.AreEqual(additionalResponse.Store,"NL"); - Assert.AreEqual(additionalResponse.AdditionalData["PaymentAccountReference"],"Yv6zs1234567890ASDFGHJKL"); - Assert.AreEqual(additionalResponse.AdditionalData["alias"],"G12345678"); - Assert.AreEqual(additionalResponse.AdditionalData["aliasType"],"Default"); - Assert.AreEqual(additionalResponse.AdditionalData["applicationLabel"],"ASDFGHJKL"); - Assert.AreEqual(additionalResponse.AdditionalData["applicationPreferredName"],"ASDFGHJKL"); - Assert.AreEqual(additionalResponse.AdditionalData["backendGiftcardIndicator"],"false"); - Assert.AreEqual(additionalResponse.AdditionalData["cardHolderName"],"John Smith"); - Assert.AreEqual(additionalResponse.AdditionalData["cardBin"],"4111111"); - - var additionalResponseFromJson = CardAcquisitionUtil.AdditionalResponse(jsonString); - Assert.AreEqual(additionalResponseFromJson.Message,"CARD_ACQ_COMPLETED"); - Assert.AreEqual(additionalResponseFromJson.Store,"NL"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["PaymentAccountReference"],"Yv6zs1234567890ASDFGHJKL"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["alias"],"G12345678"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["aliasType"],"Default"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["applicationLabel"],"ASDFGHJKL"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["applicationPreferredName"],"ASDFGHJKL"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["backendGiftcardIndicator"],"false"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["cardHolderName"],"John Smith"); - Assert.AreEqual(additionalResponseFromJson.AdditionalData["cardBin"],"4111111"); - - } - - } -} +using Adyen.Util; +using Adyen.Webhooks; +using Adyen.Webhooks.Models; +using Adyen.Util.TerminalApi; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +namespace Adyen.Test.Webhooks +{ + [TestClass] + public class HmacValidatorTest : BaseTest + { + [TestMethod] + public void TestHmac() + { + string data = "countryCode:currencyCode:merchantAccount:merchantReference:paymentAmount:sessionValidity:skinCode:NL:EUR:MagentoMerchantTest2:TEST-PAYMENT-2017-02-01-14\\:02\\:05:199:2017-02-02T14\\:02\\:05+01\\:00:PKz2KML1"; + string hmacKey = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; + var hmacValidator = new HmacValidator(); + string hmacSignature = hmacValidator.CalculateHmac(data, hmacKey); + Assert.IsTrue(string.Equals(hmacSignature, "34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=")); + } + + [TestMethod] + public void TestNotificationRequestItemHmac() + { + string hmacKey = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; + string expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc="; + var additionalData = new Dictionary + { + { "hmacSignature", expectedSign } + }; + var notificationRequestItem = new NotificationRequestItem + { + PspReference = "pspReference", + OriginalReference = "originalReference", + MerchantAccountCode = "merchantAccount", + MerchantReference = "reference", + Amount = new Amount("EUR", 1000), + EventCode = "EVENT", + Success = true, + AdditionalData = additionalData + }; + var hmacValidator = new HmacValidator(); + string data = hmacValidator.GetDataToSign(notificationRequestItem); + Assert.AreEqual("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true", data); + string encrypted = hmacValidator.CalculateHmac(notificationRequestItem, hmacKey); + Assert.AreEqual(expectedSign, encrypted); + Assert.IsTrue(hmacValidator.IsValidHmac(notificationRequestItem, hmacKey)); + notificationRequestItem.AdditionalData["hmacSignature"] = "notValidSign"; + Assert.IsFalse(hmacValidator.IsValidHmac(notificationRequestItem, hmacKey)); + } + + [TestMethod] + public void TestHmacCalculationNotificationRequestWithSpecialChars() + { + string hmacKey = "66B61474A0AA3736BA8789EDC6D6CD9EBA0C4F414A554E32A407F849C045C69D"; + string mockPath = GetMockFilePath("mocks/notification-response-refund-fail.json"); + string response = MockFileToString(mockPath); + var hmacValidator = new HmacValidator(); + NotificationRequest notificationRequest = JsonConvert.DeserializeObject(response); + NotificationRequestItem notificationItem = notificationRequest.NotificationItemContainers[0].NotificationItem; + bool isValidHmac = hmacValidator.IsValidHmac(notificationItem, hmacKey); + Assert.IsTrue(isValidHmac); + } + + [TestMethod] + public void TestNullHmacValidator() + { + var hmacValidator = new HmacValidator(); + var notificationRequestItem = new NotificationRequestItem + { + PspReference = "pspReference", + OriginalReference = "originalReference", + MerchantAccountCode = "merchantAccount", + MerchantReference = "reference", + Amount = new Amount("EUR", 1000), + EventCode = "EVENT", + Success = true, + AdditionalData = null + }; + bool isValidHmacAdditionalDataNull = hmacValidator.IsValidHmac(notificationRequestItem, "hmacKey"); + Assert.IsFalse(isValidHmacAdditionalDataNull); + notificationRequestItem.AdditionalData = new Dictionary(); + bool isValidHmacAdditionalDataEmpty = hmacValidator.IsValidHmac(notificationRequestItem, "hmacKey"); + Assert.IsFalse(isValidHmacAdditionalDataEmpty); + } + + [TestMethod] + public void TestColonAndBackslashHmacValidator() + { + var hmacValidator = new HmacValidator(); + string jsonNotification = @"{ + 'additionalData': { + 'acquirerCode': 'TestPmmAcquirer', + 'acquirerReference': 'J8DXDJ2PV6P', + 'authCode': '052095', + 'avsResult': '5 No AVS data provided', + 'avsResultRaw': '5', + 'cardSummary': '1111', + 'checkout.cardAddedBrand': 'visa', + 'cvcResult': '1 Matches', + 'cvcResultRaw': 'M', + 'expiryDate': '03/2030', + 'hmacSignature': 'CZErGCNQaSsxbaQfZaJlakqo7KPP+mIa8a+wx3yNs9A=', + 'paymentMethod': 'visa', + 'refusalReasonRaw': 'AUTHORISED', + 'retry.attempt1.acquirer': 'TestPmmAcquirer', + 'retry.attempt1.acquirerAccount': 'TestPmmAcquirerAccount', + 'retry.attempt1.avsResultRaw': '5', + 'retry.attempt1.rawResponse': 'AUTHORISED', + 'retry.attempt1.responseCode': 'Approved', + 'retry.attempt1.scaExemptionRequested': 'lowValue', + 'scaExemptionRequested': 'lowValue' + }, + 'amount': { + 'currency': 'EUR', + 'value': 1000 + }, + 'eventCode': 'AUTHORISATION', + 'eventDate': '2023-01-10T13:42:29+01:00', + 'merchantAccountCode': 'AntoniStroinski', + 'merchantReference': '\\:/\\/slashes are fun', + 'operations': [ + 'CANCEL', + 'CAPTURE', + 'REFUND' + ], + 'paymentMethod': 'visa', + 'pspReference': 'ZVWN7D3WSMK2WN82', + 'reason': '052095:1111:03/2030', + 'success': 'true' + }"; + NotificationRequestItem notificationRequestItem = JsonConvert.DeserializeObject(jsonNotification); + bool isValidHmac = hmacValidator.IsValidHmac(notificationRequestItem, "74F490DD33F7327BAECC88B2947C011FC02D014A473AAA33A8EC93E4DC069174"); + Assert.IsTrue(isValidHmac); + } + + [TestMethod] + public void TestCardAcquisitionAdditionalResponse() + { + string jsonString = @"{ + ""additionalData"": { + ""PaymentAccountReference"": ""Yv6zs1234567890ASDFGHJKL"", + ""alias"": ""G12345678"", + ""aliasType"": ""Default"", + ""applicationLabel"": ""ASDFGHJKL"", + ""applicationPreferredName"": ""ASDFGHJKL"", + ""backendGiftcardIndicator"": ""false"", + ""cardBin"": ""4111111"", + ""cardHolderName"": ""John Smith"" + }, + ""message"": ""CARD_ACQ_COMPLETED"", + ""store"": ""NL"" + }"; + string responseBased64 = "ewoiYWRkaXRpb25hbERhdGEiOnsKICJQYXltZW50QWNjb3VudFJlZmVyZW5jZSI6Ill2NnpzMTIzNDU2Nzg5MEFTREZHSEpLTCIsCiJhbGlhcyI6IkcxMjM0NTY3OCIsCiJhbGlhc1R5cGUiOiJEZWZhdWx0IiwKImFwcGxpY2F0aW9uTGFiZWwiOiJBU0RGR0hKS0wiLAoiYXBwbGljYXRpb25QcmVmZXJyZWROYW1lIjoiQVNERkdISktMIiwKICJiYWNrZW5kR2lmdGNhcmRJbmRpY2F0b3IiOiJmYWxzZSIsCiJjYXJkQmluIjoiNDExMTExMSIsCiJjYXJkSG9sZGVyTmFtZSI6IkpvaG4gU21pdGgiCgp9LAoibWVzc2FnZSI6IkNBUkRfQUNRX0NPTVBMRVRFRCIsCiJzdG9yZSI6Ik5MIgp9"; + AdditionalResponse additionalResponse = CardAcquisitionUtil.AdditionalResponse(responseBased64); + Assert.AreEqual(additionalResponse.Message,"CARD_ACQ_COMPLETED"); + Assert.AreEqual(additionalResponse.Store,"NL"); + Assert.AreEqual(additionalResponse.AdditionalData["PaymentAccountReference"],"Yv6zs1234567890ASDFGHJKL"); + Assert.AreEqual(additionalResponse.AdditionalData["alias"],"G12345678"); + Assert.AreEqual(additionalResponse.AdditionalData["aliasType"],"Default"); + Assert.AreEqual(additionalResponse.AdditionalData["applicationLabel"],"ASDFGHJKL"); + Assert.AreEqual(additionalResponse.AdditionalData["applicationPreferredName"],"ASDFGHJKL"); + Assert.AreEqual(additionalResponse.AdditionalData["backendGiftcardIndicator"],"false"); + Assert.AreEqual(additionalResponse.AdditionalData["cardHolderName"],"John Smith"); + Assert.AreEqual(additionalResponse.AdditionalData["cardBin"],"4111111"); + + AdditionalResponse additionalResponseFromJson = CardAcquisitionUtil.AdditionalResponse(jsonString); + Assert.AreEqual(additionalResponseFromJson.Message,"CARD_ACQ_COMPLETED"); + Assert.AreEqual(additionalResponseFromJson.Store,"NL"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["PaymentAccountReference"],"Yv6zs1234567890ASDFGHJKL"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["alias"],"G12345678"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["aliasType"],"Default"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["applicationLabel"],"ASDFGHJKL"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["applicationPreferredName"],"ASDFGHJKL"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["backendGiftcardIndicator"],"false"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["cardHolderName"],"John Smith"); + Assert.AreEqual(additionalResponseFromJson.AdditionalData["cardBin"],"4111111"); + } + } +} diff --git a/Adyen.Test/WebhooksTests/WebhookHandlerTest.cs b/Adyen.Test/Webhooks/WebhookHandlerTest.cs similarity index 99% rename from Adyen.Test/WebhooksTests/WebhookHandlerTest.cs rename to Adyen.Test/Webhooks/WebhookHandlerTest.cs index 0b60812e3..c87451d9c 100644 --- a/Adyen.Test/WebhooksTests/WebhookHandlerTest.cs +++ b/Adyen.Test/Webhooks/WebhookHandlerTest.cs @@ -7,7 +7,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -namespace Adyen.Test.WebhooksTests +namespace Adyen.Test.Webhooks { [TestClass] public class WebhookHandlerTest : BaseTest diff --git a/Adyen.Test/WebhooksTests/BalancePlatformWebhookHandlerTest.cs b/Adyen.Test/WebhooksTests/BalancePlatformWebhookHandlerTest.cs deleted file mode 100644 index 4f23c9517..000000000 --- a/Adyen.Test/WebhooksTests/BalancePlatformWebhookHandlerTest.cs +++ /dev/null @@ -1,551 +0,0 @@ -using System; -using Adyen.Model.AcsWebhooks; -using Adyen.Model.ConfigurationWebhooks; -using Adyen.Model.NegativeBalanceWarningWebhooks; -using Adyen.Model.ReportWebhooks; -using Adyen.Model.TransactionWebhooks; -using Adyen.Webhooks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using CapabilityProblemEntity = Adyen.Model.ConfigurationWebhooks.CapabilityProblemEntity; - -namespace Adyen.Test.WebhooksTests -{ - [TestClass] - public class BalancePlatformWebhookHandlerTest : BaseTest - { - private readonly BalancePlatformWebhookHandler _balancePlatformWebhookHandler = new BalancePlatformWebhookHandler(); - - [TestMethod] - [DataRow("balancePlatform.accountHolder.created", AccountHolderNotificationRequest.TypeEnum.Created)] - [DataRow("balancePlatform.accountHolder.updated", AccountHolderNotificationRequest.TypeEnum.Updated)] - public void Given_AccountHolder_Webhook_When_Type_Is_Provided_Result_Should_Deserialize(string type, AccountHolderNotificationRequest.TypeEnum expected) - { - // Arrange - string jsonPayload = @" -{ - 'data': { - 'balancePlatform': 'YOUR_BALANCE_PLATFORM', - 'accountHolder': { - 'contactDetails': { - 'address': { - 'country': 'NL', - 'houseNumberOrName': '274', - 'postalCode': '1020CD', - 'street': 'Brannan Street' - }, - 'email': 's.hopper@example.com', - 'phone': { - 'number': '+315551231234', - 'type': 'Mobile' - } - }, - 'description': 'S.Hopper - Staff 123', - 'id': 'AH00000000000000000000001', - 'status': 'Active' - } - }, - 'environment': 'test', - 'type': '" + type + "'" + -"}"; - // Act - _balancePlatformWebhookHandler.GetAccountHolderNotificationRequest(jsonPayload, out AccountHolderNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); - Assert.AreEqual("NL", target.Data.AccountHolder.ContactDetails.Address.Country); - Assert.AreEqual("274", target.Data.AccountHolder.ContactDetails.Address.HouseNumberOrName); - Assert.AreEqual("1020CD", target.Data.AccountHolder.ContactDetails.Address.PostalCode); - Assert.AreEqual("Brannan Street", target.Data.AccountHolder.ContactDetails.Address.Street); - Assert.AreEqual("s.hopper@example.com", target.Data.AccountHolder.ContactDetails.Email); - Assert.AreEqual("+315551231234", target.Data.AccountHolder.ContactDetails.Phone.Number); - Assert.AreEqual(Phone.TypeEnum.Mobile, target.Data.AccountHolder.ContactDetails.Phone.Type); - Assert.AreEqual("S.Hopper - Staff 123", target.Data.AccountHolder.Description); - Assert.AreEqual("AH00000000000000000000001", target.Data.AccountHolder.Id); - Assert.AreEqual(AccountHolder.StatusEnum.Active, target.Data.AccountHolder.Status); - Assert.AreEqual("test", target.Environment); - Assert.AreEqual(expected, target.Type); - } - - [TestMethod] - public void Given_AccountHolder_Webhook_When_Type_Is_Unknown_Result_Should_Be_Null() - { - string jsonPayload = @"{ 'type': 'unknowntype' }"; - bool response = _balancePlatformWebhookHandler.GetAccountHolderNotificationRequest(jsonPayload, out AccountHolderNotificationRequest target); - Assert.IsFalse(response); - Assert.IsNull(target); - } - - [TestMethod] - public void Given_AccountHolder_Webhook_When_Invalid_Json_Result_Should_Throw_JsonReaderException() - { - string jsonPayload = "{ invalid,.json; }"; - Assert.ThrowsException(() => _balancePlatformWebhookHandler.GetAccountHolderNotificationRequest(jsonPayload, out var _)); - } - - [TestMethod] - - public void Test_BalancePlatform_AccountHolderUpdated_LEM_V3() - { - // Note: We're using double-quotes here as some descriptions in the JSON payload contain single quotes ' - // Assert - const string jsonPayload = @" -{ - ""data"": { - ""balancePlatform"": ""YOUR_BALANCE_PLATFORM"", - ""accountHolder"": { - ""legalEntityId"": ""LE00000000000000000001"", - ""reference"": ""YOUR_REFERENCE-2412C"", - ""capabilities"": { - ""sendToTransferInstrument"": { - ""enabled"": true, - ""requested"": true, - ""allowed"": false, - ""problems"": [ - { - ""entity"": { - ""id"": ""LE00000000000000000001"", - ""type"": ""LegalEntity"" - }, - ""verificationErrors"": [ - { - ""code"": ""2_902"", - ""message"": ""Terms Of Service forms are not accepted."", - ""remediatingActions"": [ - { - ""code"": ""2_902"", - ""message"": ""Accept TOS"" - } - ], - ""type"": ""invalidInput"" - } - ] - }, - { - ""entity"": { - ""id"": ""SE00000000000000000001"", - ""type"": ""BankAccount"" - }, - ""verificationErrors"": [ - { - ""code"": ""2_8037"", - ""message"": ""'bankStatement' was missing."", - ""remediatingActions"": [ - { - ""code"": ""1_703"", - ""message"": ""Upload a bank statement"" - } - ], - ""type"": ""dataMissing"" - } - ] - }, - { - ""entity"": { - ""id"": ""SE00000000000000000002"", - ""type"": ""BankAccount"" - }, - ""verificationErrors"": [ - { - ""code"": ""2_8037"", - ""message"": ""'bankStatement' was missing."", - ""remediatingActions"": [ - { - ""code"": ""1_703"", - ""message"": ""Upload a bank statement"" - } - ], - ""type"": ""dataMissing"" - } - ] - }, - { - ""entity"": { - ""id"": ""LE00000000000000000001"", - ""type"": ""LegalEntity"" - }, - ""verificationErrors"": [ - { - ""code"": ""2_8189"", - ""message"": ""'UBO through control' was missing."", - ""remediatingActions"": [ - { - ""code"": ""2_151"", - ""message"": ""Add 'organization.entityAssociations' of type 'uboThroughControl' to legal entity"" - } - ], - ""type"": ""dataMissing"" - }, - { - ""code"": ""1_50"", - ""message"": ""Organization details couldn't be verified"", - ""subErrors"": [ - { - ""code"": ""1_5016"", - ""message"": ""The tax ID number couldn't be verified"", - ""remediatingActions"": [ - { - ""code"": ""1_500"", - ""message"": ""Update organization details"" - }, - { - ""code"": ""1_501"", - ""message"": ""Upload a registration document"" - } - ], - ""type"": ""invalidInput"" - } - ], - ""type"": ""invalidInput"" - }, - { - ""code"": ""2_8067"", - ""message"": ""'Signatory' was missing."", - ""remediatingActions"": [ - { - ""code"": ""2_124"", - ""message"": ""Add 'organization.entityAssociations' of type 'signatory' to legal entity"" - } - ], - ""type"": ""dataMissing"" - } - ] - } - ], - ""transferInstruments"": [ - { - ""enabled"": true, - ""requested"": true, - ""allowed"": false, - ""id"": ""SE00000000000000000001"", - ""verificationStatus"": ""pending"" - }, - { - ""enabled"": true, - ""requested"": true, - ""allowed"": false, - ""id"": ""SE00000000000000000002"", - ""verificationStatus"": ""pending"" - } - ], - ""verificationStatus"": ""pending"" - } - }, - ""id"": ""AH00000000000000000001"", - ""status"": ""active"" - } - }, - ""environment"": ""live"", - ""timestamp"": ""2024-12-15T15:42:03+01:00"", - ""type"": ""balancePlatform.accountHolder.updated"" -}"; - - _balancePlatformWebhookHandler.GetAccountHolderNotificationRequest(jsonPayload, out AccountHolderNotificationRequest accountHolderUpdatedWebhook); - - Assert.IsNotNull(accountHolderUpdatedWebhook); - Assert.AreEqual(accountHolderUpdatedWebhook.Type, AccountHolderNotificationRequest.TypeEnum.Updated); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", accountHolderUpdatedWebhook.Data.BalancePlatform); - Assert.AreEqual("AH00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Id); - Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.LegalEntityId); - Assert.AreEqual("YOUR_REFERENCE-2412C", accountHolderUpdatedWebhook.Data.AccountHolder.Reference); - Assert.AreEqual(AccountHolder.StatusEnum.Active, accountHolderUpdatedWebhook.Data.AccountHolder.Status); - Assert.IsTrue(accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities.TryGetValue("sendToTransferInstrument", out AccountHolderCapability capabilitiesData)); - Assert.AreEqual(true, capabilitiesData.Enabled); - Assert.AreEqual(true, capabilitiesData.Requested); - Assert.AreEqual(false, capabilitiesData.Allowed); - Assert.AreEqual(AccountHolderCapability.VerificationStatusEnum.Pending, capabilitiesData.VerificationStatus); - Assert.AreEqual(4, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems.Count); - Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].Entity.Id); - Assert.AreEqual(CapabilityProblemEntity.TypeEnum.LegalEntity, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].Entity.Type); - Assert.AreEqual("2_902", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].Code); - Assert.AreEqual("Terms Of Service forms are not accepted.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].Message); - Assert.AreEqual("Accept TOS", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[0].VerificationErrors[0].RemediatingActions[0].Message); - Assert.AreEqual("SE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].Entity.Id); - Assert.AreEqual(CapabilityProblemEntity.TypeEnum.BankAccount, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].Entity.Type); - Assert.AreEqual("2_8037", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].Code); - Assert.AreEqual("'bankStatement' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].Message); - Assert.AreEqual("Upload a bank statement", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[1].VerificationErrors[0].RemediatingActions[0].Message); - Assert.AreEqual("SE00000000000000000002", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].Entity.Id); - Assert.AreEqual(CapabilityProblemEntity.TypeEnum.BankAccount, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].Entity.Type); - Assert.AreEqual("2_8037", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].Code); - Assert.AreEqual("'bankStatement' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].Message); - Assert.AreEqual("Upload a bank statement", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[2].VerificationErrors[0].RemediatingActions[0].Message); - Assert.AreEqual("LE00000000000000000001", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].Entity.Id); - Assert.AreEqual(CapabilityProblemEntity.TypeEnum.LegalEntity, accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].Entity.Type); - Assert.AreEqual("2_8189", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].Code); - Assert.AreEqual("'UBO through control' was missing.", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].Message); - Assert.AreEqual("Add 'organization.entityAssociations' of type 'uboThroughControl' to legal entity", accountHolderUpdatedWebhook.Data.AccountHolder.Capabilities["sendToTransferInstrument"].Problems[3].VerificationErrors[0].RemediatingActions[0].Message); - Assert.AreEqual("live", accountHolderUpdatedWebhook.Environment); - Assert.AreEqual(DateTime.Parse("2024-12-15T15:42:03+01:00"), accountHolderUpdatedWebhook.Timestamp); - } - - [TestMethod] - public void Test_POC_Integration() - { - string jsonPayload = @" -{ - 'data': { - 'balancePlatform': 'YOUR_BALANCE_PLATFORM', - 'accountHolder': { - 'contactDetails': { - 'address': { - 'country': 'NL', - 'houseNumberOrName': '274', - 'postalCode': '1020CD', - 'street': 'Brannan Street' - }, - 'email': 's.hopper@example.com', - 'phone': { - 'number': '+315551231234', - 'type': 'Mobile' - } - }, - 'description': 'S.Hopper - Staff 123', - 'id': 'AH00000000000000000000001', - 'status': 'Active' - } - }, - 'environment': 'test', - 'type': 'balancePlatform.accountHolder.created' -}"; - - var handler = new BalancePlatformWebhookHandler(); - var response = handler.GetGenericBalancePlatformWebhook(jsonPayload); - try - { - if (response.GetType() == typeof(AccountHolderNotificationRequest)) - { - var accountHolderNotificationRequest = (AccountHolderNotificationRequest)response; - Assert.AreEqual(accountHolderNotificationRequest.Environment, "test"); - } - - if (response.GetType() == typeof(BalanceAccountNotificationRequest)) - { - var balanceAccountNotificationRequest = (BalanceAccountNotificationRequest)response; - Assert.Fail(balanceAccountNotificationRequest.Data.BalancePlatform); - } - } - catch (System.Exception e) - { - Assert.Fail(); - throw new System.Exception(e.ToString()); - } - } - - [TestMethod] - public void Test_TransactionWebhook_V4() - { - // Arrange - const string jsonPayload = @" -{ - 'data': { - 'id': 'EVJN42272224222B5JB8BRC84N686ZEUR', - 'amount': { - 'value': 7000, - 'currency': 'EUR' - }, - 'status': 'booked', - 'transfer': { - 'id': 'JN4227222422265', - 'reference': 'Split_item_1', - }, - 'valueDate': '2023-03-01T00:00:00+02:00', - 'bookingDate': '2023-02-28T13:30:20+02:00', - 'creationDate': '2023-02-28T13:30:05+02:00', - 'accountHolder': { - 'id': 'AH00000000000000000000001', - 'description': 'Your description for the account holder', - 'reference': 'Your reference for the account holder' - }, - 'balanceAccount': { - 'id': 'BA00000000000000000000001', - 'description': 'Your description for the balance account', - 'reference': 'Your reference for the balance account' - }, - 'balancePlatform': 'YOUR_BALANCE_PLATFORM' - }, - 'type': 'balancePlatform.transaction.created', - 'environment': 'test' -}"; - Assert.IsFalse(_balancePlatformWebhookHandler.GetPaymentNotificationRequest(jsonPayload, out var _)); - - // Act - _balancePlatformWebhookHandler.GetTransactionNotificationRequestV4(jsonPayload, out TransactionNotificationRequestV4 target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(TransactionNotificationRequestV4.TypeEnum.BalancePlatformTransactionCreated, target.Type); - Assert.AreEqual(Transaction.StatusEnum.Booked, target.Data.Status); - Assert.AreEqual("BA00000000000000000000001", target.Data.BalanceAccount.Id); - Assert.IsTrue(target.Data.ValueDate.Equals(DateTime.Parse("2023-03-01T00:00:00+02:00"))); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); - Assert.AreEqual("AH00000000000000000000001", target.Data.AccountHolder.Id); - Assert.AreEqual("Your description for the account holder", target.Data.AccountHolder.Description); - Assert.AreEqual("Your reference for the account holder", target.Data.AccountHolder.Reference); - Assert.AreEqual("JN4227222422265", target.Data.Transfer.Id); - Assert.AreEqual("Split_item_1", target.Data.Transfer.Reference); - Assert.AreEqual(DateTime.Parse("2023-02-28T13:30:05+02:00"), target.Data.CreationDate); - Assert.AreEqual(DateTime.Parse("2023-02-28T13:30:20+02:00"), target.Data.BookingDate); - Assert.AreEqual(7000, target.Data.Amount.Value); - Assert.AreEqual("EUR", target.Data.Amount.Currency); - Assert.AreEqual("test", target.Environment); - } - - [TestMethod] - public void Test_ReportCreatedWebhook() - { - // Arrange - const string jsonPayload = @" -{ - 'data': { - 'balancePlatform': 'YOUR_BALANCE_PLATFORM', - 'creationDate': '2024-07-02T02:01:08+02:00', - 'id': 'balanceplatform_accounting_report_2024_07_01.csv', - 'downloadUrl': 'https://balanceplatform-test.adyen.com/balanceplatform/.../.../.../balanceplatform_accounting_report_2024_07_01.csv', - 'fileName': 'balanceplatform_accounting_report_2024_07_01.csv', - 'reportType': 'balanceplatform_accounting_report' - }, - 'environment': 'test', - 'timestamp': '2024-07-02T02:01:05+02:00', - 'type': 'balancePlatform.report.created' -}"; - - // Act - _balancePlatformWebhookHandler.GetReportNotificationRequest(jsonPayload, out ReportNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(target.Type, ReportNotificationRequest.TypeEnum.BalancePlatformReportCreated); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); - Assert.AreEqual("balanceplatform_accounting_report_2024_07_01.csv", target.Data.Id); - Assert.AreEqual("balanceplatform_accounting_report_2024_07_01.csv", target.Data.FileName); - Assert.AreEqual("balanceplatform_accounting_report", target.Data.ReportType); - Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:08+02:00"), target.Data.CreationDate); - Assert.AreEqual("https://balanceplatform-test.adyen.com/balanceplatform/.../.../.../balanceplatform_accounting_report_2024_07_01.csv", target.Data.DownloadUrl); - Assert.AreEqual("test", target.Environment); - Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:05+02:00"), target.Timestamp); - } - - [TestMethod] - public void Test_AuthenticationCreatedWebhook() - { - // Arrange - const string jsonPayload = @" -{ - 'data': { - 'authentication': { - 'acsTransId': '6a4c1709-a42e-4c7f-96c7-1043adacfc97', - 'challenge': { - 'flow': 'OOB_TRIGGER_FL', - 'lastInteraction': '2022-12-22T15:49:03+01:00' - }, - 'challengeIndicator': '01', - 'createdAt': '2022-12-22T15:45:03+01:00', - 'deviceChannel': 'app', - 'dsTransID': 'a3b86754-444d-46ca-95a2-ada351d3f42c', - 'exemptionIndicator': 'lowValue', - 'inPSD2Scope': true, - 'messageCategory': 'payment', - 'messageVersion': '2.2.0', - 'riskScore': 0, - 'threeDSServerTransID': '6edcc246-23ee-4e94-ac5d-8ae620bea7d9', - 'transStatus': 'Y', - 'type': 'challenge' - }, - 'balancePlatform': 'YOUR_BALANCE_PLATFORM', - 'id': '497f6eca-6276-4993-bfeb-53cbbbba6f08', - 'paymentInstrumentId': 'PI3227C223222B5BPCMFXD2XG', - 'purchase': { - 'date': '2022-12-22T15:49:03+01:00', - 'merchantName': 'MyShop', - 'originalAmount': { - 'currency': 'EUR', - 'value': 1000 - } - }, - 'status': 'authenticated' - }, - 'environment': 'test', - 'timestamp': '2022-12-22T15:42:03+01:00', - 'type': 'balancePlatform.authentication.created' -}"; - - // Act - _balancePlatformWebhookHandler.GetAuthenticationNotificationRequest(jsonPayload, out AuthenticationNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(target.Type, AuthenticationNotificationRequest.TypeEnum.BalancePlatformAuthenticationCreated); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); - Assert.AreEqual("497f6eca-6276-4993-bfeb-53cbbbba6f08", target.Data.Id); - Assert.AreEqual("PI3227C223222B5BPCMFXD2XG", target.Data.PaymentInstrumentId); - Assert.AreEqual(AuthenticationNotificationData.StatusEnum.Authenticated, target.Data.Status); - Assert.AreEqual("MyShop", target.Data.Purchase.MerchantName); - Assert.AreEqual("2022-12-22T15:49:03+01:00", target.Data.Purchase.Date); - Assert.AreEqual("EUR", target.Data.Purchase.OriginalAmount.Currency); - Assert.AreEqual(1000, target.Data.Purchase.OriginalAmount.Value); - Assert.AreEqual(DateTime.Parse("2022-12-22T15:45:03+01:00"), target.Data.Authentication.CreatedAt); - Assert.AreEqual(AuthenticationInfo.DeviceChannelEnum.App, target.Data.Authentication.DeviceChannel); - Assert.AreEqual(ChallengeInfo.FlowEnum.OOBTRIGGERFL, target.Data.Authentication.Challenge.Flow); - Assert.AreEqual(DateTime.Parse("2022-12-22T15:49:03+01:00"), target.Data.Authentication.Challenge.LastInteraction); - Assert.AreEqual(AuthenticationInfo.ChallengeIndicatorEnum._01, target.Data.Authentication.ChallengeIndicator); - Assert.AreEqual(AuthenticationInfo.ExemptionIndicatorEnum.LowValue, target.Data.Authentication.ExemptionIndicator); - Assert.AreEqual(true, target.Data.Authentication.InPSD2Scope); - Assert.AreEqual(AuthenticationInfo.MessageCategoryEnum.Payment, target.Data.Authentication.MessageCategory); - Assert.AreEqual("2.2.0", target.Data.Authentication.MessageVersion); - Assert.AreEqual(0, target.Data.Authentication.RiskScore); - Assert.AreEqual("6edcc246-23ee-4e94-ac5d-8ae620bea7d9", target.Data.Authentication.ThreeDSServerTransID); - Assert.AreEqual(AuthenticationInfo.TransStatusEnum.Y, target.Data.Authentication.TransStatus); - Assert.AreEqual("test", target.Environment); - Assert.AreEqual(DateTime.Parse("2022-12-22T15:42:03+01:00"), target.Timestamp); - } - - [TestMethod] - public void Test_NegativeBalanceCompensationWarningWebhook() - { - // Arrange - const string jsonPayload = @" -{ - 'data': { - 'balancePlatform': 'YOUR_BALANCE_PLATFORM', - 'creationDate': '2024-07-02T02:01:08+02:00', - 'id': 'BA00000000000000000001', - 'accountHolder': { - 'description': 'Description for the account holder.', - 'reference': 'YOUR_REFERENCE', - 'id': 'AH00000000000000000001' - }, - 'amount': { - 'currency': 'EUR', - 'value': -145050 - }, - 'liableBalanceAccountId': 'BA11111111111111111111', - 'negativeBalanceSince': '2024-10-19T00:33:13+02:00', - 'scheduledCompensationAt': '2024-12-01T01:00:00+01:00' - }, - 'environment': 'test', - 'timestamp': '2024-10-22T00:00:00+02:00', - 'type': 'balancePlatform.negativeBalanceCompensationWarning.scheduled' -}"; - - // Act - _balancePlatformWebhookHandler.GetNegativeBalanceCompensationWarningNotificationRequest(jsonPayload, out NegativeBalanceCompensationWarningNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(NegativeBalanceCompensationWarningNotificationRequest.TypeEnum.BalancePlatformNegativeBalanceCompensationWarningScheduled, target.Type); - Assert.AreEqual("YOUR_BALANCE_PLATFORM", target.Data.BalancePlatform); - Assert.AreEqual(DateTime.Parse("2024-07-02T02:01:08+02:00"), target.Data.CreationDate); - Assert.AreEqual("BA00000000000000000001", target.Data.Id); - Assert.AreEqual("YOUR_REFERENCE", target.Data.AccountHolder.Reference); - Assert.AreEqual("EUR", target.Data.Amount.Currency); - Assert.AreEqual(-145050, target.Data.Amount.Value); - Assert.AreEqual("BA11111111111111111111", target.Data.LiableBalanceAccountId); - Assert.AreEqual(DateTime.Parse("2024-10-19T00:33:13+02:00"), target.Data.NegativeBalanceSince); - Assert.AreEqual(DateTime.Parse("2024-12-01T01:00:00+01:00"), target.Data.ScheduledCompensationAt); - Assert.AreEqual("test", target.Environment); - Assert.AreEqual(DateTime.Parse("2024-10-22T00:00:00+02:00"), target.Timestamp); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/WebhooksTests/ManagementWebhookHandlerTest.cs b/Adyen.Test/WebhooksTests/ManagementWebhookHandlerTest.cs deleted file mode 100644 index 2e7d4d78b..000000000 --- a/Adyen.Test/WebhooksTests/ManagementWebhookHandlerTest.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using Adyen.Model.ManagementWebhooks; -using Adyen.Webhooks; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Adyen.Test.WebhooksTests -{ - [TestClass] - public class ManagementWebhookHandlerTest : BaseTest - { - private readonly ManagementWebhookHandler _managementWebhookHandler = new ManagementWebhookHandler(); - - [TestMethod] - public void Test_Management_Webhook_PaymentMethodCreated() - { - // Arrange - const string jsonPayload = @" -{ - 'createdAt': '2022-01-24T14:59:11+01:00', - 'data': { - 'id': 'PM3224R223224K5FH4M2K9B86', - 'merchantId': 'MERCHANT_ACCOUNT', - 'status': 'SUCCESS', - 'storeId': 'ST322LJ223223K5F4SQNR9XL5', - 'type': 'visa' - }, - 'environment': 'test', - 'type': 'paymentMethod.created' -}"; - // Act - _managementWebhookHandler.GetPaymentMethodCreatedNotificationRequest(jsonPayload, out PaymentMethodCreatedNotificationRequest paymentMethodCreatedWebhook); - - // Assert - Assert.IsNotNull(paymentMethodCreatedWebhook); - Assert.AreEqual(PaymentMethodCreatedNotificationRequest.TypeEnum.PaymentMethodCreated, paymentMethodCreatedWebhook.Type); - Assert.AreEqual(paymentMethodCreatedWebhook.Data.Id, "PM3224R223224K5FH4M2K9B86"); - Assert.AreEqual(paymentMethodCreatedWebhook.Data.MerchantId, "MERCHANT_ACCOUNT"); - Assert.AreEqual(paymentMethodCreatedWebhook.Data.Status, MidServiceNotificationData.StatusEnum.Success); - Assert.AreEqual(paymentMethodCreatedWebhook.Data.StoreId, "ST322LJ223223K5F4SQNR9XL5"); - Assert.AreEqual(paymentMethodCreatedWebhook.Data.Type, "visa"); - Assert.AreEqual(DateTime.Parse("2022-01-24T14:59:11+01:00"), paymentMethodCreatedWebhook.CreatedAt); - Assert.AreEqual("test", paymentMethodCreatedWebhook.Environment); - } - - [TestMethod] - public void Test_Management_Webhook_MerchantUpdated() - { - // Arrange - const string jsonPayload = @" -{ - 'type': 'merchant.updated', - 'environment': 'test', - 'createdAt': '2022-09-20T13:42:31+02:00', - 'data': { - 'capabilities': { - 'receivePayments': { - 'allowed': true, - 'requested': true, - 'requestedLevel': 'notApplicable', - 'verificationStatus': 'valid' - } - }, - 'legalEntityId': 'LE322KH223222F5GNNW694PZN', - 'merchantId': 'YOUR_MERCHANT_ID', - 'status': 'PreActive' - } -}"; - // Act - _managementWebhookHandler.GetMerchantUpdatedNotificationRequest(jsonPayload, out MerchantUpdatedNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(target.Type, MerchantUpdatedNotificationRequest.TypeEnum.MerchantUpdated); - Assert.AreEqual("LE322KH223222F5GNNW694PZN", target.Data.LegalEntityId); - Assert.AreEqual("YOUR_MERCHANT_ID", target.Data.MerchantId); - Assert.AreEqual("PreActive", target.Data.Status); - Assert.AreEqual(DateTime.Parse("2022-09-20T13:42:31+02:00"), target.CreatedAt); - Assert.AreEqual("test", target.Environment); - - Assert.IsTrue(target.Data.Capabilities.TryGetValue("receivePayments", out AccountCapabilityData accountCapabilityData)); - Assert.AreEqual(true, accountCapabilityData.Requested); - Assert.AreEqual("notApplicable", accountCapabilityData.RequestedLevel); - } - - [TestMethod] - public void Test_Management_Webhook_MerchantCreated() - { - // Arrange - const string jsonPayload = @" -{ - 'type': 'merchant.created', - 'environment': 'test', - 'createdAt': '2022-08-12T10:50:01+02:00', - 'data': { - 'capabilities': { - 'sendToTransferInstrument': { - 'requested': true, - 'requestedLevel': 'notApplicable' - } - }, - 'companyId': 'YOUR_COMPANY_ID', - 'merchantId': 'MC3224X22322535GH8D537TJR', - 'status': 'PreActive' - } -}"; - Assert.IsFalse(_managementWebhookHandler.GetMerchantUpdatedNotificationRequest(jsonPayload, out _)); - - // Act - _managementWebhookHandler.GetMerchantCreatedNotificationRequest(jsonPayload, out MerchantCreatedNotificationRequest target); - - // Assert - Assert.IsNotNull(target); - Assert.AreEqual(MerchantCreatedNotificationRequest.TypeEnum.MerchantCreated, target.Type); - Assert.AreEqual("test", target.Environment); - Assert.AreEqual("YOUR_COMPANY_ID", target.Data.CompanyId); - Assert.AreEqual("MC3224X22322535GH8D537TJR", target.Data.MerchantId); - Assert.AreEqual("PreActive", target.Data.Status); - Assert.AreEqual(DateTime.Parse("2022-08-12T10:50:01+02:00"), target.CreatedAt); - Assert.IsTrue(target.Data.Capabilities.TryGetValue("sendToTransferInstrument", out AccountCapabilityData data)); - Assert.AreEqual("notApplicable", data.RequestedLevel); - Assert.AreEqual(true, data.Requested); - } - } -} \ No newline at end of file diff --git a/Adyen.Test/mockHttpClient.cs b/Adyen.Test/mockHttpClient.cs deleted file mode 100644 index 978a21c89..000000000 --- a/Adyen.Test/mockHttpClient.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; - -public class MockHttpMessageHandler : HttpMessageHandler -{ - private readonly string _response; - private readonly HttpStatusCode _statusCode; - - public string Input { get; private set; } - public int NumberOfCalls { get; private set; } - - public MockHttpMessageHandler(string response, HttpStatusCode statusCode) - { - _response = response; - _statusCode = statusCode; - } - - protected override async Task SendAsync(HttpRequestMessage request, - CancellationToken cancellationToken) - { - NumberOfCalls++; - if (request.Content != null) // Could be a GET-request without a body - { - Input = await request.Content.ReadAsStringAsync(); - } - return new HttpResponseMessage - { - StatusCode = _statusCode, - Content = new StringContent(_response) - }; - } -} \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/AccountHolder.json b/Adyen.Test/mocks/balanceplatform/AccountHolder.json index 8c75be5a9..4f8c64960 100644 --- a/Adyen.Test/mocks/balanceplatform/AccountHolder.json +++ b/Adyen.Test/mocks/balanceplatform/AccountHolder.json @@ -11,9 +11,10 @@ "email": "s.hopper@example.com", "phone": { "number": "+315551231234", - "type": "Mobile" + "type": "mobile" } }, + "legalEntityId": "LE322JV223222D5GG42KN6869", "description": "S.Hopper - Staff 123", "id": "AH32272223222B5CM4MWJ892H", "status": "active" diff --git a/Adyen.Test/mocks/balanceplatform/AccountHolderWithUnknownEnum.json b/Adyen.Test/mocks/balanceplatform/AccountHolderWithUnknownEnum.json new file mode 100644 index 000000000..a16376ddc --- /dev/null +++ b/Adyen.Test/mocks/balanceplatform/AccountHolderWithUnknownEnum.json @@ -0,0 +1,21 @@ +{ + "balancePlatform": "BalandePlatformExample", + "contactDetails": { + "address": { + "city": "Amsterdam", + "country": "NL", + "houseNumberOrName": "274", + "postalCode": "1020CD", + "street": "Brannan Street" + }, + "email": "s.hopper@example.com", + "phone": { + "number": "+315551231234", + "type": "mobile" + } + }, + "legalEntityId": "LE322JV223222D5GG42KN6869", + "description": "S.Hopper - Staff 123", + "id": "AH32272223222B5CM4MWJ892H", + "status": "unknown-enum" +} \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/BalanceAccount.json b/Adyen.Test/mocks/balanceplatform/BalanceAccount.json index 5e7d9ba9e..f36f0a1bb 100644 --- a/Adyen.Test/mocks/balanceplatform/BalanceAccount.json +++ b/Adyen.Test/mocks/balanceplatform/BalanceAccount.json @@ -1,6 +1,8 @@ { - "accountHolderId": "AH32272223222B59K6RTQBFNZ", + "accountHolderId": "AH32272223222C5GXTD343TKP", "defaultCurrencyCode": "EUR", + "description": "S.Hopper - Main balance account", + "timeZone": "Europe/Amsterdam", "balances": [ { "available": 0, @@ -9,6 +11,6 @@ "reserved": 0 } ], - "id": "BA3227C223222B5BLP6JQC3FD", - "status": "Active" + "id": "BA3227C223222H5J4DCGQ9V9L", + "status": "active" } \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/PaginatedAccountHoldersResponse.json b/Adyen.Test/mocks/balanceplatform/PaginatedAccountHoldersResponse.json index 4b65c66f5..be1201a7c 100644 --- a/Adyen.Test/mocks/balanceplatform/PaginatedAccountHoldersResponse.json +++ b/Adyen.Test/mocks/balanceplatform/PaginatedAccountHoldersResponse.json @@ -1,34 +1,27 @@ { "accountHolders": [ { - "contactDetails": { - "address": { - "city": "Amsterdam", - "country": "NL", - "houseNumberOrName": "6", - "postalCode": "12336750", - "street": "Simon Carmiggeltstraat" - } - }, - "description": "J. Doe", - "id": "AH32272223222B59DDWSCCMP7", - "status": "Active" + "description": "Test-305", + "legalEntityId": "LE3227C223222D5D8S5S33M4M", + "reference": "LegalEntity internal error test", + "id": "AH32272223222B5GFSNSXFFL9", + "status": "active" }, { - "contactDetails": { - "address": { - "city": "Amsterdam", - "country": "NL", - "houseNumberOrName": "11", - "postalCode": "12336750", - "street": "Simon Carmiggeltstraat" - } - }, - "description": "S. Hopper", - "id": "AH32272223222B59DJ7QBCMPN", - "status": "Active" + "description": "Test-751", + "legalEntityId": "LE3227C223222D5D8S5TT3SRX", + "reference": "LegalEntity internal error test", + "id": "AH32272223222B5GFSNVGFFM7", + "status": "active" + }, + { + "description": "Explorer Holder", + "legalEntityId": "LE3227C223222D5D8S5TT3SRX", + "reference": "Account from the Explorer Holder", + "id": "AH32272223222B5GFWNRFFVR6", + "status": "active" } ], - "hasNext": "true", - "hasPrevious": "false" + "hasNext": true, + "hasPrevious": true } \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/PaginatedBalanceAccountsResponse.json b/Adyen.Test/mocks/balanceplatform/PaginatedBalanceAccountsResponse.json index 58706682f..fb1bc8842 100644 --- a/Adyen.Test/mocks/balanceplatform/PaginatedBalanceAccountsResponse.json +++ b/Adyen.Test/mocks/balanceplatform/PaginatedBalanceAccountsResponse.json @@ -1,22 +1,31 @@ { "balanceAccounts": [ { - "accountHolderId": "AH32272223222B59K6ZKBBFNQ", + "accountHolderId": "AH32272223222B5CTBMZT6W2V", "defaultCurrencyCode": "EUR", - "id": "BA32272223222B59K6ZXHBFN6", - "status": "Active" + "description": "S. Hopper - Main Account", + "reference": "YOUR_REFERENCE-X173L", + "timeZone": "Europe/Amsterdam", + "id": "BA32272223222B5CTDNB66W2Z", + "status": "active" }, { - "accountHolderId": "AH32272223222B59K6ZKBBFNQ", + "accountHolderId": "AH32272223222B5CTBMZT6W2V", "defaultCurrencyCode": "EUR", - "id": "BA32272223222B59K72CKBFNJ", - "status": "closed" + "description": "S. Hopper - Main Account", + "reference": "YOUR_REFERENCE-X173L", + "timeZone": "Europe/Amsterdam", + "id": "BA32272223222B5CTDQPM6W2H", + "status": "active" }, { - "accountHolderId": "AH32272223222B59K6ZKBBFNQ", + "accountHolderId": "AH32272223222B5CTBMZT6W2V", "defaultCurrencyCode": "EUR", - "id": "BA32272223222B5BRR27B2M7G", - "status": "Active" + "description": "S. Hopper - Main Account", + "reference": "YOUR_REFERENCE-X173L", + "timeZone": "Europe/Amsterdam", + "id": "BA32272223222B5CVF5J63LMW", + "status": "active" } ], "hasNext": true, diff --git a/Adyen.Test/mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json b/Adyen.Test/mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json index 23bf0add2..585cfdc6d 100644 --- a/Adyen.Test/mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json +++ b/Adyen.Test/mocks/balanceplatform/PaginatedPaymentInstrumentsResponse.json @@ -1,13 +1,14 @@ { - "hasNext": "true", - "hasPrevious": "false", + "hasNext": true, + "hasPrevious": false, "paymentInstruments": [ { "balanceAccountId": "BA32272223222B59CZ3T52DKZ", "issuingCountryCode": "GB", - "status": "Active", + "status": "active", "type": "card", "card": { + "brand": "mc", "brandVariant": "mc", "cardholderName": "name", "formFactor": "virtual", @@ -24,9 +25,10 @@ { "balanceAccountId": "BA32272223222B59CZ3T52DKZ", "issuingCountryCode": "GB", - "status": "Active", + "status": "active", "type": "card", "card": { + "brand": "mc", "brandVariant": "mc", "cardholderName": "name", "formFactor": "virtual", diff --git a/Adyen.Test/mocks/balanceplatform/PaymentInstrument.json b/Adyen.Test/mocks/balanceplatform/PaymentInstrument.json index ab6c7493e..48984ca79 100644 --- a/Adyen.Test/mocks/balanceplatform/PaymentInstrument.json +++ b/Adyen.Test/mocks/balanceplatform/PaymentInstrument.json @@ -1,6 +1,13 @@ { + "balanceAccountId": "BA3227C223222B5CTBLR8BWJB", + "issuingCountryCode": "NL", + "status": "active", "type": "bankAccount", "description": "YOUR_DESCRIPTION", - "balanceAccountId": "BA3227C223222B5CTBLR8BWJB", - "issuingCountryCode": "NL" + "bankAccount": { + "formFactor": "physical", + "type": "iban", + "iban": "NL20ADYB2017000035" + }, + "id": "PI322LJ223222B5DJS7CD9LWL" } \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/SweepConfiguration.json b/Adyen.Test/mocks/balanceplatform/SweepConfiguration.json index 719d05edc..f27b44936 100644 --- a/Adyen.Test/mocks/balanceplatform/SweepConfiguration.json +++ b/Adyen.Test/mocks/balanceplatform/SweepConfiguration.json @@ -1,4 +1,5 @@ { + "id": "SWPC4227C224555B5FTD2NT2JV4WN5", "counterparty": { "merchantAccount": "YOUR_MERCHANT_ACCOUNT" }, diff --git a/Adyen.Test/mocks/balanceplatform/TransactionRuleResponse.json b/Adyen.Test/mocks/balanceplatform/TransactionRuleResponse.json index 8477e3717..fa6007f21 100644 --- a/Adyen.Test/mocks/balanceplatform/TransactionRuleResponse.json +++ b/Adyen.Test/mocks/balanceplatform/TransactionRuleResponse.json @@ -1,15 +1,28 @@ { "transactionRule": { - "description": "Allow 5 transactions per month", + "description": "Only allow point-of-sale transactions", + "entityKey": { + "entityReference": "PI3227C223222B5FN65FN5NS9", + "entityType": "paymentInstrument" + }, "interval": { - "type": "monthly" + "timeZone": "UTC", + "type": "perTransaction" + }, + "outcomeType": "hardBlock", + "reference": "YOUR_REFERENCE_4F7346", + "requestType": "authorization", + "ruleRestrictions": { + "processingTypes": { + "operation": "noneMatch", + "value": [ + "pos" + ] + } }, - "maxTransactions": 5, - "paymentInstrumentId": "PI3227C223222B59KGTXP884R", - "reference": "myRule12345", - "startDate": "2021-01-25T12:46:35", + "startDate": "2022-08-02T16:07:00.851374+02:00", "status": "active", - "type": "velocity", - "id": "TR32272223222B5CMD3V73HXG" + "type": "blockList", + "id": "TR32272223222B5GFSGFLFCHM" } } \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/TransactionRulesResponse.json b/Adyen.Test/mocks/balanceplatform/TransactionRulesResponse.json index 89b977c5f..57b77005a 100644 --- a/Adyen.Test/mocks/balanceplatform/TransactionRulesResponse.json +++ b/Adyen.Test/mocks/balanceplatform/TransactionRulesResponse.json @@ -1,33 +1,66 @@ { "transactionRules": [ { - "description": "Allow 5 transactions per month", + "aggregationLevel": "paymentInstrument", + "description": "Up to 1000 EUR per card for the last 12 hours", + "entityKey": { + "entityReference": "PG3227C223222C5GXR3M5592Q", + "entityType": "paymentInstrumentGroup" + }, "interval": { - "type": "monthly" + "duration": { + "unit": "hours", + "value": 12 + }, + "timeZone": "UTC", + "type": "sliding" }, - "maxTransactions": 5, - "paymentInstrumentGroupId": "PG3227C223222B5CMD3FJFKGZ", - "reference": "myRule12345", - "startDate": "2021-01-25T12:46:35", - "status": "active", + "outcomeType": "hardBlock", + "reference": "YOUR_REFERENCE_2918A", + "requestType": "authorization", + "ruleRestrictions": { + "totalAmount": { + "operation": "greaterThan", + "value": { + "currency": "EUR", + "value": 100000 + } + } + }, + "status": "inactive", "type": "velocity", - "id": "TR32272223222B5CMDGMC9F4F" + "id": "TR3227C223222C5GXR3XP596N" }, { - "amount": { - "currency": "EUR", - "value": 10000 + "aggregationLevel": "paymentInstrument", + "description": "NL only", + "entityKey": { + "entityReference": "PG3227C223222C5GXR3M5592Q", + "entityType": "paymentInstrumentGroup" }, - "description": "Allow up to 100 EUR per month", "interval": { - "type": "monthly" + "duration": { + "unit": "hours", + "value": 12 + }, + "timeZone": "UTC", + "type": "sliding" + }, + "outcomeType": "hardBlock", + "reference": "myRule12345", + "requestType": "authorization", + "ruleRestrictions": { + "totalAmount": { + "operation": "greaterThan", + "value": { + "currency": "EUR", + "value": 100000 + } + } }, - "paymentInstrumentGroupId": "PG3227C223222B5CMD3FJFKGZ", - "reference": "myRule16378", - "startDate": "2021-01-25T12:46:35", - "status": "active", + "status": "inactive", "type": "velocity", - "id": "TR32272223222B5CMDGT89F4F" + "id": "TR3227C223222C5GXR3WC595H" } ] } \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/TransferLimit.json b/Adyen.Test/mocks/balanceplatform/TransferLimit.json new file mode 100644 index 000000000..65dd9a775 --- /dev/null +++ b/Adyen.Test/mocks/balanceplatform/TransferLimit.json @@ -0,0 +1,16 @@ +{ + "amount": { + "value": 10000, + "currency": "EUR" + }, + "id": "TRLI00000000000000000000000001", + "scope": "perTransaction", + "reference": "Your reference for the transfer limit", + "scaInformation": { + "status": "pending" + }, + "startsAt": "2025-08-15T06:36:20+01:00", + "endsAt": "2026-08-13T23:00:00+01:00", + "limitStatus": "pendingSCA", + "transferType": "all" +} \ No newline at end of file diff --git a/Adyen.Test/mocks/balanceplatform/TransferLimits.json b/Adyen.Test/mocks/balanceplatform/TransferLimits.json new file mode 100644 index 000000000..16b055e4c --- /dev/null +++ b/Adyen.Test/mocks/balanceplatform/TransferLimits.json @@ -0,0 +1,38 @@ +{ + "transferLimits": [ + { + "amount": { + "value": 10000, + "currency": "EUR" + }, + "id": "TRLI00000000000000000000000001", + "endsAt": "2026-08-13T23:00:00+01:00", + "scope": "perTransaction", + "reference": "Your reference for the transfer limit", + "scaInformation": { + "exemption": "initialLimit", + "status": "notPerformed" + }, + "startsAt": "2025-08-13T23:00:00+01:00", + "limitStatus": "active", + "transferType": "instant" + }, + { + "amount": { + "value": 20000, + "currency": "EUR" + }, + "id": "TRLI00000000000000000000000002", + "endsAt": "2026-08-13T23:00:00+01:00", + "scope": "perTransaction", + "reference": "Your reference for the transfer limit", + "scaInformation": { + "exemption": "initialLimit", + "status": "notPerformed" + }, + "startsAt": "2025-08-13T23:00:00+01:00", + "limitStatus": "active", + "transferType": "all" + } + ] +} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/card-details-success.json b/Adyen.Test/mocks/checkout/card-details-success.json index 5945d09d7..697b8abfa 100644 --- a/Adyen.Test/mocks/checkout/card-details-success.json +++ b/Adyen.Test/mocks/checkout/card-details-success.json @@ -2,11 +2,14 @@ "brands": [ { "type": "visa", - "supported": "true" + "supported": true }, { "type": "cartebancaire", - "supported": "true" + "supported": false } - ] + ], + "fundingSource": "CREDIT", + "isCardCommercial": false, + "issuingCountryCode": "FR" } \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/payment-links-success.json b/Adyen.Test/mocks/checkout/payment-links-success.json index 2787a6788..ebf4be12c 100644 --- a/Adyen.Test/mocks/checkout/payment-links-success.json +++ b/Adyen.Test/mocks/checkout/payment-links-success.json @@ -1,4 +1,6 @@ { + "id": "your-id", + "status": "active", "amount": { "currency": "BRL", "value": 1250 diff --git a/Adyen.Test/mocks/checkout/payment-methods-response.json b/Adyen.Test/mocks/checkout/payment-methods-response.json new file mode 100644 index 000000000..693ce5251 --- /dev/null +++ b/Adyen.Test/mocks/checkout/payment-methods-response.json @@ -0,0 +1,151 @@ +{ + "paymentMethods": [ + { + "name": "AliPay", + "type": "alipay" + }, + { + "brands": [ + "cartebancaire", + "amex", + "mc", + "visa" + ], + "configuration": { + "mcDpaId": "6d41d4d6-45b1-42c3-a5d0-a28c0e69d4b1_dpa2", + "visaSrcInitiatorId": "B9SECVKIQX2SOBQ6J9X721dVBBKHhJJl1nxxVbemHGn5oB6S8", + "mcSrcClientId": "6d41d4d6-45b1-42c3-a5d0-a28c0e69d4b1", + "visaSrciDpaId": "8e6e347c-254e-863f-0e6a-196bf2d9df02" + }, + "name": "Cards", + "type": "scheme" + }, + { + "configuration": { + "merchantId": "000000000202326", + "merchantName": "TestMerchantAccount" + }, + "name": "Apple Pay", + "type": "applepay" + }, + { + "name": "Payconiq by Bancontact", + "type": "bcmc_mobile" + }, + { + "name": "Boleto Bancario", + "type": "boletobancario" + }, + { + "name": "Online bank transfer.", + "type": "directEbanking" + }, + { + "name": "DOKU", + "type": "doku" + }, + { + "name": "DOKU wallet", + "type": "doku_wallet" + }, + { + "brand": "***************", + "name": "Generic GiftCard", + "type": "giftcard" + }, + { + "brand": "*****", + "name": "Givex", + "type": "giftcard" + }, + { + "name": "GoPay Wallet", + "type": "gopay_wallet" + }, + { + "name": "GrabPay", + "type": "grabpay_SG" + }, + { + "issuers": [ + { + "id": "************", + "name": "*****" + } + ], + "name": "iDEAL", + "type": "ideal" + }, + { + "name": "Korea–issued cards", + "type": "kcp_creditcard" + }, + { + "name": "Pay later with Klarna.", + "type": "klarna" + }, + { + "name": "Pay over time with Klarna.", + "type": "klarna_account" + }, + { + "name": "Pay now with Klarna.", + "type": "klarna_paynow" + }, + { + "name": "MB WAY", + "type": "mbway" + }, + { + "name": "MobilePay", + "type": "mobilepay" + }, + { + "configuration": { + "merchantId": "50", + "gatewayMerchantId": "TestMerchantAccount" + }, + "name": "Google Pay", + "type": "paywithgoogle" + }, + { + "name": "pix", + "type": "pix" + }, + { + "name": "SEPA Direct Debit", + "type": "sepadirectdebit" + }, + { + "brand": "***", + "name": "SVS", + "type": "giftcard" + }, + { + "name": "UPI Collect", + "type": "upi_collect" + }, + { + "name": "UPI Intent", + "type": "upi_intent" + }, + { + "name": "UPI QR", + "type": "upi_qr" + }, + { + "brand": "*********", + "name": "Valuelink", + "type": "giftcard" + }, + { + "name": "Vipps", + "type": "vipps" + }, + { + "brand": "***********", + "name": "VVV Giftcard", + "type": "giftcard" + } + ] +} diff --git a/Adyen.Test/mocks/checkout/payment-request-ideal.json b/Adyen.Test/mocks/checkout/payment-request-ideal.json new file mode 100644 index 000000000..dbe8e74f6 --- /dev/null +++ b/Adyen.Test/mocks/checkout/payment-request-ideal.json @@ -0,0 +1,12 @@ +{ + "amount":{ + "currency":"EUR", + "value":1000 + }, + "merchantAccount":"myMerchantAccount", + "paymentMethod":{ + "type":"ideal" + }, + "reference":"merchantReference", + "returnUrl":"https://your-company.com/.." +} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/paymentlinks-recurring-payment-success.json b/Adyen.Test/mocks/checkout/paymentlinks-recurring-payment-success.json deleted file mode 100644 index 628896bea..000000000 --- a/Adyen.Test/mocks/checkout/paymentlinks-recurring-payment-success.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "amount": { - "currency": "EUR", - "value": 100 - }, - "expiresAt": "2020-10-28T12:00:00Z", - "reference": "REFERENCE_NUMBER", - "url": "https://checkoutshopper-test.adyen.com/checkoutshopper/payByLink.shtml?d=YW1vdW50TWlub3JW...JRA", - "merchantAccount": "YOUR_MERCHANT_ACCOUNT" -} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/paymentmethods-error-forbidden-403.json b/Adyen.Test/mocks/checkout/paymentmethods-error-forbidden-403.json deleted file mode 100644 index 28afc9887..000000000 --- a/Adyen.Test/mocks/checkout/paymentmethods-error-forbidden-403.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "status": 403, - "errorCode": "901", - "message": "Invalid Merchant Account", - "errorType": "security" -} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/payments-success.json b/Adyen.Test/mocks/checkout/payments-success.json index 0deff7d1a..25b34868f 100644 --- a/Adyen.Test/mocks/checkout/payments-success.json +++ b/Adyen.Test/mocks/checkout/payments-success.json @@ -14,81 +14,34 @@ "accountScore": 25, "results": [ { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 2, - "name": "CardChunkUsage" - } + "accountScore": 0, + "checkId": 2, + "name": "CardChunkUsage" }, { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 3, - "name": "PaymentDetailUsage" - } + "accountScore": 0, + "checkId": 3, + "name": "PaymentDetailUsage" }, { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 4, - "name": "HolderNameUsage" - } + "accountScore": 0, + "checkId": 4, + "name": "HolderNameUsage" }, { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 1, - "name": "PaymentDetailRefCheck" - } + "accountScore": 0, + "checkId": 1, + "name": "PaymentDetailRefCheck" }, { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 13, - "name": "IssuerRefCheck" - } + "accountScore": 0, + "checkId": 13, + "name": "IssuerRefCheck" }, { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 15, - "name": "IssuingCountryReferral" - } - }, - { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 27, - "name": "PmOwnerRefCheck" - } - }, - { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 10, - "name": "HolderNameContainsNumber" - } - }, - { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 11, - "name": "HolderNameIsOneWord" - } - }, - { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 82, - "name": "CustomFieldCheck" - } - }, - { - "FraudCheckResult": { - "accountScore": 0, - "checkId": 25, - "name": "CVCAuthResultCheck" - } + "accountScore": 0, + "checkId": 15, + "name": "IssuingCountryReferral" } ] }, diff --git a/Adyen.Test/mocks/checkout/paymentsdetails-error-invalid-data-422.json b/Adyen.Test/mocks/checkout/paymentsdetails-error-invalid-data-422.json deleted file mode 100644 index ce814f1ef..000000000 --- a/Adyen.Test/mocks/checkout/paymentsdetails-error-invalid-data-422.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "status": 422, - "errorCode": "101", - "message": "Invalid card number", - "errorType": "validation" -} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/paymentsresult-multibanco-success.json b/Adyen.Test/mocks/checkout/paymentsresult-multibanco-success.json deleted file mode 100644 index 5e2c9d09c..000000000 --- a/Adyen.Test/mocks/checkout/paymentsresult-multibanco-success.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "resultCode": "PresentToShopper", - "action": { - "paymentMethodType": "multibanco", - "type": "voucher", - "entity": "12101", - "expiresAt": "2020-01-12T09:37:49", - "initialAmount": { - "currency": "EUR", - "value": 1000 - }, - "merchantName": "YOUR_MERCHANT", - "merchantReference": "YOUR_ORDER_NUMBER", - "reference": "501 422 944", - "totalAmount": { - "currency": "EUR", - "value": 1000 - }, - "action": "voucher" - } -} \ No newline at end of file diff --git a/Adyen.Test/mocks/checkout/sessions-success.json b/Adyen.Test/mocks/checkout/sessions-success.json index 18c21d05a..71f040e8e 100644 --- a/Adyen.Test/mocks/checkout/sessions-success.json +++ b/Adyen.Test/mocks/checkout/sessions-success.json @@ -1,5 +1,5 @@ { - "id": "session-test-id", + "id": "CS0068299CB8DA273A", "amount": { "currency": "EUR", "value": 1000 diff --git a/Adyen.Test/mocks/disputes/accept-disputes.json b/Adyen.Test/mocks/disputes/accept-dispute.json similarity index 100% rename from Adyen.Test/mocks/disputes/accept-disputes.json rename to Adyen.Test/mocks/disputes/accept-dispute.json diff --git a/Adyen.Test/mocks/disputes/retrieve-appicable-defense-reasons.json b/Adyen.Test/mocks/disputes/retrieve-applicable-defense-reasons.json similarity index 100% rename from Adyen.Test/mocks/disputes/retrieve-appicable-defense-reasons.json rename to Adyen.Test/mocks/disputes/retrieve-applicable-defense-reasons.json diff --git a/Adyen.Test/mocks/legalentitymanagement/BusinessLine.json b/Adyen.Test/mocks/legalentitymanagement/BusinessLine.json index 1efce18e2..174f7f3e2 100644 --- a/Adyen.Test/mocks/legalentitymanagement/BusinessLine.json +++ b/Adyen.Test/mocks/legalentitymanagement/BusinessLine.json @@ -1,16 +1,17 @@ { - "capability": "issueBankAccount", - "industryCode": "55", - "legalEntityId": "LE322JV223222D5FZ9N74BSGM", + "service": "banking", + "industryCode": "4531", + "legalEntityId": "LE00000000000000000000001", "sourceOfFunds": { - "adyenProcessedFunds": "false", + "adyenProcessedFunds": false, "description": "Funds from my flower shop business", "type": "business" }, "webData": [ { - "webAddress": "https://www.adyen.com" + "webAddress": "https://www.adyen.com", + "webAddressId": "SE322JV223222J5H8V87B3DHN" } ], - "id": "SE322KT223222D5FJ7TJN2986" + "id": "SE322KH223222F5GV2SQ924F6" } \ No newline at end of file diff --git a/Adyen.Test/mocks/legalentitymanagement/LegalEntity.json b/Adyen.Test/mocks/legalentitymanagement/LegalEntity.json index 8139d64ee..b47b5f1c7 100644 --- a/Adyen.Test/mocks/legalentitymanagement/LegalEntity.json +++ b/Adyen.Test/mocks/legalentitymanagement/LegalEntity.json @@ -1,127 +1,68 @@ { - "documentDetails": [{ - "active": false, - "fileName": "string", - "id": "string" - }], - "documents": [{ "id": "string" }], - "entityAssociations": [{ - "associatorId": "string", - "entityType": "string", - "jobTitle": "string", - "legalEntityId": "string", - "name": "string", - "type": "signatory" - }], - "id": "LE322JV223222D5GG42KN6869", - "individual": { - "birthData": { "dateOfBirth": "string" }, - "email": "string", - "identificationData": { - "expiryDate": "string", - "issuerCountry": "string", - "issuerState": "string", - "nationalIdExempt": false, - "number": "string", - "type": "nationalIdNumber" + "capabilities": { + "sendToTransferInstrument": { + "allowed": false, + "requested": true, + "transferInstruments": [ + { + "allowed": false, + "id": "SE322KH223222F5GXZFNM3BGP", + "requested": true, + "verificationStatus": "pending" + } + ], + "verificationStatus": "pending" }, - "name": { - "firstName": "string", - "infix": "string", - "lastName": "string" + "receivePayments": { + "allowed": false, + "requested": true, + "verificationStatus": "pending" }, - "nationality": "string", - "phone": { - "number": "string", - "type": "string" + "sendToBalanceAccount": { + "allowed": false, + "requested": true, + "verificationStatus": "pending" }, - "residentialAddress": { - "city": "string", - "country": "string", - "postalCode": "string", - "stateOrProvince": "string", - "street": "string", - "street2": "string" + "receiveFromPlatformPayments": { + "allowed": false, + "requested": true, + "verificationStatus": "pending" }, - "taxInformation": [{ - "country": "string", - "number": "string", - "type": "string" - }], - "webData": { "webAddress": "string" } + "receiveFromBalanceAccount": { + "allowed": false, + "requested": true, + "verificationStatus": "pending" + } }, - "organization": { - "description": "string", - "doingBusinessAs": "string", - "email": "string", - "legalName": "string", - "phone": { - "number": "string", - "type": "string" - }, - "principalPlaceOfBusiness": { - "city": "string", - "country": "string", - "postalCode": "string", - "stateOrProvince": "string", - "street": "string", - "street2": "string" - }, - "registeredAddress": { - "city": "string", - "country": "string", - "postalCode": "string", - "stateOrProvince": "string", - "street": "string", - "street2": "string" - }, - "registrationNumber": "string", - "stockData": { - "marketIdentifier": "string", - "stockNumber": "string", - "tickerSymbol": "string" - }, - "taxInformation": [{ - "country": "string", - "number": "string", - "type": "string" - }], - "taxReportingClassification": { - "businessType": "other", - "financialInstitutionNumber": "string", - "mainSourceOfIncome": "businessOperation", - "type": "nonFinancialNonReportable" + "individual": { + "email": "s.hopper@example.com", + "birthData": { + "dateOfBirth": "1990-06-21" }, - "type": "associationIncorporated", - "vatAbsenceReason": "industryExemption", - "vatNumber": "string", - "webData": { "webAddress": "string" } - }, - "reference": "string", - "soleProprietorship": { - "countryOfGoverningLaw": "string", - "doingBusinessAs": "string", - "name": "string", - "principalPlaceOfBusiness": { - "city": "string", - "country": "string", - "postalCode": "string", - "stateOrProvince": "string", - "street": "string", - "street2": "string" + "name": { + "firstName": "Simone", + "lastName": "Hopper" }, - "registeredAddress": { - "city": "string", - "country": "string", - "postalCode": "string", - "stateOrProvince": "string", - "street": "string", - "street2": "string" + "phone": { + "number": "+31858888138", + "phoneCountryCode": "NL", + "type": "mobile" }, - "registrationNumber": "string", - "vatAbsenceReason": "industryExemption", - "vatNumber": "string" + "residentialAddress": { + "city": "Amsterdam", + "country": "NL", + "postalCode": "1011DJ", + "street": "Simon Carmiggeltstraat 6 - 50", + "street2": "274" + } }, - "transferInstruments": [{ "id": "string" }], - "type": "individual" + "type": "individual", + "id": "LE322JV223222D5GG42KN6869", + "transferInstruments": [ + { + "id": "SE322KH223222F5GXZFNM3BGP", + "accountIdentifier": "NL**ABNA******0123", + "trustedSource": false + } + ] } \ No newline at end of file diff --git a/Adyen.Test/mocks/legalentitymanagement/LegalEntityBusinessLines.json b/Adyen.Test/mocks/legalentitymanagement/LegalEntityBusinessLines.json new file mode 100644 index 000000000..646cd344f --- /dev/null +++ b/Adyen.Test/mocks/legalentitymanagement/LegalEntityBusinessLines.json @@ -0,0 +1,37 @@ +{ + "businessLines": [ + { + "service": "banking", + "industryCode": "55", + "legalEntityId": "LE00000000000000000000001", + "sourceOfFunds": { + "adyenProcessedFunds": false, + "description": "Funds from my flower shop business", + "type": "business" + }, + "webData": [ + { + "webAddress": "https://www.adyen.com", + "webAddressId": "SE577HA334222K5H8V87B3BPU" + } + ], + "id": "SE322JV223222F5GVGMLNB83F" + }, + { + "service": "paymentProcessing", + "industryCode": "339E", + "legalEntityId": "LE00000000000000000000001", + "salesChannels": [ + "eCommerce", + "ecomMoto" + ], + "webData": [ + { + "webAddress": "https://yoururl.com", + "webAddressId": "SE908HJ723222F5GVGPNR55YH" + } + ], + "id": "SE322JV223222F5GVGPNRB9GJ" + } + ] +} \ No newline at end of file diff --git a/Adyen.Test/mocks/management/list-terminals.json b/Adyen.Test/mocks/management/list-terminals.json index 9f50ff321..3625f6f40 100644 --- a/Adyen.Test/mocks/management/list-terminals.json +++ b/Adyen.Test/mocks/management/list-terminals.json @@ -1,4 +1,20 @@ { + "_links": { + "first": { + "href": "https://management-test.adyen.com/v3/terminals?pageNumber=1&pageSize=20" + }, + "last": { + "href": "https://management-test.adyen.com/v3/terminals?pageNumber=1&pageSize=20" + }, + "next": { + "href": "https://management-test.adyen.com/v3/terminals?pageNumber=1&pageSize=20" + }, + "self": { + "href": "https://management-test.adyen.com/v3/terminals?pageNumber=0&pageSize=20" + } + }, + "itemsTotal": 1, + "pagesTotal": 1, "data": [ { "id": "S1F2-000150183300032", diff --git a/Adyen.Test/mocks/pos-terminal-management/assing-terminals-success.json b/Adyen.Test/mocks/pos-terminal-management/assigning-terminals-success.json similarity index 100% rename from Adyen.Test/mocks/pos-terminal-management/assing-terminals-success.json rename to Adyen.Test/mocks/pos-terminal-management/assigning-terminals-success.json diff --git a/Adyen.Test/mocks/pos-terminal-management/get-terminals-details-success.json b/Adyen.Test/mocks/pos-terminal-management/get-terminal-details-success.json similarity index 100% rename from Adyen.Test/mocks/pos-terminal-management/get-terminals-details-success.json rename to Adyen.Test/mocks/pos-terminal-management/get-terminal-details-success.json diff --git a/Adyen.Test/mocks/transfers/get-all-transactions.json b/Adyen.Test/mocks/transfers/get-all-transactions.json index b55e6c2e7..c253e2bed 100644 --- a/Adyen.Test/mocks/transfers/get-all-transactions.json +++ b/Adyen.Test/mocks/transfers/get-all-transactions.json @@ -1,72 +1,109 @@ { "data": [ { - "accountHolderId": "AHA1B2C3D4E5F6G7H8I9J0", + "balancePlatform": "YOUR_BALANCE_PLATFORM", + "creationDate": "2023-08-10T14:51:20+02:00", + "id": "EVJN42272224222B5JB8BRC84N686ZEUR", + "accountHolder": { + "description": "Your description for the account holder", + "id": "AH00000000000000000000001" + }, "amount": { - "currency": "EUR", - "value": -9 + "currency": "USD", + "value": -1000 }, - "balanceAccountId": "BAB8B2C3D4E5F6G7H8D9J6GD4", - "balancePlatform": "YOUR_BALANCE_PLATFORM", - "bookingDate": "2022-03-11T11:21:24+01:00", - "category": "internal", - "createdAt": "2022-03-11T11:21:24+01:00", - "id": "1VVF0D5U66PIUIVP", - "instructedAmount": { - "currency": "EUR", - "value": -9 - }, - "reference": "REFERENCE_46e8c40e", + "balanceAccount": { + "description": "Your description for the account holder", + "id": "BA00000000000000000000001" + }, + "bookingDate": "2023-08-10T14:51:33+02:00", + "eventId": "EVJN42272224222B5JB8BRC84N686Z", "status": "booked", - "transferId": "1VVF0D5U66PIUIVP", - "type": "fee", - "valueDate": "2022-03-11T11:21:24+01:00" + "transfer": { + "id": "3JNC3O5ZVFLLGV4B", + "reference": "Your internal reference for the transfer" + }, + "valueDate": "2023-08-10T14:51:20+02:00" }, { - "accountHolderId": "AHA1B2C3D4E5F6G7H8I9J0", + "balancePlatform": "YOUR_BALANCE_PLATFORM", + "creationDate": "2023-08-10T15:34:31+02:00", + "id": "EVJN4227C224222B5JB8G3Q89N2NB6EUR", + "accountHolder": { + "description": "Your description for the account holder", + "id": "AH00000000000000000000001" + }, "amount": { - "currency": "EUR", - "value": -46 + "currency": "USD", + "value": 123 }, - "balanceAccountId": "BAB8B2C3D4E5F6G7H8D9J6GD4", - "balancePlatform": "YOUR_BALANCE_PLATFORM", - "bookingDate": "2022-03-12T14:22:52+01:00", - "category": "internal", - "createdAt": "2022-03-12T14:22:52+01:00", - "id": "1WEPGD5U6MS1CFK3", - "instructedAmount": { - "currency": "EUR", - "value": -46 - }, - "reference": "YOUR_REFERENCE", + "balanceAccount": { + "description": "Your description for the account holder", + "id": "BA00000000000000000000001" + }, + "bookingDate": "2023-08-10T15:34:40+02:00", + "eventId": "EVJN4227C224222B5JB8G3Q89N2NB6", "status": "booked", - "transferId": "1WEPGD5U6MS1CFK3", - "type": "fee", - "valueDate": "2022-03-12T14:22:52+01:00" + "transfer": { + "id": "48POO45ZVG11166J", + "reference": "Your internal reference for the transfer" + }, + "valueDate": "2023-08-10T15:34:31+02:00" }, { - "accountHolderId": "AHA1B2C3D4E5F6G7H8I9J0", + "balancePlatform": "YOUR_BALANCE_PLATFORM", + "creationDate": "2023-08-11T13:45:46+02:00", + "id": "EVJN4227C224222B5JBD3XHF8P3L8GUSD", + "accountHolder": { + "description": "Your description for the account holder", + "id": "AH00000000000000000000001" + }, "amount": { - "currency": "EUR", - "value": -8 + "currency": "USD", + "value": -10000 + }, + "balanceAccount": { + "description": "Your description for the account holder", + "id": "BA00000000000000000000001" }, - "balanceAccountId": "BAB8B2C3D4E5F6G7H8D9J6GD4", + "bookingDate": "2023-08-11T13:45:57+02:00", + "eventId": "EVJN4227C224222B5JBD3XHF8P3L8G", + "status": "booked", + "transfer": { + "id": "48RTTW5ZVT8KU9DV", + "reference": "my-reference" + }, + "valueDate": "2023-08-11T13:45:46+02:00" + }, + { "balancePlatform": "YOUR_BALANCE_PLATFORM", - "bookingDate": "2022-03-14T21:00:48+01:00", - "createdAt": "2022-03-14T15:00:00+01:00", - "description": "YOUR_DESCRIPTION_2", - "id": "2QP32A5U7IWC5WKG", - "instructedAmount": { - "currency": "EUR", - "value": -8 + "creationDate": "2023-08-11T13:45:51+02:00", + "id": "EVJN42272224222B5JBD3XJGHF4J26USD", + "accountHolder": { + "description": "Your description for the account holder", + "id": "AH00000000000000000000001" + }, + "amount": { + "currency": "USD", + "value": 1000 }, + "balanceAccount": { + "description": "Your description for the account holder", + "id": "BA00000000000000000000001" + }, + "bookingDate": "2023-08-11T13:45:58+02:00", + "eventId": "EVJN42272224222B5JBD3XJGHF4J26", "status": "booked", - "valueDate": "2022-03-14T21:00:48+01:00" + "transfer": { + "id": "48TYZO5ZVT8M1K47", + "reference": "my-reference" + }, + "valueDate": "2023-08-11T13:45:51+02:00" } ], "_links": { "next": { - "href": "https://balanceplatform-api-test.adyen.com/btl/v2/transactions?balancePlatform=Bastronaut&createdUntil=2022-03-21T00%3A00%3A00Z&createdSince=2022-03-11T00%3A00%3A00Z&limit=3&cursor=S2B-TSAjOkIrYlIlbjdqe0RreHRyM32lKRSxubXBHRkhHL2E32XitQQz5SfzpucD5HbHwpM1p6NDR1eXVQLFF6MmY33J32sobDxQYT90MHIud1hwLnd6JitcX32xJ" + "href": "https://balanceplatform-api-test.adyen.com/btl/v4/transactions?balancePlatform=TestBalancePlatform&createdUntil=2023-08-20T13%3A07%3A40Z&createdSince=2023-08-10T10%3A50%3A40Z&cursor=S2B-c0p1N0tdN0l6RGhYK1YpM0lgOTUyMDlLXElyKE9LMCtyaFEuMj1NMHgidCsrJi1ZNnhqXCtqVi5JPGpRK1F2fCFqWzU33JTojSVNJc1J1VXhncS10QDd6JX9FQFl5Zn0uNyUvSXJNQTo" } } } \ No newline at end of file diff --git a/Adyen/AcsWebhooks/Client/ClientUtils.cs b/Adyen/AcsWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..09580615a --- /dev/null +++ b/Adyen/AcsWebhooks/Client/ClientUtils.cs @@ -0,0 +1,313 @@ +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.AcsWebhooks.Models; +using Models = Adyen.AcsWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.AcsWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AuthenticationDecision.StatusEnum authenticationDecisionStatusEnum) + return Models.AuthenticationDecision.StatusEnum.ToJsonValue(authenticationDecisionStatusEnum); + if (obj is Models.AuthenticationInfo.ChallengeIndicatorEnum authenticationInfoChallengeIndicatorEnum) + return Models.AuthenticationInfo.ChallengeIndicatorEnum.ToJsonValue(authenticationInfoChallengeIndicatorEnum); + if (obj is Models.AuthenticationInfo.DeviceChannelEnum authenticationInfoDeviceChannelEnum) + return Models.AuthenticationInfo.DeviceChannelEnum.ToJsonValue(authenticationInfoDeviceChannelEnum); + if (obj is Models.AuthenticationInfo.MessageCategoryEnum authenticationInfoMessageCategoryEnum) + return Models.AuthenticationInfo.MessageCategoryEnum.ToJsonValue(authenticationInfoMessageCategoryEnum); + if (obj is Models.AuthenticationInfo.TransStatusEnum authenticationInfoTransStatusEnum) + return Models.AuthenticationInfo.TransStatusEnum.ToJsonValue(authenticationInfoTransStatusEnum); + if (obj is Models.AuthenticationInfo.TypeEnum authenticationInfoTypeEnum) + return Models.AuthenticationInfo.TypeEnum.ToJsonValue(authenticationInfoTypeEnum); + if (obj is Models.AuthenticationInfo.ExemptionIndicatorEnum authenticationInfoExemptionIndicatorEnum) + return Models.AuthenticationInfo.ExemptionIndicatorEnum.ToJsonValue(authenticationInfoExemptionIndicatorEnum); + if (obj is Models.AuthenticationInfo.TransStatusReasonEnum authenticationInfoTransStatusReasonEnum) + return Models.AuthenticationInfo.TransStatusReasonEnum.ToJsonValue(authenticationInfoTransStatusReasonEnum); + if (obj is Models.AuthenticationNotificationData.StatusEnum authenticationNotificationDataStatusEnum) + return Models.AuthenticationNotificationData.StatusEnum.ToJsonValue(authenticationNotificationDataStatusEnum); + if (obj is Models.AuthenticationNotificationRequest.TypeEnum authenticationNotificationRequestTypeEnum) + return Models.AuthenticationNotificationRequest.TypeEnum.ToJsonValue(authenticationNotificationRequestTypeEnum); + if (obj is Models.ChallengeInfo.FlowEnum challengeInfoFlowEnum) + return Models.ChallengeInfo.FlowEnum.ToJsonValue(challengeInfoFlowEnum); + if (obj is Models.ChallengeInfo.ChallengeCancelEnum challengeInfoChallengeCancelEnum) + return Models.ChallengeInfo.ChallengeCancelEnum.ToJsonValue(challengeInfoChallengeCancelEnum); + if (obj is Models.RelayedAuthenticationRequest.TypeEnum relayedAuthenticationRequestTypeEnum) + return Models.RelayedAuthenticationRequest.TypeEnum.ToJsonValue(relayedAuthenticationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/AcsWebhooks/Client/HmacKeyToken.cs b/Adyen/AcsWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..e05ec5f88 --- /dev/null +++ b/Adyen/AcsWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.AcsWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/AcsWebhooks/Client/HostConfiguration.cs b/Adyen/AcsWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..9836e6cd6 --- /dev/null +++ b/Adyen/AcsWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,140 @@ +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.AcsWebhooks.Client; +using Adyen.AcsWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.AcsWebhooks.Client +{ + /// + /// Provides hosting configuration for AcsWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationDecisionJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationInfoJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new ChallengeInfoJsonConverter()); + _jsonOptions.Converters.Add(new PurchaseJsonConverter()); + _jsonOptions.Converters.Add(new PurchaseInfoJsonConverter()); + _jsonOptions.Converters.Add(new RelayedAuthenticationRequestJsonConverter()); + _jsonOptions.Converters.Add(new RelayedAuthenticationResponseJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddAcsWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/AcsWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/AcsWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..555a228cf --- /dev/null +++ b/Adyen/AcsWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.AcsWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/AcsWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/AcsWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..08e8936e7 --- /dev/null +++ b/Adyen/AcsWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.AcsWebhooks; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the AcsWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureAcsWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddAcsWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/AcsWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/AcsWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..b1df20a58 --- /dev/null +++ b/Adyen/AcsWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen AcsWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddAcsWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddAcsWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/AcsWebhooks/Handlers/AcsWebhooksHandler.cs b/Adyen/AcsWebhooks/Handlers/AcsWebhooksHandler.cs new file mode 100644 index 000000000..b8eb41c0a --- /dev/null +++ b/Adyen/AcsWebhooks/Handlers/AcsWebhooksHandler.cs @@ -0,0 +1,95 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.AcsWebhooks.Client; +using Adyen.AcsWebhooks.Models; + +namespace Adyen.AcsWebhooks.Handlers +{ + /// + /// Interface for deserializing AcsWebhooks webhooks or verify its HMAC signature. + /// + public interface IAcsWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.AcsWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + AuthenticationNotificationRequest? DeserializeAuthenticationNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + RelayedAuthenticationRequest? DeserializeRelayedAuthenticationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize AcsWebhooks or verify the HMAC signature of the webhook. + /// + public partial class AcsWebhooksHandler : IAcsWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.AcsWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing AcsWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public AcsWebhooksHandler(Adyen.AcsWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public AuthenticationNotificationRequest? DeserializeAuthenticationNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public RelayedAuthenticationRequest? DeserializeRelayedAuthenticationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/Amount.cs b/Adyen/AcsWebhooks/Models/Amount.cs new file mode 100644 index 000000000..3c162b213 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/AuthenticationDecision.cs b/Adyen/AcsWebhooks/Models/AuthenticationDecision.cs new file mode 100644 index 000000000..048984cf0 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/AuthenticationDecision.cs @@ -0,0 +1,278 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// AuthenticationDecision. + /// + public partial class AuthenticationDecision : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the authentication. Possible values: * **refused** * **proceed** For more information, refer to [Authenticate cardholders using the Authentication SDK](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/authenticate-cardholders/). + [JsonConstructor] + public AuthenticationDecision(StatusEnum status) + { + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationDecision() + { + } + + partial void OnCreated(); + + /// + /// The status of the authentication. Possible values: * **refused** * **proceed** For more information, refer to [Authenticate cardholders using the Authentication SDK](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/authenticate-cardholders/). + /// + /// The status of the authentication. Possible values: * **refused** * **proceed** For more information, refer to [Authenticate cardholders using the Authentication SDK](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/authenticate-cardholders/). + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Proceed - proceed + /// + public static readonly StatusEnum Proceed = new("proceed"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "proceed" => StatusEnum.Proceed, + "refused" => StatusEnum.Refused, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Proceed) + return "proceed"; + + if (value == StatusEnum.Refused) + return "refused"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the authentication. Possible values: * **refused** * **proceed** For more information, refer to [Authenticate cardholders using the Authentication SDK](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/authenticate-cardholders/). + /// + /// The status of the authentication. Possible values: * **refused** * **proceed** For more information, refer to [Authenticate cardholders using the Authentication SDK](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/authenticate-cardholders/). + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationDecision {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationDecisionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationDecision Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AuthenticationDecision.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AuthenticationDecision.", nameof(status)); + + return new AuthenticationDecision(status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationDecision authenticationDecision, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationDecision, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationDecision authenticationDecision, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationDecision.Status != null) + { + string? statusRawValue = AuthenticationDecision.StatusEnum.ToJsonValue(authenticationDecision.Status); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/AcsWebhooks/Models/AuthenticationInfo.cs b/Adyen/AcsWebhooks/Models/AuthenticationInfo.cs new file mode 100644 index 000000000..f1424e1e2 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/AuthenticationInfo.cs @@ -0,0 +1,1670 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// AuthenticationInfo. + /// + public partial class AuthenticationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Universally unique transaction identifier assigned by the Access Control Server (ACS) to identify a single transaction. + /// Specifies a preference for receiving a challenge. Possible values: * **01**: No preference * **02**: No challenge requested * **03**: Challenge requested (preference) * **04**: Challenge requested (mandate) * **05**: No challenge requested (transactional risk analysis is already performed) * **07**: No challenge requested (SCA is already performed) * **08**: No challenge requested (trusted beneficiaries exemption of no challenge required) * **09**: Challenge requested (trusted beneficiaries prompt requested if challenge required) * **80**: No challenge requested (secure corporate payment with Mastercard) * **82**: No challenge requested (secure corporate payment with Visa) + /// Date and time in UTC of the cardholder authentication. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// Indicates the type of channel interface being used to initiate the transaction. Possible values: * **app** * **browser** * **3DSRequestorInitiated** (initiated by a merchant when the cardholder is not available) + /// Universally unique transaction identifier assigned by the DS (card scheme) to identify a single transaction. + /// Indicates if the purchase was in the PSD2 scope. + /// Identifies the category of the message for a specific use case. Possible values: * **payment** * **nonPayment** + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// The `transStatus` value as defined in the 3D Secure 2 specification. Possible values: * **Y**: Authentication / Account verification successful. * **N**: Not Authenticated / Account not verified. Transaction denied. * **U**: Authentication / Account verification could not be performed. * **I**: Informational Only / 3D Secure Requestor challenge preference acknowledged. * **R**: Authentication / Account verification rejected by the Issuer. + /// The type of authentication performed. Possible values: * **frictionless** * **challenge** + /// challenge + /// Indicates the exemption type that was applied to the authentication by the issuer, if exemption applied. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** * **acquirerExemption** * **noExemptionApplied** * **visaDAFExemption** + /// Risk score calculated from the transaction rules. + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonConstructor] + public AuthenticationInfo(string acsTransId, ChallengeIndicatorEnum challengeIndicator, DateTimeOffset createdAt, DeviceChannelEnum deviceChannel, string dsTransID, bool inPSD2Scope, MessageCategoryEnum messageCategory, string messageVersion, string threeDSServerTransID, TransStatusEnum transStatus, TypeEnum type, Option challenge = default, Option exemptionIndicator = default, Option riskScore = default, Option transStatusReason = default) + { + AcsTransId = acsTransId; + ChallengeIndicator = challengeIndicator; + CreatedAt = createdAt; + DeviceChannel = deviceChannel; + DsTransID = dsTransID; + InPSD2Scope = inPSD2Scope; + MessageCategory = messageCategory; + MessageVersion = messageVersion; + ThreeDSServerTransID = threeDSServerTransID; + TransStatus = transStatus; + Type = type; + _ChallengeOption = challenge; + _ExemptionIndicatorOption = exemptionIndicator; + _RiskScoreOption = riskScore; + _TransStatusReasonOption = transStatusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationInfo() + { + } + + partial void OnCreated(); + + /// + /// Specifies a preference for receiving a challenge. Possible values: * **01**: No preference * **02**: No challenge requested * **03**: Challenge requested (preference) * **04**: Challenge requested (mandate) * **05**: No challenge requested (transactional risk analysis is already performed) * **07**: No challenge requested (SCA is already performed) * **08**: No challenge requested (trusted beneficiaries exemption of no challenge required) * **09**: Challenge requested (trusted beneficiaries prompt requested if challenge required) * **80**: No challenge requested (secure corporate payment with Mastercard) * **82**: No challenge requested (secure corporate payment with Visa) + /// + /// Specifies a preference for receiving a challenge. Possible values: * **01**: No preference * **02**: No challenge requested * **03**: Challenge requested (preference) * **04**: Challenge requested (mandate) * **05**: No challenge requested (transactional risk analysis is already performed) * **07**: No challenge requested (SCA is already performed) * **08**: No challenge requested (trusted beneficiaries exemption of no challenge required) * **09**: Challenge requested (trusted beneficiaries prompt requested if challenge required) * **80**: No challenge requested (secure corporate payment with Mastercard) * **82**: No challenge requested (secure corporate payment with Visa) + [JsonConverter(typeof(ChallengeIndicatorEnumJsonConverter))] + public class ChallengeIndicatorEnum : IEnum + { + /// + /// Returns the value of the ChallengeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeIndicatorEnum._01 - 01 + /// + public static readonly ChallengeIndicatorEnum _01 = new("01"); + + /// + /// ChallengeIndicatorEnum._02 - 02 + /// + public static readonly ChallengeIndicatorEnum _02 = new("02"); + + /// + /// ChallengeIndicatorEnum._03 - 03 + /// + public static readonly ChallengeIndicatorEnum _03 = new("03"); + + /// + /// ChallengeIndicatorEnum._04 - 04 + /// + public static readonly ChallengeIndicatorEnum _04 = new("04"); + + /// + /// ChallengeIndicatorEnum._05 - 05 + /// + public static readonly ChallengeIndicatorEnum _05 = new("05"); + + /// + /// ChallengeIndicatorEnum._07 - 07 + /// + public static readonly ChallengeIndicatorEnum _07 = new("07"); + + /// + /// ChallengeIndicatorEnum._08 - 08 + /// + public static readonly ChallengeIndicatorEnum _08 = new("08"); + + /// + /// ChallengeIndicatorEnum._09 - 09 + /// + public static readonly ChallengeIndicatorEnum _09 = new("09"); + + /// + /// ChallengeIndicatorEnum._80 - 80 + /// + public static readonly ChallengeIndicatorEnum _80 = new("80"); + + /// + /// ChallengeIndicatorEnum._82 - 82 + /// + public static readonly ChallengeIndicatorEnum _82 = new("82"); + + private ChallengeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeIndicatorEnum?(string? value) => value == null ? null : new ChallengeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeIndicatorEnum._01, + "02" => ChallengeIndicatorEnum._02, + "03" => ChallengeIndicatorEnum._03, + "04" => ChallengeIndicatorEnum._04, + "05" => ChallengeIndicatorEnum._05, + "07" => ChallengeIndicatorEnum._07, + "08" => ChallengeIndicatorEnum._08, + "09" => ChallengeIndicatorEnum._09, + "80" => ChallengeIndicatorEnum._80, + "82" => ChallengeIndicatorEnum._82, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeIndicatorEnum._01) + return "01"; + + if (value == ChallengeIndicatorEnum._02) + return "02"; + + if (value == ChallengeIndicatorEnum._03) + return "03"; + + if (value == ChallengeIndicatorEnum._04) + return "04"; + + if (value == ChallengeIndicatorEnum._05) + return "05"; + + if (value == ChallengeIndicatorEnum._07) + return "07"; + + if (value == ChallengeIndicatorEnum._08) + return "08"; + + if (value == ChallengeIndicatorEnum._09) + return "09"; + + if (value == ChallengeIndicatorEnum._80) + return "80"; + + if (value == ChallengeIndicatorEnum._82) + return "82"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeIndicatorEnum. + /// + public class ChallengeIndicatorEnumJsonConverter : JsonConverter + { + public override ChallengeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeIndicatorEnum.FromStringOrDefault(value) ?? new ChallengeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// Specifies a preference for receiving a challenge. Possible values: * **01**: No preference * **02**: No challenge requested * **03**: Challenge requested (preference) * **04**: Challenge requested (mandate) * **05**: No challenge requested (transactional risk analysis is already performed) * **07**: No challenge requested (SCA is already performed) * **08**: No challenge requested (trusted beneficiaries exemption of no challenge required) * **09**: Challenge requested (trusted beneficiaries prompt requested if challenge required) * **80**: No challenge requested (secure corporate payment with Mastercard) * **82**: No challenge requested (secure corporate payment with Visa) + /// + /// Specifies a preference for receiving a challenge. Possible values: * **01**: No preference * **02**: No challenge requested * **03**: Challenge requested (preference) * **04**: Challenge requested (mandate) * **05**: No challenge requested (transactional risk analysis is already performed) * **07**: No challenge requested (SCA is already performed) * **08**: No challenge requested (trusted beneficiaries exemption of no challenge required) * **09**: Challenge requested (trusted beneficiaries prompt requested if challenge required) * **80**: No challenge requested (secure corporate payment with Mastercard) * **82**: No challenge requested (secure corporate payment with Visa) + [JsonPropertyName("challengeIndicator")] + public ChallengeIndicatorEnum ChallengeIndicator { get; set; } + + /// + /// Indicates the type of channel interface being used to initiate the transaction. Possible values: * **app** * **browser** * **3DSRequestorInitiated** (initiated by a merchant when the cardholder is not available) + /// + /// Indicates the type of channel interface being used to initiate the transaction. Possible values: * **app** * **browser** * **3DSRequestorInitiated** (initiated by a merchant when the cardholder is not available) + [JsonConverter(typeof(DeviceChannelEnumJsonConverter))] + public class DeviceChannelEnum : IEnum + { + /// + /// Returns the value of the DeviceChannelEnum. + /// + public string? Value { get; set; } + + /// + /// DeviceChannelEnum.App - app + /// + public static readonly DeviceChannelEnum App = new("app"); + + /// + /// DeviceChannelEnum.Browser - browser + /// + public static readonly DeviceChannelEnum Browser = new("browser"); + + /// + /// DeviceChannelEnum.ThreeDSRequestorInitiated - ThreeDSRequestorInitiated + /// + public static readonly DeviceChannelEnum ThreeDSRequestorInitiated = new("ThreeDSRequestorInitiated"); + + private DeviceChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeviceChannelEnum?(string? value) => value == null ? null : new DeviceChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeviceChannelEnum? option) => option?.Value; + + public static bool operator ==(DeviceChannelEnum? left, DeviceChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeviceChannelEnum? left, DeviceChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeviceChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeviceChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "app" => DeviceChannelEnum.App, + "browser" => DeviceChannelEnum.Browser, + "ThreeDSRequestorInitiated" => DeviceChannelEnum.ThreeDSRequestorInitiated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeviceChannelEnum? value) + { + if (value == null) + return null; + + if (value == DeviceChannelEnum.App) + return "app"; + + if (value == DeviceChannelEnum.Browser) + return "browser"; + + if (value == DeviceChannelEnum.ThreeDSRequestorInitiated) + return "ThreeDSRequestorInitiated"; + + return null; + } + + /// + /// JsonConverter for writing DeviceChannelEnum. + /// + public class DeviceChannelEnumJsonConverter : JsonConverter + { + public override DeviceChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeviceChannelEnum.FromStringOrDefault(value) ?? new DeviceChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeviceChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeviceChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// Indicates the type of channel interface being used to initiate the transaction. Possible values: * **app** * **browser** * **3DSRequestorInitiated** (initiated by a merchant when the cardholder is not available) + /// + /// Indicates the type of channel interface being used to initiate the transaction. Possible values: * **app** * **browser** * **3DSRequestorInitiated** (initiated by a merchant when the cardholder is not available) + [JsonPropertyName("deviceChannel")] + public DeviceChannelEnum DeviceChannel { get; set; } + + /// + /// Identifies the category of the message for a specific use case. Possible values: * **payment** * **nonPayment** + /// + /// Identifies the category of the message for a specific use case. Possible values: * **payment** * **nonPayment** + [JsonConverter(typeof(MessageCategoryEnumJsonConverter))] + public class MessageCategoryEnum : IEnum + { + /// + /// Returns the value of the MessageCategoryEnum. + /// + public string? Value { get; set; } + + /// + /// MessageCategoryEnum.Payment - payment + /// + public static readonly MessageCategoryEnum Payment = new("payment"); + + /// + /// MessageCategoryEnum.NonPayment - nonPayment + /// + public static readonly MessageCategoryEnum NonPayment = new("nonPayment"); + + private MessageCategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator MessageCategoryEnum?(string? value) => value == null ? null : new MessageCategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(MessageCategoryEnum? option) => option?.Value; + + public static bool operator ==(MessageCategoryEnum? left, MessageCategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(MessageCategoryEnum? left, MessageCategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is MessageCategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static MessageCategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "payment" => MessageCategoryEnum.Payment, + "nonPayment" => MessageCategoryEnum.NonPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(MessageCategoryEnum? value) + { + if (value == null) + return null; + + if (value == MessageCategoryEnum.Payment) + return "payment"; + + if (value == MessageCategoryEnum.NonPayment) + return "nonPayment"; + + return null; + } + + /// + /// JsonConverter for writing MessageCategoryEnum. + /// + public class MessageCategoryEnumJsonConverter : JsonConverter + { + public override MessageCategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : MessageCategoryEnum.FromStringOrDefault(value) ?? new MessageCategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, MessageCategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(MessageCategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// Identifies the category of the message for a specific use case. Possible values: * **payment** * **nonPayment** + /// + /// Identifies the category of the message for a specific use case. Possible values: * **payment** * **nonPayment** + [JsonPropertyName("messageCategory")] + public MessageCategoryEnum MessageCategory { get; set; } + + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. Possible values: * **Y**: Authentication / Account verification successful. * **N**: Not Authenticated / Account not verified. Transaction denied. * **U**: Authentication / Account verification could not be performed. * **I**: Informational Only / 3D Secure Requestor challenge preference acknowledged. * **R**: Authentication / Account verification rejected by the Issuer. + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. Possible values: * **Y**: Authentication / Account verification successful. * **N**: Not Authenticated / Account not verified. Transaction denied. * **U**: Authentication / Account verification could not be performed. * **I**: Informational Only / 3D Secure Requestor challenge preference acknowledged. * **R**: Authentication / Account verification rejected by the Issuer. + [JsonConverter(typeof(TransStatusEnumJsonConverter))] + public class TransStatusEnum : IEnum + { + /// + /// Returns the value of the TransStatusEnum. + /// + public string? Value { get; set; } + + /// + /// TransStatusEnum.Y - Y + /// + public static readonly TransStatusEnum Y = new("Y"); + + /// + /// TransStatusEnum.N - N + /// + public static readonly TransStatusEnum N = new("N"); + + /// + /// TransStatusEnum.R - R + /// + public static readonly TransStatusEnum R = new("R"); + + /// + /// TransStatusEnum.I - I + /// + public static readonly TransStatusEnum I = new("I"); + + /// + /// TransStatusEnum.U - U + /// + public static readonly TransStatusEnum U = new("U"); + + private TransStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransStatusEnum?(string? value) => value == null ? null : new TransStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransStatusEnum? option) => option?.Value; + + public static bool operator ==(TransStatusEnum? left, TransStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransStatusEnum? left, TransStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => TransStatusEnum.Y, + "N" => TransStatusEnum.N, + "R" => TransStatusEnum.R, + "I" => TransStatusEnum.I, + "U" => TransStatusEnum.U, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransStatusEnum? value) + { + if (value == null) + return null; + + if (value == TransStatusEnum.Y) + return "Y"; + + if (value == TransStatusEnum.N) + return "N"; + + if (value == TransStatusEnum.R) + return "R"; + + if (value == TransStatusEnum.I) + return "I"; + + if (value == TransStatusEnum.U) + return "U"; + + return null; + } + + /// + /// JsonConverter for writing TransStatusEnum. + /// + public class TransStatusEnumJsonConverter : JsonConverter + { + public override TransStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransStatusEnum.FromStringOrDefault(value) ?? new TransStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. Possible values: * **Y**: Authentication / Account verification successful. * **N**: Not Authenticated / Account not verified. Transaction denied. * **U**: Authentication / Account verification could not be performed. * **I**: Informational Only / 3D Secure Requestor challenge preference acknowledged. * **R**: Authentication / Account verification rejected by the Issuer. + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. Possible values: * **Y**: Authentication / Account verification successful. * **N**: Not Authenticated / Account not verified. Transaction denied. * **U**: Authentication / Account verification could not be performed. * **I**: Informational Only / 3D Secure Requestor challenge preference acknowledged. * **R**: Authentication / Account verification rejected by the Issuer. + [JsonPropertyName("transStatus")] + public TransStatusEnum TransStatus { get; set; } + + /// + /// The type of authentication performed. Possible values: * **frictionless** * **challenge** + /// + /// The type of authentication performed. Possible values: * **frictionless** * **challenge** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Frictionless - frictionless + /// + public static readonly TypeEnum Frictionless = new("frictionless"); + + /// + /// TypeEnum.Challenge - challenge + /// + public static readonly TypeEnum Challenge = new("challenge"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "frictionless" => TypeEnum.Frictionless, + "challenge" => TypeEnum.Challenge, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Frictionless) + return "frictionless"; + + if (value == TypeEnum.Challenge) + return "challenge"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of authentication performed. Possible values: * **frictionless** * **challenge** + /// + /// The type of authentication performed. Possible values: * **frictionless** * **challenge** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Indicates the exemption type that was applied to the authentication by the issuer, if exemption applied. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** * **acquirerExemption** * **noExemptionApplied** * **visaDAFExemption** + /// + /// Indicates the exemption type that was applied to the authentication by the issuer, if exemption applied. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** * **acquirerExemption** * **noExemptionApplied** * **visaDAFExemption** + [JsonConverter(typeof(ExemptionIndicatorEnumJsonConverter))] + public class ExemptionIndicatorEnum : IEnum + { + /// + /// Returns the value of the ExemptionIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ExemptionIndicatorEnum.LowValue - lowValue + /// + public static readonly ExemptionIndicatorEnum LowValue = new("lowValue"); + + /// + /// ExemptionIndicatorEnum.SecureCorporate - secureCorporate + /// + public static readonly ExemptionIndicatorEnum SecureCorporate = new("secureCorporate"); + + /// + /// ExemptionIndicatorEnum.TrustedBeneficiary - trustedBeneficiary + /// + public static readonly ExemptionIndicatorEnum TrustedBeneficiary = new("trustedBeneficiary"); + + /// + /// ExemptionIndicatorEnum.TransactionRiskAnalysis - transactionRiskAnalysis + /// + public static readonly ExemptionIndicatorEnum TransactionRiskAnalysis = new("transactionRiskAnalysis"); + + /// + /// ExemptionIndicatorEnum.AcquirerExemption - acquirerExemption + /// + public static readonly ExemptionIndicatorEnum AcquirerExemption = new("acquirerExemption"); + + /// + /// ExemptionIndicatorEnum.NoExemptionApplied - noExemptionApplied + /// + public static readonly ExemptionIndicatorEnum NoExemptionApplied = new("noExemptionApplied"); + + /// + /// ExemptionIndicatorEnum.VisaDAFExemption - visaDAFExemption + /// + public static readonly ExemptionIndicatorEnum VisaDAFExemption = new("visaDAFExemption"); + + private ExemptionIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ExemptionIndicatorEnum?(string? value) => value == null ? null : new ExemptionIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ExemptionIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ExemptionIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ExemptionIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "lowValue" => ExemptionIndicatorEnum.LowValue, + "secureCorporate" => ExemptionIndicatorEnum.SecureCorporate, + "trustedBeneficiary" => ExemptionIndicatorEnum.TrustedBeneficiary, + "transactionRiskAnalysis" => ExemptionIndicatorEnum.TransactionRiskAnalysis, + "acquirerExemption" => ExemptionIndicatorEnum.AcquirerExemption, + "noExemptionApplied" => ExemptionIndicatorEnum.NoExemptionApplied, + "visaDAFExemption" => ExemptionIndicatorEnum.VisaDAFExemption, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ExemptionIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ExemptionIndicatorEnum.LowValue) + return "lowValue"; + + if (value == ExemptionIndicatorEnum.SecureCorporate) + return "secureCorporate"; + + if (value == ExemptionIndicatorEnum.TrustedBeneficiary) + return "trustedBeneficiary"; + + if (value == ExemptionIndicatorEnum.TransactionRiskAnalysis) + return "transactionRiskAnalysis"; + + if (value == ExemptionIndicatorEnum.AcquirerExemption) + return "acquirerExemption"; + + if (value == ExemptionIndicatorEnum.NoExemptionApplied) + return "noExemptionApplied"; + + if (value == ExemptionIndicatorEnum.VisaDAFExemption) + return "visaDAFExemption"; + + return null; + } + + /// + /// JsonConverter for writing ExemptionIndicatorEnum. + /// + public class ExemptionIndicatorEnumJsonConverter : JsonConverter + { + public override ExemptionIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ExemptionIndicatorEnum.FromStringOrDefault(value) ?? new ExemptionIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ExemptionIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ExemptionIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionIndicatorOption { get; private set; } + + /// + /// Indicates the exemption type that was applied to the authentication by the issuer, if exemption applied. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** * **acquirerExemption** * **noExemptionApplied** * **visaDAFExemption** + /// + /// Indicates the exemption type that was applied to the authentication by the issuer, if exemption applied. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** * **acquirerExemption** * **noExemptionApplied** * **visaDAFExemption** + [JsonPropertyName("exemptionIndicator")] + public ExemptionIndicatorEnum? ExemptionIndicator { get { return this._ExemptionIndicatorOption; } set { this._ExemptionIndicatorOption = new(value); } } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonConverter(typeof(TransStatusReasonEnumJsonConverter))] + public class TransStatusReasonEnum : IEnum + { + /// + /// Returns the value of the TransStatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// TransStatusReasonEnum._01 - 01 + /// + public static readonly TransStatusReasonEnum _01 = new("01"); + + /// + /// TransStatusReasonEnum._02 - 02 + /// + public static readonly TransStatusReasonEnum _02 = new("02"); + + /// + /// TransStatusReasonEnum._03 - 03 + /// + public static readonly TransStatusReasonEnum _03 = new("03"); + + /// + /// TransStatusReasonEnum._04 - 04 + /// + public static readonly TransStatusReasonEnum _04 = new("04"); + + /// + /// TransStatusReasonEnum._05 - 05 + /// + public static readonly TransStatusReasonEnum _05 = new("05"); + + /// + /// TransStatusReasonEnum._06 - 06 + /// + public static readonly TransStatusReasonEnum _06 = new("06"); + + /// + /// TransStatusReasonEnum._07 - 07 + /// + public static readonly TransStatusReasonEnum _07 = new("07"); + + /// + /// TransStatusReasonEnum._08 - 08 + /// + public static readonly TransStatusReasonEnum _08 = new("08"); + + /// + /// TransStatusReasonEnum._09 - 09 + /// + public static readonly TransStatusReasonEnum _09 = new("09"); + + /// + /// TransStatusReasonEnum._10 - 10 + /// + public static readonly TransStatusReasonEnum _10 = new("10"); + + /// + /// TransStatusReasonEnum._11 - 11 + /// + public static readonly TransStatusReasonEnum _11 = new("11"); + + /// + /// TransStatusReasonEnum._12 - 12 + /// + public static readonly TransStatusReasonEnum _12 = new("12"); + + /// + /// TransStatusReasonEnum._13 - 13 + /// + public static readonly TransStatusReasonEnum _13 = new("13"); + + /// + /// TransStatusReasonEnum._14 - 14 + /// + public static readonly TransStatusReasonEnum _14 = new("14"); + + /// + /// TransStatusReasonEnum._15 - 15 + /// + public static readonly TransStatusReasonEnum _15 = new("15"); + + /// + /// TransStatusReasonEnum._16 - 16 + /// + public static readonly TransStatusReasonEnum _16 = new("16"); + + /// + /// TransStatusReasonEnum._17 - 17 + /// + public static readonly TransStatusReasonEnum _17 = new("17"); + + /// + /// TransStatusReasonEnum._18 - 18 + /// + public static readonly TransStatusReasonEnum _18 = new("18"); + + /// + /// TransStatusReasonEnum._19 - 19 + /// + public static readonly TransStatusReasonEnum _19 = new("19"); + + /// + /// TransStatusReasonEnum._20 - 20 + /// + public static readonly TransStatusReasonEnum _20 = new("20"); + + /// + /// TransStatusReasonEnum._21 - 21 + /// + public static readonly TransStatusReasonEnum _21 = new("21"); + + /// + /// TransStatusReasonEnum._22 - 22 + /// + public static readonly TransStatusReasonEnum _22 = new("22"); + + /// + /// TransStatusReasonEnum._23 - 23 + /// + public static readonly TransStatusReasonEnum _23 = new("23"); + + /// + /// TransStatusReasonEnum._24 - 24 + /// + public static readonly TransStatusReasonEnum _24 = new("24"); + + /// + /// TransStatusReasonEnum._25 - 25 + /// + public static readonly TransStatusReasonEnum _25 = new("25"); + + /// + /// TransStatusReasonEnum._26 - 26 + /// + public static readonly TransStatusReasonEnum _26 = new("26"); + + /// + /// TransStatusReasonEnum._80 - 80 + /// + public static readonly TransStatusReasonEnum _80 = new("80"); + + /// + /// TransStatusReasonEnum._81 - 81 + /// + public static readonly TransStatusReasonEnum _81 = new("81"); + + /// + /// TransStatusReasonEnum._82 - 82 + /// + public static readonly TransStatusReasonEnum _82 = new("82"); + + /// + /// TransStatusReasonEnum._83 - 83 + /// + public static readonly TransStatusReasonEnum _83 = new("83"); + + /// + /// TransStatusReasonEnum._84 - 84 + /// + public static readonly TransStatusReasonEnum _84 = new("84"); + + /// + /// TransStatusReasonEnum._85 - 85 + /// + public static readonly TransStatusReasonEnum _85 = new("85"); + + /// + /// TransStatusReasonEnum._86 - 86 + /// + public static readonly TransStatusReasonEnum _86 = new("86"); + + /// + /// TransStatusReasonEnum._87 - 87 + /// + public static readonly TransStatusReasonEnum _87 = new("87"); + + /// + /// TransStatusReasonEnum._88 - 88 + /// + public static readonly TransStatusReasonEnum _88 = new("88"); + + private TransStatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransStatusReasonEnum?(string? value) => value == null ? null : new TransStatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransStatusReasonEnum? option) => option?.Value; + + public static bool operator ==(TransStatusReasonEnum? left, TransStatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransStatusReasonEnum? left, TransStatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransStatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransStatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => TransStatusReasonEnum._01, + "02" => TransStatusReasonEnum._02, + "03" => TransStatusReasonEnum._03, + "04" => TransStatusReasonEnum._04, + "05" => TransStatusReasonEnum._05, + "06" => TransStatusReasonEnum._06, + "07" => TransStatusReasonEnum._07, + "08" => TransStatusReasonEnum._08, + "09" => TransStatusReasonEnum._09, + "10" => TransStatusReasonEnum._10, + "11" => TransStatusReasonEnum._11, + "12" => TransStatusReasonEnum._12, + "13" => TransStatusReasonEnum._13, + "14" => TransStatusReasonEnum._14, + "15" => TransStatusReasonEnum._15, + "16" => TransStatusReasonEnum._16, + "17" => TransStatusReasonEnum._17, + "18" => TransStatusReasonEnum._18, + "19" => TransStatusReasonEnum._19, + "20" => TransStatusReasonEnum._20, + "21" => TransStatusReasonEnum._21, + "22" => TransStatusReasonEnum._22, + "23" => TransStatusReasonEnum._23, + "24" => TransStatusReasonEnum._24, + "25" => TransStatusReasonEnum._25, + "26" => TransStatusReasonEnum._26, + "80" => TransStatusReasonEnum._80, + "81" => TransStatusReasonEnum._81, + "82" => TransStatusReasonEnum._82, + "83" => TransStatusReasonEnum._83, + "84" => TransStatusReasonEnum._84, + "85" => TransStatusReasonEnum._85, + "86" => TransStatusReasonEnum._86, + "87" => TransStatusReasonEnum._87, + "88" => TransStatusReasonEnum._88, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransStatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == TransStatusReasonEnum._01) + return "01"; + + if (value == TransStatusReasonEnum._02) + return "02"; + + if (value == TransStatusReasonEnum._03) + return "03"; + + if (value == TransStatusReasonEnum._04) + return "04"; + + if (value == TransStatusReasonEnum._05) + return "05"; + + if (value == TransStatusReasonEnum._06) + return "06"; + + if (value == TransStatusReasonEnum._07) + return "07"; + + if (value == TransStatusReasonEnum._08) + return "08"; + + if (value == TransStatusReasonEnum._09) + return "09"; + + if (value == TransStatusReasonEnum._10) + return "10"; + + if (value == TransStatusReasonEnum._11) + return "11"; + + if (value == TransStatusReasonEnum._12) + return "12"; + + if (value == TransStatusReasonEnum._13) + return "13"; + + if (value == TransStatusReasonEnum._14) + return "14"; + + if (value == TransStatusReasonEnum._15) + return "15"; + + if (value == TransStatusReasonEnum._16) + return "16"; + + if (value == TransStatusReasonEnum._17) + return "17"; + + if (value == TransStatusReasonEnum._18) + return "18"; + + if (value == TransStatusReasonEnum._19) + return "19"; + + if (value == TransStatusReasonEnum._20) + return "20"; + + if (value == TransStatusReasonEnum._21) + return "21"; + + if (value == TransStatusReasonEnum._22) + return "22"; + + if (value == TransStatusReasonEnum._23) + return "23"; + + if (value == TransStatusReasonEnum._24) + return "24"; + + if (value == TransStatusReasonEnum._25) + return "25"; + + if (value == TransStatusReasonEnum._26) + return "26"; + + if (value == TransStatusReasonEnum._80) + return "80"; + + if (value == TransStatusReasonEnum._81) + return "81"; + + if (value == TransStatusReasonEnum._82) + return "82"; + + if (value == TransStatusReasonEnum._83) + return "83"; + + if (value == TransStatusReasonEnum._84) + return "84"; + + if (value == TransStatusReasonEnum._85) + return "85"; + + if (value == TransStatusReasonEnum._86) + return "86"; + + if (value == TransStatusReasonEnum._87) + return "87"; + + if (value == TransStatusReasonEnum._88) + return "88"; + + return null; + } + + /// + /// JsonConverter for writing TransStatusReasonEnum. + /// + public class TransStatusReasonEnumJsonConverter : JsonConverter + { + public override TransStatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransStatusReasonEnum.FromStringOrDefault(value) ?? new TransStatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransStatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransStatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonPropertyName("transStatusReason")] + public TransStatusReasonEnum? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// Universally unique transaction identifier assigned by the Access Control Server (ACS) to identify a single transaction. + /// + /// Universally unique transaction identifier assigned by the Access Control Server (ACS) to identify a single transaction. + [JsonPropertyName("acsTransId")] + public string AcsTransId { get; set; } + + /// + /// Date and time in UTC of the cardholder authentication. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// Date and time in UTC of the cardholder authentication. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// Universally unique transaction identifier assigned by the DS (card scheme) to identify a single transaction. + /// + /// Universally unique transaction identifier assigned by the DS (card scheme) to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string DsTransID { get; set; } + + /// + /// Indicates if the purchase was in the PSD2 scope. + /// + /// Indicates if the purchase was in the PSD2 scope. + [JsonPropertyName("inPSD2Scope")] + public bool InPSD2Scope { get; set; } + + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("messageVersion")] + public string MessageVersion { get; set; } + + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("threeDSServerTransID")] + public string ThreeDSServerTransID { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("challenge")] + public ChallengeInfo? Challenge { get { return this._ChallengeOption; } set { this._ChallengeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// Risk score calculated from the transaction rules. + /// + /// Risk score calculated from the transaction rules. + [JsonPropertyName("riskScore")] + public int? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationInfo {\n"); + sb.Append(" AcsTransId: ").Append(AcsTransId).Append("\n"); + sb.Append(" ChallengeIndicator: ").Append(ChallengeIndicator).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" DeviceChannel: ").Append(DeviceChannel).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" InPSD2Scope: ").Append(InPSD2Scope).Append("\n"); + sb.Append(" MessageCategory: ").Append(MessageCategory).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" ThreeDSServerTransID: ").Append(ThreeDSServerTransID).Append("\n"); + sb.Append(" TransStatus: ").Append(TransStatus).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Challenge: ").Append(Challenge).Append("\n"); + sb.Append(" ExemptionIndicator: ").Append(ExemptionIndicator).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acsTransId = default; + Option challengeIndicator = default; + Option createdAt = default; + Option deviceChannel = default; + Option dsTransID = default; + Option inPSD2Scope = default; + Option messageCategory = default; + Option messageVersion = default; + Option threeDSServerTransID = default; + Option transStatus = default; + Option type = default; + Option challenge = default; + Option exemptionIndicator = default; + Option riskScore = default; + Option transStatusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsTransId": + acsTransId = new Option(utf8JsonReader.GetString()!); + break; + case "challengeIndicator": + string? challengeIndicatorRawValue = utf8JsonReader.GetString(); + challengeIndicator = new Option(AuthenticationInfo.ChallengeIndicatorEnum.FromStringOrDefault(challengeIndicatorRawValue)); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceChannel": + string? deviceChannelRawValue = utf8JsonReader.GetString(); + deviceChannel = new Option(AuthenticationInfo.DeviceChannelEnum.FromStringOrDefault(deviceChannelRawValue)); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "inPSD2Scope": + inPSD2Scope = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "messageCategory": + string? messageCategoryRawValue = utf8JsonReader.GetString(); + messageCategory = new Option(AuthenticationInfo.MessageCategoryEnum.FromStringOrDefault(messageCategoryRawValue)); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSServerTransID": + threeDSServerTransID = new Option(utf8JsonReader.GetString()!); + break; + case "transStatus": + string? transStatusRawValue = utf8JsonReader.GetString(); + transStatus = new Option(AuthenticationInfo.TransStatusEnum.FromStringOrDefault(transStatusRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AuthenticationInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "challenge": + challenge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "exemptionIndicator": + string? exemptionIndicatorRawValue = utf8JsonReader.GetString(); + exemptionIndicator = new Option(AuthenticationInfo.ExemptionIndicatorEnum.FromStringOrDefault(exemptionIndicatorRawValue)); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "transStatusReason": + string? transStatusReasonRawValue = utf8JsonReader.GetString(); + transStatusReason = new Option(AuthenticationInfo.TransStatusReasonEnum.FromStringOrDefault(transStatusReasonRawValue)); + break; + default: + break; + } + } + } + + if (!acsTransId.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(acsTransId)); + + if (!challengeIndicator.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(challengeIndicator)); + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(createdAt)); + + if (!deviceChannel.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(deviceChannel)); + + if (!dsTransID.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(dsTransID)); + + if (!inPSD2Scope.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(inPSD2Scope)); + + if (!messageCategory.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(messageCategory)); + + if (!messageVersion.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(messageVersion)); + + if (!threeDSServerTransID.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(threeDSServerTransID)); + + if (!transStatus.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(transStatus)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AuthenticationInfo.", nameof(type)); + + return new AuthenticationInfo(acsTransId.Value!, challengeIndicator.Value!.Value!, createdAt.Value!.Value!, deviceChannel.Value!.Value!, dsTransID.Value!, inPSD2Scope.Value!.Value!, messageCategory.Value!.Value!, messageVersion.Value!, threeDSServerTransID.Value!, transStatus.Value!.Value!, type.Value!.Value!, challenge, exemptionIndicator, riskScore, transStatusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationInfo authenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationInfo authenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationInfo.AcsTransId != null) + writer.WriteString("acsTransId", authenticationInfo.AcsTransId); + + if (authenticationInfo.ChallengeIndicator != null) + { + string? challengeIndicatorRawValue = AuthenticationInfo.ChallengeIndicatorEnum.ToJsonValue(authenticationInfo.ChallengeIndicator); + writer.WriteString("challengeIndicator", challengeIndicatorRawValue); + } + + writer.WriteString("createdAt", authenticationInfo.CreatedAt.ToString(CreatedAtFormat)); + + if (authenticationInfo.DeviceChannel != null) + { + string? deviceChannelRawValue = AuthenticationInfo.DeviceChannelEnum.ToJsonValue(authenticationInfo.DeviceChannel); + writer.WriteString("deviceChannel", deviceChannelRawValue); + } + + if (authenticationInfo.DsTransID != null) + writer.WriteString("dsTransID", authenticationInfo.DsTransID); + + writer.WriteBoolean("inPSD2Scope", authenticationInfo.InPSD2Scope); + + if (authenticationInfo.MessageCategory != null) + { + string? messageCategoryRawValue = AuthenticationInfo.MessageCategoryEnum.ToJsonValue(authenticationInfo.MessageCategory); + writer.WriteString("messageCategory", messageCategoryRawValue); + } + + if (authenticationInfo.MessageVersion != null) + writer.WriteString("messageVersion", authenticationInfo.MessageVersion); + + if (authenticationInfo.ThreeDSServerTransID != null) + writer.WriteString("threeDSServerTransID", authenticationInfo.ThreeDSServerTransID); + + if (authenticationInfo.TransStatus != null) + { + string? transStatusRawValue = AuthenticationInfo.TransStatusEnum.ToJsonValue(authenticationInfo.TransStatus); + writer.WriteString("transStatus", transStatusRawValue); + } + + if (authenticationInfo.Type != null) + { + string? typeRawValue = AuthenticationInfo.TypeEnum.ToJsonValue(authenticationInfo.Type); + writer.WriteString("type", typeRawValue); + } + + if (authenticationInfo._ChallengeOption.IsSet) + { + writer.WritePropertyName("challenge"); + JsonSerializer.Serialize(writer, authenticationInfo.Challenge, jsonSerializerOptions); + } + if (authenticationInfo._ExemptionIndicatorOption.IsSet && authenticationInfo.ExemptionIndicator != null) + { + string? exemptionIndicatorRawValue = AuthenticationInfo.ExemptionIndicatorEnum.ToJsonValue(authenticationInfo._ExemptionIndicatorOption.Value!.Value); + writer.WriteString("exemptionIndicator", exemptionIndicatorRawValue); + } + + if (authenticationInfo._RiskScoreOption.IsSet) + writer.WriteNumber("riskScore", authenticationInfo._RiskScoreOption.Value!.Value); + + if (authenticationInfo._TransStatusReasonOption.IsSet && authenticationInfo.TransStatusReason != null) + { + string? transStatusReasonRawValue = AuthenticationInfo.TransStatusReasonEnum.ToJsonValue(authenticationInfo._TransStatusReasonOption.Value!.Value); + writer.WriteString("transStatusReason", transStatusReasonRawValue); + } + } + } +} diff --git a/Adyen/AcsWebhooks/Models/AuthenticationNotificationData.cs b/Adyen/AcsWebhooks/Models/AuthenticationNotificationData.cs new file mode 100644 index 000000000..4043c8650 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/AuthenticationNotificationData.cs @@ -0,0 +1,388 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// AuthenticationNotificationData. + /// + public partial class AuthenticationNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// authentication + /// The unique identifier of the authentication. + /// The unique identifier of the payment instrument that was used for the authentication. + /// purchase + /// Outcome of the authentication. Allowed values: * authenticated * rejected * error + /// The unique identifier of the balance platform. + [JsonConstructor] + public AuthenticationNotificationData(AuthenticationInfo authentication, string id, string paymentInstrumentId, PurchaseInfo purchase, StatusEnum status, Option balancePlatform = default) + { + Authentication = authentication; + Id = id; + PaymentInstrumentId = paymentInstrumentId; + Purchase = purchase; + Status = status; + _BalancePlatformOption = balancePlatform; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationNotificationData() + { + } + + partial void OnCreated(); + + /// + /// Outcome of the authentication. Allowed values: * authenticated * rejected * error + /// + /// Outcome of the authentication. Allowed values: * authenticated * rejected * error + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Authenticated - authenticated + /// + public static readonly StatusEnum Authenticated = new("authenticated"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "authenticated" => StatusEnum.Authenticated, + "rejected" => StatusEnum.Rejected, + "error" => StatusEnum.Error, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Authenticated) + return "authenticated"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.Error) + return "error"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// Outcome of the authentication. Allowed values: * authenticated * rejected * error + /// + /// Outcome of the authentication. Allowed values: * authenticated * rejected * error + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("authentication")] + public AuthenticationInfo Authentication { get; set; } + + /// + /// The unique identifier of the authentication. + /// + /// The unique identifier of the authentication. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The unique identifier of the payment instrument that was used for the authentication. + /// + /// The unique identifier of the payment instrument that was used for the authentication. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// . + /// + [JsonPropertyName("purchase")] + public PurchaseInfo Purchase { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationNotificationData {\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Purchase: ").Append(Purchase).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authentication = default; + Option id = default; + Option paymentInstrumentId = default; + Option purchase = default; + Option status = default; + Option balancePlatform = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authentication": + authentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "purchase": + purchase = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AuthenticationNotificationData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!authentication.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationData.", nameof(authentication)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationData.", nameof(id)); + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationData.", nameof(paymentInstrumentId)); + + if (!purchase.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationData.", nameof(purchase)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationData.", nameof(status)); + + return new AuthenticationNotificationData(authentication.Value!, id.Value!, paymentInstrumentId.Value!, purchase.Value!, status.Value!.Value!, balancePlatform); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationNotificationData authenticationNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationNotificationData authenticationNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("authentication"); + JsonSerializer.Serialize(writer, authenticationNotificationData.Authentication, jsonSerializerOptions); + if (authenticationNotificationData.Id != null) + writer.WriteString("id", authenticationNotificationData.Id); + + if (authenticationNotificationData.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", authenticationNotificationData.PaymentInstrumentId); + + writer.WritePropertyName("purchase"); + JsonSerializer.Serialize(writer, authenticationNotificationData.Purchase, jsonSerializerOptions); + if (authenticationNotificationData.Status != null) + { + string? statusRawValue = AuthenticationNotificationData.StatusEnum.ToJsonValue(authenticationNotificationData.Status); + writer.WriteString("status", statusRawValue); + } + + if (authenticationNotificationData._BalancePlatformOption.IsSet) + if (authenticationNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", authenticationNotificationData.BalancePlatform); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/AuthenticationNotificationRequest.cs b/Adyen/AcsWebhooks/Models/AuthenticationNotificationRequest.cs new file mode 100644 index 000000000..8010522de --- /dev/null +++ b/Adyen/AcsWebhooks/Models/AuthenticationNotificationRequest.cs @@ -0,0 +1,336 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// AuthenticationNotificationRequest. + /// + public partial class AuthenticationNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + /// When the event was queued. + [JsonConstructor] + public AuthenticationNotificationRequest(AuthenticationNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformAuthenticationCreated - balancePlatform.authentication.created + /// + public static readonly TypeEnum BalancePlatformAuthenticationCreated = new("balancePlatform.authentication.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.authentication.created" => TypeEnum.BalancePlatformAuthenticationCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformAuthenticationCreated) + return "balancePlatform.authentication.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public AuthenticationNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AuthenticationNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AuthenticationNotificationRequest.", nameof(type)); + + return new AuthenticationNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationNotificationRequest authenticationNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationNotificationRequest authenticationNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, authenticationNotificationRequest.Data, jsonSerializerOptions); + if (authenticationNotificationRequest.Environment != null) + writer.WriteString("environment", authenticationNotificationRequest.Environment); + + if (authenticationNotificationRequest.Type != null) + { + string? typeRawValue = AuthenticationNotificationRequest.TypeEnum.ToJsonValue(authenticationNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (authenticationNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", authenticationNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/AcsWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..41d8587fe --- /dev/null +++ b/Adyen/AcsWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/ChallengeInfo.cs b/Adyen/AcsWebhooks/Models/ChallengeInfo.cs new file mode 100644 index 000000000..777c267b8 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/ChallengeInfo.cs @@ -0,0 +1,578 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// ChallengeInfo. + /// + public partial class ChallengeInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The flow used in the challenge. Possible values: * **PWD_OTP_PHONE_FL**: one-time password (OTP) flow via SMS * **PWD_OTP_EMAIL_FL**: one-time password (OTP) flow via email * **OOB_TRIGGER_FL**: out-of-band (OOB) flow + /// The last time of interaction with the challenge. + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. Possible values: * **00**: Data element is absent or value has been sent back with the key `challengeCancel`. * **01**: Cardholder selected **Cancel**. * **02**: 3DS Requestor cancelled Authentication. * **03**: Transaction abandoned. * **04**: Transaction timed out at ACS — other timeouts. * **05**: Transaction timed out at ACS — first CReq not received by ACS. * **06**: Transaction error. * **07**: Unknown. * **08**: Transaction time out at SDK. + /// The last four digits of the phone number used in the challenge. + /// The number of times the one-time password (OTP) was resent during the challenge. + /// The number of retries used in the challenge. + [JsonConstructor] + public ChallengeInfo(FlowEnum flow, DateTimeOffset lastInteraction, Option challengeCancel = default, Option phoneNumber = default, Option resends = default, Option retries = default) + { + Flow = flow; + LastInteraction = lastInteraction; + _ChallengeCancelOption = challengeCancel; + _PhoneNumberOption = phoneNumber; + _ResendsOption = resends; + _RetriesOption = retries; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ChallengeInfo() + { + } + + partial void OnCreated(); + + /// + /// The flow used in the challenge. Possible values: * **PWD_OTP_PHONE_FL**: one-time password (OTP) flow via SMS * **PWD_OTP_EMAIL_FL**: one-time password (OTP) flow via email * **OOB_TRIGGER_FL**: out-of-band (OOB) flow + /// + /// The flow used in the challenge. Possible values: * **PWD_OTP_PHONE_FL**: one-time password (OTP) flow via SMS * **PWD_OTP_EMAIL_FL**: one-time password (OTP) flow via email * **OOB_TRIGGER_FL**: out-of-band (OOB) flow + [JsonConverter(typeof(FlowEnumJsonConverter))] + public class FlowEnum : IEnum + { + /// + /// Returns the value of the FlowEnum. + /// + public string? Value { get; set; } + + /// + /// FlowEnum.PWDOTPPHONEFL - PWD_OTP_PHONE_FL + /// + public static readonly FlowEnum PWDOTPPHONEFL = new("PWD_OTP_PHONE_FL"); + + /// + /// FlowEnum.PWDOTPEMAILFL - PWD_OTP_EMAIL_FL + /// + public static readonly FlowEnum PWDOTPEMAILFL = new("PWD_OTP_EMAIL_FL"); + + /// + /// FlowEnum.OOBTRIGGERFL - OOB_TRIGGER_FL + /// + public static readonly FlowEnum OOBTRIGGERFL = new("OOB_TRIGGER_FL"); + + private FlowEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FlowEnum?(string? value) => value == null ? null : new FlowEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FlowEnum? option) => option?.Value; + + public static bool operator ==(FlowEnum? left, FlowEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FlowEnum? left, FlowEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FlowEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FlowEnum? FromStringOrDefault(string value) + { + return value switch { + "PWD_OTP_PHONE_FL" => FlowEnum.PWDOTPPHONEFL, + "PWD_OTP_EMAIL_FL" => FlowEnum.PWDOTPEMAILFL, + "OOB_TRIGGER_FL" => FlowEnum.OOBTRIGGERFL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FlowEnum? value) + { + if (value == null) + return null; + + if (value == FlowEnum.PWDOTPPHONEFL) + return "PWD_OTP_PHONE_FL"; + + if (value == FlowEnum.PWDOTPEMAILFL) + return "PWD_OTP_EMAIL_FL"; + + if (value == FlowEnum.OOBTRIGGERFL) + return "OOB_TRIGGER_FL"; + + return null; + } + + /// + /// JsonConverter for writing FlowEnum. + /// + public class FlowEnumJsonConverter : JsonConverter + { + public override FlowEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FlowEnum.FromStringOrDefault(value) ?? new FlowEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FlowEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FlowEnum.ToJsonValue(value)); + } + } + } + + /// + /// The flow used in the challenge. Possible values: * **PWD_OTP_PHONE_FL**: one-time password (OTP) flow via SMS * **PWD_OTP_EMAIL_FL**: one-time password (OTP) flow via email * **OOB_TRIGGER_FL**: out-of-band (OOB) flow + /// + /// The flow used in the challenge. Possible values: * **PWD_OTP_PHONE_FL**: one-time password (OTP) flow via SMS * **PWD_OTP_EMAIL_FL**: one-time password (OTP) flow via email * **OOB_TRIGGER_FL**: out-of-band (OOB) flow + [JsonPropertyName("flow")] + public FlowEnum Flow { get; set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. Possible values: * **00**: Data element is absent or value has been sent back with the key `challengeCancel`. * **01**: Cardholder selected **Cancel**. * **02**: 3DS Requestor cancelled Authentication. * **03**: Transaction abandoned. * **04**: Transaction timed out at ACS — other timeouts. * **05**: Transaction timed out at ACS — first CReq not received by ACS. * **06**: Transaction error. * **07**: Unknown. * **08**: Transaction time out at SDK. + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. Possible values: * **00**: Data element is absent or value has been sent back with the key `challengeCancel`. * **01**: Cardholder selected **Cancel**. * **02**: 3DS Requestor cancelled Authentication. * **03**: Transaction abandoned. * **04**: Transaction timed out at ACS — other timeouts. * **05**: Transaction timed out at ACS — first CReq not received by ACS. * **06**: Transaction error. * **07**: Unknown. * **08**: Transaction time out at SDK. + [JsonConverter(typeof(ChallengeCancelEnumJsonConverter))] + public class ChallengeCancelEnum : IEnum + { + /// + /// Returns the value of the ChallengeCancelEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeCancelEnum._00 - 00 + /// + public static readonly ChallengeCancelEnum _00 = new("00"); + + /// + /// ChallengeCancelEnum._01 - 01 + /// + public static readonly ChallengeCancelEnum _01 = new("01"); + + /// + /// ChallengeCancelEnum._02 - 02 + /// + public static readonly ChallengeCancelEnum _02 = new("02"); + + /// + /// ChallengeCancelEnum._03 - 03 + /// + public static readonly ChallengeCancelEnum _03 = new("03"); + + /// + /// ChallengeCancelEnum._04 - 04 + /// + public static readonly ChallengeCancelEnum _04 = new("04"); + + /// + /// ChallengeCancelEnum._05 - 05 + /// + public static readonly ChallengeCancelEnum _05 = new("05"); + + /// + /// ChallengeCancelEnum._06 - 06 + /// + public static readonly ChallengeCancelEnum _06 = new("06"); + + /// + /// ChallengeCancelEnum._07 - 07 + /// + public static readonly ChallengeCancelEnum _07 = new("07"); + + /// + /// ChallengeCancelEnum._08 - 08 + /// + public static readonly ChallengeCancelEnum _08 = new("08"); + + private ChallengeCancelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeCancelEnum?(string? value) => value == null ? null : new ChallengeCancelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeCancelEnum? option) => option?.Value; + + public static bool operator ==(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeCancelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeCancelEnum? FromStringOrDefault(string value) + { + return value switch { + "00" => ChallengeCancelEnum._00, + "01" => ChallengeCancelEnum._01, + "02" => ChallengeCancelEnum._02, + "03" => ChallengeCancelEnum._03, + "04" => ChallengeCancelEnum._04, + "05" => ChallengeCancelEnum._05, + "06" => ChallengeCancelEnum._06, + "07" => ChallengeCancelEnum._07, + "08" => ChallengeCancelEnum._08, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeCancelEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeCancelEnum._00) + return "00"; + + if (value == ChallengeCancelEnum._01) + return "01"; + + if (value == ChallengeCancelEnum._02) + return "02"; + + if (value == ChallengeCancelEnum._03) + return "03"; + + if (value == ChallengeCancelEnum._04) + return "04"; + + if (value == ChallengeCancelEnum._05) + return "05"; + + if (value == ChallengeCancelEnum._06) + return "06"; + + if (value == ChallengeCancelEnum._07) + return "07"; + + if (value == ChallengeCancelEnum._08) + return "08"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeCancelEnum. + /// + public class ChallengeCancelEnumJsonConverter : JsonConverter + { + public override ChallengeCancelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeCancelEnum.FromStringOrDefault(value) ?? new ChallengeCancelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeCancelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeCancelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeCancelOption { get; private set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. Possible values: * **00**: Data element is absent or value has been sent back with the key `challengeCancel`. * **01**: Cardholder selected **Cancel**. * **02**: 3DS Requestor cancelled Authentication. * **03**: Transaction abandoned. * **04**: Transaction timed out at ACS — other timeouts. * **05**: Transaction timed out at ACS — first CReq not received by ACS. * **06**: Transaction error. * **07**: Unknown. * **08**: Transaction time out at SDK. + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. Possible values: * **00**: Data element is absent or value has been sent back with the key `challengeCancel`. * **01**: Cardholder selected **Cancel**. * **02**: 3DS Requestor cancelled Authentication. * **03**: Transaction abandoned. * **04**: Transaction timed out at ACS — other timeouts. * **05**: Transaction timed out at ACS — first CReq not received by ACS. * **06**: Transaction error. * **07**: Unknown. * **08**: Transaction time out at SDK. + [JsonPropertyName("challengeCancel")] + public ChallengeCancelEnum? ChallengeCancel { get { return this._ChallengeCancelOption; } set { this._ChallengeCancelOption = new(value); } } + + /// + /// The last time of interaction with the challenge. + /// + /// The last time of interaction with the challenge. + [JsonPropertyName("lastInteraction")] + public DateTimeOffset LastInteraction { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// The last four digits of the phone number used in the challenge. + /// + /// The last four digits of the phone number used in the challenge. + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResendsOption { get; private set; } + + /// + /// The number of times the one-time password (OTP) was resent during the challenge. + /// + /// The number of times the one-time password (OTP) was resent during the challenge. + [JsonPropertyName("resends")] + public int? Resends { get { return this._ResendsOption; } set { this._ResendsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetriesOption { get; private set; } + + /// + /// The number of retries used in the challenge. + /// + /// The number of retries used in the challenge. + [JsonPropertyName("retries")] + public int? Retries { get { return this._RetriesOption; } set { this._RetriesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ChallengeInfo {\n"); + sb.Append(" Flow: ").Append(Flow).Append("\n"); + sb.Append(" LastInteraction: ").Append(LastInteraction).Append("\n"); + sb.Append(" ChallengeCancel: ").Append(ChallengeCancel).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" Resends: ").Append(Resends).Append("\n"); + sb.Append(" Retries: ").Append(Retries).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ChallengeInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastInteraction. + /// + public static string LastInteractionFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ChallengeInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option flow = default; + Option lastInteraction = default; + Option challengeCancel = default; + Option phoneNumber = default; + Option resends = default; + Option retries = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "flow": + string? flowRawValue = utf8JsonReader.GetString(); + flow = new Option(ChallengeInfo.FlowEnum.FromStringOrDefault(flowRawValue)); + break; + case "lastInteraction": + lastInteraction = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "challengeCancel": + string? challengeCancelRawValue = utf8JsonReader.GetString(); + challengeCancel = new Option(ChallengeInfo.ChallengeCancelEnum.FromStringOrDefault(challengeCancelRawValue)); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "resends": + resends = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "retries": + retries = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!flow.IsSet) + throw new ArgumentException("Property is required for class ChallengeInfo.", nameof(flow)); + + if (!lastInteraction.IsSet) + throw new ArgumentException("Property is required for class ChallengeInfo.", nameof(lastInteraction)); + + return new ChallengeInfo(flow.Value!.Value!, lastInteraction.Value!.Value!, challengeCancel, phoneNumber, resends, retries); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ChallengeInfo challengeInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, challengeInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ChallengeInfo challengeInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (challengeInfo.Flow != null) + { + string? flowRawValue = ChallengeInfo.FlowEnum.ToJsonValue(challengeInfo.Flow); + writer.WriteString("flow", flowRawValue); + } + + writer.WriteString("lastInteraction", challengeInfo.LastInteraction.ToString(LastInteractionFormat)); + + if (challengeInfo._ChallengeCancelOption.IsSet && challengeInfo.ChallengeCancel != null) + { + string? challengeCancelRawValue = ChallengeInfo.ChallengeCancelEnum.ToJsonValue(challengeInfo._ChallengeCancelOption.Value!.Value); + writer.WriteString("challengeCancel", challengeCancelRawValue); + } + + if (challengeInfo._PhoneNumberOption.IsSet) + if (challengeInfo.PhoneNumber != null) + writer.WriteString("phoneNumber", challengeInfo.PhoneNumber); + + if (challengeInfo._ResendsOption.IsSet) + writer.WriteNumber("resends", challengeInfo._ResendsOption.Value!.Value); + + if (challengeInfo._RetriesOption.IsSet) + writer.WriteNumber("retries", challengeInfo._RetriesOption.Value!.Value); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/Purchase.cs b/Adyen/AcsWebhooks/Models/Purchase.cs new file mode 100644 index 000000000..b090a7dc7 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/Purchase.cs @@ -0,0 +1,214 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// Purchase. + /// + public partial class Purchase : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The time of the purchase. + /// The name of the merchant. + /// originalAmount + [JsonConstructor] + public Purchase(DateTimeOffset date, string merchantName, Amount originalAmount) + { + Date = date; + MerchantName = merchantName; + OriginalAmount = originalAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Purchase() + { + } + + partial void OnCreated(); + + /// + /// The time of the purchase. + /// + /// The time of the purchase. + [JsonPropertyName("date")] + public DateTimeOffset Date { get; set; } + + /// + /// The name of the merchant. + /// + /// The name of the merchant. + [JsonPropertyName("merchantName")] + public string MerchantName { get; set; } + + /// + /// . + /// + [JsonPropertyName("originalAmount")] + public Amount OriginalAmount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Purchase {\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" OriginalAmount: ").Append(OriginalAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PurchaseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Date. + /// + public static string DateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Purchase Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option date = default; + Option merchantName = default; + Option originalAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "date": + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "originalAmount": + originalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!date.IsSet) + throw new ArgumentException("Property is required for class Purchase.", nameof(date)); + + if (!merchantName.IsSet) + throw new ArgumentException("Property is required for class Purchase.", nameof(merchantName)); + + if (!originalAmount.IsSet) + throw new ArgumentException("Property is required for class Purchase.", nameof(originalAmount)); + + return new Purchase(date.Value!.Value!, merchantName.Value!, originalAmount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Purchase purchase, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, purchase, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Purchase purchase, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("date", purchase.Date.ToString(DateFormat)); + + if (purchase.MerchantName != null) + writer.WriteString("merchantName", purchase.MerchantName); + + writer.WritePropertyName("originalAmount"); + JsonSerializer.Serialize(writer, purchase.OriginalAmount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/PurchaseInfo.cs b/Adyen/AcsWebhooks/Models/PurchaseInfo.cs new file mode 100644 index 000000000..5cab74017 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/PurchaseInfo.cs @@ -0,0 +1,210 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// PurchaseInfo. + /// + public partial class PurchaseInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date of the purchase. + /// The name of the business that the cardholder purchased from. + /// originalAmount + [JsonConstructor] + public PurchaseInfo(string date, string merchantName, Amount originalAmount) + { + Date = date; + MerchantName = merchantName; + OriginalAmount = originalAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PurchaseInfo() + { + } + + partial void OnCreated(); + + /// + /// The date of the purchase. + /// + /// The date of the purchase. + [JsonPropertyName("date")] + public string Date { get; set; } + + /// + /// The name of the business that the cardholder purchased from. + /// + /// The name of the business that the cardholder purchased from. + [JsonPropertyName("merchantName")] + public string MerchantName { get; set; } + + /// + /// . + /// + [JsonPropertyName("originalAmount")] + public Amount OriginalAmount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PurchaseInfo {\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" OriginalAmount: ").Append(OriginalAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PurchaseInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PurchaseInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option date = default; + Option merchantName = default; + Option originalAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "date": + date = new Option(utf8JsonReader.GetString()!); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "originalAmount": + originalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!date.IsSet) + throw new ArgumentException("Property is required for class PurchaseInfo.", nameof(date)); + + if (!merchantName.IsSet) + throw new ArgumentException("Property is required for class PurchaseInfo.", nameof(merchantName)); + + if (!originalAmount.IsSet) + throw new ArgumentException("Property is required for class PurchaseInfo.", nameof(originalAmount)); + + return new PurchaseInfo(date.Value!, merchantName.Value!, originalAmount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PurchaseInfo purchaseInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, purchaseInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PurchaseInfo purchaseInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (purchaseInfo.Date != null) + writer.WriteString("date", purchaseInfo.Date); + + if (purchaseInfo.MerchantName != null) + writer.WriteString("merchantName", purchaseInfo.MerchantName); + + writer.WritePropertyName("originalAmount"); + JsonSerializer.Serialize(writer, purchaseInfo.OriginalAmount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/RelayedAuthenticationRequest.cs b/Adyen/AcsWebhooks/Models/RelayedAuthenticationRequest.cs new file mode 100644 index 000000000..a3b442f73 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/RelayedAuthenticationRequest.cs @@ -0,0 +1,401 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// RelayedAuthenticationRequest. + /// + public partial class RelayedAuthenticationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The unique identifier of the challenge. + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_) used for the purchase. + /// purchase + /// Type of notification. + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching. + /// When the event was queued. + [JsonConstructor] + public RelayedAuthenticationRequest(string environment, string id, string paymentInstrumentId, Purchase purchase, TypeEnum type, Option threeDSRequestorAppURL = default, Option timestamp = default) + { + Environment = environment; + Id = id; + PaymentInstrumentId = paymentInstrumentId; + Purchase = purchase; + Type = type; + _ThreeDSRequestorAppURLOption = threeDSRequestorAppURL; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RelayedAuthenticationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformAuthenticationRelayed - balancePlatform.authentication.relayed + /// + public static readonly TypeEnum BalancePlatformAuthenticationRelayed = new("balancePlatform.authentication.relayed"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.authentication.relayed" => TypeEnum.BalancePlatformAuthenticationRelayed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformAuthenticationRelayed) + return "balancePlatform.authentication.relayed"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// The unique identifier of the challenge. + /// + /// The unique identifier of the challenge. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_) used for the purchase. + /// + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_) used for the purchase. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// . + /// + [JsonPropertyName("purchase")] + public Purchase Purchase { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAppURLOption { get; private set; } + + /// + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching. + /// + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching. + [JsonPropertyName("threeDSRequestorAppURL")] + public string? ThreeDSRequestorAppURL { get { return this._ThreeDSRequestorAppURLOption; } set { this._ThreeDSRequestorAppURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RelayedAuthenticationRequest {\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Purchase: ").Append(Purchase).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ThreeDSRequestorAppURL: ").Append(ThreeDSRequestorAppURL).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RelayedAuthenticationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RelayedAuthenticationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option environment = default; + Option id = default; + Option paymentInstrumentId = default; + Option purchase = default; + Option type = default; + Option threeDSRequestorAppURL = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "purchase": + purchase = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(RelayedAuthenticationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "threeDSRequestorAppURL": + threeDSRequestorAppURL = new Option(utf8JsonReader.GetString()!); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationRequest.", nameof(environment)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationRequest.", nameof(id)); + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationRequest.", nameof(paymentInstrumentId)); + + if (!purchase.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationRequest.", nameof(purchase)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationRequest.", nameof(type)); + + return new RelayedAuthenticationRequest(environment.Value!, id.Value!, paymentInstrumentId.Value!, purchase.Value!, type.Value!.Value!, threeDSRequestorAppURL, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RelayedAuthenticationRequest relayedAuthenticationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, relayedAuthenticationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RelayedAuthenticationRequest relayedAuthenticationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (relayedAuthenticationRequest.Environment != null) + writer.WriteString("environment", relayedAuthenticationRequest.Environment); + + if (relayedAuthenticationRequest.Id != null) + writer.WriteString("id", relayedAuthenticationRequest.Id); + + if (relayedAuthenticationRequest.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", relayedAuthenticationRequest.PaymentInstrumentId); + + writer.WritePropertyName("purchase"); + JsonSerializer.Serialize(writer, relayedAuthenticationRequest.Purchase, jsonSerializerOptions); + if (relayedAuthenticationRequest.Type != null) + { + string? typeRawValue = RelayedAuthenticationRequest.TypeEnum.ToJsonValue(relayedAuthenticationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (relayedAuthenticationRequest._ThreeDSRequestorAppURLOption.IsSet) + if (relayedAuthenticationRequest.ThreeDSRequestorAppURL != null) + writer.WriteString("threeDSRequestorAppURL", relayedAuthenticationRequest.ThreeDSRequestorAppURL); + + if (relayedAuthenticationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", relayedAuthenticationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/RelayedAuthenticationResponse.cs b/Adyen/AcsWebhooks/Models/RelayedAuthenticationResponse.cs new file mode 100644 index 000000000..5c4f69d4a --- /dev/null +++ b/Adyen/AcsWebhooks/Models/RelayedAuthenticationResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// RelayedAuthenticationResponse. + /// + public partial class RelayedAuthenticationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// authenticationDecision + [JsonConstructor] + public RelayedAuthenticationResponse(AuthenticationDecision authenticationDecision) + { + AuthenticationDecision = authenticationDecision; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RelayedAuthenticationResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("authenticationDecision")] + public AuthenticationDecision AuthenticationDecision { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RelayedAuthenticationResponse {\n"); + sb.Append(" AuthenticationDecision: ").Append(AuthenticationDecision).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RelayedAuthenticationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RelayedAuthenticationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationDecision = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationDecision": + authenticationDecision = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!authenticationDecision.IsSet) + throw new ArgumentException("Property is required for class RelayedAuthenticationResponse.", nameof(authenticationDecision)); + + return new RelayedAuthenticationResponse(authenticationDecision.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RelayedAuthenticationResponse relayedAuthenticationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, relayedAuthenticationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RelayedAuthenticationResponse relayedAuthenticationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("authenticationDecision"); + JsonSerializer.Serialize(writer, relayedAuthenticationResponse.AuthenticationDecision, jsonSerializerOptions); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/Resource.cs b/Adyen/AcsWebhooks/Models/Resource.cs new file mode 100644 index 000000000..56133cc5c --- /dev/null +++ b/Adyen/AcsWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/AcsWebhooks/Models/ServiceError.cs b/Adyen/AcsWebhooks/Models/ServiceError.cs new file mode 100644 index 000000000..28f7b58a2 --- /dev/null +++ b/Adyen/AcsWebhooks/Models/ServiceError.cs @@ -0,0 +1,276 @@ +// +/* + * Authentication webhooks + * + * Adyen sends webhooks to inform your system about events related to cardholder authentication. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.AcsWebhooks.Client; + +namespace Adyen.AcsWebhooks.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Adyen.csproj b/Adyen/Adyen.csproj index fa180e07d..f7f7a4088 100644 --- a/Adyen/Adyen.csproj +++ b/Adyen/Adyen.csproj @@ -1,7 +1,7 @@ - + - net8.0;net6.0;net462;netstandard2.0 + net8.0 12 enable disable @@ -36,9 +36,12 @@ - + + + - + + @@ -54,4 +57,7 @@ + + + diff --git a/Adyen/BalanceControl/Client/ApiKeyToken.cs b/Adyen/BalanceControl/Client/ApiKeyToken.cs new file mode 100644 index 000000000..78bf7c6dd --- /dev/null +++ b/Adyen/BalanceControl/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.BalanceControl.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/BalanceControl/Client/ClientUtils.cs b/Adyen/BalanceControl/Client/ClientUtils.cs new file mode 100644 index 000000000..9df735b07 --- /dev/null +++ b/Adyen/BalanceControl/Client/ClientUtils.cs @@ -0,0 +1,319 @@ +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.BalanceControl.Models; +using Models = Adyen.BalanceControl.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.BalanceControl.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.BalanceTransferRequest.TypeEnum balanceTransferRequestTypeEnum) + return Models.BalanceTransferRequest.TypeEnum.ToJsonValue(balanceTransferRequestTypeEnum); + if (obj is Models.BalanceTransferResponse.StatusEnum balanceTransferResponseStatusEnum) + return Models.BalanceTransferResponse.StatusEnum.ToJsonValue(balanceTransferResponseStatusEnum); + if (obj is Models.BalanceTransferResponse.TypeEnum balanceTransferResponseTypeEnum) + return Models.BalanceTransferResponse.TypeEnum.ToJsonValue(balanceTransferResponseTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/BalanceControl/Client/HostConfiguration.cs b/Adyen/BalanceControl/Client/HostConfiguration.cs new file mode 100644 index 000000000..bdf1a628c --- /dev/null +++ b/Adyen/BalanceControl/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.BalanceControl.Services; +using Adyen.BalanceControl.Client; +using Adyen.BalanceControl.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.BalanceControl.Client +{ + /// + /// Provides hosting configuration for BalanceControl + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/BalanceControl/v1"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BalanceTransferRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalanceTransferResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddBalanceControlHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/BalanceControl/Client/JsonSerializerOptionsProvider.cs b/Adyen/BalanceControl/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..8544ee57f --- /dev/null +++ b/Adyen/BalanceControl/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.BalanceControl.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/BalanceControl/Extensions/HostBuilderExtensions.cs b/Adyen/BalanceControl/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..17744038d --- /dev/null +++ b/Adyen/BalanceControl/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.BalanceControl; +using Adyen.BalanceControl.Client; + +namespace Adyen.BalanceControl.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the BalanceControl API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureBalanceControl(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddBalanceControlHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/BalanceControl/Extensions/ServiceCollectionExtensions.cs b/Adyen/BalanceControl/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..507eea98b --- /dev/null +++ b/Adyen/BalanceControl/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.BalanceControl.Client; + +namespace Adyen.BalanceControl.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen BalanceControl API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddBalanceControlServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddBalanceControlHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/BalanceControl/Models/Amount.cs b/Adyen/BalanceControl/Models/Amount.cs new file mode 100644 index 000000000..579b939f2 --- /dev/null +++ b/Adyen/BalanceControl/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceControl.Client; + +namespace Adyen.BalanceControl.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/BalanceControl/Models/BalanceTransferRequest.cs b/Adyen/BalanceControl/Models/BalanceTransferRequest.cs new file mode 100644 index 000000000..386c1cbd6 --- /dev/null +++ b/Adyen/BalanceControl/Models/BalanceTransferRequest.cs @@ -0,0 +1,434 @@ +// +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceControl.Client; + +namespace Adyen.BalanceControl.Models +{ + /// + /// BalanceTransferRequest. + /// + public partial class BalanceTransferRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The unique identifier of the source merchant account from which funds are deducted. + /// The unique identifier of the destination merchant account from which funds are transferred. + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + [JsonConstructor] + public BalanceTransferRequest(Amount amount, string fromMerchant, string toMerchant, TypeEnum type, Option description = default, Option reference = default) + { + Amount = amount; + FromMerchant = fromMerchant; + ToMerchant = toMerchant; + Type = type; + _DescriptionOption = description; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceTransferRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Tax - tax + /// + public static readonly TypeEnum Tax = new("tax"); + + /// + /// TypeEnum.Fee - fee + /// + public static readonly TypeEnum Fee = new("fee"); + + /// + /// TypeEnum.TerminalSale - terminalSale + /// + public static readonly TypeEnum TerminalSale = new("terminalSale"); + + /// + /// TypeEnum.Credit - credit + /// + public static readonly TypeEnum Credit = new("credit"); + + /// + /// TypeEnum.Debit - debit + /// + public static readonly TypeEnum Debit = new("debit"); + + /// + /// TypeEnum.Adjustment - adjustment + /// + public static readonly TypeEnum Adjustment = new("adjustment"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "tax" => TypeEnum.Tax, + "fee" => TypeEnum.Fee, + "terminalSale" => TypeEnum.TerminalSale, + "credit" => TypeEnum.Credit, + "debit" => TypeEnum.Debit, + "adjustment" => TypeEnum.Adjustment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Tax) + return "tax"; + + if (value == TypeEnum.Fee) + return "fee"; + + if (value == TypeEnum.TerminalSale) + return "terminalSale"; + + if (value == TypeEnum.Credit) + return "credit"; + + if (value == TypeEnum.Debit) + return "debit"; + + if (value == TypeEnum.Adjustment) + return "adjustment"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The unique identifier of the source merchant account from which funds are deducted. + /// + /// The unique identifier of the source merchant account from which funds are deducted. + [JsonPropertyName("fromMerchant")] + public string FromMerchant { get; set; } + + /// + /// The unique identifier of the destination merchant account from which funds are transferred. + /// + /// The unique identifier of the destination merchant account from which funds are transferred. + [JsonPropertyName("toMerchant")] + public string ToMerchant { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + /// + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + /// + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceTransferRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" FromMerchant: ").Append(FromMerchant).Append("\n"); + sb.Append(" ToMerchant: ").Append(ToMerchant).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 140) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 140.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceTransferRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceTransferRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option fromMerchant = default; + Option toMerchant = default; + Option type = default; + Option description = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fromMerchant": + fromMerchant = new Option(utf8JsonReader.GetString()!); + break; + case "toMerchant": + toMerchant = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceTransferRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferRequest.", nameof(amount)); + + if (!fromMerchant.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferRequest.", nameof(fromMerchant)); + + if (!toMerchant.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferRequest.", nameof(toMerchant)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferRequest.", nameof(type)); + + return new BalanceTransferRequest(amount.Value!, fromMerchant.Value!, toMerchant.Value!, type.Value!.Value!, description, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceTransferRequest balanceTransferRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceTransferRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceTransferRequest balanceTransferRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, balanceTransferRequest.Amount, jsonSerializerOptions); + if (balanceTransferRequest.FromMerchant != null) + writer.WriteString("fromMerchant", balanceTransferRequest.FromMerchant); + + if (balanceTransferRequest.ToMerchant != null) + writer.WriteString("toMerchant", balanceTransferRequest.ToMerchant); + + if (balanceTransferRequest.Type != null) + { + string? typeRawValue = BalanceTransferRequest.TypeEnum.ToJsonValue(balanceTransferRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (balanceTransferRequest._DescriptionOption.IsSet) + if (balanceTransferRequest.Description != null) + writer.WriteString("description", balanceTransferRequest.Description); + + if (balanceTransferRequest._ReferenceOption.IsSet) + if (balanceTransferRequest.Reference != null) + writer.WriteString("reference", balanceTransferRequest.Reference); + } + } +} diff --git a/Adyen/BalanceControl/Models/BalanceTransferResponse.cs b/Adyen/BalanceControl/Models/BalanceTransferResponse.cs new file mode 100644 index 000000000..5625003f6 --- /dev/null +++ b/Adyen/BalanceControl/Models/BalanceTransferResponse.cs @@ -0,0 +1,623 @@ +// +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceControl.Client; + +namespace Adyen.BalanceControl.Models +{ + /// + /// BalanceTransferResponse. + /// + public partial class BalanceTransferResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The date when the balance transfer was requested. + /// The unique identifier of the source merchant account from which funds are deducted. + /// Adyen's 16-character string reference associated with the balance transfer. + /// The status of the balance transfer. Possible values: **transferred**, **failed**, **error**, and **notEnoughBalance**. + /// The unique identifier of the destination merchant account from which funds are transferred. + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + [JsonConstructor] + public BalanceTransferResponse(Amount amount, DateTimeOffset createdAt, string fromMerchant, string pspReference, StatusEnum status, string toMerchant, TypeEnum type, Option description = default, Option reference = default) + { + Amount = amount; + CreatedAt = createdAt; + FromMerchant = fromMerchant; + PspReference = pspReference; + Status = status; + ToMerchant = toMerchant; + Type = type; + _DescriptionOption = description; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceTransferResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of the balance transfer. Possible values: **transferred**, **failed**, **error**, and **notEnoughBalance**. + /// + /// The status of the balance transfer. Possible values: **transferred**, **failed**, **error**, and **notEnoughBalance**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly StatusEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// StatusEnum.Transferred - transferred + /// + public static readonly StatusEnum Transferred = new("transferred"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "error" => StatusEnum.Error, + "failed" => StatusEnum.Failed, + "notEnoughBalance" => StatusEnum.NotEnoughBalance, + "transferred" => StatusEnum.Transferred, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == StatusEnum.Transferred) + return "transferred"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the balance transfer. Possible values: **transferred**, **failed**, **error**, and **notEnoughBalance**. + /// + /// The status of the balance transfer. Possible values: **transferred**, **failed**, **error**, and **notEnoughBalance**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Tax - tax + /// + public static readonly TypeEnum Tax = new("tax"); + + /// + /// TypeEnum.Fee - fee + /// + public static readonly TypeEnum Fee = new("fee"); + + /// + /// TypeEnum.TerminalSale - terminalSale + /// + public static readonly TypeEnum TerminalSale = new("terminalSale"); + + /// + /// TypeEnum.Credit - credit + /// + public static readonly TypeEnum Credit = new("credit"); + + /// + /// TypeEnum.Debit - debit + /// + public static readonly TypeEnum Debit = new("debit"); + + /// + /// TypeEnum.Adjustment - adjustment + /// + public static readonly TypeEnum Adjustment = new("adjustment"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "tax" => TypeEnum.Tax, + "fee" => TypeEnum.Fee, + "terminalSale" => TypeEnum.TerminalSale, + "credit" => TypeEnum.Credit, + "debit" => TypeEnum.Debit, + "adjustment" => TypeEnum.Adjustment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Tax) + return "tax"; + + if (value == TypeEnum.Fee) + return "fee"; + + if (value == TypeEnum.TerminalSale) + return "terminalSale"; + + if (value == TypeEnum.Credit) + return "credit"; + + if (value == TypeEnum.Debit) + return "debit"; + + if (value == TypeEnum.Adjustment) + return "adjustment"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + /// + /// The type of balance transfer. Possible values: **tax**, **fee**, **terminalSale**, **credit**, **debit**, and **adjustment**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The date when the balance transfer was requested. + /// + /// The date when the balance transfer was requested. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// The unique identifier of the source merchant account from which funds are deducted. + /// + /// The unique identifier of the source merchant account from which funds are deducted. + [JsonPropertyName("fromMerchant")] + public string FromMerchant { get; set; } + + /// + /// Adyen's 16-character string reference associated with the balance transfer. + /// + /// Adyen's 16-character string reference associated with the balance transfer. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The unique identifier of the destination merchant account from which funds are transferred. + /// + /// The unique identifier of the destination merchant account from which funds are transferred. + [JsonPropertyName("toMerchant")] + public string ToMerchant { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + /// + /// A human-readable description for the transfer. You can use alphanumeric characters and hyphens. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + /// + /// A reference for the balance transfer. If you don't provide this in the request, Adyen generates a unique reference. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceTransferResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" FromMerchant: ").Append(FromMerchant).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" ToMerchant: ").Append(ToMerchant).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 140) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 140.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceTransferResponseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceTransferResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option createdAt = default; + Option fromMerchant = default; + Option pspReference = default; + Option status = default; + Option toMerchant = default; + Option type = default; + Option description = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "fromMerchant": + fromMerchant = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceTransferResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "toMerchant": + toMerchant = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceTransferResponse.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(amount)); + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(createdAt)); + + if (!fromMerchant.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(fromMerchant)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(status)); + + if (!toMerchant.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(toMerchant)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceTransferResponse.", nameof(type)); + + return new BalanceTransferResponse(amount.Value!, createdAt.Value!.Value!, fromMerchant.Value!, pspReference.Value!, status.Value!.Value!, toMerchant.Value!, type.Value!.Value!, description, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceTransferResponse balanceTransferResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceTransferResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceTransferResponse balanceTransferResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, balanceTransferResponse.Amount, jsonSerializerOptions); + writer.WriteString("createdAt", balanceTransferResponse.CreatedAt.ToString(CreatedAtFormat)); + + if (balanceTransferResponse.FromMerchant != null) + writer.WriteString("fromMerchant", balanceTransferResponse.FromMerchant); + + if (balanceTransferResponse.PspReference != null) + writer.WriteString("pspReference", balanceTransferResponse.PspReference); + + if (balanceTransferResponse.Status != null) + { + string? statusRawValue = BalanceTransferResponse.StatusEnum.ToJsonValue(balanceTransferResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (balanceTransferResponse.ToMerchant != null) + writer.WriteString("toMerchant", balanceTransferResponse.ToMerchant); + + if (balanceTransferResponse.Type != null) + { + string? typeRawValue = BalanceTransferResponse.TypeEnum.ToJsonValue(balanceTransferResponse.Type); + writer.WriteString("type", typeRawValue); + } + + if (balanceTransferResponse._DescriptionOption.IsSet) + if (balanceTransferResponse.Description != null) + writer.WriteString("description", balanceTransferResponse.Description); + + if (balanceTransferResponse._ReferenceOption.IsSet) + if (balanceTransferResponse.Reference != null) + writer.WriteString("reference", balanceTransferResponse.Reference); + } + } +} diff --git a/Adyen/BalanceControl/Services/BalanceControlService.cs b/Adyen/BalanceControl/Services/BalanceControlService.cs new file mode 100644 index 000000000..61504abb9 --- /dev/null +++ b/Adyen/BalanceControl/Services/BalanceControlService.cs @@ -0,0 +1,322 @@ +// +/* + * Adyen Balance Control API + * + * The Balance Control API lets you transfer funds between merchant accounts that belong to the same legal entity and are under the same company account. ## Authentication To connect to the Balance Control API, you must authenticate your requests with an [API key or basic auth username and password](https://docs.adyen.com/development-resources/api-authentication). To learn how you can generate these, see [API credentials](https://docs.adyen.com/development-resources/api-credentials).Here is an example of authenticating a request with an API key: ``` curl -H \"X-API-Key: Your_API_key\" \\ -H \"Content-Type: application/json\" \\ ... ``` Note that when going live, you need to generate API credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning The Balance Control API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BalanceControl/v1/balanceTransfer ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalanceControl.Client; +using Adyen.BalanceControl.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalanceControl.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBalanceControlService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BalanceControlServiceEvents Events { get; } + + /// + /// Start a balance transfer + /// + /// + /// Starts a balance transfer request between merchant accounts. The following conditions must be met before you can successfully transfer balances: * The source and destination merchant accounts must be under the same company account and legal entity. * The source merchant account must have sufficient funds. * The source and destination merchant accounts must have at least one common processing currency. When sending multiple API requests with the same source and destination merchant accounts, send the requests sequentially and *not* in parallel. Some requests may not be processed if the requests are sent in parallel. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + [Obsolete("Deprecated since Adyen Balance Control API v1.")] + Task BalanceTransferAsync(BalanceTransferRequest balanceTransferRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IBalanceTransferApiResponse : Adyen.Core.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BalanceControlServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnBalanceTransfer; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorBalanceTransfer; + + internal void ExecuteOnBalanceTransfer(BalanceControlService.BalanceTransferApiResponse apiResponse) + { + OnBalanceTransfer?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorBalanceTransfer(Exception exception) + { + OnErrorBalanceTransfer?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BalanceControlService : IBalanceControlService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BalanceControlServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BalanceControlService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BalanceControlServiceEvents balanceControlServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = balanceControlServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Start a balance transfer Starts a balance transfer request between merchant accounts. The following conditions must be met before you can successfully transfer balances: * The source and destination merchant accounts must be under the same company account and legal entity. * The source merchant account must have sufficient funds. * The source and destination merchant accounts must have at least one common processing currency. When sending multiple API requests with the same source and destination merchant accounts, send the requests sequentially and *not* in parallel. Some requests may not be processed if the requests are sent in parallel. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task BalanceTransferAsync(BalanceTransferRequest balanceTransferRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceTransfer" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceTransfer"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceTransferRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceTransferRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + BalanceTransferApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceTransfer", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnBalanceTransfer(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorBalanceTransfer(exception); + throw; + } + } + + /// + /// The . + /// + public partial class BalanceTransferApiResponse : Adyen.Core.Client.ApiResponse, IBalanceTransferApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public BalanceTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public BalanceTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalanceControl.Models.BalanceTransferResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalanceControl.Models.BalanceTransferResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Client/ApiKeyToken.cs b/Adyen/BalancePlatform/Client/ApiKeyToken.cs new file mode 100644 index 000000000..db3c0330c --- /dev/null +++ b/Adyen/BalancePlatform/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.BalancePlatform.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/BalancePlatform/Client/ClientUtils.cs b/Adyen/BalancePlatform/Client/ClientUtils.cs new file mode 100644 index 000000000..ced80f1f8 --- /dev/null +++ b/Adyen/BalancePlatform/Client/ClientUtils.cs @@ -0,0 +1,592 @@ +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.BalancePlatform.Models; +using Models = Adyen.BalancePlatform.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.BalancePlatform.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AULocalAccountIdentification.TypeEnum aULocalAccountIdentificationTypeEnum) + return Models.AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentificationTypeEnum); + if (obj is Models.AccountHolder.StatusEnum accountHolderStatusEnum) + return Models.AccountHolder.StatusEnum.ToJsonValue(accountHolderStatusEnum); + if (obj is Models.AccountHolderCapability.AllowedLevelEnum accountHolderCapabilityAllowedLevelEnum) + return Models.AccountHolderCapability.AllowedLevelEnum.ToJsonValue(accountHolderCapabilityAllowedLevelEnum); + if (obj is Models.AccountHolderCapability.RequestedLevelEnum accountHolderCapabilityRequestedLevelEnum) + return Models.AccountHolderCapability.RequestedLevelEnum.ToJsonValue(accountHolderCapabilityRequestedLevelEnum); + if (obj is Models.AccountHolderCapability.VerificationStatusEnum accountHolderCapabilityVerificationStatusEnum) + return Models.AccountHolderCapability.VerificationStatusEnum.ToJsonValue(accountHolderCapabilityVerificationStatusEnum); + if (obj is Models.AccountHolderUpdateRequest.StatusEnum accountHolderUpdateRequestStatusEnum) + return Models.AccountHolderUpdateRequest.StatusEnum.ToJsonValue(accountHolderUpdateRequestStatusEnum); + if (obj is Models.AccountSupportingEntityCapability.AllowedLevelEnum accountSupportingEntityCapabilityAllowedLevelEnum) + return Models.AccountSupportingEntityCapability.AllowedLevelEnum.ToJsonValue(accountSupportingEntityCapabilityAllowedLevelEnum); + if (obj is Models.AccountSupportingEntityCapability.RequestedLevelEnum accountSupportingEntityCapabilityRequestedLevelEnum) + return Models.AccountSupportingEntityCapability.RequestedLevelEnum.ToJsonValue(accountSupportingEntityCapabilityRequestedLevelEnum); + if (obj is Models.AccountSupportingEntityCapability.VerificationStatusEnum accountSupportingEntityCapabilityVerificationStatusEnum) + return Models.AccountSupportingEntityCapability.VerificationStatusEnum.ToJsonValue(accountSupportingEntityCapabilityVerificationStatusEnum); + if (obj is Models.AdditionalBankIdentification.TypeEnum additionalBankIdentificationTypeEnum) + return Models.AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentificationTypeEnum); + if (obj is Models.AdditionalBankIdentificationRequirement.AdditionalBankIdentificationTypeEnum additionalBankIdentificationRequirementAdditionalBankIdentificationTypeEnum) + return Models.AdditionalBankIdentificationRequirement.AdditionalBankIdentificationTypeEnum.ToJsonValue(additionalBankIdentificationRequirementAdditionalBankIdentificationTypeEnum); + if (obj is Models.AdditionalBankIdentificationRequirement.TypeEnum additionalBankIdentificationRequirementTypeEnum) + return Models.AdditionalBankIdentificationRequirement.TypeEnum.ToJsonValue(additionalBankIdentificationRequirementTypeEnum); + if (obj is Models.AddressRequirement.RequiredAddressFieldsEnum addressRequirementRequiredAddressFieldsEnum) + return AddressRequirement.RequiredAddressFieldsEnum.ToJsonValue(addressRequirementRequiredAddressFieldsEnum); + if (obj is Models.AddressRequirement.TypeEnum addressRequirementTypeEnum) + return Models.AddressRequirement.TypeEnum.ToJsonValue(addressRequirementTypeEnum); + if (obj is Models.AmountMinMaxRequirement.TypeEnum amountMinMaxRequirementTypeEnum) + return Models.AmountMinMaxRequirement.TypeEnum.ToJsonValue(amountMinMaxRequirementTypeEnum); + if (obj is Models.AmountNonZeroDecimalsRequirement.TypeEnum amountNonZeroDecimalsRequirementTypeEnum) + return Models.AmountNonZeroDecimalsRequirement.TypeEnum.ToJsonValue(amountNonZeroDecimalsRequirementTypeEnum); + if (obj is Models.AssociationFinaliseRequest.TypeEnum associationFinaliseRequestTypeEnum) + return Models.AssociationFinaliseRequest.TypeEnum.ToJsonValue(associationFinaliseRequestTypeEnum); + if (obj is Models.AssociationFinaliseResponse.TypeEnum associationFinaliseResponseTypeEnum) + return Models.AssociationFinaliseResponse.TypeEnum.ToJsonValue(associationFinaliseResponseTypeEnum); + if (obj is Models.AssociationInitiateRequest.TypeEnum associationInitiateRequestTypeEnum) + return Models.AssociationInitiateRequest.TypeEnum.ToJsonValue(associationInitiateRequestTypeEnum); + if (obj is Models.AssociationStatus associationStatus) + return AssociationStatusValueConverter.ToJsonValue(associationStatus); + if (obj is Models.BRLocalAccountIdentification.TypeEnum bRLocalAccountIdentificationTypeEnum) + return Models.BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentificationTypeEnum); + if (obj is Models.BalanceAccount.StatusEnum balanceAccountStatusEnum) + return Models.BalanceAccount.StatusEnum.ToJsonValue(balanceAccountStatusEnum); + if (obj is Models.BalanceAccountBase.StatusEnum balanceAccountBaseStatusEnum) + return Models.BalanceAccountBase.StatusEnum.ToJsonValue(balanceAccountBaseStatusEnum); + if (obj is Models.BalanceAccountUpdateRequest.StatusEnum balanceAccountUpdateRequestStatusEnum) + return Models.BalanceAccountUpdateRequest.StatusEnum.ToJsonValue(balanceAccountUpdateRequestStatusEnum); + if (obj is Models.BalanceWebhookSettingInfo.StatusEnum balanceWebhookSettingInfoStatusEnum) + return Models.BalanceWebhookSettingInfo.StatusEnum.ToJsonValue(balanceWebhookSettingInfoStatusEnum); + if (obj is Models.BalanceWebhookSettingInfo.TypeEnum balanceWebhookSettingInfoTypeEnum) + return Models.BalanceWebhookSettingInfo.TypeEnum.ToJsonValue(balanceWebhookSettingInfoTypeEnum); + if (obj is Models.BalanceWebhookSettingInfoUpdate.StatusEnum balanceWebhookSettingInfoUpdateStatusEnum) + return Models.BalanceWebhookSettingInfoUpdate.StatusEnum.ToJsonValue(balanceWebhookSettingInfoUpdateStatusEnum); + if (obj is Models.BalanceWebhookSettingInfoUpdate.TypeEnum balanceWebhookSettingInfoUpdateTypeEnum) + return Models.BalanceWebhookSettingInfoUpdate.TypeEnum.ToJsonValue(balanceWebhookSettingInfoUpdateTypeEnum); + if (obj is Models.BankAccountIdentificationTypeRequirement.BankAccountIdentificationTypesEnum bankAccountIdentificationTypeRequirementBankAccountIdentificationTypesEnum) + return BankAccountIdentificationTypeRequirement.BankAccountIdentificationTypesEnum.ToJsonValue(bankAccountIdentificationTypeRequirementBankAccountIdentificationTypesEnum); + if (obj is Models.BankAccountIdentificationTypeRequirement.TypeEnum bankAccountIdentificationTypeRequirementTypeEnum) + return Models.BankAccountIdentificationTypeRequirement.TypeEnum.ToJsonValue(bankAccountIdentificationTypeRequirementTypeEnum); + if (obj is Models.BankAccountModel.FormFactorEnum bankAccountModelFormFactorEnum) + return Models.BankAccountModel.FormFactorEnum.ToJsonValue(bankAccountModelFormFactorEnum); + if (obj is Models.BankIdentification.IdentificationTypeEnum bankIdentificationIdentificationTypeEnum) + return Models.BankIdentification.IdentificationTypeEnum.ToJsonValue(bankIdentificationIdentificationTypeEnum); + if (obj is Models.CALocalAccountIdentification.AccountTypeEnum cALocalAccountIdentificationAccountTypeEnum) + return Models.CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentificationAccountTypeEnum); + if (obj is Models.CALocalAccountIdentification.TypeEnum cALocalAccountIdentificationTypeEnum) + return Models.CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentificationTypeEnum); + if (obj is Models.CZLocalAccountIdentification.TypeEnum cZLocalAccountIdentificationTypeEnum) + return Models.CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentificationTypeEnum); + if (obj is Models.CapabilityProblemEntity.TypeEnum capabilityProblemEntityTypeEnum) + return Models.CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntityTypeEnum); + if (obj is Models.CapabilityProblemEntityRecursive.TypeEnum capabilityProblemEntityRecursiveTypeEnum) + return Models.CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursiveTypeEnum); + if (obj is Models.CapabilitySettings.FundingSourceEnum capabilitySettingsFundingSourceEnum) + return CapabilitySettings.FundingSourceEnum.ToJsonValue(capabilitySettingsFundingSourceEnum); + if (obj is Models.CapabilitySettings.IntervalEnum capabilitySettingsIntervalEnum) + return Models.CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettingsIntervalEnum); + if (obj is Models.Card.FormFactorEnum cardFormFactorEnum) + return Models.Card.FormFactorEnum.ToJsonValue(cardFormFactorEnum); + if (obj is Models.CardInfo.FormFactorEnum cardInfoFormFactorEnum) + return Models.CardInfo.FormFactorEnum.ToJsonValue(cardInfoFormFactorEnum); + if (obj is Models.CardOrder.StatusEnum cardOrderStatusEnum) + return Models.CardOrder.StatusEnum.ToJsonValue(cardOrderStatusEnum); + if (obj is Models.CardOrderItemDeliveryStatus.StatusEnum cardOrderItemDeliveryStatusStatusEnum) + return Models.CardOrderItemDeliveryStatus.StatusEnum.ToJsonValue(cardOrderItemDeliveryStatusStatusEnum); + if (obj is Models.Condition.BalanceTypeEnum conditionBalanceTypeEnum) + return Models.Condition.BalanceTypeEnum.ToJsonValue(conditionBalanceTypeEnum); + if (obj is Models.Condition.ConditionTypeEnum conditionConditionTypeEnum) + return Models.Condition.ConditionTypeEnum.ToJsonValue(conditionConditionTypeEnum); + if (obj is Models.CounterpartyTypesRestriction.ValueEnum counterpartyTypesRestrictionValueEnum) + return CounterpartyTypesRestriction.ValueEnum.ToJsonValue(counterpartyTypesRestrictionValueEnum); + if (obj is Models.CreateSweepConfigurationV2.CategoryEnum createSweepConfigurationV2CategoryEnum) + return Models.CreateSweepConfigurationV2.CategoryEnum.ToJsonValue(createSweepConfigurationV2CategoryEnum); + if (obj is Models.CreateSweepConfigurationV2.PrioritiesEnum createSweepConfigurationV2PrioritiesEnum) + return CreateSweepConfigurationV2.PrioritiesEnum.ToJsonValue(createSweepConfigurationV2PrioritiesEnum); + if (obj is Models.CreateSweepConfigurationV2.ReasonEnum createSweepConfigurationV2ReasonEnum) + return Models.CreateSweepConfigurationV2.ReasonEnum.ToJsonValue(createSweepConfigurationV2ReasonEnum); + if (obj is Models.CreateSweepConfigurationV2.StatusEnum createSweepConfigurationV2StatusEnum) + return Models.CreateSweepConfigurationV2.StatusEnum.ToJsonValue(createSweepConfigurationV2StatusEnum); + if (obj is Models.CreateSweepConfigurationV2.TypeEnum createSweepConfigurationV2TypeEnum) + return Models.CreateSweepConfigurationV2.TypeEnum.ToJsonValue(createSweepConfigurationV2TypeEnum); + if (obj is Models.DKLocalAccountIdentification.TypeEnum dKLocalAccountIdentificationTypeEnum) + return Models.DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentificationTypeEnum); + if (obj is Models.DayOfWeekRestriction.ValueEnum dayOfWeekRestrictionValueEnum) + return DayOfWeekRestriction.ValueEnum.ToJsonValue(dayOfWeekRestrictionValueEnum); + if (obj is Models.Device.TypeEnum deviceTypeEnum) + return Models.Device.TypeEnum.ToJsonValue(deviceTypeEnum); + if (obj is Models.Duration.UnitEnum durationUnitEnum) + return Models.Duration.UnitEnum.ToJsonValue(durationUnitEnum); + if (obj is Models.EntryModesRestriction.ValueEnum entryModesRestrictionValueEnum) + return EntryModesRestriction.ValueEnum.ToJsonValue(entryModesRestrictionValueEnum); + if (obj is Models.GetTaxFormResponse.ContentTypeEnum getTaxFormResponseContentTypeEnum) + return Models.GetTaxFormResponse.ContentTypeEnum.ToJsonValue(getTaxFormResponseContentTypeEnum); + if (obj is Models.GrantOffer.ContractTypeEnum grantOfferContractTypeEnum) + return Models.GrantOffer.ContractTypeEnum.ToJsonValue(grantOfferContractTypeEnum); + if (obj is Models.HKLocalAccountIdentification.TypeEnum hKLocalAccountIdentificationTypeEnum) + return Models.HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentificationTypeEnum); + if (obj is Models.HULocalAccountIdentification.TypeEnum hULocalAccountIdentificationTypeEnum) + return Models.HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentificationTypeEnum); + if (obj is Models.IbanAccountIdentification.TypeEnum ibanAccountIdentificationTypeEnum) + return Models.IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentificationTypeEnum); + if (obj is Models.IbanAccountIdentificationRequirement.TypeEnum ibanAccountIdentificationRequirementTypeEnum) + return Models.IbanAccountIdentificationRequirement.TypeEnum.ToJsonValue(ibanAccountIdentificationRequirementTypeEnum); + if (obj is Models.LimitStatus limitStatus) + return LimitStatusValueConverter.ToJsonValue(limitStatus); + if (obj is Models.MatchingValuesRestriction.ValueEnum matchingValuesRestrictionValueEnum) + return MatchingValuesRestriction.ValueEnum.ToJsonValue(matchingValuesRestrictionValueEnum); + if (obj is Models.NOLocalAccountIdentification.TypeEnum nOLocalAccountIdentificationTypeEnum) + return Models.NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentificationTypeEnum); + if (obj is Models.NZLocalAccountIdentification.TypeEnum nZLocalAccountIdentificationTypeEnum) + return Models.NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentificationTypeEnum); + if (obj is Models.NetworkToken.StatusEnum networkTokenStatusEnum) + return Models.NetworkToken.StatusEnum.ToJsonValue(networkTokenStatusEnum); + if (obj is Models.NumberAndBicAccountIdentification.TypeEnum numberAndBicAccountIdentificationTypeEnum) + return Models.NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentificationTypeEnum); + if (obj is Models.PLLocalAccountIdentification.TypeEnum pLLocalAccountIdentificationTypeEnum) + return Models.PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentificationTypeEnum); + if (obj is Models.PaymentInstrument.TypeEnum paymentInstrumentTypeEnum) + return Models.PaymentInstrument.TypeEnum.ToJsonValue(paymentInstrumentTypeEnum); + if (obj is Models.PaymentInstrument.StatusEnum paymentInstrumentStatusEnum) + return Models.PaymentInstrument.StatusEnum.ToJsonValue(paymentInstrumentStatusEnum); + if (obj is Models.PaymentInstrument.StatusReasonEnum paymentInstrumentStatusReasonEnum) + return Models.PaymentInstrument.StatusReasonEnum.ToJsonValue(paymentInstrumentStatusReasonEnum); + if (obj is Models.PaymentInstrumentInfo.TypeEnum paymentInstrumentInfoTypeEnum) + return Models.PaymentInstrumentInfo.TypeEnum.ToJsonValue(paymentInstrumentInfoTypeEnum); + if (obj is Models.PaymentInstrumentInfo.StatusEnum paymentInstrumentInfoStatusEnum) + return Models.PaymentInstrumentInfo.StatusEnum.ToJsonValue(paymentInstrumentInfoStatusEnum); + if (obj is Models.PaymentInstrumentInfo.StatusReasonEnum paymentInstrumentInfoStatusReasonEnum) + return Models.PaymentInstrumentInfo.StatusReasonEnum.ToJsonValue(paymentInstrumentInfoStatusReasonEnum); + if (obj is Models.PaymentInstrumentRequirement.PaymentInstrumentTypeEnum paymentInstrumentRequirementPaymentInstrumentTypeEnum) + return Models.PaymentInstrumentRequirement.PaymentInstrumentTypeEnum.ToJsonValue(paymentInstrumentRequirementPaymentInstrumentTypeEnum); + if (obj is Models.PaymentInstrumentRequirement.TypeEnum paymentInstrumentRequirementTypeEnum) + return Models.PaymentInstrumentRequirement.TypeEnum.ToJsonValue(paymentInstrumentRequirementTypeEnum); + if (obj is Models.PaymentInstrumentUpdateRequest.StatusEnum paymentInstrumentUpdateRequestStatusEnum) + return Models.PaymentInstrumentUpdateRequest.StatusEnum.ToJsonValue(paymentInstrumentUpdateRequestStatusEnum); + if (obj is Models.PaymentInstrumentUpdateRequest.StatusReasonEnum paymentInstrumentUpdateRequestStatusReasonEnum) + return Models.PaymentInstrumentUpdateRequest.StatusReasonEnum.ToJsonValue(paymentInstrumentUpdateRequestStatusReasonEnum); + if (obj is Models.Phone.TypeEnum phoneTypeEnum) + return Models.Phone.TypeEnum.ToJsonValue(phoneTypeEnum); + if (obj is Models.PhoneNumber.PhoneTypeEnum phoneNumberPhoneTypeEnum) + return Models.PhoneNumber.PhoneTypeEnum.ToJsonValue(phoneNumberPhoneTypeEnum); + if (obj is Models.PinChangeResponse.StatusEnum pinChangeResponseStatusEnum) + return Models.PinChangeResponse.StatusEnum.ToJsonValue(pinChangeResponseStatusEnum); + if (obj is Models.ProcessingTypesRestriction.ValueEnum processingTypesRestrictionValueEnum) + return ProcessingTypesRestriction.ValueEnum.ToJsonValue(processingTypesRestrictionValueEnum); + if (obj is Models.SELocalAccountIdentification.TypeEnum sELocalAccountIdentificationTypeEnum) + return Models.SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentificationTypeEnum); + if (obj is Models.SGLocalAccountIdentification.TypeEnum sGLocalAccountIdentificationTypeEnum) + return Models.SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentificationTypeEnum); + if (obj is Models.ScaDeviceType scaDeviceType) + return ScaDeviceTypeValueConverter.ToJsonValue(scaDeviceType); + if (obj is Models.ScaEntityType scaEntityType) + return ScaEntityTypeValueConverter.ToJsonValue(scaEntityType); + if (obj is Models.ScaExemption scaExemption) + return ScaExemptionValueConverter.ToJsonValue(scaExemption); + if (obj is Models.ScaStatus scaStatus) + return ScaStatusValueConverter.ToJsonValue(scaStatus); + if (obj is Models.Scope scope) + return ScopeValueConverter.ToJsonValue(scope); + if (obj is Models.SettingType settingType) + return SettingTypeValueConverter.ToJsonValue(settingType); + if (obj is Models.SourceAccountTypesRestriction.ValueEnum sourceAccountTypesRestrictionValueEnum) + return SourceAccountTypesRestriction.ValueEnum.ToJsonValue(sourceAccountTypesRestrictionValueEnum); + if (obj is Models.StringMatch.OperationEnum stringMatchOperationEnum) + return Models.StringMatch.OperationEnum.ToJsonValue(stringMatchOperationEnum); + if (obj is Models.SweepConfigurationV2.CategoryEnum sweepConfigurationV2CategoryEnum) + return Models.SweepConfigurationV2.CategoryEnum.ToJsonValue(sweepConfigurationV2CategoryEnum); + if (obj is Models.SweepConfigurationV2.PrioritiesEnum sweepConfigurationV2PrioritiesEnum) + return SweepConfigurationV2.PrioritiesEnum.ToJsonValue(sweepConfigurationV2PrioritiesEnum); + if (obj is Models.SweepConfigurationV2.ReasonEnum sweepConfigurationV2ReasonEnum) + return Models.SweepConfigurationV2.ReasonEnum.ToJsonValue(sweepConfigurationV2ReasonEnum); + if (obj is Models.SweepConfigurationV2.StatusEnum sweepConfigurationV2StatusEnum) + return Models.SweepConfigurationV2.StatusEnum.ToJsonValue(sweepConfigurationV2StatusEnum); + if (obj is Models.SweepConfigurationV2.TypeEnum sweepConfigurationV2TypeEnum) + return Models.SweepConfigurationV2.TypeEnum.ToJsonValue(sweepConfigurationV2TypeEnum); + if (obj is Models.SweepSchedule.TypeEnum sweepScheduleTypeEnum) + return Models.SweepSchedule.TypeEnum.ToJsonValue(sweepScheduleTypeEnum); + if (obj is Models.Target.TypeEnum targetTypeEnum) + return Models.Target.TypeEnum.ToJsonValue(targetTypeEnum); + if (obj is Models.TargetUpdate.TypeEnum targetUpdateTypeEnum) + return Models.TargetUpdate.TypeEnum.ToJsonValue(targetUpdateTypeEnum); + if (obj is Models.TransactionRule.TypeEnum transactionRuleTypeEnum) + return Models.TransactionRule.TypeEnum.ToJsonValue(transactionRuleTypeEnum); + if (obj is Models.TransactionRule.OutcomeTypeEnum transactionRuleOutcomeTypeEnum) + return Models.TransactionRule.OutcomeTypeEnum.ToJsonValue(transactionRuleOutcomeTypeEnum); + if (obj is Models.TransactionRule.RequestTypeEnum transactionRuleRequestTypeEnum) + return Models.TransactionRule.RequestTypeEnum.ToJsonValue(transactionRuleRequestTypeEnum); + if (obj is Models.TransactionRule.StatusEnum transactionRuleStatusEnum) + return Models.TransactionRule.StatusEnum.ToJsonValue(transactionRuleStatusEnum); + if (obj is Models.TransactionRuleInfo.TypeEnum transactionRuleInfoTypeEnum) + return Models.TransactionRuleInfo.TypeEnum.ToJsonValue(transactionRuleInfoTypeEnum); + if (obj is Models.TransactionRuleInfo.OutcomeTypeEnum transactionRuleInfoOutcomeTypeEnum) + return Models.TransactionRuleInfo.OutcomeTypeEnum.ToJsonValue(transactionRuleInfoOutcomeTypeEnum); + if (obj is Models.TransactionRuleInfo.RequestTypeEnum transactionRuleInfoRequestTypeEnum) + return Models.TransactionRuleInfo.RequestTypeEnum.ToJsonValue(transactionRuleInfoRequestTypeEnum); + if (obj is Models.TransactionRuleInfo.StatusEnum transactionRuleInfoStatusEnum) + return Models.TransactionRuleInfo.StatusEnum.ToJsonValue(transactionRuleInfoStatusEnum); + if (obj is Models.TransactionRuleInterval.TypeEnum transactionRuleIntervalTypeEnum) + return Models.TransactionRuleInterval.TypeEnum.ToJsonValue(transactionRuleIntervalTypeEnum); + if (obj is Models.TransactionRuleInterval.DayOfWeekEnum transactionRuleIntervalDayOfWeekEnum) + return Models.TransactionRuleInterval.DayOfWeekEnum.ToJsonValue(transactionRuleIntervalDayOfWeekEnum); + if (obj is Models.TransferRoute.CategoryEnum transferRouteCategoryEnum) + return Models.TransferRoute.CategoryEnum.ToJsonValue(transferRouteCategoryEnum); + if (obj is Models.TransferRoute.PriorityEnum transferRoutePriorityEnum) + return Models.TransferRoute.PriorityEnum.ToJsonValue(transferRoutePriorityEnum); + if (obj is Models.TransferRouteRequest.CategoryEnum transferRouteRequestCategoryEnum) + return Models.TransferRouteRequest.CategoryEnum.ToJsonValue(transferRouteRequestCategoryEnum); + if (obj is Models.TransferRouteRequest.PrioritiesEnum transferRouteRequestPrioritiesEnum) + return TransferRouteRequest.PrioritiesEnum.ToJsonValue(transferRouteRequestPrioritiesEnum); + if (obj is Models.TransferType transferType) + return TransferTypeValueConverter.ToJsonValue(transferType); + if (obj is Models.UKLocalAccountIdentification.TypeEnum uKLocalAccountIdentificationTypeEnum) + return Models.UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentificationTypeEnum); + if (obj is Models.USInstantPayoutAddressRequirement.TypeEnum uSInstantPayoutAddressRequirementTypeEnum) + return Models.USInstantPayoutAddressRequirement.TypeEnum.ToJsonValue(uSInstantPayoutAddressRequirementTypeEnum); + if (obj is Models.USInternationalAchAddressRequirement.TypeEnum uSInternationalAchAddressRequirementTypeEnum) + return Models.USInternationalAchAddressRequirement.TypeEnum.ToJsonValue(uSInternationalAchAddressRequirementTypeEnum); + if (obj is Models.USInternationalAchPriorityRequirement.TypeEnum uSInternationalAchPriorityRequirementTypeEnum) + return Models.USInternationalAchPriorityRequirement.TypeEnum.ToJsonValue(uSInternationalAchPriorityRequirementTypeEnum); + if (obj is Models.USLocalAccountIdentification.AccountTypeEnum uSLocalAccountIdentificationAccountTypeEnum) + return Models.USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentificationAccountTypeEnum); + if (obj is Models.USLocalAccountIdentification.TypeEnum uSLocalAccountIdentificationTypeEnum) + return Models.USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentificationTypeEnum); + if (obj is Models.UpdateNetworkTokenRequest.StatusEnum updateNetworkTokenRequestStatusEnum) + return Models.UpdateNetworkTokenRequest.StatusEnum.ToJsonValue(updateNetworkTokenRequestStatusEnum); + if (obj is Models.UpdatePaymentInstrument.TypeEnum updatePaymentInstrumentTypeEnum) + return Models.UpdatePaymentInstrument.TypeEnum.ToJsonValue(updatePaymentInstrumentTypeEnum); + if (obj is Models.UpdatePaymentInstrument.StatusEnum updatePaymentInstrumentStatusEnum) + return Models.UpdatePaymentInstrument.StatusEnum.ToJsonValue(updatePaymentInstrumentStatusEnum); + if (obj is Models.UpdatePaymentInstrument.StatusReasonEnum updatePaymentInstrumentStatusReasonEnum) + return Models.UpdatePaymentInstrument.StatusReasonEnum.ToJsonValue(updatePaymentInstrumentStatusReasonEnum); + if (obj is Models.UpdateSweepConfigurationV2.CategoryEnum updateSweepConfigurationV2CategoryEnum) + return Models.UpdateSweepConfigurationV2.CategoryEnum.ToJsonValue(updateSweepConfigurationV2CategoryEnum); + if (obj is Models.UpdateSweepConfigurationV2.PrioritiesEnum updateSweepConfigurationV2PrioritiesEnum) + return UpdateSweepConfigurationV2.PrioritiesEnum.ToJsonValue(updateSweepConfigurationV2PrioritiesEnum); + if (obj is Models.UpdateSweepConfigurationV2.ReasonEnum updateSweepConfigurationV2ReasonEnum) + return Models.UpdateSweepConfigurationV2.ReasonEnum.ToJsonValue(updateSweepConfigurationV2ReasonEnum); + if (obj is Models.UpdateSweepConfigurationV2.StatusEnum updateSweepConfigurationV2StatusEnum) + return Models.UpdateSweepConfigurationV2.StatusEnum.ToJsonValue(updateSweepConfigurationV2StatusEnum); + if (obj is Models.UpdateSweepConfigurationV2.TypeEnum updateSweepConfigurationV2TypeEnum) + return Models.UpdateSweepConfigurationV2.TypeEnum.ToJsonValue(updateSweepConfigurationV2TypeEnum); + if (obj is Models.VerificationDeadline.CapabilitiesEnum verificationDeadlineCapabilitiesEnum) + return VerificationDeadline.CapabilitiesEnum.ToJsonValue(verificationDeadlineCapabilitiesEnum); + if (obj is Models.VerificationError.CapabilitiesEnum verificationErrorCapabilitiesEnum) + return VerificationError.CapabilitiesEnum.ToJsonValue(verificationErrorCapabilitiesEnum); + if (obj is Models.VerificationError.TypeEnum verificationErrorTypeEnum) + return Models.VerificationError.TypeEnum.ToJsonValue(verificationErrorTypeEnum); + if (obj is Models.VerificationErrorRecursive.CapabilitiesEnum verificationErrorRecursiveCapabilitiesEnum) + return VerificationErrorRecursive.CapabilitiesEnum.ToJsonValue(verificationErrorRecursiveCapabilitiesEnum); + if (obj is Models.VerificationErrorRecursive.TypeEnum verificationErrorRecursiveTypeEnum) + return Models.VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursiveTypeEnum); + if (obj is Models.WalletProviderDeviceType.ValueEnum walletProviderDeviceTypeValueEnum) + return WalletProviderDeviceType.ValueEnum.ToJsonValue(walletProviderDeviceTypeValueEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key, + /// + /// The clientKey header. + /// + ClientKey + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + ApiKeyHeader.ClientKey => "clientKey", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/BalancePlatform/Client/HostConfiguration.cs b/Adyen/BalancePlatform/Client/HostConfiguration.cs new file mode 100644 index 000000000..d0e5ea0b2 --- /dev/null +++ b/Adyen/BalancePlatform/Client/HostConfiguration.cs @@ -0,0 +1,386 @@ +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.BalancePlatform.Services; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.BalancePlatform.Client +{ + /// + /// Provides hosting configuration for BalancePlatform + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://balanceplatform-api-test.adyen.com/bcl/v2"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderInfoJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderUpdateRequestJsonConverter()); + _jsonOptions.Converters.Add(new AccountSupportingEntityCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new ActiveNetworkTokensRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalBankIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalBankIdentificationRequirementJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AddressRequirementJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AmountMinMaxRequirementJsonConverter()); + _jsonOptions.Converters.Add(new AmountNonZeroDecimalsRequirementJsonConverter()); + _jsonOptions.Converters.Add(new ApproveAssociationRequestJsonConverter()); + _jsonOptions.Converters.Add(new ApproveAssociationResponseJsonConverter()); + _jsonOptions.Converters.Add(new ApproveTransferLimitRequestJsonConverter()); + _jsonOptions.Converters.Add(new AssociationJsonConverter()); + _jsonOptions.Converters.Add(new AssociationDelegatedAuthenticationDataJsonConverter()); + _jsonOptions.Converters.Add(new AssociationFinaliseRequestJsonConverter()); + _jsonOptions.Converters.Add(new AssociationFinaliseResponseJsonConverter()); + _jsonOptions.Converters.Add(new AssociationInitiateRequestJsonConverter()); + _jsonOptions.Converters.Add(new AssociationInitiateResponseJsonConverter()); + _jsonOptions.Converters.Add(new AssociationListingJsonConverter()); + _jsonOptions.Converters.Add(new AssociationStatusJsonConverter()); + _jsonOptions.Converters.Add(new AssociationStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationJsonConverter()); + _jsonOptions.Converters.Add(new AuthorisedCardUsersJsonConverter()); + _jsonOptions.Converters.Add(new BRLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BalanceJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountBaseJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountInfoJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountUpdateRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformJsonConverter()); + _jsonOptions.Converters.Add(new BalanceSweepConfigurationsResponseJsonConverter()); + _jsonOptions.Converters.Add(new BalanceWebhookSettingJsonConverter()); + _jsonOptions.Converters.Add(new BalanceWebhookSettingInfoJsonConverter()); + _jsonOptions.Converters.Add(new BalanceWebhookSettingInfoUpdateJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountDetailsJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountIdentificationTypeRequirementJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountIdentificationValidationRequestJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountIdentificationValidationRequestAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountModelJsonConverter()); + _jsonOptions.Converters.Add(new BankIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BeginScaDeviceRegistrationRequestJsonConverter()); + _jsonOptions.Converters.Add(new BeginScaDeviceRegistrationResponseJsonConverter()); + _jsonOptions.Converters.Add(new BrandVariantsRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new BulkAddressJsonConverter()); + _jsonOptions.Converters.Add(new CALocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new CapabilitySettingsJsonConverter()); + _jsonOptions.Converters.Add(new CapitalBalanceJsonConverter()); + _jsonOptions.Converters.Add(new CapitalGrantAccountJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CardConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new CardInfoJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderItemJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderItemDeliveryStatusJsonConverter()); + _jsonOptions.Converters.Add(new ConditionJsonConverter()); + _jsonOptions.Converters.Add(new ContactDetailsJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyBankRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyTypesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new CountriesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new CreateScaInformationJsonConverter()); + _jsonOptions.Converters.Add(new CreateSweepConfigurationV2JsonConverter()); + _jsonOptions.Converters.Add(new CreateTransferLimitRequestJsonConverter()); + _jsonOptions.Converters.Add(new DKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new DayOfWeekRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new DefaultErrorResponseEntityJsonConverter()); + _jsonOptions.Converters.Add(new DelegatedAuthenticationDataJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryAddressJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryContactJsonConverter()); + _jsonOptions.Converters.Add(new DeviceJsonConverter()); + _jsonOptions.Converters.Add(new DeviceInfoJsonConverter()); + _jsonOptions.Converters.Add(new DifferentCurrenciesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new DurationJsonConverter()); + _jsonOptions.Converters.Add(new EntryModesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new ExpiryJsonConverter()); + _jsonOptions.Converters.Add(new FeeJsonConverter()); + _jsonOptions.Converters.Add(new FinishScaDeviceRegistrationRequestJsonConverter()); + _jsonOptions.Converters.Add(new FinishScaDeviceRegistrationResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetNetworkTokenResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetTaxFormResponseJsonConverter()); + _jsonOptions.Converters.Add(new GrantLimitJsonConverter()); + _jsonOptions.Converters.Add(new GrantOfferJsonConverter()); + _jsonOptions.Converters.Add(new GrantOffersJsonConverter()); + _jsonOptions.Converters.Add(new HKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new HULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new HrefJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationRequirementJsonConverter()); + _jsonOptions.Converters.Add(new InternationalTransactionRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new LimitStatusJsonConverter()); + _jsonOptions.Converters.Add(new LimitStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new LinkJsonConverter()); + _jsonOptions.Converters.Add(new ListAssociationsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListNetworkTokensResponseJsonConverter()); + _jsonOptions.Converters.Add(new MatchingTransactionsRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new MatchingValuesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new MccsRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new MerchantAcquirerPairJsonConverter()); + _jsonOptions.Converters.Add(new MerchantNamesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new MerchantsRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new NOLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenActivationDataRequestJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenActivationDataResponseJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenRequestorJsonConverter()); + _jsonOptions.Converters.Add(new NumberAndBicAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PLLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PaginatedAccountHoldersResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaginatedBalanceAccountsResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaginatedGetCardOrderItemResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaginatedGetCardOrderResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaginatedPaymentInstrumentsResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentAdditionalBankAccountIdentificationsInnerJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentGroupJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentGroupInfoJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentInfoJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentRequirementJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentRevealInfoJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentRevealRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentRevealResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentUpdateRequestJsonConverter()); + _jsonOptions.Converters.Add(new PhoneJsonConverter()); + _jsonOptions.Converters.Add(new PhoneNumberJsonConverter()); + _jsonOptions.Converters.Add(new PinChangeRequestJsonConverter()); + _jsonOptions.Converters.Add(new PinChangeResponseJsonConverter()); + _jsonOptions.Converters.Add(new PlatformPaymentConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new ProcessingTypesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new PublicKeyResponseJsonConverter()); + _jsonOptions.Converters.Add(new RegisterSCAFinalResponseJsonConverter()); + _jsonOptions.Converters.Add(new RegisterSCARequestJsonConverter()); + _jsonOptions.Converters.Add(new RegisterSCAResponseJsonConverter()); + _jsonOptions.Converters.Add(new RemediatingActionJsonConverter()); + _jsonOptions.Converters.Add(new RemoveAssociationRequestJsonConverter()); + _jsonOptions.Converters.Add(new RepaymentJsonConverter()); + _jsonOptions.Converters.Add(new RepaymentTermJsonConverter()); + _jsonOptions.Converters.Add(new RestServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new RevealPinRequestJsonConverter()); + _jsonOptions.Converters.Add(new RevealPinResponseJsonConverter()); + _jsonOptions.Converters.Add(new RiskScoresJsonConverter()); + _jsonOptions.Converters.Add(new RiskScoresRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new SELocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new SGLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new SameAmountRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new SameCounterpartyRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new ScaDeviceJsonConverter()); + _jsonOptions.Converters.Add(new ScaDeviceTypeJsonConverter()); + _jsonOptions.Converters.Add(new ScaDeviceTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new ScaEntityJsonConverter()); + _jsonOptions.Converters.Add(new ScaEntityTypeJsonConverter()); + _jsonOptions.Converters.Add(new ScaEntityTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new ScaExemptionJsonConverter()); + _jsonOptions.Converters.Add(new ScaExemptionNullableJsonConverter()); + _jsonOptions.Converters.Add(new ScaInformationJsonConverter()); + _jsonOptions.Converters.Add(new ScaStatusJsonConverter()); + _jsonOptions.Converters.Add(new ScaStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new ScopeJsonConverter()); + _jsonOptions.Converters.Add(new ScopeNullableJsonConverter()); + _jsonOptions.Converters.Add(new SearchRegisteredDevicesResponseJsonConverter()); + _jsonOptions.Converters.Add(new SettingTypeJsonConverter()); + _jsonOptions.Converters.Add(new SettingTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new SourceAccountTypesRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new StringMatchJsonConverter()); + _jsonOptions.Converters.Add(new SubmitScaAssociationRequestJsonConverter()); + _jsonOptions.Converters.Add(new SubmitScaAssociationResponseJsonConverter()); + _jsonOptions.Converters.Add(new SweepConfigurationV2JsonConverter()); + _jsonOptions.Converters.Add(new SweepCounterpartyJsonConverter()); + _jsonOptions.Converters.Add(new SweepScheduleJsonConverter()); + _jsonOptions.Converters.Add(new TargetJsonConverter()); + _jsonOptions.Converters.Add(new TargetUpdateJsonConverter()); + _jsonOptions.Converters.Add(new ThresholdRepaymentJsonConverter()); + _jsonOptions.Converters.Add(new TimeOfDayJsonConverter()); + _jsonOptions.Converters.Add(new TimeOfDayRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new TokenRequestorsRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new TotalAmountRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleEntityKeyJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleInfoJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleIntervalJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleResponseJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleRestrictionsJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRulesResponseJsonConverter()); + _jsonOptions.Converters.Add(new TransferLimitJsonConverter()); + _jsonOptions.Converters.Add(new TransferLimitListResponseJsonConverter()); + _jsonOptions.Converters.Add(new TransferRouteJsonConverter()); + _jsonOptions.Converters.Add(new TransferRouteRequestJsonConverter()); + _jsonOptions.Converters.Add(new TransferRouteRequirementsInnerJsonConverter()); + _jsonOptions.Converters.Add(new TransferRouteResponseJsonConverter()); + _jsonOptions.Converters.Add(new TransferTypeJsonConverter()); + _jsonOptions.Converters.Add(new TransferTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new UKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new USInstantPayoutAddressRequirementJsonConverter()); + _jsonOptions.Converters.Add(new USInternationalAchAddressRequirementJsonConverter()); + _jsonOptions.Converters.Add(new USInternationalAchPriorityRequirementJsonConverter()); + _jsonOptions.Converters.Add(new USLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new UpdateNetworkTokenRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdatePaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new UpdateSweepConfigurationV2JsonConverter()); + _jsonOptions.Converters.Add(new VerificationDeadlineJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new WalletProviderAccountScoreRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new WalletProviderDeviceScoreJsonConverter()); + _jsonOptions.Converters.Add(new WalletProviderDeviceTypeJsonConverter()); + _jsonOptions.Converters.Add(new WebhookSettingJsonConverter()); + _jsonOptions.Converters.Add(new WebhookSettingsJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddBalancePlatformHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/BalancePlatform/Client/JsonSerializerOptionsProvider.cs b/Adyen/BalancePlatform/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..611138007 --- /dev/null +++ b/Adyen/BalancePlatform/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.BalancePlatform.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/BalancePlatform/Extensions/HostBuilderExtensions.cs b/Adyen/BalancePlatform/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..8c0fc8876 --- /dev/null +++ b/Adyen/BalancePlatform/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.BalancePlatform; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the BalancePlatform API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureBalancePlatform(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddBalancePlatformHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/BalancePlatform/Extensions/ServiceCollectionExtensions.cs b/Adyen/BalancePlatform/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..32b0ece40 --- /dev/null +++ b/Adyen/BalancePlatform/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen BalancePlatform API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddBalancePlatformServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddBalancePlatformHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AULocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/AULocalAccountIdentification.cs new file mode 100644 index 000000000..355ac253c --- /dev/null +++ b/Adyen/BalancePlatform/Models/AULocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AULocalAccountIdentification. + /// + public partial class AULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// **auLocal** (default to TypeEnum.AuLocal) + [JsonConstructor] + public AULocalAccountIdentification(string accountNumber, string bsbCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BsbCode = bsbCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuLocal - auLocal + /// + public static readonly TypeEnum AuLocal = new("auLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auLocal" => TypeEnum.AuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuLocal) + return "auLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + [JsonPropertyName("bsbCode")] + public string BsbCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BsbCode: ").Append(BsbCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 9.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // BsbCode (string) maxLength + if (this.BsbCode != null && this.BsbCode.Length > 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be less than 6.", new [] { "BsbCode" }); + } + + // BsbCode (string) minLength + if (this.BsbCode != null && this.BsbCode.Length < 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be greater than 6.", new [] { "BsbCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bsbCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bsbCode": + bsbCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(accountNumber)); + + if (!bsbCode.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(bsbCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(type)); + + return new AULocalAccountIdentification(accountNumber.Value!, bsbCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, aULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (aULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", aULocalAccountIdentification.AccountNumber); + + if (aULocalAccountIdentification.BsbCode != null) + writer.WriteString("bsbCode", aULocalAccountIdentification.BsbCode); + + if (aULocalAccountIdentification.Type != null) + { + string? typeRawValue = AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AccountHolder.cs b/Adyen/BalancePlatform/Models/AccountHolder.cs new file mode 100644 index 000000000..39ecd462e --- /dev/null +++ b/Adyen/BalancePlatform/Models/AccountHolder.cs @@ -0,0 +1,598 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AccountHolder. + /// + public partial class AccountHolder : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the account holder. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// contactDetails + /// Your description for the account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the migrated account holder in the classic integration. + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// Your reference for the account holder. + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonConstructor] + public AccountHolder(string id, string legalEntityId, Option balancePlatform = default, Option?> capabilities = default, Option contactDetails = default, Option description = default, Option?> metadata = default, Option migratedAccountHolderCode = default, Option primaryBalanceAccount = default, Option reference = default, Option status = default, Option timeZone = default, Option?> verificationDeadlines = default) + { + Id = id; + LegalEntityId = legalEntityId; + _BalancePlatformOption = balancePlatform; + _CapabilitiesOption = capabilities; + _ContactDetailsOption = contactDetails; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountHolderCodeOption = migratedAccountHolderCode; + _PrimaryBalanceAccountOption = primaryBalanceAccount; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + _VerificationDeadlinesOption = verificationDeadlines; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolder() + { + } + + partial void OnCreated(); + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The unique identifier of the account holder. + /// + /// The unique identifier of the account holder. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("contactDetails")] + [Obsolete("")] + public ContactDetails? ContactDetails { get { return this._ContactDetailsOption; } set { this._ContactDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the account holder. + /// + /// Your description for the account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountHolderCodeOption { get; } + + /// + /// The unique identifier of the migrated account holder in the classic integration. + /// + /// The unique identifier of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountHolderCode")] + public string? MigratedAccountHolderCode { get { return this._MigratedAccountHolderCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrimaryBalanceAccountOption { get; private set; } + + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + [JsonPropertyName("primaryBalanceAccount")] + public string? PrimaryBalanceAccount { get { return this._PrimaryBalanceAccountOption; } set { this._PrimaryBalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the account holder. + /// + /// Your reference for the account holder. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationDeadlinesOption { get; } + + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonPropertyName("verificationDeadlines")] + public List? VerificationDeadlines { get { return this._VerificationDeadlinesOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolder {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ContactDetails: ").Append(ContactDetails).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountHolderCode: ").Append(MigratedAccountHolderCode).Append("\n"); + sb.Append(" PrimaryBalanceAccount: ").Append(PrimaryBalanceAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append(" VerificationDeadlines: ").Append(VerificationDeadlines).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolder Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option legalEntityId = default; + Option balancePlatform = default; + Option?> capabilities = default; + Option contactDetails = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountHolderCode = default; + Option primaryBalanceAccount = default; + Option reference = default; + Option status = default; + Option timeZone = default; + Option?> verificationDeadlines = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contactDetails": + contactDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountHolderCode": + migratedAccountHolderCode = new Option(utf8JsonReader.GetString()!); + break; + case "primaryBalanceAccount": + primaryBalanceAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AccountHolder.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + case "verificationDeadlines": + verificationDeadlines = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class AccountHolder.", nameof(id)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class AccountHolder.", nameof(legalEntityId)); + + return new AccountHolder(id.Value!, legalEntityId.Value!, balancePlatform, capabilities, contactDetails, description, metadata, migratedAccountHolderCode, primaryBalanceAccount, reference, status, timeZone, verificationDeadlines); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolder accountHolder, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolder, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolder accountHolder, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolder.Id != null) + writer.WriteString("id", accountHolder.Id); + + if (accountHolder.LegalEntityId != null) + writer.WriteString("legalEntityId", accountHolder.LegalEntityId); + + if (accountHolder._BalancePlatformOption.IsSet) + if (accountHolder.BalancePlatform != null) + writer.WriteString("balancePlatform", accountHolder.BalancePlatform); + + if (accountHolder._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountHolder.Capabilities, jsonSerializerOptions); + } + if (accountHolder._ContactDetailsOption.IsSet) + { + writer.WritePropertyName("contactDetails"); + JsonSerializer.Serialize(writer, accountHolder.ContactDetails, jsonSerializerOptions); + } + if (accountHolder._DescriptionOption.IsSet) + if (accountHolder.Description != null) + writer.WriteString("description", accountHolder.Description); + + if (accountHolder._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, accountHolder.Metadata, jsonSerializerOptions); + } + if (accountHolder._MigratedAccountHolderCodeOption.IsSet) + if (accountHolder.MigratedAccountHolderCode != null) + writer.WriteString("migratedAccountHolderCode", accountHolder.MigratedAccountHolderCode); + + if (accountHolder._PrimaryBalanceAccountOption.IsSet) + if (accountHolder.PrimaryBalanceAccount != null) + writer.WriteString("primaryBalanceAccount", accountHolder.PrimaryBalanceAccount); + + if (accountHolder._ReferenceOption.IsSet) + if (accountHolder.Reference != null) + writer.WriteString("reference", accountHolder.Reference); + + if (accountHolder._StatusOption.IsSet && accountHolder.Status != null) + { + string? statusRawValue = AccountHolder.StatusEnum.ToJsonValue(accountHolder._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (accountHolder._TimeZoneOption.IsSet) + if (accountHolder.TimeZone != null) + writer.WriteString("timeZone", accountHolder.TimeZone); + + if (accountHolder._VerificationDeadlinesOption.IsSet) + { + writer.WritePropertyName("verificationDeadlines"); + JsonSerializer.Serialize(writer, accountHolder.VerificationDeadlines, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AccountHolderCapability.cs b/Adyen/BalancePlatform/Models/AccountHolderCapability.cs new file mode 100644 index 000000000..39a81f190 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AccountHolderCapability.cs @@ -0,0 +1,773 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AccountHolderCapability. + /// + public partial class AccountHolderCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// allowedSettings + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// Contains verification errors and the actions that you can take to resolve them. + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// requestedSettings + /// Contains the status of the transfer instruments associated with this capability. + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + public AccountHolderCapability(Option allowed = default, Option allowedLevel = default, Option allowedSettings = default, Option enabled = default, Option?> problems = default, Option requested = default, Option requestedLevel = default, Option requestedSettings = default, Option?> transferInstruments = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _AllowedSettingsOption = allowedSettings; + _EnabledOption = enabled; + _ProblemsOption = problems; + _RequestedOption = requested; + _RequestedLevelOption = requestedLevel; + _RequestedSettingsOption = requestedSettings; + _TransferInstrumentsOption = transferInstruments; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderCapability() + { + } + + partial void OnCreated(); + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(AllowedLevelEnumJsonConverter))] + public class AllowedLevelEnum : IEnum + { + /// + /// Returns the value of the AllowedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// AllowedLevelEnum.High - high + /// + public static readonly AllowedLevelEnum High = new("high"); + + /// + /// AllowedLevelEnum.Low - low + /// + public static readonly AllowedLevelEnum Low = new("low"); + + /// + /// AllowedLevelEnum.Medium - medium + /// + public static readonly AllowedLevelEnum Medium = new("medium"); + + /// + /// AllowedLevelEnum.NotApplicable - notApplicable + /// + public static readonly AllowedLevelEnum NotApplicable = new("notApplicable"); + + private AllowedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AllowedLevelEnum?(string? value) => value == null ? null : new AllowedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AllowedLevelEnum? option) => option?.Value; + + public static bool operator ==(AllowedLevelEnum? left, AllowedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AllowedLevelEnum? left, AllowedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AllowedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AllowedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => AllowedLevelEnum.High, + "low" => AllowedLevelEnum.Low, + "medium" => AllowedLevelEnum.Medium, + "notApplicable" => AllowedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AllowedLevelEnum? value) + { + if (value == null) + return null; + + if (value == AllowedLevelEnum.High) + return "high"; + + if (value == AllowedLevelEnum.Low) + return "low"; + + if (value == AllowedLevelEnum.Medium) + return "medium"; + + if (value == AllowedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing AllowedLevelEnum. + /// + public class AllowedLevelEnumJsonConverter : JsonConverter + { + public override AllowedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AllowedLevelEnum.FromStringOrDefault(value) ?? new AllowedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AllowedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AllowedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; } + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public AllowedLevelEnum? AllowedLevel { get { return this._AllowedLevelOption; } } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(RequestedLevelEnumJsonConverter))] + public class RequestedLevelEnum : IEnum + { + /// + /// Returns the value of the RequestedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// RequestedLevelEnum.High - high + /// + public static readonly RequestedLevelEnum High = new("high"); + + /// + /// RequestedLevelEnum.Low - low + /// + public static readonly RequestedLevelEnum Low = new("low"); + + /// + /// RequestedLevelEnum.Medium - medium + /// + public static readonly RequestedLevelEnum Medium = new("medium"); + + /// + /// RequestedLevelEnum.NotApplicable - notApplicable + /// + public static readonly RequestedLevelEnum NotApplicable = new("notApplicable"); + + private RequestedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestedLevelEnum?(string? value) => value == null ? null : new RequestedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestedLevelEnum? option) => option?.Value; + + public static bool operator ==(RequestedLevelEnum? left, RequestedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestedLevelEnum? left, RequestedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => RequestedLevelEnum.High, + "low" => RequestedLevelEnum.Low, + "medium" => RequestedLevelEnum.Medium, + "notApplicable" => RequestedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestedLevelEnum? value) + { + if (value == null) + return null; + + if (value == RequestedLevelEnum.High) + return "high"; + + if (value == RequestedLevelEnum.Low) + return "low"; + + if (value == RequestedLevelEnum.Medium) + return "medium"; + + if (value == RequestedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing RequestedLevelEnum. + /// + public class RequestedLevelEnumJsonConverter : JsonConverter + { + public override RequestedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestedLevelEnum.FromStringOrDefault(value) ?? new RequestedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedLevelOption { get; private set; } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public RequestedLevelEnum? RequestedLevel { get { return this._RequestedLevelOption; } set { this._RequestedLevelOption = new(value); } } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => VerificationStatusEnum.Invalid, + "pending" => VerificationStatusEnum.Pending, + "rejected" => VerificationStatusEnum.Rejected, + "valid" => VerificationStatusEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; } + + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("allowedSettings")] + public CapabilitySettings? AllowedSettings { get { return this._AllowedSettingsOption; } set { this._AllowedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; } + + /// + /// Contains verification errors and the actions that you can take to resolve them. + /// + /// Contains verification errors and the actions that you can take to resolve them. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; private set; } + + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } set { this._RequestedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("requestedSettings")] + public CapabilitySettings? RequestedSettings { get { return this._RequestedSettingsOption; } set { this._RequestedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferInstrumentsOption { get; } + + /// + /// Contains the status of the transfer instruments associated with this capability. + /// + /// Contains the status of the transfer instruments associated with this capability. + [JsonPropertyName("transferInstruments")] + public List? TransferInstruments { get { return this._TransferInstrumentsOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" AllowedSettings: ").Append(AllowedSettings).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" RequestedSettings: ").Append(RequestedSettings).Append("\n"); + sb.Append(" TransferInstruments: ").Append(TransferInstruments).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option allowedLevel = default; + Option allowedSettings = default; + Option enabled = default; + Option?> problems = default; + Option requested = default; + Option requestedLevel = default; + Option requestedSettings = default; + Option?> transferInstruments = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + string? allowedLevelRawValue = utf8JsonReader.GetString(); + allowedLevel = new Option(AccountHolderCapability.AllowedLevelEnum.FromStringOrDefault(allowedLevelRawValue)); + break; + case "allowedSettings": + allowedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + string? requestedLevelRawValue = utf8JsonReader.GetString(); + requestedLevel = new Option(AccountHolderCapability.RequestedLevelEnum.FromStringOrDefault(requestedLevelRawValue)); + break; + case "requestedSettings": + requestedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstruments": + transferInstruments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(AccountHolderCapability.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + + return new AccountHolderCapability(allowed, allowedLevel, allowedSettings, enabled, problems, requested, requestedLevel, requestedSettings, transferInstruments, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderCapability accountHolderCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderCapability accountHolderCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", accountHolderCapability._AllowedOption.Value!.Value); + + if (accountHolderCapability._AllowedLevelOption.IsSet && accountHolderCapability.AllowedLevel != null) + { + string? allowedLevelRawValue = AccountHolderCapability.AllowedLevelEnum.ToJsonValue(accountHolderCapability._AllowedLevelOption.Value!.Value); + writer.WriteString("allowedLevel", allowedLevelRawValue); + } + + if (accountHolderCapability._AllowedSettingsOption.IsSet) + { + writer.WritePropertyName("allowedSettings"); + JsonSerializer.Serialize(writer, accountHolderCapability.AllowedSettings, jsonSerializerOptions); + } + if (accountHolderCapability._EnabledOption.IsSet) + writer.WriteBoolean("enabled", accountHolderCapability._EnabledOption.Value!.Value); + + if (accountHolderCapability._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, accountHolderCapability.Problems, jsonSerializerOptions); + } + if (accountHolderCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", accountHolderCapability._RequestedOption.Value!.Value); + + if (accountHolderCapability._RequestedLevelOption.IsSet && accountHolderCapability.RequestedLevel != null) + { + string? requestedLevelRawValue = AccountHolderCapability.RequestedLevelEnum.ToJsonValue(accountHolderCapability._RequestedLevelOption.Value!.Value); + writer.WriteString("requestedLevel", requestedLevelRawValue); + } + + if (accountHolderCapability._RequestedSettingsOption.IsSet) + { + writer.WritePropertyName("requestedSettings"); + JsonSerializer.Serialize(writer, accountHolderCapability.RequestedSettings, jsonSerializerOptions); + } + if (accountHolderCapability._TransferInstrumentsOption.IsSet) + { + writer.WritePropertyName("transferInstruments"); + JsonSerializer.Serialize(writer, accountHolderCapability.TransferInstruments, jsonSerializerOptions); + } + if (accountHolderCapability._VerificationStatusOption.IsSet && accountHolderCapability.VerificationStatus != null) + { + string? verificationStatusRawValue = AccountHolderCapability.VerificationStatusEnum.ToJsonValue(accountHolderCapability._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AccountHolderInfo.cs b/Adyen/BalancePlatform/Models/AccountHolderInfo.cs new file mode 100644 index 000000000..bee797fca --- /dev/null +++ b/Adyen/BalancePlatform/Models/AccountHolderInfo.cs @@ -0,0 +1,386 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AccountHolderInfo. + /// + public partial class AccountHolderInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// contactDetails + /// Your description for the account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the migrated account holder in the classic integration. + /// Your reference for the account holder. + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public AccountHolderInfo(string legalEntityId, Option balancePlatform = default, Option?> capabilities = default, Option contactDetails = default, Option description = default, Option?> metadata = default, Option migratedAccountHolderCode = default, Option reference = default, Option timeZone = default) + { + LegalEntityId = legalEntityId; + _BalancePlatformOption = balancePlatform; + _CapabilitiesOption = capabilities; + _ContactDetailsOption = contactDetails; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountHolderCodeOption = migratedAccountHolderCode; + _ReferenceOption = reference; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderInfo() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("contactDetails")] + [Obsolete("")] + public ContactDetails? ContactDetails { get { return this._ContactDetailsOption; } set { this._ContactDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the account holder. + /// + /// Your description for the account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountHolderCodeOption { get; } + + /// + /// The unique identifier of the migrated account holder in the classic integration. + /// + /// The unique identifier of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountHolderCode")] + public string? MigratedAccountHolderCode { get { return this._MigratedAccountHolderCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the account holder. + /// + /// Your reference for the account holder. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderInfo {\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ContactDetails: ").Append(ContactDetails).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountHolderCode: ").Append(MigratedAccountHolderCode).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option legalEntityId = default; + Option balancePlatform = default; + Option?> capabilities = default; + Option contactDetails = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountHolderCode = default; + Option reference = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contactDetails": + contactDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountHolderCode": + migratedAccountHolderCode = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class AccountHolderInfo.", nameof(legalEntityId)); + + return new AccountHolderInfo(legalEntityId.Value!, balancePlatform, capabilities, contactDetails, description, metadata, migratedAccountHolderCode, reference, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderInfo accountHolderInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderInfo accountHolderInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderInfo.LegalEntityId != null) + writer.WriteString("legalEntityId", accountHolderInfo.LegalEntityId); + + if (accountHolderInfo._BalancePlatformOption.IsSet) + if (accountHolderInfo.BalancePlatform != null) + writer.WriteString("balancePlatform", accountHolderInfo.BalancePlatform); + + if (accountHolderInfo._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountHolderInfo.Capabilities, jsonSerializerOptions); + } + if (accountHolderInfo._ContactDetailsOption.IsSet) + { + writer.WritePropertyName("contactDetails"); + JsonSerializer.Serialize(writer, accountHolderInfo.ContactDetails, jsonSerializerOptions); + } + if (accountHolderInfo._DescriptionOption.IsSet) + if (accountHolderInfo.Description != null) + writer.WriteString("description", accountHolderInfo.Description); + + if (accountHolderInfo._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, accountHolderInfo.Metadata, jsonSerializerOptions); + } + if (accountHolderInfo._MigratedAccountHolderCodeOption.IsSet) + if (accountHolderInfo.MigratedAccountHolderCode != null) + writer.WriteString("migratedAccountHolderCode", accountHolderInfo.MigratedAccountHolderCode); + + if (accountHolderInfo._ReferenceOption.IsSet) + if (accountHolderInfo.Reference != null) + writer.WriteString("reference", accountHolderInfo.Reference); + + if (accountHolderInfo._TimeZoneOption.IsSet) + if (accountHolderInfo.TimeZone != null) + writer.WriteString("timeZone", accountHolderInfo.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AccountHolderUpdateRequest.cs b/Adyen/BalancePlatform/Models/AccountHolderUpdateRequest.cs new file mode 100644 index 000000000..be6be85cd --- /dev/null +++ b/Adyen/BalancePlatform/Models/AccountHolderUpdateRequest.cs @@ -0,0 +1,559 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AccountHolderUpdateRequest. + /// + public partial class AccountHolderUpdateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// contactDetails + /// Your description for the account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the migrated account holder in the classic integration. + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// Your reference for the account holder. + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonConstructor] + public AccountHolderUpdateRequest(Option balancePlatform = default, Option?> capabilities = default, Option contactDetails = default, Option description = default, Option?> metadata = default, Option migratedAccountHolderCode = default, Option primaryBalanceAccount = default, Option reference = default, Option status = default, Option timeZone = default, Option?> verificationDeadlines = default) + { + _BalancePlatformOption = balancePlatform; + _CapabilitiesOption = capabilities; + _ContactDetailsOption = contactDetails; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountHolderCodeOption = migratedAccountHolderCode; + _PrimaryBalanceAccountOption = primaryBalanceAccount; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + _VerificationDeadlinesOption = verificationDeadlines; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderUpdateRequest() + { + } + + partial void OnCreated(); + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("contactDetails")] + [Obsolete("")] + public ContactDetails? ContactDetails { get { return this._ContactDetailsOption; } set { this._ContactDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the account holder. + /// + /// Your description for the account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountHolderCodeOption { get; } + + /// + /// The unique identifier of the migrated account holder in the classic integration. + /// + /// The unique identifier of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountHolderCode")] + public string? MigratedAccountHolderCode { get { return this._MigratedAccountHolderCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrimaryBalanceAccountOption { get; private set; } + + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + [JsonPropertyName("primaryBalanceAccount")] + public string? PrimaryBalanceAccount { get { return this._PrimaryBalanceAccountOption; } set { this._PrimaryBalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the account holder. + /// + /// Your reference for the account holder. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationDeadlinesOption { get; } + + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonPropertyName("verificationDeadlines")] + public List? VerificationDeadlines { get { return this._VerificationDeadlinesOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderUpdateRequest {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ContactDetails: ").Append(ContactDetails).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountHolderCode: ").Append(MigratedAccountHolderCode).Append("\n"); + sb.Append(" PrimaryBalanceAccount: ").Append(PrimaryBalanceAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append(" VerificationDeadlines: ").Append(VerificationDeadlines).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderUpdateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderUpdateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option?> capabilities = default; + Option contactDetails = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountHolderCode = default; + Option primaryBalanceAccount = default; + Option reference = default; + Option status = default; + Option timeZone = default; + Option?> verificationDeadlines = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contactDetails": + contactDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountHolderCode": + migratedAccountHolderCode = new Option(utf8JsonReader.GetString()!); + break; + case "primaryBalanceAccount": + primaryBalanceAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AccountHolderUpdateRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + case "verificationDeadlines": + verificationDeadlines = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AccountHolderUpdateRequest(balancePlatform, capabilities, contactDetails, description, metadata, migratedAccountHolderCode, primaryBalanceAccount, reference, status, timeZone, verificationDeadlines); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderUpdateRequest accountHolderUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderUpdateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderUpdateRequest accountHolderUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderUpdateRequest._BalancePlatformOption.IsSet) + if (accountHolderUpdateRequest.BalancePlatform != null) + writer.WriteString("balancePlatform", accountHolderUpdateRequest.BalancePlatform); + + if (accountHolderUpdateRequest._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountHolderUpdateRequest.Capabilities, jsonSerializerOptions); + } + if (accountHolderUpdateRequest._ContactDetailsOption.IsSet) + { + writer.WritePropertyName("contactDetails"); + JsonSerializer.Serialize(writer, accountHolderUpdateRequest.ContactDetails, jsonSerializerOptions); + } + if (accountHolderUpdateRequest._DescriptionOption.IsSet) + if (accountHolderUpdateRequest.Description != null) + writer.WriteString("description", accountHolderUpdateRequest.Description); + + if (accountHolderUpdateRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, accountHolderUpdateRequest.Metadata, jsonSerializerOptions); + } + if (accountHolderUpdateRequest._MigratedAccountHolderCodeOption.IsSet) + if (accountHolderUpdateRequest.MigratedAccountHolderCode != null) + writer.WriteString("migratedAccountHolderCode", accountHolderUpdateRequest.MigratedAccountHolderCode); + + if (accountHolderUpdateRequest._PrimaryBalanceAccountOption.IsSet) + if (accountHolderUpdateRequest.PrimaryBalanceAccount != null) + writer.WriteString("primaryBalanceAccount", accountHolderUpdateRequest.PrimaryBalanceAccount); + + if (accountHolderUpdateRequest._ReferenceOption.IsSet) + if (accountHolderUpdateRequest.Reference != null) + writer.WriteString("reference", accountHolderUpdateRequest.Reference); + + if (accountHolderUpdateRequest._StatusOption.IsSet && accountHolderUpdateRequest.Status != null) + { + string? statusRawValue = AccountHolderUpdateRequest.StatusEnum.ToJsonValue(accountHolderUpdateRequest._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (accountHolderUpdateRequest._TimeZoneOption.IsSet) + if (accountHolderUpdateRequest.TimeZone != null) + writer.WriteString("timeZone", accountHolderUpdateRequest.TimeZone); + + if (accountHolderUpdateRequest._VerificationDeadlinesOption.IsSet) + { + writer.WritePropertyName("verificationDeadlines"); + JsonSerializer.Serialize(writer, accountHolderUpdateRequest.VerificationDeadlines, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AccountSupportingEntityCapability.cs b/Adyen/BalancePlatform/Models/AccountSupportingEntityCapability.cs new file mode 100644 index 000000000..4768c97f4 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AccountSupportingEntityCapability.cs @@ -0,0 +1,696 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AccountSupportingEntityCapability. + /// + public partial class AccountSupportingEntityCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// The ID of the supporting entity. + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + public AccountSupportingEntityCapability(Option allowed = default, Option allowedLevel = default, Option enabled = default, Option id = default, Option requested = default, Option requestedLevel = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _EnabledOption = enabled; + _IdOption = id; + _RequestedOption = requested; + _RequestedLevelOption = requestedLevel; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountSupportingEntityCapability() + { + } + + partial void OnCreated(); + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(AllowedLevelEnumJsonConverter))] + public class AllowedLevelEnum : IEnum + { + /// + /// Returns the value of the AllowedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// AllowedLevelEnum.High - high + /// + public static readonly AllowedLevelEnum High = new("high"); + + /// + /// AllowedLevelEnum.Low - low + /// + public static readonly AllowedLevelEnum Low = new("low"); + + /// + /// AllowedLevelEnum.Medium - medium + /// + public static readonly AllowedLevelEnum Medium = new("medium"); + + /// + /// AllowedLevelEnum.NotApplicable - notApplicable + /// + public static readonly AllowedLevelEnum NotApplicable = new("notApplicable"); + + private AllowedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AllowedLevelEnum?(string? value) => value == null ? null : new AllowedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AllowedLevelEnum? option) => option?.Value; + + public static bool operator ==(AllowedLevelEnum? left, AllowedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AllowedLevelEnum? left, AllowedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AllowedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AllowedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => AllowedLevelEnum.High, + "low" => AllowedLevelEnum.Low, + "medium" => AllowedLevelEnum.Medium, + "notApplicable" => AllowedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AllowedLevelEnum? value) + { + if (value == null) + return null; + + if (value == AllowedLevelEnum.High) + return "high"; + + if (value == AllowedLevelEnum.Low) + return "low"; + + if (value == AllowedLevelEnum.Medium) + return "medium"; + + if (value == AllowedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing AllowedLevelEnum. + /// + public class AllowedLevelEnumJsonConverter : JsonConverter + { + public override AllowedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AllowedLevelEnum.FromStringOrDefault(value) ?? new AllowedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AllowedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AllowedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; } + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public AllowedLevelEnum? AllowedLevel { get { return this._AllowedLevelOption; } } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(RequestedLevelEnumJsonConverter))] + public class RequestedLevelEnum : IEnum + { + /// + /// Returns the value of the RequestedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// RequestedLevelEnum.High - high + /// + public static readonly RequestedLevelEnum High = new("high"); + + /// + /// RequestedLevelEnum.Low - low + /// + public static readonly RequestedLevelEnum Low = new("low"); + + /// + /// RequestedLevelEnum.Medium - medium + /// + public static readonly RequestedLevelEnum Medium = new("medium"); + + /// + /// RequestedLevelEnum.NotApplicable - notApplicable + /// + public static readonly RequestedLevelEnum NotApplicable = new("notApplicable"); + + private RequestedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestedLevelEnum?(string? value) => value == null ? null : new RequestedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestedLevelEnum? option) => option?.Value; + + public static bool operator ==(RequestedLevelEnum? left, RequestedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestedLevelEnum? left, RequestedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => RequestedLevelEnum.High, + "low" => RequestedLevelEnum.Low, + "medium" => RequestedLevelEnum.Medium, + "notApplicable" => RequestedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestedLevelEnum? value) + { + if (value == null) + return null; + + if (value == RequestedLevelEnum.High) + return "high"; + + if (value == RequestedLevelEnum.Low) + return "low"; + + if (value == RequestedLevelEnum.Medium) + return "medium"; + + if (value == RequestedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing RequestedLevelEnum. + /// + public class RequestedLevelEnumJsonConverter : JsonConverter + { + public override RequestedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestedLevelEnum.FromStringOrDefault(value) ?? new RequestedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedLevelOption { get; private set; } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public RequestedLevelEnum? RequestedLevel { get { return this._RequestedLevelOption; } set { this._RequestedLevelOption = new(value); } } + + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => VerificationStatusEnum.Invalid, + "pending" => VerificationStatusEnum.Pending, + "rejected" => VerificationStatusEnum.Rejected, + "valid" => VerificationStatusEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; } + + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; } + + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// The ID of the supporting entity. + /// + /// The ID of the supporting entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; private set; } + + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } set { this._RequestedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountSupportingEntityCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountSupportingEntityCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountSupportingEntityCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option allowedLevel = default; + Option enabled = default; + Option id = default; + Option requested = default; + Option requestedLevel = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + string? allowedLevelRawValue = utf8JsonReader.GetString(); + allowedLevel = new Option(AccountSupportingEntityCapability.AllowedLevelEnum.FromStringOrDefault(allowedLevelRawValue)); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + string? requestedLevelRawValue = utf8JsonReader.GetString(); + requestedLevel = new Option(AccountSupportingEntityCapability.RequestedLevelEnum.FromStringOrDefault(requestedLevelRawValue)); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(AccountSupportingEntityCapability.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + + return new AccountSupportingEntityCapability(allowed, allowedLevel, enabled, id, requested, requestedLevel, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountSupportingEntityCapability accountSupportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountSupportingEntityCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountSupportingEntityCapability accountSupportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountSupportingEntityCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", accountSupportingEntityCapability._AllowedOption.Value!.Value); + + if (accountSupportingEntityCapability._AllowedLevelOption.IsSet && accountSupportingEntityCapability.AllowedLevel != null) + { + string? allowedLevelRawValue = AccountSupportingEntityCapability.AllowedLevelEnum.ToJsonValue(accountSupportingEntityCapability._AllowedLevelOption.Value!.Value); + writer.WriteString("allowedLevel", allowedLevelRawValue); + } + + if (accountSupportingEntityCapability._EnabledOption.IsSet) + writer.WriteBoolean("enabled", accountSupportingEntityCapability._EnabledOption.Value!.Value); + + if (accountSupportingEntityCapability._IdOption.IsSet) + if (accountSupportingEntityCapability.Id != null) + writer.WriteString("id", accountSupportingEntityCapability.Id); + + if (accountSupportingEntityCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", accountSupportingEntityCapability._RequestedOption.Value!.Value); + + if (accountSupportingEntityCapability._RequestedLevelOption.IsSet && accountSupportingEntityCapability.RequestedLevel != null) + { + string? requestedLevelRawValue = AccountSupportingEntityCapability.RequestedLevelEnum.ToJsonValue(accountSupportingEntityCapability._RequestedLevelOption.Value!.Value); + writer.WriteString("requestedLevel", requestedLevelRawValue); + } + + if (accountSupportingEntityCapability._VerificationStatusOption.IsSet && accountSupportingEntityCapability.VerificationStatus != null) + { + string? verificationStatusRawValue = AccountSupportingEntityCapability.VerificationStatusEnum.ToJsonValue(accountSupportingEntityCapability._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/ActiveNetworkTokensRestriction.cs b/Adyen/BalancePlatform/Models/ActiveNetworkTokensRestriction.cs new file mode 100644 index 000000000..c9a427d6d --- /dev/null +++ b/Adyen/BalancePlatform/Models/ActiveNetworkTokensRestriction.cs @@ -0,0 +1,195 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ActiveNetworkTokensRestriction. + /// + public partial class ActiveNetworkTokensRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// The number of tokens. + [JsonConstructor] + public ActiveNetworkTokensRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ActiveNetworkTokensRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The number of tokens. + /// + /// The number of tokens. + [JsonPropertyName("value")] + public int? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ActiveNetworkTokensRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ActiveNetworkTokensRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ActiveNetworkTokensRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class ActiveNetworkTokensRestriction.", nameof(operation)); + + return new ActiveNetworkTokensRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ActiveNetworkTokensRestriction activeNetworkTokensRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, activeNetworkTokensRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ActiveNetworkTokensRestriction activeNetworkTokensRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (activeNetworkTokensRestriction.Operation != null) + writer.WriteString("operation", activeNetworkTokensRestriction.Operation); + + if (activeNetworkTokensRestriction._ValueOption.IsSet) + writer.WriteNumber("value", activeNetworkTokensRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AdditionalBankIdentification.cs b/Adyen/BalancePlatform/Models/AdditionalBankIdentification.cs new file mode 100644 index 000000000..2b0f15db8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AdditionalBankIdentification.cs @@ -0,0 +1,326 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AdditionalBankIdentification. + /// + public partial class AdditionalBankIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the additional bank identification. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConstructor] + public AdditionalBankIdentification(Option code = default, Option type = default) + { + _CodeOption = code; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalBankIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuBsbCode - auBsbCode + /// + public static readonly TypeEnum AuBsbCode = new("auBsbCode"); + + /// + /// TypeEnum.CaRoutingNumber - caRoutingNumber + /// + public static readonly TypeEnum CaRoutingNumber = new("caRoutingNumber"); + + /// + /// TypeEnum.GbSortCode - gbSortCode + /// + public static readonly TypeEnum GbSortCode = new("gbSortCode"); + + /// + /// TypeEnum.UsRoutingNumber - usRoutingNumber + /// + public static readonly TypeEnum UsRoutingNumber = new("usRoutingNumber"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auBsbCode" => TypeEnum.AuBsbCode, + "caRoutingNumber" => TypeEnum.CaRoutingNumber, + "gbSortCode" => TypeEnum.GbSortCode, + "usRoutingNumber" => TypeEnum.UsRoutingNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuBsbCode) + return "auBsbCode"; + + if (value == TypeEnum.CaRoutingNumber) + return "caRoutingNumber"; + + if (value == TypeEnum.GbSortCode) + return "gbSortCode"; + + if (value == TypeEnum.UsRoutingNumber) + return "usRoutingNumber"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The value of the additional bank identification. + /// + /// The value of the additional bank identification. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalBankIdentification {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalBankIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalBankIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AdditionalBankIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AdditionalBankIdentification(code, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalBankIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalBankIdentification._CodeOption.IsSet) + if (additionalBankIdentification.Code != null) + writer.WriteString("code", additionalBankIdentification.Code); + + if (additionalBankIdentification._TypeOption.IsSet && additionalBankIdentification.Type != null) + { + string? typeRawValue = AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AdditionalBankIdentificationRequirement.cs b/Adyen/BalancePlatform/Models/AdditionalBankIdentificationRequirement.cs new file mode 100644 index 000000000..9b85c6c10 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AdditionalBankIdentificationRequirement.cs @@ -0,0 +1,443 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AdditionalBankIdentificationRequirement. + /// + public partial class AdditionalBankIdentificationRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// The description of the additional bank identification requirement. + /// **additionalBankIdentificationRequirement** (default to TypeEnum.AdditionalBankIdentificationRequirement) + [JsonConstructor] + public AdditionalBankIdentificationRequirement(Option additionalBankIdentificationType = default, Option description = default, TypeEnum type = default) + { + _AdditionalBankIdentificationTypeOption = additionalBankIdentificationType; + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalBankIdentificationRequirement() + { + } + + partial void OnCreated(); + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConverter(typeof(AdditionalBankIdentificationTypeEnumJsonConverter))] + public class AdditionalBankIdentificationTypeEnum : IEnum + { + /// + /// Returns the value of the AdditionalBankIdentificationTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AdditionalBankIdentificationTypeEnum.AuBsbCode - auBsbCode + /// + public static readonly AdditionalBankIdentificationTypeEnum AuBsbCode = new("auBsbCode"); + + /// + /// AdditionalBankIdentificationTypeEnum.CaRoutingNumber - caRoutingNumber + /// + public static readonly AdditionalBankIdentificationTypeEnum CaRoutingNumber = new("caRoutingNumber"); + + /// + /// AdditionalBankIdentificationTypeEnum.GbSortCode - gbSortCode + /// + public static readonly AdditionalBankIdentificationTypeEnum GbSortCode = new("gbSortCode"); + + /// + /// AdditionalBankIdentificationTypeEnum.UsRoutingNumber - usRoutingNumber + /// + public static readonly AdditionalBankIdentificationTypeEnum UsRoutingNumber = new("usRoutingNumber"); + + private AdditionalBankIdentificationTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdditionalBankIdentificationTypeEnum?(string? value) => value == null ? null : new AdditionalBankIdentificationTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdditionalBankIdentificationTypeEnum? option) => option?.Value; + + public static bool operator ==(AdditionalBankIdentificationTypeEnum? left, AdditionalBankIdentificationTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdditionalBankIdentificationTypeEnum? left, AdditionalBankIdentificationTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdditionalBankIdentificationTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdditionalBankIdentificationTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auBsbCode" => AdditionalBankIdentificationTypeEnum.AuBsbCode, + "caRoutingNumber" => AdditionalBankIdentificationTypeEnum.CaRoutingNumber, + "gbSortCode" => AdditionalBankIdentificationTypeEnum.GbSortCode, + "usRoutingNumber" => AdditionalBankIdentificationTypeEnum.UsRoutingNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdditionalBankIdentificationTypeEnum? value) + { + if (value == null) + return null; + + if (value == AdditionalBankIdentificationTypeEnum.AuBsbCode) + return "auBsbCode"; + + if (value == AdditionalBankIdentificationTypeEnum.CaRoutingNumber) + return "caRoutingNumber"; + + if (value == AdditionalBankIdentificationTypeEnum.GbSortCode) + return "gbSortCode"; + + if (value == AdditionalBankIdentificationTypeEnum.UsRoutingNumber) + return "usRoutingNumber"; + + return null; + } + + /// + /// JsonConverter for writing AdditionalBankIdentificationTypeEnum. + /// + public class AdditionalBankIdentificationTypeEnumJsonConverter : JsonConverter + { + public override AdditionalBankIdentificationTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdditionalBankIdentificationTypeEnum.FromStringOrDefault(value) ?? new AdditionalBankIdentificationTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentificationTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdditionalBankIdentificationTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalBankIdentificationTypeOption { get; private set; } + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonPropertyName("additionalBankIdentificationType")] + public AdditionalBankIdentificationTypeEnum? AdditionalBankIdentificationType { get { return this._AdditionalBankIdentificationTypeOption; } set { this._AdditionalBankIdentificationTypeOption = new(value); } } + + /// + /// **additionalBankIdentificationRequirement** + /// + /// **additionalBankIdentificationRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AdditionalBankIdentificationRequirement - additionalBankIdentificationRequirement + /// + public static readonly TypeEnum AdditionalBankIdentificationRequirement = new("additionalBankIdentificationRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "additionalBankIdentificationRequirement" => TypeEnum.AdditionalBankIdentificationRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AdditionalBankIdentificationRequirement) + return "additionalBankIdentificationRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **additionalBankIdentificationRequirement** + /// + /// **additionalBankIdentificationRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the additional bank identification requirement. + /// + /// The description of the additional bank identification requirement. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalBankIdentificationRequirement {\n"); + sb.Append(" AdditionalBankIdentificationType: ").Append(AdditionalBankIdentificationType).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalBankIdentificationRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalBankIdentificationRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option additionalBankIdentificationType = default; + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalBankIdentificationType": + string? additionalBankIdentificationTypeRawValue = utf8JsonReader.GetString(); + additionalBankIdentificationType = new Option(AdditionalBankIdentificationRequirement.AdditionalBankIdentificationTypeEnum.FromStringOrDefault(additionalBankIdentificationTypeRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AdditionalBankIdentificationRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AdditionalBankIdentificationRequirement.", nameof(type)); + + return new AdditionalBankIdentificationRequirement(additionalBankIdentificationType, description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentificationRequirement additionalBankIdentificationRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalBankIdentificationRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalBankIdentificationRequirement additionalBankIdentificationRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalBankIdentificationRequirement._AdditionalBankIdentificationTypeOption.IsSet && additionalBankIdentificationRequirement.AdditionalBankIdentificationType != null) + { + string? additionalBankIdentificationTypeRawValue = AdditionalBankIdentificationRequirement.AdditionalBankIdentificationTypeEnum.ToJsonValue(additionalBankIdentificationRequirement._AdditionalBankIdentificationTypeOption.Value!.Value); + writer.WriteString("additionalBankIdentificationType", additionalBankIdentificationTypeRawValue); + } + + if (additionalBankIdentificationRequirement._DescriptionOption.IsSet) + if (additionalBankIdentificationRequirement.Description != null) + writer.WriteString("description", additionalBankIdentificationRequirement.Description); + + if (additionalBankIdentificationRequirement.Type != null) + { + string? typeRawValue = AdditionalBankIdentificationRequirement.TypeEnum.ToJsonValue(additionalBankIdentificationRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Address.cs b/Adyen/BalancePlatform/Models/Address.cs new file mode 100644 index 000000000..2d86eff07 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AddressRequirement.cs b/Adyen/BalancePlatform/Models/AddressRequirement.cs new file mode 100644 index 000000000..22e858607 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AddressRequirement.cs @@ -0,0 +1,449 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AddressRequirement. + /// + public partial class AddressRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the required address related fields for a particular route. + /// List of address fields. + /// **addressRequirement** (default to TypeEnum.AddressRequirement) + [JsonConstructor] + public AddressRequirement(Option description = default, Option?> requiredAddressFields = default, TypeEnum type = default) + { + _DescriptionOption = description; + _RequiredAddressFieldsOption = requiredAddressFields; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AddressRequirement() + { + } + + partial void OnCreated(); + + /// + /// Defines RequiredAddressFields. + /// + [JsonConverter(typeof(RequiredAddressFieldsEnumJsonConverter))] + public class RequiredAddressFieldsEnum : IEnum + { + /// + /// Returns the value of the RequiredAddressFieldsEnum. + /// + public string? Value { get; set; } + + /// + /// RequiredAddressFieldsEnum.City - city + /// + public static readonly RequiredAddressFieldsEnum City = new("city"); + + /// + /// RequiredAddressFieldsEnum.Country - country + /// + public static readonly RequiredAddressFieldsEnum Country = new("country"); + + /// + /// RequiredAddressFieldsEnum.Line1 - line1 + /// + public static readonly RequiredAddressFieldsEnum Line1 = new("line1"); + + /// + /// RequiredAddressFieldsEnum.PostalCode - postalCode + /// + public static readonly RequiredAddressFieldsEnum PostalCode = new("postalCode"); + + /// + /// RequiredAddressFieldsEnum.StateOrProvince - stateOrProvince + /// + public static readonly RequiredAddressFieldsEnum StateOrProvince = new("stateOrProvince"); + + private RequiredAddressFieldsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequiredAddressFieldsEnum?(string? value) => value == null ? null : new RequiredAddressFieldsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequiredAddressFieldsEnum? option) => option?.Value; + + public static bool operator ==(RequiredAddressFieldsEnum? left, RequiredAddressFieldsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequiredAddressFieldsEnum? left, RequiredAddressFieldsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequiredAddressFieldsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequiredAddressFieldsEnum? FromStringOrDefault(string value) + { + return value switch { + "city" => RequiredAddressFieldsEnum.City, + "country" => RequiredAddressFieldsEnum.Country, + "line1" => RequiredAddressFieldsEnum.Line1, + "postalCode" => RequiredAddressFieldsEnum.PostalCode, + "stateOrProvince" => RequiredAddressFieldsEnum.StateOrProvince, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequiredAddressFieldsEnum? value) + { + if (value == null) + return null; + + if (value == RequiredAddressFieldsEnum.City) + return "city"; + + if (value == RequiredAddressFieldsEnum.Country) + return "country"; + + if (value == RequiredAddressFieldsEnum.Line1) + return "line1"; + + if (value == RequiredAddressFieldsEnum.PostalCode) + return "postalCode"; + + if (value == RequiredAddressFieldsEnum.StateOrProvince) + return "stateOrProvince"; + + return null; + } + + /// + /// JsonConverter for writing RequiredAddressFieldsEnum. + /// + public class RequiredAddressFieldsEnumJsonConverter : JsonConverter + { + public override RequiredAddressFieldsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequiredAddressFieldsEnum.FromStringOrDefault(value) ?? new RequiredAddressFieldsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequiredAddressFieldsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequiredAddressFieldsEnum.ToJsonValue(value)); + } + } + } + + /// + /// **addressRequirement** + /// + /// **addressRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AddressRequirement - addressRequirement + /// + public static readonly TypeEnum AddressRequirement = new("addressRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "addressRequirement" => TypeEnum.AddressRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AddressRequirement) + return "addressRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **addressRequirement** + /// + /// **addressRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies the required address related fields for a particular route. + /// + /// Specifies the required address related fields for a particular route. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RequiredAddressFieldsOption { get; private set; } + + /// + /// List of address fields. + /// + /// List of address fields. + [JsonPropertyName("requiredAddressFields")] + public List? RequiredAddressFields { get { return this._RequiredAddressFieldsOption; } set { this._RequiredAddressFieldsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AddressRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" RequiredAddressFields: ").Append(RequiredAddressFields).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AddressRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option?> requiredAddressFields = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "requiredAddressFields": + requiredAddressFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AddressRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AddressRequirement.", nameof(type)); + + return new AddressRequirement(description, requiredAddressFields, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AddressRequirement addressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, addressRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AddressRequirement addressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (addressRequirement._DescriptionOption.IsSet) + if (addressRequirement.Description != null) + writer.WriteString("description", addressRequirement.Description); + + if (addressRequirement._RequiredAddressFieldsOption.IsSet) + { + writer.WritePropertyName("requiredAddressFields"); + JsonSerializer.Serialize(writer, addressRequirement.RequiredAddressFields, jsonSerializerOptions); + } + if (addressRequirement.Type != null) + { + string? typeRawValue = AddressRequirement.TypeEnum.ToJsonValue(addressRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Amount.cs b/Adyen/BalancePlatform/Models/Amount.cs new file mode 100644 index 000000000..3f5d2beb8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Amount.cs @@ -0,0 +1,190 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AmountMinMaxRequirement.cs b/Adyen/BalancePlatform/Models/AmountMinMaxRequirement.cs new file mode 100644 index 000000000..c2afd0432 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AmountMinMaxRequirement.cs @@ -0,0 +1,342 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AmountMinMaxRequirement. + /// + public partial class AmountMinMaxRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the eligible amounts for a particular route. + /// Maximum amount. + /// Minimum amount. + /// **amountMinMaxRequirement** (default to TypeEnum.AmountMinMaxRequirement) + [JsonConstructor] + public AmountMinMaxRequirement(Option description = default, Option max = default, Option min = default, TypeEnum type = default) + { + _DescriptionOption = description; + _MaxOption = max; + _MinOption = min; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmountMinMaxRequirement() + { + } + + partial void OnCreated(); + + /// + /// **amountMinMaxRequirement** + /// + /// **amountMinMaxRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AmountMinMaxRequirement - amountMinMaxRequirement + /// + public static readonly TypeEnum AmountMinMaxRequirement = new("amountMinMaxRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "amountMinMaxRequirement" => TypeEnum.AmountMinMaxRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AmountMinMaxRequirement) + return "amountMinMaxRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **amountMinMaxRequirement** + /// + /// **amountMinMaxRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies the eligible amounts for a particular route. + /// + /// Specifies the eligible amounts for a particular route. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxOption { get; private set; } + + /// + /// Maximum amount. + /// + /// Maximum amount. + [JsonPropertyName("max")] + public long? Max { get { return this._MaxOption; } set { this._MaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MinOption { get; private set; } + + /// + /// Minimum amount. + /// + /// Minimum amount. + [JsonPropertyName("min")] + public long? Min { get { return this._MinOption; } set { this._MinOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmountMinMaxRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Max: ").Append(Max).Append("\n"); + sb.Append(" Min: ").Append(Min).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountMinMaxRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmountMinMaxRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option max = default; + Option min = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "max": + max = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "min": + min = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AmountMinMaxRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AmountMinMaxRequirement.", nameof(type)); + + return new AmountMinMaxRequirement(description, max, min, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmountMinMaxRequirement amountMinMaxRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amountMinMaxRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmountMinMaxRequirement amountMinMaxRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (amountMinMaxRequirement._DescriptionOption.IsSet) + if (amountMinMaxRequirement.Description != null) + writer.WriteString("description", amountMinMaxRequirement.Description); + + if (amountMinMaxRequirement._MaxOption.IsSet) + writer.WriteNumber("max", amountMinMaxRequirement._MaxOption.Value!.Value); + + if (amountMinMaxRequirement._MinOption.IsSet) + writer.WriteNumber("min", amountMinMaxRequirement._MinOption.Value!.Value); + + if (amountMinMaxRequirement.Type != null) + { + string? typeRawValue = AmountMinMaxRequirement.TypeEnum.ToJsonValue(amountMinMaxRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AmountNonZeroDecimalsRequirement.cs b/Adyen/BalancePlatform/Models/AmountNonZeroDecimalsRequirement.cs new file mode 100644 index 000000000..636793211 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AmountNonZeroDecimalsRequirement.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AmountNonZeroDecimalsRequirement. + /// + public partial class AmountNonZeroDecimalsRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies for which routes the amount in a transfer request must have no non-zero decimal places, so the transfer can only be processed if the amount consists of round numbers. + /// **amountNonZeroDecimalsRequirement** (default to TypeEnum.AmountNonZeroDecimalsRequirement) + [JsonConstructor] + public AmountNonZeroDecimalsRequirement(Option description = default, TypeEnum type = default) + { + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmountNonZeroDecimalsRequirement() + { + } + + partial void OnCreated(); + + /// + /// **amountNonZeroDecimalsRequirement** + /// + /// **amountNonZeroDecimalsRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AmountNonZeroDecimalsRequirement - amountNonZeroDecimalsRequirement + /// + public static readonly TypeEnum AmountNonZeroDecimalsRequirement = new("amountNonZeroDecimalsRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "amountNonZeroDecimalsRequirement" => TypeEnum.AmountNonZeroDecimalsRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AmountNonZeroDecimalsRequirement) + return "amountNonZeroDecimalsRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **amountNonZeroDecimalsRequirement** + /// + /// **amountNonZeroDecimalsRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies for which routes the amount in a transfer request must have no non-zero decimal places, so the transfer can only be processed if the amount consists of round numbers. + /// + /// Specifies for which routes the amount in a transfer request must have no non-zero decimal places, so the transfer can only be processed if the amount consists of round numbers. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmountNonZeroDecimalsRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountNonZeroDecimalsRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmountNonZeroDecimalsRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AmountNonZeroDecimalsRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AmountNonZeroDecimalsRequirement.", nameof(type)); + + return new AmountNonZeroDecimalsRequirement(description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmountNonZeroDecimalsRequirement amountNonZeroDecimalsRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amountNonZeroDecimalsRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmountNonZeroDecimalsRequirement amountNonZeroDecimalsRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (amountNonZeroDecimalsRequirement._DescriptionOption.IsSet) + if (amountNonZeroDecimalsRequirement.Description != null) + writer.WriteString("description", amountNonZeroDecimalsRequirement.Description); + + if (amountNonZeroDecimalsRequirement.Type != null) + { + string? typeRawValue = AmountNonZeroDecimalsRequirement.TypeEnum.ToJsonValue(amountNonZeroDecimalsRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/ApproveAssociationRequest.cs b/Adyen/BalancePlatform/Models/ApproveAssociationRequest.cs new file mode 100644 index 000000000..111f690e2 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ApproveAssociationRequest.cs @@ -0,0 +1,244 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ApproveAssociationRequest. + /// + public partial class ApproveAssociationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the entity. + /// entityType + /// List of device ids associated to the entity that will be approved. + /// status + [JsonConstructor] + public ApproveAssociationRequest(string entityId, ScaEntityType entityType, List scaDeviceIds, AssociationStatus status) + { + EntityId = entityId; + EntityType = entityType; + ScaDeviceIds = scaDeviceIds; + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApproveAssociationRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("entityType")] + public ScaEntityType EntityType { get; set; } + + /// + /// . + /// + [JsonPropertyName("status")] + public AssociationStatus Status { get; set; } + + /// + /// The unique identifier of the entity. + /// + /// The unique identifier of the entity. + [JsonPropertyName("entityId")] + public string EntityId { get; set; } + + /// + /// List of device ids associated to the entity that will be approved. + /// + /// List of device ids associated to the entity that will be approved. + [JsonPropertyName("scaDeviceIds")] + public List ScaDeviceIds { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApproveAssociationRequest {\n"); + sb.Append(" EntityId: ").Append(EntityId).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" ScaDeviceIds: ").Append(ScaDeviceIds).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EntityId (string) maxLength + if (this.EntityId != null && this.EntityId.Length > 100) + { + yield return new ValidationResult("Invalid value for EntityId, length must be less than 100.", new [] { "EntityId" }); + } + + // EntityId (string) minLength + if (this.EntityId != null && this.EntityId.Length < 1) + { + yield return new ValidationResult("Invalid value for EntityId, length must be greater than 1.", new [] { "EntityId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApproveAssociationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApproveAssociationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entityId = default; + Option entityType = default; + Option?> scaDeviceIds = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entityId": + entityId = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + if (entityTypeRawValue != null) + entityType = new Option(ScaEntityTypeValueConverter.FromStringOrDefault(entityTypeRawValue)); + break; + case "scaDeviceIds": + scaDeviceIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(AssociationStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!entityId.IsSet) + throw new ArgumentException("Property is required for class ApproveAssociationRequest.", nameof(entityId)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class ApproveAssociationRequest.", nameof(entityType)); + + if (!scaDeviceIds.IsSet) + throw new ArgumentException("Property is required for class ApproveAssociationRequest.", nameof(scaDeviceIds)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ApproveAssociationRequest.", nameof(status)); + + return new ApproveAssociationRequest(entityId.Value!, entityType.Value!.Value!, scaDeviceIds.Value!, status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApproveAssociationRequest approveAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, approveAssociationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApproveAssociationRequest approveAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (approveAssociationRequest.EntityId != null) + writer.WriteString("entityId", approveAssociationRequest.EntityId); + + var entityTypeRawValue = ScaEntityTypeValueConverter.ToJsonValue(approveAssociationRequest.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + + writer.WritePropertyName("scaDeviceIds"); + JsonSerializer.Serialize(writer, approveAssociationRequest.ScaDeviceIds, jsonSerializerOptions); + var statusRawValue = AssociationStatusValueConverter.ToJsonValue(approveAssociationRequest.Status); + writer.WriteString("status", statusRawValue); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ApproveAssociationResponse.cs b/Adyen/BalancePlatform/Models/ApproveAssociationResponse.cs new file mode 100644 index 000000000..993f1dbc3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ApproveAssociationResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ApproveAssociationResponse. + /// + public partial class ApproveAssociationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of associations. + [JsonConstructor] + public ApproveAssociationResponse(List scaAssociations) + { + ScaAssociations = scaAssociations; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApproveAssociationResponse() + { + } + + partial void OnCreated(); + + /// + /// The list of associations. + /// + /// The list of associations. + [JsonPropertyName("scaAssociations")] + public List ScaAssociations { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApproveAssociationResponse {\n"); + sb.Append(" ScaAssociations: ").Append(ScaAssociations).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApproveAssociationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApproveAssociationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> scaAssociations = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "scaAssociations": + scaAssociations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!scaAssociations.IsSet) + throw new ArgumentException("Property is required for class ApproveAssociationResponse.", nameof(scaAssociations)); + + return new ApproveAssociationResponse(scaAssociations.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApproveAssociationResponse approveAssociationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, approveAssociationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApproveAssociationResponse approveAssociationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("scaAssociations"); + JsonSerializer.Serialize(writer, approveAssociationResponse.ScaAssociations, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ApproveTransferLimitRequest.cs b/Adyen/BalancePlatform/Models/ApproveTransferLimitRequest.cs new file mode 100644 index 000000000..e9dbe40e8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ApproveTransferLimitRequest.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ApproveTransferLimitRequest. + /// + public partial class ApproveTransferLimitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A list that includes the `transferLimitId` of all the pending transfer limits you want to approve. + [JsonConstructor] + public ApproveTransferLimitRequest(List transferLimitIds) + { + TransferLimitIds = transferLimitIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApproveTransferLimitRequest() + { + } + + partial void OnCreated(); + + /// + /// A list that includes the `transferLimitId` of all the pending transfer limits you want to approve. + /// + /// A list that includes the `transferLimitId` of all the pending transfer limits you want to approve. + [JsonPropertyName("transferLimitIds")] + public List TransferLimitIds { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApproveTransferLimitRequest {\n"); + sb.Append(" TransferLimitIds: ").Append(TransferLimitIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApproveTransferLimitRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApproveTransferLimitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transferLimitIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferLimitIds": + transferLimitIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!transferLimitIds.IsSet) + throw new ArgumentException("Property is required for class ApproveTransferLimitRequest.", nameof(transferLimitIds)); + + return new ApproveTransferLimitRequest(transferLimitIds.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApproveTransferLimitRequest approveTransferLimitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, approveTransferLimitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApproveTransferLimitRequest approveTransferLimitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("transferLimitIds"); + JsonSerializer.Serialize(writer, approveTransferLimitRequest.TransferLimitIds, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Association.cs b/Adyen/BalancePlatform/Models/Association.cs new file mode 100644 index 000000000..dd0aa3b5e --- /dev/null +++ b/Adyen/BalancePlatform/Models/Association.cs @@ -0,0 +1,258 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Association. + /// + public partial class Association : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the entity. + /// entityType + /// The unique identifier for the SCA device. + /// status + [JsonConstructor] + public Association(string entityId, ScaEntityType entityType, string scaDeviceId, AssociationStatus status) + { + EntityId = entityId; + EntityType = entityType; + ScaDeviceId = scaDeviceId; + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Association() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("entityType")] + public ScaEntityType EntityType { get; set; } + + /// + /// . + /// + [JsonPropertyName("status")] + public AssociationStatus Status { get; set; } + + /// + /// The unique identifier of the entity. + /// + /// The unique identifier of the entity. + [JsonPropertyName("entityId")] + public string EntityId { get; set; } + + /// + /// The unique identifier for the SCA device. + /// + /// The unique identifier for the SCA device. + /* BSDR11111111111A1AAA1AAAAA1AA1 */ + [JsonPropertyName("scaDeviceId")] + public string ScaDeviceId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Association {\n"); + sb.Append(" EntityId: ").Append(EntityId).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" ScaDeviceId: ").Append(ScaDeviceId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EntityId (string) maxLength + if (this.EntityId != null && this.EntityId.Length > 100) + { + yield return new ValidationResult("Invalid value for EntityId, length must be less than 100.", new [] { "EntityId" }); + } + + // EntityId (string) minLength + if (this.EntityId != null && this.EntityId.Length < 1) + { + yield return new ValidationResult("Invalid value for EntityId, length must be greater than 1.", new [] { "EntityId" }); + } + + // ScaDeviceId (string) maxLength + if (this.ScaDeviceId != null && this.ScaDeviceId.Length > 30) + { + yield return new ValidationResult("Invalid value for ScaDeviceId, length must be less than 30.", new [] { "ScaDeviceId" }); + } + + // ScaDeviceId (string) minLength + if (this.ScaDeviceId != null && this.ScaDeviceId.Length < 30) + { + yield return new ValidationResult("Invalid value for ScaDeviceId, length must be greater than 30.", new [] { "ScaDeviceId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Association Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entityId = default; + Option entityType = default; + Option scaDeviceId = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entityId": + entityId = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + if (entityTypeRawValue != null) + entityType = new Option(ScaEntityTypeValueConverter.FromStringOrDefault(entityTypeRawValue)); + break; + case "scaDeviceId": + scaDeviceId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(AssociationStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!entityId.IsSet) + throw new ArgumentException("Property is required for class Association.", nameof(entityId)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class Association.", nameof(entityType)); + + if (!scaDeviceId.IsSet) + throw new ArgumentException("Property is required for class Association.", nameof(scaDeviceId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class Association.", nameof(status)); + + return new Association(entityId.Value!, entityType.Value!.Value!, scaDeviceId.Value!, status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Association association, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, association, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Association association, JsonSerializerOptions jsonSerializerOptions) + { + + if (association.EntityId != null) + writer.WriteString("entityId", association.EntityId); + + var entityTypeRawValue = ScaEntityTypeValueConverter.ToJsonValue(association.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + + if (association.ScaDeviceId != null) + writer.WriteString("scaDeviceId", association.ScaDeviceId); + + var statusRawValue = AssociationStatusValueConverter.ToJsonValue(association.Status); + writer.WriteString("status", statusRawValue); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationDelegatedAuthenticationData.cs b/Adyen/BalancePlatform/Models/AssociationDelegatedAuthenticationData.cs new file mode 100644 index 000000000..bb4110d21 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationDelegatedAuthenticationData.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationDelegatedAuthenticationData. + /// + public partial class AssociationDelegatedAuthenticationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A base64-encoded block with the data required to authenticate the request. You obtain this information by using our authentication SDK. + [JsonConstructor] + public AssociationDelegatedAuthenticationData(string sdkOutput) + { + SdkOutput = sdkOutput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationDelegatedAuthenticationData() + { + } + + partial void OnCreated(); + + /// + /// A base64-encoded block with the data required to authenticate the request. You obtain this information by using our authentication SDK. + /// + /// A base64-encoded block with the data required to authenticate the request. You obtain this information by using our authentication SDK. + [JsonPropertyName("sdkOutput")] + public string SdkOutput { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationDelegatedAuthenticationData {\n"); + sb.Append(" SdkOutput: ").Append(SdkOutput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkOutput (string) maxLength + if (this.SdkOutput != null && this.SdkOutput.Length > 20000) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be less than 20000.", new [] { "SdkOutput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationDelegatedAuthenticationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationDelegatedAuthenticationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkOutput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkOutput": + sdkOutput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!sdkOutput.IsSet) + throw new ArgumentException("Property is required for class AssociationDelegatedAuthenticationData.", nameof(sdkOutput)); + + return new AssociationDelegatedAuthenticationData(sdkOutput.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationDelegatedAuthenticationData associationDelegatedAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationDelegatedAuthenticationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationDelegatedAuthenticationData associationDelegatedAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (associationDelegatedAuthenticationData.SdkOutput != null) + writer.WriteString("sdkOutput", associationDelegatedAuthenticationData.SdkOutput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationFinaliseRequest.cs b/Adyen/BalancePlatform/Models/AssociationFinaliseRequest.cs new file mode 100644 index 000000000..99046c7ff --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationFinaliseRequest.cs @@ -0,0 +1,306 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationFinaliseRequest. + /// + public partial class AssociationFinaliseRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + /// strongCustomerAuthentication + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonConstructor] + public AssociationFinaliseRequest(List ids, AssociationDelegatedAuthenticationData strongCustomerAuthentication, TypeEnum type) + { + Ids = ids; + StrongCustomerAuthentication = strongCustomerAuthentication; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationFinaliseRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentInstrument - PaymentInstrument + /// + public static readonly TypeEnum PaymentInstrument = new("PaymentInstrument"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "PaymentInstrument" => TypeEnum.PaymentInstrument, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentInstrument) + return "PaymentInstrument"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + [JsonPropertyName("ids")] + public List Ids { get; set; } + + /// + /// . + /// + [JsonPropertyName("strongCustomerAuthentication")] + public AssociationDelegatedAuthenticationData StrongCustomerAuthentication { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationFinaliseRequest {\n"); + sb.Append(" Ids: ").Append(Ids).Append("\n"); + sb.Append(" StrongCustomerAuthentication: ").Append(StrongCustomerAuthentication).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationFinaliseRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationFinaliseRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> ids = default; + Option strongCustomerAuthentication = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ids": + ids = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "strongCustomerAuthentication": + strongCustomerAuthentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AssociationFinaliseRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!ids.IsSet) + throw new ArgumentException("Property is required for class AssociationFinaliseRequest.", nameof(ids)); + + if (!strongCustomerAuthentication.IsSet) + throw new ArgumentException("Property is required for class AssociationFinaliseRequest.", nameof(strongCustomerAuthentication)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AssociationFinaliseRequest.", nameof(type)); + + return new AssociationFinaliseRequest(ids.Value!, strongCustomerAuthentication.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationFinaliseRequest associationFinaliseRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationFinaliseRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationFinaliseRequest associationFinaliseRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("ids"); + JsonSerializer.Serialize(writer, associationFinaliseRequest.Ids, jsonSerializerOptions); + writer.WritePropertyName("strongCustomerAuthentication"); + JsonSerializer.Serialize(writer, associationFinaliseRequest.StrongCustomerAuthentication, jsonSerializerOptions); + if (associationFinaliseRequest.Type != null) + { + string? typeRawValue = AssociationFinaliseRequest.TypeEnum.ToJsonValue(associationFinaliseRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationFinaliseResponse.cs b/Adyen/BalancePlatform/Models/AssociationFinaliseResponse.cs new file mode 100644 index 000000000..81f8499b0 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationFinaliseResponse.cs @@ -0,0 +1,321 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationFinaliseResponse. + /// + public partial class AssociationFinaliseResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of resource that you associated with the SCA device. + /// The unique identifier of the SCA device you associated with a resource. + /// The list of unique identifiers of the resources that you associated with the SCA device. + [JsonConstructor] + public AssociationFinaliseResponse(TypeEnum type, Option deviceId = default, Option?> ids = default) + { + Type = type; + _DeviceIdOption = deviceId; + _IdsOption = ids; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationFinaliseResponse() + { + } + + partial void OnCreated(); + + /// + /// The type of resource that you associated with the SCA device. + /// + /// The type of resource that you associated with the SCA device. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PAYMENTINSTRUMENT - PAYMENT_INSTRUMENT + /// + public static readonly TypeEnum PAYMENTINSTRUMENT = new("PAYMENT_INSTRUMENT"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "PAYMENT_INSTRUMENT" => TypeEnum.PAYMENTINSTRUMENT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PAYMENTINSTRUMENT) + return "PAYMENT_INSTRUMENT"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of resource that you associated with the SCA device. + /// + /// The type of resource that you associated with the SCA device. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceIdOption { get; private set; } + + /// + /// The unique identifier of the SCA device you associated with a resource. + /// + /// The unique identifier of the SCA device you associated with a resource. + [JsonPropertyName("deviceId")] + public string? DeviceId { get { return this._DeviceIdOption; } set { this._DeviceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IdsOption { get; private set; } + + /// + /// The list of unique identifiers of the resources that you associated with the SCA device. + /// + /// The list of unique identifiers of the resources that you associated with the SCA device. + [JsonPropertyName("ids")] + public List? Ids { get { return this._IdsOption; } set { this._IdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationFinaliseResponse {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" DeviceId: ").Append(DeviceId).Append("\n"); + sb.Append(" Ids: ").Append(Ids).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationFinaliseResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationFinaliseResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option deviceId = default; + Option?> ids = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AssociationFinaliseResponse.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "deviceId": + deviceId = new Option(utf8JsonReader.GetString()!); + break; + case "ids": + ids = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AssociationFinaliseResponse.", nameof(type)); + + return new AssociationFinaliseResponse(type.Value!.Value!, deviceId, ids); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationFinaliseResponse associationFinaliseResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationFinaliseResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationFinaliseResponse associationFinaliseResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (associationFinaliseResponse.Type != null) + { + string? typeRawValue = AssociationFinaliseResponse.TypeEnum.ToJsonValue(associationFinaliseResponse.Type); + writer.WriteString("type", typeRawValue); + } + + if (associationFinaliseResponse._DeviceIdOption.IsSet) + if (associationFinaliseResponse.DeviceId != null) + writer.WriteString("deviceId", associationFinaliseResponse.DeviceId); + + if (associationFinaliseResponse._IdsOption.IsSet) + { + writer.WritePropertyName("ids"); + JsonSerializer.Serialize(writer, associationFinaliseResponse.Ids, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationInitiateRequest.cs b/Adyen/BalancePlatform/Models/AssociationInitiateRequest.cs new file mode 100644 index 000000000..1f1624c1d --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationInitiateRequest.cs @@ -0,0 +1,288 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationInitiateRequest. + /// + public partial class AssociationInitiateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonConstructor] + public AssociationInitiateRequest(List ids, TypeEnum type) + { + Ids = ids; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationInitiateRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentInstrument - PaymentInstrument + /// + public static readonly TypeEnum PaymentInstrument = new("PaymentInstrument"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "PaymentInstrument" => TypeEnum.PaymentInstrument, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentInstrument) + return "PaymentInstrument"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + /// + /// The type of resource that you are associating with the SCA device. Possible value: **PaymentInstrument** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + /// + /// The list of unique identifiers of the resources that you are associating with the SCA device. Maximum: 5 strings. + [JsonPropertyName("ids")] + public List Ids { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationInitiateRequest {\n"); + sb.Append(" Ids: ").Append(Ids).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationInitiateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationInitiateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> ids = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ids": + ids = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AssociationInitiateRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!ids.IsSet) + throw new ArgumentException("Property is required for class AssociationInitiateRequest.", nameof(ids)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AssociationInitiateRequest.", nameof(type)); + + return new AssociationInitiateRequest(ids.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationInitiateRequest associationInitiateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationInitiateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationInitiateRequest associationInitiateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("ids"); + JsonSerializer.Serialize(writer, associationInitiateRequest.Ids, jsonSerializerOptions); + if (associationInitiateRequest.Type != null) + { + string? typeRawValue = AssociationInitiateRequest.TypeEnum.ToJsonValue(associationInitiateRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationInitiateResponse.cs b/Adyen/BalancePlatform/Models/AssociationInitiateResponse.cs new file mode 100644 index 000000000..c56f16d04 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationInitiateResponse.cs @@ -0,0 +1,183 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationInitiateResponse. + /// + public partial class AssociationInitiateResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A string that you must pass to the authentication SDK to continue with the association process. + [JsonConstructor] + public AssociationInitiateResponse(Option sdkInput = default) + { + _SdkInputOption = sdkInput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationInitiateResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInputOption { get; private set; } + + /// + /// A string that you must pass to the authentication SDK to continue with the association process. + /// + /// A string that you must pass to the authentication SDK to continue with the association process. + [JsonPropertyName("sdkInput")] + public string? SdkInput { get { return this._SdkInputOption; } set { this._SdkInputOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationInitiateResponse {\n"); + sb.Append(" SdkInput: ").Append(SdkInput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkInput (string) maxLength + if (this.SdkInput != null && this.SdkInput.Length > 20000) + { + yield return new ValidationResult("Invalid value for SdkInput, length must be less than 20000.", new [] { "SdkInput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationInitiateResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationInitiateResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkInput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkInput": + sdkInput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AssociationInitiateResponse(sdkInput); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationInitiateResponse associationInitiateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationInitiateResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationInitiateResponse associationInitiateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (associationInitiateResponse._SdkInputOption.IsSet) + if (associationInitiateResponse.SdkInput != null) + writer.WriteString("sdkInput", associationInitiateResponse.SdkInput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationListing.cs b/Adyen/BalancePlatform/Models/AssociationListing.cs new file mode 100644 index 000000000..db421a852 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationListing.cs @@ -0,0 +1,340 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AssociationListing. + /// + public partial class AssociationListing : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date and time when the association was created. + /// The unique identifier of the entity. + /// entityType + /// The unique identifier of the SCA device. + /// scaDeviceType + /// status + /// The human-readable name for the SCA device that was registered. + [JsonConstructor] + public AssociationListing(DateTimeOffset createdAt, string entityId, ScaEntityType entityType, string scaDeviceId, ScaDeviceType scaDeviceType, AssociationStatus status, Option scaDeviceName = default) + { + CreatedAt = createdAt; + EntityId = entityId; + EntityType = entityType; + ScaDeviceId = scaDeviceId; + ScaDeviceType = scaDeviceType; + Status = status; + _ScaDeviceNameOption = scaDeviceName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AssociationListing() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("entityType")] + public ScaEntityType EntityType { get; set; } + + /// + /// . + /// + [JsonPropertyName("scaDeviceType")] + public ScaDeviceType ScaDeviceType { get; set; } + + /// + /// . + /// + [JsonPropertyName("status")] + public AssociationStatus Status { get; set; } + + /// + /// The date and time when the association was created. + /// + /// The date and time when the association was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// The unique identifier of the entity. + /// + /// The unique identifier of the entity. + [JsonPropertyName("entityId")] + public string EntityId { get; set; } + + /// + /// The unique identifier of the SCA device. + /// + /// The unique identifier of the SCA device. + /* BSDR11111111111A1AAA1AAAAA1AA1 */ + [JsonPropertyName("scaDeviceId")] + public string ScaDeviceId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaDeviceNameOption { get; private set; } + + /// + /// The human-readable name for the SCA device that was registered. + /// + /// The human-readable name for the SCA device that was registered. + [JsonPropertyName("scaDeviceName")] + public string? ScaDeviceName { get { return this._ScaDeviceNameOption; } set { this._ScaDeviceNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AssociationListing {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" EntityId: ").Append(EntityId).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" ScaDeviceId: ").Append(ScaDeviceId).Append("\n"); + sb.Append(" ScaDeviceType: ").Append(ScaDeviceType).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" ScaDeviceName: ").Append(ScaDeviceName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EntityId (string) maxLength + if (this.EntityId != null && this.EntityId.Length > 100) + { + yield return new ValidationResult("Invalid value for EntityId, length must be less than 100.", new [] { "EntityId" }); + } + + // EntityId (string) minLength + if (this.EntityId != null && this.EntityId.Length < 1) + { + yield return new ValidationResult("Invalid value for EntityId, length must be greater than 1.", new [] { "EntityId" }); + } + + // ScaDeviceId (string) maxLength + if (this.ScaDeviceId != null && this.ScaDeviceId.Length > 30) + { + yield return new ValidationResult("Invalid value for ScaDeviceId, length must be less than 30.", new [] { "ScaDeviceId" }); + } + + // ScaDeviceId (string) minLength + if (this.ScaDeviceId != null && this.ScaDeviceId.Length < 30) + { + yield return new ValidationResult("Invalid value for ScaDeviceId, length must be greater than 30.", new [] { "ScaDeviceId" }); + } + + // ScaDeviceName (string) maxLength + if (this.ScaDeviceName != null && this.ScaDeviceName.Length > 64) + { + yield return new ValidationResult("Invalid value for ScaDeviceName, length must be less than 64.", new [] { "ScaDeviceName" }); + } + + // ScaDeviceName (string) minLength + if (this.ScaDeviceName != null && this.ScaDeviceName.Length < 0) + { + yield return new ValidationResult("Invalid value for ScaDeviceName, length must be greater than 0.", new [] { "ScaDeviceName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AssociationListingJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AssociationListing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option entityId = default; + Option entityType = default; + Option scaDeviceId = default; + Option scaDeviceType = default; + Option status = default; + Option scaDeviceName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityId": + entityId = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + if (entityTypeRawValue != null) + entityType = new Option(ScaEntityTypeValueConverter.FromStringOrDefault(entityTypeRawValue)); + break; + case "scaDeviceId": + scaDeviceId = new Option(utf8JsonReader.GetString()!); + break; + case "scaDeviceType": + string? scaDeviceTypeRawValue = utf8JsonReader.GetString(); + if (scaDeviceTypeRawValue != null) + scaDeviceType = new Option(ScaDeviceTypeValueConverter.FromStringOrDefault(scaDeviceTypeRawValue)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(AssociationStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "scaDeviceName": + scaDeviceName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(createdAt)); + + if (!entityId.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(entityId)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(entityType)); + + if (!scaDeviceId.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(scaDeviceId)); + + if (!scaDeviceType.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(scaDeviceType)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AssociationListing.", nameof(status)); + + return new AssociationListing(createdAt.Value!.Value!, entityId.Value!, entityType.Value!.Value!, scaDeviceId.Value!, scaDeviceType.Value!.Value!, status.Value!.Value!, scaDeviceName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationListing associationListing, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, associationListing, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AssociationListing associationListing, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", associationListing.CreatedAt.ToString(CreatedAtFormat)); + + if (associationListing.EntityId != null) + writer.WriteString("entityId", associationListing.EntityId); + + var entityTypeRawValue = ScaEntityTypeValueConverter.ToJsonValue(associationListing.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + + if (associationListing.ScaDeviceId != null) + writer.WriteString("scaDeviceId", associationListing.ScaDeviceId); + + var scaDeviceTypeRawValue = ScaDeviceTypeValueConverter.ToJsonValue(associationListing.ScaDeviceType); + writer.WriteString("scaDeviceType", scaDeviceTypeRawValue); + + var statusRawValue = AssociationStatusValueConverter.ToJsonValue(associationListing.Status); + writer.WriteString("status", statusRawValue); + + if (associationListing._ScaDeviceNameOption.IsSet) + if (associationListing.ScaDeviceName != null) + writer.WriteString("scaDeviceName", associationListing.ScaDeviceName); + } + } +} diff --git a/Adyen/BalancePlatform/Models/AssociationStatus.cs b/Adyen/BalancePlatform/Models/AssociationStatus.cs new file mode 100644 index 000000000..3fa117ba3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AssociationStatus.cs @@ -0,0 +1,176 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Defines AssociationStatus + /// + public enum AssociationStatus + { + /// + /// Enum PendingApproval for value: pendingApproval + /// + PendingApproval = 1, + + /// + /// Enum Active for value: active + /// + Active = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class AssociationStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static AssociationStatus FromString(string value) + { + if (value.Equals("pendingApproval")) + return AssociationStatus.PendingApproval; + + if (value.Equals("active")) + return AssociationStatus.Active; + + throw new NotImplementedException($"Could not convert value to type AssociationStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static AssociationStatus? FromStringOrDefault(string value) + { + if (value.Equals("pendingApproval")) + return AssociationStatus.PendingApproval; + + if (value.Equals("active")) + return AssociationStatus.Active; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(AssociationStatus value) + { + if (value == AssociationStatus.PendingApproval) + return "pendingApproval"; + + if (value == AssociationStatus.Active) + return "active"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class AssociationStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override AssociationStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + AssociationStatus? result = rawValue == null + ? null + : AssociationStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the AssociationStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationStatus associationStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(AssociationStatusValueConverter.ToJsonValue(associationStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class AssociationStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a AssociationStatus from the Json object + /// + /// + /// + /// + /// + public override AssociationStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + AssociationStatus? result = rawValue == null + ? null + : AssociationStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the AssociationStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AssociationStatus? associationStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(associationStatus.HasValue ? AssociationStatusValueConverter.ToJsonValue(associationStatus.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Authentication.cs b/Adyen/BalancePlatform/Models/Authentication.cs new file mode 100644 index 000000000..479939c09 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Authentication.cs @@ -0,0 +1,240 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Authentication. + /// + public partial class Authentication : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address where the one-time password (OTP) is sent. + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + /// phone + [JsonConstructor] + public Authentication(Option email = default, Option password = default, Option phone = default) + { + _EmailOption = email; + _PasswordOption = password; + _PhoneOption = phone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Authentication() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address where the one-time password (OTP) is sent. + /// + /// The email address where the one-time password (OTP) is sent. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + /// + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public Phone? Phone { get { return this._PhoneOption; } set { this._PhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Authentication {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 30) + { + yield return new ValidationResult("Invalid value for Password, length must be less than 30.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 1) + { + yield return new ValidationResult("Invalid value for Password, length must be greater than 1.", new [] { "Password" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Authentication Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option password = default; + Option phone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Authentication(email, password, phone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Authentication authentication, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authentication, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Authentication authentication, JsonSerializerOptions jsonSerializerOptions) + { + + if (authentication._EmailOption.IsSet) + if (authentication.Email != null) + writer.WriteString("email", authentication.Email); + + if (authentication._PasswordOption.IsSet) + if (authentication.Password != null) + writer.WriteString("password", authentication.Password); + + if (authentication._PhoneOption.IsSet) + { + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, authentication.Phone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/AuthorisedCardUsers.cs b/Adyen/BalancePlatform/Models/AuthorisedCardUsers.cs new file mode 100644 index 000000000..e8424d9f7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/AuthorisedCardUsers.cs @@ -0,0 +1,179 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// AuthorisedCardUsers. + /// + public partial class AuthorisedCardUsers : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The legal entity IDs of the authorized card users linked to the specified payment instrument. + [JsonConstructor] + public AuthorisedCardUsers(Option?> legalEntityIds = default) + { + _LegalEntityIdsOption = legalEntityIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthorisedCardUsers() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LegalEntityIdsOption { get; private set; } + + /// + /// The legal entity IDs of the authorized card users linked to the specified payment instrument. + /// + /// The legal entity IDs of the authorized card users linked to the specified payment instrument. + [JsonPropertyName("legalEntityIds")] + public List? LegalEntityIds { get { return this._LegalEntityIdsOption; } set { this._LegalEntityIdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthorisedCardUsers {\n"); + sb.Append(" LegalEntityIds: ").Append(LegalEntityIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthorisedCardUsersJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthorisedCardUsers Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> legalEntityIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legalEntityIds": + legalEntityIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AuthorisedCardUsers(legalEntityIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthorisedCardUsers authorisedCardUsers, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authorisedCardUsers, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthorisedCardUsers authorisedCardUsers, JsonSerializerOptions jsonSerializerOptions) + { + + if (authorisedCardUsers._LegalEntityIdsOption.IsSet) + { + writer.WritePropertyName("legalEntityIds"); + JsonSerializer.Serialize(writer, authorisedCardUsers.LegalEntityIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BRLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/BRLocalAccountIdentification.cs new file mode 100644 index 000000000..eca148605 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BRLocalAccountIdentification.cs @@ -0,0 +1,402 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BRLocalAccountIdentification. + /// + public partial class BRLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 3-digit bank code, with leading zeros. + /// The bank account branch number, without separators or whitespace. + /// The 8-digit ISPB, with leading zeros. + /// **brLocal** (default to TypeEnum.BrLocal) + [JsonConstructor] + public BRLocalAccountIdentification(string accountNumber, string bankCode, string branchNumber, Option ispb = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + BranchNumber = branchNumber; + _IspbOption = ispb; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BRLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BrLocal - brLocal + /// + public static readonly TypeEnum BrLocal = new("brLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "brLocal" => TypeEnum.BrLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BrLocal) + return "brLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit bank code, with leading zeros. + /// + /// The 3-digit bank code, with leading zeros. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// The bank account branch number, without separators or whitespace. + /// + /// The bank account branch number, without separators or whitespace. + [JsonPropertyName("branchNumber")] + public string BranchNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IspbOption { get; private set; } + + /// + /// The 8-digit ISPB, with leading zeros. + /// + /// The 8-digit ISPB, with leading zeros. + [JsonPropertyName("ispb")] + public string? Ispb { get { return this._IspbOption; } set { this._IspbOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BRLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" BranchNumber: ").Append(BranchNumber).Append("\n"); + sb.Append(" Ispb: ").Append(Ispb).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 1.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 3.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 3.", new [] { "BankCode" }); + } + + // BranchNumber (string) maxLength + if (this.BranchNumber != null && this.BranchNumber.Length > 4) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be less than 4.", new [] { "BranchNumber" }); + } + + // BranchNumber (string) minLength + if (this.BranchNumber != null && this.BranchNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be greater than 1.", new [] { "BranchNumber" }); + } + + // Ispb (string) maxLength + if (this.Ispb != null && this.Ispb.Length > 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be less than 8.", new [] { "Ispb" }); + } + + // Ispb (string) minLength + if (this.Ispb != null && this.Ispb.Length < 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be greater than 8.", new [] { "Ispb" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BRLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BRLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option branchNumber = default; + Option ispb = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "branchNumber": + branchNumber = new Option(utf8JsonReader.GetString()!); + break; + case "ispb": + ispb = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BRLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(bankCode)); + + if (!branchNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(branchNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(type)); + + return new BRLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, branchNumber.Value!, ispb, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bRLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (bRLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", bRLocalAccountIdentification.AccountNumber); + + if (bRLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", bRLocalAccountIdentification.BankCode); + + if (bRLocalAccountIdentification.BranchNumber != null) + writer.WriteString("branchNumber", bRLocalAccountIdentification.BranchNumber); + + if (bRLocalAccountIdentification._IspbOption.IsSet) + if (bRLocalAccountIdentification.Ispb != null) + writer.WriteString("ispb", bRLocalAccountIdentification.Ispb); + + if (bRLocalAccountIdentification.Type != null) + { + string? typeRawValue = BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Balance.cs b/Adyen/BalancePlatform/Models/Balance.cs new file mode 100644 index 000000000..2c0d6390e --- /dev/null +++ b/Adyen/BalancePlatform/Models/Balance.cs @@ -0,0 +1,252 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Balance. + /// + public partial class Balance : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The balance available for use. + /// The sum of the transactions that have already been settled. + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The balance currently held in reserve. + /// The sum of the transactions that will be settled in the future. + [JsonConstructor] + public Balance(long available, long varBalance, string currency, long reserved, Option pending = default) + { + Available = available; + VarBalance = varBalance; + Currency = currency; + Reserved = reserved; + _PendingOption = pending; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Balance() + { + } + + partial void OnCreated(); + + /// + /// The balance available for use. + /// + /// The balance available for use. + [JsonPropertyName("available")] + public long Available { get; set; } + + /// + /// The sum of the transactions that have already been settled. + /// + /// The sum of the transactions that have already been settled. + [JsonPropertyName("balance")] + public long VarBalance { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The balance currently held in reserve. + /// + /// The balance currently held in reserve. + [JsonPropertyName("reserved")] + public long Reserved { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PendingOption { get; private set; } + + /// + /// The sum of the transactions that will be settled in the future. + /// + /// The sum of the transactions that will be settled in the future. + [JsonPropertyName("pending")] + public long? Pending { get { return this._PendingOption; } set { this._PendingOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Balance {\n"); + sb.Append(" Available: ").Append(Available).Append("\n"); + sb.Append(" VarBalance: ").Append(VarBalance).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Reserved: ").Append(Reserved).Append("\n"); + sb.Append(" Pending: ").Append(Pending).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Balance Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option available = default; + Option varBalance = default; + Option currency = default; + Option reserved = default; + Option pending = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "available": + available = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "balance": + varBalance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "reserved": + reserved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "pending": + pending = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!available.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(available)); + + if (!varBalance.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(varBalance)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(currency)); + + if (!reserved.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(reserved)); + + return new Balance(available.Value!.Value!, varBalance.Value!.Value!, currency.Value!, reserved.Value!.Value!, pending); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Balance balance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balance, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Balance balance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("available", balance.Available); + + writer.WriteNumber("balance", balance.VarBalance); + + if (balance.Currency != null) + writer.WriteString("currency", balance.Currency); + + writer.WriteNumber("reserved", balance.Reserved); + + if (balance._PendingOption.IsSet) + writer.WriteNumber("pending", balance._PendingOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceAccount.cs b/Adyen/BalancePlatform/Models/BalanceAccount.cs new file mode 100644 index 000000000..a971277ee --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceAccount.cs @@ -0,0 +1,554 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceAccount. + /// + public partial class BalanceAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// The unique identifier of the balance account. + /// List of balances with the amount and currency. + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// platformPaymentConfiguration + /// Your reference for the balance account, maximum 150 characters. + /// The status of the balance account, set to **active** by default. + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public BalanceAccount(string accountHolderId, string id, Option?> balances = default, Option defaultCurrencyCode = default, Option description = default, Option?> metadata = default, Option migratedAccountCode = default, Option platformPaymentConfiguration = default, Option reference = default, Option status = default, Option timeZone = default) + { + AccountHolderId = accountHolderId; + Id = id; + _BalancesOption = balances; + _DefaultCurrencyCodeOption = defaultCurrencyCode; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountCodeOption = migratedAccountCode; + _PlatformPaymentConfigurationOption = platformPaymentConfiguration; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccount() + { + } + + partial void OnCreated(); + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// The unique identifier of the balance account. + /// + /// The unique identifier of the balance account. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BalancesOption { get; private set; } + + /// + /// List of balances with the amount and currency. + /// + /// List of balances with the amount and currency. + [JsonPropertyName("balances")] + public List? Balances { get { return this._BalancesOption; } set { this._BalancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultCurrencyCodeOption { get; private set; } + + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + [JsonPropertyName("defaultCurrencyCode")] + public string? DefaultCurrencyCode { get { return this._DefaultCurrencyCodeOption; } set { this._DefaultCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountCodeOption { get; } + + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountCode")] + public string? MigratedAccountCode { get { return this._MigratedAccountCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformPaymentConfiguration")] + public PlatformPaymentConfiguration? PlatformPaymentConfiguration { get { return this._PlatformPaymentConfigurationOption; } set { this._PlatformPaymentConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the balance account, maximum 150 characters. + /// + /// Your reference for the balance account, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccount {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" DefaultCurrencyCode: ").Append(DefaultCurrencyCode).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountCode: ").Append(MigratedAccountCode).Append("\n"); + sb.Append(" PlatformPaymentConfiguration: ").Append(PlatformPaymentConfiguration).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option id = default; + Option?> balances = default; + Option defaultCurrencyCode = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountCode = default; + Option platformPaymentConfiguration = default; + Option reference = default; + Option status = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "balances": + balances = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "defaultCurrencyCode": + defaultCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountCode": + migratedAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentConfiguration": + platformPaymentConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceAccount.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class BalanceAccount.", nameof(accountHolderId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BalanceAccount.", nameof(id)); + + return new BalanceAccount(accountHolderId.Value!, id.Value!, balances, defaultCurrencyCode, description, metadata, migratedAccountCode, platformPaymentConfiguration, reference, status, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccount balanceAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccount balanceAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccount.AccountHolderId != null) + writer.WriteString("accountHolderId", balanceAccount.AccountHolderId); + + if (balanceAccount.Id != null) + writer.WriteString("id", balanceAccount.Id); + + if (balanceAccount._BalancesOption.IsSet) + { + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, balanceAccount.Balances, jsonSerializerOptions); + } + if (balanceAccount._DefaultCurrencyCodeOption.IsSet) + if (balanceAccount.DefaultCurrencyCode != null) + writer.WriteString("defaultCurrencyCode", balanceAccount.DefaultCurrencyCode); + + if (balanceAccount._DescriptionOption.IsSet) + if (balanceAccount.Description != null) + writer.WriteString("description", balanceAccount.Description); + + if (balanceAccount._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceAccount.Metadata, jsonSerializerOptions); + } + if (balanceAccount._MigratedAccountCodeOption.IsSet) + if (balanceAccount.MigratedAccountCode != null) + writer.WriteString("migratedAccountCode", balanceAccount.MigratedAccountCode); + + if (balanceAccount._PlatformPaymentConfigurationOption.IsSet) + { + writer.WritePropertyName("platformPaymentConfiguration"); + JsonSerializer.Serialize(writer, balanceAccount.PlatformPaymentConfiguration, jsonSerializerOptions); + } + if (balanceAccount._ReferenceOption.IsSet) + if (balanceAccount.Reference != null) + writer.WriteString("reference", balanceAccount.Reference); + + if (balanceAccount._StatusOption.IsSet && balanceAccount.Status != null) + { + string? statusRawValue = BalanceAccount.StatusEnum.ToJsonValue(balanceAccount._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (balanceAccount._TimeZoneOption.IsSet) + if (balanceAccount.TimeZone != null) + writer.WriteString("timeZone", balanceAccount.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceAccountBase.cs b/Adyen/BalancePlatform/Models/BalanceAccountBase.cs new file mode 100644 index 000000000..aa2d6bd53 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceAccountBase.cs @@ -0,0 +1,528 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceAccountBase. + /// + public partial class BalanceAccountBase : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// The unique identifier of the balance account. + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// platformPaymentConfiguration + /// Your reference for the balance account, maximum 150 characters. + /// The status of the balance account, set to **active** by default. + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public BalanceAccountBase(string accountHolderId, string id, Option defaultCurrencyCode = default, Option description = default, Option?> metadata = default, Option migratedAccountCode = default, Option platformPaymentConfiguration = default, Option reference = default, Option status = default, Option timeZone = default) + { + AccountHolderId = accountHolderId; + Id = id; + _DefaultCurrencyCodeOption = defaultCurrencyCode; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountCodeOption = migratedAccountCode; + _PlatformPaymentConfigurationOption = platformPaymentConfiguration; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountBase() + { + } + + partial void OnCreated(); + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// The unique identifier of the balance account. + /// + /// The unique identifier of the balance account. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultCurrencyCodeOption { get; private set; } + + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + [JsonPropertyName("defaultCurrencyCode")] + public string? DefaultCurrencyCode { get { return this._DefaultCurrencyCodeOption; } set { this._DefaultCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountCodeOption { get; } + + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountCode")] + public string? MigratedAccountCode { get { return this._MigratedAccountCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformPaymentConfiguration")] + public PlatformPaymentConfiguration? PlatformPaymentConfiguration { get { return this._PlatformPaymentConfigurationOption; } set { this._PlatformPaymentConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the balance account, maximum 150 characters. + /// + /// Your reference for the balance account, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountBase {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" DefaultCurrencyCode: ").Append(DefaultCurrencyCode).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountCode: ").Append(MigratedAccountCode).Append("\n"); + sb.Append(" PlatformPaymentConfiguration: ").Append(PlatformPaymentConfiguration).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountBaseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountBase Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option id = default; + Option defaultCurrencyCode = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountCode = default; + Option platformPaymentConfiguration = default; + Option reference = default; + Option status = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "defaultCurrencyCode": + defaultCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountCode": + migratedAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentConfiguration": + platformPaymentConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceAccountBase.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountBase.", nameof(accountHolderId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountBase.", nameof(id)); + + return new BalanceAccountBase(accountHolderId.Value!, id.Value!, defaultCurrencyCode, description, metadata, migratedAccountCode, platformPaymentConfiguration, reference, status, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountBase balanceAccountBase, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountBase, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountBase balanceAccountBase, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccountBase.AccountHolderId != null) + writer.WriteString("accountHolderId", balanceAccountBase.AccountHolderId); + + if (balanceAccountBase.Id != null) + writer.WriteString("id", balanceAccountBase.Id); + + if (balanceAccountBase._DefaultCurrencyCodeOption.IsSet) + if (balanceAccountBase.DefaultCurrencyCode != null) + writer.WriteString("defaultCurrencyCode", balanceAccountBase.DefaultCurrencyCode); + + if (balanceAccountBase._DescriptionOption.IsSet) + if (balanceAccountBase.Description != null) + writer.WriteString("description", balanceAccountBase.Description); + + if (balanceAccountBase._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceAccountBase.Metadata, jsonSerializerOptions); + } + if (balanceAccountBase._MigratedAccountCodeOption.IsSet) + if (balanceAccountBase.MigratedAccountCode != null) + writer.WriteString("migratedAccountCode", balanceAccountBase.MigratedAccountCode); + + if (balanceAccountBase._PlatformPaymentConfigurationOption.IsSet) + { + writer.WritePropertyName("platformPaymentConfiguration"); + JsonSerializer.Serialize(writer, balanceAccountBase.PlatformPaymentConfiguration, jsonSerializerOptions); + } + if (balanceAccountBase._ReferenceOption.IsSet) + if (balanceAccountBase.Reference != null) + writer.WriteString("reference", balanceAccountBase.Reference); + + if (balanceAccountBase._StatusOption.IsSet && balanceAccountBase.Status != null) + { + string? statusRawValue = BalanceAccountBase.StatusEnum.ToJsonValue(balanceAccountBase._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (balanceAccountBase._TimeZoneOption.IsSet) + if (balanceAccountBase.TimeZone != null) + writer.WriteString("timeZone", balanceAccountBase.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceAccountInfo.cs b/Adyen/BalancePlatform/Models/BalanceAccountInfo.cs new file mode 100644 index 000000000..ed633d2de --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceAccountInfo.cs @@ -0,0 +1,359 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceAccountInfo. + /// + public partial class BalanceAccountInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// platformPaymentConfiguration + /// Your reference for the balance account, maximum 150 characters. + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public BalanceAccountInfo(string accountHolderId, Option defaultCurrencyCode = default, Option description = default, Option?> metadata = default, Option migratedAccountCode = default, Option platformPaymentConfiguration = default, Option reference = default, Option timeZone = default) + { + AccountHolderId = accountHolderId; + _DefaultCurrencyCodeOption = defaultCurrencyCode; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountCodeOption = migratedAccountCode; + _PlatformPaymentConfigurationOption = platformPaymentConfiguration; + _ReferenceOption = reference; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountInfo() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultCurrencyCodeOption { get; private set; } + + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + [JsonPropertyName("defaultCurrencyCode")] + public string? DefaultCurrencyCode { get { return this._DefaultCurrencyCodeOption; } set { this._DefaultCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountCodeOption { get; } + + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountCode")] + public string? MigratedAccountCode { get { return this._MigratedAccountCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformPaymentConfiguration")] + public PlatformPaymentConfiguration? PlatformPaymentConfiguration { get { return this._PlatformPaymentConfigurationOption; } set { this._PlatformPaymentConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the balance account, maximum 150 characters. + /// + /// Your reference for the balance account, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountInfo {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" DefaultCurrencyCode: ").Append(DefaultCurrencyCode).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountCode: ").Append(MigratedAccountCode).Append("\n"); + sb.Append(" PlatformPaymentConfiguration: ").Append(PlatformPaymentConfiguration).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option defaultCurrencyCode = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountCode = default; + Option platformPaymentConfiguration = default; + Option reference = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "defaultCurrencyCode": + defaultCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountCode": + migratedAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentConfiguration": + platformPaymentConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountInfo.", nameof(accountHolderId)); + + return new BalanceAccountInfo(accountHolderId.Value!, defaultCurrencyCode, description, metadata, migratedAccountCode, platformPaymentConfiguration, reference, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountInfo balanceAccountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountInfo balanceAccountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccountInfo.AccountHolderId != null) + writer.WriteString("accountHolderId", balanceAccountInfo.AccountHolderId); + + if (balanceAccountInfo._DefaultCurrencyCodeOption.IsSet) + if (balanceAccountInfo.DefaultCurrencyCode != null) + writer.WriteString("defaultCurrencyCode", balanceAccountInfo.DefaultCurrencyCode); + + if (balanceAccountInfo._DescriptionOption.IsSet) + if (balanceAccountInfo.Description != null) + writer.WriteString("description", balanceAccountInfo.Description); + + if (balanceAccountInfo._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceAccountInfo.Metadata, jsonSerializerOptions); + } + if (balanceAccountInfo._MigratedAccountCodeOption.IsSet) + if (balanceAccountInfo.MigratedAccountCode != null) + writer.WriteString("migratedAccountCode", balanceAccountInfo.MigratedAccountCode); + + if (balanceAccountInfo._PlatformPaymentConfigurationOption.IsSet) + { + writer.WritePropertyName("platformPaymentConfiguration"); + JsonSerializer.Serialize(writer, balanceAccountInfo.PlatformPaymentConfiguration, jsonSerializerOptions); + } + if (balanceAccountInfo._ReferenceOption.IsSet) + if (balanceAccountInfo.Reference != null) + writer.WriteString("reference", balanceAccountInfo.Reference); + + if (balanceAccountInfo._TimeZoneOption.IsSet) + if (balanceAccountInfo.TimeZone != null) + writer.WriteString("timeZone", balanceAccountInfo.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceAccountUpdateRequest.cs b/Adyen/BalancePlatform/Models/BalanceAccountUpdateRequest.cs new file mode 100644 index 000000000..3996579b7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceAccountUpdateRequest.cs @@ -0,0 +1,464 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceAccountUpdateRequest. + /// + public partial class BalanceAccountUpdateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// A human-readable description of the balance account. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// platformPaymentConfiguration + /// Your reference to the balance account. + /// The status of the balance account. Payment instruments linked to the balance account can only be used if the balance account status is **active**. Possible values: **active**, **closed**, **suspended**. + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public BalanceAccountUpdateRequest(Option accountHolderId = default, Option description = default, Option?> metadata = default, Option platformPaymentConfiguration = default, Option reference = default, Option status = default, Option timeZone = default) + { + _AccountHolderIdOption = accountHolderId; + _DescriptionOption = description; + _MetadataOption = metadata; + _PlatformPaymentConfigurationOption = platformPaymentConfiguration; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountUpdateRequest() + { + } + + partial void OnCreated(); + + /// + /// The status of the balance account. Payment instruments linked to the balance account can only be used if the balance account status is **active**. Possible values: **active**, **closed**, **suspended**. + /// + /// The status of the balance account. Payment instruments linked to the balance account can only be used if the balance account status is **active**. Possible values: **active**, **closed**, **suspended**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the balance account. Payment instruments linked to the balance account can only be used if the balance account status is **active**. Possible values: **active**, **closed**, **suspended**. + /// + /// The status of the balance account. Payment instruments linked to the balance account can only be used if the balance account status is **active**. Possible values: **active**, **closed**, **suspended**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderIdOption { get; private set; } + + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + [JsonPropertyName("accountHolderId")] + public string? AccountHolderId { get { return this._AccountHolderIdOption; } set { this._AccountHolderIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description of the balance account. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// + /// A human-readable description of the balance account. You can use this parameter to distinguish between multiple balance accounts under an account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformPaymentConfiguration")] + public PlatformPaymentConfiguration? PlatformPaymentConfiguration { get { return this._PlatformPaymentConfigurationOption; } set { this._PlatformPaymentConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference to the balance account. + /// + /// Your reference to the balance account. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountUpdateRequest {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" PlatformPaymentConfiguration: ").Append(PlatformPaymentConfiguration).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountUpdateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountUpdateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option description = default; + Option?> metadata = default; + Option platformPaymentConfiguration = default; + Option reference = default; + Option status = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformPaymentConfiguration": + platformPaymentConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceAccountUpdateRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalanceAccountUpdateRequest(accountHolderId, description, metadata, platformPaymentConfiguration, reference, status, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountUpdateRequest balanceAccountUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountUpdateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountUpdateRequest balanceAccountUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccountUpdateRequest._AccountHolderIdOption.IsSet) + if (balanceAccountUpdateRequest.AccountHolderId != null) + writer.WriteString("accountHolderId", balanceAccountUpdateRequest.AccountHolderId); + + if (balanceAccountUpdateRequest._DescriptionOption.IsSet) + if (balanceAccountUpdateRequest.Description != null) + writer.WriteString("description", balanceAccountUpdateRequest.Description); + + if (balanceAccountUpdateRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceAccountUpdateRequest.Metadata, jsonSerializerOptions); + } + if (balanceAccountUpdateRequest._PlatformPaymentConfigurationOption.IsSet) + { + writer.WritePropertyName("platformPaymentConfiguration"); + JsonSerializer.Serialize(writer, balanceAccountUpdateRequest.PlatformPaymentConfiguration, jsonSerializerOptions); + } + if (balanceAccountUpdateRequest._ReferenceOption.IsSet) + if (balanceAccountUpdateRequest.Reference != null) + writer.WriteString("reference", balanceAccountUpdateRequest.Reference); + + if (balanceAccountUpdateRequest._StatusOption.IsSet && balanceAccountUpdateRequest.Status != null) + { + string? statusRawValue = BalanceAccountUpdateRequest.StatusEnum.ToJsonValue(balanceAccountUpdateRequest._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (balanceAccountUpdateRequest._TimeZoneOption.IsSet) + if (balanceAccountUpdateRequest.TimeZone != null) + writer.WriteString("timeZone", balanceAccountUpdateRequest.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalancePlatform.cs b/Adyen/BalancePlatform/Models/BalancePlatform.cs new file mode 100644 index 000000000..d924c5ee9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalancePlatform.cs @@ -0,0 +1,227 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalancePlatform. + /// + public partial class BalancePlatform : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// Your description of the balance platform. + /// The status of the balance platform. Possible values: **Active**, **Inactive**, **Closed**, **Suspended**. + [JsonConstructor] + public BalancePlatform(string id, Option description = default, Option status = default) + { + Id = id; + _DescriptionOption = description; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatform() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description of the balance platform. + /// + /// Your description of the balance platform. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the balance platform. Possible values: **Active**, **Inactive**, **Closed**, **Suspended**. + /// + /// The status of the balance platform. Possible values: **Active**, **Inactive**, **Closed**, **Suspended**. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatform {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatform Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option description = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BalancePlatform.", nameof(id)); + + return new BalancePlatform(id.Value!, description, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatform balancePlatform, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatform, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatform balancePlatform, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatform.Id != null) + writer.WriteString("id", balancePlatform.Id); + + if (balancePlatform._DescriptionOption.IsSet) + if (balancePlatform.Description != null) + writer.WriteString("description", balancePlatform.Description); + + if (balancePlatform._StatusOption.IsSet) + if (balancePlatform.Status != null) + writer.WriteString("status", balancePlatform.Status); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceSweepConfigurationsResponse.cs b/Adyen/BalancePlatform/Models/BalanceSweepConfigurationsResponse.cs new file mode 100644 index 000000000..3e932b26e --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceSweepConfigurationsResponse.cs @@ -0,0 +1,209 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceSweepConfigurationsResponse. + /// + public partial class BalanceSweepConfigurationsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + /// List of sweeps associated with the balance account. + [JsonConstructor] + public BalanceSweepConfigurationsResponse(bool hasNext, bool hasPrevious, List sweeps) + { + HasNext = hasNext; + HasPrevious = hasPrevious; + Sweeps = sweeps; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceSweepConfigurationsResponse() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// List of sweeps associated with the balance account. + /// + /// List of sweeps associated with the balance account. + [JsonPropertyName("sweeps")] + public List Sweeps { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceSweepConfigurationsResponse {\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append(" Sweeps: ").Append(Sweeps).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceSweepConfigurationsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceSweepConfigurationsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option hasNext = default; + Option hasPrevious = default; + Option?> sweeps = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "sweeps": + sweeps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class BalanceSweepConfigurationsResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class BalanceSweepConfigurationsResponse.", nameof(hasPrevious)); + + if (!sweeps.IsSet) + throw new ArgumentException("Property is required for class BalanceSweepConfigurationsResponse.", nameof(sweeps)); + + return new BalanceSweepConfigurationsResponse(hasNext.Value!.Value!, hasPrevious.Value!.Value!, sweeps.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceSweepConfigurationsResponse balanceSweepConfigurationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceSweepConfigurationsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceSweepConfigurationsResponse balanceSweepConfigurationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("hasNext", balanceSweepConfigurationsResponse.HasNext); + + writer.WriteBoolean("hasPrevious", balanceSweepConfigurationsResponse.HasPrevious); + + writer.WritePropertyName("sweeps"); + JsonSerializer.Serialize(writer, balanceSweepConfigurationsResponse.Sweeps, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceWebhookSetting.cs b/Adyen/BalancePlatform/Models/BalanceWebhookSetting.cs new file mode 100644 index 000000000..e083c61d9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceWebhookSetting.cs @@ -0,0 +1,224 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceWebhookSetting. + /// + public partial class BalanceWebhookSetting : WebhookSetting, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The unique identifier of the webhook setting. + /// status + /// target + /// The list of settings and criteria for triggering the [balance webhook](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + [JsonConstructor] + public BalanceWebhookSetting(string currency, string id, string status, Target target, Option?> conditions = default) : base(currency, id, status, target) + { + _ConditionsOption = conditions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceWebhookSetting() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConditionsOption { get; private set; } + + /// + /// The list of settings and criteria for triggering the [balance webhook](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// The list of settings and criteria for triggering the [balance webhook](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + [JsonPropertyName("conditions")] + public List? Conditions { get { return this._ConditionsOption; } set { this._ConditionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceWebhookSetting {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" Conditions: ").Append(Conditions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class BalanceWebhookSettingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceWebhookSetting Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option id = default; + Option status = default; + Option target = default; + Option type = default; + Option?> conditions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "target": + target = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(SettingTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "conditions": + conditions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSetting.", nameof(currency)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSetting.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSetting.", nameof(status)); + + if (!target.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSetting.", nameof(target)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSetting.", nameof(type)); + + return new BalanceWebhookSetting(currency.Value!, id.Value!, status.Value!, target.Value!, conditions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceWebhookSetting balanceWebhookSetting, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceWebhookSetting, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceWebhookSetting balanceWebhookSetting, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceWebhookSetting.Currency != null) + writer.WriteString("currency", balanceWebhookSetting.Currency); + + if (balanceWebhookSetting.Id != null) + writer.WriteString("id", balanceWebhookSetting.Id); + + if (balanceWebhookSetting.Status != null) + writer.WriteString("status", balanceWebhookSetting.Status); + + writer.WritePropertyName("target"); + JsonSerializer.Serialize(writer, balanceWebhookSetting.Target, jsonSerializerOptions); + if (balanceWebhookSetting.Type != null) + writer.WriteString("type", SettingTypeValueConverter.ToJsonValue(balanceWebhookSetting.Type)); + + if (balanceWebhookSetting._ConditionsOption.IsSet) + { + writer.WritePropertyName("conditions"); + JsonSerializer.Serialize(writer, balanceWebhookSetting.Conditions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfo.cs b/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfo.cs new file mode 100644 index 000000000..37595ebf8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfo.cs @@ -0,0 +1,467 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceWebhookSettingInfo. + /// + public partial class BalanceWebhookSettingInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// target + /// The type of the webhook you are configuring. Set to **balance**. + /// The array of conditions a balance change must meet for Adyen to send the webhook. + [JsonConstructor] + public BalanceWebhookSettingInfo(string currency, StatusEnum status, Target target, TypeEnum type, Option?> conditions = default) + { + Currency = currency; + Status = status; + Target = target; + Type = type; + _ConditionsOption = conditions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceWebhookSettingInfo() + { + } + + partial void OnCreated(); + + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The type of the webhook you are configuring. Set to **balance**. + /// + /// The type of the webhook you are configuring. Set to **balance**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Balance - balance + /// + public static readonly TypeEnum Balance = new("balance"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balance" => TypeEnum.Balance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Balance) + return "balance"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the webhook you are configuring. Set to **balance**. + /// + /// The type of the webhook you are configuring. Set to **balance**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// . + /// + [JsonPropertyName("target")] + public Target Target { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConditionsOption { get; private set; } + + /// + /// The array of conditions a balance change must meet for Adyen to send the webhook. + /// + /// The array of conditions a balance change must meet for Adyen to send the webhook. + [JsonPropertyName("conditions")] + public List? Conditions { get { return this._ConditionsOption; } set { this._ConditionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceWebhookSettingInfo {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Target: ").Append(Target).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Conditions: ").Append(Conditions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 1) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 1.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceWebhookSettingInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceWebhookSettingInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option status = default; + Option target = default; + Option type = default; + Option?> conditions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceWebhookSettingInfo.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "target": + target = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceWebhookSettingInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "conditions": + conditions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSettingInfo.", nameof(currency)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSettingInfo.", nameof(status)); + + if (!target.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSettingInfo.", nameof(target)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceWebhookSettingInfo.", nameof(type)); + + return new BalanceWebhookSettingInfo(currency.Value!, status.Value!.Value!, target.Value!, type.Value!.Value!, conditions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceWebhookSettingInfo balanceWebhookSettingInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceWebhookSettingInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceWebhookSettingInfo balanceWebhookSettingInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceWebhookSettingInfo.Currency != null) + writer.WriteString("currency", balanceWebhookSettingInfo.Currency); + + if (balanceWebhookSettingInfo.Status != null) + { + string? statusRawValue = BalanceWebhookSettingInfo.StatusEnum.ToJsonValue(balanceWebhookSettingInfo.Status); + writer.WriteString("status", statusRawValue); + } + + writer.WritePropertyName("target"); + JsonSerializer.Serialize(writer, balanceWebhookSettingInfo.Target, jsonSerializerOptions); + if (balanceWebhookSettingInfo.Type != null) + { + string? typeRawValue = BalanceWebhookSettingInfo.TypeEnum.ToJsonValue(balanceWebhookSettingInfo.Type); + writer.WriteString("type", typeRawValue); + } + + if (balanceWebhookSettingInfo._ConditionsOption.IsSet) + { + writer.WritePropertyName("conditions"); + JsonSerializer.Serialize(writer, balanceWebhookSettingInfo.Conditions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfoUpdate.cs b/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfoUpdate.cs new file mode 100644 index 000000000..05cba1961 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BalanceWebhookSettingInfoUpdate.cs @@ -0,0 +1,487 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BalanceWebhookSettingInfoUpdate. + /// + public partial class BalanceWebhookSettingInfoUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The array of conditions a balance change must meet for Adyen to send the webhook. + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// target + /// The type of the webhook you are configuring. Set to **balance**. + [JsonConstructor] + public BalanceWebhookSettingInfoUpdate(Option?> conditions = default, Option currency = default, Option status = default, Option target = default, Option type = default) + { + _ConditionsOption = conditions; + _CurrencyOption = currency; + _StatusOption = status; + _TargetOption = target; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceWebhookSettingInfoUpdate() + { + } + + partial void OnCreated(); + + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + /// + /// The status of the webhook setting. Possible values: * **active**: You receive a balance webhook if any of the conditions in this setting are met. * **inactive**: You do not receive a balance webhook even if the conditions in this settings are met. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The type of the webhook you are configuring. Set to **balance**. + /// + /// The type of the webhook you are configuring. Set to **balance**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Balance - balance + /// + public static readonly TypeEnum Balance = new("balance"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balance" => TypeEnum.Balance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Balance) + return "balance"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the webhook you are configuring. Set to **balance**. + /// + /// The type of the webhook you are configuring. Set to **balance**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConditionsOption { get; private set; } + + /// + /// The array of conditions a balance change must meet for Adyen to send the webhook. + /// + /// The array of conditions a balance change must meet for Adyen to send the webhook. + [JsonPropertyName("conditions")] + public List? Conditions { get { return this._ConditionsOption; } set { this._ConditionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("target")] + public TargetUpdate? Target { get { return this._TargetOption; } set { this._TargetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceWebhookSettingInfoUpdate {\n"); + sb.Append(" Conditions: ").Append(Conditions).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Target: ").Append(Target).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 1) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 1.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceWebhookSettingInfoUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceWebhookSettingInfoUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> conditions = default; + Option currency = default; + Option status = default; + Option target = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "conditions": + conditions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceWebhookSettingInfoUpdate.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "target": + target = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceWebhookSettingInfoUpdate.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BalanceWebhookSettingInfoUpdate(conditions, currency, status, target, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceWebhookSettingInfoUpdate balanceWebhookSettingInfoUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceWebhookSettingInfoUpdate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceWebhookSettingInfoUpdate balanceWebhookSettingInfoUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceWebhookSettingInfoUpdate._ConditionsOption.IsSet) + { + writer.WritePropertyName("conditions"); + JsonSerializer.Serialize(writer, balanceWebhookSettingInfoUpdate.Conditions, jsonSerializerOptions); + } + if (balanceWebhookSettingInfoUpdate._CurrencyOption.IsSet) + if (balanceWebhookSettingInfoUpdate.Currency != null) + writer.WriteString("currency", balanceWebhookSettingInfoUpdate.Currency); + + if (balanceWebhookSettingInfoUpdate._StatusOption.IsSet && balanceWebhookSettingInfoUpdate.Status != null) + { + string? statusRawValue = BalanceWebhookSettingInfoUpdate.StatusEnum.ToJsonValue(balanceWebhookSettingInfoUpdate._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (balanceWebhookSettingInfoUpdate._TargetOption.IsSet) + { + writer.WritePropertyName("target"); + JsonSerializer.Serialize(writer, balanceWebhookSettingInfoUpdate.Target, jsonSerializerOptions); + } + if (balanceWebhookSettingInfoUpdate._TypeOption.IsSet && balanceWebhookSettingInfoUpdate.Type != null) + { + string? typeRawValue = BalanceWebhookSettingInfoUpdate.TypeEnum.ToJsonValue(balanceWebhookSettingInfoUpdate._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccount.cs b/Adyen/BalancePlatform/Models/BankAccount.cs new file mode 100644 index 000000000..1f09ca169 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccount.cs @@ -0,0 +1,170 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankAccount. + /// + public partial class BankAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountIdentification + [JsonConstructor] + public BankAccount(BankAccountAccountIdentification accountIdentification) + { + AccountIdentification = accountIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccount() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("accountIdentification")] + public BankAccountAccountIdentification AccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccount {\n"); + sb.Append(" AccountIdentification: ").Append(AccountIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountIdentification": + accountIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountIdentification.IsSet) + throw new ArgumentException("Property is required for class BankAccount.", nameof(accountIdentification)); + + return new BankAccount(accountIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountIdentification"); + JsonSerializer.Serialize(writer, bankAccount.AccountIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountAccountIdentification.cs b/Adyen/BalancePlatform/Models/BankAccountAccountIdentification.cs new file mode 100644 index 000000000..3e29590db --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountAccountIdentification.cs @@ -0,0 +1,565 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Contains the bank account details. The fields required in this object depend on the country of the bank account and the currency of the transfer.. + /// + public partial class BankAccountAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(AULocalAccountIdentification aULocalAccountIdentification) + { + AULocalAccountIdentification = aULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(BRLocalAccountIdentification bRLocalAccountIdentification) + { + BRLocalAccountIdentification = bRLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(CALocalAccountIdentification cALocalAccountIdentification) + { + CALocalAccountIdentification = cALocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(CZLocalAccountIdentification cZLocalAccountIdentification) + { + CZLocalAccountIdentification = cZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(DKLocalAccountIdentification dKLocalAccountIdentification) + { + DKLocalAccountIdentification = dKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(HKLocalAccountIdentification hKLocalAccountIdentification) + { + HKLocalAccountIdentification = hKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(HULocalAccountIdentification hULocalAccountIdentification) + { + HULocalAccountIdentification = hULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(NOLocalAccountIdentification nOLocalAccountIdentification) + { + NOLocalAccountIdentification = nOLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(NZLocalAccountIdentification nZLocalAccountIdentification) + { + NZLocalAccountIdentification = nZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(NumberAndBicAccountIdentification numberAndBicAccountIdentification) + { + NumberAndBicAccountIdentification = numberAndBicAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(PLLocalAccountIdentification pLLocalAccountIdentification) + { + PLLocalAccountIdentification = pLLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(SELocalAccountIdentification sELocalAccountIdentification) + { + SELocalAccountIdentification = sELocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(SGLocalAccountIdentification sGLocalAccountIdentification) + { + SGLocalAccountIdentification = sGLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(UKLocalAccountIdentification uKLocalAccountIdentification) + { + UKLocalAccountIdentification = uKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountAccountIdentification(USLocalAccountIdentification uSLocalAccountIdentification) + { + USLocalAccountIdentification = uSLocalAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AULocalAccountIdentification? AULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public BRLocalAccountIdentification? BRLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CALocalAccountIdentification? CALocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CZLocalAccountIdentification? CZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public DKLocalAccountIdentification? DKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HKLocalAccountIdentification? HKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HULocalAccountIdentification? HULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// .. + /// + public NOLocalAccountIdentification? NOLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NZLocalAccountIdentification? NZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NumberAndBicAccountIdentification? NumberAndBicAccountIdentification { get; set; } + + /// + /// .. + /// + public PLLocalAccountIdentification? PLLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SELocalAccountIdentification? SELocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SGLocalAccountIdentification? SGLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public UKLocalAccountIdentification? UKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public USLocalAccountIdentification? USLocalAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountAccountIdentification {\n"); + if (this.AULocalAccountIdentification != null) + sb.Append(AULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.BRLocalAccountIdentification != null) + sb.Append(BRLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CALocalAccountIdentification != null) + sb.Append(CALocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CZLocalAccountIdentification != null) + sb.Append(CZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.DKLocalAccountIdentification != null) + sb.Append(DKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HKLocalAccountIdentification != null) + sb.Append(HKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HULocalAccountIdentification != null) + sb.Append(HULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NOLocalAccountIdentification != null) + sb.Append(NOLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NZLocalAccountIdentification != null) + sb.Append(NZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NumberAndBicAccountIdentification != null) + sb.Append(NumberAndBicAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.PLLocalAccountIdentification != null) + sb.Append(PLLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SELocalAccountIdentification != null) + sb.Append(SELocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SGLocalAccountIdentification != null) + sb.Append(SGLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.UKLocalAccountIdentification != null) + sb.Append(UKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.USLocalAccountIdentification != null) + sb.Append(USLocalAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AULocalAccountIdentification? aULocalAccountIdentification = default; + BRLocalAccountIdentification? bRLocalAccountIdentification = default; + CALocalAccountIdentification? cALocalAccountIdentification = default; + CZLocalAccountIdentification? cZLocalAccountIdentification = default; + DKLocalAccountIdentification? dKLocalAccountIdentification = default; + HKLocalAccountIdentification? hKLocalAccountIdentification = default; + HULocalAccountIdentification? hULocalAccountIdentification = default; + IbanAccountIdentification? ibanAccountIdentification = default; + NOLocalAccountIdentification? nOLocalAccountIdentification = default; + NZLocalAccountIdentification? nZLocalAccountIdentification = default; + NumberAndBicAccountIdentification? numberAndBicAccountIdentification = default; + PLLocalAccountIdentification? pLLocalAccountIdentification = default; + SELocalAccountIdentification? sELocalAccountIdentification = default; + SGLocalAccountIdentification? sGLocalAccountIdentification = default; + UKLocalAccountIdentification? uKLocalAccountIdentification = default; + USLocalAccountIdentification? uSLocalAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAULocalAccountIdentification, jsonSerializerOptions, out aULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderBRLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBRLocalAccountIdentification, jsonSerializerOptions, out bRLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCALocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCALocalAccountIdentification, jsonSerializerOptions, out cALocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCZLocalAccountIdentification, jsonSerializerOptions, out cZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderDKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDKLocalAccountIdentification, jsonSerializerOptions, out dKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHKLocalAccountIdentification, jsonSerializerOptions, out hKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHULocalAccountIdentification, jsonSerializerOptions, out hULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + + Utf8JsonReader utf8JsonReaderNOLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNOLocalAccountIdentification, jsonSerializerOptions, out nOLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNZLocalAccountIdentification, jsonSerializerOptions, out nZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNumberAndBicAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumberAndBicAccountIdentification, jsonSerializerOptions, out numberAndBicAccountIdentification); + + Utf8JsonReader utf8JsonReaderPLLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPLLocalAccountIdentification, jsonSerializerOptions, out pLLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSELocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSELocalAccountIdentification, jsonSerializerOptions, out sELocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSGLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSGLocalAccountIdentification, jsonSerializerOptions, out sGLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUKLocalAccountIdentification, jsonSerializerOptions, out uKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUSLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSLocalAccountIdentification, jsonSerializerOptions, out uSLocalAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (aULocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(aULocalAccountIdentification); + + if (bRLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(bRLocalAccountIdentification); + + if (cALocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(cALocalAccountIdentification); + + if (cZLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(cZLocalAccountIdentification); + + if (dKLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(dKLocalAccountIdentification); + + if (hKLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(hKLocalAccountIdentification); + + if (hULocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(hULocalAccountIdentification); + + if (ibanAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(ibanAccountIdentification); + + if (nOLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(nOLocalAccountIdentification); + + if (nZLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(nZLocalAccountIdentification); + + if (numberAndBicAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(numberAndBicAccountIdentification); + + if (pLLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(pLLocalAccountIdentification); + + if (sELocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(sELocalAccountIdentification); + + if (sGLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(sGLocalAccountIdentification); + + if (uKLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(uKLocalAccountIdentification); + + if (uSLocalAccountIdentification?.Type != null) + return new BankAccountAccountIdentification(uSLocalAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountAccountIdentification bankAccountAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + if (bankAccountAccountIdentification.AULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.AULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.BRLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.BRLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.CALocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.CALocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.CZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.CZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.DKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.DKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.HKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.HKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.HULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.HULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.IbanAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.NOLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.NOLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.NZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.NZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.NumberAndBicAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.NumberAndBicAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.PLLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.PLLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.SELocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.SELocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.SGLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.SGLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.UKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.UKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountAccountIdentification.USLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountAccountIdentification.USLocalAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, bankAccountAccountIdentification, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountAccountIdentification bankAccountAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountDetails.cs b/Adyen/BalancePlatform/Models/BankAccountDetails.cs new file mode 100644 index 000000000..dd444d976 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountDetails.cs @@ -0,0 +1,346 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankAccountDetails. + /// + public partial class BankAccountDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to "checking") + /// The bank account branch number, without separators or whitespace + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. (default to "physical") + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **iban** or **usLocal** or **ukLocal** (default to "iban") + [JsonConstructor] + public BankAccountDetails(Option accountNumber = default, Option accountType = default, Option branchNumber = default, Option formFactor = default, Option iban = default, Option routingNumber = default, Option sortCode = default, string type = @"iban") + { + _AccountNumberOption = accountNumber; + _AccountTypeOption = accountType; + _BranchNumberOption = branchNumber; + _FormFactorOption = formFactor; + _IbanOption = iban; + _RoutingNumberOption = routingNumber; + _SortCodeOption = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountNumberOption { get; private set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string? AccountNumber { get { return this._AccountNumberOption; } set { this._AccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public string? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BranchNumberOption { get; private set; } + + /// + /// The bank account branch number, without separators or whitespace + /// + /// The bank account branch number, without separators or whitespace + [JsonPropertyName("branchNumber")] + public string? BranchNumber { get { return this._BranchNumberOption; } set { this._BranchNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FormFactorOption { get; private set; } + + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + [JsonPropertyName("formFactor")] + public string? FormFactor { get { return this._FormFactorOption; } set { this._FormFactorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RoutingNumberOption { get; private set; } + + /// + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string? RoutingNumber { get { return this._RoutingNumberOption; } set { this._RoutingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SortCodeOption { get; private set; } + + /// + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string? SortCode { get { return this._SortCodeOption; } set { this._SortCodeOption = new(value); } } + + /// + /// **iban** or **usLocal** or **ukLocal** + /// + /// **iban** or **usLocal** or **ukLocal** + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountDetails {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BranchNumber: ").Append(BranchNumber).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option accountType = default; + Option branchNumber = default; + Option formFactor = default; + Option iban = default; + Option routingNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + accountType = new Option(utf8JsonReader.GetString()!); + break; + case "branchNumber": + branchNumber = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + formFactor = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BankAccountDetails.", nameof(type)); + + return new BankAccountDetails(accountNumber, accountType, branchNumber, formFactor, iban, routingNumber, sortCode, type.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountDetails bankAccountDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountDetails bankAccountDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccountDetails._AccountNumberOption.IsSet) + if (bankAccountDetails.AccountNumber != null) + writer.WriteString("accountNumber", bankAccountDetails.AccountNumber); + + if (bankAccountDetails._AccountTypeOption.IsSet) + if (bankAccountDetails.AccountType != null) + writer.WriteString("accountType", bankAccountDetails.AccountType); + + if (bankAccountDetails._BranchNumberOption.IsSet) + if (bankAccountDetails.BranchNumber != null) + writer.WriteString("branchNumber", bankAccountDetails.BranchNumber); + + if (bankAccountDetails._FormFactorOption.IsSet) + if (bankAccountDetails.FormFactor != null) + writer.WriteString("formFactor", bankAccountDetails.FormFactor); + + if (bankAccountDetails._IbanOption.IsSet) + if (bankAccountDetails.Iban != null) + writer.WriteString("iban", bankAccountDetails.Iban); + + if (bankAccountDetails._RoutingNumberOption.IsSet) + if (bankAccountDetails.RoutingNumber != null) + writer.WriteString("routingNumber", bankAccountDetails.RoutingNumber); + + if (bankAccountDetails._SortCodeOption.IsSet) + if (bankAccountDetails.SortCode != null) + writer.WriteString("sortCode", bankAccountDetails.SortCode); + + if (bankAccountDetails.Type != null) + writer.WriteString("type", bankAccountDetails.Type); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountIdentificationTypeRequirement.cs b/Adyen/BalancePlatform/Models/BankAccountIdentificationTypeRequirement.cs new file mode 100644 index 000000000..853956b8a --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountIdentificationTypeRequirement.cs @@ -0,0 +1,557 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankAccountIdentificationTypeRequirement. + /// + public partial class BankAccountIdentificationTypeRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of bank account identification types: eg.; [iban , numberAndBic] + /// Specifies the bank account details for a particular route per required field in this object depending on the country of the bank account and the currency of the transfer. + /// **bankAccountIdentificationTypeRequirement** (default to TypeEnum.BankAccountIdentificationTypeRequirement) + [JsonConstructor] + public BankAccountIdentificationTypeRequirement(Option?> bankAccountIdentificationTypes = default, Option description = default, TypeEnum type = default) + { + _BankAccountIdentificationTypesOption = bankAccountIdentificationTypes; + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountIdentificationTypeRequirement() + { + } + + partial void OnCreated(); + + /// + /// Defines BankAccountIdentificationTypes. + /// + [JsonConverter(typeof(BankAccountIdentificationTypesEnumJsonConverter))] + public class BankAccountIdentificationTypesEnum : IEnum + { + /// + /// Returns the value of the BankAccountIdentificationTypesEnum. + /// + public string? Value { get; set; } + + /// + /// BankAccountIdentificationTypesEnum.AuLocal - auLocal + /// + public static readonly BankAccountIdentificationTypesEnum AuLocal = new("auLocal"); + + /// + /// BankAccountIdentificationTypesEnum.BrLocal - brLocal + /// + public static readonly BankAccountIdentificationTypesEnum BrLocal = new("brLocal"); + + /// + /// BankAccountIdentificationTypesEnum.CaLocal - caLocal + /// + public static readonly BankAccountIdentificationTypesEnum CaLocal = new("caLocal"); + + /// + /// BankAccountIdentificationTypesEnum.CzLocal - czLocal + /// + public static readonly BankAccountIdentificationTypesEnum CzLocal = new("czLocal"); + + /// + /// BankAccountIdentificationTypesEnum.DkLocal - dkLocal + /// + public static readonly BankAccountIdentificationTypesEnum DkLocal = new("dkLocal"); + + /// + /// BankAccountIdentificationTypesEnum.HkLocal - hkLocal + /// + public static readonly BankAccountIdentificationTypesEnum HkLocal = new("hkLocal"); + + /// + /// BankAccountIdentificationTypesEnum.HuLocal - huLocal + /// + public static readonly BankAccountIdentificationTypesEnum HuLocal = new("huLocal"); + + /// + /// BankAccountIdentificationTypesEnum.Iban - iban + /// + public static readonly BankAccountIdentificationTypesEnum Iban = new("iban"); + + /// + /// BankAccountIdentificationTypesEnum.Legacy - legacy + /// + public static readonly BankAccountIdentificationTypesEnum Legacy = new("legacy"); + + /// + /// BankAccountIdentificationTypesEnum.NoLocal - noLocal + /// + public static readonly BankAccountIdentificationTypesEnum NoLocal = new("noLocal"); + + /// + /// BankAccountIdentificationTypesEnum.NumberAndBic - numberAndBic + /// + public static readonly BankAccountIdentificationTypesEnum NumberAndBic = new("numberAndBic"); + + /// + /// BankAccountIdentificationTypesEnum.NzLocal - nzLocal + /// + public static readonly BankAccountIdentificationTypesEnum NzLocal = new("nzLocal"); + + /// + /// BankAccountIdentificationTypesEnum.PlLocal - plLocal + /// + public static readonly BankAccountIdentificationTypesEnum PlLocal = new("plLocal"); + + /// + /// BankAccountIdentificationTypesEnum.SeLocal - seLocal + /// + public static readonly BankAccountIdentificationTypesEnum SeLocal = new("seLocal"); + + /// + /// BankAccountIdentificationTypesEnum.SgLocal - sgLocal + /// + public static readonly BankAccountIdentificationTypesEnum SgLocal = new("sgLocal"); + + /// + /// BankAccountIdentificationTypesEnum.UkLocal - ukLocal + /// + public static readonly BankAccountIdentificationTypesEnum UkLocal = new("ukLocal"); + + /// + /// BankAccountIdentificationTypesEnum.UsLocal - usLocal + /// + public static readonly BankAccountIdentificationTypesEnum UsLocal = new("usLocal"); + + private BankAccountIdentificationTypesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BankAccountIdentificationTypesEnum?(string? value) => value == null ? null : new BankAccountIdentificationTypesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BankAccountIdentificationTypesEnum? option) => option?.Value; + + public static bool operator ==(BankAccountIdentificationTypesEnum? left, BankAccountIdentificationTypesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BankAccountIdentificationTypesEnum? left, BankAccountIdentificationTypesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BankAccountIdentificationTypesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BankAccountIdentificationTypesEnum? FromStringOrDefault(string value) + { + return value switch { + "auLocal" => BankAccountIdentificationTypesEnum.AuLocal, + "brLocal" => BankAccountIdentificationTypesEnum.BrLocal, + "caLocal" => BankAccountIdentificationTypesEnum.CaLocal, + "czLocal" => BankAccountIdentificationTypesEnum.CzLocal, + "dkLocal" => BankAccountIdentificationTypesEnum.DkLocal, + "hkLocal" => BankAccountIdentificationTypesEnum.HkLocal, + "huLocal" => BankAccountIdentificationTypesEnum.HuLocal, + "iban" => BankAccountIdentificationTypesEnum.Iban, + "legacy" => BankAccountIdentificationTypesEnum.Legacy, + "noLocal" => BankAccountIdentificationTypesEnum.NoLocal, + "numberAndBic" => BankAccountIdentificationTypesEnum.NumberAndBic, + "nzLocal" => BankAccountIdentificationTypesEnum.NzLocal, + "plLocal" => BankAccountIdentificationTypesEnum.PlLocal, + "seLocal" => BankAccountIdentificationTypesEnum.SeLocal, + "sgLocal" => BankAccountIdentificationTypesEnum.SgLocal, + "ukLocal" => BankAccountIdentificationTypesEnum.UkLocal, + "usLocal" => BankAccountIdentificationTypesEnum.UsLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BankAccountIdentificationTypesEnum? value) + { + if (value == null) + return null; + + if (value == BankAccountIdentificationTypesEnum.AuLocal) + return "auLocal"; + + if (value == BankAccountIdentificationTypesEnum.BrLocal) + return "brLocal"; + + if (value == BankAccountIdentificationTypesEnum.CaLocal) + return "caLocal"; + + if (value == BankAccountIdentificationTypesEnum.CzLocal) + return "czLocal"; + + if (value == BankAccountIdentificationTypesEnum.DkLocal) + return "dkLocal"; + + if (value == BankAccountIdentificationTypesEnum.HkLocal) + return "hkLocal"; + + if (value == BankAccountIdentificationTypesEnum.HuLocal) + return "huLocal"; + + if (value == BankAccountIdentificationTypesEnum.Iban) + return "iban"; + + if (value == BankAccountIdentificationTypesEnum.Legacy) + return "legacy"; + + if (value == BankAccountIdentificationTypesEnum.NoLocal) + return "noLocal"; + + if (value == BankAccountIdentificationTypesEnum.NumberAndBic) + return "numberAndBic"; + + if (value == BankAccountIdentificationTypesEnum.NzLocal) + return "nzLocal"; + + if (value == BankAccountIdentificationTypesEnum.PlLocal) + return "plLocal"; + + if (value == BankAccountIdentificationTypesEnum.SeLocal) + return "seLocal"; + + if (value == BankAccountIdentificationTypesEnum.SgLocal) + return "sgLocal"; + + if (value == BankAccountIdentificationTypesEnum.UkLocal) + return "ukLocal"; + + if (value == BankAccountIdentificationTypesEnum.UsLocal) + return "usLocal"; + + return null; + } + + /// + /// JsonConverter for writing BankAccountIdentificationTypesEnum. + /// + public class BankAccountIdentificationTypesEnumJsonConverter : JsonConverter + { + public override BankAccountIdentificationTypesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BankAccountIdentificationTypesEnum.FromStringOrDefault(value) ?? new BankAccountIdentificationTypesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BankAccountIdentificationTypesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BankAccountIdentificationTypesEnum.ToJsonValue(value)); + } + } + } + + /// + /// **bankAccountIdentificationTypeRequirement** + /// + /// **bankAccountIdentificationTypeRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccountIdentificationTypeRequirement - bankAccountIdentificationTypeRequirement + /// + public static readonly TypeEnum BankAccountIdentificationTypeRequirement = new("bankAccountIdentificationTypeRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccountIdentificationTypeRequirement" => TypeEnum.BankAccountIdentificationTypeRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccountIdentificationTypeRequirement) + return "bankAccountIdentificationTypeRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **bankAccountIdentificationTypeRequirement** + /// + /// **bankAccountIdentificationTypeRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BankAccountIdentificationTypesOption { get; private set; } + + /// + /// List of bank account identification types: eg.; [iban , numberAndBic] + /// + /// List of bank account identification types: eg.; [iban , numberAndBic] + [JsonPropertyName("bankAccountIdentificationTypes")] + public List? BankAccountIdentificationTypes { get { return this._BankAccountIdentificationTypesOption; } set { this._BankAccountIdentificationTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies the bank account details for a particular route per required field in this object depending on the country of the bank account and the currency of the transfer. + /// + /// Specifies the bank account details for a particular route per required field in this object depending on the country of the bank account and the currency of the transfer. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountIdentificationTypeRequirement {\n"); + sb.Append(" BankAccountIdentificationTypes: ").Append(BankAccountIdentificationTypes).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountIdentificationTypeRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountIdentificationTypeRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> bankAccountIdentificationTypes = default; + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountIdentificationTypes": + bankAccountIdentificationTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BankAccountIdentificationTypeRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BankAccountIdentificationTypeRequirement.", nameof(type)); + + return new BankAccountIdentificationTypeRequirement(bankAccountIdentificationTypes, description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountIdentificationTypeRequirement bankAccountIdentificationTypeRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountIdentificationTypeRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountIdentificationTypeRequirement bankAccountIdentificationTypeRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccountIdentificationTypeRequirement._BankAccountIdentificationTypesOption.IsSet) + { + writer.WritePropertyName("bankAccountIdentificationTypes"); + JsonSerializer.Serialize(writer, bankAccountIdentificationTypeRequirement.BankAccountIdentificationTypes, jsonSerializerOptions); + } + if (bankAccountIdentificationTypeRequirement._DescriptionOption.IsSet) + if (bankAccountIdentificationTypeRequirement.Description != null) + writer.WriteString("description", bankAccountIdentificationTypeRequirement.Description); + + if (bankAccountIdentificationTypeRequirement.Type != null) + { + string? typeRawValue = BankAccountIdentificationTypeRequirement.TypeEnum.ToJsonValue(bankAccountIdentificationTypeRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequest.cs b/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequest.cs new file mode 100644 index 000000000..78c600a26 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequest.cs @@ -0,0 +1,170 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankAccountIdentificationValidationRequest. + /// + public partial class BankAccountIdentificationValidationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountIdentification + [JsonConstructor] + public BankAccountIdentificationValidationRequest(BankAccountIdentificationValidationRequestAccountIdentification accountIdentification) + { + AccountIdentification = accountIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountIdentificationValidationRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("accountIdentification")] + public BankAccountIdentificationValidationRequestAccountIdentification AccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountIdentificationValidationRequest {\n"); + sb.Append(" AccountIdentification: ").Append(AccountIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountIdentificationValidationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountIdentificationValidationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountIdentification": + accountIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountIdentification.IsSet) + throw new ArgumentException("Property is required for class BankAccountIdentificationValidationRequest.", nameof(accountIdentification)); + + return new BankAccountIdentificationValidationRequest(accountIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountIdentificationValidationRequest bankAccountIdentificationValidationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountIdentificationValidationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountIdentificationValidationRequest bankAccountIdentificationValidationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountIdentification"); + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequest.AccountIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequestAccountIdentification.cs b/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequestAccountIdentification.cs new file mode 100644 index 000000000..8ef044899 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountIdentificationValidationRequestAccountIdentification.cs @@ -0,0 +1,565 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Bank account identification.. + /// + public partial class BankAccountIdentificationValidationRequestAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(AULocalAccountIdentification aULocalAccountIdentification) + { + AULocalAccountIdentification = aULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(BRLocalAccountIdentification bRLocalAccountIdentification) + { + BRLocalAccountIdentification = bRLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(CALocalAccountIdentification cALocalAccountIdentification) + { + CALocalAccountIdentification = cALocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(CZLocalAccountIdentification cZLocalAccountIdentification) + { + CZLocalAccountIdentification = cZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(DKLocalAccountIdentification dKLocalAccountIdentification) + { + DKLocalAccountIdentification = dKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(HKLocalAccountIdentification hKLocalAccountIdentification) + { + HKLocalAccountIdentification = hKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(HULocalAccountIdentification hULocalAccountIdentification) + { + HULocalAccountIdentification = hULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(NOLocalAccountIdentification nOLocalAccountIdentification) + { + NOLocalAccountIdentification = nOLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(NZLocalAccountIdentification nZLocalAccountIdentification) + { + NZLocalAccountIdentification = nZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(NumberAndBicAccountIdentification numberAndBicAccountIdentification) + { + NumberAndBicAccountIdentification = numberAndBicAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(PLLocalAccountIdentification pLLocalAccountIdentification) + { + PLLocalAccountIdentification = pLLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(SELocalAccountIdentification sELocalAccountIdentification) + { + SELocalAccountIdentification = sELocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(SGLocalAccountIdentification sGLocalAccountIdentification) + { + SGLocalAccountIdentification = sGLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(UKLocalAccountIdentification uKLocalAccountIdentification) + { + UKLocalAccountIdentification = uKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountIdentificationValidationRequestAccountIdentification(USLocalAccountIdentification uSLocalAccountIdentification) + { + USLocalAccountIdentification = uSLocalAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AULocalAccountIdentification? AULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public BRLocalAccountIdentification? BRLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CALocalAccountIdentification? CALocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CZLocalAccountIdentification? CZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public DKLocalAccountIdentification? DKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HKLocalAccountIdentification? HKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HULocalAccountIdentification? HULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// .. + /// + public NOLocalAccountIdentification? NOLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NZLocalAccountIdentification? NZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NumberAndBicAccountIdentification? NumberAndBicAccountIdentification { get; set; } + + /// + /// .. + /// + public PLLocalAccountIdentification? PLLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SELocalAccountIdentification? SELocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SGLocalAccountIdentification? SGLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public UKLocalAccountIdentification? UKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public USLocalAccountIdentification? USLocalAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountIdentificationValidationRequestAccountIdentification {\n"); + if (this.AULocalAccountIdentification != null) + sb.Append(AULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.BRLocalAccountIdentification != null) + sb.Append(BRLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CALocalAccountIdentification != null) + sb.Append(CALocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CZLocalAccountIdentification != null) + sb.Append(CZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.DKLocalAccountIdentification != null) + sb.Append(DKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HKLocalAccountIdentification != null) + sb.Append(HKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HULocalAccountIdentification != null) + sb.Append(HULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NOLocalAccountIdentification != null) + sb.Append(NOLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NZLocalAccountIdentification != null) + sb.Append(NZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NumberAndBicAccountIdentification != null) + sb.Append(NumberAndBicAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.PLLocalAccountIdentification != null) + sb.Append(PLLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SELocalAccountIdentification != null) + sb.Append(SELocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SGLocalAccountIdentification != null) + sb.Append(SGLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.UKLocalAccountIdentification != null) + sb.Append(UKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.USLocalAccountIdentification != null) + sb.Append(USLocalAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountIdentificationValidationRequestAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountIdentificationValidationRequestAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AULocalAccountIdentification? aULocalAccountIdentification = default; + BRLocalAccountIdentification? bRLocalAccountIdentification = default; + CALocalAccountIdentification? cALocalAccountIdentification = default; + CZLocalAccountIdentification? cZLocalAccountIdentification = default; + DKLocalAccountIdentification? dKLocalAccountIdentification = default; + HKLocalAccountIdentification? hKLocalAccountIdentification = default; + HULocalAccountIdentification? hULocalAccountIdentification = default; + IbanAccountIdentification? ibanAccountIdentification = default; + NOLocalAccountIdentification? nOLocalAccountIdentification = default; + NZLocalAccountIdentification? nZLocalAccountIdentification = default; + NumberAndBicAccountIdentification? numberAndBicAccountIdentification = default; + PLLocalAccountIdentification? pLLocalAccountIdentification = default; + SELocalAccountIdentification? sELocalAccountIdentification = default; + SGLocalAccountIdentification? sGLocalAccountIdentification = default; + UKLocalAccountIdentification? uKLocalAccountIdentification = default; + USLocalAccountIdentification? uSLocalAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAULocalAccountIdentification, jsonSerializerOptions, out aULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderBRLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBRLocalAccountIdentification, jsonSerializerOptions, out bRLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCALocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCALocalAccountIdentification, jsonSerializerOptions, out cALocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCZLocalAccountIdentification, jsonSerializerOptions, out cZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderDKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDKLocalAccountIdentification, jsonSerializerOptions, out dKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHKLocalAccountIdentification, jsonSerializerOptions, out hKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHULocalAccountIdentification, jsonSerializerOptions, out hULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + + Utf8JsonReader utf8JsonReaderNOLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNOLocalAccountIdentification, jsonSerializerOptions, out nOLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNZLocalAccountIdentification, jsonSerializerOptions, out nZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNumberAndBicAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumberAndBicAccountIdentification, jsonSerializerOptions, out numberAndBicAccountIdentification); + + Utf8JsonReader utf8JsonReaderPLLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPLLocalAccountIdentification, jsonSerializerOptions, out pLLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSELocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSELocalAccountIdentification, jsonSerializerOptions, out sELocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSGLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSGLocalAccountIdentification, jsonSerializerOptions, out sGLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUKLocalAccountIdentification, jsonSerializerOptions, out uKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUSLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSLocalAccountIdentification, jsonSerializerOptions, out uSLocalAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (aULocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(aULocalAccountIdentification); + + if (bRLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(bRLocalAccountIdentification); + + if (cALocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(cALocalAccountIdentification); + + if (cZLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(cZLocalAccountIdentification); + + if (dKLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(dKLocalAccountIdentification); + + if (hKLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(hKLocalAccountIdentification); + + if (hULocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(hULocalAccountIdentification); + + if (ibanAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(ibanAccountIdentification); + + if (nOLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(nOLocalAccountIdentification); + + if (nZLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(nZLocalAccountIdentification); + + if (numberAndBicAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(numberAndBicAccountIdentification); + + if (pLLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(pLLocalAccountIdentification); + + if (sELocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(sELocalAccountIdentification); + + if (sGLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(sGLocalAccountIdentification); + + if (uKLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(uKLocalAccountIdentification); + + if (uSLocalAccountIdentification?.Type != null) + return new BankAccountIdentificationValidationRequestAccountIdentification(uSLocalAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountIdentificationValidationRequestAccountIdentification bankAccountIdentificationValidationRequestAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + if (bankAccountIdentificationValidationRequestAccountIdentification.AULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.AULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.BRLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.BRLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.CALocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.CALocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.CZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.CZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.DKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.DKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.HKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.HKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.HULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.HULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.IbanAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.NOLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.NOLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.NZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.NZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.NumberAndBicAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.NumberAndBicAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.PLLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.PLLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.SELocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.SELocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.SGLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.SGLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.UKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.UKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountIdentificationValidationRequestAccountIdentification.USLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountIdentificationValidationRequestAccountIdentification.USLocalAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, bankAccountIdentificationValidationRequestAccountIdentification, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountIdentificationValidationRequestAccountIdentification bankAccountIdentificationValidationRequestAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankAccountModel.cs b/Adyen/BalancePlatform/Models/BankAccountModel.cs new file mode 100644 index 000000000..ef1ad79f5 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankAccountModel.cs @@ -0,0 +1,292 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankAccountModel. + /// + public partial class BankAccountModel : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. (default to FormFactorEnum.Physical) + [JsonConstructor] + public BankAccountModel(Option formFactor = default) + { + _FormFactorOption = formFactor; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountModel() + { + } + + partial void OnCreated(); + + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + [JsonConverter(typeof(FormFactorEnumJsonConverter))] + public class FormFactorEnum : IEnum + { + /// + /// Returns the value of the FormFactorEnum. + /// + public string? Value { get; set; } + + /// + /// FormFactorEnum.Physical - physical + /// + public static readonly FormFactorEnum Physical = new("physical"); + + /// + /// FormFactorEnum.Unknown - unknown + /// + public static readonly FormFactorEnum Unknown = new("unknown"); + + /// + /// FormFactorEnum.Virtual - virtual + /// + public static readonly FormFactorEnum Virtual = new("virtual"); + + private FormFactorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FormFactorEnum?(string? value) => value == null ? null : new FormFactorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FormFactorEnum? option) => option?.Value; + + public static bool operator ==(FormFactorEnum? left, FormFactorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FormFactorEnum? left, FormFactorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FormFactorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FormFactorEnum? FromStringOrDefault(string value) + { + return value switch { + "physical" => FormFactorEnum.Physical, + "unknown" => FormFactorEnum.Unknown, + "virtual" => FormFactorEnum.Virtual, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FormFactorEnum? value) + { + if (value == null) + return null; + + if (value == FormFactorEnum.Physical) + return "physical"; + + if (value == FormFactorEnum.Unknown) + return "unknown"; + + if (value == FormFactorEnum.Virtual) + return "virtual"; + + return null; + } + + /// + /// JsonConverter for writing FormFactorEnum. + /// + public class FormFactorEnumJsonConverter : JsonConverter + { + public override FormFactorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FormFactorEnum.FromStringOrDefault(value) ?? new FormFactorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FormFactorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FormFactorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FormFactorOption { get; private set; } + + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + [JsonPropertyName("formFactor")] + public FormFactorEnum? FormFactor { get { return this._FormFactorOption; } set { this._FormFactorOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountModel {\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountModelJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option formFactor = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "formFactor": + string? formFactorRawValue = utf8JsonReader.GetString(); + formFactor = new Option(BankAccountModel.FormFactorEnum.FromStringOrDefault(formFactorRawValue)); + break; + default: + break; + } + } + } + + + return new BankAccountModel(formFactor); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountModel bankAccountModel, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountModel, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountModel bankAccountModel, JsonSerializerOptions jsonSerializerOptions) + { + + var formFactorRawValue = BankAccountModel.FormFactorEnum.ToJsonValue(bankAccountModel._FormFactorOption.Value!.Value); + if (formFactorRawValue != null) + writer.WriteString("formFactor", formFactorRawValue); + else + writer.WriteNull("formFactor"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BankIdentification.cs b/Adyen/BalancePlatform/Models/BankIdentification.cs new file mode 100644 index 000000000..bece70956 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BankIdentification.cs @@ -0,0 +1,351 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BankIdentification. + /// + public partial class BankIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// The bank identification code. + /// The type of the identification. Possible values: **iban**, **routingNumber**, **sortCode**, **bic**. + [JsonConstructor] + public BankIdentification(Option country = default, Option identification = default, Option identificationType = default) + { + _CountryOption = country; + _IdentificationOption = identification; + _IdentificationTypeOption = identificationType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of the identification. Possible values: **iban**, **routingNumber**, **sortCode**, **bic**. + /// + /// The type of the identification. Possible values: **iban**, **routingNumber**, **sortCode**, **bic**. + [JsonConverter(typeof(IdentificationTypeEnumJsonConverter))] + public class IdentificationTypeEnum : IEnum + { + /// + /// Returns the value of the IdentificationTypeEnum. + /// + public string? Value { get; set; } + + /// + /// IdentificationTypeEnum.Bic - bic + /// + public static readonly IdentificationTypeEnum Bic = new("bic"); + + /// + /// IdentificationTypeEnum.Iban - iban + /// + public static readonly IdentificationTypeEnum Iban = new("iban"); + + /// + /// IdentificationTypeEnum.RoutingNumber - routingNumber + /// + public static readonly IdentificationTypeEnum RoutingNumber = new("routingNumber"); + + /// + /// IdentificationTypeEnum.SortCode - sortCode + /// + public static readonly IdentificationTypeEnum SortCode = new("sortCode"); + + private IdentificationTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IdentificationTypeEnum?(string? value) => value == null ? null : new IdentificationTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IdentificationTypeEnum? option) => option?.Value; + + public static bool operator ==(IdentificationTypeEnum? left, IdentificationTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IdentificationTypeEnum? left, IdentificationTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IdentificationTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IdentificationTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bic" => IdentificationTypeEnum.Bic, + "iban" => IdentificationTypeEnum.Iban, + "routingNumber" => IdentificationTypeEnum.RoutingNumber, + "sortCode" => IdentificationTypeEnum.SortCode, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IdentificationTypeEnum? value) + { + if (value == null) + return null; + + if (value == IdentificationTypeEnum.Bic) + return "bic"; + + if (value == IdentificationTypeEnum.Iban) + return "iban"; + + if (value == IdentificationTypeEnum.RoutingNumber) + return "routingNumber"; + + if (value == IdentificationTypeEnum.SortCode) + return "sortCode"; + + return null; + } + + /// + /// JsonConverter for writing IdentificationTypeEnum. + /// + public class IdentificationTypeEnumJsonConverter : JsonConverter + { + public override IdentificationTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IdentificationTypeEnum.FromStringOrDefault(value) ?? new IdentificationTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IdentificationTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IdentificationTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdentificationTypeOption { get; private set; } + + /// + /// The type of the identification. Possible values: **iban**, **routingNumber**, **sortCode**, **bic**. + /// + /// The type of the identification. Possible values: **iban**, **routingNumber**, **sortCode**, **bic**. + [JsonPropertyName("identificationType")] + public IdentificationTypeEnum? IdentificationType { get { return this._IdentificationTypeOption; } set { this._IdentificationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// Two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// + /// Two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdentificationOption { get; private set; } + + /// + /// The bank identification code. + /// + /// The bank identification code. + [JsonPropertyName("identification")] + public string? Identification { get { return this._IdentificationOption; } set { this._IdentificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankIdentification {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Identification: ").Append(Identification).Append("\n"); + sb.Append(" IdentificationType: ").Append(IdentificationType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option identification = default; + Option identificationType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "identification": + identification = new Option(utf8JsonReader.GetString()!); + break; + case "identificationType": + string? identificationTypeRawValue = utf8JsonReader.GetString(); + identificationType = new Option(BankIdentification.IdentificationTypeEnum.FromStringOrDefault(identificationTypeRawValue)); + break; + default: + break; + } + } + } + + + return new BankIdentification(country, identification, identificationType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankIdentification bankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankIdentification bankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankIdentification._CountryOption.IsSet) + if (bankIdentification.Country != null) + writer.WriteString("country", bankIdentification.Country); + + if (bankIdentification._IdentificationOption.IsSet) + if (bankIdentification.Identification != null) + writer.WriteString("identification", bankIdentification.Identification); + + if (bankIdentification._IdentificationTypeOption.IsSet && bankIdentification.IdentificationType != null) + { + string? identificationTypeRawValue = BankIdentification.IdentificationTypeEnum.ToJsonValue(bankIdentification._IdentificationTypeOption.Value!.Value); + writer.WriteString("identificationType", identificationTypeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationRequest.cs b/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationRequest.cs new file mode 100644 index 000000000..7d0d46dcd --- /dev/null +++ b/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationRequest.cs @@ -0,0 +1,215 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BeginScaDeviceRegistrationRequest. + /// + public partial class BeginScaDeviceRegistrationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + [JsonConstructor] + public BeginScaDeviceRegistrationRequest(string name, string sdkOutput) + { + Name = name; + SdkOutput = sdkOutput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BeginScaDeviceRegistrationRequest() + { + } + + partial void OnCreated(); + + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + [JsonPropertyName("sdkOutput")] + public string SdkOutput { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BeginScaDeviceRegistrationRequest {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" SdkOutput: ").Append(SdkOutput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Name (string) maxLength + if (this.Name != null && this.Name.Length > 64) + { + yield return new ValidationResult("Invalid value for Name, length must be less than 64.", new [] { "Name" }); + } + + // Name (string) minLength + if (this.Name != null && this.Name.Length < 0) + { + yield return new ValidationResult("Invalid value for Name, length must be greater than 0.", new [] { "Name" }); + } + + // SdkOutput (string) maxLength + if (this.SdkOutput != null && this.SdkOutput.Length > 10000) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be less than 10000.", new [] { "SdkOutput" }); + } + + // SdkOutput (string) minLength + if (this.SdkOutput != null && this.SdkOutput.Length < 0) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be greater than 0.", new [] { "SdkOutput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BeginScaDeviceRegistrationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BeginScaDeviceRegistrationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option sdkOutput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "sdkOutput": + sdkOutput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class BeginScaDeviceRegistrationRequest.", nameof(name)); + + if (!sdkOutput.IsSet) + throw new ArgumentException("Property is required for class BeginScaDeviceRegistrationRequest.", nameof(sdkOutput)); + + return new BeginScaDeviceRegistrationRequest(name.Value!, sdkOutput.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BeginScaDeviceRegistrationRequest beginScaDeviceRegistrationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, beginScaDeviceRegistrationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BeginScaDeviceRegistrationRequest beginScaDeviceRegistrationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (beginScaDeviceRegistrationRequest.Name != null) + writer.WriteString("name", beginScaDeviceRegistrationRequest.Name); + + if (beginScaDeviceRegistrationRequest.SdkOutput != null) + writer.WriteString("sdkOutput", beginScaDeviceRegistrationRequest.SdkOutput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationResponse.cs b/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationResponse.cs new file mode 100644 index 000000000..4a3a8deaa --- /dev/null +++ b/Adyen/BalancePlatform/Models/BeginScaDeviceRegistrationResponse.cs @@ -0,0 +1,208 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BeginScaDeviceRegistrationResponse. + /// + public partial class BeginScaDeviceRegistrationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// scaDevice + /// A string that you must pass to the authentication SDK to continue with the registration process. + [JsonConstructor] + public BeginScaDeviceRegistrationResponse(Option scaDevice = default, Option sdkInput = default) + { + _ScaDeviceOption = scaDevice; + _SdkInputOption = sdkInput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BeginScaDeviceRegistrationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("scaDevice")] + public ScaDevice? ScaDevice { get { return this._ScaDeviceOption; } set { this._ScaDeviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInputOption { get; private set; } + + /// + /// A string that you must pass to the authentication SDK to continue with the registration process. + /// + /// A string that you must pass to the authentication SDK to continue with the registration process. + [JsonPropertyName("sdkInput")] + public string? SdkInput { get { return this._SdkInputOption; } set { this._SdkInputOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BeginScaDeviceRegistrationResponse {\n"); + sb.Append(" ScaDevice: ").Append(ScaDevice).Append("\n"); + sb.Append(" SdkInput: ").Append(SdkInput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkInput (string) maxLength + if (this.SdkInput != null && this.SdkInput.Length > 10000) + { + yield return new ValidationResult("Invalid value for SdkInput, length must be less than 10000.", new [] { "SdkInput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BeginScaDeviceRegistrationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BeginScaDeviceRegistrationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option scaDevice = default; + Option sdkInput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "scaDevice": + scaDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sdkInput": + sdkInput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BeginScaDeviceRegistrationResponse(scaDevice, sdkInput); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BeginScaDeviceRegistrationResponse beginScaDeviceRegistrationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, beginScaDeviceRegistrationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BeginScaDeviceRegistrationResponse beginScaDeviceRegistrationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (beginScaDeviceRegistrationResponse._ScaDeviceOption.IsSet) + { + writer.WritePropertyName("scaDevice"); + JsonSerializer.Serialize(writer, beginScaDeviceRegistrationResponse.ScaDevice, jsonSerializerOptions); + } + if (beginScaDeviceRegistrationResponse._SdkInputOption.IsSet) + if (beginScaDeviceRegistrationResponse.SdkInput != null) + writer.WriteString("sdkInput", beginScaDeviceRegistrationResponse.SdkInput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/BrandVariantsRestriction.cs b/Adyen/BalancePlatform/Models/BrandVariantsRestriction.cs new file mode 100644 index 000000000..c7c02902c --- /dev/null +++ b/Adyen/BalancePlatform/Models/BrandVariantsRestriction.cs @@ -0,0 +1,198 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BrandVariantsRestriction. + /// + public partial class BrandVariantsRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of card brand variants. Possible values: - **mc**, **mccredit**, **mccommercialcredit_b2b**, **mcdebit**, **mcbusinessdebit**, **mcbusinessworlddebit**, **mcprepaid**, **mcmaestro** - **visa**, **visacredit**, **visadebit**, **visaprepaid**. You can specify a rule for a generic variant. For example, to create a rule for all Mastercard payment instruments, use **mc**. The rule is applied to all payment instruments under **mc**, such as **mcbusinessdebit** and **mcdebit**. + [JsonConstructor] + public BrandVariantsRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BrandVariantsRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of card brand variants. Possible values: - **mc**, **mccredit**, **mccommercialcredit_b2b**, **mcdebit**, **mcbusinessdebit**, **mcbusinessworlddebit**, **mcprepaid**, **mcmaestro** - **visa**, **visacredit**, **visadebit**, **visaprepaid**. You can specify a rule for a generic variant. For example, to create a rule for all Mastercard payment instruments, use **mc**. The rule is applied to all payment instruments under **mc**, such as **mcbusinessdebit** and **mcdebit**. + /// + /// List of card brand variants. Possible values: - **mc**, **mccredit**, **mccommercialcredit_b2b**, **mcdebit**, **mcbusinessdebit**, **mcbusinessworlddebit**, **mcprepaid**, **mcmaestro** - **visa**, **visacredit**, **visadebit**, **visaprepaid**. You can specify a rule for a generic variant. For example, to create a rule for all Mastercard payment instruments, use **mc**. The rule is applied to all payment instruments under **mc**, such as **mcbusinessdebit** and **mcdebit**. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BrandVariantsRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BrandVariantsRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BrandVariantsRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class BrandVariantsRestriction.", nameof(operation)); + + return new BrandVariantsRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BrandVariantsRestriction brandVariantsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, brandVariantsRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BrandVariantsRestriction brandVariantsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (brandVariantsRestriction.Operation != null) + writer.WriteString("operation", brandVariantsRestriction.Operation); + + if (brandVariantsRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, brandVariantsRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/BulkAddress.cs b/Adyen/BalancePlatform/Models/BulkAddress.cs new file mode 100644 index 000000000..537f45cb3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/BulkAddress.cs @@ -0,0 +1,446 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// BulkAddress. + /// + public partial class BulkAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + /// The name of the city. + /// The name of the company. + /// The email address. + /// The house number or name. + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + /// Additional information about the delivery address. For example, an apartment number. + /// Additional information about the delivery address. + /// The full telephone number. + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + /// The streetname of the house. + [JsonConstructor] + public BulkAddress(string country, Option city = default, Option company = default, Option email = default, Option houseNumberOrName = default, Option line1 = default, Option line2 = default, Option line3 = default, Option mobile = default, Option postalCode = default, Option stateOrProvince = default, Option street = default) + { + Country = country; + _CityOption = city; + _CompanyOption = company; + _EmailOption = email; + _HouseNumberOrNameOption = houseNumberOrName; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _MobileOption = mobile; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + _StreetOption = street; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BulkAddress() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// The name of the company. + /// + /// The name of the company. + [JsonPropertyName("company")] + public string? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address. + /// + /// The email address. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HouseNumberOrNameOption { get; private set; } + + /// + /// The house number or name. + /// + /// The house number or name. + [JsonPropertyName("houseNumberOrName")] + public string? HouseNumberOrName { get { return this._HouseNumberOrNameOption; } set { this._HouseNumberOrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + /// + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// Additional information about the delivery address. For example, an apartment number. + /// + /// Additional information about the delivery address. For example, an apartment number. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Additional information about the delivery address. + /// + /// Additional information about the delivery address. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobileOption { get; private set; } + + /// + /// The full telephone number. + /// + /// The full telephone number. + [JsonPropertyName("mobile")] + public string? Mobile { get { return this._MobileOption; } set { this._MobileOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + /// + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + /// + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StreetOption { get; private set; } + + /// + /// The streetname of the house. + /// + /// The streetname of the house. + [JsonPropertyName("street")] + public string? Street { get { return this._StreetOption; } set { this._StreetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BulkAddress {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" Mobile: ").Append(Mobile).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BulkAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BulkAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option company = default; + Option email = default; + Option houseNumberOrName = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option mobile = default; + Option postalCode = default; + Option stateOrProvince = default; + Option street = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "company": + company = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "mobile": + mobile = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class BulkAddress.", nameof(country)); + + return new BulkAddress(country.Value!, city, company, email, houseNumberOrName, line1, line2, line3, mobile, postalCode, stateOrProvince, street); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BulkAddress bulkAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bulkAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BulkAddress bulkAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (bulkAddress.Country != null) + writer.WriteString("country", bulkAddress.Country); + + if (bulkAddress._CityOption.IsSet) + if (bulkAddress.City != null) + writer.WriteString("city", bulkAddress.City); + + if (bulkAddress._CompanyOption.IsSet) + if (bulkAddress.Company != null) + writer.WriteString("company", bulkAddress.Company); + + if (bulkAddress._EmailOption.IsSet) + if (bulkAddress.Email != null) + writer.WriteString("email", bulkAddress.Email); + + if (bulkAddress._HouseNumberOrNameOption.IsSet) + if (bulkAddress.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", bulkAddress.HouseNumberOrName); + + if (bulkAddress._Line1Option.IsSet) + if (bulkAddress.Line1 != null) + writer.WriteString("line1", bulkAddress.Line1); + + if (bulkAddress._Line2Option.IsSet) + if (bulkAddress.Line2 != null) + writer.WriteString("line2", bulkAddress.Line2); + + if (bulkAddress._Line3Option.IsSet) + if (bulkAddress.Line3 != null) + writer.WriteString("line3", bulkAddress.Line3); + + if (bulkAddress._MobileOption.IsSet) + if (bulkAddress.Mobile != null) + writer.WriteString("mobile", bulkAddress.Mobile); + + if (bulkAddress._PostalCodeOption.IsSet) + if (bulkAddress.PostalCode != null) + writer.WriteString("postalCode", bulkAddress.PostalCode); + + if (bulkAddress._StateOrProvinceOption.IsSet) + if (bulkAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", bulkAddress.StateOrProvince); + + if (bulkAddress._StreetOption.IsSet) + if (bulkAddress.Street != null) + writer.WriteString("street", bulkAddress.Street); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CALocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/CALocalAccountIdentification.cs new file mode 100644 index 000000000..8dc24baa6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CALocalAccountIdentification.cs @@ -0,0 +1,496 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CALocalAccountIdentification. + /// + public partial class CALocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// The 3-digit institution number, without separators or whitespace. + /// The 5-digit transit number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **caLocal** (default to TypeEnum.CaLocal) + [JsonConstructor] + public CALocalAccountIdentification(string accountNumber, string institutionNumber, string transitNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + InstitutionNumber = institutionNumber; + TransitNumber = transitNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CALocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CaLocal - caLocal + /// + public static readonly TypeEnum CaLocal = new("caLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "caLocal" => TypeEnum.CaLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CaLocal) + return "caLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit institution number, without separators or whitespace. + /// + /// The 3-digit institution number, without separators or whitespace. + [JsonPropertyName("institutionNumber")] + public string InstitutionNumber { get; set; } + + /// + /// The 5-digit transit number, without separators or whitespace. + /// + /// The 5-digit transit number, without separators or whitespace. + [JsonPropertyName("transitNumber")] + public string TransitNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CALocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" InstitutionNumber: ").Append(InstitutionNumber).Append("\n"); + sb.Append(" TransitNumber: ").Append(TransitNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 12) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 12.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // InstitutionNumber (string) maxLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length > 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be less than 3.", new [] { "InstitutionNumber" }); + } + + // InstitutionNumber (string) minLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length < 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be greater than 3.", new [] { "InstitutionNumber" }); + } + + // TransitNumber (string) maxLength + if (this.TransitNumber != null && this.TransitNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be less than 5.", new [] { "TransitNumber" }); + } + + // TransitNumber (string) minLength + if (this.TransitNumber != null && this.TransitNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be greater than 5.", new [] { "TransitNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CALocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CALocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option institutionNumber = default; + Option transitNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "institutionNumber": + institutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "transitNumber": + transitNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(CALocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CALocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(accountNumber)); + + if (!institutionNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(institutionNumber)); + + if (!transitNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(transitNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(type)); + + return new CALocalAccountIdentification(accountNumber.Value!, institutionNumber.Value!, transitNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cALocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cALocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cALocalAccountIdentification.AccountNumber); + + if (cALocalAccountIdentification.InstitutionNumber != null) + writer.WriteString("institutionNumber", cALocalAccountIdentification.InstitutionNumber); + + if (cALocalAccountIdentification.TransitNumber != null) + writer.WriteString("transitNumber", cALocalAccountIdentification.TransitNumber); + + if (cALocalAccountIdentification._AccountTypeOption.IsSet && cALocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (cALocalAccountIdentification.Type != null) + { + string? typeRawValue = CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CZLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/CZLocalAccountIdentification.cs new file mode 100644 index 000000000..3ab62df15 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CZLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CZLocalAccountIdentification. + /// + public partial class CZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// **czLocal** (default to TypeEnum.CzLocal) + [JsonConstructor] + public CZLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CzLocal - czLocal + /// + public static readonly TypeEnum CzLocal = new("czLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "czLocal" => TypeEnum.CzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CzLocal) + return "czLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(type)); + + return new CZLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cZLocalAccountIdentification.AccountNumber); + + if (cZLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", cZLocalAccountIdentification.BankCode); + + if (cZLocalAccountIdentification.Type != null) + { + string? typeRawValue = CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapabilityProblem.cs b/Adyen/BalancePlatform/Models/CapabilityProblem.cs new file mode 100644 index 000000000..51141ceda --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapabilityProblem.cs @@ -0,0 +1,204 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapabilityProblem. + /// + public partial class CapabilityProblem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// entity + /// Contains information about the verification error. + [JsonConstructor] + public CapabilityProblem(Option entity = default, Option?> verificationErrors = default) + { + _EntityOption = entity; + _VerificationErrorsOption = verificationErrors; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("entity")] + public CapabilityProblemEntity? Entity { get { return this._EntityOption; } set { this._EntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationErrorsOption { get; private set; } + + /// + /// Contains information about the verification error. + /// + /// Contains information about the verification error. + [JsonPropertyName("verificationErrors")] + public List? VerificationErrors { get { return this._VerificationErrorsOption; } set { this._VerificationErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblem {\n"); + sb.Append(" Entity: ").Append(Entity).Append("\n"); + sb.Append(" VerificationErrors: ").Append(VerificationErrors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entity = default; + Option?> verificationErrors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entity": + entity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationErrors": + verificationErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilityProblem(entity, verificationErrors); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblem._EntityOption.IsSet) + { + writer.WritePropertyName("entity"); + JsonSerializer.Serialize(writer, capabilityProblem.Entity, jsonSerializerOptions); + } + if (capabilityProblem._VerificationErrorsOption.IsSet) + { + writer.WritePropertyName("verificationErrors"); + JsonSerializer.Serialize(writer, capabilityProblem.VerificationErrors, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapabilityProblemEntity.cs b/Adyen/BalancePlatform/Models/CapabilityProblemEntity.cs new file mode 100644 index 000000000..938708898 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapabilityProblemEntity.cs @@ -0,0 +1,368 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapabilityProblemEntity. + /// + public partial class CapabilityProblemEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// owner + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConstructor] + public CapabilityProblemEntity(Option?> documents = default, Option id = default, Option owner = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _OwnerOption = owner; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntity() + { + } + + partial void OnCreated(); + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("owner")] + public CapabilityProblemEntityRecursive? Owner { get { return this._OwnerOption; } set { this._OwnerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntity {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Owner: ").Append(Owner).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option owner = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "owner": + owner = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntity.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntity(documents, id, owner, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntity._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntity._IdOption.IsSet) + if (capabilityProblemEntity.Id != null) + writer.WriteString("id", capabilityProblemEntity.Id); + + if (capabilityProblemEntity._OwnerOption.IsSet) + { + writer.WritePropertyName("owner"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Owner, jsonSerializerOptions); + } + if (capabilityProblemEntity._TypeOption.IsSet && capabilityProblemEntity.Type != null) + { + string? typeRawValue = CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntity._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapabilityProblemEntityRecursive.cs b/Adyen/BalancePlatform/Models/CapabilityProblemEntityRecursive.cs new file mode 100644 index 000000000..5282c5994 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapabilityProblemEntityRecursive.cs @@ -0,0 +1,343 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapabilityProblemEntityRecursive. + /// + public partial class CapabilityProblemEntityRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConstructor] + public CapabilityProblemEntityRecursive(Option?> documents = default, Option id = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntityRecursive() + { + } + + partial void OnCreated(); + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntityRecursive {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntityRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntityRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntityRecursive(documents, id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntityRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntityRecursive._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntityRecursive.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntityRecursive._IdOption.IsSet) + if (capabilityProblemEntityRecursive.Id != null) + writer.WriteString("id", capabilityProblemEntityRecursive.Id); + + if (capabilityProblemEntityRecursive._TypeOption.IsSet && capabilityProblemEntityRecursive.Type != null) + { + string? typeRawValue = CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapabilitySettings.cs b/Adyen/BalancePlatform/Models/CapabilitySettings.cs new file mode 100644 index 000000000..06c64493c --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapabilitySettings.cs @@ -0,0 +1,500 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapabilitySettings. + /// + public partial class CapabilitySettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amountPerIndustry + /// authorizedCardUsers + /// fundingSource + /// interval + /// maxAmount + [JsonConstructor] + public CapabilitySettings(Option?> amountPerIndustry = default, Option authorizedCardUsers = default, Option?> fundingSource = default, Option interval = default, Option maxAmount = default) + { + _AmountPerIndustryOption = amountPerIndustry; + _AuthorizedCardUsersOption = authorizedCardUsers; + _FundingSourceOption = fundingSource; + _IntervalOption = interval; + _MaxAmountOption = maxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilitySettings() + { + } + + partial void OnCreated(); + + /// + /// Defines FundingSource. + /// + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + /// + /// FundingSourceEnum.Prepaid - prepaid + /// + public static readonly FundingSourceEnum Prepaid = new("prepaid"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + "prepaid" => FundingSourceEnum.Prepaid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + if (value == FundingSourceEnum.Prepaid) + return "prepaid"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines Interval. + /// + [JsonConverter(typeof(IntervalEnumJsonConverter))] + public class IntervalEnum : IEnum + { + /// + /// Returns the value of the IntervalEnum. + /// + public string? Value { get; set; } + + /// + /// IntervalEnum.Daily - daily + /// + public static readonly IntervalEnum Daily = new("daily"); + + /// + /// IntervalEnum.Monthly - monthly + /// + public static readonly IntervalEnum Monthly = new("monthly"); + + /// + /// IntervalEnum.Weekly - weekly + /// + public static readonly IntervalEnum Weekly = new("weekly"); + + private IntervalEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IntervalEnum?(string? value) => value == null ? null : new IntervalEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IntervalEnum? option) => option?.Value; + + public static bool operator ==(IntervalEnum? left, IntervalEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IntervalEnum? left, IntervalEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IntervalEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IntervalEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => IntervalEnum.Daily, + "monthly" => IntervalEnum.Monthly, + "weekly" => IntervalEnum.Weekly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IntervalEnum? value) + { + if (value == null) + return null; + + if (value == IntervalEnum.Daily) + return "daily"; + + if (value == IntervalEnum.Monthly) + return "monthly"; + + if (value == IntervalEnum.Weekly) + return "weekly"; + + return null; + } + + /// + /// JsonConverter for writing IntervalEnum. + /// + public class IntervalEnumJsonConverter : JsonConverter + { + public override IntervalEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IntervalEnum.FromStringOrDefault(value) ?? new IntervalEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IntervalEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IntervalEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IntervalOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interval")] + public IntervalEnum? Interval { get { return this._IntervalOption; } set { this._IntervalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AmountPerIndustryOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amountPerIndustry")] + public Dictionary? AmountPerIndustry { get { return this._AmountPerIndustryOption; } set { this._AmountPerIndustryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorizedCardUsersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authorizedCardUsers")] + public bool? AuthorizedCardUsers { get { return this._AuthorizedCardUsersOption; } set { this._AuthorizedCardUsersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FundingSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundingSource")] + public List? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maxAmount")] + public Amount? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilitySettings {\n"); + sb.Append(" AmountPerIndustry: ").Append(AmountPerIndustry).Append("\n"); + sb.Append(" AuthorizedCardUsers: ").Append(AuthorizedCardUsers).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Interval: ").Append(Interval).Append("\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilitySettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilitySettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> amountPerIndustry = default; + Option authorizedCardUsers = default; + Option?> fundingSource = default; + Option interval = default; + Option maxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amountPerIndustry": + amountPerIndustry = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authorizedCardUsers": + authorizedCardUsers = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "fundingSource": + fundingSource = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interval": + string? intervalRawValue = utf8JsonReader.GetString(); + interval = new Option(CapabilitySettings.IntervalEnum.FromStringOrDefault(intervalRawValue)); + break; + case "maxAmount": + maxAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilitySettings(amountPerIndustry, authorizedCardUsers, fundingSource, interval, maxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilitySettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilitySettings._AmountPerIndustryOption.IsSet) + { + writer.WritePropertyName("amountPerIndustry"); + JsonSerializer.Serialize(writer, capabilitySettings.AmountPerIndustry, jsonSerializerOptions); + } + if (capabilitySettings._AuthorizedCardUsersOption.IsSet) + writer.WriteBoolean("authorizedCardUsers", capabilitySettings._AuthorizedCardUsersOption.Value!.Value); + + if (capabilitySettings._FundingSourceOption.IsSet) + { + writer.WritePropertyName("fundingSource"); + JsonSerializer.Serialize(writer, capabilitySettings.FundingSource, jsonSerializerOptions); + } + if (capabilitySettings._IntervalOption.IsSet && capabilitySettings.Interval != null) + { + string? intervalRawValue = CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettings._IntervalOption.Value!.Value); + writer.WriteString("interval", intervalRawValue); + } + + if (capabilitySettings._MaxAmountOption.IsSet) + { + writer.WritePropertyName("maxAmount"); + JsonSerializer.Serialize(writer, capabilitySettings.MaxAmount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapitalBalance.cs b/Adyen/BalancePlatform/Models/CapitalBalance.cs new file mode 100644 index 000000000..14020998f --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapitalBalance.cs @@ -0,0 +1,228 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapitalBalance. + /// + public partial class CapitalBalance : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// Fee amount. + /// Principal amount. + /// Total amount. A sum of principal amount and fee amount. + [JsonConstructor] + public CapitalBalance(string currency, long fee, long principal, long total) + { + Currency = currency; + Fee = fee; + Principal = principal; + Total = total; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalBalance() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// Fee amount. + /// + /// Fee amount. + [JsonPropertyName("fee")] + public long Fee { get; set; } + + /// + /// Principal amount. + /// + /// Principal amount. + [JsonPropertyName("principal")] + public long Principal { get; set; } + + /// + /// Total amount. A sum of principal amount and fee amount. + /// + /// Total amount. A sum of principal amount and fee amount. + [JsonPropertyName("total")] + public long Total { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalBalance {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Fee: ").Append(Fee).Append("\n"); + sb.Append(" Principal: ").Append(Principal).Append("\n"); + sb.Append(" Total: ").Append(Total).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalBalanceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalBalance Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option fee = default; + Option principal = default; + Option total = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "fee": + fee = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "principal": + principal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "total": + total = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(currency)); + + if (!fee.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(fee)); + + if (!principal.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(principal)); + + if (!total.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(total)); + + return new CapitalBalance(currency.Value!, fee.Value!.Value!, principal.Value!.Value!, total.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalBalance capitalBalance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalBalance, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalBalance capitalBalance, JsonSerializerOptions jsonSerializerOptions) + { + + if (capitalBalance.Currency != null) + writer.WriteString("currency", capitalBalance.Currency); + + writer.WriteNumber("fee", capitalBalance.Fee); + + writer.WriteNumber("principal", capitalBalance.Principal); + + writer.WriteNumber("total", capitalBalance.Total); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CapitalGrantAccount.cs b/Adyen/BalancePlatform/Models/CapitalGrantAccount.cs new file mode 100644 index 000000000..357e425a3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CapitalGrantAccount.cs @@ -0,0 +1,255 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CapitalGrantAccount. + /// + public partial class CapitalGrantAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The balances of the grant account. + /// The unique identifier of the balance account used to fund the grant. + /// The identifier of the grant account. + /// The limits of the grant account. + [JsonConstructor] + public CapitalGrantAccount(Option?> balances = default, Option fundingBalanceAccountId = default, Option id = default, Option?> limits = default) + { + _BalancesOption = balances; + _FundingBalanceAccountIdOption = fundingBalanceAccountId; + _IdOption = id; + _LimitsOption = limits; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalGrantAccount() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BalancesOption { get; private set; } + + /// + /// The balances of the grant account. + /// + /// The balances of the grant account. + [JsonPropertyName("balances")] + public List? Balances { get { return this._BalancesOption; } set { this._BalancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingBalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the balance account used to fund the grant. + /// + /// The unique identifier of the balance account used to fund the grant. + [JsonPropertyName("fundingBalanceAccountId")] + public string? FundingBalanceAccountId { get { return this._FundingBalanceAccountIdOption; } set { this._FundingBalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The identifier of the grant account. + /// + /// The identifier of the grant account. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LimitsOption { get; private set; } + + /// + /// The limits of the grant account. + /// + /// The limits of the grant account. + [JsonPropertyName("limits")] + public List? Limits { get { return this._LimitsOption; } set { this._LimitsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalGrantAccount {\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" FundingBalanceAccountId: ").Append(FundingBalanceAccountId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Limits: ").Append(Limits).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalGrantAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalGrantAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> balances = default; + Option fundingBalanceAccountId = default; + Option id = default; + Option?> limits = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balances": + balances = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundingBalanceAccountId": + fundingBalanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "limits": + limits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapitalGrantAccount(balances, fundingBalanceAccountId, id, limits); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalGrantAccount capitalGrantAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalGrantAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalGrantAccount capitalGrantAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (capitalGrantAccount._BalancesOption.IsSet) + { + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, capitalGrantAccount.Balances, jsonSerializerOptions); + } + if (capitalGrantAccount._FundingBalanceAccountIdOption.IsSet) + if (capitalGrantAccount.FundingBalanceAccountId != null) + writer.WriteString("fundingBalanceAccountId", capitalGrantAccount.FundingBalanceAccountId); + + if (capitalGrantAccount._IdOption.IsSet) + if (capitalGrantAccount.Id != null) + writer.WriteString("id", capitalGrantAccount.Id); + + if (capitalGrantAccount._LimitsOption.IsSet) + { + writer.WritePropertyName("limits"); + JsonSerializer.Serialize(writer, capitalGrantAccount.Limits, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Card.cs b/Adyen/BalancePlatform/Models/Card.cs new file mode 100644 index 000000000..ae3938d37 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Card.cs @@ -0,0 +1,598 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// The name of the cardholder. Maximum length: 26 characters. + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + /// authentication + /// The bank identification number (BIN) of the card number. + /// configuration + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + /// deliveryContact + /// expiration + /// Last last four digits of the card number. + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonConstructor] + public Card(string brand, string brandVariant, string cardholderName, FormFactorEnum formFactor, string number, Option authentication = default, Option bin = default, Option configuration = default, Option cvc = default, Option deliveryContact = default, Option expiration = default, Option lastFour = default, Option threeDSecure = default, Option usage = default) + { + Brand = brand; + BrandVariant = brandVariant; + CardholderName = cardholderName; + FormFactor = formFactor; + Number = number; + _AuthenticationOption = authentication; + _BinOption = bin; + _ConfigurationOption = configuration; + _CvcOption = cvc; + _DeliveryContactOption = deliveryContact; + _ExpirationOption = expiration; + _LastFourOption = lastFour; + _ThreeDSecureOption = threeDSecure; + _UsageOption = usage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonConverter(typeof(FormFactorEnumJsonConverter))] + public class FormFactorEnum : IEnum + { + /// + /// Returns the value of the FormFactorEnum. + /// + public string? Value { get; set; } + + /// + /// FormFactorEnum.Physical - physical + /// + public static readonly FormFactorEnum Physical = new("physical"); + + /// + /// FormFactorEnum.Unknown - unknown + /// + public static readonly FormFactorEnum Unknown = new("unknown"); + + /// + /// FormFactorEnum.Virtual - virtual + /// + public static readonly FormFactorEnum Virtual = new("virtual"); + + private FormFactorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FormFactorEnum?(string? value) => value == null ? null : new FormFactorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FormFactorEnum? option) => option?.Value; + + public static bool operator ==(FormFactorEnum? left, FormFactorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FormFactorEnum? left, FormFactorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FormFactorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FormFactorEnum? FromStringOrDefault(string value) + { + return value switch { + "physical" => FormFactorEnum.Physical, + "unknown" => FormFactorEnum.Unknown, + "virtual" => FormFactorEnum.Virtual, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FormFactorEnum? value) + { + if (value == null) + return null; + + if (value == FormFactorEnum.Physical) + return "physical"; + + if (value == FormFactorEnum.Unknown) + return "unknown"; + + if (value == FormFactorEnum.Virtual) + return "virtual"; + + return null; + } + + /// + /// JsonConverter for writing FormFactorEnum. + /// + public class FormFactorEnumJsonConverter : JsonConverter + { + public override FormFactorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FormFactorEnum.FromStringOrDefault(value) ?? new FormFactorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FormFactorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FormFactorEnum.ToJsonValue(value)); + } + } + } + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonPropertyName("formFactor")] + public FormFactorEnum FormFactor { get; set; } + + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + [JsonPropertyName("brand")] + public string Brand { get; set; } + + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("brandVariant")] + public string BrandVariant { get; set; } + + /// + /// The name of the cardholder. Maximum length: 26 characters. + /// + /// The name of the cardholder. Maximum length: 26 characters. + [JsonPropertyName("cardholderName")] + public string CardholderName { get; set; } + + /// + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + /// + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + [JsonPropertyName("number")] + public string Number { get; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authentication")] + public Authentication? Authentication { get { return this._AuthenticationOption; } set { this._AuthenticationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinOption { get; private set; } + + /// + /// The bank identification number (BIN) of the card number. + /// + /// The bank identification number (BIN) of the card number. + [JsonPropertyName("bin")] + public string? Bin { get { return this._BinOption; } set { this._BinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("configuration")] + public CardConfiguration? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + /// + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryContactOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryContact")] + public DeliveryContact? DeliveryContact { get { return this._DeliveryContactOption; } set { this._DeliveryContactOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpirationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("expiration")] + public Expiry? Expiration { get { return this._ExpirationOption; } set { this._ExpirationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastFourOption { get; private set; } + + /// + /// Last last four digits of the card number. + /// + /// Last last four digits of the card number. + [JsonPropertyName("lastFour")] + public string? LastFour { get { return this._LastFourOption; } set { this._LastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("threeDSecure")] + public string? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsageOption { get; private set; } + + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonPropertyName("usage")] + public string? Usage { get { return this._UsageOption; } set { this._UsageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" BrandVariant: ").Append(BrandVariant).Append("\n"); + sb.Append(" CardholderName: ").Append(CardholderName).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" Bin: ").Append(Bin).Append("\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" DeliveryContact: ").Append(DeliveryContact).Append("\n"); + sb.Append(" Expiration: ").Append(Expiration).Append("\n"); + sb.Append(" LastFour: ").Append(LastFour).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Usage: ").Append(Usage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CardholderName (string) maxLength + if (this.CardholderName != null && this.CardholderName.Length > 26) + { + yield return new ValidationResult("Invalid value for CardholderName, length must be less than 26.", new [] { "CardholderName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option brandVariant = default; + Option cardholderName = default; + Option formFactor = default; + Option number = default; + Option authentication = default; + Option bin = default; + Option configuration = default; + Option cvc = default; + Option deliveryContact = default; + Option expiration = default; + Option lastFour = default; + Option threeDSecure = default; + Option usage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "brandVariant": + brandVariant = new Option(utf8JsonReader.GetString()!); + break; + case "cardholderName": + cardholderName = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + string? formFactorRawValue = utf8JsonReader.GetString(); + formFactor = new Option(Card.FormFactorEnum.FromStringOrDefault(formFactorRawValue)); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "authentication": + authentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bin": + bin = new Option(utf8JsonReader.GetString()!); + break; + case "configuration": + configuration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryContact": + deliveryContact = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiration": + expiration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lastFour": + lastFour = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSecure": + threeDSecure = new Option(utf8JsonReader.GetString()!); + break; + case "usage": + usage = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!brand.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(brand)); + + if (!brandVariant.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(brandVariant)); + + if (!cardholderName.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardholderName)); + + if (!formFactor.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(formFactor)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(number)); + + return new Card(brand.Value!, brandVariant.Value!, cardholderName.Value!, formFactor.Value!.Value!, number.Value!, authentication, bin, configuration, cvc, deliveryContact, expiration, lastFour, threeDSecure, usage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + if (card.Brand != null) + writer.WriteString("brand", card.Brand); + + if (card.BrandVariant != null) + writer.WriteString("brandVariant", card.BrandVariant); + + if (card.CardholderName != null) + writer.WriteString("cardholderName", card.CardholderName); + + if (card.FormFactor != null) + { + string? formFactorRawValue = Card.FormFactorEnum.ToJsonValue(card.FormFactor); + writer.WriteString("formFactor", formFactorRawValue); + } + + if (card.Number != null) + writer.WriteString("number", card.Number); + + if (card._AuthenticationOption.IsSet) + { + writer.WritePropertyName("authentication"); + JsonSerializer.Serialize(writer, card.Authentication, jsonSerializerOptions); + } + if (card._BinOption.IsSet) + if (card.Bin != null) + writer.WriteString("bin", card.Bin); + + if (card._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, card.Configuration, jsonSerializerOptions); + } + if (card._CvcOption.IsSet) + if (card.Cvc != null) + writer.WriteString("cvc", card.Cvc); + + if (card._DeliveryContactOption.IsSet) + { + writer.WritePropertyName("deliveryContact"); + JsonSerializer.Serialize(writer, card.DeliveryContact, jsonSerializerOptions); + } + if (card._ExpirationOption.IsSet) + { + writer.WritePropertyName("expiration"); + JsonSerializer.Serialize(writer, card.Expiration, jsonSerializerOptions); + } + if (card._LastFourOption.IsSet) + if (card.LastFour != null) + writer.WriteString("lastFour", card.LastFour); + + if (card._ThreeDSecureOption.IsSet) + if (card.ThreeDSecure != null) + writer.WriteString("threeDSecure", card.ThreeDSecure); + + if (card._UsageOption.IsSet) + if (card.Usage != null) + writer.WriteString("usage", card.Usage); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CardConfiguration.cs b/Adyen/BalancePlatform/Models/CardConfiguration.cs new file mode 100644 index 000000000..119351c80 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CardConfiguration.cs @@ -0,0 +1,502 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CardConfiguration. + /// + public partial class CardConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + /// bulkAddress + /// The ID of the card image. This is the image that will be printed on the full front of the card. + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + /// Overrides the envelope design ID defined in the `configurationProfileId`. + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + /// Overrides the logistics company defined in the `configurationProfileId`. + [JsonConstructor] + public CardConfiguration(string configurationProfileId, Option activation = default, Option activationUrl = default, Option bulkAddress = default, Option cardImageId = default, Option carrier = default, Option carrierImageId = default, Option currency = default, Option envelope = default, Option insert = default, Option language = default, Option logoImageId = default, Option pinMailer = default, Option shipmentMethod = default) + { + ConfigurationProfileId = configurationProfileId; + _ActivationOption = activation; + _ActivationUrlOption = activationUrl; + _BulkAddressOption = bulkAddress; + _CardImageIdOption = cardImageId; + _CarrierOption = carrier; + _CarrierImageIdOption = carrierImageId; + _CurrencyOption = currency; + _EnvelopeOption = envelope; + _InsertOption = insert; + _LanguageOption = language; + _LogoImageIdOption = logoImageId; + _PinMailerOption = pinMailer; + _ShipmentMethodOption = shipmentMethod; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardConfiguration() + { + } + + partial void OnCreated(); + + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + [JsonPropertyName("configurationProfileId")] + public string ConfigurationProfileId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActivationOption { get; private set; } + + /// + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + /// + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + [JsonPropertyName("activation")] + public string? Activation { get { return this._ActivationOption; } set { this._ActivationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActivationUrlOption { get; private set; } + + /// + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + /// + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + [JsonPropertyName("activationUrl")] + public string? ActivationUrl { get { return this._ActivationUrlOption; } set { this._ActivationUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BulkAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bulkAddress")] + public BulkAddress? BulkAddress { get { return this._BulkAddressOption; } set { this._BulkAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardImageIdOption { get; private set; } + + /// + /// The ID of the card image. This is the image that will be printed on the full front of the card. + /// + /// The ID of the card image. This is the image that will be printed on the full front of the card. + [JsonPropertyName("cardImageId")] + public string? CardImageId { get { return this._CardImageIdOption; } set { this._CardImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierOption { get; private set; } + + /// + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + /// + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + [JsonPropertyName("carrier")] + public string? Carrier { get { return this._CarrierOption; } set { this._CarrierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierImageIdOption { get; private set; } + + /// + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + /// + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + [JsonPropertyName("carrierImageId")] + public string? CarrierImageId { get { return this._CarrierImageIdOption; } set { this._CarrierImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + /// + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnvelopeOption { get; private set; } + + /// + /// Overrides the envelope design ID defined in the `configurationProfileId`. + /// + /// Overrides the envelope design ID defined in the `configurationProfileId`. + [JsonPropertyName("envelope")] + public string? Envelope { get { return this._EnvelopeOption; } set { this._EnvelopeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InsertOption { get; private set; } + + /// + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + /// + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + [JsonPropertyName("insert")] + public string? Insert { get { return this._InsertOption; } set { this._InsertOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LogoImageIdOption { get; private set; } + + /// + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + /// + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + [JsonPropertyName("logoImageId")] + public string? LogoImageId { get { return this._LogoImageIdOption; } set { this._LogoImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PinMailerOption { get; private set; } + + /// + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + /// + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + [JsonPropertyName("pinMailer")] + public string? PinMailer { get { return this._PinMailerOption; } set { this._PinMailerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipmentMethodOption { get; private set; } + + /// + /// Overrides the logistics company defined in the `configurationProfileId`. + /// + /// Overrides the logistics company defined in the `configurationProfileId`. + [JsonPropertyName("shipmentMethod")] + public string? ShipmentMethod { get { return this._ShipmentMethodOption; } set { this._ShipmentMethodOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardConfiguration {\n"); + sb.Append(" ConfigurationProfileId: ").Append(ConfigurationProfileId).Append("\n"); + sb.Append(" Activation: ").Append(Activation).Append("\n"); + sb.Append(" ActivationUrl: ").Append(ActivationUrl).Append("\n"); + sb.Append(" BulkAddress: ").Append(BulkAddress).Append("\n"); + sb.Append(" CardImageId: ").Append(CardImageId).Append("\n"); + sb.Append(" Carrier: ").Append(Carrier).Append("\n"); + sb.Append(" CarrierImageId: ").Append(CarrierImageId).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Envelope: ").Append(Envelope).Append("\n"); + sb.Append(" Insert: ").Append(Insert).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" LogoImageId: ").Append(LogoImageId).Append("\n"); + sb.Append(" PinMailer: ").Append(PinMailer).Append("\n"); + sb.Append(" ShipmentMethod: ").Append(ShipmentMethod).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ActivationUrl (string) maxLength + if (this.ActivationUrl != null && this.ActivationUrl.Length > 255) + { + yield return new ValidationResult("Invalid value for ActivationUrl, length must be less than 255.", new [] { "ActivationUrl" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option configurationProfileId = default; + Option activation = default; + Option activationUrl = default; + Option bulkAddress = default; + Option cardImageId = default; + Option carrier = default; + Option carrierImageId = default; + Option currency = default; + Option envelope = default; + Option insert = default; + Option language = default; + Option logoImageId = default; + Option pinMailer = default; + Option shipmentMethod = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "configurationProfileId": + configurationProfileId = new Option(utf8JsonReader.GetString()!); + break; + case "activation": + activation = new Option(utf8JsonReader.GetString()!); + break; + case "activationUrl": + activationUrl = new Option(utf8JsonReader.GetString()!); + break; + case "bulkAddress": + bulkAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardImageId": + cardImageId = new Option(utf8JsonReader.GetString()!); + break; + case "carrier": + carrier = new Option(utf8JsonReader.GetString()!); + break; + case "carrierImageId": + carrierImageId = new Option(utf8JsonReader.GetString()!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "envelope": + envelope = new Option(utf8JsonReader.GetString()!); + break; + case "insert": + insert = new Option(utf8JsonReader.GetString()!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "logoImageId": + logoImageId = new Option(utf8JsonReader.GetString()!); + break; + case "pinMailer": + pinMailer = new Option(utf8JsonReader.GetString()!); + break; + case "shipmentMethod": + shipmentMethod = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!configurationProfileId.IsSet) + throw new ArgumentException("Property is required for class CardConfiguration.", nameof(configurationProfileId)); + + return new CardConfiguration(configurationProfileId.Value!, activation, activationUrl, bulkAddress, cardImageId, carrier, carrierImageId, currency, envelope, insert, language, logoImageId, pinMailer, shipmentMethod); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardConfiguration cardConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardConfiguration cardConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardConfiguration.ConfigurationProfileId != null) + writer.WriteString("configurationProfileId", cardConfiguration.ConfigurationProfileId); + + if (cardConfiguration._ActivationOption.IsSet) + if (cardConfiguration.Activation != null) + writer.WriteString("activation", cardConfiguration.Activation); + + if (cardConfiguration._ActivationUrlOption.IsSet) + if (cardConfiguration.ActivationUrl != null) + writer.WriteString("activationUrl", cardConfiguration.ActivationUrl); + + if (cardConfiguration._BulkAddressOption.IsSet) + { + writer.WritePropertyName("bulkAddress"); + JsonSerializer.Serialize(writer, cardConfiguration.BulkAddress, jsonSerializerOptions); + } + if (cardConfiguration._CardImageIdOption.IsSet) + if (cardConfiguration.CardImageId != null) + writer.WriteString("cardImageId", cardConfiguration.CardImageId); + + if (cardConfiguration._CarrierOption.IsSet) + if (cardConfiguration.Carrier != null) + writer.WriteString("carrier", cardConfiguration.Carrier); + + if (cardConfiguration._CarrierImageIdOption.IsSet) + if (cardConfiguration.CarrierImageId != null) + writer.WriteString("carrierImageId", cardConfiguration.CarrierImageId); + + if (cardConfiguration._CurrencyOption.IsSet) + if (cardConfiguration.Currency != null) + writer.WriteString("currency", cardConfiguration.Currency); + + if (cardConfiguration._EnvelopeOption.IsSet) + if (cardConfiguration.Envelope != null) + writer.WriteString("envelope", cardConfiguration.Envelope); + + if (cardConfiguration._InsertOption.IsSet) + if (cardConfiguration.Insert != null) + writer.WriteString("insert", cardConfiguration.Insert); + + if (cardConfiguration._LanguageOption.IsSet) + if (cardConfiguration.Language != null) + writer.WriteString("language", cardConfiguration.Language); + + if (cardConfiguration._LogoImageIdOption.IsSet) + if (cardConfiguration.LogoImageId != null) + writer.WriteString("logoImageId", cardConfiguration.LogoImageId); + + if (cardConfiguration._PinMailerOption.IsSet) + if (cardConfiguration.PinMailer != null) + writer.WriteString("pinMailer", cardConfiguration.PinMailer); + + if (cardConfiguration._ShipmentMethodOption.IsSet) + if (cardConfiguration.ShipmentMethod != null) + writer.WriteString("shipmentMethod", cardConfiguration.ShipmentMethod); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CardInfo.cs b/Adyen/BalancePlatform/Models/CardInfo.cs new file mode 100644 index 000000000..eb5bd3024 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CardInfo.cs @@ -0,0 +1,478 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CardInfo. + /// + public partial class CardInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// The name of the cardholder. Maximum length: 26 characters. + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// authentication + /// configuration + /// deliveryContact + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonConstructor] + public CardInfo(string brand, string brandVariant, string cardholderName, FormFactorEnum formFactor, Option authentication = default, Option configuration = default, Option deliveryContact = default, Option threeDSecure = default, Option usage = default) + { + Brand = brand; + BrandVariant = brandVariant; + CardholderName = cardholderName; + FormFactor = formFactor; + _AuthenticationOption = authentication; + _ConfigurationOption = configuration; + _DeliveryContactOption = deliveryContact; + _ThreeDSecureOption = threeDSecure; + _UsageOption = usage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardInfo() + { + } + + partial void OnCreated(); + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonConverter(typeof(FormFactorEnumJsonConverter))] + public class FormFactorEnum : IEnum + { + /// + /// Returns the value of the FormFactorEnum. + /// + public string? Value { get; set; } + + /// + /// FormFactorEnum.Physical - physical + /// + public static readonly FormFactorEnum Physical = new("physical"); + + /// + /// FormFactorEnum.Unknown - unknown + /// + public static readonly FormFactorEnum Unknown = new("unknown"); + + /// + /// FormFactorEnum.Virtual - virtual + /// + public static readonly FormFactorEnum Virtual = new("virtual"); + + private FormFactorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FormFactorEnum?(string? value) => value == null ? null : new FormFactorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FormFactorEnum? option) => option?.Value; + + public static bool operator ==(FormFactorEnum? left, FormFactorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FormFactorEnum? left, FormFactorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FormFactorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FormFactorEnum? FromStringOrDefault(string value) + { + return value switch { + "physical" => FormFactorEnum.Physical, + "unknown" => FormFactorEnum.Unknown, + "virtual" => FormFactorEnum.Virtual, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FormFactorEnum? value) + { + if (value == null) + return null; + + if (value == FormFactorEnum.Physical) + return "physical"; + + if (value == FormFactorEnum.Unknown) + return "unknown"; + + if (value == FormFactorEnum.Virtual) + return "virtual"; + + return null; + } + + /// + /// JsonConverter for writing FormFactorEnum. + /// + public class FormFactorEnumJsonConverter : JsonConverter + { + public override FormFactorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FormFactorEnum.FromStringOrDefault(value) ?? new FormFactorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FormFactorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FormFactorEnum.ToJsonValue(value)); + } + } + } + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonPropertyName("formFactor")] + public FormFactorEnum FormFactor { get; set; } + + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + [JsonPropertyName("brand")] + public string Brand { get; set; } + + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("brandVariant")] + public string BrandVariant { get; set; } + + /// + /// The name of the cardholder. Maximum length: 26 characters. + /// + /// The name of the cardholder. Maximum length: 26 characters. + [JsonPropertyName("cardholderName")] + public string CardholderName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authentication")] + public Authentication? Authentication { get { return this._AuthenticationOption; } set { this._AuthenticationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("configuration")] + public CardConfiguration? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryContactOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryContact")] + public DeliveryContact? DeliveryContact { get { return this._DeliveryContactOption; } set { this._DeliveryContactOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("threeDSecure")] + public string? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsageOption { get; private set; } + + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonPropertyName("usage")] + public string? Usage { get { return this._UsageOption; } set { this._UsageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardInfo {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" BrandVariant: ").Append(BrandVariant).Append("\n"); + sb.Append(" CardholderName: ").Append(CardholderName).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" DeliveryContact: ").Append(DeliveryContact).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Usage: ").Append(Usage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CardholderName (string) maxLength + if (this.CardholderName != null && this.CardholderName.Length > 26) + { + yield return new ValidationResult("Invalid value for CardholderName, length must be less than 26.", new [] { "CardholderName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option brandVariant = default; + Option cardholderName = default; + Option formFactor = default; + Option authentication = default; + Option configuration = default; + Option deliveryContact = default; + Option threeDSecure = default; + Option usage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "brandVariant": + brandVariant = new Option(utf8JsonReader.GetString()!); + break; + case "cardholderName": + cardholderName = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + string? formFactorRawValue = utf8JsonReader.GetString(); + formFactor = new Option(CardInfo.FormFactorEnum.FromStringOrDefault(formFactorRawValue)); + break; + case "authentication": + authentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "configuration": + configuration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryContact": + deliveryContact = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSecure": + threeDSecure = new Option(utf8JsonReader.GetString()!); + break; + case "usage": + usage = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!brand.IsSet) + throw new ArgumentException("Property is required for class CardInfo.", nameof(brand)); + + if (!brandVariant.IsSet) + throw new ArgumentException("Property is required for class CardInfo.", nameof(brandVariant)); + + if (!cardholderName.IsSet) + throw new ArgumentException("Property is required for class CardInfo.", nameof(cardholderName)); + + if (!formFactor.IsSet) + throw new ArgumentException("Property is required for class CardInfo.", nameof(formFactor)); + + return new CardInfo(brand.Value!, brandVariant.Value!, cardholderName.Value!, formFactor.Value!.Value!, authentication, configuration, deliveryContact, threeDSecure, usage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardInfo cardInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardInfo cardInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardInfo.Brand != null) + writer.WriteString("brand", cardInfo.Brand); + + if (cardInfo.BrandVariant != null) + writer.WriteString("brandVariant", cardInfo.BrandVariant); + + if (cardInfo.CardholderName != null) + writer.WriteString("cardholderName", cardInfo.CardholderName); + + if (cardInfo.FormFactor != null) + { + string? formFactorRawValue = CardInfo.FormFactorEnum.ToJsonValue(cardInfo.FormFactor); + writer.WriteString("formFactor", formFactorRawValue); + } + + if (cardInfo._AuthenticationOption.IsSet) + { + writer.WritePropertyName("authentication"); + JsonSerializer.Serialize(writer, cardInfo.Authentication, jsonSerializerOptions); + } + if (cardInfo._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, cardInfo.Configuration, jsonSerializerOptions); + } + if (cardInfo._DeliveryContactOption.IsSet) + { + writer.WritePropertyName("deliveryContact"); + JsonSerializer.Serialize(writer, cardInfo.DeliveryContact, jsonSerializerOptions); + } + if (cardInfo._ThreeDSecureOption.IsSet) + if (cardInfo.ThreeDSecure != null) + writer.WriteString("threeDSecure", cardInfo.ThreeDSecure); + + if (cardInfo._UsageOption.IsSet) + if (cardInfo.Usage != null) + writer.WriteString("usage", cardInfo.Usage); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CardOrder.cs b/Adyen/BalancePlatform/Models/CardOrder.cs new file mode 100644 index 000000000..ce4540fbd --- /dev/null +++ b/Adyen/BalancePlatform/Models/CardOrder.cs @@ -0,0 +1,474 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CardOrder. + /// + public partial class CardOrder : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the card order is created. + /// The unique identifier of the card manufacturer profile. + /// The date when the card order processing ends. + /// The date when you manually closed the card order. Card orders are automatically closed by the end of the day it was created. If you manually closed it beforehand, the closing date is shown as the `endDate`. + /// The unique identifier of the card order. + /// The date when the card order processing begins. + /// The service center. + /// The status of the card order. Possible values: **Open**, **Closed**. + [JsonConstructor] + public CardOrder(Option beginDate = default, Option cardManufacturingProfileId = default, Option closedDate = default, Option endDate = default, Option id = default, Option lockDate = default, Option serviceCenter = default, Option status = default) + { + _BeginDateOption = beginDate; + _CardManufacturingProfileIdOption = cardManufacturingProfileId; + _ClosedDateOption = closedDate; + _EndDateOption = endDate; + _IdOption = id; + _LockDateOption = lockDate; + _ServiceCenterOption = serviceCenter; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrder() + { + } + + partial void OnCreated(); + + /// + /// The status of the card order. Possible values: **Open**, **Closed**. + /// + /// The status of the card order. Possible values: **Open**, **Closed**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Open - open + /// + public static readonly StatusEnum Open = new("open"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "closed" => StatusEnum.Closed, + "open" => StatusEnum.Open, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Open) + return "open"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the card order. Possible values: **Open**, **Closed**. + /// + /// The status of the card order. Possible values: **Open**, **Closed**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BeginDateOption { get; private set; } + + /// + /// The date when the card order is created. + /// + /// The date when the card order is created. + [JsonPropertyName("beginDate")] + public DateTimeOffset? BeginDate { get { return this._BeginDateOption; } set { this._BeginDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardManufacturingProfileIdOption { get; private set; } + + /// + /// The unique identifier of the card manufacturer profile. + /// + /// The unique identifier of the card manufacturer profile. + [JsonPropertyName("cardManufacturingProfileId")] + public string? CardManufacturingProfileId { get { return this._CardManufacturingProfileIdOption; } set { this._CardManufacturingProfileIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClosedDateOption { get; private set; } + + /// + /// The date when the card order processing ends. + /// + /// The date when the card order processing ends. + [JsonPropertyName("closedDate")] + public DateTimeOffset? ClosedDate { get { return this._ClosedDateOption; } set { this._ClosedDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndDateOption { get; private set; } + + /// + /// The date when you manually closed the card order. Card orders are automatically closed by the end of the day it was created. If you manually closed it beforehand, the closing date is shown as the `endDate`. + /// + /// The date when you manually closed the card order. Card orders are automatically closed by the end of the day it was created. If you manually closed it beforehand, the closing date is shown as the `endDate`. + [JsonPropertyName("endDate")] + public DateTimeOffset? EndDate { get { return this._EndDateOption; } set { this._EndDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the card order. + /// + /// The unique identifier of the card order. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LockDateOption { get; private set; } + + /// + /// The date when the card order processing begins. + /// + /// The date when the card order processing begins. + [JsonPropertyName("lockDate")] + public DateTimeOffset? LockDate { get { return this._LockDateOption; } set { this._LockDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ServiceCenterOption { get; private set; } + + /// + /// The service center. + /// + /// The service center. + [JsonPropertyName("serviceCenter")] + public string? ServiceCenter { get { return this._ServiceCenterOption; } set { this._ServiceCenterOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrder {\n"); + sb.Append(" BeginDate: ").Append(BeginDate).Append("\n"); + sb.Append(" CardManufacturingProfileId: ").Append(CardManufacturingProfileId).Append("\n"); + sb.Append(" ClosedDate: ").Append(ClosedDate).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" ServiceCenter: ").Append(ServiceCenter).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderJsonConverter : JsonConverter + { + /// + /// The format to use to serialize BeginDate. + /// + public static string BeginDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ClosedDate. + /// + public static string ClosedDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize EndDate. + /// + public static string EndDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize LockDate. + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrder Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option beginDate = default; + Option cardManufacturingProfileId = default; + Option closedDate = default; + Option endDate = default; + Option id = default; + Option lockDate = default; + Option serviceCenter = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "beginDate": + beginDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "cardManufacturingProfileId": + cardManufacturingProfileId = new Option(utf8JsonReader.GetString()!); + break; + case "closedDate": + closedDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "endDate": + endDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "lockDate": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "serviceCenter": + serviceCenter = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(CardOrder.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new CardOrder(beginDate, cardManufacturingProfileId, closedDate, endDate, id, lockDate, serviceCenter, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrder cardOrder, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrder, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrder cardOrder, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardOrder._BeginDateOption.IsSet) + writer.WriteString("beginDate", cardOrder._BeginDateOption.Value!.Value.ToString(BeginDateFormat)); + + if (cardOrder._CardManufacturingProfileIdOption.IsSet) + if (cardOrder.CardManufacturingProfileId != null) + writer.WriteString("cardManufacturingProfileId", cardOrder.CardManufacturingProfileId); + + if (cardOrder._ClosedDateOption.IsSet) + writer.WriteString("closedDate", cardOrder._ClosedDateOption.Value!.Value.ToString(ClosedDateFormat)); + + if (cardOrder._EndDateOption.IsSet) + writer.WriteString("endDate", cardOrder._EndDateOption.Value!.Value.ToString(EndDateFormat)); + + if (cardOrder._IdOption.IsSet) + if (cardOrder.Id != null) + writer.WriteString("id", cardOrder.Id); + + if (cardOrder._LockDateOption.IsSet) + writer.WriteString("lockDate", cardOrder._LockDateOption.Value!.Value.ToString(LockDateFormat)); + + if (cardOrder._ServiceCenterOption.IsSet) + if (cardOrder.ServiceCenter != null) + writer.WriteString("serviceCenter", cardOrder.ServiceCenter); + + if (cardOrder._StatusOption.IsSet && cardOrder.Status != null) + { + string? statusRawValue = CardOrder.StatusEnum.ToJsonValue(cardOrder._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CardOrderItem.cs b/Adyen/BalancePlatform/Models/CardOrderItem.cs new file mode 100644 index 000000000..de33c96d4 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CardOrderItem.cs @@ -0,0 +1,356 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CardOrderItem. + /// + public partial class CardOrderItem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// card + /// The unique identifier of the card order item. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + /// The unique identifier of the payment instrument related to the card order item. + /// pin + /// The shipping method used to deliver the card or the PIN. + [JsonConstructor] + public CardOrderItem(Option balancePlatform = default, Option card = default, Option cardOrderItemId = default, Option creationDate = default, Option id = default, Option paymentInstrumentId = default, Option pin = default, Option shippingMethod = default) + { + _BalancePlatformOption = balancePlatform; + _CardOption = card; + _CardOrderItemIdOption = cardOrderItemId; + _CreationDateOption = creationDate; + _IdOption = id; + _PaymentInstrumentIdOption = paymentInstrumentId; + _PinOption = pin; + _ShippingMethodOption = shippingMethod; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrderItem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public CardOrderItemDeliveryStatus? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOrderItemIdOption { get; private set; } + + /// + /// The unique identifier of the card order item. + /// + /// The unique identifier of the card order item. + [JsonPropertyName("cardOrderItemId")] + public string? CardOrderItemId { get { return this._CardOrderItemIdOption; } set { this._CardOrderItemIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument related to the card order item. + /// + /// The unique identifier of the payment instrument related to the card order item. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PinOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pin")] + public CardOrderItemDeliveryStatus? Pin { get { return this._PinOption; } set { this._PinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShippingMethodOption { get; private set; } + + /// + /// The shipping method used to deliver the card or the PIN. + /// + /// The shipping method used to deliver the card or the PIN. + [JsonPropertyName("shippingMethod")] + public string? ShippingMethod { get { return this._ShippingMethodOption; } set { this._ShippingMethodOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrderItem {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" CardOrderItemId: ").Append(CardOrderItemId).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Pin: ").Append(Pin).Append("\n"); + sb.Append(" ShippingMethod: ").Append(ShippingMethod).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderItemJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrderItem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option card = default; + Option cardOrderItemId = default; + Option creationDate = default; + Option id = default; + Option paymentInstrumentId = default; + Option pin = default; + Option shippingMethod = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardOrderItemId": + cardOrderItemId = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "pin": + pin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shippingMethod": + shippingMethod = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardOrderItem(balancePlatform, card, cardOrderItemId, creationDate, id, paymentInstrumentId, pin, shippingMethod); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrderItem cardOrderItem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrderItem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrderItem cardOrderItem, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardOrderItem._BalancePlatformOption.IsSet) + if (cardOrderItem.BalancePlatform != null) + writer.WriteString("balancePlatform", cardOrderItem.BalancePlatform); + + if (cardOrderItem._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, cardOrderItem.Card, jsonSerializerOptions); + } + if (cardOrderItem._CardOrderItemIdOption.IsSet) + if (cardOrderItem.CardOrderItemId != null) + writer.WriteString("cardOrderItemId", cardOrderItem.CardOrderItemId); + + if (cardOrderItem._CreationDateOption.IsSet) + writer.WriteString("creationDate", cardOrderItem._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (cardOrderItem._IdOption.IsSet) + if (cardOrderItem.Id != null) + writer.WriteString("id", cardOrderItem.Id); + + if (cardOrderItem._PaymentInstrumentIdOption.IsSet) + if (cardOrderItem.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", cardOrderItem.PaymentInstrumentId); + + if (cardOrderItem._PinOption.IsSet) + { + writer.WritePropertyName("pin"); + JsonSerializer.Serialize(writer, cardOrderItem.Pin, jsonSerializerOptions); + } + if (cardOrderItem._ShippingMethodOption.IsSet) + if (cardOrderItem.ShippingMethod != null) + writer.WriteString("shippingMethod", cardOrderItem.ShippingMethod); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CardOrderItemDeliveryStatus.cs b/Adyen/BalancePlatform/Models/CardOrderItemDeliveryStatus.cs new file mode 100644 index 000000000..f81bac608 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CardOrderItemDeliveryStatus.cs @@ -0,0 +1,387 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CardOrderItemDeliveryStatus. + /// + public partial class CardOrderItemDeliveryStatus : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An error message. + /// The status of the PIN delivery. + /// The tracking number of the PIN delivery. + [JsonConstructor] + public CardOrderItemDeliveryStatus(Option errorMessage = default, Option status = default, Option trackingNumber = default) + { + _ErrorMessageOption = errorMessage; + _StatusOption = status; + _TrackingNumberOption = trackingNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrderItemDeliveryStatus() + { + } + + partial void OnCreated(); + + /// + /// The status of the PIN delivery. + /// + /// The status of the PIN delivery. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Created - created + /// + public static readonly StatusEnum Created = new("created"); + + /// + /// StatusEnum.Delivered - delivered + /// + public static readonly StatusEnum Delivered = new("delivered"); + + /// + /// StatusEnum.NotApplicable - notApplicable + /// + public static readonly StatusEnum NotApplicable = new("notApplicable"); + + /// + /// StatusEnum.Processing - processing + /// + public static readonly StatusEnum Processing = new("processing"); + + /// + /// StatusEnum.Produced - produced + /// + public static readonly StatusEnum Produced = new("produced"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.Shipped - shipped + /// + public static readonly StatusEnum Shipped = new("shipped"); + + /// + /// StatusEnum.Unknown - unknown + /// + public static readonly StatusEnum Unknown = new("unknown"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "created" => StatusEnum.Created, + "delivered" => StatusEnum.Delivered, + "notApplicable" => StatusEnum.NotApplicable, + "processing" => StatusEnum.Processing, + "produced" => StatusEnum.Produced, + "rejected" => StatusEnum.Rejected, + "shipped" => StatusEnum.Shipped, + "unknown" => StatusEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Created) + return "created"; + + if (value == StatusEnum.Delivered) + return "delivered"; + + if (value == StatusEnum.NotApplicable) + return "notApplicable"; + + if (value == StatusEnum.Processing) + return "processing"; + + if (value == StatusEnum.Produced) + return "produced"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.Shipped) + return "shipped"; + + if (value == StatusEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the PIN delivery. + /// + /// The status of the PIN delivery. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorMessageOption { get; private set; } + + /// + /// An error message. + /// + /// An error message. + [JsonPropertyName("errorMessage")] + public string? ErrorMessage { get { return this._ErrorMessageOption; } set { this._ErrorMessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingNumberOption { get; private set; } + + /// + /// The tracking number of the PIN delivery. + /// + /// The tracking number of the PIN delivery. + [JsonPropertyName("trackingNumber")] + public string? TrackingNumber { get { return this._TrackingNumberOption; } set { this._TrackingNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrderItemDeliveryStatus {\n"); + sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TrackingNumber: ").Append(TrackingNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderItemDeliveryStatusJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrderItemDeliveryStatus Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorMessage = default; + Option status = default; + Option trackingNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorMessage": + errorMessage = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(CardOrderItemDeliveryStatus.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "trackingNumber": + trackingNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardOrderItemDeliveryStatus(errorMessage, status, trackingNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrderItemDeliveryStatus cardOrderItemDeliveryStatus, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrderItemDeliveryStatus, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrderItemDeliveryStatus cardOrderItemDeliveryStatus, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardOrderItemDeliveryStatus._ErrorMessageOption.IsSet) + if (cardOrderItemDeliveryStatus.ErrorMessage != null) + writer.WriteString("errorMessage", cardOrderItemDeliveryStatus.ErrorMessage); + + if (cardOrderItemDeliveryStatus._StatusOption.IsSet && cardOrderItemDeliveryStatus.Status != null) + { + string? statusRawValue = CardOrderItemDeliveryStatus.StatusEnum.ToJsonValue(cardOrderItemDeliveryStatus._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (cardOrderItemDeliveryStatus._TrackingNumberOption.IsSet) + if (cardOrderItemDeliveryStatus.TrackingNumber != null) + writer.WriteString("trackingNumber", cardOrderItemDeliveryStatus.TrackingNumber); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Condition.cs b/Adyen/BalancePlatform/Models/Condition.cs new file mode 100644 index 000000000..06dc6c3a7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Condition.cs @@ -0,0 +1,460 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Condition. + /// + public partial class Condition : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Define the type of balance about which you want to get notified. Possible values: * **available**: the balance available for use. * **balance**: the sum of transactions that have already been settled. * **pending**: the sum of transactions that will be settled in the future. * **reserved**: the balance currently held in reserve. + /// Define when you want to get notified about a balance change. Possible values: * **greaterThan**: the balance in the account(s) exceeds the specified `value`. * **greaterThanOrEqual**: the balance in the account(s) reaches or exceeds the specified `value`. * **lessThan**: the balance in the account(s) drops below the specified `value`. * **lessThanOrEqual**: the balance in the account(s) reaches to drops below the specified `value`. + /// The value limit in the specified balance type and currency, in minor units. + [JsonConstructor] + public Condition(BalanceTypeEnum balanceType, ConditionTypeEnum conditionType, long value) + { + BalanceType = balanceType; + ConditionType = conditionType; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Condition() + { + } + + partial void OnCreated(); + + /// + /// Define the type of balance about which you want to get notified. Possible values: * **available**: the balance available for use. * **balance**: the sum of transactions that have already been settled. * **pending**: the sum of transactions that will be settled in the future. * **reserved**: the balance currently held in reserve. + /// + /// Define the type of balance about which you want to get notified. Possible values: * **available**: the balance available for use. * **balance**: the sum of transactions that have already been settled. * **pending**: the sum of transactions that will be settled in the future. * **reserved**: the balance currently held in reserve. + [JsonConverter(typeof(BalanceTypeEnumJsonConverter))] + public class BalanceTypeEnum : IEnum + { + /// + /// Returns the value of the BalanceTypeEnum. + /// + public string? Value { get; set; } + + /// + /// BalanceTypeEnum.Balance - balance + /// + public static readonly BalanceTypeEnum Balance = new("balance"); + + /// + /// BalanceTypeEnum.Available - available + /// + public static readonly BalanceTypeEnum Available = new("available"); + + /// + /// BalanceTypeEnum.Pending - pending + /// + public static readonly BalanceTypeEnum Pending = new("pending"); + + /// + /// BalanceTypeEnum.Reserved - reserved + /// + public static readonly BalanceTypeEnum Reserved = new("reserved"); + + private BalanceTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BalanceTypeEnum?(string? value) => value == null ? null : new BalanceTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BalanceTypeEnum? option) => option?.Value; + + public static bool operator ==(BalanceTypeEnum? left, BalanceTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BalanceTypeEnum? left, BalanceTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BalanceTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BalanceTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balance" => BalanceTypeEnum.Balance, + "available" => BalanceTypeEnum.Available, + "pending" => BalanceTypeEnum.Pending, + "reserved" => BalanceTypeEnum.Reserved, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BalanceTypeEnum? value) + { + if (value == null) + return null; + + if (value == BalanceTypeEnum.Balance) + return "balance"; + + if (value == BalanceTypeEnum.Available) + return "available"; + + if (value == BalanceTypeEnum.Pending) + return "pending"; + + if (value == BalanceTypeEnum.Reserved) + return "reserved"; + + return null; + } + + /// + /// JsonConverter for writing BalanceTypeEnum. + /// + public class BalanceTypeEnumJsonConverter : JsonConverter + { + public override BalanceTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BalanceTypeEnum.FromStringOrDefault(value) ?? new BalanceTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BalanceTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BalanceTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Define the type of balance about which you want to get notified. Possible values: * **available**: the balance available for use. * **balance**: the sum of transactions that have already been settled. * **pending**: the sum of transactions that will be settled in the future. * **reserved**: the balance currently held in reserve. + /// + /// Define the type of balance about which you want to get notified. Possible values: * **available**: the balance available for use. * **balance**: the sum of transactions that have already been settled. * **pending**: the sum of transactions that will be settled in the future. * **reserved**: the balance currently held in reserve. + [JsonPropertyName("balanceType")] + public BalanceTypeEnum BalanceType { get; set; } + + /// + /// Define when you want to get notified about a balance change. Possible values: * **greaterThan**: the balance in the account(s) exceeds the specified `value`. * **greaterThanOrEqual**: the balance in the account(s) reaches or exceeds the specified `value`. * **lessThan**: the balance in the account(s) drops below the specified `value`. * **lessThanOrEqual**: the balance in the account(s) reaches to drops below the specified `value`. + /// + /// Define when you want to get notified about a balance change. Possible values: * **greaterThan**: the balance in the account(s) exceeds the specified `value`. * **greaterThanOrEqual**: the balance in the account(s) reaches or exceeds the specified `value`. * **lessThan**: the balance in the account(s) drops below the specified `value`. * **lessThanOrEqual**: the balance in the account(s) reaches to drops below the specified `value`. + [JsonConverter(typeof(ConditionTypeEnumJsonConverter))] + public class ConditionTypeEnum : IEnum + { + /// + /// Returns the value of the ConditionTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ConditionTypeEnum.GreaterThan - greaterThan + /// + public static readonly ConditionTypeEnum GreaterThan = new("greaterThan"); + + /// + /// ConditionTypeEnum.GreaterThanOrEqual - greaterThanOrEqual + /// + public static readonly ConditionTypeEnum GreaterThanOrEqual = new("greaterThanOrEqual"); + + /// + /// ConditionTypeEnum.LessThan - lessThan + /// + public static readonly ConditionTypeEnum LessThan = new("lessThan"); + + /// + /// ConditionTypeEnum.LessThanOrEqual - lessThanOrEqual + /// + public static readonly ConditionTypeEnum LessThanOrEqual = new("lessThanOrEqual"); + + private ConditionTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ConditionTypeEnum?(string? value) => value == null ? null : new ConditionTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ConditionTypeEnum? option) => option?.Value; + + public static bool operator ==(ConditionTypeEnum? left, ConditionTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ConditionTypeEnum? left, ConditionTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ConditionTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ConditionTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "greaterThan" => ConditionTypeEnum.GreaterThan, + "greaterThanOrEqual" => ConditionTypeEnum.GreaterThanOrEqual, + "lessThan" => ConditionTypeEnum.LessThan, + "lessThanOrEqual" => ConditionTypeEnum.LessThanOrEqual, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ConditionTypeEnum? value) + { + if (value == null) + return null; + + if (value == ConditionTypeEnum.GreaterThan) + return "greaterThan"; + + if (value == ConditionTypeEnum.GreaterThanOrEqual) + return "greaterThanOrEqual"; + + if (value == ConditionTypeEnum.LessThan) + return "lessThan"; + + if (value == ConditionTypeEnum.LessThanOrEqual) + return "lessThanOrEqual"; + + return null; + } + + /// + /// JsonConverter for writing ConditionTypeEnum. + /// + public class ConditionTypeEnumJsonConverter : JsonConverter + { + public override ConditionTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ConditionTypeEnum.FromStringOrDefault(value) ?? new ConditionTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ConditionTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ConditionTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Define when you want to get notified about a balance change. Possible values: * **greaterThan**: the balance in the account(s) exceeds the specified `value`. * **greaterThanOrEqual**: the balance in the account(s) reaches or exceeds the specified `value`. * **lessThan**: the balance in the account(s) drops below the specified `value`. * **lessThanOrEqual**: the balance in the account(s) reaches to drops below the specified `value`. + /// + /// Define when you want to get notified about a balance change. Possible values: * **greaterThan**: the balance in the account(s) exceeds the specified `value`. * **greaterThanOrEqual**: the balance in the account(s) reaches or exceeds the specified `value`. * **lessThan**: the balance in the account(s) drops below the specified `value`. * **lessThanOrEqual**: the balance in the account(s) reaches to drops below the specified `value`. + [JsonPropertyName("conditionType")] + public ConditionTypeEnum ConditionType { get; set; } + + /// + /// The value limit in the specified balance type and currency, in minor units. + /// + /// The value limit in the specified balance type and currency, in minor units. + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Condition {\n"); + sb.Append(" BalanceType: ").Append(BalanceType).Append("\n"); + sb.Append(" ConditionType: ").Append(ConditionType).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ConditionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Condition Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceType = default; + Option conditionType = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceType": + string? balanceTypeRawValue = utf8JsonReader.GetString(); + balanceType = new Option(Condition.BalanceTypeEnum.FromStringOrDefault(balanceTypeRawValue)); + break; + case "conditionType": + string? conditionTypeRawValue = utf8JsonReader.GetString(); + conditionType = new Option(Condition.ConditionTypeEnum.FromStringOrDefault(conditionTypeRawValue)); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!balanceType.IsSet) + throw new ArgumentException("Property is required for class Condition.", nameof(balanceType)); + + if (!conditionType.IsSet) + throw new ArgumentException("Property is required for class Condition.", nameof(conditionType)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Condition.", nameof(value)); + + return new Condition(balanceType.Value!.Value!, conditionType.Value!.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Condition condition, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, condition, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Condition condition, JsonSerializerOptions jsonSerializerOptions) + { + + if (condition.BalanceType != null) + { + string? balanceTypeRawValue = Condition.BalanceTypeEnum.ToJsonValue(condition.BalanceType); + writer.WriteString("balanceType", balanceTypeRawValue); + } + + if (condition.ConditionType != null) + { + string? conditionTypeRawValue = Condition.ConditionTypeEnum.ToJsonValue(condition.ConditionType); + writer.WriteString("conditionType", conditionTypeRawValue); + } + + writer.WriteNumber("value", condition.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ContactDetails.cs b/Adyen/BalancePlatform/Models/ContactDetails.cs new file mode 100644 index 000000000..fdfcfb1dc --- /dev/null +++ b/Adyen/BalancePlatform/Models/ContactDetails.cs @@ -0,0 +1,232 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ContactDetails. + /// + public partial class ContactDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The email address of the account holder. + /// phone + /// The URL of the account holder's website. + [JsonConstructor] + public ContactDetails(Address address, string email, Phone phone, Option webAddress = default) + { + Address = address; + Email = email; + Phone = phone; + _WebAddressOption = webAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ContactDetails() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public Address Address { get; set; } + + /// + /// The email address of the account holder. + /// + /// The email address of the account holder. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public Phone Phone { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressOption { get; private set; } + + /// + /// The URL of the account holder's website. + /// + /// The URL of the account holder's website. + [JsonPropertyName("webAddress")] + public string? WebAddress { get { return this._WebAddressOption; } set { this._WebAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ContactDetails {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" WebAddress: ").Append(WebAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ContactDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ContactDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option email = default; + Option phone = default; + Option webAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webAddress": + webAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(address)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(email)); + + if (!phone.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(phone)); + + return new ContactDetails(address.Value!, email.Value!, phone.Value!, webAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ContactDetails contactDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, contactDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ContactDetails contactDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, contactDetails.Address, jsonSerializerOptions); + if (contactDetails.Email != null) + writer.WriteString("email", contactDetails.Email); + + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, contactDetails.Phone, jsonSerializerOptions); + if (contactDetails._WebAddressOption.IsSet) + if (contactDetails.WebAddress != null) + writer.WriteString("webAddress", contactDetails.WebAddress); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Counterparty.cs b/Adyen/BalancePlatform/Models/Counterparty.cs new file mode 100644 index 000000000..894333879 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Counterparty.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Counterparty. + /// + public partial class Counterparty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bankAccount + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + [JsonConstructor] + public Counterparty(Option bankAccount = default, Option transferInstrumentId = default) + { + _BankAccountOption = bankAccount; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Counterparty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccount? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Counterparty {\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Counterparty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccount = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Counterparty(bankAccount, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Counterparty counterparty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterparty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Counterparty counterparty, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterparty._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, counterparty.BankAccount, jsonSerializerOptions); + } + if (counterparty._TransferInstrumentIdOption.IsSet) + if (counterparty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", counterparty.TransferInstrumentId); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CounterpartyBankRestriction.cs b/Adyen/BalancePlatform/Models/CounterpartyBankRestriction.cs new file mode 100644 index 000000000..91e68dc22 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CounterpartyBankRestriction.cs @@ -0,0 +1,198 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CounterpartyBankRestriction. + /// + public partial class CounterpartyBankRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// The list of counterparty bank institutions to be evaluated. + [JsonConstructor] + public CounterpartyBankRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CounterpartyBankRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// The list of counterparty bank institutions to be evaluated. + /// + /// The list of counterparty bank institutions to be evaluated. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CounterpartyBankRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyBankRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CounterpartyBankRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class CounterpartyBankRestriction.", nameof(operation)); + + return new CounterpartyBankRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CounterpartyBankRestriction counterpartyBankRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterpartyBankRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CounterpartyBankRestriction counterpartyBankRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterpartyBankRestriction.Operation != null) + writer.WriteString("operation", counterpartyBankRestriction.Operation); + + if (counterpartyBankRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, counterpartyBankRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CounterpartyTypesRestriction.cs b/Adyen/BalancePlatform/Models/CounterpartyTypesRestriction.cs new file mode 100644 index 000000000..c8b66dbb1 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CounterpartyTypesRestriction.cs @@ -0,0 +1,318 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CounterpartyTypesRestriction. + /// + public partial class CounterpartyTypesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// The list of counterparty types to be evaluated. + [JsonConstructor] + public CounterpartyTypesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CounterpartyTypesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.BalanceAccount - balanceAccount + /// + public static readonly ValueEnum BalanceAccount = new("balanceAccount"); + + /// + /// ValueEnum.BankAccount - bankAccount + /// + public static readonly ValueEnum BankAccount = new("bankAccount"); + + /// + /// ValueEnum.Card - card + /// + public static readonly ValueEnum Card = new("card"); + + /// + /// ValueEnum.TransferInstrument - transferInstrument + /// + public static readonly ValueEnum TransferInstrument = new("transferInstrument"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "balanceAccount" => ValueEnum.BalanceAccount, + "bankAccount" => ValueEnum.BankAccount, + "card" => ValueEnum.Card, + "transferInstrument" => ValueEnum.TransferInstrument, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.BalanceAccount) + return "balanceAccount"; + + if (value == ValueEnum.BankAccount) + return "bankAccount"; + + if (value == ValueEnum.Card) + return "card"; + + if (value == ValueEnum.TransferInstrument) + return "transferInstrument"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// The list of counterparty types to be evaluated. + /// + /// The list of counterparty types to be evaluated. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CounterpartyTypesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyTypesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CounterpartyTypesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class CounterpartyTypesRestriction.", nameof(operation)); + + return new CounterpartyTypesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CounterpartyTypesRestriction counterpartyTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterpartyTypesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CounterpartyTypesRestriction counterpartyTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterpartyTypesRestriction.Operation != null) + writer.WriteString("operation", counterpartyTypesRestriction.Operation); + + if (counterpartyTypesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, counterpartyTypesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CountriesRestriction.cs b/Adyen/BalancePlatform/Models/CountriesRestriction.cs new file mode 100644 index 000000000..c69f4ea13 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CountriesRestriction.cs @@ -0,0 +1,198 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CountriesRestriction. + /// + public partial class CountriesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. + [JsonConstructor] + public CountriesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CountriesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. + /// + /// List of two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CountriesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CountriesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CountriesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class CountriesRestriction.", nameof(operation)); + + return new CountriesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CountriesRestriction countriesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, countriesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CountriesRestriction countriesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (countriesRestriction.Operation != null) + writer.WriteString("operation", countriesRestriction.Operation); + + if (countriesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, countriesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CreateScaInformation.cs b/Adyen/BalancePlatform/Models/CreateScaInformation.cs new file mode 100644 index 000000000..7b0689e28 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CreateScaInformation.cs @@ -0,0 +1,203 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CreateScaInformation. + /// + public partial class CreateScaInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// exemption + /// Indicates whether to initiate Strong Customer Authentication (SCA) later, during approval, or immediately after you submit this request. Possible values: * **true**: you can initiate SCA later, during approval, for all pending transfer limits. * **false** (default): you initiate SCA immediately after submitting the transfer limit request. + [JsonConstructor] + public CreateScaInformation(Option exemption = default, Option scaOnApproval = default) + { + _ExemptionOption = exemption; + _ScaOnApprovalOption = scaOnApproval; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateScaInformation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("exemption")] + public ScaExemption? Exemption { get { return this._ExemptionOption; } set { this._ExemptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaOnApprovalOption { get; private set; } + + /// + /// Indicates whether to initiate Strong Customer Authentication (SCA) later, during approval, or immediately after you submit this request. Possible values: * **true**: you can initiate SCA later, during approval, for all pending transfer limits. * **false** (default): you initiate SCA immediately after submitting the transfer limit request. + /// + /// Indicates whether to initiate Strong Customer Authentication (SCA) later, during approval, or immediately after you submit this request. Possible values: * **true**: you can initiate SCA later, during approval, for all pending transfer limits. * **false** (default): you initiate SCA immediately after submitting the transfer limit request. + [JsonPropertyName("scaOnApproval")] + public bool? ScaOnApproval { get { return this._ScaOnApprovalOption; } set { this._ScaOnApprovalOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateScaInformation {\n"); + sb.Append(" Exemption: ").Append(Exemption).Append("\n"); + sb.Append(" ScaOnApproval: ").Append(ScaOnApproval).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateScaInformationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateScaInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option exemption = default; + Option scaOnApproval = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "exemption": + string? exemptionRawValue = utf8JsonReader.GetString(); + if (exemptionRawValue != null) + exemption = new Option(ScaExemptionValueConverter.FromStringOrDefault(exemptionRawValue)); + break; + case "scaOnApproval": + scaOnApproval = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new CreateScaInformation(exemption, scaOnApproval); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateScaInformation createScaInformation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createScaInformation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateScaInformation createScaInformation, JsonSerializerOptions jsonSerializerOptions) + { + + if (createScaInformation._ExemptionOption.IsSet) + { + var exemptionRawValue = ScaExemptionValueConverter.ToJsonValue(createScaInformation.Exemption!.Value); + writer.WriteString("exemption", exemptionRawValue); + } + if (createScaInformation._ScaOnApprovalOption.IsSet) + writer.WriteBoolean("scaOnApproval", createScaInformation._ScaOnApprovalOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/CreateSweepConfigurationV2.cs b/Adyen/BalancePlatform/Models/CreateSweepConfigurationV2.cs new file mode 100644 index 000000000..a6a099f92 --- /dev/null +++ b/Adyen/BalancePlatform/Models/CreateSweepConfigurationV2.cs @@ -0,0 +1,1298 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CreateSweepConfigurationV2. + /// + public partial class CreateSweepConfigurationV2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// counterparty + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// schedule + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The reason for disabling the sweep. + /// The human readable reason for disabling the sweep. + /// Your reference for the sweep configuration. + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// sweepAmount + /// targetAmount + /// triggerAmount + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. (default to TypeEnum.Push) + [JsonConstructor] + public CreateSweepConfigurationV2(SweepCounterparty counterparty, string currency, SweepSchedule schedule, Option category = default, Option description = default, Option?> priorities = default, Option reason = default, Option reasonDetail = default, Option reference = default, Option referenceForBeneficiary = default, Option status = default, Option sweepAmount = default, Option targetAmount = default, Option triggerAmount = default, Option type = default) + { + Counterparty = counterparty; + Currency = currency; + Schedule = schedule; + _CategoryOption = category; + _DescriptionOption = description; + _PrioritiesOption = priorities; + _ReasonOption = reason; + _ReasonDetailOption = reasonDetail; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _StatusOption = status; + _SweepAmountOption = sweepAmount; + _TargetAmountOption = targetAmount; + _TriggerAmountOption = triggerAmount; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateSweepConfigurationV2() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "internal" => CategoryEnum.Internal, + "platformPayment" => CategoryEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Pull - pull + /// + public static readonly TypeEnum Pull = new("pull"); + + /// + /// TypeEnum.Push - push + /// + public static readonly TypeEnum Push = new("push"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pull" => TypeEnum.Pull, + "push" => TypeEnum.Push, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Pull) + return "pull"; + + if (value == TypeEnum.Push) + return "push"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public SweepCounterparty Counterparty { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// . + /// + [JsonPropertyName("schedule")] + public SweepSchedule Schedule { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonDetailOption { get; } + + /// + /// The human readable reason for disabling the sweep. + /// + /// The human readable reason for disabling the sweep. + [JsonPropertyName("reasonDetail")] + public string? ReasonDetail { get { return this._ReasonDetailOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the sweep configuration. + /// + /// Your reference for the sweep configuration. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SweepAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sweepAmount")] + public Amount? SweepAmount { get { return this._SweepAmountOption; } set { this._SweepAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("targetAmount")] + public Amount? TargetAmount { get { return this._TargetAmountOption; } set { this._TargetAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TriggerAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("triggerAmount")] + public Amount? TriggerAmount { get { return this._TriggerAmountOption; } set { this._TriggerAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateSweepConfigurationV2 {\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Schedule: ").Append(Schedule).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" ReasonDetail: ").Append(ReasonDetail).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SweepAmount: ").Append(SweepAmount).Append("\n"); + sb.Append(" TargetAmount: ").Append(TargetAmount).Append("\n"); + sb.Append(" TriggerAmount: ").Append(TriggerAmount).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + // ReferenceForBeneficiary (string) maxLength + if (this.ReferenceForBeneficiary != null && this.ReferenceForBeneficiary.Length > 80) + { + yield return new ValidationResult("Invalid value for ReferenceForBeneficiary, length must be less than 80.", new [] { "ReferenceForBeneficiary" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateSweepConfigurationV2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateSweepConfigurationV2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option counterparty = default; + Option currency = default; + Option schedule = default; + Option category = default; + Option description = default; + Option?> priorities = default; + Option reason = default; + Option reasonDetail = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option status = default; + Option sweepAmount = default; + Option targetAmount = default; + Option triggerAmount = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "schedule": + schedule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(CreateSweepConfigurationV2.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(CreateSweepConfigurationV2.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reasonDetail": + reasonDetail = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(CreateSweepConfigurationV2.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "sweepAmount": + sweepAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "targetAmount": + targetAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "triggerAmount": + triggerAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CreateSweepConfigurationV2.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!counterparty.IsSet) + throw new ArgumentException("Property is required for class CreateSweepConfigurationV2.", nameof(counterparty)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class CreateSweepConfigurationV2.", nameof(currency)); + + if (!schedule.IsSet) + throw new ArgumentException("Property is required for class CreateSweepConfigurationV2.", nameof(schedule)); + + return new CreateSweepConfigurationV2(counterparty.Value!, currency.Value!, schedule.Value!, category, description, priorities, reason, reasonDetail, reference, referenceForBeneficiary, status, sweepAmount, targetAmount, triggerAmount, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateSweepConfigurationV2 createSweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createSweepConfigurationV2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateSweepConfigurationV2 createSweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.Counterparty, jsonSerializerOptions); + if (createSweepConfigurationV2.Currency != null) + writer.WriteString("currency", createSweepConfigurationV2.Currency); + + writer.WritePropertyName("schedule"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.Schedule, jsonSerializerOptions); + if (createSweepConfigurationV2._CategoryOption.IsSet && createSweepConfigurationV2.Category != null) + { + string? categoryRawValue = CreateSweepConfigurationV2.CategoryEnum.ToJsonValue(createSweepConfigurationV2._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (createSweepConfigurationV2._DescriptionOption.IsSet) + if (createSweepConfigurationV2.Description != null) + writer.WriteString("description", createSweepConfigurationV2.Description); + + if (createSweepConfigurationV2._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.Priorities, jsonSerializerOptions); + } + if (createSweepConfigurationV2._ReasonOption.IsSet && createSweepConfigurationV2.Reason != null) + { + string? reasonRawValue = CreateSweepConfigurationV2.ReasonEnum.ToJsonValue(createSweepConfigurationV2._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (createSweepConfigurationV2._ReasonDetailOption.IsSet) + if (createSweepConfigurationV2.ReasonDetail != null) + writer.WriteString("reasonDetail", createSweepConfigurationV2.ReasonDetail); + + if (createSweepConfigurationV2._ReferenceOption.IsSet) + if (createSweepConfigurationV2.Reference != null) + writer.WriteString("reference", createSweepConfigurationV2.Reference); + + if (createSweepConfigurationV2._ReferenceForBeneficiaryOption.IsSet) + if (createSweepConfigurationV2.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", createSweepConfigurationV2.ReferenceForBeneficiary); + + if (createSweepConfigurationV2._StatusOption.IsSet && createSweepConfigurationV2.Status != null) + { + string? statusRawValue = CreateSweepConfigurationV2.StatusEnum.ToJsonValue(createSweepConfigurationV2._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (createSweepConfigurationV2._SweepAmountOption.IsSet) + { + writer.WritePropertyName("sweepAmount"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.SweepAmount, jsonSerializerOptions); + } + if (createSweepConfigurationV2._TargetAmountOption.IsSet) + { + writer.WritePropertyName("targetAmount"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.TargetAmount, jsonSerializerOptions); + } + if (createSweepConfigurationV2._TriggerAmountOption.IsSet) + { + writer.WritePropertyName("triggerAmount"); + JsonSerializer.Serialize(writer, createSweepConfigurationV2.TriggerAmount, jsonSerializerOptions); + } + if (createSweepConfigurationV2._TypeOption.IsSet && createSweepConfigurationV2.Type != null) + { + string? typeRawValue = CreateSweepConfigurationV2.TypeEnum.ToJsonValue(createSweepConfigurationV2._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/CreateTransferLimitRequest.cs b/Adyen/BalancePlatform/Models/CreateTransferLimitRequest.cs new file mode 100644 index 000000000..2b2dcafae --- /dev/null +++ b/Adyen/BalancePlatform/Models/CreateTransferLimitRequest.cs @@ -0,0 +1,319 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// CreateTransferLimitRequest. + /// + public partial class CreateTransferLimitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// scope + /// transferType + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// Your reference for the transfer limit. + /// scaInformation + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + [JsonConstructor] + public CreateTransferLimitRequest(Amount amount, Scope scope, TransferType transferType, Option endsAt = default, Option reference = default, Option scaInformation = default, Option startsAt = default) + { + Amount = amount; + Scope = scope; + TransferType = transferType; + _EndsAtOption = endsAt; + _ReferenceOption = reference; + _ScaInformationOption = scaInformation; + _StartsAtOption = startsAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateTransferLimitRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("scope")] + public Scope Scope { get; set; } + + /// + /// . + /// + [JsonPropertyName("transferType")] + public TransferType TransferType { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndsAtOption { get; private set; } + + /// + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + [JsonPropertyName("endsAt")] + public DateTimeOffset? EndsAt { get { return this._EndsAtOption; } set { this._EndsAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer limit. + /// + /// Your reference for the transfer limit. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaInformationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("scaInformation")] + public CreateScaInformation? ScaInformation { get { return this._ScaInformationOption; } set { this._ScaInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartsAtOption { get; private set; } + + /// + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + [JsonPropertyName("startsAt")] + public DateTimeOffset? StartsAt { get { return this._StartsAtOption; } set { this._StartsAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateTransferLimitRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Scope: ").Append(Scope).Append("\n"); + sb.Append(" TransferType: ").Append(TransferType).Append("\n"); + sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ScaInformation: ").Append(ScaInformation).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateTransferLimitRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EndsAt. + /// + public static string EndsAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize StartsAt. + /// + public static string StartsAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateTransferLimitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option scope = default; + Option transferType = default; + Option endsAt = default; + Option reference = default; + Option scaInformation = default; + Option startsAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "scope": + string? scopeRawValue = utf8JsonReader.GetString(); + if (scopeRawValue != null) + scope = new Option(ScopeValueConverter.FromStringOrDefault(scopeRawValue)); + break; + case "transferType": + string? transferTypeRawValue = utf8JsonReader.GetString(); + if (transferTypeRawValue != null) + transferType = new Option(TransferTypeValueConverter.FromStringOrDefault(transferTypeRawValue)); + break; + case "endsAt": + endsAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "scaInformation": + scaInformation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "startsAt": + startsAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CreateTransferLimitRequest.", nameof(amount)); + + if (!scope.IsSet) + throw new ArgumentException("Property is required for class CreateTransferLimitRequest.", nameof(scope)); + + if (!transferType.IsSet) + throw new ArgumentException("Property is required for class CreateTransferLimitRequest.", nameof(transferType)); + + return new CreateTransferLimitRequest(amount.Value!, scope.Value!.Value!, transferType.Value!.Value!, endsAt, reference, scaInformation, startsAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateTransferLimitRequest createTransferLimitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createTransferLimitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateTransferLimitRequest createTransferLimitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, createTransferLimitRequest.Amount, jsonSerializerOptions); + var scopeRawValue = ScopeValueConverter.ToJsonValue(createTransferLimitRequest.Scope); + writer.WriteString("scope", scopeRawValue); + + var transferTypeRawValue = TransferTypeValueConverter.ToJsonValue(createTransferLimitRequest.TransferType); + writer.WriteString("transferType", transferTypeRawValue); + + if (createTransferLimitRequest._EndsAtOption.IsSet) + writer.WriteString("endsAt", createTransferLimitRequest._EndsAtOption.Value!.Value.ToString(EndsAtFormat)); + + if (createTransferLimitRequest._ReferenceOption.IsSet) + if (createTransferLimitRequest.Reference != null) + writer.WriteString("reference", createTransferLimitRequest.Reference); + + if (createTransferLimitRequest._ScaInformationOption.IsSet) + { + writer.WritePropertyName("scaInformation"); + JsonSerializer.Serialize(writer, createTransferLimitRequest.ScaInformation, jsonSerializerOptions); + } + if (createTransferLimitRequest._StartsAtOption.IsSet) + writer.WriteString("startsAt", createTransferLimitRequest._StartsAtOption.Value!.Value.ToString(StartsAtFormat)); + } + } +} diff --git a/Adyen/BalancePlatform/Models/DKLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/DKLocalAccountIdentification.cs new file mode 100644 index 000000000..687ba7884 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DKLocalAccountIdentification. + /// + public partial class DKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// **dkLocal** (default to TypeEnum.DkLocal) + [JsonConstructor] + public DKLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DkLocal - dkLocal + /// + public static readonly TypeEnum DkLocal = new("dkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dkLocal" => TypeEnum.DkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DkLocal) + return "dkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(type)); + + return new DKLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (dKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", dKLocalAccountIdentification.AccountNumber); + + if (dKLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", dKLocalAccountIdentification.BankCode); + + if (dKLocalAccountIdentification.Type != null) + { + string? typeRawValue = DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/DayOfWeekRestriction.cs b/Adyen/BalancePlatform/Models/DayOfWeekRestriction.cs new file mode 100644 index 000000000..a9adc3272 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DayOfWeekRestriction.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DayOfWeekRestriction. + /// + public partial class DayOfWeekRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of days of the week. Possible values: **monday**, **tuesday**, **wednesday**, **thursday**, **friday**, **saturday**, **sunday**. + [JsonConstructor] + public DayOfWeekRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DayOfWeekRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.Friday - friday + /// + public static readonly ValueEnum Friday = new("friday"); + + /// + /// ValueEnum.Monday - monday + /// + public static readonly ValueEnum Monday = new("monday"); + + /// + /// ValueEnum.Saturday - saturday + /// + public static readonly ValueEnum Saturday = new("saturday"); + + /// + /// ValueEnum.Sunday - sunday + /// + public static readonly ValueEnum Sunday = new("sunday"); + + /// + /// ValueEnum.Thursday - thursday + /// + public static readonly ValueEnum Thursday = new("thursday"); + + /// + /// ValueEnum.Tuesday - tuesday + /// + public static readonly ValueEnum Tuesday = new("tuesday"); + + /// + /// ValueEnum.Wednesday - wednesday + /// + public static readonly ValueEnum Wednesday = new("wednesday"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "friday" => ValueEnum.Friday, + "monday" => ValueEnum.Monday, + "saturday" => ValueEnum.Saturday, + "sunday" => ValueEnum.Sunday, + "thursday" => ValueEnum.Thursday, + "tuesday" => ValueEnum.Tuesday, + "wednesday" => ValueEnum.Wednesday, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.Friday) + return "friday"; + + if (value == ValueEnum.Monday) + return "monday"; + + if (value == ValueEnum.Saturday) + return "saturday"; + + if (value == ValueEnum.Sunday) + return "sunday"; + + if (value == ValueEnum.Thursday) + return "thursday"; + + if (value == ValueEnum.Tuesday) + return "tuesday"; + + if (value == ValueEnum.Wednesday) + return "wednesday"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of days of the week. Possible values: **monday**, **tuesday**, **wednesday**, **thursday**, **friday**, **saturday**, **sunday**. + /// + /// List of days of the week. Possible values: **monday**, **tuesday**, **wednesday**, **thursday**, **friday**, **saturday**, **sunday**. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DayOfWeekRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DayOfWeekRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DayOfWeekRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class DayOfWeekRestriction.", nameof(operation)); + + return new DayOfWeekRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DayOfWeekRestriction dayOfWeekRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dayOfWeekRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DayOfWeekRestriction dayOfWeekRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (dayOfWeekRestriction.Operation != null) + writer.WriteString("operation", dayOfWeekRestriction.Operation); + + if (dayOfWeekRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, dayOfWeekRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/DefaultErrorResponseEntity.cs b/Adyen/BalancePlatform/Models/DefaultErrorResponseEntity.cs new file mode 100644 index 000000000..480af4ad5 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DefaultErrorResponseEntity.cs @@ -0,0 +1,352 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Standardized error response following RFC-7807 format. + /// + public partial class DefaultErrorResponseEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// Unique business error code. + /// A URI that identifies the specific occurrence of the problem if applicable. + /// Array of fields with validation errors when applicable. + /// The unique reference for the request. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonConstructor] + public DefaultErrorResponseEntity(Option detail = default, Option errorCode = default, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option status = default, Option title = default, Option type = default) + { + _DetailOption = detail; + _ErrorCodeOption = errorCode; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _StatusOption = status; + _TitleOption = title; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefaultErrorResponseEntity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailOption { get; private set; } + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string? Detail { get { return this._DetailOption; } set { this._DetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// Unique business error code. + /// + /// Unique business error code. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Array of fields with validation errors when applicable. + /// + /// Array of fields with validation errors when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// The unique reference for the request. + /// + /// The unique reference for the request. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefaultErrorResponseEntity {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefaultErrorResponseEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefaultErrorResponseEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option status = default; + Option title = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DefaultErrorResponseEntity(detail, errorCode, instance, invalidFields, requestId, status, title, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defaultErrorResponseEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (defaultErrorResponseEntity._DetailOption.IsSet) + if (defaultErrorResponseEntity.Detail != null) + writer.WriteString("detail", defaultErrorResponseEntity.Detail); + + if (defaultErrorResponseEntity._ErrorCodeOption.IsSet) + if (defaultErrorResponseEntity.ErrorCode != null) + writer.WriteString("errorCode", defaultErrorResponseEntity.ErrorCode); + + if (defaultErrorResponseEntity._InstanceOption.IsSet) + if (defaultErrorResponseEntity.Instance != null) + writer.WriteString("instance", defaultErrorResponseEntity.Instance); + + if (defaultErrorResponseEntity._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, defaultErrorResponseEntity.InvalidFields, jsonSerializerOptions); + } + if (defaultErrorResponseEntity._RequestIdOption.IsSet) + if (defaultErrorResponseEntity.RequestId != null) + writer.WriteString("requestId", defaultErrorResponseEntity.RequestId); + + if (defaultErrorResponseEntity._StatusOption.IsSet) + writer.WriteNumber("status", defaultErrorResponseEntity._StatusOption.Value!.Value); + + if (defaultErrorResponseEntity._TitleOption.IsSet) + if (defaultErrorResponseEntity.Title != null) + writer.WriteString("title", defaultErrorResponseEntity.Title); + + if (defaultErrorResponseEntity._TypeOption.IsSet) + if (defaultErrorResponseEntity.Type != null) + writer.WriteString("type", defaultErrorResponseEntity.Type); + } + } +} diff --git a/Adyen/BalancePlatform/Models/DelegatedAuthenticationData.cs b/Adyen/BalancePlatform/Models/DelegatedAuthenticationData.cs new file mode 100644 index 000000000..eafebe675 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DelegatedAuthenticationData.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DelegatedAuthenticationData. + /// + public partial class DelegatedAuthenticationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using our authentication SDK. + [JsonConstructor] + public DelegatedAuthenticationData(string sdkOutput) + { + SdkOutput = sdkOutput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DelegatedAuthenticationData() + { + } + + partial void OnCreated(); + + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using our authentication SDK. + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using our authentication SDK. + [JsonPropertyName("sdkOutput")] + public string SdkOutput { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DelegatedAuthenticationData {\n"); + sb.Append(" SdkOutput: ").Append(SdkOutput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkOutput (string) maxLength + if (this.SdkOutput != null && this.SdkOutput.Length > 20000) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be less than 20000.", new [] { "SdkOutput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DelegatedAuthenticationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DelegatedAuthenticationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkOutput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkOutput": + sdkOutput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!sdkOutput.IsSet) + throw new ArgumentException("Property is required for class DelegatedAuthenticationData.", nameof(sdkOutput)); + + return new DelegatedAuthenticationData(sdkOutput.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DelegatedAuthenticationData delegatedAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, delegatedAuthenticationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DelegatedAuthenticationData delegatedAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (delegatedAuthenticationData.SdkOutput != null) + writer.WriteString("sdkOutput", delegatedAuthenticationData.SdkOutput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/DeliveryAddress.cs b/Adyen/BalancePlatform/Models/DeliveryAddress.cs new file mode 100644 index 000000000..3c50b48fd --- /dev/null +++ b/Adyen/BalancePlatform/Models/DeliveryAddress.cs @@ -0,0 +1,321 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DeliveryAddress. + /// + public partial class DeliveryAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The name of the city. + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + /// Additional information about the delivery address. + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + [JsonConstructor] + public DeliveryAddress(string country, Option city = default, Option line1 = default, Option line2 = default, Option line3 = default, Option postalCode = default, Option stateOrProvince = default) + { + Country = country; + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryAddress() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + /// + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + /// + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Additional information about the delivery address. + /// + /// Additional information about the delivery address. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + /// + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryAddress {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(country)); + + return new DeliveryAddress(country.Value!, city, line1, line2, line3, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (deliveryAddress.Country != null) + writer.WriteString("country", deliveryAddress.Country); + + if (deliveryAddress._CityOption.IsSet) + if (deliveryAddress.City != null) + writer.WriteString("city", deliveryAddress.City); + + if (deliveryAddress._Line1Option.IsSet) + if (deliveryAddress.Line1 != null) + writer.WriteString("line1", deliveryAddress.Line1); + + if (deliveryAddress._Line2Option.IsSet) + if (deliveryAddress.Line2 != null) + writer.WriteString("line2", deliveryAddress.Line2); + + if (deliveryAddress._Line3Option.IsSet) + if (deliveryAddress.Line3 != null) + writer.WriteString("line3", deliveryAddress.Line3); + + if (deliveryAddress._PostalCodeOption.IsSet) + if (deliveryAddress.PostalCode != null) + writer.WriteString("postalCode", deliveryAddress.PostalCode); + + if (deliveryAddress._StateOrProvinceOption.IsSet) + if (deliveryAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", deliveryAddress.StateOrProvince); + } + } +} diff --git a/Adyen/BalancePlatform/Models/DeliveryContact.cs b/Adyen/BalancePlatform/Models/DeliveryContact.cs new file mode 100644 index 000000000..3dc39d367 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DeliveryContact.cs @@ -0,0 +1,312 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DeliveryContact. + /// + public partial class DeliveryContact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// name + /// The company name of the contact. + /// The email address of the contact. + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + /// phoneNumber + /// The URL of the contact's website. + [JsonConstructor] + public DeliveryContact(DeliveryAddress address, Name name, Option company = default, Option email = default, Option fullPhoneNumber = default, Option phoneNumber = default, Option webAddress = default) + { + Address = address; + Name = name; + _CompanyOption = company; + _EmailOption = email; + _FullPhoneNumberOption = fullPhoneNumber; + _PhoneNumberOption = phoneNumber; + _WebAddressOption = webAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryContact() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public DeliveryAddress Address { get; set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name Name { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// The company name of the contact. + /// + /// The company name of the contact. + [JsonPropertyName("company")] + public string? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the contact. + /// + /// The email address of the contact. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullPhoneNumberOption { get; private set; } + + /// + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + /// + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + [JsonPropertyName("fullPhoneNumber")] + public string? FullPhoneNumber { get { return this._FullPhoneNumberOption; } set { this._FullPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phoneNumber")] + public PhoneNumber? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressOption { get; private set; } + + /// + /// The URL of the contact's website. + /// + /// The URL of the contact's website. + [JsonPropertyName("webAddress")] + public string? WebAddress { get { return this._WebAddressOption; } set { this._WebAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryContact {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FullPhoneNumber: ").Append(FullPhoneNumber).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" WebAddress: ").Append(WebAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryContactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryContact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option name = default; + Option company = default; + Option email = default; + Option fullPhoneNumber = default; + Option phoneNumber = default; + Option webAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "company": + company = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "fullPhoneNumber": + fullPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webAddress": + webAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class DeliveryContact.", nameof(address)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class DeliveryContact.", nameof(name)); + + return new DeliveryContact(address.Value!, name.Value!, company, email, fullPhoneNumber, phoneNumber, webAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryContact deliveryContact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryContact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryContact deliveryContact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, deliveryContact.Address, jsonSerializerOptions); + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, deliveryContact.Name, jsonSerializerOptions); + if (deliveryContact._CompanyOption.IsSet) + if (deliveryContact.Company != null) + writer.WriteString("company", deliveryContact.Company); + + if (deliveryContact._EmailOption.IsSet) + if (deliveryContact.Email != null) + writer.WriteString("email", deliveryContact.Email); + + if (deliveryContact._FullPhoneNumberOption.IsSet) + if (deliveryContact.FullPhoneNumber != null) + writer.WriteString("fullPhoneNumber", deliveryContact.FullPhoneNumber); + + if (deliveryContact._PhoneNumberOption.IsSet) + { + writer.WritePropertyName("phoneNumber"); + JsonSerializer.Serialize(writer, deliveryContact.PhoneNumber, jsonSerializerOptions); + } + if (deliveryContact._WebAddressOption.IsSet) + if (deliveryContact.WebAddress != null) + writer.WriteString("webAddress", deliveryContact.WebAddress); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Device.cs b/Adyen/BalancePlatform/Models/Device.cs new file mode 100644 index 000000000..d5b16e987 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Device.cs @@ -0,0 +1,367 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Device. + /// + public partial class Device : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the SCA device. + /// The name of the SCA device. You can show this name to your user to help them identify the device. + /// The unique identifier of the payment instrument that is associated with the SCA device. + /// The type of device. Possible values: **ios**, **android**, **browser**. + [JsonConstructor] + public Device(Option id = default, Option name = default, Option paymentInstrumentId = default, Option type = default) + { + _IdOption = id; + _NameOption = name; + _PaymentInstrumentIdOption = paymentInstrumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Device() + { + } + + partial void OnCreated(); + + /// + /// The type of device. Possible values: **ios**, **android**, **browser**. + /// + /// The type of device. Possible values: **ios**, **android**, **browser**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ios - ios + /// + public static readonly TypeEnum Ios = new("ios"); + + /// + /// TypeEnum.Android - android + /// + public static readonly TypeEnum Android = new("android"); + + /// + /// TypeEnum.Browser - browser + /// + public static readonly TypeEnum Browser = new("browser"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ios" => TypeEnum.Ios, + "android" => TypeEnum.Android, + "browser" => TypeEnum.Browser, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ios) + return "ios"; + + if (value == TypeEnum.Android) + return "android"; + + if (value == TypeEnum.Browser) + return "browser"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of device. Possible values: **ios**, **android**, **browser**. + /// + /// The type of device. Possible values: **ios**, **android**, **browser**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the SCA device. + /// + /// The unique identifier of the SCA device. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the SCA device. You can show this name to your user to help them identify the device. + /// + /// The name of the SCA device. You can show this name to your user to help them identify the device. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that is associated with the SCA device. + /// + /// The unique identifier of the payment instrument that is associated with the SCA device. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Device {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Device Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option paymentInstrumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Device.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new Device(id, name, paymentInstrumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Device device, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, device, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Device device, JsonSerializerOptions jsonSerializerOptions) + { + + if (device._IdOption.IsSet) + if (device.Id != null) + writer.WriteString("id", device.Id); + + if (device._NameOption.IsSet) + if (device.Name != null) + writer.WriteString("name", device.Name); + + if (device._PaymentInstrumentIdOption.IsSet) + if (device.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", device.PaymentInstrumentId); + + if (device._TypeOption.IsSet && device.Type != null) + { + string? typeRawValue = Device.TypeEnum.ToJsonValue(device._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/DeviceInfo.cs b/Adyen/BalancePlatform/Models/DeviceInfo.cs new file mode 100644 index 000000000..83eb95819 --- /dev/null +++ b/Adyen/BalancePlatform/Models/DeviceInfo.cs @@ -0,0 +1,428 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DeviceInfo. + /// + public partial class DeviceInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The technology used to capture the card details. + /// The name of the device. + /// The form factor of the device to be provisioned. + /// The IMEI number of the device being provisioned. + /// The 2-digit device type provided on the ISO messages that the token is being provisioned to. + /// The MSISDN of the device being provisioned. + /// The name of the device operating system. + /// The version of the device operating system. + /// Different types of payments supported for the network token. + /// The serial number of the device. + /// The architecture or technology used for network token storage. + [JsonConstructor] + public DeviceInfo(Option cardCaptureTechnology = default, Option deviceName = default, Option formFactor = default, Option imei = default, Option isoDeviceType = default, Option msisdn = default, Option osName = default, Option osVersion = default, Option?> paymentTypes = default, Option serialNumber = default, Option storageTechnology = default) + { + _CardCaptureTechnologyOption = cardCaptureTechnology; + _DeviceNameOption = deviceName; + _FormFactorOption = formFactor; + _ImeiOption = imei; + _IsoDeviceTypeOption = isoDeviceType; + _MsisdnOption = msisdn; + _OsNameOption = osName; + _OsVersionOption = osVersion; + _PaymentTypesOption = paymentTypes; + _SerialNumberOption = serialNumber; + _StorageTechnologyOption = storageTechnology; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeviceInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardCaptureTechnologyOption { get; private set; } + + /// + /// The technology used to capture the card details. + /// + /// The technology used to capture the card details. + [JsonPropertyName("cardCaptureTechnology")] + public string? CardCaptureTechnology { get { return this._CardCaptureTechnologyOption; } set { this._CardCaptureTechnologyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceNameOption { get; private set; } + + /// + /// The name of the device. + /// + /// The name of the device. + [JsonPropertyName("deviceName")] + public string? DeviceName { get { return this._DeviceNameOption; } set { this._DeviceNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FormFactorOption { get; private set; } + + /// + /// The form factor of the device to be provisioned. + /// + /// The form factor of the device to be provisioned. + [JsonPropertyName("formFactor")] + public string? FormFactor { get { return this._FormFactorOption; } set { this._FormFactorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ImeiOption { get; private set; } + + /// + /// The IMEI number of the device being provisioned. + /// + /// The IMEI number of the device being provisioned. + [JsonPropertyName("imei")] + public string? Imei { get { return this._ImeiOption; } set { this._ImeiOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IsoDeviceTypeOption { get; private set; } + + /// + /// The 2-digit device type provided on the ISO messages that the token is being provisioned to. + /// + /// The 2-digit device type provided on the ISO messages that the token is being provisioned to. + [JsonPropertyName("isoDeviceType")] + public string? IsoDeviceType { get { return this._IsoDeviceTypeOption; } set { this._IsoDeviceTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MsisdnOption { get; private set; } + + /// + /// The MSISDN of the device being provisioned. + /// + /// The MSISDN of the device being provisioned. + [JsonPropertyName("msisdn")] + public string? Msisdn { get { return this._MsisdnOption; } set { this._MsisdnOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsNameOption { get; private set; } + + /// + /// The name of the device operating system. + /// + /// The name of the device operating system. + [JsonPropertyName("osName")] + public string? OsName { get { return this._OsNameOption; } set { this._OsNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsVersionOption { get; private set; } + + /// + /// The version of the device operating system. + /// + /// The version of the device operating system. + [JsonPropertyName("osVersion")] + public string? OsVersion { get { return this._OsVersionOption; } set { this._OsVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PaymentTypesOption { get; private set; } + + /// + /// Different types of payments supported for the network token. + /// + /// Different types of payments supported for the network token. + [JsonPropertyName("paymentTypes")] + public List? PaymentTypes { get { return this._PaymentTypesOption; } set { this._PaymentTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SerialNumberOption { get; private set; } + + /// + /// The serial number of the device. + /// + /// The serial number of the device. + [JsonPropertyName("serialNumber")] + public string? SerialNumber { get { return this._SerialNumberOption; } set { this._SerialNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorageTechnologyOption { get; private set; } + + /// + /// The architecture or technology used for network token storage. + /// + /// The architecture or technology used for network token storage. + [JsonPropertyName("storageTechnology")] + public string? StorageTechnology { get { return this._StorageTechnologyOption; } set { this._StorageTechnologyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeviceInfo {\n"); + sb.Append(" CardCaptureTechnology: ").Append(CardCaptureTechnology).Append("\n"); + sb.Append(" DeviceName: ").Append(DeviceName).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Imei: ").Append(Imei).Append("\n"); + sb.Append(" IsoDeviceType: ").Append(IsoDeviceType).Append("\n"); + sb.Append(" Msisdn: ").Append(Msisdn).Append("\n"); + sb.Append(" OsName: ").Append(OsName).Append("\n"); + sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); + sb.Append(" PaymentTypes: ").Append(PaymentTypes).Append("\n"); + sb.Append(" SerialNumber: ").Append(SerialNumber).Append("\n"); + sb.Append(" StorageTechnology: ").Append(StorageTechnology).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeviceInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeviceInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardCaptureTechnology = default; + Option deviceName = default; + Option formFactor = default; + Option imei = default; + Option isoDeviceType = default; + Option msisdn = default; + Option osName = default; + Option osVersion = default; + Option?> paymentTypes = default; + Option serialNumber = default; + Option storageTechnology = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardCaptureTechnology": + cardCaptureTechnology = new Option(utf8JsonReader.GetString()!); + break; + case "deviceName": + deviceName = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + formFactor = new Option(utf8JsonReader.GetString()!); + break; + case "imei": + imei = new Option(utf8JsonReader.GetString()!); + break; + case "isoDeviceType": + isoDeviceType = new Option(utf8JsonReader.GetString()!); + break; + case "msisdn": + msisdn = new Option(utf8JsonReader.GetString()!); + break; + case "osName": + osName = new Option(utf8JsonReader.GetString()!); + break; + case "osVersion": + osVersion = new Option(utf8JsonReader.GetString()!); + break; + case "paymentTypes": + paymentTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "serialNumber": + serialNumber = new Option(utf8JsonReader.GetString()!); + break; + case "storageTechnology": + storageTechnology = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DeviceInfo(cardCaptureTechnology, deviceName, formFactor, imei, isoDeviceType, msisdn, osName, osVersion, paymentTypes, serialNumber, storageTechnology); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeviceInfo deviceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deviceInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeviceInfo deviceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (deviceInfo._CardCaptureTechnologyOption.IsSet) + if (deviceInfo.CardCaptureTechnology != null) + writer.WriteString("cardCaptureTechnology", deviceInfo.CardCaptureTechnology); + + if (deviceInfo._DeviceNameOption.IsSet) + if (deviceInfo.DeviceName != null) + writer.WriteString("deviceName", deviceInfo.DeviceName); + + if (deviceInfo._FormFactorOption.IsSet) + if (deviceInfo.FormFactor != null) + writer.WriteString("formFactor", deviceInfo.FormFactor); + + if (deviceInfo._ImeiOption.IsSet) + if (deviceInfo.Imei != null) + writer.WriteString("imei", deviceInfo.Imei); + + if (deviceInfo._IsoDeviceTypeOption.IsSet) + if (deviceInfo.IsoDeviceType != null) + writer.WriteString("isoDeviceType", deviceInfo.IsoDeviceType); + + if (deviceInfo._MsisdnOption.IsSet) + if (deviceInfo.Msisdn != null) + writer.WriteString("msisdn", deviceInfo.Msisdn); + + if (deviceInfo._OsNameOption.IsSet) + if (deviceInfo.OsName != null) + writer.WriteString("osName", deviceInfo.OsName); + + if (deviceInfo._OsVersionOption.IsSet) + if (deviceInfo.OsVersion != null) + writer.WriteString("osVersion", deviceInfo.OsVersion); + + if (deviceInfo._PaymentTypesOption.IsSet) + { + writer.WritePropertyName("paymentTypes"); + JsonSerializer.Serialize(writer, deviceInfo.PaymentTypes, jsonSerializerOptions); + } + if (deviceInfo._SerialNumberOption.IsSet) + if (deviceInfo.SerialNumber != null) + writer.WriteString("serialNumber", deviceInfo.SerialNumber); + + if (deviceInfo._StorageTechnologyOption.IsSet) + if (deviceInfo.StorageTechnology != null) + writer.WriteString("storageTechnology", deviceInfo.StorageTechnology); + } + } +} diff --git a/Adyen/BalancePlatform/Models/DifferentCurrenciesRestriction.cs b/Adyen/BalancePlatform/Models/DifferentCurrenciesRestriction.cs new file mode 100644 index 000000000..d28127e5d --- /dev/null +++ b/Adyen/BalancePlatform/Models/DifferentCurrenciesRestriction.cs @@ -0,0 +1,195 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// DifferentCurrenciesRestriction. + /// + public partial class DifferentCurrenciesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// Checks the currency of the payment against the currency of the payment instrument. Possible values: - **true**: The currency of the payment is different from the currency of the payment instrument. - **false**: The currencies are the same. + [JsonConstructor] + public DifferentCurrenciesRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DifferentCurrenciesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// Checks the currency of the payment against the currency of the payment instrument. Possible values: - **true**: The currency of the payment is different from the currency of the payment instrument. - **false**: The currencies are the same. + /// + /// Checks the currency of the payment against the currency of the payment instrument. Possible values: - **true**: The currency of the payment is different from the currency of the payment instrument. - **false**: The currencies are the same. + [JsonPropertyName("value")] + public bool? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DifferentCurrenciesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DifferentCurrenciesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DifferentCurrenciesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class DifferentCurrenciesRestriction.", nameof(operation)); + + return new DifferentCurrenciesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DifferentCurrenciesRestriction differentCurrenciesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, differentCurrenciesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DifferentCurrenciesRestriction differentCurrenciesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (differentCurrenciesRestriction.Operation != null) + writer.WriteString("operation", differentCurrenciesRestriction.Operation); + + if (differentCurrenciesRestriction._ValueOption.IsSet) + writer.WriteBoolean("value", differentCurrenciesRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Duration.cs b/Adyen/BalancePlatform/Models/Duration.cs new file mode 100644 index 000000000..74c1f426c --- /dev/null +++ b/Adyen/BalancePlatform/Models/Duration.cs @@ -0,0 +1,334 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Duration. + /// + public partial class Duration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unit of time. You can only use **minutes** and **hours** if the `interval.type` is **sliding**. Possible values: **minutes**, **hours**, **days**, **weeks**, or **months** + /// The length of time by the unit. For example, 5 days. The maximum duration is 90 days or an equivalent in other units. For example, 3 months. + [JsonConstructor] + public Duration(Option unit = default, Option value = default) + { + _UnitOption = unit; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Duration() + { + } + + partial void OnCreated(); + + /// + /// The unit of time. You can only use **minutes** and **hours** if the `interval.type` is **sliding**. Possible values: **minutes**, **hours**, **days**, **weeks**, or **months** + /// + /// The unit of time. You can only use **minutes** and **hours** if the `interval.type` is **sliding**. Possible values: **minutes**, **hours**, **days**, **weeks**, or **months** + [JsonConverter(typeof(UnitEnumJsonConverter))] + public class UnitEnum : IEnum + { + /// + /// Returns the value of the UnitEnum. + /// + public string? Value { get; set; } + + /// + /// UnitEnum.Days - days + /// + public static readonly UnitEnum Days = new("days"); + + /// + /// UnitEnum.Hours - hours + /// + public static readonly UnitEnum Hours = new("hours"); + + /// + /// UnitEnum.Minutes - minutes + /// + public static readonly UnitEnum Minutes = new("minutes"); + + /// + /// UnitEnum.Months - months + /// + public static readonly UnitEnum Months = new("months"); + + /// + /// UnitEnum.Weeks - weeks + /// + public static readonly UnitEnum Weeks = new("weeks"); + + private UnitEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator UnitEnum?(string? value) => value == null ? null : new UnitEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(UnitEnum? option) => option?.Value; + + public static bool operator ==(UnitEnum? left, UnitEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(UnitEnum? left, UnitEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is UnitEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static UnitEnum? FromStringOrDefault(string value) + { + return value switch { + "days" => UnitEnum.Days, + "hours" => UnitEnum.Hours, + "minutes" => UnitEnum.Minutes, + "months" => UnitEnum.Months, + "weeks" => UnitEnum.Weeks, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(UnitEnum? value) + { + if (value == null) + return null; + + if (value == UnitEnum.Days) + return "days"; + + if (value == UnitEnum.Hours) + return "hours"; + + if (value == UnitEnum.Minutes) + return "minutes"; + + if (value == UnitEnum.Months) + return "months"; + + if (value == UnitEnum.Weeks) + return "weeks"; + + return null; + } + + /// + /// JsonConverter for writing UnitEnum. + /// + public class UnitEnumJsonConverter : JsonConverter + { + public override UnitEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : UnitEnum.FromStringOrDefault(value) ?? new UnitEnum(value); + } + + public override void Write(Utf8JsonWriter writer, UnitEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(UnitEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnitOption { get; private set; } + + /// + /// The unit of time. You can only use **minutes** and **hours** if the `interval.type` is **sliding**. Possible values: **minutes**, **hours**, **days**, **weeks**, or **months** + /// + /// The unit of time. You can only use **minutes** and **hours** if the `interval.type` is **sliding**. Possible values: **minutes**, **hours**, **days**, **weeks**, or **months** + [JsonPropertyName("unit")] + public UnitEnum? Unit { get { return this._UnitOption; } set { this._UnitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The length of time by the unit. For example, 5 days. The maximum duration is 90 days or an equivalent in other units. For example, 3 months. + /// + /// The length of time by the unit. For example, 5 days. The maximum duration is 90 days or an equivalent in other units. For example, 3 months. + [JsonPropertyName("value")] + public int? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Duration {\n"); + sb.Append(" Unit: ").Append(Unit).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Duration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option unit = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "unit": + string? unitRawValue = utf8JsonReader.GetString(); + unit = new Option(Duration.UnitEnum.FromStringOrDefault(unitRawValue)); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Duration(unit, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Duration duration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, duration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Duration duration, JsonSerializerOptions jsonSerializerOptions) + { + + if (duration._UnitOption.IsSet && duration.Unit != null) + { + string? unitRawValue = Duration.UnitEnum.ToJsonValue(duration._UnitOption.Value!.Value); + writer.WriteString("unit", unitRawValue); + } + + if (duration._ValueOption.IsSet) + writer.WriteNumber("value", duration._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/EntryModesRestriction.cs b/Adyen/BalancePlatform/Models/EntryModesRestriction.cs new file mode 100644 index 000000000..2ced9e4fe --- /dev/null +++ b/Adyen/BalancePlatform/Models/EntryModesRestriction.cs @@ -0,0 +1,363 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// EntryModesRestriction. + /// + public partial class EntryModesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of point-of-sale entry modes. Possible values: **barcode**, **chip**, **cof**, **contactless**, **magstripe**, **manual**, **ocr**, **server**. + [JsonConstructor] + public EntryModesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EntryModesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.Barcode - barcode + /// + public static readonly ValueEnum Barcode = new("barcode"); + + /// + /// ValueEnum.Chip - chip + /// + public static readonly ValueEnum Chip = new("chip"); + + /// + /// ValueEnum.Cof - cof + /// + public static readonly ValueEnum Cof = new("cof"); + + /// + /// ValueEnum.Contactless - contactless + /// + public static readonly ValueEnum Contactless = new("contactless"); + + /// + /// ValueEnum.Magstripe - magstripe + /// + public static readonly ValueEnum Magstripe = new("magstripe"); + + /// + /// ValueEnum.Manual - manual + /// + public static readonly ValueEnum Manual = new("manual"); + + /// + /// ValueEnum.Ocr - ocr + /// + public static readonly ValueEnum Ocr = new("ocr"); + + /// + /// ValueEnum.Server - server + /// + public static readonly ValueEnum Server = new("server"); + + /// + /// ValueEnum.Unknown - unknown + /// + public static readonly ValueEnum Unknown = new("unknown"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "barcode" => ValueEnum.Barcode, + "chip" => ValueEnum.Chip, + "cof" => ValueEnum.Cof, + "contactless" => ValueEnum.Contactless, + "magstripe" => ValueEnum.Magstripe, + "manual" => ValueEnum.Manual, + "ocr" => ValueEnum.Ocr, + "server" => ValueEnum.Server, + "unknown" => ValueEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.Barcode) + return "barcode"; + + if (value == ValueEnum.Chip) + return "chip"; + + if (value == ValueEnum.Cof) + return "cof"; + + if (value == ValueEnum.Contactless) + return "contactless"; + + if (value == ValueEnum.Magstripe) + return "magstripe"; + + if (value == ValueEnum.Manual) + return "manual"; + + if (value == ValueEnum.Ocr) + return "ocr"; + + if (value == ValueEnum.Server) + return "server"; + + if (value == ValueEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of point-of-sale entry modes. Possible values: **barcode**, **chip**, **cof**, **contactless**, **magstripe**, **manual**, **ocr**, **server**. + /// + /// List of point-of-sale entry modes. Possible values: **barcode**, **chip**, **cof**, **contactless**, **magstripe**, **manual**, **ocr**, **server**. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EntryModesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EntryModesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EntryModesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class EntryModesRestriction.", nameof(operation)); + + return new EntryModesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EntryModesRestriction entryModesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, entryModesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EntryModesRestriction entryModesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (entryModesRestriction.Operation != null) + writer.WriteString("operation", entryModesRestriction.Operation); + + if (entryModesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, entryModesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Expiry.cs b/Adyen/BalancePlatform/Models/Expiry.cs new file mode 100644 index 000000000..231f91a6d --- /dev/null +++ b/Adyen/BalancePlatform/Models/Expiry.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Expiry. + /// + public partial class Expiry : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The month in which the card will expire. + /// The year in which the card will expire. + [JsonConstructor] + public Expiry(Option month = default, Option year = default) + { + _MonthOption = month; + _YearOption = year; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Expiry() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MonthOption { get; private set; } + + /// + /// The month in which the card will expire. + /// + /// The month in which the card will expire. + [JsonPropertyName("month")] + public string? Month { get { return this._MonthOption; } set { this._MonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _YearOption { get; private set; } + + /// + /// The year in which the card will expire. + /// + /// The year in which the card will expire. + [JsonPropertyName("year")] + public string? Year { get { return this._YearOption; } set { this._YearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Expiry {\n"); + sb.Append(" Month: ").Append(Month).Append("\n"); + sb.Append(" Year: ").Append(Year).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExpiryJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Expiry Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option month = default; + Option year = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "month": + month = new Option(utf8JsonReader.GetString()!); + break; + case "year": + year = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Expiry(month, year); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Expiry expiry, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, expiry, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Expiry expiry, JsonSerializerOptions jsonSerializerOptions) + { + + if (expiry._MonthOption.IsSet) + if (expiry.Month != null) + writer.WriteString("month", expiry.Month); + + if (expiry._YearOption.IsSet) + if (expiry.Year != null) + writer.WriteString("year", expiry.Year); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Fee.cs b/Adyen/BalancePlatform/Models/Fee.cs new file mode 100644 index 000000000..dae7b335c --- /dev/null +++ b/Adyen/BalancePlatform/Models/Fee.cs @@ -0,0 +1,170 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Fee. + /// + public partial class Fee : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public Fee(Amount amount) + { + Amount = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Fee() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Fee {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FeeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Fee Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Fee.", nameof(amount)); + + return new Fee(amount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Fee fee, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fee, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Fee fee, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, fee.Amount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationRequest.cs b/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationRequest.cs new file mode 100644 index 000000000..958fa9536 --- /dev/null +++ b/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationRequest.cs @@ -0,0 +1,183 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// FinishScaDeviceRegistrationRequest. + /// + public partial class FinishScaDeviceRegistrationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + [JsonConstructor] + public FinishScaDeviceRegistrationRequest(string sdkOutput) + { + SdkOutput = sdkOutput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FinishScaDeviceRegistrationRequest() + { + } + + partial void OnCreated(); + + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + /// + /// A base64-encoded block with the data required to register the SCA device. You obtain this information by using Adyen's authentication SDK. + [JsonPropertyName("sdkOutput")] + public string SdkOutput { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FinishScaDeviceRegistrationRequest {\n"); + sb.Append(" SdkOutput: ").Append(SdkOutput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkOutput (string) maxLength + if (this.SdkOutput != null && this.SdkOutput.Length > 10000) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be less than 10000.", new [] { "SdkOutput" }); + } + + // SdkOutput (string) minLength + if (this.SdkOutput != null && this.SdkOutput.Length < 0) + { + yield return new ValidationResult("Invalid value for SdkOutput, length must be greater than 0.", new [] { "SdkOutput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FinishScaDeviceRegistrationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FinishScaDeviceRegistrationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkOutput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkOutput": + sdkOutput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!sdkOutput.IsSet) + throw new ArgumentException("Property is required for class FinishScaDeviceRegistrationRequest.", nameof(sdkOutput)); + + return new FinishScaDeviceRegistrationRequest(sdkOutput.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FinishScaDeviceRegistrationRequest finishScaDeviceRegistrationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, finishScaDeviceRegistrationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FinishScaDeviceRegistrationRequest finishScaDeviceRegistrationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (finishScaDeviceRegistrationRequest.SdkOutput != null) + writer.WriteString("sdkOutput", finishScaDeviceRegistrationRequest.SdkOutput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationResponse.cs b/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationResponse.cs new file mode 100644 index 000000000..dbc55a48a --- /dev/null +++ b/Adyen/BalancePlatform/Models/FinishScaDeviceRegistrationResponse.cs @@ -0,0 +1,178 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// FinishScaDeviceRegistrationResponse. + /// + public partial class FinishScaDeviceRegistrationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// scaDevice + [JsonConstructor] + public FinishScaDeviceRegistrationResponse(Option scaDevice = default) + { + _ScaDeviceOption = scaDevice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FinishScaDeviceRegistrationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("scaDevice")] + public ScaDevice? ScaDevice { get { return this._ScaDeviceOption; } set { this._ScaDeviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FinishScaDeviceRegistrationResponse {\n"); + sb.Append(" ScaDevice: ").Append(ScaDevice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FinishScaDeviceRegistrationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FinishScaDeviceRegistrationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option scaDevice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "scaDevice": + scaDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new FinishScaDeviceRegistrationResponse(scaDevice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FinishScaDeviceRegistrationResponse finishScaDeviceRegistrationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, finishScaDeviceRegistrationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FinishScaDeviceRegistrationResponse finishScaDeviceRegistrationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (finishScaDeviceRegistrationResponse._ScaDeviceOption.IsSet) + { + writer.WritePropertyName("scaDevice"); + JsonSerializer.Serialize(writer, finishScaDeviceRegistrationResponse.ScaDevice, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/GetNetworkTokenResponse.cs b/Adyen/BalancePlatform/Models/GetNetworkTokenResponse.cs new file mode 100644 index 000000000..2566db2da --- /dev/null +++ b/Adyen/BalancePlatform/Models/GetNetworkTokenResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// GetNetworkTokenResponse. + /// + public partial class GetNetworkTokenResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// token + [JsonConstructor] + public GetNetworkTokenResponse(NetworkToken token) + { + Token = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetNetworkTokenResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("token")] + public NetworkToken Token { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetNetworkTokenResponse {\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetNetworkTokenResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetNetworkTokenResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "token": + token = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!token.IsSet) + throw new ArgumentException("Property is required for class GetNetworkTokenResponse.", nameof(token)); + + return new GetNetworkTokenResponse(token.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetNetworkTokenResponse getNetworkTokenResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getNetworkTokenResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetNetworkTokenResponse getNetworkTokenResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("token"); + JsonSerializer.Serialize(writer, getNetworkTokenResponse.Token, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/GetTaxFormResponse.cs b/Adyen/BalancePlatform/Models/GetTaxFormResponse.cs new file mode 100644 index 000000000..367127e3d --- /dev/null +++ b/Adyen/BalancePlatform/Models/GetTaxFormResponse.cs @@ -0,0 +1,292 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// GetTaxFormResponse. + /// + public partial class GetTaxFormResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The content of the tax form in Base64 format. + /// The content type of the tax form. Possible values: * **application/pdf** + [JsonConstructor] + public GetTaxFormResponse(byte[] content, Option contentType = default) + { + Content = content; + _ContentTypeOption = contentType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetTaxFormResponse() + { + } + + partial void OnCreated(); + + /// + /// The content type of the tax form. Possible values: * **application/pdf** + /// + /// The content type of the tax form. Possible values: * **application/pdf** + [JsonConverter(typeof(ContentTypeEnumJsonConverter))] + public class ContentTypeEnum : IEnum + { + /// + /// Returns the value of the ContentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ContentTypeEnum.ApplicationPdf - application/pdf + /// + public static readonly ContentTypeEnum ApplicationPdf = new("application/pdf"); + + private ContentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContentTypeEnum?(string? value) => value == null ? null : new ContentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContentTypeEnum? option) => option?.Value; + + public static bool operator ==(ContentTypeEnum? left, ContentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContentTypeEnum? left, ContentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "application/pdf" => ContentTypeEnum.ApplicationPdf, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContentTypeEnum? value) + { + if (value == null) + return null; + + if (value == ContentTypeEnum.ApplicationPdf) + return "application/pdf"; + + return null; + } + + /// + /// JsonConverter for writing ContentTypeEnum. + /// + public class ContentTypeEnumJsonConverter : JsonConverter + { + public override ContentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContentTypeEnum.FromStringOrDefault(value) ?? new ContentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContentTypeOption { get; private set; } + + /// + /// The content type of the tax form. Possible values: * **application/pdf** + /// + /// The content type of the tax form. Possible values: * **application/pdf** + [JsonPropertyName("contentType")] + public ContentTypeEnum? ContentType { get { return this._ContentTypeOption; } set { this._ContentTypeOption = new(value); } } + + /// + /// The content of the tax form in Base64 format. + /// + /// The content of the tax form in Base64 format. + [JsonPropertyName("content")] + public byte[] Content { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetTaxFormResponse {\n"); + sb.Append(" Content: ").Append(Content).Append("\n"); + sb.Append(" ContentType: ").Append(ContentType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetTaxFormResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetTaxFormResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option content = default; + Option contentType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "content": + content = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contentType": + string? contentTypeRawValue = utf8JsonReader.GetString(); + contentType = new Option(GetTaxFormResponse.ContentTypeEnum.FromStringOrDefault(contentTypeRawValue)); + break; + default: + break; + } + } + } + + if (!content.IsSet) + throw new ArgumentException("Property is required for class GetTaxFormResponse.", nameof(content)); + + return new GetTaxFormResponse(content.Value!, contentType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetTaxFormResponse getTaxFormResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getTaxFormResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetTaxFormResponse getTaxFormResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("content"); + JsonSerializer.Serialize(writer, getTaxFormResponse.Content, jsonSerializerOptions); + if (getTaxFormResponse._ContentTypeOption.IsSet && getTaxFormResponse.ContentType != null) + { + string? contentTypeRawValue = GetTaxFormResponse.ContentTypeEnum.ToJsonValue(getTaxFormResponse._ContentTypeOption.Value!.Value); + writer.WriteString("contentType", contentTypeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/GrantLimit.cs b/Adyen/BalancePlatform/Models/GrantLimit.cs new file mode 100644 index 000000000..5396914c0 --- /dev/null +++ b/Adyen/BalancePlatform/Models/GrantLimit.cs @@ -0,0 +1,178 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// GrantLimit. + /// + public partial class GrantLimit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public GrantLimit(Option amount = default) + { + _AmountOption = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GrantLimit() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GrantLimit {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GrantLimitJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GrantLimit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new GrantLimit(amount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrantLimit grantLimit, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, grantLimit, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GrantLimit grantLimit, JsonSerializerOptions jsonSerializerOptions) + { + + if (grantLimit._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, grantLimit.Amount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/GrantOffer.cs b/Adyen/BalancePlatform/Models/GrantOffer.cs new file mode 100644 index 000000000..2030ee786 --- /dev/null +++ b/Adyen/BalancePlatform/Models/GrantOffer.cs @@ -0,0 +1,460 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// GrantOffer. + /// + public partial class GrantOffer : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the account holder to which the grant is offered. + /// amount + /// The contract type of the grant offer. Possible value: **cashAdvance**, **loan**. + /// The end date of the grant offer validity period. + /// fee + /// The unique identifier of the grant offer. + /// repayment + /// The starting date of the grant offer validity period. + [JsonConstructor] + public GrantOffer(string accountHolderId, Option amount = default, Option contractType = default, Option expiresAt = default, Option fee = default, Option id = default, Option repayment = default, Option startsAt = default) + { + AccountHolderId = accountHolderId; + _AmountOption = amount; + _ContractTypeOption = contractType; + _ExpiresAtOption = expiresAt; + _FeeOption = fee; + _IdOption = id; + _RepaymentOption = repayment; + _StartsAtOption = startsAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GrantOffer() + { + } + + partial void OnCreated(); + + /// + /// The contract type of the grant offer. Possible value: **cashAdvance**, **loan**. + /// + /// The contract type of the grant offer. Possible value: **cashAdvance**, **loan**. + [JsonConverter(typeof(ContractTypeEnumJsonConverter))] + public class ContractTypeEnum : IEnum + { + /// + /// Returns the value of the ContractTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ContractTypeEnum.CashAdvance - cashAdvance + /// + public static readonly ContractTypeEnum CashAdvance = new("cashAdvance"); + + /// + /// ContractTypeEnum.Loan - loan + /// + public static readonly ContractTypeEnum Loan = new("loan"); + + private ContractTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractTypeEnum?(string? value) => value == null ? null : new ContractTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractTypeEnum? option) => option?.Value; + + public static bool operator ==(ContractTypeEnum? left, ContractTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractTypeEnum? left, ContractTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "cashAdvance" => ContractTypeEnum.CashAdvance, + "loan" => ContractTypeEnum.Loan, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractTypeEnum? value) + { + if (value == null) + return null; + + if (value == ContractTypeEnum.CashAdvance) + return "cashAdvance"; + + if (value == ContractTypeEnum.Loan) + return "loan"; + + return null; + } + + /// + /// JsonConverter for writing ContractTypeEnum. + /// + public class ContractTypeEnumJsonConverter : JsonConverter + { + public override ContractTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractTypeEnum.FromStringOrDefault(value) ?? new ContractTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractTypeOption { get; private set; } + + /// + /// The contract type of the grant offer. Possible value: **cashAdvance**, **loan**. + /// + /// The contract type of the grant offer. Possible value: **cashAdvance**, **loan**. + [JsonPropertyName("contractType")] + public ContractTypeEnum? ContractType { get { return this._ContractTypeOption; } set { this._ContractTypeOption = new(value); } } + + /// + /// The identifier of the account holder to which the grant is offered. + /// + /// The identifier of the account holder to which the grant is offered. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The end date of the grant offer validity period. + /// + /// The end date of the grant offer validity period. + [JsonPropertyName("expiresAt")] + public DateTimeOffset? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FeeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fee")] + public Fee? Fee { get { return this._FeeOption; } set { this._FeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the grant offer. + /// + /// The unique identifier of the grant offer. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RepaymentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("repayment")] + public Repayment? Repayment { get { return this._RepaymentOption; } set { this._RepaymentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartsAtOption { get; private set; } + + /// + /// The starting date of the grant offer validity period. + /// + /// The starting date of the grant offer validity period. + [JsonPropertyName("startsAt")] + public DateTimeOffset? StartsAt { get { return this._StartsAtOption; } set { this._StartsAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GrantOffer {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" ContractType: ").Append(ContractType).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" Fee: ").Append(Fee).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Repayment: ").Append(Repayment).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GrantOfferJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize StartsAt. + /// + public static string StartsAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GrantOffer Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option amount = default; + Option contractType = default; + Option expiresAt = default; + Option fee = default; + Option id = default; + Option repayment = default; + Option startsAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contractType": + string? contractTypeRawValue = utf8JsonReader.GetString(); + contractType = new Option(GrantOffer.ContractTypeEnum.FromStringOrDefault(contractTypeRawValue)); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "fee": + fee = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "repayment": + repayment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "startsAt": + startsAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class GrantOffer.", nameof(accountHolderId)); + + return new GrantOffer(accountHolderId.Value!, amount, contractType, expiresAt, fee, id, repayment, startsAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrantOffer grantOffer, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, grantOffer, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GrantOffer grantOffer, JsonSerializerOptions jsonSerializerOptions) + { + + if (grantOffer.AccountHolderId != null) + writer.WriteString("accountHolderId", grantOffer.AccountHolderId); + + if (grantOffer._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, grantOffer.Amount, jsonSerializerOptions); + } + if (grantOffer._ContractTypeOption.IsSet && grantOffer.ContractType != null) + { + string? contractTypeRawValue = GrantOffer.ContractTypeEnum.ToJsonValue(grantOffer._ContractTypeOption.Value!.Value); + writer.WriteString("contractType", contractTypeRawValue); + } + + if (grantOffer._ExpiresAtOption.IsSet) + writer.WriteString("expiresAt", grantOffer._ExpiresAtOption.Value!.Value.ToString(ExpiresAtFormat)); + + if (grantOffer._FeeOption.IsSet) + { + writer.WritePropertyName("fee"); + JsonSerializer.Serialize(writer, grantOffer.Fee, jsonSerializerOptions); + } + if (grantOffer._IdOption.IsSet) + if (grantOffer.Id != null) + writer.WriteString("id", grantOffer.Id); + + if (grantOffer._RepaymentOption.IsSet) + { + writer.WritePropertyName("repayment"); + JsonSerializer.Serialize(writer, grantOffer.Repayment, jsonSerializerOptions); + } + if (grantOffer._StartsAtOption.IsSet) + writer.WriteString("startsAt", grantOffer._StartsAtOption.Value!.Value.ToString(StartsAtFormat)); + } + } +} diff --git a/Adyen/BalancePlatform/Models/GrantOffers.cs b/Adyen/BalancePlatform/Models/GrantOffers.cs new file mode 100644 index 000000000..d4fd8e826 --- /dev/null +++ b/Adyen/BalancePlatform/Models/GrantOffers.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// GrantOffers. + /// + public partial class GrantOffers : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A list of available grant offers. + [JsonConstructor] + public GrantOffers(List varGrantOffers) + { + VarGrantOffers = varGrantOffers; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GrantOffers() + { + } + + partial void OnCreated(); + + /// + /// A list of available grant offers. + /// + /// A list of available grant offers. + [JsonPropertyName("grantOffers")] + public List VarGrantOffers { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GrantOffers {\n"); + sb.Append(" VarGrantOffers: ").Append(VarGrantOffers).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GrantOffersJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GrantOffers Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> varGrantOffers = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "grantOffers": + varGrantOffers = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!varGrantOffers.IsSet) + throw new ArgumentException("Property is required for class GrantOffers.", nameof(varGrantOffers)); + + return new GrantOffers(varGrantOffers.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GrantOffers grantOffers, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, grantOffers, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GrantOffers grantOffers, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("grantOffers"); + JsonSerializer.Serialize(writer, grantOffers.VarGrantOffers, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/HKLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/HKLocalAccountIdentification.cs new file mode 100644 index 000000000..9322320ab --- /dev/null +++ b/Adyen/BalancePlatform/Models/HKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// HKLocalAccountIdentification. + /// + public partial class HKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// The 3-digit clearing code, without separators or whitespace. + /// **hkLocal** (default to TypeEnum.HkLocal) + [JsonConstructor] + public HKLocalAccountIdentification(string accountNumber, string clearingCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingCode = clearingCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HkLocal - hkLocal + /// + public static readonly TypeEnum HkLocal = new("hkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "hkLocal" => TypeEnum.HkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HkLocal) + return "hkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit clearing code, without separators or whitespace. + /// + /// The 3-digit clearing code, without separators or whitespace. + [JsonPropertyName("clearingCode")] + public string ClearingCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingCode: ").Append(ClearingCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 9.", new [] { "AccountNumber" }); + } + + // ClearingCode (string) maxLength + if (this.ClearingCode != null && this.ClearingCode.Length > 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be less than 3.", new [] { "ClearingCode" }); + } + + // ClearingCode (string) minLength + if (this.ClearingCode != null && this.ClearingCode.Length < 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be greater than 3.", new [] { "ClearingCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingCode": + clearingCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingCode.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(clearingCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(type)); + + return new HKLocalAccountIdentification(accountNumber.Value!, clearingCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hKLocalAccountIdentification.AccountNumber); + + if (hKLocalAccountIdentification.ClearingCode != null) + writer.WriteString("clearingCode", hKLocalAccountIdentification.ClearingCode); + + if (hKLocalAccountIdentification.Type != null) + { + string? typeRawValue = HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/HULocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/HULocalAccountIdentification.cs new file mode 100644 index 000000000..6c8581918 --- /dev/null +++ b/Adyen/BalancePlatform/Models/HULocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// HULocalAccountIdentification. + /// + public partial class HULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 24-digit bank account number, without separators or whitespace. + /// **huLocal** (default to TypeEnum.HuLocal) + [JsonConstructor] + public HULocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HuLocal - huLocal + /// + public static readonly TypeEnum HuLocal = new("huLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "huLocal" => TypeEnum.HuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HuLocal) + return "huLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 24-digit bank account number, without separators or whitespace. + /// + /// The 24-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 24.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 24.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(type)); + + return new HULocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hULocalAccountIdentification.AccountNumber); + + if (hULocalAccountIdentification.Type != null) + { + string? typeRawValue = HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Href.cs b/Adyen/BalancePlatform/Models/Href.cs new file mode 100644 index 000000000..36ebcd4c6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Href.cs @@ -0,0 +1,176 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Href. + /// + public partial class Href : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// varHref + [JsonConstructor] + public Href(Option varHref = default) + { + _VarHrefOption = varHref; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Href() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VarHrefOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("href")] + public string? VarHref { get { return this._VarHrefOption; } set { this._VarHrefOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Href {\n"); + sb.Append(" VarHref: ").Append(VarHref).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HrefJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Href Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option varHref = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "href": + varHref = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Href(varHref); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Href href, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, href, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Href href, JsonSerializerOptions jsonSerializerOptions) + { + + if (href._VarHrefOption.IsSet) + if (href.VarHref != null) + writer.WriteString("href", href.VarHref); + } + } +} diff --git a/Adyen/BalancePlatform/Models/IbanAccountIdentification.cs b/Adyen/BalancePlatform/Models/IbanAccountIdentification.cs new file mode 100644 index 000000000..ddb7e0fcf --- /dev/null +++ b/Adyen/BalancePlatform/Models/IbanAccountIdentification.cs @@ -0,0 +1,289 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// IbanAccountIdentification. + /// + public partial class IbanAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// **iban** (default to TypeEnum.Iban) + [JsonConstructor] + public IbanAccountIdentification(string iban, TypeEnum type = default) + { + Iban = iban; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **iban** + /// + /// **iban** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Iban - iban + /// + public static readonly TypeEnum Iban = new("iban"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "iban" => TypeEnum.Iban, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Iban) + return "iban"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **iban** + /// + /// **iban** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentification {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(iban)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(type)); + + return new IbanAccountIdentification(iban.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentification.Iban != null) + writer.WriteString("iban", ibanAccountIdentification.Iban); + + if (ibanAccountIdentification.Type != null) + { + string? typeRawValue = IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/IbanAccountIdentificationRequirement.cs b/Adyen/BalancePlatform/Models/IbanAccountIdentificationRequirement.cs new file mode 100644 index 000000000..130dae6dc --- /dev/null +++ b/Adyen/BalancePlatform/Models/IbanAccountIdentificationRequirement.cs @@ -0,0 +1,320 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// IbanAccountIdentificationRequirement. + /// + public partial class IbanAccountIdentificationRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the allowed prefixes for the international bank account number as defined in the ISO-13616 standard. + /// Contains the list of allowed prefixes for international bank accounts. For example: NL, US, UK. + /// **ibanAccountIdentificationRequirement** (default to TypeEnum.IbanAccountIdentificationRequirement) + [JsonConstructor] + public IbanAccountIdentificationRequirement(Option description = default, Option?> ibanPrefixes = default, TypeEnum type = default) + { + _DescriptionOption = description; + _IbanPrefixesOption = ibanPrefixes; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentificationRequirement() + { + } + + partial void OnCreated(); + + /// + /// **ibanAccountIdentificationRequirement** + /// + /// **ibanAccountIdentificationRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IbanAccountIdentificationRequirement - ibanAccountIdentificationRequirement + /// + public static readonly TypeEnum IbanAccountIdentificationRequirement = new("ibanAccountIdentificationRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ibanAccountIdentificationRequirement" => TypeEnum.IbanAccountIdentificationRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IbanAccountIdentificationRequirement) + return "ibanAccountIdentificationRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ibanAccountIdentificationRequirement** + /// + /// **ibanAccountIdentificationRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies the allowed prefixes for the international bank account number as defined in the ISO-13616 standard. + /// + /// Specifies the allowed prefixes for the international bank account number as defined in the ISO-13616 standard. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IbanPrefixesOption { get; private set; } + + /// + /// Contains the list of allowed prefixes for international bank accounts. For example: NL, US, UK. + /// + /// Contains the list of allowed prefixes for international bank accounts. For example: NL, US, UK. + [JsonPropertyName("ibanPrefixes")] + public List? IbanPrefixes { get { return this._IbanPrefixesOption; } set { this._IbanPrefixesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentificationRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" IbanPrefixes: ").Append(IbanPrefixes).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentificationRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option?> ibanPrefixes = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "ibanPrefixes": + ibanPrefixes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentificationRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentificationRequirement.", nameof(type)); + + return new IbanAccountIdentificationRequirement(description, ibanPrefixes, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentificationRequirement ibanAccountIdentificationRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentificationRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentificationRequirement ibanAccountIdentificationRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentificationRequirement._DescriptionOption.IsSet) + if (ibanAccountIdentificationRequirement.Description != null) + writer.WriteString("description", ibanAccountIdentificationRequirement.Description); + + if (ibanAccountIdentificationRequirement._IbanPrefixesOption.IsSet) + { + writer.WritePropertyName("ibanPrefixes"); + JsonSerializer.Serialize(writer, ibanAccountIdentificationRequirement.IbanPrefixes, jsonSerializerOptions); + } + if (ibanAccountIdentificationRequirement.Type != null) + { + string? typeRawValue = IbanAccountIdentificationRequirement.TypeEnum.ToJsonValue(ibanAccountIdentificationRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/InternationalTransactionRestriction.cs b/Adyen/BalancePlatform/Models/InternationalTransactionRestriction.cs new file mode 100644 index 000000000..7dc002f01 --- /dev/null +++ b/Adyen/BalancePlatform/Models/InternationalTransactionRestriction.cs @@ -0,0 +1,195 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// InternationalTransactionRestriction. + /// + public partial class InternationalTransactionRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// Boolean indicating whether transaction is an international transaction. Possible values: - **true**: The transaction is an international transaction. - **false**: The transaction is a domestic transaction. + [JsonConstructor] + public InternationalTransactionRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternationalTransactionRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// Boolean indicating whether transaction is an international transaction. Possible values: - **true**: The transaction is an international transaction. - **false**: The transaction is a domestic transaction. + /// + /// Boolean indicating whether transaction is an international transaction. Possible values: - **true**: The transaction is an international transaction. - **false**: The transaction is a domestic transaction. + [JsonPropertyName("value")] + public bool? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternationalTransactionRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternationalTransactionRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternationalTransactionRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class InternationalTransactionRestriction.", nameof(operation)); + + return new InternationalTransactionRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternationalTransactionRestriction internationalTransactionRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internationalTransactionRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternationalTransactionRestriction internationalTransactionRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (internationalTransactionRestriction.Operation != null) + writer.WriteString("operation", internationalTransactionRestriction.Operation); + + if (internationalTransactionRestriction._ValueOption.IsSet) + writer.WriteBoolean("value", internationalTransactionRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/InvalidField.cs b/Adyen/BalancePlatform/Models/InvalidField.cs new file mode 100644 index 000000000..787f380c5 --- /dev/null +++ b/Adyen/BalancePlatform/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The field that has an invalid value. + /// The invalid value. + /// Description of the validation error. + [JsonConstructor] + public InvalidField(string name, string value, string message) + { + Name = name; + Value = value; + Message = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option value = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + return new InvalidField(name.Value!, value.Value!, message.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + } + } +} diff --git a/Adyen/BalancePlatform/Models/LimitStatus.cs b/Adyen/BalancePlatform/Models/LimitStatus.cs new file mode 100644 index 000000000..eafc575c7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/LimitStatus.cs @@ -0,0 +1,205 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. + /// + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. + public enum LimitStatus + { + /// + /// Enum Active for value: active + /// + Active = 1, + + /// + /// Enum Inactive for value: inactive + /// + Inactive = 2, + + /// + /// Enum PendingSCA for value: pendingSCA + /// + PendingSCA = 3, + + /// + /// Enum Scheduled for value: scheduled + /// + Scheduled = 4 + } + + /// + /// Converts to and from the JSON value + /// + public static class LimitStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static LimitStatus FromString(string value) + { + if (value.Equals("active")) + return LimitStatus.Active; + + if (value.Equals("inactive")) + return LimitStatus.Inactive; + + if (value.Equals("pendingSCA")) + return LimitStatus.PendingSCA; + + if (value.Equals("scheduled")) + return LimitStatus.Scheduled; + + throw new NotImplementedException($"Could not convert value to type LimitStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static LimitStatus? FromStringOrDefault(string value) + { + if (value.Equals("active")) + return LimitStatus.Active; + + if (value.Equals("inactive")) + return LimitStatus.Inactive; + + if (value.Equals("pendingSCA")) + return LimitStatus.PendingSCA; + + if (value.Equals("scheduled")) + return LimitStatus.Scheduled; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(LimitStatus value) + { + if (value == LimitStatus.Active) + return "active"; + + if (value == LimitStatus.Inactive) + return "inactive"; + + if (value == LimitStatus.PendingSCA) + return "pendingSCA"; + + if (value == LimitStatus.Scheduled) + return "scheduled"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class LimitStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override LimitStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + LimitStatus? result = rawValue == null + ? null + : LimitStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the LimitStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LimitStatus limitStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(LimitStatusValueConverter.ToJsonValue(limitStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class LimitStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a LimitStatus from the Json object + /// + /// + /// + /// + /// + public override LimitStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + LimitStatus? result = rawValue == null + ? null + : LimitStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the LimitStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LimitStatus? limitStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(limitStatus.HasValue ? LimitStatusValueConverter.ToJsonValue(limitStatus.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Link.cs b/Adyen/BalancePlatform/Models/Link.cs new file mode 100644 index 000000000..a55c64877 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Link.cs @@ -0,0 +1,278 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Link. + /// + public partial class Link : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// first + /// last + /// next + /// previous + /// self + [JsonConstructor] + public Link(Option first = default, Option last = default, Option next = default, Option previous = default, Option self = default) + { + _FirstOption = first; + _LastOption = last; + _NextOption = next; + _PreviousOption = previous; + _SelfOption = self; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Link() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("first")] + public Href? First { get { return this._FirstOption; } set { this._FirstOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("last")] + public Href? Last { get { return this._LastOption; } set { this._LastOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NextOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("next")] + public Href? Next { get { return this._NextOption; } set { this._NextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreviousOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("previous")] + public Href? Previous { get { return this._PreviousOption; } set { this._PreviousOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelfOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("self")] + public Href? Self { get { return this._SelfOption; } set { this._SelfOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Link {\n"); + sb.Append(" First: ").Append(First).Append("\n"); + sb.Append(" Last: ").Append(Last).Append("\n"); + sb.Append(" Next: ").Append(Next).Append("\n"); + sb.Append(" Previous: ").Append(Previous).Append("\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LinkJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Link Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option first = default; + Option last = default; + Option next = default; + Option previous = default; + Option self = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "first": + first = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "last": + last = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next": + next = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "previous": + previous = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Link(first, last, next, previous, self); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Link link, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, link, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Link link, JsonSerializerOptions jsonSerializerOptions) + { + + if (link._FirstOption.IsSet) + { + writer.WritePropertyName("first"); + JsonSerializer.Serialize(writer, link.First, jsonSerializerOptions); + } + if (link._LastOption.IsSet) + { + writer.WritePropertyName("last"); + JsonSerializer.Serialize(writer, link.Last, jsonSerializerOptions); + } + if (link._NextOption.IsSet) + { + writer.WritePropertyName("next"); + JsonSerializer.Serialize(writer, link.Next, jsonSerializerOptions); + } + if (link._PreviousOption.IsSet) + { + writer.WritePropertyName("previous"); + JsonSerializer.Serialize(writer, link.Previous, jsonSerializerOptions); + } + if (link._SelfOption.IsSet) + { + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, link.Self, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/ListAssociationsResponse.cs b/Adyen/BalancePlatform/Models/ListAssociationsResponse.cs new file mode 100644 index 000000000..71875a02e --- /dev/null +++ b/Adyen/BalancePlatform/Models/ListAssociationsResponse.cs @@ -0,0 +1,228 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ListAssociationsResponse. + /// + public partial class ListAssociationsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// Contains a list of associations and their corresponding details. + /// The total number of items available. + /// The total number of pages available. + [JsonConstructor] + public ListAssociationsResponse(Link links, List data, int itemsTotal, int pagesTotal) + { + Links = links; + Data = data; + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListAssociationsResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("_links")] + public Link Links { get; set; } + + /// + /// Contains a list of associations and their corresponding details. + /// + /// Contains a list of associations and their corresponding details. + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// The total number of items available. + /// + /// The total number of items available. + /* 1 */ + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// The total number of pages available. + /// + /// The total number of pages available. + /* 1 */ + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListAssociationsResponse {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListAssociationsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListAssociationsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option?> data = default; + Option itemsTotal = default; + Option pagesTotal = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!links.IsSet) + throw new ArgumentException("Property is required for class ListAssociationsResponse.", nameof(links)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class ListAssociationsResponse.", nameof(data)); + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListAssociationsResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListAssociationsResponse.", nameof(pagesTotal)); + + return new ListAssociationsResponse(links.Value!, data.Value!, itemsTotal.Value!.Value!, pagesTotal.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListAssociationsResponse listAssociationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listAssociationsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListAssociationsResponse listAssociationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listAssociationsResponse.Links, jsonSerializerOptions); + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listAssociationsResponse.Data, jsonSerializerOptions); + writer.WriteNumber("itemsTotal", listAssociationsResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listAssociationsResponse.PagesTotal); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ListNetworkTokensResponse.cs b/Adyen/BalancePlatform/Models/ListNetworkTokensResponse.cs new file mode 100644 index 000000000..d2e0887d8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ListNetworkTokensResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ListNetworkTokensResponse. + /// + public partial class ListNetworkTokensResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of network tokens. + [JsonConstructor] + public ListNetworkTokensResponse(Option?> networkTokens = default) + { + _NetworkTokensOption = networkTokens; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListNetworkTokensResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _NetworkTokensOption { get; private set; } + + /// + /// List of network tokens. + /// + /// List of network tokens. + [JsonPropertyName("networkTokens")] + public List? NetworkTokens { get { return this._NetworkTokensOption; } set { this._NetworkTokensOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListNetworkTokensResponse {\n"); + sb.Append(" NetworkTokens: ").Append(NetworkTokens).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListNetworkTokensResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListNetworkTokensResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> networkTokens = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "networkTokens": + networkTokens = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ListNetworkTokensResponse(networkTokens); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListNetworkTokensResponse listNetworkTokensResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listNetworkTokensResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListNetworkTokensResponse listNetworkTokensResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (listNetworkTokensResponse._NetworkTokensOption.IsSet) + { + writer.WritePropertyName("networkTokens"); + JsonSerializer.Serialize(writer, listNetworkTokensResponse.NetworkTokens, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/MatchingTransactionsRestriction.cs b/Adyen/BalancePlatform/Models/MatchingTransactionsRestriction.cs new file mode 100644 index 000000000..ca37ff98f --- /dev/null +++ b/Adyen/BalancePlatform/Models/MatchingTransactionsRestriction.cs @@ -0,0 +1,195 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MatchingTransactionsRestriction. + /// + public partial class MatchingTransactionsRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// The number of transactions. + [JsonConstructor] + public MatchingTransactionsRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MatchingTransactionsRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The number of transactions. + /// + /// The number of transactions. + [JsonPropertyName("value")] + public int? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MatchingTransactionsRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MatchingTransactionsRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MatchingTransactionsRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class MatchingTransactionsRestriction.", nameof(operation)); + + return new MatchingTransactionsRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MatchingTransactionsRestriction matchingTransactionsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, matchingTransactionsRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MatchingTransactionsRestriction matchingTransactionsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (matchingTransactionsRestriction.Operation != null) + writer.WriteString("operation", matchingTransactionsRestriction.Operation); + + if (matchingTransactionsRestriction._ValueOption.IsSet) + writer.WriteNumber("value", matchingTransactionsRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/MatchingValuesRestriction.cs b/Adyen/BalancePlatform/Models/MatchingValuesRestriction.cs new file mode 100644 index 000000000..ab6f02794 --- /dev/null +++ b/Adyen/BalancePlatform/Models/MatchingValuesRestriction.cs @@ -0,0 +1,326 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MatchingValuesRestriction. + /// + public partial class MatchingValuesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public MatchingValuesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MatchingValuesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.AcquirerId - acquirerId + /// + public static readonly ValueEnum AcquirerId = new("acquirerId"); + + /// + /// ValueEnum.Amount - amount + /// + public static readonly ValueEnum Amount = new("amount"); + + /// + /// ValueEnum.Currency - currency + /// + public static readonly ValueEnum Currency = new("currency"); + + /// + /// ValueEnum.MerchantId - merchantId + /// + public static readonly ValueEnum MerchantId = new("merchantId"); + + /// + /// ValueEnum.MerchantName - merchantName + /// + public static readonly ValueEnum MerchantName = new("merchantName"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "acquirerId" => ValueEnum.AcquirerId, + "amount" => ValueEnum.Amount, + "currency" => ValueEnum.Currency, + "merchantId" => ValueEnum.MerchantId, + "merchantName" => ValueEnum.MerchantName, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.AcquirerId) + return "acquirerId"; + + if (value == ValueEnum.Amount) + return "amount"; + + if (value == ValueEnum.Currency) + return "currency"; + + if (value == ValueEnum.MerchantId) + return "merchantId"; + + if (value == ValueEnum.MerchantName) + return "merchantName"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MatchingValuesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MatchingValuesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MatchingValuesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class MatchingValuesRestriction.", nameof(operation)); + + return new MatchingValuesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MatchingValuesRestriction matchingValuesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, matchingValuesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MatchingValuesRestriction matchingValuesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (matchingValuesRestriction.Operation != null) + writer.WriteString("operation", matchingValuesRestriction.Operation); + + if (matchingValuesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, matchingValuesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/MccsRestriction.cs b/Adyen/BalancePlatform/Models/MccsRestriction.cs new file mode 100644 index 000000000..32d882cc6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/MccsRestriction.cs @@ -0,0 +1,198 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MccsRestriction. + /// + public partial class MccsRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of merchant category codes (MCCs). + [JsonConstructor] + public MccsRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MccsRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of merchant category codes (MCCs). + /// + /// List of merchant category codes (MCCs). + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MccsRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MccsRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MccsRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class MccsRestriction.", nameof(operation)); + + return new MccsRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MccsRestriction mccsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mccsRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MccsRestriction mccsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (mccsRestriction.Operation != null) + writer.WriteString("operation", mccsRestriction.Operation); + + if (mccsRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, mccsRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/MerchantAcquirerPair.cs b/Adyen/BalancePlatform/Models/MerchantAcquirerPair.cs new file mode 100644 index 000000000..1383c44cb --- /dev/null +++ b/Adyen/BalancePlatform/Models/MerchantAcquirerPair.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MerchantAcquirerPair. + /// + public partial class MerchantAcquirerPair : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The acquirer ID. + /// The merchant identification number (MID). + [JsonConstructor] + public MerchantAcquirerPair(Option acquirerId = default, Option merchantId = default) + { + _AcquirerIdOption = acquirerId; + _MerchantIdOption = merchantId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantAcquirerPair() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerIdOption { get; private set; } + + /// + /// The acquirer ID. + /// + /// The acquirer ID. + [JsonPropertyName("acquirerId")] + public string? AcquirerId { get { return this._AcquirerIdOption; } set { this._AcquirerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The merchant identification number (MID). + /// + /// The merchant identification number (MID). + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantAcquirerPair {\n"); + sb.Append(" AcquirerId: ").Append(AcquirerId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantAcquirerPairJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantAcquirerPair Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerId = default; + Option merchantId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerId": + acquirerId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantAcquirerPair(acquirerId, merchantId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantAcquirerPair merchantAcquirerPair, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantAcquirerPair, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantAcquirerPair merchantAcquirerPair, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantAcquirerPair._AcquirerIdOption.IsSet) + if (merchantAcquirerPair.AcquirerId != null) + writer.WriteString("acquirerId", merchantAcquirerPair.AcquirerId); + + if (merchantAcquirerPair._MerchantIdOption.IsSet) + if (merchantAcquirerPair.MerchantId != null) + writer.WriteString("merchantId", merchantAcquirerPair.MerchantId); + } + } +} diff --git a/Adyen/BalancePlatform/Models/MerchantNamesRestriction.cs b/Adyen/BalancePlatform/Models/MerchantNamesRestriction.cs new file mode 100644 index 000000000..5776c7ce5 --- /dev/null +++ b/Adyen/BalancePlatform/Models/MerchantNamesRestriction.cs @@ -0,0 +1,197 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MerchantNamesRestriction. + /// + public partial class MerchantNamesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public MerchantNamesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantNamesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantNamesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantNamesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantNamesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class MerchantNamesRestriction.", nameof(operation)); + + return new MerchantNamesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantNamesRestriction merchantNamesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantNamesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantNamesRestriction merchantNamesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantNamesRestriction.Operation != null) + writer.WriteString("operation", merchantNamesRestriction.Operation); + + if (merchantNamesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, merchantNamesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/MerchantsRestriction.cs b/Adyen/BalancePlatform/Models/MerchantsRestriction.cs new file mode 100644 index 000000000..6e8f353a7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/MerchantsRestriction.cs @@ -0,0 +1,198 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// MerchantsRestriction. + /// + public partial class MerchantsRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of merchant ID and acquirer ID pairs. + [JsonConstructor] + public MerchantsRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantsRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of merchant ID and acquirer ID pairs. + /// + /// List of merchant ID and acquirer ID pairs. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantsRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantsRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantsRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class MerchantsRestriction.", nameof(operation)); + + return new MerchantsRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantsRestriction merchantsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantsRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantsRestriction merchantsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantsRestriction.Operation != null) + writer.WriteString("operation", merchantsRestriction.Operation); + + if (merchantsRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, merchantsRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/NOLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/NOLocalAccountIdentification.cs new file mode 100644 index 000000000..1073c6345 --- /dev/null +++ b/Adyen/BalancePlatform/Models/NOLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NOLocalAccountIdentification. + /// + public partial class NOLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 11-digit bank account number, without separators or whitespace. + /// **noLocal** (default to TypeEnum.NoLocal) + [JsonConstructor] + public NOLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NOLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NoLocal - noLocal + /// + public static readonly TypeEnum NoLocal = new("noLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "noLocal" => TypeEnum.NoLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NoLocal) + return "noLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 11-digit bank account number, without separators or whitespace. + /// + /// The 11-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NOLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 11.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 11.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NOLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NOLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NOLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(type)); + + return new NOLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nOLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nOLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nOLocalAccountIdentification.AccountNumber); + + if (nOLocalAccountIdentification.Type != null) + { + string? typeRawValue = NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/NZLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/NZLocalAccountIdentification.cs new file mode 100644 index 000000000..f64239638 --- /dev/null +++ b/Adyen/BalancePlatform/Models/NZLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NZLocalAccountIdentification. + /// + public partial class NZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// **nzLocal** (default to TypeEnum.NzLocal) + [JsonConstructor] + public NZLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NzLocal - nzLocal + /// + public static readonly TypeEnum NzLocal = new("nzLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nzLocal" => TypeEnum.NzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NzLocal) + return "nzLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 16) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 16.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 15) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 15.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(type)); + + return new NZLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nZLocalAccountIdentification.AccountNumber); + + if (nZLocalAccountIdentification.Type != null) + { + string? typeRawValue = NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Name.cs b/Adyen/BalancePlatform/Models/Name.cs new file mode 100644 index 000000000..86ef94568 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/BalancePlatform/Models/NetworkToken.cs b/Adyen/BalancePlatform/Models/NetworkToken.cs new file mode 100644 index 000000000..bd036329f --- /dev/null +++ b/Adyen/BalancePlatform/Models/NetworkToken.cs @@ -0,0 +1,505 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NetworkToken. + /// + public partial class NetworkToken : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The card brand variant of the payment instrument associated with the network token. For example, **mc_prepaid_mrw**. + /// Date and time when the network token was created, in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) extended format. For example, **2025-03-19T10:15:30+01:00**.. + /// device + /// The unique identifier of the network token. + /// The unique identifier of the payment instrument to which this network token belongs to. + /// The status of the network token. Possible values: **active**, **inactive**, **suspended**, **closed**. + /// The last four digits of the network token `id`. + /// tokenRequestor + /// The type of network token. For example, **wallet**, **cof**. + [JsonConstructor] + public NetworkToken(Option brandVariant = default, Option creationDate = default, Option device = default, Option id = default, Option paymentInstrumentId = default, Option status = default, Option tokenLastFour = default, Option tokenRequestor = default, Option type = default) + { + _BrandVariantOption = brandVariant; + _CreationDateOption = creationDate; + _DeviceOption = device; + _IdOption = id; + _PaymentInstrumentIdOption = paymentInstrumentId; + _StatusOption = status; + _TokenLastFourOption = tokenLastFour; + _TokenRequestorOption = tokenRequestor; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkToken() + { + } + + partial void OnCreated(); + + /// + /// The status of the network token. Possible values: **active**, **inactive**, **suspended**, **closed**. + /// + /// The status of the network token. Possible values: **active**, **inactive**, **suspended**, **closed**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + "closed" => StatusEnum.Closed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + if (value == StatusEnum.Closed) + return "closed"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the network token. Possible values: **active**, **inactive**, **suspended**, **closed**. + /// + /// The status of the network token. Possible values: **active**, **inactive**, **suspended**, **closed**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandVariantOption { get; private set; } + + /// + /// The card brand variant of the payment instrument associated with the network token. For example, **mc_prepaid_mrw**. + /// + /// The card brand variant of the payment instrument associated with the network token. For example, **mc_prepaid_mrw**. + [JsonPropertyName("brandVariant")] + public string? BrandVariant { get { return this._BrandVariantOption; } set { this._BrandVariantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// Date and time when the network token was created, in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) extended format. For example, **2025-03-19T10:15:30+01:00**.. + /// + /// Date and time when the network token was created, in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) extended format. For example, **2025-03-19T10:15:30+01:00**.. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("device")] + public DeviceInfo? Device { get { return this._DeviceOption; } set { this._DeviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the network token. + /// + /// The unique identifier of the network token. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument to which this network token belongs to. + /// + /// The unique identifier of the payment instrument to which this network token belongs to. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenLastFourOption { get; private set; } + + /// + /// The last four digits of the network token `id`. + /// + /// The last four digits of the network token `id`. + [JsonPropertyName("tokenLastFour")] + public string? TokenLastFour { get { return this._TokenLastFourOption; } set { this._TokenLastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenRequestorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenRequestor")] + public NetworkTokenRequestor? TokenRequestor { get { return this._TokenRequestorOption; } set { this._TokenRequestorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of network token. For example, **wallet**, **cof**. + /// + /// The type of network token. For example, **wallet**, **cof**. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkToken {\n"); + sb.Append(" BrandVariant: ").Append(BrandVariant).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Device: ").Append(Device).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TokenLastFour: ").Append(TokenLastFour).Append("\n"); + sb.Append(" TokenRequestor: ").Append(TokenRequestor).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkToken Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brandVariant = default; + Option creationDate = default; + Option device = default; + Option id = default; + Option paymentInstrumentId = default; + Option status = default; + Option tokenLastFour = default; + Option tokenRequestor = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brandVariant": + brandVariant = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "device": + device = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(NetworkToken.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "tokenLastFour": + tokenLastFour = new Option(utf8JsonReader.GetString()!); + break; + case "tokenRequestor": + tokenRequestor = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkToken(brandVariant, creationDate, device, id, paymentInstrumentId, status, tokenLastFour, tokenRequestor, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkToken networkToken, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkToken, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkToken networkToken, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkToken._BrandVariantOption.IsSet) + if (networkToken.BrandVariant != null) + writer.WriteString("brandVariant", networkToken.BrandVariant); + + if (networkToken._CreationDateOption.IsSet) + writer.WriteString("creationDate", networkToken._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (networkToken._DeviceOption.IsSet) + { + writer.WritePropertyName("device"); + JsonSerializer.Serialize(writer, networkToken.Device, jsonSerializerOptions); + } + if (networkToken._IdOption.IsSet) + if (networkToken.Id != null) + writer.WriteString("id", networkToken.Id); + + if (networkToken._PaymentInstrumentIdOption.IsSet) + if (networkToken.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", networkToken.PaymentInstrumentId); + + if (networkToken._StatusOption.IsSet && networkToken.Status != null) + { + string? statusRawValue = NetworkToken.StatusEnum.ToJsonValue(networkToken._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (networkToken._TokenLastFourOption.IsSet) + if (networkToken.TokenLastFour != null) + writer.WriteString("tokenLastFour", networkToken.TokenLastFour); + + if (networkToken._TokenRequestorOption.IsSet) + { + writer.WritePropertyName("tokenRequestor"); + JsonSerializer.Serialize(writer, networkToken.TokenRequestor, jsonSerializerOptions); + } + if (networkToken._TypeOption.IsSet) + if (networkToken.Type != null) + writer.WriteString("type", networkToken.Type); + } + } +} diff --git a/Adyen/BalancePlatform/Models/NetworkTokenActivationDataRequest.cs b/Adyen/BalancePlatform/Models/NetworkTokenActivationDataRequest.cs new file mode 100644 index 000000000..3c8e0ee1d --- /dev/null +++ b/Adyen/BalancePlatform/Models/NetworkTokenActivationDataRequest.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NetworkTokenActivationDataRequest. + /// + public partial class NetworkTokenActivationDataRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A block of data automatically generated by Adyen's SDK for network token provisioning. This `sdkOutput` is required to create provisioning data for the network token. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + [JsonConstructor] + public NetworkTokenActivationDataRequest(Option sdkOutput = default) + { + _SdkOutputOption = sdkOutput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenActivationDataRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkOutputOption { get; private set; } + + /// + /// A block of data automatically generated by Adyen's SDK for network token provisioning. This `sdkOutput` is required to create provisioning data for the network token. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + /// + /// A block of data automatically generated by Adyen's SDK for network token provisioning. This `sdkOutput` is required to create provisioning data for the network token. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + [JsonPropertyName("sdkOutput")] + public string? SdkOutput { get { return this._SdkOutputOption; } set { this._SdkOutputOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenActivationDataRequest {\n"); + sb.Append(" SdkOutput: ").Append(SdkOutput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenActivationDataRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenActivationDataRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkOutput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkOutput": + sdkOutput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkTokenActivationDataRequest(sdkOutput); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenActivationDataRequest networkTokenActivationDataRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenActivationDataRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenActivationDataRequest networkTokenActivationDataRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenActivationDataRequest._SdkOutputOption.IsSet) + if (networkTokenActivationDataRequest.SdkOutput != null) + writer.WriteString("sdkOutput", networkTokenActivationDataRequest.SdkOutput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/NetworkTokenActivationDataResponse.cs b/Adyen/BalancePlatform/Models/NetworkTokenActivationDataResponse.cs new file mode 100644 index 000000000..319c75f95 --- /dev/null +++ b/Adyen/BalancePlatform/Models/NetworkTokenActivationDataResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NetworkTokenActivationDataResponse. + /// + public partial class NetworkTokenActivationDataResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A block of data that contains the activation data for a network token. This `sdkInput` is required to initialize Adyen's SDK for network token provisioning. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + [JsonConstructor] + public NetworkTokenActivationDataResponse(Option sdkInput = default) + { + _SdkInputOption = sdkInput; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenActivationDataResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInputOption { get; private set; } + + /// + /// A block of data that contains the activation data for a network token. This `sdkInput` is required to initialize Adyen's SDK for network token provisioning. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + /// + /// A block of data that contains the activation data for a network token. This `sdkInput` is required to initialize Adyen's SDK for network token provisioning. For more information, see the repositories for Adyen's SDKs for network token provisioning: * [Adyen Apple Pay Provisioning SDK](https://github.com/Adyen/adyen-apple-pay-provisioning-ios). * [Adyen Google Wallet Provisioning SDK](https://github.com/Adyen/adyen-issuing-android) + [JsonPropertyName("sdkInput")] + public string? SdkInput { get { return this._SdkInputOption; } set { this._SdkInputOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenActivationDataResponse {\n"); + sb.Append(" SdkInput: ").Append(SdkInput).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenActivationDataResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenActivationDataResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkInput = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkInput": + sdkInput = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkTokenActivationDataResponse(sdkInput); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenActivationDataResponse networkTokenActivationDataResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenActivationDataResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenActivationDataResponse networkTokenActivationDataResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenActivationDataResponse._SdkInputOption.IsSet) + if (networkTokenActivationDataResponse.SdkInput != null) + writer.WriteString("sdkInput", networkTokenActivationDataResponse.SdkInput); + } + } +} diff --git a/Adyen/BalancePlatform/Models/NetworkTokenRequestor.cs b/Adyen/BalancePlatform/Models/NetworkTokenRequestor.cs new file mode 100644 index 000000000..af45947d4 --- /dev/null +++ b/Adyen/BalancePlatform/Models/NetworkTokenRequestor.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NetworkTokenRequestor. + /// + public partial class NetworkTokenRequestor : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The id of the network token requestor. + /// The name of the network token requestor. + [JsonConstructor] + public NetworkTokenRequestor(Option id = default, Option name = default) + { + _IdOption = id; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenRequestor() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The id of the network token requestor. + /// + /// The id of the network token requestor. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the network token requestor. + /// + /// The name of the network token requestor. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenRequestor {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenRequestorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenRequestor Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkTokenRequestor(id, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenRequestor networkTokenRequestor, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenRequestor, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenRequestor networkTokenRequestor, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenRequestor._IdOption.IsSet) + if (networkTokenRequestor.Id != null) + writer.WriteString("id", networkTokenRequestor.Id); + + if (networkTokenRequestor._NameOption.IsSet) + if (networkTokenRequestor.Name != null) + writer.WriteString("name", networkTokenRequestor.Name); + } + } +} diff --git a/Adyen/BalancePlatform/Models/NumberAndBicAccountIdentification.cs b/Adyen/BalancePlatform/Models/NumberAndBicAccountIdentification.cs new file mode 100644 index 000000000..cf427f590 --- /dev/null +++ b/Adyen/BalancePlatform/Models/NumberAndBicAccountIdentification.cs @@ -0,0 +1,352 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// NumberAndBicAccountIdentification. + /// + public partial class NumberAndBicAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// additionalBankIdentification + /// **numberAndBic** (default to TypeEnum.NumberAndBic) + [JsonConstructor] + public NumberAndBicAccountIdentification(string accountNumber, string bic, Option additionalBankIdentification = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _AdditionalBankIdentificationOption = additionalBankIdentification; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NumberAndBicAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NumberAndBic - numberAndBic + /// + public static readonly TypeEnum NumberAndBic = new("numberAndBic"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "numberAndBic" => TypeEnum.NumberAndBic, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NumberAndBic) + return "numberAndBic"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalBankIdentificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalBankIdentification")] + public AdditionalBankIdentification? AdditionalBankIdentification { get { return this._AdditionalBankIdentificationOption; } set { this._AdditionalBankIdentificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberAndBicAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" AdditionalBankIdentification: ").Append(AdditionalBankIdentification).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 34) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 34.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NumberAndBicAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NumberAndBicAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option additionalBankIdentification = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "additionalBankIdentification": + additionalBankIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NumberAndBicAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(bic)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(type)); + + return new NumberAndBicAccountIdentification(accountNumber.Value!, bic.Value!, additionalBankIdentification, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, numberAndBicAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (numberAndBicAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", numberAndBicAccountIdentification.AccountNumber); + + if (numberAndBicAccountIdentification.Bic != null) + writer.WriteString("bic", numberAndBicAccountIdentification.Bic); + + if (numberAndBicAccountIdentification._AdditionalBankIdentificationOption.IsSet) + { + writer.WritePropertyName("additionalBankIdentification"); + JsonSerializer.Serialize(writer, numberAndBicAccountIdentification.AdditionalBankIdentification, jsonSerializerOptions); + } + if (numberAndBicAccountIdentification.Type != null) + { + string? typeRawValue = NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PLLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/PLLocalAccountIdentification.cs new file mode 100644 index 000000000..3160e82e6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PLLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PLLocalAccountIdentification. + /// + public partial class PLLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// **plLocal** (default to TypeEnum.PlLocal) + [JsonConstructor] + public PLLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PLLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlLocal - plLocal + /// + public static readonly TypeEnum PlLocal = new("plLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "plLocal" => TypeEnum.PlLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlLocal) + return "plLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PLLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 26.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 26.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PLLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PLLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PLLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(type)); + + return new PLLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pLLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (pLLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", pLLocalAccountIdentification.AccountNumber); + + if (pLLocalAccountIdentification.Type != null) + { + string? typeRawValue = PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaginatedAccountHoldersResponse.cs b/Adyen/BalancePlatform/Models/PaginatedAccountHoldersResponse.cs new file mode 100644 index 000000000..c3135166f --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaginatedAccountHoldersResponse.cs @@ -0,0 +1,208 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaginatedAccountHoldersResponse. + /// + public partial class PaginatedAccountHoldersResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of account holders. + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + [JsonConstructor] + public PaginatedAccountHoldersResponse(List accountHolders, bool hasNext, bool hasPrevious) + { + AccountHolders = accountHolders; + HasNext = hasNext; + HasPrevious = hasPrevious; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginatedAccountHoldersResponse() + { + } + + partial void OnCreated(); + + /// + /// List of account holders. + /// + /// List of account holders. + [JsonPropertyName("accountHolders")] + public List AccountHolders { get; set; } + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginatedAccountHoldersResponse {\n"); + sb.Append(" AccountHolders: ").Append(AccountHolders).Append("\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginatedAccountHoldersResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginatedAccountHoldersResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> accountHolders = default; + Option hasNext = default; + Option hasPrevious = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolders": + accountHolders = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!accountHolders.IsSet) + throw new ArgumentException("Property is required for class PaginatedAccountHoldersResponse.", nameof(accountHolders)); + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class PaginatedAccountHoldersResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class PaginatedAccountHoldersResponse.", nameof(hasPrevious)); + + return new PaginatedAccountHoldersResponse(accountHolders.Value!, hasNext.Value!.Value!, hasPrevious.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginatedAccountHoldersResponse paginatedAccountHoldersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginatedAccountHoldersResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginatedAccountHoldersResponse paginatedAccountHoldersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountHolders"); + JsonSerializer.Serialize(writer, paginatedAccountHoldersResponse.AccountHolders, jsonSerializerOptions); + writer.WriteBoolean("hasNext", paginatedAccountHoldersResponse.HasNext); + + writer.WriteBoolean("hasPrevious", paginatedAccountHoldersResponse.HasPrevious); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaginatedBalanceAccountsResponse.cs b/Adyen/BalancePlatform/Models/PaginatedBalanceAccountsResponse.cs new file mode 100644 index 000000000..d3cd294ae --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaginatedBalanceAccountsResponse.cs @@ -0,0 +1,208 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaginatedBalanceAccountsResponse. + /// + public partial class PaginatedBalanceAccountsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of balance accounts. + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + [JsonConstructor] + public PaginatedBalanceAccountsResponse(List balanceAccounts, bool hasNext, bool hasPrevious) + { + BalanceAccounts = balanceAccounts; + HasNext = hasNext; + HasPrevious = hasPrevious; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginatedBalanceAccountsResponse() + { + } + + partial void OnCreated(); + + /// + /// List of balance accounts. + /// + /// List of balance accounts. + [JsonPropertyName("balanceAccounts")] + public List BalanceAccounts { get; set; } + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginatedBalanceAccountsResponse {\n"); + sb.Append(" BalanceAccounts: ").Append(BalanceAccounts).Append("\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginatedBalanceAccountsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginatedBalanceAccountsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> balanceAccounts = default; + Option hasNext = default; + Option hasPrevious = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccounts": + balanceAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!balanceAccounts.IsSet) + throw new ArgumentException("Property is required for class PaginatedBalanceAccountsResponse.", nameof(balanceAccounts)); + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class PaginatedBalanceAccountsResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class PaginatedBalanceAccountsResponse.", nameof(hasPrevious)); + + return new PaginatedBalanceAccountsResponse(balanceAccounts.Value!, hasNext.Value!.Value!, hasPrevious.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginatedBalanceAccountsResponse paginatedBalanceAccountsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginatedBalanceAccountsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginatedBalanceAccountsResponse paginatedBalanceAccountsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("balanceAccounts"); + JsonSerializer.Serialize(writer, paginatedBalanceAccountsResponse.BalanceAccounts, jsonSerializerOptions); + writer.WriteBoolean("hasNext", paginatedBalanceAccountsResponse.HasNext); + + writer.WriteBoolean("hasPrevious", paginatedBalanceAccountsResponse.HasPrevious); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaginatedGetCardOrderItemResponse.cs b/Adyen/BalancePlatform/Models/PaginatedGetCardOrderItemResponse.cs new file mode 100644 index 000000000..5f7cc8a90 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaginatedGetCardOrderItemResponse.cs @@ -0,0 +1,208 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaginatedGetCardOrderItemResponse. + /// + public partial class PaginatedGetCardOrderItemResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of card order items in the card order batch. + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + [JsonConstructor] + public PaginatedGetCardOrderItemResponse(List data, bool hasNext, bool hasPrevious) + { + Data = data; + HasNext = hasNext; + HasPrevious = hasPrevious; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginatedGetCardOrderItemResponse() + { + } + + partial void OnCreated(); + + /// + /// List of card order items in the card order batch. + /// + /// List of card order items in the card order batch. + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginatedGetCardOrderItemResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginatedGetCardOrderItemResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginatedGetCardOrderItemResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option hasNext = default; + Option hasPrevious = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class PaginatedGetCardOrderItemResponse.", nameof(data)); + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class PaginatedGetCardOrderItemResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class PaginatedGetCardOrderItemResponse.", nameof(hasPrevious)); + + return new PaginatedGetCardOrderItemResponse(data.Value!, hasNext.Value!.Value!, hasPrevious.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginatedGetCardOrderItemResponse paginatedGetCardOrderItemResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginatedGetCardOrderItemResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginatedGetCardOrderItemResponse paginatedGetCardOrderItemResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paginatedGetCardOrderItemResponse.Data, jsonSerializerOptions); + writer.WriteBoolean("hasNext", paginatedGetCardOrderItemResponse.HasNext); + + writer.WriteBoolean("hasPrevious", paginatedGetCardOrderItemResponse.HasPrevious); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaginatedGetCardOrderResponse.cs b/Adyen/BalancePlatform/Models/PaginatedGetCardOrderResponse.cs new file mode 100644 index 000000000..a29982323 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaginatedGetCardOrderResponse.cs @@ -0,0 +1,216 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaginatedGetCardOrderResponse. + /// + public partial class PaginatedGetCardOrderResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + /// Contains objects with information about card orders. + [JsonConstructor] + public PaginatedGetCardOrderResponse(bool hasNext, bool hasPrevious, Option?> cardOrders = default) + { + HasNext = hasNext; + HasPrevious = hasPrevious; + _CardOrdersOption = cardOrders; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginatedGetCardOrderResponse() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CardOrdersOption { get; private set; } + + /// + /// Contains objects with information about card orders. + /// + /// Contains objects with information about card orders. + [JsonPropertyName("cardOrders")] + public List? CardOrders { get { return this._CardOrdersOption; } set { this._CardOrdersOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginatedGetCardOrderResponse {\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append(" CardOrders: ").Append(CardOrders).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginatedGetCardOrderResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginatedGetCardOrderResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option hasNext = default; + Option hasPrevious = default; + Option?> cardOrders = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "cardOrders": + cardOrders = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class PaginatedGetCardOrderResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class PaginatedGetCardOrderResponse.", nameof(hasPrevious)); + + return new PaginatedGetCardOrderResponse(hasNext.Value!.Value!, hasPrevious.Value!.Value!, cardOrders); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginatedGetCardOrderResponse paginatedGetCardOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginatedGetCardOrderResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginatedGetCardOrderResponse paginatedGetCardOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("hasNext", paginatedGetCardOrderResponse.HasNext); + + writer.WriteBoolean("hasPrevious", paginatedGetCardOrderResponse.HasPrevious); + + if (paginatedGetCardOrderResponse._CardOrdersOption.IsSet) + { + writer.WritePropertyName("cardOrders"); + JsonSerializer.Serialize(writer, paginatedGetCardOrderResponse.CardOrders, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaginatedPaymentInstrumentsResponse.cs b/Adyen/BalancePlatform/Models/PaginatedPaymentInstrumentsResponse.cs new file mode 100644 index 000000000..e29628696 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaginatedPaymentInstrumentsResponse.cs @@ -0,0 +1,209 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaginatedPaymentInstrumentsResponse. + /// + public partial class PaginatedPaymentInstrumentsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether there are more items on the next page. + /// Indicates whether there are more items on the previous page. + /// List of payment instruments associated with the balance account. + [JsonConstructor] + public PaginatedPaymentInstrumentsResponse(bool hasNext, bool hasPrevious, List paymentInstruments) + { + HasNext = hasNext; + HasPrevious = hasPrevious; + PaymentInstruments = paymentInstruments; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginatedPaymentInstrumentsResponse() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether there are more items on the next page. + /// + /// Indicates whether there are more items on the next page. + [JsonPropertyName("hasNext")] + public bool HasNext { get; set; } + + /// + /// Indicates whether there are more items on the previous page. + /// + /// Indicates whether there are more items on the previous page. + [JsonPropertyName("hasPrevious")] + public bool HasPrevious { get; set; } + + /// + /// List of payment instruments associated with the balance account. + /// + /// List of payment instruments associated with the balance account. + [JsonPropertyName("paymentInstruments")] + public List PaymentInstruments { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginatedPaymentInstrumentsResponse {\n"); + sb.Append(" HasNext: ").Append(HasNext).Append("\n"); + sb.Append(" HasPrevious: ").Append(HasPrevious).Append("\n"); + sb.Append(" PaymentInstruments: ").Append(PaymentInstruments).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginatedPaymentInstrumentsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginatedPaymentInstrumentsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option hasNext = default; + Option hasPrevious = default; + Option?> paymentInstruments = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "hasNext": + hasNext = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPrevious": + hasPrevious = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentInstruments": + paymentInstruments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!hasNext.IsSet) + throw new ArgumentException("Property is required for class PaginatedPaymentInstrumentsResponse.", nameof(hasNext)); + + if (!hasPrevious.IsSet) + throw new ArgumentException("Property is required for class PaginatedPaymentInstrumentsResponse.", nameof(hasPrevious)); + + if (!paymentInstruments.IsSet) + throw new ArgumentException("Property is required for class PaginatedPaymentInstrumentsResponse.", nameof(paymentInstruments)); + + return new PaginatedPaymentInstrumentsResponse(hasNext.Value!.Value!, hasPrevious.Value!.Value!, paymentInstruments.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginatedPaymentInstrumentsResponse paginatedPaymentInstrumentsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginatedPaymentInstrumentsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginatedPaymentInstrumentsResponse paginatedPaymentInstrumentsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("hasNext", paginatedPaymentInstrumentsResponse.HasNext); + + writer.WriteBoolean("hasPrevious", paginatedPaymentInstrumentsResponse.HasPrevious); + + writer.WritePropertyName("paymentInstruments"); + JsonSerializer.Serialize(writer, paginatedPaymentInstrumentsResponse.PaymentInstruments, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrument.cs b/Adyen/BalancePlatform/Models/PaymentInstrument.cs new file mode 100644 index 000000000..d5621c218 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrument.cs @@ -0,0 +1,920 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrument. + /// + public partial class PaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// The unique identifier of the payment instrument. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// bankAccount + /// card + /// Your description for the payment instrument, maximum 300 characters. + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// Your reference for the payment instrument, maximum 150 characters. + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// The status comment provides additional information for the statusReason of the payment instrument. + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConstructor] + public PaymentInstrument(string balanceAccountId, string id, string issuingCountryCode, TypeEnum type, Option?> additionalBankAccountIdentifications = default, Option bankAccount = default, Option card = default, Option description = default, Option paymentInstrumentGroupId = default, Option reference = default, Option replacedById = default, Option replacementOfId = default, Option status = default, Option statusComment = default, Option statusReason = default) + { + BalanceAccountId = balanceAccountId; + Id = id; + IssuingCountryCode = issuingCountryCode; + Type = type; + _AdditionalBankAccountIdentificationsOption = additionalBankAccountIdentifications; + _BankAccountOption = bankAccount; + _CardOption = card; + _DescriptionOption = description; + _PaymentInstrumentGroupIdOption = paymentInstrumentGroupId; + _ReferenceOption = reference; + _ReplacedByIdOption = replacedById; + _ReplacementOfIdOption = replacementOfId; + _StatusOption = status; + _StatusCommentOption = statusComment; + _StatusReasonOption = statusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "card" => TypeEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.Card) + return "card"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConverter(typeof(StatusReasonEnumJsonConverter))] + public class StatusReasonEnum : IEnum + { + /// + /// Returns the value of the StatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// StatusReasonEnum.AccountClosure - accountClosure + /// + public static readonly StatusReasonEnum AccountClosure = new("accountClosure"); + + /// + /// StatusReasonEnum.Damaged - damaged + /// + public static readonly StatusReasonEnum Damaged = new("damaged"); + + /// + /// StatusReasonEnum.EndOfLife - endOfLife + /// + public static readonly StatusReasonEnum EndOfLife = new("endOfLife"); + + /// + /// StatusReasonEnum.Expired - expired + /// + public static readonly StatusReasonEnum Expired = new("expired"); + + /// + /// StatusReasonEnum.Lost - lost + /// + public static readonly StatusReasonEnum Lost = new("lost"); + + /// + /// StatusReasonEnum.Other - other + /// + public static readonly StatusReasonEnum Other = new("other"); + + /// + /// StatusReasonEnum.Stolen - stolen + /// + public static readonly StatusReasonEnum Stolen = new("stolen"); + + /// + /// StatusReasonEnum.SuspectedFraud - suspectedFraud + /// + public static readonly StatusReasonEnum SuspectedFraud = new("suspectedFraud"); + + /// + /// StatusReasonEnum.TransactionRule - transactionRule + /// + public static readonly StatusReasonEnum TransactionRule = new("transactionRule"); + + private StatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusReasonEnum?(string? value) => value == null ? null : new StatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusReasonEnum? option) => option?.Value; + + public static bool operator ==(StatusReasonEnum? left, StatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusReasonEnum? left, StatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountClosure" => StatusReasonEnum.AccountClosure, + "damaged" => StatusReasonEnum.Damaged, + "endOfLife" => StatusReasonEnum.EndOfLife, + "expired" => StatusReasonEnum.Expired, + "lost" => StatusReasonEnum.Lost, + "other" => StatusReasonEnum.Other, + "stolen" => StatusReasonEnum.Stolen, + "suspectedFraud" => StatusReasonEnum.SuspectedFraud, + "transactionRule" => StatusReasonEnum.TransactionRule, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == StatusReasonEnum.AccountClosure) + return "accountClosure"; + + if (value == StatusReasonEnum.Damaged) + return "damaged"; + + if (value == StatusReasonEnum.EndOfLife) + return "endOfLife"; + + if (value == StatusReasonEnum.Expired) + return "expired"; + + if (value == StatusReasonEnum.Lost) + return "lost"; + + if (value == StatusReasonEnum.Other) + return "other"; + + if (value == StatusReasonEnum.Stolen) + return "stolen"; + + if (value == StatusReasonEnum.SuspectedFraud) + return "suspectedFraud"; + + if (value == StatusReasonEnum.TransactionRule) + return "transactionRule"; + + return null; + } + + /// + /// JsonConverter for writing StatusReasonEnum. + /// + public class StatusReasonEnumJsonConverter : JsonConverter + { + public override StatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusReasonEnum.FromStringOrDefault(value) ?? new StatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusReasonOption { get; private set; } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonPropertyName("statusReason")] + public StatusReasonEnum? StatusReason { get { return this._StatusReasonOption; } set { this._StatusReasonOption = new(value); } } + + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// The unique identifier of the payment instrument. + /// + /// The unique identifier of the payment instrument. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + [JsonPropertyName("issuingCountryCode")] + public string IssuingCountryCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalBankAccountIdentificationsOption { get; private set; } + + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + [JsonPropertyName("additionalBankAccountIdentifications")] + [Obsolete("Deprecated since Configuration API v2. Please use `bankAccount` object instead")] + public List? AdditionalBankAccountIdentifications { get { return this._AdditionalBankAccountIdentificationsOption; } set { this._AdditionalBankAccountIdentificationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountDetails? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument, maximum 300 characters. + /// + /// Your description for the payment instrument, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentGroupIdOption { get; private set; } + + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + [JsonPropertyName("paymentInstrumentGroupId")] + public string? PaymentInstrumentGroupId { get { return this._PaymentInstrumentGroupIdOption; } set { this._PaymentInstrumentGroupIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument, maximum 150 characters. + /// + /// Your reference for the payment instrument, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacedByIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + [JsonPropertyName("replacedById")] + public string? ReplacedById { get { return this._ReplacedByIdOption; } set { this._ReplacedByIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacementOfIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + [JsonPropertyName("replacementOfId")] + public string? ReplacementOfId { get { return this._ReplacementOfIdOption; } set { this._ReplacementOfIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusCommentOption { get; private set; } + + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + [JsonPropertyName("statusComment")] + public string? StatusComment { get { return this._StatusCommentOption; } set { this._StatusCommentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrument {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalBankAccountIdentifications: ").Append(AdditionalBankAccountIdentifications).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrumentGroupId: ").Append(PaymentInstrumentGroupId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReplacedById: ").Append(ReplacedById).Append("\n"); + sb.Append(" ReplacementOfId: ").Append(ReplacementOfId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); + sb.Append(" StatusReason: ").Append(StatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option id = default; + Option issuingCountryCode = default; + Option type = default; + Option?> additionalBankAccountIdentifications = default; + Option bankAccount = default; + Option card = default; + Option description = default; + Option paymentInstrumentGroupId = default; + Option reference = default; + Option replacedById = default; + Option replacementOfId = default; + Option status = default; + Option statusComment = default; + Option statusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentInstrument.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "additionalBankAccountIdentifications": + additionalBankAccountIdentifications = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentGroupId": + paymentInstrumentGroupId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "replacedById": + replacedById = new Option(utf8JsonReader.GetString()!); + break; + case "replacementOfId": + replacementOfId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentInstrument.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "statusComment": + statusComment = new Option(utf8JsonReader.GetString()!); + break; + case "statusReason": + string? statusReasonRawValue = utf8JsonReader.GetString(); + statusReason = new Option(PaymentInstrument.StatusReasonEnum.FromStringOrDefault(statusReasonRawValue)); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(balanceAccountId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(id)); + + if (!issuingCountryCode.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(issuingCountryCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(type)); + + return new PaymentInstrument(balanceAccountId.Value!, id.Value!, issuingCountryCode.Value!, type.Value!.Value!, additionalBankAccountIdentifications, bankAccount, card, description, paymentInstrumentGroupId, reference, replacedById, replacementOfId, status, statusComment, statusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrument.BalanceAccountId != null) + writer.WriteString("balanceAccountId", paymentInstrument.BalanceAccountId); + + if (paymentInstrument.Id != null) + writer.WriteString("id", paymentInstrument.Id); + + if (paymentInstrument.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", paymentInstrument.IssuingCountryCode); + + if (paymentInstrument.Type != null) + { + string? typeRawValue = PaymentInstrument.TypeEnum.ToJsonValue(paymentInstrument.Type); + writer.WriteString("type", typeRawValue); + } + + if (paymentInstrument._AdditionalBankAccountIdentificationsOption.IsSet) + { + writer.WritePropertyName("additionalBankAccountIdentifications"); + JsonSerializer.Serialize(writer, paymentInstrument.AdditionalBankAccountIdentifications, jsonSerializerOptions); + } + if (paymentInstrument._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, paymentInstrument.BankAccount, jsonSerializerOptions); + } + if (paymentInstrument._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, paymentInstrument.Card, jsonSerializerOptions); + } + if (paymentInstrument._DescriptionOption.IsSet) + if (paymentInstrument.Description != null) + writer.WriteString("description", paymentInstrument.Description); + + if (paymentInstrument._PaymentInstrumentGroupIdOption.IsSet) + if (paymentInstrument.PaymentInstrumentGroupId != null) + writer.WriteString("paymentInstrumentGroupId", paymentInstrument.PaymentInstrumentGroupId); + + if (paymentInstrument._ReferenceOption.IsSet) + if (paymentInstrument.Reference != null) + writer.WriteString("reference", paymentInstrument.Reference); + + if (paymentInstrument._ReplacedByIdOption.IsSet) + if (paymentInstrument.ReplacedById != null) + writer.WriteString("replacedById", paymentInstrument.ReplacedById); + + if (paymentInstrument._ReplacementOfIdOption.IsSet) + if (paymentInstrument.ReplacementOfId != null) + writer.WriteString("replacementOfId", paymentInstrument.ReplacementOfId); + + if (paymentInstrument._StatusOption.IsSet && paymentInstrument.Status != null) + { + string? statusRawValue = PaymentInstrument.StatusEnum.ToJsonValue(paymentInstrument._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (paymentInstrument._StatusCommentOption.IsSet) + if (paymentInstrument.StatusComment != null) + writer.WriteString("statusComment", paymentInstrument.StatusComment); + + if (paymentInstrument._StatusReasonOption.IsSet && paymentInstrument.StatusReason != null) + { + string? statusReasonRawValue = PaymentInstrument.StatusReasonEnum.ToJsonValue(paymentInstrument._StatusReasonOption.Value!.Value); + writer.WriteString("statusReason", statusReasonRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs new file mode 100644 index 000000000..1662eb23b --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs @@ -0,0 +1,175 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentAdditionalBankAccountIdentificationsInner. + /// + public partial class PaymentInstrumentAdditionalBankAccountIdentificationsInner : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentInstrumentAdditionalBankAccountIdentificationsInner(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentAdditionalBankAccountIdentificationsInner {\n"); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentAdditionalBankAccountIdentificationsInnerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentAdditionalBankAccountIdentificationsInner Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + IbanAccountIdentification? ibanAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (ibanAccountIdentification?.Type != null) + return new PaymentInstrumentAdditionalBankAccountIdentificationsInner(ibanAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentAdditionalBankAccountIdentificationsInner paymentInstrumentAdditionalBankAccountIdentificationsInner, JsonSerializerOptions jsonSerializerOptions) + { + if (paymentInstrumentAdditionalBankAccountIdentificationsInner.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, paymentInstrumentAdditionalBankAccountIdentificationsInner.IbanAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, paymentInstrumentAdditionalBankAccountIdentificationsInner, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentAdditionalBankAccountIdentificationsInner paymentInstrumentAdditionalBankAccountIdentificationsInner, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentGroup.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentGroup.cs new file mode 100644 index 000000000..cf678f82e --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentGroup.cs @@ -0,0 +1,304 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentGroup. + /// + public partial class PaymentInstrumentGroup : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + /// The tx variant of the payment instrument group. + /// Your description for the payment instrument group. + /// The unique identifier of the payment instrument group. + /// Properties of the payment instrument group. + /// Your reference for the payment instrument group. + [JsonConstructor] + public PaymentInstrumentGroup(string balancePlatform, string txVariant, Option description = default, Option id = default, Option?> properties = default, Option reference = default) + { + BalancePlatform = balancePlatform; + TxVariant = txVariant; + _DescriptionOption = description; + _IdOption = id; + _PropertiesOption = properties; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentGroup() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + [JsonPropertyName("balancePlatform")] + public string BalancePlatform { get; set; } + + /// + /// The tx variant of the payment instrument group. + /// + /// The tx variant of the payment instrument group. + [JsonPropertyName("txVariant")] + public string TxVariant { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument group. + /// + /// Your description for the payment instrument group. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument group. + /// + /// The unique identifier of the payment instrument group. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PropertiesOption { get; private set; } + + /// + /// Properties of the payment instrument group. + /// + /// Properties of the payment instrument group. + [JsonPropertyName("properties")] + public Dictionary? Properties { get { return this._PropertiesOption; } set { this._PropertiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument group. + /// + /// Your reference for the payment instrument group. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentGroup {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" TxVariant: ").Append(TxVariant).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Properties: ").Append(Properties).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentGroupJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentGroup Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option txVariant = default; + Option description = default; + Option id = default; + Option?> properties = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "txVariant": + txVariant = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "properties": + properties = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!balancePlatform.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentGroup.", nameof(balancePlatform)); + + if (!txVariant.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentGroup.", nameof(txVariant)); + + return new PaymentInstrumentGroup(balancePlatform.Value!, txVariant.Value!, description, id, properties, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentGroup paymentInstrumentGroup, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentGroup, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentGroup paymentInstrumentGroup, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentGroup.BalancePlatform != null) + writer.WriteString("balancePlatform", paymentInstrumentGroup.BalancePlatform); + + if (paymentInstrumentGroup.TxVariant != null) + writer.WriteString("txVariant", paymentInstrumentGroup.TxVariant); + + if (paymentInstrumentGroup._DescriptionOption.IsSet) + if (paymentInstrumentGroup.Description != null) + writer.WriteString("description", paymentInstrumentGroup.Description); + + if (paymentInstrumentGroup._IdOption.IsSet) + if (paymentInstrumentGroup.Id != null) + writer.WriteString("id", paymentInstrumentGroup.Id); + + if (paymentInstrumentGroup._PropertiesOption.IsSet) + { + writer.WritePropertyName("properties"); + JsonSerializer.Serialize(writer, paymentInstrumentGroup.Properties, jsonSerializerOptions); + } + if (paymentInstrumentGroup._ReferenceOption.IsSet) + if (paymentInstrumentGroup.Reference != null) + writer.WriteString("reference", paymentInstrumentGroup.Reference); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentGroupInfo.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentGroupInfo.cs new file mode 100644 index 000000000..3f8c97b36 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentGroupInfo.cs @@ -0,0 +1,279 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentGroupInfo. + /// + public partial class PaymentInstrumentGroupInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + /// The tx variant of the payment instrument group. + /// Your description for the payment instrument group. + /// Properties of the payment instrument group. + /// Your reference for the payment instrument group. + [JsonConstructor] + public PaymentInstrumentGroupInfo(string balancePlatform, string txVariant, Option description = default, Option?> properties = default, Option reference = default) + { + BalancePlatform = balancePlatform; + TxVariant = txVariant; + _DescriptionOption = description; + _PropertiesOption = properties; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentGroupInfo() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the payment instrument group belongs. + [JsonPropertyName("balancePlatform")] + public string BalancePlatform { get; set; } + + /// + /// The tx variant of the payment instrument group. + /// + /// The tx variant of the payment instrument group. + [JsonPropertyName("txVariant")] + public string TxVariant { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument group. + /// + /// Your description for the payment instrument group. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PropertiesOption { get; private set; } + + /// + /// Properties of the payment instrument group. + /// + /// Properties of the payment instrument group. + [JsonPropertyName("properties")] + public Dictionary? Properties { get { return this._PropertiesOption; } set { this._PropertiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument group. + /// + /// Your reference for the payment instrument group. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentGroupInfo {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" TxVariant: ").Append(TxVariant).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Properties: ").Append(Properties).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentGroupInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentGroupInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option txVariant = default; + Option description = default; + Option?> properties = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "txVariant": + txVariant = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "properties": + properties = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!balancePlatform.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentGroupInfo.", nameof(balancePlatform)); + + if (!txVariant.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentGroupInfo.", nameof(txVariant)); + + return new PaymentInstrumentGroupInfo(balancePlatform.Value!, txVariant.Value!, description, properties, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentGroupInfo paymentInstrumentGroupInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentGroupInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentGroupInfo paymentInstrumentGroupInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentGroupInfo.BalancePlatform != null) + writer.WriteString("balancePlatform", paymentInstrumentGroupInfo.BalancePlatform); + + if (paymentInstrumentGroupInfo.TxVariant != null) + writer.WriteString("txVariant", paymentInstrumentGroupInfo.TxVariant); + + if (paymentInstrumentGroupInfo._DescriptionOption.IsSet) + if (paymentInstrumentGroupInfo.Description != null) + writer.WriteString("description", paymentInstrumentGroupInfo.Description); + + if (paymentInstrumentGroupInfo._PropertiesOption.IsSet) + { + writer.WritePropertyName("properties"); + JsonSerializer.Serialize(writer, paymentInstrumentGroupInfo.Properties, jsonSerializerOptions); + } + if (paymentInstrumentGroupInfo._ReferenceOption.IsSet) + if (paymentInstrumentGroupInfo.Reference != null) + writer.WriteString("reference", paymentInstrumentGroupInfo.Reference); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentInfo.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentInfo.cs new file mode 100644 index 000000000..2c02e20d9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentInfo.cs @@ -0,0 +1,823 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentInfo. + /// + public partial class PaymentInstrumentInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// bankAccount + /// card + /// Your description for the payment instrument, maximum 300 characters. + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// Your reference for the payment instrument, maximum 150 characters. + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// The status comment provides additional information for the statusReason of the payment instrument. + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConstructor] + public PaymentInstrumentInfo(string balanceAccountId, string issuingCountryCode, TypeEnum type, Option bankAccount = default, Option card = default, Option description = default, Option paymentInstrumentGroupId = default, Option reference = default, Option status = default, Option statusComment = default, Option statusReason = default) + { + BalanceAccountId = balanceAccountId; + IssuingCountryCode = issuingCountryCode; + Type = type; + _BankAccountOption = bankAccount; + _CardOption = card; + _DescriptionOption = description; + _PaymentInstrumentGroupIdOption = paymentInstrumentGroupId; + _ReferenceOption = reference; + _StatusOption = status; + _StatusCommentOption = statusComment; + _StatusReasonOption = statusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "card" => TypeEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.Card) + return "card"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConverter(typeof(StatusReasonEnumJsonConverter))] + public class StatusReasonEnum : IEnum + { + /// + /// Returns the value of the StatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// StatusReasonEnum.AccountClosure - accountClosure + /// + public static readonly StatusReasonEnum AccountClosure = new("accountClosure"); + + /// + /// StatusReasonEnum.Damaged - damaged + /// + public static readonly StatusReasonEnum Damaged = new("damaged"); + + /// + /// StatusReasonEnum.EndOfLife - endOfLife + /// + public static readonly StatusReasonEnum EndOfLife = new("endOfLife"); + + /// + /// StatusReasonEnum.Expired - expired + /// + public static readonly StatusReasonEnum Expired = new("expired"); + + /// + /// StatusReasonEnum.Lost - lost + /// + public static readonly StatusReasonEnum Lost = new("lost"); + + /// + /// StatusReasonEnum.Other - other + /// + public static readonly StatusReasonEnum Other = new("other"); + + /// + /// StatusReasonEnum.Stolen - stolen + /// + public static readonly StatusReasonEnum Stolen = new("stolen"); + + /// + /// StatusReasonEnum.SuspectedFraud - suspectedFraud + /// + public static readonly StatusReasonEnum SuspectedFraud = new("suspectedFraud"); + + /// + /// StatusReasonEnum.TransactionRule - transactionRule + /// + public static readonly StatusReasonEnum TransactionRule = new("transactionRule"); + + private StatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusReasonEnum?(string? value) => value == null ? null : new StatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusReasonEnum? option) => option?.Value; + + public static bool operator ==(StatusReasonEnum? left, StatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusReasonEnum? left, StatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountClosure" => StatusReasonEnum.AccountClosure, + "damaged" => StatusReasonEnum.Damaged, + "endOfLife" => StatusReasonEnum.EndOfLife, + "expired" => StatusReasonEnum.Expired, + "lost" => StatusReasonEnum.Lost, + "other" => StatusReasonEnum.Other, + "stolen" => StatusReasonEnum.Stolen, + "suspectedFraud" => StatusReasonEnum.SuspectedFraud, + "transactionRule" => StatusReasonEnum.TransactionRule, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == StatusReasonEnum.AccountClosure) + return "accountClosure"; + + if (value == StatusReasonEnum.Damaged) + return "damaged"; + + if (value == StatusReasonEnum.EndOfLife) + return "endOfLife"; + + if (value == StatusReasonEnum.Expired) + return "expired"; + + if (value == StatusReasonEnum.Lost) + return "lost"; + + if (value == StatusReasonEnum.Other) + return "other"; + + if (value == StatusReasonEnum.Stolen) + return "stolen"; + + if (value == StatusReasonEnum.SuspectedFraud) + return "suspectedFraud"; + + if (value == StatusReasonEnum.TransactionRule) + return "transactionRule"; + + return null; + } + + /// + /// JsonConverter for writing StatusReasonEnum. + /// + public class StatusReasonEnumJsonConverter : JsonConverter + { + public override StatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusReasonEnum.FromStringOrDefault(value) ?? new StatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusReasonOption { get; private set; } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonPropertyName("statusReason")] + public StatusReasonEnum? StatusReason { get { return this._StatusReasonOption; } set { this._StatusReasonOption = new(value); } } + + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + [JsonPropertyName("issuingCountryCode")] + public string IssuingCountryCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountModel? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public CardInfo? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument, maximum 300 characters. + /// + /// Your description for the payment instrument, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentGroupIdOption { get; private set; } + + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + [JsonPropertyName("paymentInstrumentGroupId")] + public string? PaymentInstrumentGroupId { get { return this._PaymentInstrumentGroupIdOption; } set { this._PaymentInstrumentGroupIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument, maximum 150 characters. + /// + /// Your reference for the payment instrument, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusCommentOption { get; private set; } + + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + [JsonPropertyName("statusComment")] + public string? StatusComment { get { return this._StatusCommentOption; } set { this._StatusCommentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentInfo {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrumentGroupId: ").Append(PaymentInstrumentGroupId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); + sb.Append(" StatusReason: ").Append(StatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option issuingCountryCode = default; + Option type = default; + Option bankAccount = default; + Option card = default; + Option description = default; + Option paymentInstrumentGroupId = default; + Option reference = default; + Option status = default; + Option statusComment = default; + Option statusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentInstrumentInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentGroupId": + paymentInstrumentGroupId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentInstrumentInfo.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "statusComment": + statusComment = new Option(utf8JsonReader.GetString()!); + break; + case "statusReason": + string? statusReasonRawValue = utf8JsonReader.GetString(); + statusReason = new Option(PaymentInstrumentInfo.StatusReasonEnum.FromStringOrDefault(statusReasonRawValue)); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentInfo.", nameof(balanceAccountId)); + + if (!issuingCountryCode.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentInfo.", nameof(issuingCountryCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentInfo.", nameof(type)); + + return new PaymentInstrumentInfo(balanceAccountId.Value!, issuingCountryCode.Value!, type.Value!.Value!, bankAccount, card, description, paymentInstrumentGroupId, reference, status, statusComment, statusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentInfo paymentInstrumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentInfo paymentInstrumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentInfo.BalanceAccountId != null) + writer.WriteString("balanceAccountId", paymentInstrumentInfo.BalanceAccountId); + + if (paymentInstrumentInfo.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", paymentInstrumentInfo.IssuingCountryCode); + + if (paymentInstrumentInfo.Type != null) + { + string? typeRawValue = PaymentInstrumentInfo.TypeEnum.ToJsonValue(paymentInstrumentInfo.Type); + writer.WriteString("type", typeRawValue); + } + + if (paymentInstrumentInfo._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, paymentInstrumentInfo.BankAccount, jsonSerializerOptions); + } + if (paymentInstrumentInfo._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, paymentInstrumentInfo.Card, jsonSerializerOptions); + } + if (paymentInstrumentInfo._DescriptionOption.IsSet) + if (paymentInstrumentInfo.Description != null) + writer.WriteString("description", paymentInstrumentInfo.Description); + + if (paymentInstrumentInfo._PaymentInstrumentGroupIdOption.IsSet) + if (paymentInstrumentInfo.PaymentInstrumentGroupId != null) + writer.WriteString("paymentInstrumentGroupId", paymentInstrumentInfo.PaymentInstrumentGroupId); + + if (paymentInstrumentInfo._ReferenceOption.IsSet) + if (paymentInstrumentInfo.Reference != null) + writer.WriteString("reference", paymentInstrumentInfo.Reference); + + if (paymentInstrumentInfo._StatusOption.IsSet && paymentInstrumentInfo.Status != null) + { + string? statusRawValue = PaymentInstrumentInfo.StatusEnum.ToJsonValue(paymentInstrumentInfo._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (paymentInstrumentInfo._StatusCommentOption.IsSet) + if (paymentInstrumentInfo.StatusComment != null) + writer.WriteString("statusComment", paymentInstrumentInfo.StatusComment); + + if (paymentInstrumentInfo._StatusReasonOption.IsSet && paymentInstrumentInfo.StatusReason != null) + { + string? statusReasonRawValue = PaymentInstrumentInfo.StatusReasonEnum.ToJsonValue(paymentInstrumentInfo._StatusReasonOption.Value!.Value); + writer.WriteString("statusReason", statusReasonRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentRequirement.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentRequirement.cs new file mode 100644 index 000000000..0a74daca6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentRequirement.cs @@ -0,0 +1,500 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentRequirement. + /// + public partial class PaymentInstrumentRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the requirements for the payment instrument that need to be included in the request for a particular route. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// The two-character ISO-3166-1 alpha-2 country code list for payment instruments. + /// Specifies if the requirement only applies to transfers to another balance platform. + /// The type of the payment instrument. For example, \"BankAccount\" or \"Card\". + /// **paymentInstrumentRequirement** (default to TypeEnum.PaymentInstrumentRequirement) + [JsonConstructor] + public PaymentInstrumentRequirement(Option description = default, Option issuingCountryCode = default, Option?> issuingCountryCodes = default, Option onlyForCrossBalancePlatform = default, Option paymentInstrumentType = default, TypeEnum type = default) + { + _DescriptionOption = description; + _IssuingCountryCodeOption = issuingCountryCode; + _IssuingCountryCodesOption = issuingCountryCodes; + _OnlyForCrossBalancePlatformOption = onlyForCrossBalancePlatform; + _PaymentInstrumentTypeOption = paymentInstrumentType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentRequirement() + { + } + + partial void OnCreated(); + + /// + /// The type of the payment instrument. For example, \"BankAccount\" or \"Card\". + /// + /// The type of the payment instrument. For example, \"BankAccount\" or \"Card\". + [JsonConverter(typeof(PaymentInstrumentTypeEnumJsonConverter))] + public class PaymentInstrumentTypeEnum : IEnum + { + /// + /// Returns the value of the PaymentInstrumentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentInstrumentTypeEnum.BankAccount - BankAccount + /// + public static readonly PaymentInstrumentTypeEnum BankAccount = new("BankAccount"); + + /// + /// PaymentInstrumentTypeEnum.Card - Card + /// + public static readonly PaymentInstrumentTypeEnum Card = new("Card"); + + private PaymentInstrumentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentInstrumentTypeEnum?(string? value) => value == null ? null : new PaymentInstrumentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentInstrumentTypeEnum? option) => option?.Value; + + public static bool operator ==(PaymentInstrumentTypeEnum? left, PaymentInstrumentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentInstrumentTypeEnum? left, PaymentInstrumentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentInstrumentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentInstrumentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => PaymentInstrumentTypeEnum.BankAccount, + "Card" => PaymentInstrumentTypeEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentInstrumentTypeEnum? value) + { + if (value == null) + return null; + + if (value == PaymentInstrumentTypeEnum.BankAccount) + return "BankAccount"; + + if (value == PaymentInstrumentTypeEnum.Card) + return "Card"; + + return null; + } + + /// + /// JsonConverter for writing PaymentInstrumentTypeEnum. + /// + public class PaymentInstrumentTypeEnumJsonConverter : JsonConverter + { + public override PaymentInstrumentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentInstrumentTypeEnum.FromStringOrDefault(value) ?? new PaymentInstrumentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentInstrumentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentInstrumentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentTypeOption { get; private set; } + + /// + /// The type of the payment instrument. For example, \"BankAccount\" or \"Card\". + /// + /// The type of the payment instrument. For example, \"BankAccount\" or \"Card\". + [JsonPropertyName("paymentInstrumentType")] + public PaymentInstrumentTypeEnum? PaymentInstrumentType { get { return this._PaymentInstrumentTypeOption; } set { this._PaymentInstrumentTypeOption = new(value); } } + + /// + /// **paymentInstrumentRequirement** + /// + /// **paymentInstrumentRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentInstrumentRequirement - paymentInstrumentRequirement + /// + public static readonly TypeEnum PaymentInstrumentRequirement = new("paymentInstrumentRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentInstrumentRequirement" => TypeEnum.PaymentInstrumentRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentInstrumentRequirement) + return "paymentInstrumentRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **paymentInstrumentRequirement** + /// + /// **paymentInstrumentRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies the requirements for the payment instrument that need to be included in the request for a particular route. + /// + /// Specifies the requirements for the payment instrument that need to be included in the request for a particular route. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuingCountryCodeOption { get; private set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + [JsonPropertyName("issuingCountryCode")] + public string? IssuingCountryCode { get { return this._IssuingCountryCodeOption; } set { this._IssuingCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IssuingCountryCodesOption { get; private set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code list for payment instruments. + /// + /// The two-character ISO-3166-1 alpha-2 country code list for payment instruments. + [JsonPropertyName("issuingCountryCodes")] + public List? IssuingCountryCodes { get { return this._IssuingCountryCodesOption; } set { this._IssuingCountryCodesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OnlyForCrossBalancePlatformOption { get; private set; } + + /// + /// Specifies if the requirement only applies to transfers to another balance platform. + /// + /// Specifies if the requirement only applies to transfers to another balance platform. + [JsonPropertyName("onlyForCrossBalancePlatform")] + public bool? OnlyForCrossBalancePlatform { get { return this._OnlyForCrossBalancePlatformOption; } set { this._OnlyForCrossBalancePlatformOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append(" IssuingCountryCodes: ").Append(IssuingCountryCodes).Append("\n"); + sb.Append(" OnlyForCrossBalancePlatform: ").Append(OnlyForCrossBalancePlatform).Append("\n"); + sb.Append(" PaymentInstrumentType: ").Append(PaymentInstrumentType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option issuingCountryCode = default; + Option?> issuingCountryCodes = default; + Option onlyForCrossBalancePlatform = default; + Option paymentInstrumentType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCodes": + issuingCountryCodes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "onlyForCrossBalancePlatform": + onlyForCrossBalancePlatform = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentInstrumentType": + string? paymentInstrumentTypeRawValue = utf8JsonReader.GetString(); + paymentInstrumentType = new Option(PaymentInstrumentRequirement.PaymentInstrumentTypeEnum.FromStringOrDefault(paymentInstrumentTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentInstrumentRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRequirement.", nameof(type)); + + return new PaymentInstrumentRequirement(description, issuingCountryCode, issuingCountryCodes, onlyForCrossBalancePlatform, paymentInstrumentType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentRequirement paymentInstrumentRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentRequirement paymentInstrumentRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentRequirement._DescriptionOption.IsSet) + if (paymentInstrumentRequirement.Description != null) + writer.WriteString("description", paymentInstrumentRequirement.Description); + + if (paymentInstrumentRequirement._IssuingCountryCodeOption.IsSet) + if (paymentInstrumentRequirement.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", paymentInstrumentRequirement.IssuingCountryCode); + + if (paymentInstrumentRequirement._IssuingCountryCodesOption.IsSet) + { + writer.WritePropertyName("issuingCountryCodes"); + JsonSerializer.Serialize(writer, paymentInstrumentRequirement.IssuingCountryCodes, jsonSerializerOptions); + } + if (paymentInstrumentRequirement._OnlyForCrossBalancePlatformOption.IsSet) + writer.WriteBoolean("onlyForCrossBalancePlatform", paymentInstrumentRequirement._OnlyForCrossBalancePlatformOption.Value!.Value); + + if (paymentInstrumentRequirement._PaymentInstrumentTypeOption.IsSet && paymentInstrumentRequirement.PaymentInstrumentType != null) + { + string? paymentInstrumentTypeRawValue = PaymentInstrumentRequirement.PaymentInstrumentTypeEnum.ToJsonValue(paymentInstrumentRequirement._PaymentInstrumentTypeOption.Value!.Value); + writer.WriteString("paymentInstrumentType", paymentInstrumentTypeRawValue); + } + + if (paymentInstrumentRequirement.Type != null) + { + string? typeRawValue = PaymentInstrumentRequirement.TypeEnum.ToJsonValue(paymentInstrumentRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentRevealInfo.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealInfo.cs new file mode 100644 index 000000000..6f2ac3cc5 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealInfo.cs @@ -0,0 +1,209 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentRevealInfo. + /// + public partial class PaymentInstrumentRevealInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The CVC2 value of the card. + /// expiration + /// The primary account number (PAN) of the card. + [JsonConstructor] + public PaymentInstrumentRevealInfo(string cvc, Expiry expiration, string pan) + { + Cvc = cvc; + Expiration = expiration; + Pan = pan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentRevealInfo() + { + } + + partial void OnCreated(); + + /// + /// The CVC2 value of the card. + /// + /// The CVC2 value of the card. + [JsonPropertyName("cvc")] + public string Cvc { get; set; } + + /// + /// . + /// + [JsonPropertyName("expiration")] + public Expiry Expiration { get; set; } + + /// + /// The primary account number (PAN) of the card. + /// + /// The primary account number (PAN) of the card. + [JsonPropertyName("pan")] + public string Pan { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentRevealInfo {\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" Expiration: ").Append(Expiration).Append("\n"); + sb.Append(" Pan: ").Append(Pan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentRevealInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentRevealInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cvc = default; + Option expiration = default; + Option pan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "expiration": + expiration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pan": + pan = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!cvc.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealInfo.", nameof(cvc)); + + if (!expiration.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealInfo.", nameof(expiration)); + + if (!pan.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealInfo.", nameof(pan)); + + return new PaymentInstrumentRevealInfo(cvc.Value!, expiration.Value!, pan.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentRevealInfo paymentInstrumentRevealInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentRevealInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentRevealInfo paymentInstrumentRevealInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentRevealInfo.Cvc != null) + writer.WriteString("cvc", paymentInstrumentRevealInfo.Cvc); + + writer.WritePropertyName("expiration"); + JsonSerializer.Serialize(writer, paymentInstrumentRevealInfo.Expiration, jsonSerializerOptions); + if (paymentInstrumentRevealInfo.Pan != null) + writer.WriteString("pan", paymentInstrumentRevealInfo.Pan); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentRevealRequest.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealRequest.cs new file mode 100644 index 000000000..d6f2a361a --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentRevealRequest. + /// + public partial class PaymentInstrumentRevealRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + [JsonConstructor] + public PaymentInstrumentRevealRequest(string encryptedKey, string paymentInstrumentId) + { + EncryptedKey = encryptedKey; + PaymentInstrumentId = paymentInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentRevealRequest() + { + } + + partial void OnCreated(); + + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + [JsonPropertyName("encryptedKey")] + public string EncryptedKey { get; set; } + + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentRevealRequest {\n"); + sb.Append(" EncryptedKey: ").Append(EncryptedKey).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentRevealRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentRevealRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encryptedKey = default; + Option paymentInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encryptedKey": + encryptedKey = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!encryptedKey.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealRequest.", nameof(encryptedKey)); + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealRequest.", nameof(paymentInstrumentId)); + + return new PaymentInstrumentRevealRequest(encryptedKey.Value!, paymentInstrumentId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentRevealRequest paymentInstrumentRevealRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentRevealRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentRevealRequest paymentInstrumentRevealRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentRevealRequest.EncryptedKey != null) + writer.WriteString("encryptedKey", paymentInstrumentRevealRequest.EncryptedKey); + + if (paymentInstrumentRevealRequest.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", paymentInstrumentRevealRequest.PaymentInstrumentId); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentRevealResponse.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealResponse.cs new file mode 100644 index 000000000..c13505c5a --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentRevealResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentRevealResponse. + /// + public partial class PaymentInstrumentRevealResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The data encrypted using the `encryptedKey`. + [JsonConstructor] + public PaymentInstrumentRevealResponse(string encryptedData) + { + EncryptedData = encryptedData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentRevealResponse() + { + } + + partial void OnCreated(); + + /// + /// The data encrypted using the `encryptedKey`. + /// + /// The data encrypted using the `encryptedKey`. + [JsonPropertyName("encryptedData")] + public string EncryptedData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentRevealResponse {\n"); + sb.Append(" EncryptedData: ").Append(EncryptedData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentRevealResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentRevealResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encryptedData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encryptedData": + encryptedData = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!encryptedData.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentRevealResponse.", nameof(encryptedData)); + + return new PaymentInstrumentRevealResponse(encryptedData.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentRevealResponse paymentInstrumentRevealResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentRevealResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentRevealResponse paymentInstrumentRevealResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentRevealResponse.EncryptedData != null) + writer.WriteString("encryptedData", paymentInstrumentRevealResponse.EncryptedData); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PaymentInstrumentUpdateRequest.cs b/Adyen/BalancePlatform/Models/PaymentInstrumentUpdateRequest.cs new file mode 100644 index 000000000..96b234444 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PaymentInstrumentUpdateRequest.cs @@ -0,0 +1,570 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PaymentInstrumentUpdateRequest. + /// + public partial class PaymentInstrumentUpdateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance account associated with this payment instrument. >You can only change the balance account ID if the payment instrument has **inactive** status. + /// card + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + /// The reason for updating the status of the payment instrument. Possible values: **lost**, **stolen**, **damaged**, **suspectedFraud**, **expired**, **endOfLife**, **accountClosure**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConstructor] + public PaymentInstrumentUpdateRequest(Option balanceAccountId = default, Option card = default, Option status = default, Option statusComment = default, Option statusReason = default) + { + _BalanceAccountIdOption = balanceAccountId; + _CardOption = card; + _StatusOption = status; + _StatusCommentOption = statusComment; + _StatusReasonOption = statusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentUpdateRequest() + { + } + + partial void OnCreated(); + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The reason for updating the status of the payment instrument. Possible values: **lost**, **stolen**, **damaged**, **suspectedFraud**, **expired**, **endOfLife**, **accountClosure**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for updating the status of the payment instrument. Possible values: **lost**, **stolen**, **damaged**, **suspectedFraud**, **expired**, **endOfLife**, **accountClosure**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConverter(typeof(StatusReasonEnumJsonConverter))] + public class StatusReasonEnum : IEnum + { + /// + /// Returns the value of the StatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// StatusReasonEnum.AccountClosure - accountClosure + /// + public static readonly StatusReasonEnum AccountClosure = new("accountClosure"); + + /// + /// StatusReasonEnum.Damaged - damaged + /// + public static readonly StatusReasonEnum Damaged = new("damaged"); + + /// + /// StatusReasonEnum.EndOfLife - endOfLife + /// + public static readonly StatusReasonEnum EndOfLife = new("endOfLife"); + + /// + /// StatusReasonEnum.Expired - expired + /// + public static readonly StatusReasonEnum Expired = new("expired"); + + /// + /// StatusReasonEnum.Lost - lost + /// + public static readonly StatusReasonEnum Lost = new("lost"); + + /// + /// StatusReasonEnum.Other - other + /// + public static readonly StatusReasonEnum Other = new("other"); + + /// + /// StatusReasonEnum.Stolen - stolen + /// + public static readonly StatusReasonEnum Stolen = new("stolen"); + + /// + /// StatusReasonEnum.SuspectedFraud - suspectedFraud + /// + public static readonly StatusReasonEnum SuspectedFraud = new("suspectedFraud"); + + /// + /// StatusReasonEnum.TransactionRule - transactionRule + /// + public static readonly StatusReasonEnum TransactionRule = new("transactionRule"); + + private StatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusReasonEnum?(string? value) => value == null ? null : new StatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusReasonEnum? option) => option?.Value; + + public static bool operator ==(StatusReasonEnum? left, StatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusReasonEnum? left, StatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountClosure" => StatusReasonEnum.AccountClosure, + "damaged" => StatusReasonEnum.Damaged, + "endOfLife" => StatusReasonEnum.EndOfLife, + "expired" => StatusReasonEnum.Expired, + "lost" => StatusReasonEnum.Lost, + "other" => StatusReasonEnum.Other, + "stolen" => StatusReasonEnum.Stolen, + "suspectedFraud" => StatusReasonEnum.SuspectedFraud, + "transactionRule" => StatusReasonEnum.TransactionRule, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == StatusReasonEnum.AccountClosure) + return "accountClosure"; + + if (value == StatusReasonEnum.Damaged) + return "damaged"; + + if (value == StatusReasonEnum.EndOfLife) + return "endOfLife"; + + if (value == StatusReasonEnum.Expired) + return "expired"; + + if (value == StatusReasonEnum.Lost) + return "lost"; + + if (value == StatusReasonEnum.Other) + return "other"; + + if (value == StatusReasonEnum.Stolen) + return "stolen"; + + if (value == StatusReasonEnum.SuspectedFraud) + return "suspectedFraud"; + + if (value == StatusReasonEnum.TransactionRule) + return "transactionRule"; + + return null; + } + + /// + /// JsonConverter for writing StatusReasonEnum. + /// + public class StatusReasonEnumJsonConverter : JsonConverter + { + public override StatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusReasonEnum.FromStringOrDefault(value) ?? new StatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusReasonOption { get; private set; } + + /// + /// The reason for updating the status of the payment instrument. Possible values: **lost**, **stolen**, **damaged**, **suspectedFraud**, **expired**, **endOfLife**, **accountClosure**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for updating the status of the payment instrument. Possible values: **lost**, **stolen**, **damaged**, **suspectedFraud**, **expired**, **endOfLife**, **accountClosure**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonPropertyName("statusReason")] + public StatusReasonEnum? StatusReason { get { return this._StatusReasonOption; } set { this._StatusReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the balance account associated with this payment instrument. >You can only change the balance account ID if the payment instrument has **inactive** status. + /// + /// The unique identifier of the balance account associated with this payment instrument. >You can only change the balance account ID if the payment instrument has **inactive** status. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public CardInfo? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusCommentOption { get; private set; } + + /// + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + /// + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + [JsonPropertyName("statusComment")] + public string? StatusComment { get { return this._StatusCommentOption; } set { this._StatusCommentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentUpdateRequest {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); + sb.Append(" StatusReason: ").Append(StatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentUpdateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentUpdateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option card = default; + Option status = default; + Option statusComment = default; + Option statusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentInstrumentUpdateRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "statusComment": + statusComment = new Option(utf8JsonReader.GetString()!); + break; + case "statusReason": + string? statusReasonRawValue = utf8JsonReader.GetString(); + statusReason = new Option(PaymentInstrumentUpdateRequest.StatusReasonEnum.FromStringOrDefault(statusReasonRawValue)); + break; + default: + break; + } + } + } + + + return new PaymentInstrumentUpdateRequest(balanceAccountId, card, status, statusComment, statusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentUpdateRequest paymentInstrumentUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentUpdateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentUpdateRequest paymentInstrumentUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentUpdateRequest._BalanceAccountIdOption.IsSet) + if (paymentInstrumentUpdateRequest.BalanceAccountId != null) + writer.WriteString("balanceAccountId", paymentInstrumentUpdateRequest.BalanceAccountId); + + if (paymentInstrumentUpdateRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, paymentInstrumentUpdateRequest.Card, jsonSerializerOptions); + } + if (paymentInstrumentUpdateRequest._StatusOption.IsSet && paymentInstrumentUpdateRequest.Status != null) + { + string? statusRawValue = PaymentInstrumentUpdateRequest.StatusEnum.ToJsonValue(paymentInstrumentUpdateRequest._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (paymentInstrumentUpdateRequest._StatusCommentOption.IsSet) + if (paymentInstrumentUpdateRequest.StatusComment != null) + writer.WriteString("statusComment", paymentInstrumentUpdateRequest.StatusComment); + + if (paymentInstrumentUpdateRequest._StatusReasonOption.IsSet && paymentInstrumentUpdateRequest.StatusReason != null) + { + string? statusReasonRawValue = PaymentInstrumentUpdateRequest.StatusReasonEnum.ToJsonValue(paymentInstrumentUpdateRequest._StatusReasonOption.Value!.Value); + writer.WriteString("statusReason", statusReasonRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/Phone.cs b/Adyen/BalancePlatform/Models/Phone.cs new file mode 100644 index 000000000..987dd98d1 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Phone.cs @@ -0,0 +1,298 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Phone. + /// + public partial class Phone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonConstructor] + public Phone(string number, TypeEnum type) + { + Number = number; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Phone() + { + } + + partial void OnCreated(); + + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Landline - landline + /// + public static readonly TypeEnum Landline = new("landline"); + + /// + /// TypeEnum.Mobile - mobile + /// + public static readonly TypeEnum Mobile = new("mobile"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "landline" => TypeEnum.Landline, + "mobile" => TypeEnum.Mobile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Landline) + return "landline"; + + if (value == TypeEnum.Mobile) + return "mobile"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + [JsonPropertyName("number")] + public string Number { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Phone {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Phone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Phone.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!number.IsSet) + throw new ArgumentException("Property is required for class Phone.", nameof(number)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Phone.", nameof(type)); + + return new Phone(number.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + if (phone.Number != null) + writer.WriteString("number", phone.Number); + + if (phone.Type != null) + { + string? typeRawValue = Phone.TypeEnum.ToJsonValue(phone.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PhoneNumber.cs b/Adyen/BalancePlatform/Models/PhoneNumber.cs new file mode 100644 index 000000000..675edc4d9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PhoneNumber.cs @@ -0,0 +1,351 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PhoneNumber. + /// + public partial class PhoneNumber : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + /// The phone number. The inclusion of the phone number country code is not necessary. + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonConstructor] + public PhoneNumber(Option phoneCountryCode = default, Option varPhoneNumber = default, Option phoneType = default) + { + _PhoneCountryCodeOption = phoneCountryCode; + _VarPhoneNumberOption = varPhoneNumber; + _PhoneTypeOption = phoneType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PhoneNumber() + { + } + + partial void OnCreated(); + + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonConverter(typeof(PhoneTypeEnumJsonConverter))] + public class PhoneTypeEnum : IEnum + { + /// + /// Returns the value of the PhoneTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PhoneTypeEnum.Fax - Fax + /// + public static readonly PhoneTypeEnum Fax = new("Fax"); + + /// + /// PhoneTypeEnum.Landline - Landline + /// + public static readonly PhoneTypeEnum Landline = new("Landline"); + + /// + /// PhoneTypeEnum.Mobile - Mobile + /// + public static readonly PhoneTypeEnum Mobile = new("Mobile"); + + /// + /// PhoneTypeEnum.SIP - SIP + /// + public static readonly PhoneTypeEnum SIP = new("SIP"); + + private PhoneTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PhoneTypeEnum?(string? value) => value == null ? null : new PhoneTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PhoneTypeEnum? option) => option?.Value; + + public static bool operator ==(PhoneTypeEnum? left, PhoneTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PhoneTypeEnum? left, PhoneTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PhoneTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PhoneTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "Fax" => PhoneTypeEnum.Fax, + "Landline" => PhoneTypeEnum.Landline, + "Mobile" => PhoneTypeEnum.Mobile, + "SIP" => PhoneTypeEnum.SIP, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PhoneTypeEnum? value) + { + if (value == null) + return null; + + if (value == PhoneTypeEnum.Fax) + return "Fax"; + + if (value == PhoneTypeEnum.Landline) + return "Landline"; + + if (value == PhoneTypeEnum.Mobile) + return "Mobile"; + + if (value == PhoneTypeEnum.SIP) + return "SIP"; + + return null; + } + + /// + /// JsonConverter for writing PhoneTypeEnum. + /// + public class PhoneTypeEnumJsonConverter : JsonConverter + { + public override PhoneTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PhoneTypeEnum.FromStringOrDefault(value) ?? new PhoneTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PhoneTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PhoneTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneTypeOption { get; private set; } + + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonPropertyName("phoneType")] + public PhoneTypeEnum? PhoneType { get { return this._PhoneTypeOption; } set { this._PhoneTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneCountryCodeOption { get; private set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + [JsonPropertyName("phoneCountryCode")] + public string? PhoneCountryCode { get { return this._PhoneCountryCodeOption; } set { this._PhoneCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VarPhoneNumberOption { get; private set; } + + /// + /// The phone number. The inclusion of the phone number country code is not necessary. + /// + /// The phone number. The inclusion of the phone number country code is not necessary. + [JsonPropertyName("phoneNumber")] + public string? VarPhoneNumber { get { return this._VarPhoneNumberOption; } set { this._VarPhoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PhoneNumber {\n"); + sb.Append(" PhoneCountryCode: ").Append(PhoneCountryCode).Append("\n"); + sb.Append(" VarPhoneNumber: ").Append(VarPhoneNumber).Append("\n"); + sb.Append(" PhoneType: ").Append(PhoneType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneNumberJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PhoneNumber Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option phoneCountryCode = default; + Option varPhoneNumber = default; + Option phoneType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "phoneCountryCode": + phoneCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + varPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "phoneType": + string? phoneTypeRawValue = utf8JsonReader.GetString(); + phoneType = new Option(PhoneNumber.PhoneTypeEnum.FromStringOrDefault(phoneTypeRawValue)); + break; + default: + break; + } + } + } + + + return new PhoneNumber(phoneCountryCode, varPhoneNumber, phoneType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phoneNumber, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + if (phoneNumber._PhoneCountryCodeOption.IsSet) + if (phoneNumber.PhoneCountryCode != null) + writer.WriteString("phoneCountryCode", phoneNumber.PhoneCountryCode); + + if (phoneNumber._VarPhoneNumberOption.IsSet) + if (phoneNumber.VarPhoneNumber != null) + writer.WriteString("phoneNumber", phoneNumber.VarPhoneNumber); + + if (phoneNumber._PhoneTypeOption.IsSet && phoneNumber.PhoneType != null) + { + string? phoneTypeRawValue = PhoneNumber.PhoneTypeEnum.ToJsonValue(phoneNumber._PhoneTypeOption.Value!.Value); + writer.WriteString("phoneType", phoneTypeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PinChangeRequest.cs b/Adyen/BalancePlatform/Models/PinChangeRequest.cs new file mode 100644 index 000000000..5e87494cd --- /dev/null +++ b/Adyen/BalancePlatform/Models/PinChangeRequest.cs @@ -0,0 +1,231 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PinChangeRequest. + /// + public partial class PinChangeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + /// The 16-digit token that you used to generate the `encryptedPinBlock`. + [JsonConstructor] + public PinChangeRequest(string encryptedKey, string encryptedPinBlock, string paymentInstrumentId, string token) + { + EncryptedKey = encryptedKey; + EncryptedPinBlock = encryptedPinBlock; + PaymentInstrumentId = paymentInstrumentId; + Token = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PinChangeRequest() + { + } + + partial void OnCreated(); + + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + [JsonPropertyName("encryptedKey")] + public string EncryptedKey { get; set; } + + /// + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + /// + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + [JsonPropertyName("encryptedPinBlock")] + public string EncryptedPinBlock { get; set; } + + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// The 16-digit token that you used to generate the `encryptedPinBlock`. + /// + /// The 16-digit token that you used to generate the `encryptedPinBlock`. + [JsonPropertyName("token")] + public string Token { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PinChangeRequest {\n"); + sb.Append(" EncryptedKey: ").Append(EncryptedKey).Append("\n"); + sb.Append(" EncryptedPinBlock: ").Append(EncryptedPinBlock).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PinChangeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PinChangeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encryptedKey = default; + Option encryptedPinBlock = default; + Option paymentInstrumentId = default; + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encryptedKey": + encryptedKey = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedPinBlock": + encryptedPinBlock = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!encryptedKey.IsSet) + throw new ArgumentException("Property is required for class PinChangeRequest.", nameof(encryptedKey)); + + if (!encryptedPinBlock.IsSet) + throw new ArgumentException("Property is required for class PinChangeRequest.", nameof(encryptedPinBlock)); + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class PinChangeRequest.", nameof(paymentInstrumentId)); + + if (!token.IsSet) + throw new ArgumentException("Property is required for class PinChangeRequest.", nameof(token)); + + return new PinChangeRequest(encryptedKey.Value!, encryptedPinBlock.Value!, paymentInstrumentId.Value!, token.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PinChangeRequest pinChangeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pinChangeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PinChangeRequest pinChangeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (pinChangeRequest.EncryptedKey != null) + writer.WriteString("encryptedKey", pinChangeRequest.EncryptedKey); + + if (pinChangeRequest.EncryptedPinBlock != null) + writer.WriteString("encryptedPinBlock", pinChangeRequest.EncryptedPinBlock); + + if (pinChangeRequest.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", pinChangeRequest.PaymentInstrumentId); + + if (pinChangeRequest.Token != null) + writer.WriteString("token", pinChangeRequest.Token); + } + } +} diff --git a/Adyen/BalancePlatform/Models/PinChangeResponse.cs b/Adyen/BalancePlatform/Models/PinChangeResponse.cs new file mode 100644 index 000000000..98ff906a2 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PinChangeResponse.cs @@ -0,0 +1,287 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PinChangeResponse. + /// + public partial class PinChangeResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the request for PIN change. Possible values: **completed**, **pending**, **unavailable**. + [JsonConstructor] + public PinChangeResponse(StatusEnum status) + { + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PinChangeResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of the request for PIN change. Possible values: **completed**, **pending**, **unavailable**. + /// + /// The status of the request for PIN change. Possible values: **completed**, **pending**, **unavailable**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Completed - completed + /// + public static readonly StatusEnum Completed = new("completed"); + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + /// + /// StatusEnum.Unavailable - unavailable + /// + public static readonly StatusEnum Unavailable = new("unavailable"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "completed" => StatusEnum.Completed, + "pending" => StatusEnum.Pending, + "unavailable" => StatusEnum.Unavailable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Completed) + return "completed"; + + if (value == StatusEnum.Pending) + return "pending"; + + if (value == StatusEnum.Unavailable) + return "unavailable"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the request for PIN change. Possible values: **completed**, **pending**, **unavailable**. + /// + /// The status of the request for PIN change. Possible values: **completed**, **pending**, **unavailable**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PinChangeResponse {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PinChangeResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PinChangeResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PinChangeResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PinChangeResponse.", nameof(status)); + + return new PinChangeResponse(status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PinChangeResponse pinChangeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pinChangeResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PinChangeResponse pinChangeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (pinChangeResponse.Status != null) + { + string? statusRawValue = PinChangeResponse.StatusEnum.ToJsonValue(pinChangeResponse.Status); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PlatformPaymentConfiguration.cs b/Adyen/BalancePlatform/Models/PlatformPaymentConfiguration.cs new file mode 100644 index 000000000..ac9ef593f --- /dev/null +++ b/Adyen/BalancePlatform/Models/PlatformPaymentConfiguration.cs @@ -0,0 +1,201 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PlatformPaymentConfiguration. + /// + public partial class PlatformPaymentConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + [JsonConstructor] + public PlatformPaymentConfiguration(Option salesDayClosingTime = default, Option settlementDelayDays = default) + { + _SalesDayClosingTimeOption = salesDayClosingTime; + _SettlementDelayDaysOption = settlementDelayDays; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformPaymentConfiguration() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SalesDayClosingTimeOption { get; private set; } + + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + [JsonPropertyName("salesDayClosingTime")] + public string? SalesDayClosingTime { get { return this._SalesDayClosingTimeOption; } set { this._SalesDayClosingTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SettlementDelayDaysOption { get; private set; } + + /// + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + /// + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + [JsonPropertyName("settlementDelayDays")] + public int? SettlementDelayDays { get { return this._SettlementDelayDaysOption; } set { this._SettlementDelayDaysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformPaymentConfiguration {\n"); + sb.Append(" SalesDayClosingTime: ").Append(SalesDayClosingTime).Append("\n"); + sb.Append(" SettlementDelayDays: ").Append(SettlementDelayDays).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformPaymentConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformPaymentConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option salesDayClosingTime = default; + Option settlementDelayDays = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "salesDayClosingTime": + salesDayClosingTime = new Option(utf8JsonReader.GetString()!); + break; + case "settlementDelayDays": + settlementDelayDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new PlatformPaymentConfiguration(salesDayClosingTime, settlementDelayDays); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformPaymentConfiguration platformPaymentConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformPaymentConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformPaymentConfiguration platformPaymentConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformPaymentConfiguration._SalesDayClosingTimeOption.IsSet) + if (platformPaymentConfiguration.SalesDayClosingTime != null) + writer.WriteString("salesDayClosingTime", platformPaymentConfiguration.SalesDayClosingTime); + + if (platformPaymentConfiguration._SettlementDelayDaysOption.IsSet) + writer.WriteNumber("settlementDelayDays", platformPaymentConfiguration._SettlementDelayDaysOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ProcessingTypesRestriction.cs b/Adyen/BalancePlatform/Models/ProcessingTypesRestriction.cs new file mode 100644 index 000000000..d7503415b --- /dev/null +++ b/Adyen/BalancePlatform/Models/ProcessingTypesRestriction.cs @@ -0,0 +1,354 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ProcessingTypesRestriction. + /// + public partial class ProcessingTypesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// List of processing types. Possible values: **atmWithdraw**, **balanceInquiry**, **ecommerce**, **moto**, **pos**, **recurring**, **token**. + [JsonConstructor] + public ProcessingTypesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ProcessingTypesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.AtmWithdraw - atmWithdraw + /// + public static readonly ValueEnum AtmWithdraw = new("atmWithdraw"); + + /// + /// ValueEnum.BalanceInquiry - balanceInquiry + /// + public static readonly ValueEnum BalanceInquiry = new("balanceInquiry"); + + /// + /// ValueEnum.Ecommerce - ecommerce + /// + public static readonly ValueEnum Ecommerce = new("ecommerce"); + + /// + /// ValueEnum.Moto - moto + /// + public static readonly ValueEnum Moto = new("moto"); + + /// + /// ValueEnum.Pos - pos + /// + public static readonly ValueEnum Pos = new("pos"); + + /// + /// ValueEnum.Recurring - recurring + /// + public static readonly ValueEnum Recurring = new("recurring"); + + /// + /// ValueEnum.Token - token + /// + public static readonly ValueEnum Token = new("token"); + + /// + /// ValueEnum.Unknown - unknown + /// + public static readonly ValueEnum Unknown = new("unknown"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "atmWithdraw" => ValueEnum.AtmWithdraw, + "balanceInquiry" => ValueEnum.BalanceInquiry, + "ecommerce" => ValueEnum.Ecommerce, + "moto" => ValueEnum.Moto, + "pos" => ValueEnum.Pos, + "recurring" => ValueEnum.Recurring, + "token" => ValueEnum.Token, + "unknown" => ValueEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.AtmWithdraw) + return "atmWithdraw"; + + if (value == ValueEnum.BalanceInquiry) + return "balanceInquiry"; + + if (value == ValueEnum.Ecommerce) + return "ecommerce"; + + if (value == ValueEnum.Moto) + return "moto"; + + if (value == ValueEnum.Pos) + return "pos"; + + if (value == ValueEnum.Recurring) + return "recurring"; + + if (value == ValueEnum.Token) + return "token"; + + if (value == ValueEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// List of processing types. Possible values: **atmWithdraw**, **balanceInquiry**, **ecommerce**, **moto**, **pos**, **recurring**, **token**. + /// + /// List of processing types. Possible values: **atmWithdraw**, **balanceInquiry**, **ecommerce**, **moto**, **pos**, **recurring**, **token**. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProcessingTypesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProcessingTypesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ProcessingTypesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class ProcessingTypesRestriction.", nameof(operation)); + + return new ProcessingTypesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProcessingTypesRestriction processingTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, processingTypesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProcessingTypesRestriction processingTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (processingTypesRestriction.Operation != null) + writer.WriteString("operation", processingTypesRestriction.Operation); + + if (processingTypesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, processingTypesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/PublicKeyResponse.cs b/Adyen/BalancePlatform/Models/PublicKeyResponse.cs new file mode 100644 index 000000000..2c06e5704 --- /dev/null +++ b/Adyen/BalancePlatform/Models/PublicKeyResponse.cs @@ -0,0 +1,191 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// PublicKeyResponse. + /// + public partial class PublicKeyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The public key you need for encrypting a symmetric session key. + /// The expiry date of the public key. + [JsonConstructor] + public PublicKeyResponse(string publicKey, string publicKeyExpiryDate) + { + PublicKey = publicKey; + PublicKeyExpiryDate = publicKeyExpiryDate; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PublicKeyResponse() + { + } + + partial void OnCreated(); + + /// + /// The public key you need for encrypting a symmetric session key. + /// + /// The public key you need for encrypting a symmetric session key. + [JsonPropertyName("publicKey")] + public string PublicKey { get; set; } + + /// + /// The expiry date of the public key. + /// + /// The expiry date of the public key. + [JsonPropertyName("publicKeyExpiryDate")] + public string PublicKeyExpiryDate { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PublicKeyResponse {\n"); + sb.Append(" PublicKey: ").Append(PublicKey).Append("\n"); + sb.Append(" PublicKeyExpiryDate: ").Append(PublicKeyExpiryDate).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PublicKeyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PublicKeyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option publicKey = default; + Option publicKeyExpiryDate = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "publicKey": + publicKey = new Option(utf8JsonReader.GetString()!); + break; + case "publicKeyExpiryDate": + publicKeyExpiryDate = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!publicKey.IsSet) + throw new ArgumentException("Property is required for class PublicKeyResponse.", nameof(publicKey)); + + if (!publicKeyExpiryDate.IsSet) + throw new ArgumentException("Property is required for class PublicKeyResponse.", nameof(publicKeyExpiryDate)); + + return new PublicKeyResponse(publicKey.Value!, publicKeyExpiryDate.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PublicKeyResponse publicKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, publicKeyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PublicKeyResponse publicKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (publicKeyResponse.PublicKey != null) + writer.WriteString("publicKey", publicKeyResponse.PublicKey); + + if (publicKeyResponse.PublicKeyExpiryDate != null) + writer.WriteString("publicKeyExpiryDate", publicKeyResponse.PublicKeyExpiryDate); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RegisterSCAFinalResponse.cs b/Adyen/BalancePlatform/Models/RegisterSCAFinalResponse.cs new file mode 100644 index 000000000..cc4ca070b --- /dev/null +++ b/Adyen/BalancePlatform/Models/RegisterSCAFinalResponse.cs @@ -0,0 +1,176 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RegisterSCAFinalResponse. + /// + public partial class RegisterSCAFinalResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies if the registration was initiated successfully. + [JsonConstructor] + public RegisterSCAFinalResponse(Option success = default) + { + _SuccessOption = success; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RegisterSCAFinalResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuccessOption { get; private set; } + + /// + /// Specifies if the registration was initiated successfully. + /// + /// Specifies if the registration was initiated successfully. + [JsonPropertyName("success")] + public bool? Success { get { return this._SuccessOption; } set { this._SuccessOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RegisterSCAFinalResponse {\n"); + sb.Append(" Success: ").Append(Success).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RegisterSCAFinalResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RegisterSCAFinalResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option success = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "success": + success = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new RegisterSCAFinalResponse(success); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RegisterSCAFinalResponse registerSCAFinalResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, registerSCAFinalResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RegisterSCAFinalResponse registerSCAFinalResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (registerSCAFinalResponse._SuccessOption.IsSet) + writer.WriteBoolean("success", registerSCAFinalResponse._SuccessOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RegisterSCARequest.cs b/Adyen/BalancePlatform/Models/RegisterSCARequest.cs new file mode 100644 index 000000000..885c43ace --- /dev/null +++ b/Adyen/BalancePlatform/Models/RegisterSCARequest.cs @@ -0,0 +1,214 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RegisterSCARequest. + /// + public partial class RegisterSCARequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the payment instrument for which you are registering the SCA device. + /// strongCustomerAuthentication + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. If you do not specify a `name`, Adyen automatically generates one. + [JsonConstructor] + public RegisterSCARequest(string paymentInstrumentId, DelegatedAuthenticationData strongCustomerAuthentication, Option name = default) + { + PaymentInstrumentId = paymentInstrumentId; + StrongCustomerAuthentication = strongCustomerAuthentication; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RegisterSCARequest() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the payment instrument for which you are registering the SCA device. + /// + /// The unique identifier of the payment instrument for which you are registering the SCA device. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// . + /// + [JsonPropertyName("strongCustomerAuthentication")] + public DelegatedAuthenticationData StrongCustomerAuthentication { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. If you do not specify a `name`, Adyen automatically generates one. + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. If you do not specify a `name`, Adyen automatically generates one. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RegisterSCARequest {\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" StrongCustomerAuthentication: ").Append(StrongCustomerAuthentication).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RegisterSCARequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RegisterSCARequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option paymentInstrumentId = default; + Option strongCustomerAuthentication = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "strongCustomerAuthentication": + strongCustomerAuthentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class RegisterSCARequest.", nameof(paymentInstrumentId)); + + if (!strongCustomerAuthentication.IsSet) + throw new ArgumentException("Property is required for class RegisterSCARequest.", nameof(strongCustomerAuthentication)); + + return new RegisterSCARequest(paymentInstrumentId.Value!, strongCustomerAuthentication.Value!, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RegisterSCARequest registerSCARequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, registerSCARequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RegisterSCARequest registerSCARequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (registerSCARequest.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", registerSCARequest.PaymentInstrumentId); + + writer.WritePropertyName("strongCustomerAuthentication"); + JsonSerializer.Serialize(writer, registerSCARequest.StrongCustomerAuthentication, jsonSerializerOptions); + if (registerSCARequest._NameOption.IsSet) + if (registerSCARequest.Name != null) + writer.WriteString("name", registerSCARequest.Name); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RegisterSCAResponse.cs b/Adyen/BalancePlatform/Models/RegisterSCAResponse.cs new file mode 100644 index 000000000..34bc2842f --- /dev/null +++ b/Adyen/BalancePlatform/Models/RegisterSCAResponse.cs @@ -0,0 +1,257 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RegisterSCAResponse. + /// + public partial class RegisterSCAResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the SCA device you are registering. + /// The unique identifier of the payment instrument for which you are registering the SCA device. + /// A string that you must pass to the authentication SDK to continue with the registration process. + /// Specifies if the registration was initiated successfully. + [JsonConstructor] + public RegisterSCAResponse(Option id = default, Option paymentInstrumentId = default, Option sdkInput = default, Option success = default) + { + _IdOption = id; + _PaymentInstrumentIdOption = paymentInstrumentId; + _SdkInputOption = sdkInput; + _SuccessOption = success; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RegisterSCAResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the SCA device you are registering. + /// + /// The unique identifier of the SCA device you are registering. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument for which you are registering the SCA device. + /// + /// The unique identifier of the payment instrument for which you are registering the SCA device. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInputOption { get; private set; } + + /// + /// A string that you must pass to the authentication SDK to continue with the registration process. + /// + /// A string that you must pass to the authentication SDK to continue with the registration process. + [JsonPropertyName("sdkInput")] + public string? SdkInput { get { return this._SdkInputOption; } set { this._SdkInputOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuccessOption { get; private set; } + + /// + /// Specifies if the registration was initiated successfully. + /// + /// Specifies if the registration was initiated successfully. + [JsonPropertyName("success")] + public bool? Success { get { return this._SuccessOption; } set { this._SuccessOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RegisterSCAResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" SdkInput: ").Append(SdkInput).Append("\n"); + sb.Append(" Success: ").Append(Success).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SdkInput (string) maxLength + if (this.SdkInput != null && this.SdkInput.Length > 20000) + { + yield return new ValidationResult("Invalid value for SdkInput, length must be less than 20000.", new [] { "SdkInput" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RegisterSCAResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RegisterSCAResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option paymentInstrumentId = default; + Option sdkInput = default; + Option success = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "sdkInput": + sdkInput = new Option(utf8JsonReader.GetString()!); + break; + case "success": + success = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new RegisterSCAResponse(id, paymentInstrumentId, sdkInput, success); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RegisterSCAResponse registerSCAResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, registerSCAResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RegisterSCAResponse registerSCAResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (registerSCAResponse._IdOption.IsSet) + if (registerSCAResponse.Id != null) + writer.WriteString("id", registerSCAResponse.Id); + + if (registerSCAResponse._PaymentInstrumentIdOption.IsSet) + if (registerSCAResponse.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", registerSCAResponse.PaymentInstrumentId); + + if (registerSCAResponse._SdkInputOption.IsSet) + if (registerSCAResponse.SdkInput != null) + writer.WriteString("sdkInput", registerSCAResponse.SdkInput); + + if (registerSCAResponse._SuccessOption.IsSet) + writer.WriteBoolean("success", registerSCAResponse._SuccessOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RemediatingAction.cs b/Adyen/BalancePlatform/Models/RemediatingAction.cs new file mode 100644 index 000000000..4d8354d10 --- /dev/null +++ b/Adyen/BalancePlatform/Models/RemediatingAction.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RemediatingAction. + /// + public partial class RemediatingAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The remediating action code. + /// A description of how you can resolve the verification error. + [JsonConstructor] + public RemediatingAction(Option code = default, Option message = default) + { + _CodeOption = code; + _MessageOption = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RemediatingAction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The remediating action code. + /// + /// The remediating action code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of how you can resolve the verification error. + /// + /// A description of how you can resolve the verification error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RemediatingAction {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RemediatingActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RemediatingAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RemediatingAction(code, message); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, remediatingAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (remediatingAction._CodeOption.IsSet) + if (remediatingAction.Code != null) + writer.WriteString("code", remediatingAction.Code); + + if (remediatingAction._MessageOption.IsSet) + if (remediatingAction.Message != null) + writer.WriteString("message", remediatingAction.Message); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RemoveAssociationRequest.cs b/Adyen/BalancePlatform/Models/RemoveAssociationRequest.cs new file mode 100644 index 000000000..a58396dc0 --- /dev/null +++ b/Adyen/BalancePlatform/Models/RemoveAssociationRequest.cs @@ -0,0 +1,224 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RemoveAssociationRequest. + /// + public partial class RemoveAssociationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the entity. + /// entityType + /// A list of device ids associated with the entity that should be removed. + [JsonConstructor] + public RemoveAssociationRequest(string entityId, ScaEntityType entityType, List scaDeviceIds) + { + EntityId = entityId; + EntityType = entityType; + ScaDeviceIds = scaDeviceIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RemoveAssociationRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("entityType")] + public ScaEntityType EntityType { get; set; } + + /// + /// The unique identifier of the entity. + /// + /// The unique identifier of the entity. + [JsonPropertyName("entityId")] + public string EntityId { get; set; } + + /// + /// A list of device ids associated with the entity that should be removed. + /// + /// A list of device ids associated with the entity that should be removed. + [JsonPropertyName("scaDeviceIds")] + public List ScaDeviceIds { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RemoveAssociationRequest {\n"); + sb.Append(" EntityId: ").Append(EntityId).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" ScaDeviceIds: ").Append(ScaDeviceIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EntityId (string) maxLength + if (this.EntityId != null && this.EntityId.Length > 100) + { + yield return new ValidationResult("Invalid value for EntityId, length must be less than 100.", new [] { "EntityId" }); + } + + // EntityId (string) minLength + if (this.EntityId != null && this.EntityId.Length < 1) + { + yield return new ValidationResult("Invalid value for EntityId, length must be greater than 1.", new [] { "EntityId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RemoveAssociationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RemoveAssociationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entityId = default; + Option entityType = default; + Option?> scaDeviceIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entityId": + entityId = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + if (entityTypeRawValue != null) + entityType = new Option(ScaEntityTypeValueConverter.FromStringOrDefault(entityTypeRawValue)); + break; + case "scaDeviceIds": + scaDeviceIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!entityId.IsSet) + throw new ArgumentException("Property is required for class RemoveAssociationRequest.", nameof(entityId)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class RemoveAssociationRequest.", nameof(entityType)); + + if (!scaDeviceIds.IsSet) + throw new ArgumentException("Property is required for class RemoveAssociationRequest.", nameof(scaDeviceIds)); + + return new RemoveAssociationRequest(entityId.Value!, entityType.Value!.Value!, scaDeviceIds.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RemoveAssociationRequest removeAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, removeAssociationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RemoveAssociationRequest removeAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (removeAssociationRequest.EntityId != null) + writer.WriteString("entityId", removeAssociationRequest.EntityId); + + var entityTypeRawValue = ScaEntityTypeValueConverter.ToJsonValue(removeAssociationRequest.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + + writer.WritePropertyName("scaDeviceIds"); + JsonSerializer.Serialize(writer, removeAssociationRequest.ScaDeviceIds, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Repayment.cs b/Adyen/BalancePlatform/Models/Repayment.cs new file mode 100644 index 000000000..b3a8a91b9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Repayment.cs @@ -0,0 +1,221 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Repayment. + /// + public partial class Repayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + /// term + /// threshold + [JsonConstructor] + public Repayment(int basisPoints, Option term = default, Option threshold = default) + { + BasisPoints = basisPoints; + _TermOption = term; + _ThresholdOption = threshold; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Repayment() + { + } + + partial void OnCreated(); + + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + [JsonPropertyName("basisPoints")] + public int BasisPoints { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("term")] + public RepaymentTerm? Term { get { return this._TermOption; } set { this._TermOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThresholdOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threshold")] + public ThresholdRepayment? Threshold { get { return this._ThresholdOption; } set { this._ThresholdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Repayment {\n"); + sb.Append(" BasisPoints: ").Append(BasisPoints).Append("\n"); + sb.Append(" Term: ").Append(Term).Append("\n"); + sb.Append(" Threshold: ").Append(Threshold).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RepaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Repayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option basisPoints = default; + Option term = default; + Option threshold = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "basisPoints": + basisPoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "term": + term = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threshold": + threshold = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!basisPoints.IsSet) + throw new ArgumentException("Property is required for class Repayment.", nameof(basisPoints)); + + return new Repayment(basisPoints.Value!.Value!, term, threshold); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Repayment repayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, repayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Repayment repayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("basisPoints", repayment.BasisPoints); + + if (repayment._TermOption.IsSet) + { + writer.WritePropertyName("term"); + JsonSerializer.Serialize(writer, repayment.Term, jsonSerializerOptions); + } + if (repayment._ThresholdOption.IsSet) + { + writer.WritePropertyName("threshold"); + JsonSerializer.Serialize(writer, repayment.Threshold, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/RepaymentTerm.cs b/Adyen/BalancePlatform/Models/RepaymentTerm.cs new file mode 100644 index 000000000..e089a9d4c --- /dev/null +++ b/Adyen/BalancePlatform/Models/RepaymentTerm.cs @@ -0,0 +1,194 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RepaymentTerm. + /// + public partial class RepaymentTerm : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The estimated term for repaying the grant, in days. + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + [JsonConstructor] + public RepaymentTerm(int estimatedDays, Option maximumDays = default) + { + EstimatedDays = estimatedDays; + _MaximumDaysOption = maximumDays; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RepaymentTerm() + { + } + + partial void OnCreated(); + + /// + /// The estimated term for repaying the grant, in days. + /// + /// The estimated term for repaying the grant, in days. + [JsonPropertyName("estimatedDays")] + public int EstimatedDays { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaximumDaysOption { get; private set; } + + /// + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + /// + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + [JsonPropertyName("maximumDays")] + public int? MaximumDays { get { return this._MaximumDaysOption; } set { this._MaximumDaysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RepaymentTerm {\n"); + sb.Append(" EstimatedDays: ").Append(EstimatedDays).Append("\n"); + sb.Append(" MaximumDays: ").Append(MaximumDays).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RepaymentTermJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RepaymentTerm Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option estimatedDays = default; + Option maximumDays = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "estimatedDays": + estimatedDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "maximumDays": + maximumDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!estimatedDays.IsSet) + throw new ArgumentException("Property is required for class RepaymentTerm.", nameof(estimatedDays)); + + return new RepaymentTerm(estimatedDays.Value!.Value!, maximumDays); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RepaymentTerm repaymentTerm, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, repaymentTerm, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RepaymentTerm repaymentTerm, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("estimatedDays", repaymentTerm.EstimatedDays); + + if (repaymentTerm._MaximumDaysOption.IsSet) + writer.WriteNumber("maximumDays", repaymentTerm._MaximumDaysOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RestServiceError.cs b/Adyen/BalancePlatform/Models/RestServiceError.cs new file mode 100644 index 000000000..1a089d0df --- /dev/null +++ b/Adyen/BalancePlatform/Models/RestServiceError.cs @@ -0,0 +1,352 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RestServiceError. + /// + public partial class RestServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// A code that identifies the problem type. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// A unique URI that identifies the specific occurrence of the problem. + /// Detailed explanation of each validation error, when applicable. + /// A unique reference for the request, essentially the same as `pspReference`. + /// response + [JsonConstructor] + public RestServiceError(string detail, string errorCode, int status, string title, string type, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option response = default) + { + Detail = detail; + ErrorCode = errorCode; + Status = status; + Title = title; + Type = type; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _ResponseOption = response; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RestServiceError() + { + } + + partial void OnCreated(); + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string Detail { get; set; } + + /// + /// A code that identifies the problem type. + /// + /// A code that identifies the problem type. + [JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A unique URI that identifies the specific occurrence of the problem. + /// + /// A unique URI that identifies the specific occurrence of the problem. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Detailed explanation of each validation error, when applicable. + /// + /// Detailed explanation of each validation error, when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// A unique reference for the request, essentially the same as `pspReference`. + /// + /// A unique reference for the request, essentially the same as `pspReference`. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("response")] + public Object? Response { get { return this._ResponseOption; } set { this._ResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RestServiceError {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RestServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RestServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option status = default; + Option title = default; + Option type = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option response = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "response": + response = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!detail.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(detail)); + + if (!errorCode.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(errorCode)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(status)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(title)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(type)); + + return new RestServiceError(detail.Value!, errorCode.Value!, status.Value!.Value!, title.Value!, type.Value!, instance, invalidFields, requestId, response); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, restServiceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (restServiceError.Detail != null) + writer.WriteString("detail", restServiceError.Detail); + + if (restServiceError.ErrorCode != null) + writer.WriteString("errorCode", restServiceError.ErrorCode); + + writer.WriteNumber("status", restServiceError.Status); + + if (restServiceError.Title != null) + writer.WriteString("title", restServiceError.Title); + + if (restServiceError.Type != null) + writer.WriteString("type", restServiceError.Type); + + if (restServiceError._InstanceOption.IsSet) + if (restServiceError.Instance != null) + writer.WriteString("instance", restServiceError.Instance); + + if (restServiceError._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, restServiceError.InvalidFields, jsonSerializerOptions); + } + if (restServiceError._RequestIdOption.IsSet) + if (restServiceError.RequestId != null) + writer.WriteString("requestId", restServiceError.RequestId); + + if (restServiceError._ResponseOption.IsSet) + { + writer.WritePropertyName("response"); + JsonSerializer.Serialize(writer, restServiceError.Response, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/RevealPinRequest.cs b/Adyen/BalancePlatform/Models/RevealPinRequest.cs new file mode 100644 index 000000000..60978f72e --- /dev/null +++ b/Adyen/BalancePlatform/Models/RevealPinRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RevealPinRequest. + /// + public partial class RevealPinRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + [JsonConstructor] + public RevealPinRequest(string encryptedKey, string paymentInstrumentId) + { + EncryptedKey = encryptedKey; + PaymentInstrumentId = paymentInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RevealPinRequest() + { + } + + partial void OnCreated(); + + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + /// + /// The symmetric session key that you encrypted with the [public key](https://docs.adyen.com/api-explorer/balanceplatform/2/get/publicKey) that you received from Adyen. + [JsonPropertyName("encryptedKey")] + public string EncryptedKey { get; set; } + + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + /// + /// The unique identifier of the payment instrument, which is the card for which you are managing the PIN. + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RevealPinRequest {\n"); + sb.Append(" EncryptedKey: ").Append(EncryptedKey).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RevealPinRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RevealPinRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encryptedKey = default; + Option paymentInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encryptedKey": + encryptedKey = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!encryptedKey.IsSet) + throw new ArgumentException("Property is required for class RevealPinRequest.", nameof(encryptedKey)); + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class RevealPinRequest.", nameof(paymentInstrumentId)); + + return new RevealPinRequest(encryptedKey.Value!, paymentInstrumentId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RevealPinRequest revealPinRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, revealPinRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RevealPinRequest revealPinRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (revealPinRequest.EncryptedKey != null) + writer.WriteString("encryptedKey", revealPinRequest.EncryptedKey); + + if (revealPinRequest.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", revealPinRequest.PaymentInstrumentId); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RevealPinResponse.cs b/Adyen/BalancePlatform/Models/RevealPinResponse.cs new file mode 100644 index 000000000..5c675814b --- /dev/null +++ b/Adyen/BalancePlatform/Models/RevealPinResponse.cs @@ -0,0 +1,191 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RevealPinResponse. + /// + public partial class RevealPinResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + /// The 16-digit token that you need to extract the `encryptedPinBlock`. + [JsonConstructor] + public RevealPinResponse(string encryptedPinBlock, string token) + { + EncryptedPinBlock = encryptedPinBlock; + Token = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RevealPinResponse() + { + } + + partial void OnCreated(); + + /// + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + /// + /// The encrypted [PIN block](https://www.pcisecuritystandards.org/glossary/pin-block). + [JsonPropertyName("encryptedPinBlock")] + public string EncryptedPinBlock { get; set; } + + /// + /// The 16-digit token that you need to extract the `encryptedPinBlock`. + /// + /// The 16-digit token that you need to extract the `encryptedPinBlock`. + [JsonPropertyName("token")] + public string Token { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RevealPinResponse {\n"); + sb.Append(" EncryptedPinBlock: ").Append(EncryptedPinBlock).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RevealPinResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RevealPinResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encryptedPinBlock = default; + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encryptedPinBlock": + encryptedPinBlock = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!encryptedPinBlock.IsSet) + throw new ArgumentException("Property is required for class RevealPinResponse.", nameof(encryptedPinBlock)); + + if (!token.IsSet) + throw new ArgumentException("Property is required for class RevealPinResponse.", nameof(token)); + + return new RevealPinResponse(encryptedPinBlock.Value!, token.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RevealPinResponse revealPinResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, revealPinResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RevealPinResponse revealPinResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (revealPinResponse.EncryptedPinBlock != null) + writer.WriteString("encryptedPinBlock", revealPinResponse.EncryptedPinBlock); + + if (revealPinResponse.Token != null) + writer.WriteString("token", revealPinResponse.Token); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RiskScores.cs b/Adyen/BalancePlatform/Models/RiskScores.cs new file mode 100644 index 000000000..2a0cf3fa8 --- /dev/null +++ b/Adyen/BalancePlatform/Models/RiskScores.cs @@ -0,0 +1,200 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RiskScores. + /// + public partial class RiskScores : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Transaction risk score provided by Mastercard. Values provided by Mastercard range between 0 (lowest risk) to 998 (highest risk). + /// Transaction risk score provided by Visa. Values provided by Visa range between 01 (lowest risk) to 99 (highest risk). + [JsonConstructor] + public RiskScores(Option mastercard = default, Option visa = default) + { + _MastercardOption = mastercard; + _VisaOption = visa; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RiskScores() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MastercardOption { get; private set; } + + /// + /// Transaction risk score provided by Mastercard. Values provided by Mastercard range between 0 (lowest risk) to 998 (highest risk). + /// + /// Transaction risk score provided by Mastercard. Values provided by Mastercard range between 0 (lowest risk) to 998 (highest risk). + [JsonPropertyName("mastercard")] + public int? Mastercard { get { return this._MastercardOption; } set { this._MastercardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaOption { get; private set; } + + /// + /// Transaction risk score provided by Visa. Values provided by Visa range between 01 (lowest risk) to 99 (highest risk). + /// + /// Transaction risk score provided by Visa. Values provided by Visa range between 01 (lowest risk) to 99 (highest risk). + [JsonPropertyName("visa")] + public int? Visa { get { return this._VisaOption; } set { this._VisaOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RiskScores {\n"); + sb.Append(" Mastercard: ").Append(Mastercard).Append("\n"); + sb.Append(" Visa: ").Append(Visa).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RiskScoresJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RiskScores Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option mastercard = default; + Option visa = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "mastercard": + mastercard = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "visa": + visa = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new RiskScores(mastercard, visa); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RiskScores riskScores, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, riskScores, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RiskScores riskScores, JsonSerializerOptions jsonSerializerOptions) + { + + if (riskScores._MastercardOption.IsSet) + writer.WriteNumber("mastercard", riskScores._MastercardOption.Value!.Value); + + if (riskScores._VisaOption.IsSet) + writer.WriteNumber("visa", riskScores._VisaOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/RiskScoresRestriction.cs b/Adyen/BalancePlatform/Models/RiskScoresRestriction.cs new file mode 100644 index 000000000..89f9301a9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/RiskScoresRestriction.cs @@ -0,0 +1,197 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// RiskScoresRestriction. + /// + public partial class RiskScoresRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public RiskScoresRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RiskScoresRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public RiskScores? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RiskScoresRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RiskScoresRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RiskScoresRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class RiskScoresRestriction.", nameof(operation)); + + return new RiskScoresRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RiskScoresRestriction riskScoresRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, riskScoresRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RiskScoresRestriction riskScoresRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (riskScoresRestriction.Operation != null) + writer.WriteString("operation", riskScoresRestriction.Operation); + + if (riskScoresRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, riskScoresRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/SELocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/SELocalAccountIdentification.cs new file mode 100644 index 000000000..a6583fc3e --- /dev/null +++ b/Adyen/BalancePlatform/Models/SELocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SELocalAccountIdentification. + /// + public partial class SELocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// **seLocal** (default to TypeEnum.SeLocal) + [JsonConstructor] + public SELocalAccountIdentification(string accountNumber, string clearingNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingNumber = clearingNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SELocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SeLocal - seLocal + /// + public static readonly TypeEnum SeLocal = new("seLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "seLocal" => TypeEnum.SeLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SeLocal) + return "seLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + [JsonPropertyName("clearingNumber")] + public string ClearingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SELocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingNumber: ").Append(ClearingNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 7) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 7.", new [] { "AccountNumber" }); + } + + // ClearingNumber (string) maxLength + if (this.ClearingNumber != null && this.ClearingNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be less than 5.", new [] { "ClearingNumber" }); + } + + // ClearingNumber (string) minLength + if (this.ClearingNumber != null && this.ClearingNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be greater than 4.", new [] { "ClearingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SELocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SELocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingNumber": + clearingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SELocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(clearingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(type)); + + return new SELocalAccountIdentification(accountNumber.Value!, clearingNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sELocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sELocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sELocalAccountIdentification.AccountNumber); + + if (sELocalAccountIdentification.ClearingNumber != null) + writer.WriteString("clearingNumber", sELocalAccountIdentification.ClearingNumber); + + if (sELocalAccountIdentification.Type != null) + { + string? typeRawValue = SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/SGLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/SGLocalAccountIdentification.cs new file mode 100644 index 000000000..aec8c07f3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SGLocalAccountIdentification.cs @@ -0,0 +1,337 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SGLocalAccountIdentification. + /// + public partial class SGLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// **sgLocal** (default to TypeEnum.SgLocal) + [JsonConstructor] + public SGLocalAccountIdentification(string accountNumber, string bic, Option type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SGLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SgLocal - sgLocal + /// + public static readonly TypeEnum SgLocal = new("sgLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sgLocal" => TypeEnum.SgLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SgLocal) + return "sgLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SGLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 19) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 19.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SGLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SGLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SGLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(bic)); + + return new SGLocalAccountIdentification(accountNumber.Value!, bic.Value!, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sGLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sGLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sGLocalAccountIdentification.AccountNumber); + + if (sGLocalAccountIdentification.Bic != null) + writer.WriteString("bic", sGLocalAccountIdentification.Bic); + + if (sGLocalAccountIdentification._TypeOption.IsSet && sGLocalAccountIdentification.Type != null) + { + string? typeRawValue = SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/SameAmountRestriction.cs b/Adyen/BalancePlatform/Models/SameAmountRestriction.cs new file mode 100644 index 000000000..5c76f350d --- /dev/null +++ b/Adyen/BalancePlatform/Models/SameAmountRestriction.cs @@ -0,0 +1,194 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SameAmountRestriction. + /// + public partial class SameAmountRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public SameAmountRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SameAmountRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public bool? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SameAmountRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SameAmountRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SameAmountRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class SameAmountRestriction.", nameof(operation)); + + return new SameAmountRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SameAmountRestriction sameAmountRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sameAmountRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SameAmountRestriction sameAmountRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (sameAmountRestriction.Operation != null) + writer.WriteString("operation", sameAmountRestriction.Operation); + + if (sameAmountRestriction._ValueOption.IsSet) + writer.WriteBoolean("value", sameAmountRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SameCounterpartyRestriction.cs b/Adyen/BalancePlatform/Models/SameCounterpartyRestriction.cs new file mode 100644 index 000000000..2eecedfeb --- /dev/null +++ b/Adyen/BalancePlatform/Models/SameCounterpartyRestriction.cs @@ -0,0 +1,194 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SameCounterpartyRestriction. + /// + public partial class SameCounterpartyRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public SameCounterpartyRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SameCounterpartyRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public bool? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SameCounterpartyRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SameCounterpartyRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SameCounterpartyRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class SameCounterpartyRestriction.", nameof(operation)); + + return new SameCounterpartyRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SameCounterpartyRestriction sameCounterpartyRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sameCounterpartyRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SameCounterpartyRestriction sameCounterpartyRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (sameCounterpartyRestriction.Operation != null) + writer.WriteString("operation", sameCounterpartyRestriction.Operation); + + if (sameCounterpartyRestriction._ValueOption.IsSet) + writer.WriteBoolean("value", sameCounterpartyRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaDevice.cs b/Adyen/BalancePlatform/Models/ScaDevice.cs new file mode 100644 index 000000000..d2db72068 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaDevice.cs @@ -0,0 +1,224 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// A resource that contains information about a device, including its unique ID, name, and type.. + /// + public partial class ScaDevice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the SCA device you are registering. + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + /// type + [JsonConstructor] + public ScaDevice(string id, string name, ScaDeviceType type) + { + Id = id; + Name = name; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScaDevice() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("type")] + public ScaDeviceType Type { get; set; } + + /// + /// The unique identifier of the SCA device you are registering. + /// + /// The unique identifier of the SCA device you are registering. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + /// + /// The name of the SCA device that you are registering. You can use it to help your users identify the device. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScaDevice {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Name (string) maxLength + if (this.Name != null && this.Name.Length > 64) + { + yield return new ValidationResult("Invalid value for Name, length must be less than 64.", new [] { "Name" }); + } + + // Name (string) minLength + if (this.Name != null && this.Name.Length < 0) + { + yield return new ValidationResult("Invalid value for Name, length must be greater than 0.", new [] { "Name" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScaDeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScaDevice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ScaDeviceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class ScaDevice.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class ScaDevice.", nameof(name)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ScaDevice.", nameof(type)); + + return new ScaDevice(id.Value!, name.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaDevice scaDevice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scaDevice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScaDevice scaDevice, JsonSerializerOptions jsonSerializerOptions) + { + + if (scaDevice.Id != null) + writer.WriteString("id", scaDevice.Id); + + if (scaDevice.Name != null) + writer.WriteString("name", scaDevice.Name); + + var typeRawValue = ScaDeviceTypeValueConverter.ToJsonValue(scaDevice.Type); + writer.WriteString("type", typeRawValue); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaDeviceType.cs b/Adyen/BalancePlatform/Models/ScaDeviceType.cs new file mode 100644 index 000000000..6c11ad2f9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaDeviceType.cs @@ -0,0 +1,190 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Defines ScaDeviceType + /// + public enum ScaDeviceType + { + /// + /// Enum Browser for value: browser + /// + Browser = 1, + + /// + /// Enum Ios for value: ios + /// + Ios = 2, + + /// + /// Enum Android for value: android + /// + Android = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class ScaDeviceTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ScaDeviceType FromString(string value) + { + if (value.Equals("browser")) + return ScaDeviceType.Browser; + + if (value.Equals("ios")) + return ScaDeviceType.Ios; + + if (value.Equals("android")) + return ScaDeviceType.Android; + + throw new NotImplementedException($"Could not convert value to type ScaDeviceType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ScaDeviceType? FromStringOrDefault(string value) + { + if (value.Equals("browser")) + return ScaDeviceType.Browser; + + if (value.Equals("ios")) + return ScaDeviceType.Ios; + + if (value.Equals("android")) + return ScaDeviceType.Android; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ScaDeviceType value) + { + if (value == ScaDeviceType.Browser) + return "browser"; + + if (value == ScaDeviceType.Ios) + return "ios"; + + if (value == ScaDeviceType.Android) + return "android"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ScaDeviceTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ScaDeviceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaDeviceType? result = rawValue == null + ? null + : ScaDeviceTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaDeviceType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaDeviceType scaDeviceType, JsonSerializerOptions options) + { + writer.WriteStringValue(ScaDeviceTypeValueConverter.ToJsonValue(scaDeviceType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ScaDeviceTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a ScaDeviceType from the Json object + /// + /// + /// + /// + /// + public override ScaDeviceType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaDeviceType? result = rawValue == null + ? null + : ScaDeviceTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaDeviceType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaDeviceType? scaDeviceType, JsonSerializerOptions options) + { + writer.WriteStringValue(scaDeviceType.HasValue ? ScaDeviceTypeValueConverter.ToJsonValue(scaDeviceType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaEntity.cs b/Adyen/BalancePlatform/Models/ScaEntity.cs new file mode 100644 index 000000000..2e7ee894d --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaEntity.cs @@ -0,0 +1,205 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ScaEntity. + /// + public partial class ScaEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the entity. + /// type + [JsonConstructor] + public ScaEntity(string id, ScaEntityType type) + { + Id = id; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScaEntity() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("type")] + public ScaEntityType Type { get; set; } + + /// + /// The unique identifier of the entity. + /// + /// The unique identifier of the entity. + /* AH9999Z99Z999999ZZZZ9999Z */ + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScaEntity {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Id (string) maxLength + if (this.Id != null && this.Id.Length > 100) + { + yield return new ValidationResult("Invalid value for Id, length must be less than 100.", new [] { "Id" }); + } + + // Id (string) minLength + if (this.Id != null && this.Id.Length < 0) + { + yield return new ValidationResult("Invalid value for Id, length must be greater than 0.", new [] { "Id" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScaEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScaEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ScaEntityTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class ScaEntity.", nameof(id)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ScaEntity.", nameof(type)); + + return new ScaEntity(id.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaEntity scaEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scaEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScaEntity scaEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (scaEntity.Id != null) + writer.WriteString("id", scaEntity.Id); + + var typeRawValue = ScaEntityTypeValueConverter.ToJsonValue(scaEntity.Type); + writer.WriteString("type", typeRawValue); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaEntityType.cs b/Adyen/BalancePlatform/Models/ScaEntityType.cs new file mode 100644 index 000000000..a09107b23 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaEntityType.cs @@ -0,0 +1,176 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Defines ScaEntityType + /// + public enum ScaEntityType + { + /// + /// Enum AccountHolder for value: accountHolder + /// + AccountHolder = 1, + + /// + /// Enum PaymentInstrument for value: paymentInstrument + /// + PaymentInstrument = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class ScaEntityTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ScaEntityType FromString(string value) + { + if (value.Equals("accountHolder")) + return ScaEntityType.AccountHolder; + + if (value.Equals("paymentInstrument")) + return ScaEntityType.PaymentInstrument; + + throw new NotImplementedException($"Could not convert value to type ScaEntityType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ScaEntityType? FromStringOrDefault(string value) + { + if (value.Equals("accountHolder")) + return ScaEntityType.AccountHolder; + + if (value.Equals("paymentInstrument")) + return ScaEntityType.PaymentInstrument; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ScaEntityType value) + { + if (value == ScaEntityType.AccountHolder) + return "accountHolder"; + + if (value == ScaEntityType.PaymentInstrument) + return "paymentInstrument"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ScaEntityTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ScaEntityType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaEntityType? result = rawValue == null + ? null + : ScaEntityTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaEntityType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaEntityType scaEntityType, JsonSerializerOptions options) + { + writer.WriteStringValue(ScaEntityTypeValueConverter.ToJsonValue(scaEntityType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ScaEntityTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a ScaEntityType from the Json object + /// + /// + /// + /// + /// + public override ScaEntityType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaEntityType? result = rawValue == null + ? null + : ScaEntityTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaEntityType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaEntityType? scaEntityType, JsonSerializerOptions options) + { + writer.WriteStringValue(scaEntityType.HasValue ? ScaEntityTypeValueConverter.ToJsonValue(scaEntityType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaExemption.cs b/Adyen/BalancePlatform/Models/ScaExemption.cs new file mode 100644 index 000000000..b8fdb6dd6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaExemption.cs @@ -0,0 +1,219 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The type of exemption for Strong Customer Authentication (SCA). Possible values: * **lowerLimit**: the newly created limit is lower than the existing limit. * **notRegulated**: the limit is created in a country, region, or industry where it is not mandated by law to use SCA. * **setByPlatform**: you set a limit for one of your user's balance accounts, or for your balance platform. * **initialLimit**: there are no existing transfer limits set on the balance account or balance platform. * **alreadyPerformed**: you are confident about your user's identity and do not need to verify this using SCA. + /// + /// The type of exemption for Strong Customer Authentication (SCA). Possible values: * **lowerLimit**: the newly created limit is lower than the existing limit. * **notRegulated**: the limit is created in a country, region, or industry where it is not mandated by law to use SCA. * **setByPlatform**: you set a limit for one of your user's balance accounts, or for your balance platform. * **initialLimit**: there are no existing transfer limits set on the balance account or balance platform. * **alreadyPerformed**: you are confident about your user's identity and do not need to verify this using SCA. + public enum ScaExemption + { + /// + /// Enum SetByPlatform for value: setByPlatform + /// + SetByPlatform = 1, + + /// + /// Enum InitialLimit for value: initialLimit + /// + InitialLimit = 2, + + /// + /// Enum LowerLimit for value: lowerLimit + /// + LowerLimit = 3, + + /// + /// Enum NotRegulated for value: notRegulated + /// + NotRegulated = 4, + + /// + /// Enum AlreadyPerformed for value: alreadyPerformed + /// + AlreadyPerformed = 5 + } + + /// + /// Converts to and from the JSON value + /// + public static class ScaExemptionValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ScaExemption FromString(string value) + { + if (value.Equals("setByPlatform")) + return ScaExemption.SetByPlatform; + + if (value.Equals("initialLimit")) + return ScaExemption.InitialLimit; + + if (value.Equals("lowerLimit")) + return ScaExemption.LowerLimit; + + if (value.Equals("notRegulated")) + return ScaExemption.NotRegulated; + + if (value.Equals("alreadyPerformed")) + return ScaExemption.AlreadyPerformed; + + throw new NotImplementedException($"Could not convert value to type ScaExemption: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ScaExemption? FromStringOrDefault(string value) + { + if (value.Equals("setByPlatform")) + return ScaExemption.SetByPlatform; + + if (value.Equals("initialLimit")) + return ScaExemption.InitialLimit; + + if (value.Equals("lowerLimit")) + return ScaExemption.LowerLimit; + + if (value.Equals("notRegulated")) + return ScaExemption.NotRegulated; + + if (value.Equals("alreadyPerformed")) + return ScaExemption.AlreadyPerformed; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ScaExemption value) + { + if (value == ScaExemption.SetByPlatform) + return "setByPlatform"; + + if (value == ScaExemption.InitialLimit) + return "initialLimit"; + + if (value == ScaExemption.LowerLimit) + return "lowerLimit"; + + if (value == ScaExemption.NotRegulated) + return "notRegulated"; + + if (value == ScaExemption.AlreadyPerformed) + return "alreadyPerformed"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ScaExemptionJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ScaExemption Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaExemption? result = rawValue == null + ? null + : ScaExemptionValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaExemption to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaExemption scaExemption, JsonSerializerOptions options) + { + writer.WriteStringValue(ScaExemptionValueConverter.ToJsonValue(scaExemption).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ScaExemptionNullableJsonConverter : JsonConverter + { + /// + /// Returns a ScaExemption from the Json object + /// + /// + /// + /// + /// + public override ScaExemption? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaExemption? result = rawValue == null + ? null + : ScaExemptionValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaExemption to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaExemption? scaExemption, JsonSerializerOptions options) + { + writer.WriteStringValue(scaExemption.HasValue ? ScaExemptionValueConverter.ToJsonValue(scaExemption.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaInformation.cs b/Adyen/BalancePlatform/Models/ScaInformation.cs new file mode 100644 index 000000000..879033dba --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaInformation.cs @@ -0,0 +1,200 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ScaInformation. + /// + public partial class ScaInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// status + /// exemption + [JsonConstructor] + public ScaInformation(ScaStatus status, Option exemption = default) + { + Status = status; + _ExemptionOption = exemption; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScaInformation() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("status")] + public ScaStatus Status { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("exemption")] + public ScaExemption? Exemption { get { return this._ExemptionOption; } set { this._ExemptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScaInformation {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Exemption: ").Append(Exemption).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScaInformationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScaInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option exemption = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(ScaStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "exemption": + string? exemptionRawValue = utf8JsonReader.GetString(); + if (exemptionRawValue != null) + exemption = new Option(ScaExemptionValueConverter.FromStringOrDefault(exemptionRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ScaInformation.", nameof(status)); + + return new ScaInformation(status.Value!.Value!, exemption); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaInformation scaInformation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scaInformation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScaInformation scaInformation, JsonSerializerOptions jsonSerializerOptions) + { + + var statusRawValue = ScaStatusValueConverter.ToJsonValue(scaInformation.Status); + writer.WriteString("status", statusRawValue); + + if (scaInformation._ExemptionOption.IsSet) + { + var exemptionRawValue = ScaExemptionValueConverter.ToJsonValue(scaInformation.Exemption!.Value); + writer.WriteString("exemption", exemptionRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/ScaStatus.cs b/Adyen/BalancePlatform/Models/ScaStatus.cs new file mode 100644 index 000000000..cdf9f8f20 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ScaStatus.cs @@ -0,0 +1,191 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The status of Strong Customer Authentication (SCA). Possible values: * **notPerformed**: the requester was unable to successfully authenticate the request using SCA, or has an SCA exemption. * **pending**: the request is pending SCA authentication. * **performed**: the request is successfully authenticated using SCA. + /// + /// The status of Strong Customer Authentication (SCA). Possible values: * **notPerformed**: the requester was unable to successfully authenticate the request using SCA, or has an SCA exemption. * **pending**: the request is pending SCA authentication. * **performed**: the request is successfully authenticated using SCA. + public enum ScaStatus + { + /// + /// Enum NotPerformed for value: notPerformed + /// + NotPerformed = 1, + + /// + /// Enum Pending for value: pending + /// + Pending = 2, + + /// + /// Enum Performed for value: performed + /// + Performed = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class ScaStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ScaStatus FromString(string value) + { + if (value.Equals("notPerformed")) + return ScaStatus.NotPerformed; + + if (value.Equals("pending")) + return ScaStatus.Pending; + + if (value.Equals("performed")) + return ScaStatus.Performed; + + throw new NotImplementedException($"Could not convert value to type ScaStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ScaStatus? FromStringOrDefault(string value) + { + if (value.Equals("notPerformed")) + return ScaStatus.NotPerformed; + + if (value.Equals("pending")) + return ScaStatus.Pending; + + if (value.Equals("performed")) + return ScaStatus.Performed; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ScaStatus value) + { + if (value == ScaStatus.NotPerformed) + return "notPerformed"; + + if (value == ScaStatus.Pending) + return "pending"; + + if (value == ScaStatus.Performed) + return "performed"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ScaStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ScaStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaStatus? result = rawValue == null + ? null + : ScaStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaStatus scaStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(ScaStatusValueConverter.ToJsonValue(scaStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ScaStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a ScaStatus from the Json object + /// + /// + /// + /// + /// + public override ScaStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ScaStatus? result = rawValue == null + ? null + : ScaStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ScaStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScaStatus? scaStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(scaStatus.HasValue ? ScaStatusValueConverter.ToJsonValue(scaStatus.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Scope.cs b/Adyen/BalancePlatform/Models/Scope.cs new file mode 100644 index 000000000..4b03027c7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/Scope.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. + /// + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. + public enum Scope + { + /// + /// Enum PerDay for value: perDay + /// + PerDay = 1, + + /// + /// Enum PerTransaction for value: perTransaction + /// + PerTransaction = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class ScopeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static Scope FromString(string value) + { + if (value.Equals("perDay")) + return Scope.PerDay; + + if (value.Equals("perTransaction")) + return Scope.PerTransaction; + + throw new NotImplementedException($"Could not convert value to type Scope: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static Scope? FromStringOrDefault(string value) + { + if (value.Equals("perDay")) + return Scope.PerDay; + + if (value.Equals("perTransaction")) + return Scope.PerTransaction; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(Scope value) + { + if (value == Scope.PerDay) + return "perDay"; + + if (value == Scope.PerTransaction) + return "perTransaction"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ScopeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override Scope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Scope? result = rawValue == null + ? null + : ScopeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Scope to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Scope scope, JsonSerializerOptions options) + { + writer.WriteStringValue(ScopeValueConverter.ToJsonValue(scope).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ScopeNullableJsonConverter : JsonConverter + { + /// + /// Returns a Scope from the Json object + /// + /// + /// + /// + /// + public override Scope? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Scope? result = rawValue == null + ? null + : ScopeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Scope to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Scope? scope, JsonSerializerOptions options) + { + writer.WriteStringValue(scope.HasValue ? ScopeValueConverter.ToJsonValue(scope.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SearchRegisteredDevicesResponse.cs b/Adyen/BalancePlatform/Models/SearchRegisteredDevicesResponse.cs new file mode 100644 index 000000000..605eda849 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SearchRegisteredDevicesResponse.cs @@ -0,0 +1,251 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SearchRegisteredDevicesResponse. + /// + public partial class SearchRegisteredDevicesResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains a list of registered SCA devices and their corresponding details. + /// The total amount of registered SCA devices that match the query parameters. + /// link + /// The total amount of list pages. + [JsonConstructor] + public SearchRegisteredDevicesResponse(Option?> data = default, Option itemsTotal = default, Option link = default, Option pagesTotal = default) + { + _DataOption = data; + _ItemsTotalOption = itemsTotal; + _LinkOption = link; + _PagesTotalOption = pagesTotal; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SearchRegisteredDevicesResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Contains a list of registered SCA devices and their corresponding details. + /// + /// Contains a list of registered SCA devices and their corresponding details. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ItemsTotalOption { get; private set; } + + /// + /// The total amount of registered SCA devices that match the query parameters. + /// + /// The total amount of registered SCA devices that match the query parameters. + [JsonPropertyName("itemsTotal")] + public int? ItemsTotal { get { return this._ItemsTotalOption; } set { this._ItemsTotalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinkOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("link")] + public Link? Link { get { return this._LinkOption; } set { this._LinkOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PagesTotalOption { get; private set; } + + /// + /// The total amount of list pages. + /// + /// The total amount of list pages. + [JsonPropertyName("pagesTotal")] + public int? PagesTotal { get { return this._PagesTotalOption; } set { this._PagesTotalOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SearchRegisteredDevicesResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" Link: ").Append(Link).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SearchRegisteredDevicesResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SearchRegisteredDevicesResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option itemsTotal = default; + Option link = default; + Option pagesTotal = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "link": + link = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new SearchRegisteredDevicesResponse(data, itemsTotal, link, pagesTotal); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SearchRegisteredDevicesResponse searchRegisteredDevicesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, searchRegisteredDevicesResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SearchRegisteredDevicesResponse searchRegisteredDevicesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (searchRegisteredDevicesResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, searchRegisteredDevicesResponse.Data, jsonSerializerOptions); + } + if (searchRegisteredDevicesResponse._ItemsTotalOption.IsSet) + writer.WriteNumber("itemsTotal", searchRegisteredDevicesResponse._ItemsTotalOption.Value!.Value); + + if (searchRegisteredDevicesResponse._LinkOption.IsSet) + { + writer.WritePropertyName("link"); + JsonSerializer.Serialize(writer, searchRegisteredDevicesResponse.Link, jsonSerializerOptions); + } + if (searchRegisteredDevicesResponse._PagesTotalOption.IsSet) + writer.WriteNumber("pagesTotal", searchRegisteredDevicesResponse._PagesTotalOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SettingType.cs b/Adyen/BalancePlatform/Models/SettingType.cs new file mode 100644 index 000000000..ef117c41d --- /dev/null +++ b/Adyen/BalancePlatform/Models/SettingType.cs @@ -0,0 +1,162 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Defines SettingType + /// + public enum SettingType + { + /// + /// Enum Balance for value: balance + /// + Balance = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class SettingTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static SettingType FromString(string value) + { + if (value.Equals("balance")) + return SettingType.Balance; + + throw new NotImplementedException($"Could not convert value to type SettingType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static SettingType? FromStringOrDefault(string value) + { + if (value.Equals("balance")) + return SettingType.Balance; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(SettingType value) + { + if (value == SettingType.Balance) + return "balance"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class SettingTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override SettingType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SettingType? result = rawValue == null + ? null + : SettingTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SettingType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SettingType settingType, JsonSerializerOptions options) + { + writer.WriteStringValue(SettingTypeValueConverter.ToJsonValue(settingType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class SettingTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a SettingType from the Json object + /// + /// + /// + /// + /// + public override SettingType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SettingType? result = rawValue == null + ? null + : SettingTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SettingType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SettingType? settingType, JsonSerializerOptions options) + { + writer.WriteStringValue(settingType.HasValue ? SettingTypeValueConverter.ToJsonValue(settingType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SourceAccountTypesRestriction.cs b/Adyen/BalancePlatform/Models/SourceAccountTypesRestriction.cs new file mode 100644 index 000000000..eb51a4677 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SourceAccountTypesRestriction.cs @@ -0,0 +1,300 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SourceAccountTypesRestriction. + /// + public partial class SourceAccountTypesRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// The list of source account types to be evaluated. + [JsonConstructor] + public SourceAccountTypesRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SourceAccountTypesRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.BalanceAccount - balanceAccount + /// + public static readonly ValueEnum BalanceAccount = new("balanceAccount"); + + /// + /// ValueEnum.BusinessAccount - businessAccount + /// + public static readonly ValueEnum BusinessAccount = new("businessAccount"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "balanceAccount" => ValueEnum.BalanceAccount, + "businessAccount" => ValueEnum.BusinessAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.BalanceAccount) + return "balanceAccount"; + + if (value == ValueEnum.BusinessAccount) + return "businessAccount"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// The list of source account types to be evaluated. + /// + /// The list of source account types to be evaluated. + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SourceAccountTypesRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SourceAccountTypesRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SourceAccountTypesRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class SourceAccountTypesRestriction.", nameof(operation)); + + return new SourceAccountTypesRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SourceAccountTypesRestriction sourceAccountTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sourceAccountTypesRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SourceAccountTypesRestriction sourceAccountTypesRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (sourceAccountTypesRestriction.Operation != null) + writer.WriteString("operation", sourceAccountTypesRestriction.Operation); + + if (sourceAccountTypesRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, sourceAccountTypesRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/StringMatch.cs b/Adyen/BalancePlatform/Models/StringMatch.cs new file mode 100644 index 000000000..c3ed952e6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/StringMatch.cs @@ -0,0 +1,326 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// StringMatch. + /// + public partial class StringMatch : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of string matching operation. Possible values: **startsWith**, **endsWith**, **isEqualTo**, **contains**, + /// The string to be matched. + [JsonConstructor] + public StringMatch(Option operation = default, Option value = default) + { + _OperationOption = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StringMatch() + { + } + + partial void OnCreated(); + + /// + /// The type of string matching operation. Possible values: **startsWith**, **endsWith**, **isEqualTo**, **contains**, + /// + /// The type of string matching operation. Possible values: **startsWith**, **endsWith**, **isEqualTo**, **contains**, + [JsonConverter(typeof(OperationEnumJsonConverter))] + public class OperationEnum : IEnum + { + /// + /// Returns the value of the OperationEnum. + /// + public string? Value { get; set; } + + /// + /// OperationEnum.Contains - contains + /// + public static readonly OperationEnum Contains = new("contains"); + + /// + /// OperationEnum.EndsWith - endsWith + /// + public static readonly OperationEnum EndsWith = new("endsWith"); + + /// + /// OperationEnum.IsEqualTo - isEqualTo + /// + public static readonly OperationEnum IsEqualTo = new("isEqualTo"); + + /// + /// OperationEnum.StartsWith - startsWith + /// + public static readonly OperationEnum StartsWith = new("startsWith"); + + private OperationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator OperationEnum?(string? value) => value == null ? null : new OperationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(OperationEnum? option) => option?.Value; + + public static bool operator ==(OperationEnum? left, OperationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(OperationEnum? left, OperationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is OperationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static OperationEnum? FromStringOrDefault(string value) + { + return value switch { + "contains" => OperationEnum.Contains, + "endsWith" => OperationEnum.EndsWith, + "isEqualTo" => OperationEnum.IsEqualTo, + "startsWith" => OperationEnum.StartsWith, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(OperationEnum? value) + { + if (value == null) + return null; + + if (value == OperationEnum.Contains) + return "contains"; + + if (value == OperationEnum.EndsWith) + return "endsWith"; + + if (value == OperationEnum.IsEqualTo) + return "isEqualTo"; + + if (value == OperationEnum.StartsWith) + return "startsWith"; + + return null; + } + + /// + /// JsonConverter for writing OperationEnum. + /// + public class OperationEnumJsonConverter : JsonConverter + { + public override OperationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : OperationEnum.FromStringOrDefault(value) ?? new OperationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, OperationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(OperationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OperationOption { get; private set; } + + /// + /// The type of string matching operation. Possible values: **startsWith**, **endsWith**, **isEqualTo**, **contains**, + /// + /// The type of string matching operation. Possible values: **startsWith**, **endsWith**, **isEqualTo**, **contains**, + [JsonPropertyName("operation")] + public OperationEnum? Operation { get { return this._OperationOption; } set { this._OperationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The string to be matched. + /// + /// The string to be matched. + [JsonPropertyName("value")] + public string? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StringMatch {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StringMatchJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StringMatch Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + string? operationRawValue = utf8JsonReader.GetString(); + operation = new Option(StringMatch.OperationEnum.FromStringOrDefault(operationRawValue)); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StringMatch(operation, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StringMatch stringMatch, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, stringMatch, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StringMatch stringMatch, JsonSerializerOptions jsonSerializerOptions) + { + + if (stringMatch._OperationOption.IsSet && stringMatch.Operation != null) + { + string? operationRawValue = StringMatch.OperationEnum.ToJsonValue(stringMatch._OperationOption.Value!.Value); + writer.WriteString("operation", operationRawValue); + } + + if (stringMatch._ValueOption.IsSet) + if (stringMatch.Value != null) + writer.WriteString("value", stringMatch.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SubmitScaAssociationRequest.cs b/Adyen/BalancePlatform/Models/SubmitScaAssociationRequest.cs new file mode 100644 index 000000000..1a6df2fa2 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SubmitScaAssociationRequest.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SubmitScaAssociationRequest. + /// + public partial class SubmitScaAssociationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of entities to be associated. + [JsonConstructor] + public SubmitScaAssociationRequest(List entities) + { + Entities = entities; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubmitScaAssociationRequest() + { + } + + partial void OnCreated(); + + /// + /// The list of entities to be associated. + /// + /// The list of entities to be associated. + [JsonPropertyName("entities")] + public List Entities { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubmitScaAssociationRequest {\n"); + sb.Append(" Entities: ").Append(Entities).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubmitScaAssociationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubmitScaAssociationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> entities = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entities": + entities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!entities.IsSet) + throw new ArgumentException("Property is required for class SubmitScaAssociationRequest.", nameof(entities)); + + return new SubmitScaAssociationRequest(entities.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubmitScaAssociationRequest submitScaAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, submitScaAssociationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubmitScaAssociationRequest submitScaAssociationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("entities"); + JsonSerializer.Serialize(writer, submitScaAssociationRequest.Entities, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SubmitScaAssociationResponse.cs b/Adyen/BalancePlatform/Models/SubmitScaAssociationResponse.cs new file mode 100644 index 000000000..bc7488267 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SubmitScaAssociationResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SubmitScaAssociationResponse. + /// + public partial class SubmitScaAssociationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of associations created to the entities and their statuses. + [JsonConstructor] + public SubmitScaAssociationResponse(List scaAssociations) + { + ScaAssociations = scaAssociations; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubmitScaAssociationResponse() + { + } + + partial void OnCreated(); + + /// + /// List of associations created to the entities and their statuses. + /// + /// List of associations created to the entities and their statuses. + [JsonPropertyName("scaAssociations")] + public List ScaAssociations { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubmitScaAssociationResponse {\n"); + sb.Append(" ScaAssociations: ").Append(ScaAssociations).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubmitScaAssociationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubmitScaAssociationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> scaAssociations = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "scaAssociations": + scaAssociations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!scaAssociations.IsSet) + throw new ArgumentException("Property is required for class SubmitScaAssociationResponse.", nameof(scaAssociations)); + + return new SubmitScaAssociationResponse(scaAssociations.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubmitScaAssociationResponse submitScaAssociationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, submitScaAssociationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubmitScaAssociationResponse submitScaAssociationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("scaAssociations"); + JsonSerializer.Serialize(writer, submitScaAssociationResponse.ScaAssociations, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SweepConfigurationV2.cs b/Adyen/BalancePlatform/Models/SweepConfigurationV2.cs new file mode 100644 index 000000000..535539b5f --- /dev/null +++ b/Adyen/BalancePlatform/Models/SweepConfigurationV2.cs @@ -0,0 +1,1318 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SweepConfigurationV2. + /// + public partial class SweepConfigurationV2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// counterparty + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// The unique identifier of the sweep. + /// schedule + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The reason for disabling the sweep. + /// The human readable reason for disabling the sweep. + /// Your reference for the sweep configuration. + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// sweepAmount + /// targetAmount + /// triggerAmount + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. (default to TypeEnum.Push) + [JsonConstructor] + public SweepConfigurationV2(SweepCounterparty counterparty, string currency, string id, SweepSchedule schedule, Option category = default, Option description = default, Option?> priorities = default, Option reason = default, Option reasonDetail = default, Option reference = default, Option referenceForBeneficiary = default, Option status = default, Option sweepAmount = default, Option targetAmount = default, Option triggerAmount = default, Option type = default) + { + Counterparty = counterparty; + Currency = currency; + Id = id; + Schedule = schedule; + _CategoryOption = category; + _DescriptionOption = description; + _PrioritiesOption = priorities; + _ReasonOption = reason; + _ReasonDetailOption = reasonDetail; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _StatusOption = status; + _SweepAmountOption = sweepAmount; + _TargetAmountOption = targetAmount; + _TriggerAmountOption = triggerAmount; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepConfigurationV2() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "internal" => CategoryEnum.Internal, + "platformPayment" => CategoryEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Pull - pull + /// + public static readonly TypeEnum Pull = new("pull"); + + /// + /// TypeEnum.Push - push + /// + public static readonly TypeEnum Push = new("push"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pull" => TypeEnum.Pull, + "push" => TypeEnum.Push, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Pull) + return "pull"; + + if (value == TypeEnum.Push) + return "push"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public SweepCounterparty Counterparty { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The unique identifier of the sweep. + /// + /// The unique identifier of the sweep. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// . + /// + [JsonPropertyName("schedule")] + public SweepSchedule Schedule { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonDetailOption { get; } + + /// + /// The human readable reason for disabling the sweep. + /// + /// The human readable reason for disabling the sweep. + [JsonPropertyName("reasonDetail")] + public string? ReasonDetail { get { return this._ReasonDetailOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the sweep configuration. + /// + /// Your reference for the sweep configuration. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SweepAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sweepAmount")] + public Amount? SweepAmount { get { return this._SweepAmountOption; } set { this._SweepAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("targetAmount")] + public Amount? TargetAmount { get { return this._TargetAmountOption; } set { this._TargetAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TriggerAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("triggerAmount")] + public Amount? TriggerAmount { get { return this._TriggerAmountOption; } set { this._TriggerAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepConfigurationV2 {\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Schedule: ").Append(Schedule).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" ReasonDetail: ").Append(ReasonDetail).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SweepAmount: ").Append(SweepAmount).Append("\n"); + sb.Append(" TargetAmount: ").Append(TargetAmount).Append("\n"); + sb.Append(" TriggerAmount: ").Append(TriggerAmount).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + // ReferenceForBeneficiary (string) maxLength + if (this.ReferenceForBeneficiary != null && this.ReferenceForBeneficiary.Length > 80) + { + yield return new ValidationResult("Invalid value for ReferenceForBeneficiary, length must be less than 80.", new [] { "ReferenceForBeneficiary" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepConfigurationV2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepConfigurationV2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option counterparty = default; + Option currency = default; + Option id = default; + Option schedule = default; + Option category = default; + Option description = default; + Option?> priorities = default; + Option reason = default; + Option reasonDetail = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option status = default; + Option sweepAmount = default; + Option targetAmount = default; + Option triggerAmount = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "schedule": + schedule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(SweepConfigurationV2.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(SweepConfigurationV2.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reasonDetail": + reasonDetail = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(SweepConfigurationV2.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "sweepAmount": + sweepAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "targetAmount": + targetAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "triggerAmount": + triggerAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SweepConfigurationV2.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!counterparty.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(counterparty)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(currency)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(id)); + + if (!schedule.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(schedule)); + + return new SweepConfigurationV2(counterparty.Value!, currency.Value!, id.Value!, schedule.Value!, category, description, priorities, reason, reasonDetail, reference, referenceForBeneficiary, status, sweepAmount, targetAmount, triggerAmount, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepConfigurationV2 sweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepConfigurationV2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepConfigurationV2 sweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Counterparty, jsonSerializerOptions); + if (sweepConfigurationV2.Currency != null) + writer.WriteString("currency", sweepConfigurationV2.Currency); + + if (sweepConfigurationV2.Id != null) + writer.WriteString("id", sweepConfigurationV2.Id); + + writer.WritePropertyName("schedule"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Schedule, jsonSerializerOptions); + if (sweepConfigurationV2._CategoryOption.IsSet && sweepConfigurationV2.Category != null) + { + string? categoryRawValue = SweepConfigurationV2.CategoryEnum.ToJsonValue(sweepConfigurationV2._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (sweepConfigurationV2._DescriptionOption.IsSet) + if (sweepConfigurationV2.Description != null) + writer.WriteString("description", sweepConfigurationV2.Description); + + if (sweepConfigurationV2._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Priorities, jsonSerializerOptions); + } + if (sweepConfigurationV2._ReasonOption.IsSet && sweepConfigurationV2.Reason != null) + { + string? reasonRawValue = SweepConfigurationV2.ReasonEnum.ToJsonValue(sweepConfigurationV2._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (sweepConfigurationV2._ReasonDetailOption.IsSet) + if (sweepConfigurationV2.ReasonDetail != null) + writer.WriteString("reasonDetail", sweepConfigurationV2.ReasonDetail); + + if (sweepConfigurationV2._ReferenceOption.IsSet) + if (sweepConfigurationV2.Reference != null) + writer.WriteString("reference", sweepConfigurationV2.Reference); + + if (sweepConfigurationV2._ReferenceForBeneficiaryOption.IsSet) + if (sweepConfigurationV2.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", sweepConfigurationV2.ReferenceForBeneficiary); + + if (sweepConfigurationV2._StatusOption.IsSet && sweepConfigurationV2.Status != null) + { + string? statusRawValue = SweepConfigurationV2.StatusEnum.ToJsonValue(sweepConfigurationV2._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (sweepConfigurationV2._SweepAmountOption.IsSet) + { + writer.WritePropertyName("sweepAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.SweepAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TargetAmountOption.IsSet) + { + writer.WritePropertyName("targetAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.TargetAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TriggerAmountOption.IsSet) + { + writer.WritePropertyName("triggerAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.TriggerAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TypeOption.IsSet && sweepConfigurationV2.Type != null) + { + string? typeRawValue = SweepConfigurationV2.TypeEnum.ToJsonValue(sweepConfigurationV2._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/SweepCounterparty.cs b/Adyen/BalancePlatform/Models/SweepCounterparty.cs new file mode 100644 index 000000000..5bcadea38 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SweepCounterparty.cs @@ -0,0 +1,227 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SweepCounterparty. + /// + public partial class SweepCounterparty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + [JsonConstructor] + public SweepCounterparty(Option balanceAccountId = default, Option merchantAccount = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _MerchantAccountOption = merchantAccount; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepCounterparty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + /// + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + /// + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepCounterparty {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepCounterpartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepCounterparty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option merchantAccount = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SweepCounterparty(balanceAccountId, merchantAccount, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepCounterparty sweepCounterparty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepCounterparty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepCounterparty sweepCounterparty, JsonSerializerOptions jsonSerializerOptions) + { + + if (sweepCounterparty._BalanceAccountIdOption.IsSet) + if (sweepCounterparty.BalanceAccountId != null) + writer.WriteString("balanceAccountId", sweepCounterparty.BalanceAccountId); + + if (sweepCounterparty._MerchantAccountOption.IsSet) + if (sweepCounterparty.MerchantAccount != null) + writer.WriteString("merchantAccount", sweepCounterparty.MerchantAccount); + + if (sweepCounterparty._TransferInstrumentIdOption.IsSet) + if (sweepCounterparty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", sweepCounterparty.TransferInstrumentId); + } + } +} diff --git a/Adyen/BalancePlatform/Models/SweepSchedule.cs b/Adyen/BalancePlatform/Models/SweepSchedule.cs new file mode 100644 index 000000000..fe2f32ac4 --- /dev/null +++ b/Adyen/BalancePlatform/Models/SweepSchedule.cs @@ -0,0 +1,330 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// SweepSchedule. + /// + public partial class SweepSchedule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: **&ast;**, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + [JsonConstructor] + public SweepSchedule(TypeEnum type, Option cronExpression = default) + { + Type = type; + _CronExpressionOption = cronExpression; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepSchedule() + { + } + + partial void OnCreated(); + + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Daily - daily + /// + public static readonly TypeEnum Daily = new("daily"); + + /// + /// TypeEnum.Weekly - weekly + /// + public static readonly TypeEnum Weekly = new("weekly"); + + /// + /// TypeEnum.Monthly - monthly + /// + public static readonly TypeEnum Monthly = new("monthly"); + + /// + /// TypeEnum.Balance - balance + /// + public static readonly TypeEnum Balance = new("balance"); + + /// + /// TypeEnum.Cron - cron + /// + public static readonly TypeEnum Cron = new("cron"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => TypeEnum.Daily, + "weekly" => TypeEnum.Weekly, + "monthly" => TypeEnum.Monthly, + "balance" => TypeEnum.Balance, + "cron" => TypeEnum.Cron, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Daily) + return "daily"; + + if (value == TypeEnum.Weekly) + return "weekly"; + + if (value == TypeEnum.Monthly) + return "monthly"; + + if (value == TypeEnum.Balance) + return "balance"; + + if (value == TypeEnum.Cron) + return "cron"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CronExpressionOption { get; private set; } + + /// + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: **&ast;**, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + /// + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: *****, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + [JsonPropertyName("cronExpression")] + public string? CronExpression { get { return this._CronExpressionOption; } set { this._CronExpressionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepSchedule {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CronExpression: ").Append(CronExpression).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepScheduleJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepSchedule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option cronExpression = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SweepSchedule.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "cronExpression": + cronExpression = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SweepSchedule.", nameof(type)); + + return new SweepSchedule(type.Value!.Value!, cronExpression); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepSchedule sweepSchedule, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepSchedule, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepSchedule sweepSchedule, JsonSerializerOptions jsonSerializerOptions) + { + + if (sweepSchedule.Type != null) + { + string? typeRawValue = SweepSchedule.TypeEnum.ToJsonValue(sweepSchedule.Type); + writer.WriteString("type", typeRawValue); + } + + if (sweepSchedule._CronExpressionOption.IsSet) + if (sweepSchedule.CronExpression != null) + writer.WriteString("cronExpression", sweepSchedule.CronExpression); + } + } +} diff --git a/Adyen/BalancePlatform/Models/Target.cs b/Adyen/BalancePlatform/Models/Target.cs new file mode 100644 index 000000000..f1f33edbe --- /dev/null +++ b/Adyen/BalancePlatform/Models/Target.cs @@ -0,0 +1,313 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// Target. + /// + public partial class Target : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonConstructor] + public Target(string id, TypeEnum type) + { + Id = id; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Target() + { + } + + partial void OnCreated(); + + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalanceAccount - balanceAccount + /// + public static readonly TypeEnum BalanceAccount = new("balanceAccount"); + + /// + /// TypeEnum.AccountHolder - accountHolder + /// + public static readonly TypeEnum AccountHolder = new("accountHolder"); + + /// + /// TypeEnum.BalancePlatform - balancePlatform + /// + public static readonly TypeEnum BalancePlatform = new("balancePlatform"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balanceAccount" => TypeEnum.BalanceAccount, + "accountHolder" => TypeEnum.AccountHolder, + "balancePlatform" => TypeEnum.BalancePlatform, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalanceAccount) + return "balanceAccount"; + + if (value == TypeEnum.AccountHolder) + return "accountHolder"; + + if (value == TypeEnum.BalancePlatform) + return "balancePlatform"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Target {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Id (string) minLength + if (this.Id != null && this.Id.Length < 1) + { + yield return new ValidationResult("Invalid value for Id, length must be greater than 1.", new [] { "Id" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TargetJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Target Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Target.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Target.", nameof(id)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Target.", nameof(type)); + + return new Target(id.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Target target, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, target, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Target target, JsonSerializerOptions jsonSerializerOptions) + { + + if (target.Id != null) + writer.WriteString("id", target.Id); + + if (target.Type != null) + { + string? typeRawValue = Target.TypeEnum.ToJsonValue(target.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TargetUpdate.cs b/Adyen/BalancePlatform/Models/TargetUpdate.cs new file mode 100644 index 000000000..a82e81acd --- /dev/null +++ b/Adyen/BalancePlatform/Models/TargetUpdate.cs @@ -0,0 +1,323 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TargetUpdate. + /// + public partial class TargetUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonConstructor] + public TargetUpdate(Option id = default, Option type = default) + { + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TargetUpdate() + { + } + + partial void OnCreated(); + + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalanceAccount - balanceAccount + /// + public static readonly TypeEnum BalanceAccount = new("balanceAccount"); + + /// + /// TypeEnum.AccountHolder - accountHolder + /// + public static readonly TypeEnum AccountHolder = new("accountHolder"); + + /// + /// TypeEnum.BalancePlatform - balancePlatform + /// + public static readonly TypeEnum BalancePlatform = new("balancePlatform"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balanceAccount" => TypeEnum.BalanceAccount, + "accountHolder" => TypeEnum.AccountHolder, + "balancePlatform" => TypeEnum.BalancePlatform, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalanceAccount) + return "balanceAccount"; + + if (value == TypeEnum.AccountHolder) + return "accountHolder"; + + if (value == TypeEnum.BalancePlatform) + return "balancePlatform"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + /// + /// The resource for which you want to receive notifications. Possible values: * **balancePlatform**: receive notifications about balance changes in your entire balance platform. * **accountHolder**: receive notifications about balance changes of a specific user. * **balanceAccount**: receive notifications about balance changes in a specific balance account. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + /// + /// The unique identifier of the `target.type`. This can be the ID of your: * balance platform * account holder * account holder's balance account + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TargetUpdate {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Id (string) minLength + if (this.Id != null && this.Id.Length < 1) + { + yield return new ValidationResult("Invalid value for Id, length must be greater than 1.", new [] { "Id" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TargetUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TargetUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TargetUpdate.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new TargetUpdate(id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TargetUpdate targetUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, targetUpdate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TargetUpdate targetUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + if (targetUpdate._IdOption.IsSet) + if (targetUpdate.Id != null) + writer.WriteString("id", targetUpdate.Id); + + if (targetUpdate._TypeOption.IsSet && targetUpdate.Type != null) + { + string? typeRawValue = TargetUpdate.TypeEnum.ToJsonValue(targetUpdate._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/ThresholdRepayment.cs b/Adyen/BalancePlatform/Models/ThresholdRepayment.cs new file mode 100644 index 000000000..d6c6812e2 --- /dev/null +++ b/Adyen/BalancePlatform/Models/ThresholdRepayment.cs @@ -0,0 +1,170 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// ThresholdRepayment. + /// + public partial class ThresholdRepayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public ThresholdRepayment(Amount amount) + { + Amount = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThresholdRepayment() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThresholdRepayment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThresholdRepaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThresholdRepayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class ThresholdRepayment.", nameof(amount)); + + return new ThresholdRepayment(amount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThresholdRepayment thresholdRepayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, thresholdRepayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThresholdRepayment thresholdRepayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, thresholdRepayment.Amount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/TimeOfDay.cs b/Adyen/BalancePlatform/Models/TimeOfDay.cs new file mode 100644 index 000000000..a67793534 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TimeOfDay.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TimeOfDay. + /// + public partial class TimeOfDay : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The end time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + /// The start time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + [JsonConstructor] + public TimeOfDay(Option endTime = default, Option startTime = default) + { + _EndTimeOption = endTime; + _StartTimeOption = startTime; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TimeOfDay() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndTimeOption { get; private set; } + + /// + /// The end time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + /// + /// The end time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + [JsonPropertyName("endTime")] + public string? EndTime { get { return this._EndTimeOption; } set { this._EndTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartTimeOption { get; private set; } + + /// + /// The start time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + /// + /// The start time in a time-only ISO-8601 extended offset format. For example: **08:00:00+02:00**, **22:30:00-03:00**. + [JsonPropertyName("startTime")] + public string? StartTime { get { return this._StartTimeOption; } set { this._StartTimeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TimeOfDay {\n"); + sb.Append(" EndTime: ").Append(EndTime).Append("\n"); + sb.Append(" StartTime: ").Append(StartTime).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TimeOfDayJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TimeOfDay Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option endTime = default; + Option startTime = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "endTime": + endTime = new Option(utf8JsonReader.GetString()!); + break; + case "startTime": + startTime = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TimeOfDay(endTime, startTime); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TimeOfDay timeOfDay, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, timeOfDay, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TimeOfDay timeOfDay, JsonSerializerOptions jsonSerializerOptions) + { + + if (timeOfDay._EndTimeOption.IsSet) + if (timeOfDay.EndTime != null) + writer.WriteString("endTime", timeOfDay.EndTime); + + if (timeOfDay._StartTimeOption.IsSet) + if (timeOfDay.StartTime != null) + writer.WriteString("startTime", timeOfDay.StartTime); + } + } +} diff --git a/Adyen/BalancePlatform/Models/TimeOfDayRestriction.cs b/Adyen/BalancePlatform/Models/TimeOfDayRestriction.cs new file mode 100644 index 000000000..25e472b2b --- /dev/null +++ b/Adyen/BalancePlatform/Models/TimeOfDayRestriction.cs @@ -0,0 +1,197 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TimeOfDayRestriction. + /// + public partial class TimeOfDayRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public TimeOfDayRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TimeOfDayRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public TimeOfDay? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TimeOfDayRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TimeOfDayRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TimeOfDayRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class TimeOfDayRestriction.", nameof(operation)); + + return new TimeOfDayRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TimeOfDayRestriction timeOfDayRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, timeOfDayRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TimeOfDayRestriction timeOfDayRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (timeOfDayRestriction.Operation != null) + writer.WriteString("operation", timeOfDayRestriction.Operation); + + if (timeOfDayRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, timeOfDayRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TokenRequestorsRestriction.cs b/Adyen/BalancePlatform/Models/TokenRequestorsRestriction.cs new file mode 100644 index 000000000..97f1b1b2c --- /dev/null +++ b/Adyen/BalancePlatform/Models/TokenRequestorsRestriction.cs @@ -0,0 +1,197 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TokenRequestorsRestriction. + /// + public partial class TokenRequestorsRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public TokenRequestorsRestriction(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenRequestorsRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenRequestorsRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenRequestorsRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenRequestorsRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class TokenRequestorsRestriction.", nameof(operation)); + + return new TokenRequestorsRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenRequestorsRestriction tokenRequestorsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenRequestorsRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenRequestorsRestriction tokenRequestorsRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (tokenRequestorsRestriction.Operation != null) + writer.WriteString("operation", tokenRequestorsRestriction.Operation); + + if (tokenRequestorsRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, tokenRequestorsRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TotalAmountRestriction.cs b/Adyen/BalancePlatform/Models/TotalAmountRestriction.cs new file mode 100644 index 000000000..c61e18232 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TotalAmountRestriction.cs @@ -0,0 +1,197 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TotalAmountRestriction. + /// + public partial class TotalAmountRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public TotalAmountRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TotalAmountRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public Amount? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TotalAmountRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TotalAmountRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TotalAmountRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class TotalAmountRestriction.", nameof(operation)); + + return new TotalAmountRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TotalAmountRestriction totalAmountRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, totalAmountRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TotalAmountRestriction totalAmountRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (totalAmountRestriction.Operation != null) + writer.WriteString("operation", totalAmountRestriction.Operation); + + if (totalAmountRestriction._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, totalAmountRestriction.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRule.cs b/Adyen/BalancePlatform/Models/TransactionRule.cs new file mode 100644 index 000000000..84c89ac36 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRule.cs @@ -0,0 +1,955 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRule. + /// + public partial class TransactionRule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your description for the transaction rule. + /// entityKey + /// interval + /// Your reference for the transaction rule. + /// ruleRestrictions + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + /// The unique identifier of the transaction rule. + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonConstructor] + public TransactionRule(string description, TransactionRuleEntityKey entityKey, TransactionRuleInterval interval, string reference, TransactionRuleRestrictions ruleRestrictions, TypeEnum type, Option aggregationLevel = default, Option endDate = default, Option id = default, Option outcomeType = default, Option requestType = default, Option score = default, Option startDate = default, Option status = default) + { + Description = description; + EntityKey = entityKey; + Interval = interval; + Reference = reference; + RuleRestrictions = ruleRestrictions; + Type = type; + _AggregationLevelOption = aggregationLevel; + _EndDateOption = endDate; + _IdOption = id; + _OutcomeTypeOption = outcomeType; + _RequestTypeOption = requestType; + _ScoreOption = score; + _StartDateOption = startDate; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRule() + { + } + + partial void OnCreated(); + + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AllowList - allowList + /// + public static readonly TypeEnum AllowList = new("allowList"); + + /// + /// TypeEnum.BlockList - blockList + /// + public static readonly TypeEnum BlockList = new("blockList"); + + /// + /// TypeEnum.MaxUsage - maxUsage + /// + public static readonly TypeEnum MaxUsage = new("maxUsage"); + + /// + /// TypeEnum.Velocity - velocity + /// + public static readonly TypeEnum Velocity = new("velocity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "allowList" => TypeEnum.AllowList, + "blockList" => TypeEnum.BlockList, + "maxUsage" => TypeEnum.MaxUsage, + "velocity" => TypeEnum.Velocity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AllowList) + return "allowList"; + + if (value == TypeEnum.BlockList) + return "blockList"; + + if (value == TypeEnum.MaxUsage) + return "maxUsage"; + + if (value == TypeEnum.Velocity) + return "velocity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + [JsonConverter(typeof(OutcomeTypeEnumJsonConverter))] + public class OutcomeTypeEnum : IEnum + { + /// + /// Returns the value of the OutcomeTypeEnum. + /// + public string? Value { get; set; } + + /// + /// OutcomeTypeEnum.EnforceSCA - enforceSCA + /// + public static readonly OutcomeTypeEnum EnforceSCA = new("enforceSCA"); + + /// + /// OutcomeTypeEnum.HardBlock - hardBlock + /// + public static readonly OutcomeTypeEnum HardBlock = new("hardBlock"); + + /// + /// OutcomeTypeEnum.ScoreBased - scoreBased + /// + public static readonly OutcomeTypeEnum ScoreBased = new("scoreBased"); + + /// + /// OutcomeTypeEnum.TimedBlock - timedBlock + /// + public static readonly OutcomeTypeEnum TimedBlock = new("timedBlock"); + + private OutcomeTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator OutcomeTypeEnum?(string? value) => value == null ? null : new OutcomeTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(OutcomeTypeEnum? option) => option?.Value; + + public static bool operator ==(OutcomeTypeEnum? left, OutcomeTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(OutcomeTypeEnum? left, OutcomeTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is OutcomeTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static OutcomeTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "enforceSCA" => OutcomeTypeEnum.EnforceSCA, + "hardBlock" => OutcomeTypeEnum.HardBlock, + "scoreBased" => OutcomeTypeEnum.ScoreBased, + "timedBlock" => OutcomeTypeEnum.TimedBlock, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(OutcomeTypeEnum? value) + { + if (value == null) + return null; + + if (value == OutcomeTypeEnum.EnforceSCA) + return "enforceSCA"; + + if (value == OutcomeTypeEnum.HardBlock) + return "hardBlock"; + + if (value == OutcomeTypeEnum.ScoreBased) + return "scoreBased"; + + if (value == OutcomeTypeEnum.TimedBlock) + return "timedBlock"; + + return null; + } + + /// + /// JsonConverter for writing OutcomeTypeEnum. + /// + public class OutcomeTypeEnumJsonConverter : JsonConverter + { + public override OutcomeTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : OutcomeTypeEnum.FromStringOrDefault(value) ?? new OutcomeTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, OutcomeTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(OutcomeTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutcomeTypeOption { get; private set; } + + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + [JsonPropertyName("outcomeType")] + public OutcomeTypeEnum? OutcomeType { get { return this._OutcomeTypeOption; } set { this._OutcomeTypeOption = new(value); } } + + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + [JsonConverter(typeof(RequestTypeEnumJsonConverter))] + public class RequestTypeEnum : IEnum + { + /// + /// Returns the value of the RequestTypeEnum. + /// + public string? Value { get; set; } + + /// + /// RequestTypeEnum.Authentication - authentication + /// + public static readonly RequestTypeEnum Authentication = new("authentication"); + + /// + /// RequestTypeEnum.Authorization - authorization + /// + public static readonly RequestTypeEnum Authorization = new("authorization"); + + /// + /// RequestTypeEnum.BankTransfer - bankTransfer + /// + public static readonly RequestTypeEnum BankTransfer = new("bankTransfer"); + + /// + /// RequestTypeEnum.Tokenization - tokenization + /// + public static readonly RequestTypeEnum Tokenization = new("tokenization"); + + private RequestTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestTypeEnum?(string? value) => value == null ? null : new RequestTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestTypeEnum? option) => option?.Value; + + public static bool operator ==(RequestTypeEnum? left, RequestTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestTypeEnum? left, RequestTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "authentication" => RequestTypeEnum.Authentication, + "authorization" => RequestTypeEnum.Authorization, + "bankTransfer" => RequestTypeEnum.BankTransfer, + "tokenization" => RequestTypeEnum.Tokenization, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestTypeEnum? value) + { + if (value == null) + return null; + + if (value == RequestTypeEnum.Authentication) + return "authentication"; + + if (value == RequestTypeEnum.Authorization) + return "authorization"; + + if (value == RequestTypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == RequestTypeEnum.Tokenization) + return "tokenization"; + + return null; + } + + /// + /// JsonConverter for writing RequestTypeEnum. + /// + public class RequestTypeEnumJsonConverter : JsonConverter + { + public override RequestTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestTypeEnum.FromStringOrDefault(value) ?? new RequestTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestTypeOption { get; private set; } + + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + [JsonPropertyName("requestType")] + public RequestTypeEnum? RequestType { get { return this._RequestTypeOption; } set { this._RequestTypeOption = new(value); } } + + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Your description for the transaction rule. + /// + /// Your description for the transaction rule. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// . + /// + [JsonPropertyName("entityKey")] + public TransactionRuleEntityKey EntityKey { get; set; } + + /// + /// . + /// + [JsonPropertyName("interval")] + public TransactionRuleInterval Interval { get; set; } + + /// + /// Your reference for the transaction rule. + /// + /// Your reference for the transaction rule. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// . + /// + [JsonPropertyName("ruleRestrictions")] + public TransactionRuleRestrictions RuleRestrictions { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AggregationLevelOption { get; private set; } + + /// + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + /// + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + [JsonPropertyName("aggregationLevel")] + public string? AggregationLevel { get { return this._AggregationLevelOption; } set { this._AggregationLevelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndDateOption { get; private set; } + + /// + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + /// + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + [JsonPropertyName("endDate")] + public string? EndDate { get { return this._EndDateOption; } set { this._EndDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the transaction rule. + /// + /// The unique identifier of the transaction rule. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + /// + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartDateOption { get; private set; } + + /// + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + /// + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + [JsonPropertyName("startDate")] + public string? StartDate { get { return this._StartDateOption; } set { this._StartDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRule {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EntityKey: ").Append(EntityKey).Append("\n"); + sb.Append(" Interval: ").Append(Interval).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" RuleRestrictions: ").Append(RuleRestrictions).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AggregationLevel: ").Append(AggregationLevel).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" OutcomeType: ").Append(OutcomeType).Append("\n"); + sb.Append(" RequestType: ").Append(RequestType).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option entityKey = default; + Option interval = default; + Option reference = default; + Option ruleRestrictions = default; + Option type = default; + Option aggregationLevel = default; + Option endDate = default; + Option id = default; + Option outcomeType = default; + Option requestType = default; + Option score = default; + Option startDate = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "entityKey": + entityKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interval": + interval = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "ruleRestrictions": + ruleRestrictions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransactionRule.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "aggregationLevel": + aggregationLevel = new Option(utf8JsonReader.GetString()!); + break; + case "endDate": + endDate = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "outcomeType": + string? outcomeTypeRawValue = utf8JsonReader.GetString(); + outcomeType = new Option(TransactionRule.OutcomeTypeEnum.FromStringOrDefault(outcomeTypeRawValue)); + break; + case "requestType": + string? requestTypeRawValue = utf8JsonReader.GetString(); + requestType = new Option(TransactionRule.RequestTypeEnum.FromStringOrDefault(requestTypeRawValue)); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "startDate": + startDate = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransactionRule.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!description.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(description)); + + if (!entityKey.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(entityKey)); + + if (!interval.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(interval)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(reference)); + + if (!ruleRestrictions.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(ruleRestrictions)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransactionRule.", nameof(type)); + + return new TransactionRule(description.Value!, entityKey.Value!, interval.Value!, reference.Value!, ruleRestrictions.Value!, type.Value!.Value!, aggregationLevel, endDate, id, outcomeType, requestType, score, startDate, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRule transactionRule, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRule, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRule transactionRule, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRule.Description != null) + writer.WriteString("description", transactionRule.Description); + + writer.WritePropertyName("entityKey"); + JsonSerializer.Serialize(writer, transactionRule.EntityKey, jsonSerializerOptions); + writer.WritePropertyName("interval"); + JsonSerializer.Serialize(writer, transactionRule.Interval, jsonSerializerOptions); + if (transactionRule.Reference != null) + writer.WriteString("reference", transactionRule.Reference); + + writer.WritePropertyName("ruleRestrictions"); + JsonSerializer.Serialize(writer, transactionRule.RuleRestrictions, jsonSerializerOptions); + if (transactionRule.Type != null) + { + string? typeRawValue = TransactionRule.TypeEnum.ToJsonValue(transactionRule.Type); + writer.WriteString("type", typeRawValue); + } + + if (transactionRule._AggregationLevelOption.IsSet) + if (transactionRule.AggregationLevel != null) + writer.WriteString("aggregationLevel", transactionRule.AggregationLevel); + + if (transactionRule._EndDateOption.IsSet) + if (transactionRule.EndDate != null) + writer.WriteString("endDate", transactionRule.EndDate); + + if (transactionRule._IdOption.IsSet) + if (transactionRule.Id != null) + writer.WriteString("id", transactionRule.Id); + + if (transactionRule._OutcomeTypeOption.IsSet && transactionRule.OutcomeType != null) + { + string? outcomeTypeRawValue = TransactionRule.OutcomeTypeEnum.ToJsonValue(transactionRule._OutcomeTypeOption.Value!.Value); + writer.WriteString("outcomeType", outcomeTypeRawValue); + } + + if (transactionRule._RequestTypeOption.IsSet && transactionRule.RequestType != null) + { + string? requestTypeRawValue = TransactionRule.RequestTypeEnum.ToJsonValue(transactionRule._RequestTypeOption.Value!.Value); + writer.WriteString("requestType", requestTypeRawValue); + } + + if (transactionRule._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRule._ScoreOption.Value!.Value); + + if (transactionRule._StartDateOption.IsSet) + if (transactionRule.StartDate != null) + writer.WriteString("startDate", transactionRule.StartDate); + + if (transactionRule._StatusOption.IsSet && transactionRule.Status != null) + { + string? statusRawValue = TransactionRule.StatusEnum.ToJsonValue(transactionRule._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRuleEntityKey.cs b/Adyen/BalancePlatform/Models/TransactionRuleEntityKey.cs new file mode 100644 index 000000000..255725fdd --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRuleEntityKey.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRuleEntityKey. + /// + public partial class TransactionRuleEntityKey : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource. + /// The type of resource. Possible values: **balancePlatform**, **paymentInstrumentGroup**, **accountHolder**, **balanceAccount**, or **paymentInstrument**. + [JsonConstructor] + public TransactionRuleEntityKey(Option entityReference = default, Option entityType = default) + { + _EntityReferenceOption = entityReference; + _EntityTypeOption = entityType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleEntityKey() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityReferenceOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("entityReference")] + public string? EntityReference { get { return this._EntityReferenceOption; } set { this._EntityReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityTypeOption { get; private set; } + + /// + /// The type of resource. Possible values: **balancePlatform**, **paymentInstrumentGroup**, **accountHolder**, **balanceAccount**, or **paymentInstrument**. + /// + /// The type of resource. Possible values: **balancePlatform**, **paymentInstrumentGroup**, **accountHolder**, **balanceAccount**, or **paymentInstrument**. + [JsonPropertyName("entityType")] + public string? EntityType { get { return this._EntityTypeOption; } set { this._EntityTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleEntityKey {\n"); + sb.Append(" EntityReference: ").Append(EntityReference).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleEntityKeyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleEntityKey Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entityReference = default; + Option entityType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entityReference": + entityReference = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + entityType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransactionRuleEntityKey(entityReference, entityType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleEntityKey transactionRuleEntityKey, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleEntityKey, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleEntityKey transactionRuleEntityKey, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleEntityKey._EntityReferenceOption.IsSet) + if (transactionRuleEntityKey.EntityReference != null) + writer.WriteString("entityReference", transactionRuleEntityKey.EntityReference); + + if (transactionRuleEntityKey._EntityTypeOption.IsSet) + if (transactionRuleEntityKey.EntityType != null) + writer.WriteString("entityType", transactionRuleEntityKey.EntityType); + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRuleInfo.cs b/Adyen/BalancePlatform/Models/TransactionRuleInfo.cs new file mode 100644 index 000000000..a6f65f22a --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRuleInfo.cs @@ -0,0 +1,930 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRuleInfo. + /// + public partial class TransactionRuleInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your description for the transaction rule. + /// entityKey + /// interval + /// Your reference for the transaction rule. + /// ruleRestrictions + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonConstructor] + public TransactionRuleInfo(string description, TransactionRuleEntityKey entityKey, TransactionRuleInterval interval, string reference, TransactionRuleRestrictions ruleRestrictions, TypeEnum type, Option aggregationLevel = default, Option endDate = default, Option outcomeType = default, Option requestType = default, Option score = default, Option startDate = default, Option status = default) + { + Description = description; + EntityKey = entityKey; + Interval = interval; + Reference = reference; + RuleRestrictions = ruleRestrictions; + Type = type; + _AggregationLevelOption = aggregationLevel; + _EndDateOption = endDate; + _OutcomeTypeOption = outcomeType; + _RequestTypeOption = requestType; + _ScoreOption = score; + _StartDateOption = startDate; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleInfo() + { + } + + partial void OnCreated(); + + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AllowList - allowList + /// + public static readonly TypeEnum AllowList = new("allowList"); + + /// + /// TypeEnum.BlockList - blockList + /// + public static readonly TypeEnum BlockList = new("blockList"); + + /// + /// TypeEnum.MaxUsage - maxUsage + /// + public static readonly TypeEnum MaxUsage = new("maxUsage"); + + /// + /// TypeEnum.Velocity - velocity + /// + public static readonly TypeEnum Velocity = new("velocity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "allowList" => TypeEnum.AllowList, + "blockList" => TypeEnum.BlockList, + "maxUsage" => TypeEnum.MaxUsage, + "velocity" => TypeEnum.Velocity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AllowList) + return "allowList"; + + if (value == TypeEnum.BlockList) + return "blockList"; + + if (value == TypeEnum.MaxUsage) + return "maxUsage"; + + if (value == TypeEnum.Velocity) + return "velocity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + /// + /// The [type of rule](https://docs.adyen.com/issuing/transaction-rules#rule-types), which defines if a rule blocks transactions based on individual characteristics or accumulates data. Possible values: * **blockList**: decline a transaction when the conditions are met. * **maxUsage**: add the amount or number of transactions for the lifetime of a payment instrument, and then decline a transaction when the specified limits are met. * **velocity**: add the amount or number of transactions based on a specified time interval, and then decline a transaction when the specified limits are met. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + [JsonConverter(typeof(OutcomeTypeEnumJsonConverter))] + public class OutcomeTypeEnum : IEnum + { + /// + /// Returns the value of the OutcomeTypeEnum. + /// + public string? Value { get; set; } + + /// + /// OutcomeTypeEnum.EnforceSCA - enforceSCA + /// + public static readonly OutcomeTypeEnum EnforceSCA = new("enforceSCA"); + + /// + /// OutcomeTypeEnum.HardBlock - hardBlock + /// + public static readonly OutcomeTypeEnum HardBlock = new("hardBlock"); + + /// + /// OutcomeTypeEnum.ScoreBased - scoreBased + /// + public static readonly OutcomeTypeEnum ScoreBased = new("scoreBased"); + + /// + /// OutcomeTypeEnum.TimedBlock - timedBlock + /// + public static readonly OutcomeTypeEnum TimedBlock = new("timedBlock"); + + private OutcomeTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator OutcomeTypeEnum?(string? value) => value == null ? null : new OutcomeTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(OutcomeTypeEnum? option) => option?.Value; + + public static bool operator ==(OutcomeTypeEnum? left, OutcomeTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(OutcomeTypeEnum? left, OutcomeTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is OutcomeTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static OutcomeTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "enforceSCA" => OutcomeTypeEnum.EnforceSCA, + "hardBlock" => OutcomeTypeEnum.HardBlock, + "scoreBased" => OutcomeTypeEnum.ScoreBased, + "timedBlock" => OutcomeTypeEnum.TimedBlock, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(OutcomeTypeEnum? value) + { + if (value == null) + return null; + + if (value == OutcomeTypeEnum.EnforceSCA) + return "enforceSCA"; + + if (value == OutcomeTypeEnum.HardBlock) + return "hardBlock"; + + if (value == OutcomeTypeEnum.ScoreBased) + return "scoreBased"; + + if (value == OutcomeTypeEnum.TimedBlock) + return "timedBlock"; + + return null; + } + + /// + /// JsonConverter for writing OutcomeTypeEnum. + /// + public class OutcomeTypeEnumJsonConverter : JsonConverter + { + public override OutcomeTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : OutcomeTypeEnum.FromStringOrDefault(value) ?? new OutcomeTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, OutcomeTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(OutcomeTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutcomeTypeOption { get; private set; } + + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + /// + /// The [outcome](https://docs.adyen.com/issuing/transaction-rules#outcome) that will be applied when a transaction meets the conditions of the rule. Possible values: * **hardBlock** (default): the transaction is declined. * **scoreBased**: the transaction is assigned the `score` you specified. Adyen calculates the total score and if it exceeds 100, the transaction is declined. This value is not allowed when `requestType` is **bankTransfer**. * **enforceSCA**: your user is prompted to verify their identity using [3D Secure authentication](https://docs.adyen.com/issuing/3d-secure/). If the authentication fails or times out, the transaction is declined. This value is only allowed when `requestType` is **authentication**. + [JsonPropertyName("outcomeType")] + public OutcomeTypeEnum? OutcomeType { get { return this._OutcomeTypeOption; } set { this._OutcomeTypeOption = new(value); } } + + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + [JsonConverter(typeof(RequestTypeEnumJsonConverter))] + public class RequestTypeEnum : IEnum + { + /// + /// Returns the value of the RequestTypeEnum. + /// + public string? Value { get; set; } + + /// + /// RequestTypeEnum.Authentication - authentication + /// + public static readonly RequestTypeEnum Authentication = new("authentication"); + + /// + /// RequestTypeEnum.Authorization - authorization + /// + public static readonly RequestTypeEnum Authorization = new("authorization"); + + /// + /// RequestTypeEnum.BankTransfer - bankTransfer + /// + public static readonly RequestTypeEnum BankTransfer = new("bankTransfer"); + + /// + /// RequestTypeEnum.Tokenization - tokenization + /// + public static readonly RequestTypeEnum Tokenization = new("tokenization"); + + private RequestTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestTypeEnum?(string? value) => value == null ? null : new RequestTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestTypeEnum? option) => option?.Value; + + public static bool operator ==(RequestTypeEnum? left, RequestTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestTypeEnum? left, RequestTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "authentication" => RequestTypeEnum.Authentication, + "authorization" => RequestTypeEnum.Authorization, + "bankTransfer" => RequestTypeEnum.BankTransfer, + "tokenization" => RequestTypeEnum.Tokenization, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestTypeEnum? value) + { + if (value == null) + return null; + + if (value == RequestTypeEnum.Authentication) + return "authentication"; + + if (value == RequestTypeEnum.Authorization) + return "authorization"; + + if (value == RequestTypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == RequestTypeEnum.Tokenization) + return "tokenization"; + + return null; + } + + /// + /// JsonConverter for writing RequestTypeEnum. + /// + public class RequestTypeEnumJsonConverter : JsonConverter + { + public override RequestTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestTypeEnum.FromStringOrDefault(value) ?? new RequestTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestTypeOption { get; private set; } + + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + /// + /// Indicates the type of request to which the rule applies. If not provided, by default, this is set to **authorization**. Possible values: **authorization**, **authentication**, **tokenization**, **bankTransfer**. + [JsonPropertyName("requestType")] + public RequestTypeEnum? RequestType { get { return this._RequestTypeOption; } set { this._RequestTypeOption = new(value); } } + + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + /// + /// The status of the transaction rule. If you provide a `startDate` in the request, the rule is automatically created with an **active** status. Possible values: **active**, **inactive**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Your description for the transaction rule. + /// + /// Your description for the transaction rule. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// . + /// + [JsonPropertyName("entityKey")] + public TransactionRuleEntityKey EntityKey { get; set; } + + /// + /// . + /// + [JsonPropertyName("interval")] + public TransactionRuleInterval Interval { get; set; } + + /// + /// Your reference for the transaction rule. + /// + /// Your reference for the transaction rule. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// . + /// + [JsonPropertyName("ruleRestrictions")] + public TransactionRuleRestrictions RuleRestrictions { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AggregationLevelOption { get; private set; } + + /// + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + /// + /// The level at which data must be accumulated, used in rules with `type` **velocity** or **maxUsage**. The level must be the [same or lower in hierarchy](https://docs.adyen.com/issuing/transaction-rules#accumulate-data) than the `entityKey`. If not provided, by default, the rule will accumulate data at the **paymentInstrument** level. Possible values: **paymentInstrument**, **paymentInstrumentGroup**, **balanceAccount**, **accountHolder**, **balancePlatform**. + [JsonPropertyName("aggregationLevel")] + public string? AggregationLevel { get { return this._AggregationLevelOption; } set { this._AggregationLevelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndDateOption { get; private set; } + + /// + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + /// + /// The date when the rule will stop being evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided, the rule will be evaluated until the rule status is set to **inactive**. + [JsonPropertyName("endDate")] + public string? EndDate { get { return this._EndDateOption; } set { this._EndDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + /// + /// A positive or negative score applied to the transaction if it meets the conditions of the rule. Required when `outcomeType` is **scoreBased**. The value must be between **-100** and **100**. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartDateOption { get; private set; } + + /// + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + /// + /// The date when the rule will start to be evaluated, in ISO 8601 extended offset date-time format. For example, **2025-03-19T10:15:30+01:00**. If not provided when creating a transaction rule, the `startDate` is set to the date when the rule status is set to **active**. + [JsonPropertyName("startDate")] + public string? StartDate { get { return this._StartDateOption; } set { this._StartDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleInfo {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EntityKey: ").Append(EntityKey).Append("\n"); + sb.Append(" Interval: ").Append(Interval).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" RuleRestrictions: ").Append(RuleRestrictions).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AggregationLevel: ").Append(AggregationLevel).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" OutcomeType: ").Append(OutcomeType).Append("\n"); + sb.Append(" RequestType: ").Append(RequestType).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option entityKey = default; + Option interval = default; + Option reference = default; + Option ruleRestrictions = default; + Option type = default; + Option aggregationLevel = default; + Option endDate = default; + Option outcomeType = default; + Option requestType = default; + Option score = default; + Option startDate = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "entityKey": + entityKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interval": + interval = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "ruleRestrictions": + ruleRestrictions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransactionRuleInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "aggregationLevel": + aggregationLevel = new Option(utf8JsonReader.GetString()!); + break; + case "endDate": + endDate = new Option(utf8JsonReader.GetString()!); + break; + case "outcomeType": + string? outcomeTypeRawValue = utf8JsonReader.GetString(); + outcomeType = new Option(TransactionRuleInfo.OutcomeTypeEnum.FromStringOrDefault(outcomeTypeRawValue)); + break; + case "requestType": + string? requestTypeRawValue = utf8JsonReader.GetString(); + requestType = new Option(TransactionRuleInfo.RequestTypeEnum.FromStringOrDefault(requestTypeRawValue)); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "startDate": + startDate = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransactionRuleInfo.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!description.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(description)); + + if (!entityKey.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(entityKey)); + + if (!interval.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(interval)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(reference)); + + if (!ruleRestrictions.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(ruleRestrictions)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInfo.", nameof(type)); + + return new TransactionRuleInfo(description.Value!, entityKey.Value!, interval.Value!, reference.Value!, ruleRestrictions.Value!, type.Value!.Value!, aggregationLevel, endDate, outcomeType, requestType, score, startDate, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleInfo transactionRuleInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleInfo transactionRuleInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleInfo.Description != null) + writer.WriteString("description", transactionRuleInfo.Description); + + writer.WritePropertyName("entityKey"); + JsonSerializer.Serialize(writer, transactionRuleInfo.EntityKey, jsonSerializerOptions); + writer.WritePropertyName("interval"); + JsonSerializer.Serialize(writer, transactionRuleInfo.Interval, jsonSerializerOptions); + if (transactionRuleInfo.Reference != null) + writer.WriteString("reference", transactionRuleInfo.Reference); + + writer.WritePropertyName("ruleRestrictions"); + JsonSerializer.Serialize(writer, transactionRuleInfo.RuleRestrictions, jsonSerializerOptions); + if (transactionRuleInfo.Type != null) + { + string? typeRawValue = TransactionRuleInfo.TypeEnum.ToJsonValue(transactionRuleInfo.Type); + writer.WriteString("type", typeRawValue); + } + + if (transactionRuleInfo._AggregationLevelOption.IsSet) + if (transactionRuleInfo.AggregationLevel != null) + writer.WriteString("aggregationLevel", transactionRuleInfo.AggregationLevel); + + if (transactionRuleInfo._EndDateOption.IsSet) + if (transactionRuleInfo.EndDate != null) + writer.WriteString("endDate", transactionRuleInfo.EndDate); + + if (transactionRuleInfo._OutcomeTypeOption.IsSet && transactionRuleInfo.OutcomeType != null) + { + string? outcomeTypeRawValue = TransactionRuleInfo.OutcomeTypeEnum.ToJsonValue(transactionRuleInfo._OutcomeTypeOption.Value!.Value); + writer.WriteString("outcomeType", outcomeTypeRawValue); + } + + if (transactionRuleInfo._RequestTypeOption.IsSet && transactionRuleInfo.RequestType != null) + { + string? requestTypeRawValue = TransactionRuleInfo.RequestTypeEnum.ToJsonValue(transactionRuleInfo._RequestTypeOption.Value!.Value); + writer.WriteString("requestType", requestTypeRawValue); + } + + if (transactionRuleInfo._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRuleInfo._ScoreOption.Value!.Value); + + if (transactionRuleInfo._StartDateOption.IsSet) + if (transactionRuleInfo.StartDate != null) + writer.WriteString("startDate", transactionRuleInfo.StartDate); + + if (transactionRuleInfo._StatusOption.IsSet && transactionRuleInfo.Status != null) + { + string? statusRawValue = TransactionRuleInfo.StatusEnum.ToJsonValue(transactionRuleInfo._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRuleInterval.cs b/Adyen/BalancePlatform/Models/TransactionRuleInterval.cs new file mode 100644 index 000000000..c586732fd --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRuleInterval.cs @@ -0,0 +1,598 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRuleInterval. + /// + public partial class TransactionRuleInterval : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [type of interval](https://docs.adyen.com/issuing/transaction-rules#time-intervals) during which the rule conditions and limits apply, and how often counters are reset. Possible values: * **perTransaction**: conditions are evaluated and the counters are reset for every transaction. * **daily**: the counters are reset daily at 00:00:00 CET. * **weekly**: the counters are reset every Monday at 00:00:00 CET. * **monthly**: the counters reset every first day of the month at 00:00:00 CET. * **lifetime**: conditions are applied to the lifetime of the payment instrument. * **rolling**: conditions are applied and the counters are reset based on a `duration`. If the reset date and time are not provided, Adyen applies the default reset time similar to fixed intervals. For example, if the duration is every two weeks, the counter resets every third Monday at 00:00:00 CET. * **sliding**: conditions are applied and the counters are reset based on the current time and a `duration` that you specify. + /// The day of month, used when the `duration.unit` is **months**. If not provided, by default, this is set to **1**, the first day of the month. + /// The day of week, used when the `duration.unit` is **weeks**. If not provided, by default, this is set to **monday**. Possible values: **sunday**, **monday**, **tuesday**, **wednesday**, **thursday**, **friday**. + /// duration + /// The time of day, in **hh:mm:ss** format, used when the `duration.unit` is **hours**. If not provided, by default, this is set to **00:00:00**. + /// The [time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). For example, **Europe/Amsterdam**. By default, this is set to **UTC**. + [JsonConstructor] + public TransactionRuleInterval(TypeEnum type, Option dayOfMonth = default, Option dayOfWeek = default, Option duration = default, Option timeOfDay = default, Option timeZone = default) + { + Type = type; + _DayOfMonthOption = dayOfMonth; + _DayOfWeekOption = dayOfWeek; + _DurationOption = duration; + _TimeOfDayOption = timeOfDay; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleInterval() + { + } + + partial void OnCreated(); + + /// + /// The [type of interval](https://docs.adyen.com/issuing/transaction-rules#time-intervals) during which the rule conditions and limits apply, and how often counters are reset. Possible values: * **perTransaction**: conditions are evaluated and the counters are reset for every transaction. * **daily**: the counters are reset daily at 00:00:00 CET. * **weekly**: the counters are reset every Monday at 00:00:00 CET. * **monthly**: the counters reset every first day of the month at 00:00:00 CET. * **lifetime**: conditions are applied to the lifetime of the payment instrument. * **rolling**: conditions are applied and the counters are reset based on a `duration`. If the reset date and time are not provided, Adyen applies the default reset time similar to fixed intervals. For example, if the duration is every two weeks, the counter resets every third Monday at 00:00:00 CET. * **sliding**: conditions are applied and the counters are reset based on the current time and a `duration` that you specify. + /// + /// The [type of interval](https://docs.adyen.com/issuing/transaction-rules#time-intervals) during which the rule conditions and limits apply, and how often counters are reset. Possible values: * **perTransaction**: conditions are evaluated and the counters are reset for every transaction. * **daily**: the counters are reset daily at 00:00:00 CET. * **weekly**: the counters are reset every Monday at 00:00:00 CET. * **monthly**: the counters reset every first day of the month at 00:00:00 CET. * **lifetime**: conditions are applied to the lifetime of the payment instrument. * **rolling**: conditions are applied and the counters are reset based on a `duration`. If the reset date and time are not provided, Adyen applies the default reset time similar to fixed intervals. For example, if the duration is every two weeks, the counter resets every third Monday at 00:00:00 CET. * **sliding**: conditions are applied and the counters are reset based on the current time and a `duration` that you specify. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Daily - daily + /// + public static readonly TypeEnum Daily = new("daily"); + + /// + /// TypeEnum.Lifetime - lifetime + /// + public static readonly TypeEnum Lifetime = new("lifetime"); + + /// + /// TypeEnum.Monthly - monthly + /// + public static readonly TypeEnum Monthly = new("monthly"); + + /// + /// TypeEnum.PerTransaction - perTransaction + /// + public static readonly TypeEnum PerTransaction = new("perTransaction"); + + /// + /// TypeEnum.Rolling - rolling + /// + public static readonly TypeEnum Rolling = new("rolling"); + + /// + /// TypeEnum.Sliding - sliding + /// + public static readonly TypeEnum Sliding = new("sliding"); + + /// + /// TypeEnum.Weekly - weekly + /// + public static readonly TypeEnum Weekly = new("weekly"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => TypeEnum.Daily, + "lifetime" => TypeEnum.Lifetime, + "monthly" => TypeEnum.Monthly, + "perTransaction" => TypeEnum.PerTransaction, + "rolling" => TypeEnum.Rolling, + "sliding" => TypeEnum.Sliding, + "weekly" => TypeEnum.Weekly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Daily) + return "daily"; + + if (value == TypeEnum.Lifetime) + return "lifetime"; + + if (value == TypeEnum.Monthly) + return "monthly"; + + if (value == TypeEnum.PerTransaction) + return "perTransaction"; + + if (value == TypeEnum.Rolling) + return "rolling"; + + if (value == TypeEnum.Sliding) + return "sliding"; + + if (value == TypeEnum.Weekly) + return "weekly"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The [type of interval](https://docs.adyen.com/issuing/transaction-rules#time-intervals) during which the rule conditions and limits apply, and how often counters are reset. Possible values: * **perTransaction**: conditions are evaluated and the counters are reset for every transaction. * **daily**: the counters are reset daily at 00:00:00 CET. * **weekly**: the counters are reset every Monday at 00:00:00 CET. * **monthly**: the counters reset every first day of the month at 00:00:00 CET. * **lifetime**: conditions are applied to the lifetime of the payment instrument. * **rolling**: conditions are applied and the counters are reset based on a `duration`. If the reset date and time are not provided, Adyen applies the default reset time similar to fixed intervals. For example, if the duration is every two weeks, the counter resets every third Monday at 00:00:00 CET. * **sliding**: conditions are applied and the counters are reset based on the current time and a `duration` that you specify. + /// + /// The [type of interval](https://docs.adyen.com/issuing/transaction-rules#time-intervals) during which the rule conditions and limits apply, and how often counters are reset. Possible values: * **perTransaction**: conditions are evaluated and the counters are reset for every transaction. * **daily**: the counters are reset daily at 00:00:00 CET. * **weekly**: the counters are reset every Monday at 00:00:00 CET. * **monthly**: the counters reset every first day of the month at 00:00:00 CET. * **lifetime**: conditions are applied to the lifetime of the payment instrument. * **rolling**: conditions are applied and the counters are reset based on a `duration`. If the reset date and time are not provided, Adyen applies the default reset time similar to fixed intervals. For example, if the duration is every two weeks, the counter resets every third Monday at 00:00:00 CET. * **sliding**: conditions are applied and the counters are reset based on the current time and a `duration` that you specify. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The day of week, used when the `duration.unit` is **weeks**. If not provided, by default, this is set to **monday**. Possible values: **sunday**, **monday**, **tuesday**, **wednesday**, **thursday**, **friday**. + /// + /// The day of week, used when the `duration.unit` is **weeks**. If not provided, by default, this is set to **monday**. Possible values: **sunday**, **monday**, **tuesday**, **wednesday**, **thursday**, **friday**. + [JsonConverter(typeof(DayOfWeekEnumJsonConverter))] + public class DayOfWeekEnum : IEnum + { + /// + /// Returns the value of the DayOfWeekEnum. + /// + public string? Value { get; set; } + + /// + /// DayOfWeekEnum.Friday - friday + /// + public static readonly DayOfWeekEnum Friday = new("friday"); + + /// + /// DayOfWeekEnum.Monday - monday + /// + public static readonly DayOfWeekEnum Monday = new("monday"); + + /// + /// DayOfWeekEnum.Saturday - saturday + /// + public static readonly DayOfWeekEnum Saturday = new("saturday"); + + /// + /// DayOfWeekEnum.Sunday - sunday + /// + public static readonly DayOfWeekEnum Sunday = new("sunday"); + + /// + /// DayOfWeekEnum.Thursday - thursday + /// + public static readonly DayOfWeekEnum Thursday = new("thursday"); + + /// + /// DayOfWeekEnum.Tuesday - tuesday + /// + public static readonly DayOfWeekEnum Tuesday = new("tuesday"); + + /// + /// DayOfWeekEnum.Wednesday - wednesday + /// + public static readonly DayOfWeekEnum Wednesday = new("wednesday"); + + private DayOfWeekEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DayOfWeekEnum?(string? value) => value == null ? null : new DayOfWeekEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DayOfWeekEnum? option) => option?.Value; + + public static bool operator ==(DayOfWeekEnum? left, DayOfWeekEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DayOfWeekEnum? left, DayOfWeekEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DayOfWeekEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DayOfWeekEnum? FromStringOrDefault(string value) + { + return value switch { + "friday" => DayOfWeekEnum.Friday, + "monday" => DayOfWeekEnum.Monday, + "saturday" => DayOfWeekEnum.Saturday, + "sunday" => DayOfWeekEnum.Sunday, + "thursday" => DayOfWeekEnum.Thursday, + "tuesday" => DayOfWeekEnum.Tuesday, + "wednesday" => DayOfWeekEnum.Wednesday, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DayOfWeekEnum? value) + { + if (value == null) + return null; + + if (value == DayOfWeekEnum.Friday) + return "friday"; + + if (value == DayOfWeekEnum.Monday) + return "monday"; + + if (value == DayOfWeekEnum.Saturday) + return "saturday"; + + if (value == DayOfWeekEnum.Sunday) + return "sunday"; + + if (value == DayOfWeekEnum.Thursday) + return "thursday"; + + if (value == DayOfWeekEnum.Tuesday) + return "tuesday"; + + if (value == DayOfWeekEnum.Wednesday) + return "wednesday"; + + return null; + } + + /// + /// JsonConverter for writing DayOfWeekEnum. + /// + public class DayOfWeekEnumJsonConverter : JsonConverter + { + public override DayOfWeekEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DayOfWeekEnum.FromStringOrDefault(value) ?? new DayOfWeekEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DayOfWeekEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DayOfWeekEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DayOfWeekOption { get; private set; } + + /// + /// The day of week, used when the `duration.unit` is **weeks**. If not provided, by default, this is set to **monday**. Possible values: **sunday**, **monday**, **tuesday**, **wednesday**, **thursday**, **friday**. + /// + /// The day of week, used when the `duration.unit` is **weeks**. If not provided, by default, this is set to **monday**. Possible values: **sunday**, **monday**, **tuesday**, **wednesday**, **thursday**, **friday**. + [JsonPropertyName("dayOfWeek")] + public DayOfWeekEnum? DayOfWeek { get { return this._DayOfWeekOption; } set { this._DayOfWeekOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DayOfMonthOption { get; private set; } + + /// + /// The day of month, used when the `duration.unit` is **months**. If not provided, by default, this is set to **1**, the first day of the month. + /// + /// The day of month, used when the `duration.unit` is **months**. If not provided, by default, this is set to **1**, the first day of the month. + [JsonPropertyName("dayOfMonth")] + public int? DayOfMonth { get { return this._DayOfMonthOption; } set { this._DayOfMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("duration")] + public Duration? Duration { get { return this._DurationOption; } set { this._DurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeOfDayOption { get; private set; } + + /// + /// The time of day, in **hh:mm:ss** format, used when the `duration.unit` is **hours**. If not provided, by default, this is set to **00:00:00**. + /// + /// The time of day, in **hh:mm:ss** format, used when the `duration.unit` is **hours**. If not provided, by default, this is set to **00:00:00**. + [JsonPropertyName("timeOfDay")] + public string? TimeOfDay { get { return this._TimeOfDayOption; } set { this._TimeOfDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The [time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). For example, **Europe/Amsterdam**. By default, this is set to **UTC**. + /// + /// The [time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). For example, **Europe/Amsterdam**. By default, this is set to **UTC**. + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleInterval {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" DayOfMonth: ").Append(DayOfMonth).Append("\n"); + sb.Append(" DayOfWeek: ").Append(DayOfWeek).Append("\n"); + sb.Append(" Duration: ").Append(Duration).Append("\n"); + sb.Append(" TimeOfDay: ").Append(TimeOfDay).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleIntervalJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleInterval Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option dayOfMonth = default; + Option dayOfWeek = default; + Option duration = default; + Option timeOfDay = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransactionRuleInterval.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "dayOfMonth": + dayOfMonth = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "dayOfWeek": + string? dayOfWeekRawValue = utf8JsonReader.GetString(); + dayOfWeek = new Option(TransactionRuleInterval.DayOfWeekEnum.FromStringOrDefault(dayOfWeekRawValue)); + break; + case "duration": + duration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeOfDay": + timeOfDay = new Option(utf8JsonReader.GetString()!); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransactionRuleInterval.", nameof(type)); + + return new TransactionRuleInterval(type.Value!.Value!, dayOfMonth, dayOfWeek, duration, timeOfDay, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleInterval transactionRuleInterval, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleInterval, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleInterval transactionRuleInterval, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleInterval.Type != null) + { + string? typeRawValue = TransactionRuleInterval.TypeEnum.ToJsonValue(transactionRuleInterval.Type); + writer.WriteString("type", typeRawValue); + } + + if (transactionRuleInterval._DayOfMonthOption.IsSet) + writer.WriteNumber("dayOfMonth", transactionRuleInterval._DayOfMonthOption.Value!.Value); + + if (transactionRuleInterval._DayOfWeekOption.IsSet && transactionRuleInterval.DayOfWeek != null) + { + string? dayOfWeekRawValue = TransactionRuleInterval.DayOfWeekEnum.ToJsonValue(transactionRuleInterval._DayOfWeekOption.Value!.Value); + writer.WriteString("dayOfWeek", dayOfWeekRawValue); + } + + if (transactionRuleInterval._DurationOption.IsSet) + { + writer.WritePropertyName("duration"); + JsonSerializer.Serialize(writer, transactionRuleInterval.Duration, jsonSerializerOptions); + } + if (transactionRuleInterval._TimeOfDayOption.IsSet) + if (transactionRuleInterval.TimeOfDay != null) + writer.WriteString("timeOfDay", transactionRuleInterval.TimeOfDay); + + if (transactionRuleInterval._TimeZoneOption.IsSet) + if (transactionRuleInterval.TimeZone != null) + writer.WriteString("timeZone", transactionRuleInterval.TimeZone); + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRuleResponse.cs b/Adyen/BalancePlatform/Models/TransactionRuleResponse.cs new file mode 100644 index 000000000..a3f0d6d61 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRuleResponse.cs @@ -0,0 +1,178 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRuleResponse. + /// + public partial class TransactionRuleResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// transactionRule + [JsonConstructor] + public TransactionRuleResponse(Option transactionRule = default) + { + _TransactionRuleOption = transactionRule; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRule")] + public TransactionRule? TransactionRule { get { return this._TransactionRuleOption; } set { this._TransactionRuleOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleResponse {\n"); + sb.Append(" TransactionRule: ").Append(TransactionRule).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option transactionRule = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transactionRule": + transactionRule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionRuleResponse(transactionRule); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleResponse transactionRuleResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleResponse transactionRuleResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleResponse._TransactionRuleOption.IsSet) + { + writer.WritePropertyName("transactionRule"); + JsonSerializer.Serialize(writer, transactionRuleResponse.TransactionRule, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRuleRestrictions.cs b/Adyen/BalancePlatform/Models/TransactionRuleRestrictions.cs new file mode 100644 index 000000000..d0d6c0d0d --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRuleRestrictions.cs @@ -0,0 +1,778 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRuleRestrictions. + /// + public partial class TransactionRuleRestrictions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// activeNetworkTokens + /// brandVariants + /// counterpartyBank + /// counterpartyTypes + /// countries + /// dayOfWeek + /// differentCurrencies + /// entryModes + /// internationalTransaction + /// matchingTransactions + /// matchingValues + /// mccs + /// merchantNames + /// merchants + /// processingTypes + /// riskScores + /// sameAmountRestriction + /// sameCounterpartyRestriction + /// sourceAccountTypes + /// timeOfDay + /// tokenRequestors + /// totalAmount + /// walletProviderAccountScore + /// walletProviderDeviceScore + /// walletProviderDeviceType + [JsonConstructor] + public TransactionRuleRestrictions(Option activeNetworkTokens = default, Option brandVariants = default, Option counterpartyBank = default, Option counterpartyTypes = default, Option countries = default, Option dayOfWeek = default, Option differentCurrencies = default, Option entryModes = default, Option internationalTransaction = default, Option matchingTransactions = default, Option matchingValues = default, Option mccs = default, Option merchantNames = default, Option merchants = default, Option processingTypes = default, Option riskScores = default, Option sameAmountRestriction = default, Option sameCounterpartyRestriction = default, Option sourceAccountTypes = default, Option timeOfDay = default, Option tokenRequestors = default, Option totalAmount = default, Option walletProviderAccountScore = default, Option walletProviderDeviceScore = default, Option walletProviderDeviceType = default) + { + _ActiveNetworkTokensOption = activeNetworkTokens; + _BrandVariantsOption = brandVariants; + _CounterpartyBankOption = counterpartyBank; + _CounterpartyTypesOption = counterpartyTypes; + _CountriesOption = countries; + _DayOfWeekOption = dayOfWeek; + _DifferentCurrenciesOption = differentCurrencies; + _EntryModesOption = entryModes; + _InternationalTransactionOption = internationalTransaction; + _MatchingTransactionsOption = matchingTransactions; + _MatchingValuesOption = matchingValues; + _MccsOption = mccs; + _MerchantNamesOption = merchantNames; + _MerchantsOption = merchants; + _ProcessingTypesOption = processingTypes; + _RiskScoresOption = riskScores; + _SameAmountRestrictionOption = sameAmountRestriction; + _SameCounterpartyRestrictionOption = sameCounterpartyRestriction; + _SourceAccountTypesOption = sourceAccountTypes; + _TimeOfDayOption = timeOfDay; + _TokenRequestorsOption = tokenRequestors; + _TotalAmountOption = totalAmount; + _WalletProviderAccountScoreOption = walletProviderAccountScore; + _WalletProviderDeviceScoreOption = walletProviderDeviceScore; + _WalletProviderDeviceTypeOption = walletProviderDeviceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleRestrictions() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveNetworkTokensOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("activeNetworkTokens")] + public ActiveNetworkTokensRestriction? ActiveNetworkTokens { get { return this._ActiveNetworkTokensOption; } set { this._ActiveNetworkTokensOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandVariantsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("brandVariants")] + public BrandVariantsRestriction? BrandVariants { get { return this._BrandVariantsOption; } set { this._BrandVariantsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyBankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterpartyBank")] + public CounterpartyBankRestriction? CounterpartyBank { get { return this._CounterpartyBankOption; } set { this._CounterpartyBankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyTypesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterpartyTypes")] + public CounterpartyTypesRestriction? CounterpartyTypes { get { return this._CounterpartyTypesOption; } set { this._CounterpartyTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountriesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("countries")] + public CountriesRestriction? Countries { get { return this._CountriesOption; } set { this._CountriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DayOfWeekOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dayOfWeek")] + public DayOfWeekRestriction? DayOfWeek { get { return this._DayOfWeekOption; } set { this._DayOfWeekOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DifferentCurrenciesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("differentCurrencies")] + public DifferentCurrenciesRestriction? DifferentCurrencies { get { return this._DifferentCurrenciesOption; } set { this._DifferentCurrenciesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntryModesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("entryModes")] + public EntryModesRestriction? EntryModes { get { return this._EntryModesOption; } set { this._EntryModesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InternationalTransactionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("internationalTransaction")] + public InternationalTransactionRestriction? InternationalTransaction { get { return this._InternationalTransactionOption; } set { this._InternationalTransactionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MatchingTransactionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("matchingTransactions")] + public MatchingTransactionsRestriction? MatchingTransactions { get { return this._MatchingTransactionsOption; } set { this._MatchingTransactionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MatchingValuesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("matchingValues")] + public MatchingValuesRestriction? MatchingValues { get { return this._MatchingValuesOption; } set { this._MatchingValuesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mccs")] + public MccsRestriction? Mccs { get { return this._MccsOption; } set { this._MccsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantNamesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantNames")] + public MerchantNamesRestriction? MerchantNames { get { return this._MerchantNamesOption; } set { this._MerchantNamesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchants")] + public MerchantsRestriction? Merchants { get { return this._MerchantsOption; } set { this._MerchantsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProcessingTypesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("processingTypes")] + public ProcessingTypesRestriction? ProcessingTypes { get { return this._ProcessingTypesOption; } set { this._ProcessingTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoresOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskScores")] + public RiskScoresRestriction? RiskScores { get { return this._RiskScoresOption; } set { this._RiskScoresOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SameAmountRestrictionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sameAmountRestriction")] + public SameAmountRestriction? SameAmountRestriction { get { return this._SameAmountRestrictionOption; } set { this._SameAmountRestrictionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SameCounterpartyRestrictionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sameCounterpartyRestriction")] + public SameCounterpartyRestriction? SameCounterpartyRestriction { get { return this._SameCounterpartyRestrictionOption; } set { this._SameCounterpartyRestrictionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceAccountTypesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sourceAccountTypes")] + public SourceAccountTypesRestriction? SourceAccountTypes { get { return this._SourceAccountTypesOption; } set { this._SourceAccountTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeOfDayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("timeOfDay")] + public TimeOfDayRestriction? TimeOfDay { get { return this._TimeOfDayOption; } set { this._TimeOfDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenRequestorsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenRequestors")] + public TokenRequestorsRestriction? TokenRequestors { get { return this._TokenRequestorsOption; } set { this._TokenRequestorsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("totalAmount")] + public TotalAmountRestriction? TotalAmount { get { return this._TotalAmountOption; } set { this._TotalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletProviderAccountScoreOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("walletProviderAccountScore")] + public WalletProviderAccountScoreRestriction? WalletProviderAccountScore { get { return this._WalletProviderAccountScoreOption; } set { this._WalletProviderAccountScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletProviderDeviceScoreOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("walletProviderDeviceScore")] + public WalletProviderDeviceScore? WalletProviderDeviceScore { get { return this._WalletProviderDeviceScoreOption; } set { this._WalletProviderDeviceScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletProviderDeviceTypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("walletProviderDeviceType")] + public WalletProviderDeviceType? WalletProviderDeviceType { get { return this._WalletProviderDeviceTypeOption; } set { this._WalletProviderDeviceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleRestrictions {\n"); + sb.Append(" ActiveNetworkTokens: ").Append(ActiveNetworkTokens).Append("\n"); + sb.Append(" BrandVariants: ").Append(BrandVariants).Append("\n"); + sb.Append(" CounterpartyBank: ").Append(CounterpartyBank).Append("\n"); + sb.Append(" CounterpartyTypes: ").Append(CounterpartyTypes).Append("\n"); + sb.Append(" Countries: ").Append(Countries).Append("\n"); + sb.Append(" DayOfWeek: ").Append(DayOfWeek).Append("\n"); + sb.Append(" DifferentCurrencies: ").Append(DifferentCurrencies).Append("\n"); + sb.Append(" EntryModes: ").Append(EntryModes).Append("\n"); + sb.Append(" InternationalTransaction: ").Append(InternationalTransaction).Append("\n"); + sb.Append(" MatchingTransactions: ").Append(MatchingTransactions).Append("\n"); + sb.Append(" MatchingValues: ").Append(MatchingValues).Append("\n"); + sb.Append(" Mccs: ").Append(Mccs).Append("\n"); + sb.Append(" MerchantNames: ").Append(MerchantNames).Append("\n"); + sb.Append(" Merchants: ").Append(Merchants).Append("\n"); + sb.Append(" ProcessingTypes: ").Append(ProcessingTypes).Append("\n"); + sb.Append(" RiskScores: ").Append(RiskScores).Append("\n"); + sb.Append(" SameAmountRestriction: ").Append(SameAmountRestriction).Append("\n"); + sb.Append(" SameCounterpartyRestriction: ").Append(SameCounterpartyRestriction).Append("\n"); + sb.Append(" SourceAccountTypes: ").Append(SourceAccountTypes).Append("\n"); + sb.Append(" TimeOfDay: ").Append(TimeOfDay).Append("\n"); + sb.Append(" TokenRequestors: ").Append(TokenRequestors).Append("\n"); + sb.Append(" TotalAmount: ").Append(TotalAmount).Append("\n"); + sb.Append(" WalletProviderAccountScore: ").Append(WalletProviderAccountScore).Append("\n"); + sb.Append(" WalletProviderDeviceScore: ").Append(WalletProviderDeviceScore).Append("\n"); + sb.Append(" WalletProviderDeviceType: ").Append(WalletProviderDeviceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleRestrictionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleRestrictions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option activeNetworkTokens = default; + Option brandVariants = default; + Option counterpartyBank = default; + Option counterpartyTypes = default; + Option countries = default; + Option dayOfWeek = default; + Option differentCurrencies = default; + Option entryModes = default; + Option internationalTransaction = default; + Option matchingTransactions = default; + Option matchingValues = default; + Option mccs = default; + Option merchantNames = default; + Option merchants = default; + Option processingTypes = default; + Option riskScores = default; + Option sameAmountRestriction = default; + Option sameCounterpartyRestriction = default; + Option sourceAccountTypes = default; + Option timeOfDay = default; + Option tokenRequestors = default; + Option totalAmount = default; + Option walletProviderAccountScore = default; + Option walletProviderDeviceScore = default; + Option walletProviderDeviceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "activeNetworkTokens": + activeNetworkTokens = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "brandVariants": + brandVariants = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "counterpartyBank": + counterpartyBank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "counterpartyTypes": + counterpartyTypes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countries": + countries = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dayOfWeek": + dayOfWeek = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "differentCurrencies": + differentCurrencies = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "entryModes": + entryModes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "internationalTransaction": + internationalTransaction = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "matchingTransactions": + matchingTransactions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "matchingValues": + matchingValues = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mccs": + mccs = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantNames": + merchantNames = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchants": + merchants = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "processingTypes": + processingTypes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "riskScores": + riskScores = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sameAmountRestriction": + sameAmountRestriction = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sameCounterpartyRestriction": + sameCounterpartyRestriction = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sourceAccountTypes": + sourceAccountTypes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeOfDay": + timeOfDay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tokenRequestors": + tokenRequestors = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "totalAmount": + totalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "walletProviderAccountScore": + walletProviderAccountScore = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "walletProviderDeviceScore": + walletProviderDeviceScore = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "walletProviderDeviceType": + walletProviderDeviceType = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionRuleRestrictions(activeNetworkTokens, brandVariants, counterpartyBank, counterpartyTypes, countries, dayOfWeek, differentCurrencies, entryModes, internationalTransaction, matchingTransactions, matchingValues, mccs, merchantNames, merchants, processingTypes, riskScores, sameAmountRestriction, sameCounterpartyRestriction, sourceAccountTypes, timeOfDay, tokenRequestors, totalAmount, walletProviderAccountScore, walletProviderDeviceScore, walletProviderDeviceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleRestrictions transactionRuleRestrictions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleRestrictions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleRestrictions transactionRuleRestrictions, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleRestrictions._ActiveNetworkTokensOption.IsSet) + { + writer.WritePropertyName("activeNetworkTokens"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.ActiveNetworkTokens, jsonSerializerOptions); + } + if (transactionRuleRestrictions._BrandVariantsOption.IsSet) + { + writer.WritePropertyName("brandVariants"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.BrandVariants, jsonSerializerOptions); + } + if (transactionRuleRestrictions._CounterpartyBankOption.IsSet) + { + writer.WritePropertyName("counterpartyBank"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.CounterpartyBank, jsonSerializerOptions); + } + if (transactionRuleRestrictions._CounterpartyTypesOption.IsSet) + { + writer.WritePropertyName("counterpartyTypes"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.CounterpartyTypes, jsonSerializerOptions); + } + if (transactionRuleRestrictions._CountriesOption.IsSet) + { + writer.WritePropertyName("countries"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.Countries, jsonSerializerOptions); + } + if (transactionRuleRestrictions._DayOfWeekOption.IsSet) + { + writer.WritePropertyName("dayOfWeek"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.DayOfWeek, jsonSerializerOptions); + } + if (transactionRuleRestrictions._DifferentCurrenciesOption.IsSet) + { + writer.WritePropertyName("differentCurrencies"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.DifferentCurrencies, jsonSerializerOptions); + } + if (transactionRuleRestrictions._EntryModesOption.IsSet) + { + writer.WritePropertyName("entryModes"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.EntryModes, jsonSerializerOptions); + } + if (transactionRuleRestrictions._InternationalTransactionOption.IsSet) + { + writer.WritePropertyName("internationalTransaction"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.InternationalTransaction, jsonSerializerOptions); + } + if (transactionRuleRestrictions._MatchingTransactionsOption.IsSet) + { + writer.WritePropertyName("matchingTransactions"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.MatchingTransactions, jsonSerializerOptions); + } + if (transactionRuleRestrictions._MatchingValuesOption.IsSet) + { + writer.WritePropertyName("matchingValues"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.MatchingValues, jsonSerializerOptions); + } + if (transactionRuleRestrictions._MccsOption.IsSet) + { + writer.WritePropertyName("mccs"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.Mccs, jsonSerializerOptions); + } + if (transactionRuleRestrictions._MerchantNamesOption.IsSet) + { + writer.WritePropertyName("merchantNames"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.MerchantNames, jsonSerializerOptions); + } + if (transactionRuleRestrictions._MerchantsOption.IsSet) + { + writer.WritePropertyName("merchants"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.Merchants, jsonSerializerOptions); + } + if (transactionRuleRestrictions._ProcessingTypesOption.IsSet) + { + writer.WritePropertyName("processingTypes"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.ProcessingTypes, jsonSerializerOptions); + } + if (transactionRuleRestrictions._RiskScoresOption.IsSet) + { + writer.WritePropertyName("riskScores"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.RiskScores, jsonSerializerOptions); + } + if (transactionRuleRestrictions._SameAmountRestrictionOption.IsSet) + { + writer.WritePropertyName("sameAmountRestriction"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.SameAmountRestriction, jsonSerializerOptions); + } + if (transactionRuleRestrictions._SameCounterpartyRestrictionOption.IsSet) + { + writer.WritePropertyName("sameCounterpartyRestriction"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.SameCounterpartyRestriction, jsonSerializerOptions); + } + if (transactionRuleRestrictions._SourceAccountTypesOption.IsSet) + { + writer.WritePropertyName("sourceAccountTypes"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.SourceAccountTypes, jsonSerializerOptions); + } + if (transactionRuleRestrictions._TimeOfDayOption.IsSet) + { + writer.WritePropertyName("timeOfDay"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.TimeOfDay, jsonSerializerOptions); + } + if (transactionRuleRestrictions._TokenRequestorsOption.IsSet) + { + writer.WritePropertyName("tokenRequestors"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.TokenRequestors, jsonSerializerOptions); + } + if (transactionRuleRestrictions._TotalAmountOption.IsSet) + { + writer.WritePropertyName("totalAmount"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.TotalAmount, jsonSerializerOptions); + } + if (transactionRuleRestrictions._WalletProviderAccountScoreOption.IsSet) + { + writer.WritePropertyName("walletProviderAccountScore"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.WalletProviderAccountScore, jsonSerializerOptions); + } + if (transactionRuleRestrictions._WalletProviderDeviceScoreOption.IsSet) + { + writer.WritePropertyName("walletProviderDeviceScore"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.WalletProviderDeviceScore, jsonSerializerOptions); + } + if (transactionRuleRestrictions._WalletProviderDeviceTypeOption.IsSet) + { + writer.WritePropertyName("walletProviderDeviceType"); + JsonSerializer.Serialize(writer, transactionRuleRestrictions.WalletProviderDeviceType, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransactionRulesResponse.cs b/Adyen/BalancePlatform/Models/TransactionRulesResponse.cs new file mode 100644 index 000000000..9e8b3d7d7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransactionRulesResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransactionRulesResponse. + /// + public partial class TransactionRulesResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of transaction rules. + [JsonConstructor] + public TransactionRulesResponse(Option?> transactionRules = default) + { + _TransactionRulesOption = transactionRules; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRulesResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransactionRulesOption { get; private set; } + + /// + /// List of transaction rules. + /// + /// List of transaction rules. + [JsonPropertyName("transactionRules")] + public List? TransactionRules { get { return this._TransactionRulesOption; } set { this._TransactionRulesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRulesResponse {\n"); + sb.Append(" TransactionRules: ").Append(TransactionRules).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRulesResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRulesResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transactionRules = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transactionRules": + transactionRules = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionRulesResponse(transactionRules); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRulesResponse transactionRulesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRulesResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRulesResponse transactionRulesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRulesResponse._TransactionRulesOption.IsSet) + { + writer.WritePropertyName("transactionRules"); + JsonSerializer.Serialize(writer, transactionRulesResponse.TransactionRules, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferLimit.cs b/Adyen/BalancePlatform/Models/TransferLimit.cs new file mode 100644 index 000000000..bcd16b625 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferLimit.cs @@ -0,0 +1,356 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The transfer limit configured to regulate outgoing transfers.. + /// + public partial class TransferLimit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The unique identifier of the transfer limit. + /// limitStatus + /// scope + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// transferType + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// Your reference for the transfer limit. + /// scaInformation + [JsonConstructor] + public TransferLimit(Amount amount, string id, LimitStatus limitStatus, Scope scope, DateTimeOffset startsAt, TransferType transferType, Option endsAt = default, Option reference = default, Option scaInformation = default) + { + Amount = amount; + Id = id; + LimitStatus = limitStatus; + Scope = scope; + StartsAt = startsAt; + TransferType = transferType; + _EndsAtOption = endsAt; + _ReferenceOption = reference; + _ScaInformationOption = scaInformation; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferLimit() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("limitStatus")] + public LimitStatus LimitStatus { get; set; } + + /// + /// . + /// + [JsonPropertyName("scope")] + public Scope Scope { get; set; } + + /// + /// . + /// + [JsonPropertyName("transferType")] + public TransferType TransferType { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The unique identifier of the transfer limit. + /// + /// The unique identifier of the transfer limit. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// + /// The date and time when the transfer limit becomes active. If you specify a date in the future, we will schedule a transfer limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + [JsonPropertyName("startsAt")] + public DateTimeOffset StartsAt { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndsAtOption { get; private set; } + + /// + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + /// + /// The date and time when the transfer limit becomes inactive. If you do not specify an end date, the limit stays active until you override it with a new limit. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): **YYYY-MM-DDThh:mm:ss.sssTZD** + [JsonPropertyName("endsAt")] + public DateTimeOffset? EndsAt { get { return this._EndsAtOption; } set { this._EndsAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer limit. + /// + /// Your reference for the transfer limit. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaInformationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("scaInformation")] + public ScaInformation? ScaInformation { get { return this._ScaInformationOption; } set { this._ScaInformationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferLimit {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LimitStatus: ").Append(LimitStatus).Append("\n"); + sb.Append(" Scope: ").Append(Scope).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append(" TransferType: ").Append(TransferType).Append("\n"); + sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ScaInformation: ").Append(ScaInformation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferLimitJsonConverter : JsonConverter + { + /// + /// The format to use to serialize StartsAt. + /// + public static string StartsAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize EndsAt. + /// + public static string EndsAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferLimit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option id = default; + Option limitStatus = default; + Option scope = default; + Option startsAt = default; + Option transferType = default; + Option endsAt = default; + Option reference = default; + Option scaInformation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "limitStatus": + string? limitStatusRawValue = utf8JsonReader.GetString(); + if (limitStatusRawValue != null) + limitStatus = new Option(LimitStatusValueConverter.FromStringOrDefault(limitStatusRawValue)); + break; + case "scope": + string? scopeRawValue = utf8JsonReader.GetString(); + if (scopeRawValue != null) + scope = new Option(ScopeValueConverter.FromStringOrDefault(scopeRawValue)); + break; + case "startsAt": + startsAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "transferType": + string? transferTypeRawValue = utf8JsonReader.GetString(); + if (transferTypeRawValue != null) + transferType = new Option(TransferTypeValueConverter.FromStringOrDefault(transferTypeRawValue)); + break; + case "endsAt": + endsAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "scaInformation": + scaInformation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(amount)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(id)); + + if (!limitStatus.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(limitStatus)); + + if (!scope.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(scope)); + + if (!startsAt.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(startsAt)); + + if (!transferType.IsSet) + throw new ArgumentException("Property is required for class TransferLimit.", nameof(transferType)); + + return new TransferLimit(amount.Value!, id.Value!, limitStatus.Value!.Value!, scope.Value!.Value!, startsAt.Value!.Value!, transferType.Value!.Value!, endsAt, reference, scaInformation); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferLimit transferLimit, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferLimit, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferLimit transferLimit, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferLimit.Amount, jsonSerializerOptions); + if (transferLimit.Id != null) + writer.WriteString("id", transferLimit.Id); + + var limitStatusRawValue = LimitStatusValueConverter.ToJsonValue(transferLimit.LimitStatus); + writer.WriteString("limitStatus", limitStatusRawValue); + + var scopeRawValue = ScopeValueConverter.ToJsonValue(transferLimit.Scope); + writer.WriteString("scope", scopeRawValue); + + writer.WriteString("startsAt", transferLimit.StartsAt.ToString(StartsAtFormat)); + + var transferTypeRawValue = TransferTypeValueConverter.ToJsonValue(transferLimit.TransferType); + writer.WriteString("transferType", transferTypeRawValue); + + if (transferLimit._EndsAtOption.IsSet) + writer.WriteString("endsAt", transferLimit._EndsAtOption.Value!.Value.ToString(EndsAtFormat)); + + if (transferLimit._ReferenceOption.IsSet) + if (transferLimit.Reference != null) + writer.WriteString("reference", transferLimit.Reference); + + if (transferLimit._ScaInformationOption.IsSet) + { + writer.WritePropertyName("scaInformation"); + JsonSerializer.Serialize(writer, transferLimit.ScaInformation, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferLimitListResponse.cs b/Adyen/BalancePlatform/Models/TransferLimitListResponse.cs new file mode 100644 index 000000000..a17fed52f --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferLimitListResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransferLimitListResponse. + /// + public partial class TransferLimitListResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of available transfer limits. + [JsonConstructor] + public TransferLimitListResponse(List transferLimits) + { + TransferLimits = transferLimits; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferLimitListResponse() + { + } + + partial void OnCreated(); + + /// + /// List of available transfer limits. + /// + /// List of available transfer limits. + [JsonPropertyName("transferLimits")] + public List TransferLimits { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferLimitListResponse {\n"); + sb.Append(" TransferLimits: ").Append(TransferLimits).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferLimitListResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferLimitListResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transferLimits = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferLimits": + transferLimits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!transferLimits.IsSet) + throw new ArgumentException("Property is required for class TransferLimitListResponse.", nameof(transferLimits)); + + return new TransferLimitListResponse(transferLimits.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferLimitListResponse transferLimitListResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferLimitListResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferLimitListResponse transferLimitListResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("transferLimits"); + JsonSerializer.Serialize(writer, transferLimitListResponse.TransferLimits, jsonSerializerOptions); + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferRoute.cs b/Adyen/BalancePlatform/Models/TransferRoute.cs new file mode 100644 index 000000000..d22b76d8d --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferRoute.cs @@ -0,0 +1,599 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransferRoute. + /// + public partial class TransferRoute : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// A set of rules defined by clearing houses and banking partners. Your transfer request must adhere to these rules to ensure successful initiation of transfer. Based on the priority, one or more requirements may be returned. Each requirement is defined with a `type` and `description`. + [JsonConstructor] + public TransferRoute(Option category = default, Option country = default, Option currency = default, Option priority = default, Option?> requirements = default) + { + _CategoryOption = category; + _CountryOption = country; + _CurrencyOption = currency; + _PriorityOption = priority; + _RequirementsOption = requirements; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferRoute() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Card - card + /// + public static readonly CategoryEnum Card = new("card"); + + /// + /// CategoryEnum.Grants - grants + /// + public static readonly CategoryEnum Grants = new("grants"); + + /// + /// CategoryEnum.Interest - interest + /// + public static readonly CategoryEnum Interest = new("interest"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.IssuedCard - issuedCard + /// + public static readonly CategoryEnum IssuedCard = new("issuedCard"); + + /// + /// CategoryEnum.Migration - migration + /// + public static readonly CategoryEnum Migration = new("migration"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + /// + /// CategoryEnum.TopUp - topUp + /// + public static readonly CategoryEnum TopUp = new("topUp"); + + /// + /// CategoryEnum.Upgrade - upgrade + /// + public static readonly CategoryEnum Upgrade = new("upgrade"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "card" => CategoryEnum.Card, + "grants" => CategoryEnum.Grants, + "interest" => CategoryEnum.Interest, + "internal" => CategoryEnum.Internal, + "issuedCard" => CategoryEnum.IssuedCard, + "migration" => CategoryEnum.Migration, + "platformPayment" => CategoryEnum.PlatformPayment, + "topUp" => CategoryEnum.TopUp, + "upgrade" => CategoryEnum.Upgrade, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Card) + return "card"; + + if (value == CategoryEnum.Grants) + return "grants"; + + if (value == CategoryEnum.Interest) + return "interest"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.IssuedCard) + return "issuedCard"; + + if (value == CategoryEnum.Migration) + return "migration"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + if (value == CategoryEnum.TopUp) + return "topUp"; + + if (value == CategoryEnum.Upgrade) + return "upgrade"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + /// + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RequirementsOption { get; private set; } + + /// + /// A set of rules defined by clearing houses and banking partners. Your transfer request must adhere to these rules to ensure successful initiation of transfer. Based on the priority, one or more requirements may be returned. Each requirement is defined with a `type` and `description`. + /// + /// A set of rules defined by clearing houses and banking partners. Your transfer request must adhere to these rules to ensure successful initiation of transfer. Based on the priority, one or more requirements may be returned. Each requirement is defined with a `type` and `description`. + [JsonPropertyName("requirements")] + public List? Requirements { get { return this._RequirementsOption; } set { this._RequirementsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferRoute {\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Requirements: ").Append(Requirements).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferRouteJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferRoute Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option category = default; + Option country = default; + Option currency = default; + Option priority = default; + Option?> requirements = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(TransferRoute.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(TransferRoute.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "requirements": + requirements = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransferRoute(category, country, currency, priority, requirements); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferRoute transferRoute, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferRoute, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferRoute transferRoute, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferRoute._CategoryOption.IsSet && transferRoute.Category != null) + { + string? categoryRawValue = TransferRoute.CategoryEnum.ToJsonValue(transferRoute._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (transferRoute._CountryOption.IsSet) + if (transferRoute.Country != null) + writer.WriteString("country", transferRoute.Country); + + if (transferRoute._CurrencyOption.IsSet) + if (transferRoute.Currency != null) + writer.WriteString("currency", transferRoute.Currency); + + if (transferRoute._PriorityOption.IsSet && transferRoute.Priority != null) + { + string? priorityRawValue = TransferRoute.PriorityEnum.ToJsonValue(transferRoute._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (transferRoute._RequirementsOption.IsSet) + { + writer.WritePropertyName("requirements"); + JsonSerializer.Serialize(writer, transferRoute.Requirements, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferRouteRequest.cs b/Adyen/BalancePlatform/Models/TransferRouteRequest.cs new file mode 100644 index 000000000..6e2957b1e --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferRouteRequest.cs @@ -0,0 +1,549 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransferRouteRequest. + /// + public partial class TransferRouteRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier assigned to the balance platform associated with the account holder. + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). Required if `counterparty` is **transferInstrumentId**. + /// counterparty + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. > Either `counterparty` or `country` field must be provided in a transfer route request. + /// The list of priorities for the bank transfer. Priorities set the speed at which the transfer is sent and the fees that you have to pay. Multiple values can be provided. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConstructor] + public TransferRouteRequest(string balancePlatform, CategoryEnum category, string currency, Option balanceAccountId = default, Option counterparty = default, Option country = default, Option?> priorities = default) + { + BalancePlatform = balancePlatform; + Category = category; + Currency = currency; + _BalanceAccountIdOption = balanceAccountId; + _CounterpartyOption = counterparty; + _CountryOption = country; + _PrioritiesOption = priorities; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferRouteRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + /// + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. + [JsonPropertyName("category")] + public CategoryEnum Category { get; set; } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The unique identifier assigned to the balance platform associated with the account holder. + /// + /// The unique identifier assigned to the balance platform associated with the account holder. + [JsonPropertyName("balancePlatform")] + public string BalancePlatform { get; set; } + + /// + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + /// + /// The three-character ISO currency code of transfer. For example, **USD** or **EUR**. + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). Required if `counterparty` is **transferInstrumentId**. + /// + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). Required if `counterparty` is **transferInstrumentId**. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public Counterparty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. > Either `counterparty` or `country` field must be provided in a transfer route request. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the counterparty. For example, **US** or **NL**. > Either `counterparty` or `country` field must be provided in a transfer route request. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. Priorities set the speed at which the transfer is sent and the fees that you have to pay. Multiple values can be provided. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The list of priorities for the bank transfer. Priorities set the speed at which the transfer is sent and the fees that you have to pay. Multiple values can be provided. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferRouteRequest {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferRouteRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferRouteRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option category = default; + Option currency = default; + Option balanceAccountId = default; + Option counterparty = default; + Option country = default; + Option?> priorities = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(TransferRouteRequest.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!balancePlatform.IsSet) + throw new ArgumentException("Property is required for class TransferRouteRequest.", nameof(balancePlatform)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class TransferRouteRequest.", nameof(category)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class TransferRouteRequest.", nameof(currency)); + + return new TransferRouteRequest(balancePlatform.Value!, category.Value!.Value!, currency.Value!, balanceAccountId, counterparty, country, priorities); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferRouteRequest transferRouteRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferRouteRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferRouteRequest transferRouteRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferRouteRequest.BalancePlatform != null) + writer.WriteString("balancePlatform", transferRouteRequest.BalancePlatform); + + if (transferRouteRequest.Category != null) + { + string? categoryRawValue = TransferRouteRequest.CategoryEnum.ToJsonValue(transferRouteRequest.Category); + writer.WriteString("category", categoryRawValue); + } + + if (transferRouteRequest.Currency != null) + writer.WriteString("currency", transferRouteRequest.Currency); + + if (transferRouteRequest._BalanceAccountIdOption.IsSet) + if (transferRouteRequest.BalanceAccountId != null) + writer.WriteString("balanceAccountId", transferRouteRequest.BalanceAccountId); + + if (transferRouteRequest._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, transferRouteRequest.Counterparty, jsonSerializerOptions); + } + if (transferRouteRequest._CountryOption.IsSet) + if (transferRouteRequest.Country != null) + writer.WriteString("country", transferRouteRequest.Country); + + if (transferRouteRequest._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, transferRouteRequest.Priorities, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferRouteRequirementsInner.cs b/Adyen/BalancePlatform/Models/TransferRouteRequirementsInner.cs new file mode 100644 index 000000000..34c94246e --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferRouteRequirementsInner.cs @@ -0,0 +1,409 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransferRouteRequirementsInner. + /// + public partial class TransferRouteRequirementsInner : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(AdditionalBankIdentificationRequirement additionalBankIdentificationRequirement) + { + AdditionalBankIdentificationRequirement = additionalBankIdentificationRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(AddressRequirement addressRequirement) + { + AddressRequirement = addressRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(AmountMinMaxRequirement amountMinMaxRequirement) + { + AmountMinMaxRequirement = amountMinMaxRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(AmountNonZeroDecimalsRequirement amountNonZeroDecimalsRequirement) + { + AmountNonZeroDecimalsRequirement = amountNonZeroDecimalsRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(BankAccountIdentificationTypeRequirement bankAccountIdentificationTypeRequirement) + { + BankAccountIdentificationTypeRequirement = bankAccountIdentificationTypeRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(IbanAccountIdentificationRequirement ibanAccountIdentificationRequirement) + { + IbanAccountIdentificationRequirement = ibanAccountIdentificationRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(PaymentInstrumentRequirement paymentInstrumentRequirement) + { + PaymentInstrumentRequirement = paymentInstrumentRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(USInstantPayoutAddressRequirement uSInstantPayoutAddressRequirement) + { + USInstantPayoutAddressRequirement = uSInstantPayoutAddressRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(USInternationalAchAddressRequirement uSInternationalAchAddressRequirement) + { + USInternationalAchAddressRequirement = uSInternationalAchAddressRequirement; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferRouteRequirementsInner(USInternationalAchPriorityRequirement uSInternationalAchPriorityRequirement) + { + USInternationalAchPriorityRequirement = uSInternationalAchPriorityRequirement; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AdditionalBankIdentificationRequirement? AdditionalBankIdentificationRequirement { get; set; } + + /// + /// .. + /// + public AddressRequirement? AddressRequirement { get; set; } + + /// + /// .. + /// + public AmountMinMaxRequirement? AmountMinMaxRequirement { get; set; } + + /// + /// .. + /// + public AmountNonZeroDecimalsRequirement? AmountNonZeroDecimalsRequirement { get; set; } + + /// + /// .. + /// + public BankAccountIdentificationTypeRequirement? BankAccountIdentificationTypeRequirement { get; set; } + + /// + /// .. + /// + public IbanAccountIdentificationRequirement? IbanAccountIdentificationRequirement { get; set; } + + /// + /// .. + /// + public PaymentInstrumentRequirement? PaymentInstrumentRequirement { get; set; } + + /// + /// .. + /// + public USInstantPayoutAddressRequirement? USInstantPayoutAddressRequirement { get; set; } + + /// + /// .. + /// + public USInternationalAchAddressRequirement? USInternationalAchAddressRequirement { get; set; } + + /// + /// .. + /// + public USInternationalAchPriorityRequirement? USInternationalAchPriorityRequirement { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferRouteRequirementsInner {\n"); + if (this.AdditionalBankIdentificationRequirement != null) + sb.Append(AdditionalBankIdentificationRequirement.ToString().Replace("\n", "\n ")); + if (this.AddressRequirement != null) + sb.Append(AddressRequirement.ToString().Replace("\n", "\n ")); + if (this.AmountMinMaxRequirement != null) + sb.Append(AmountMinMaxRequirement.ToString().Replace("\n", "\n ")); + if (this.AmountNonZeroDecimalsRequirement != null) + sb.Append(AmountNonZeroDecimalsRequirement.ToString().Replace("\n", "\n ")); + if (this.BankAccountIdentificationTypeRequirement != null) + sb.Append(BankAccountIdentificationTypeRequirement.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentificationRequirement != null) + sb.Append(IbanAccountIdentificationRequirement.ToString().Replace("\n", "\n ")); + if (this.PaymentInstrumentRequirement != null) + sb.Append(PaymentInstrumentRequirement.ToString().Replace("\n", "\n ")); + if (this.USInstantPayoutAddressRequirement != null) + sb.Append(USInstantPayoutAddressRequirement.ToString().Replace("\n", "\n ")); + if (this.USInternationalAchAddressRequirement != null) + sb.Append(USInternationalAchAddressRequirement.ToString().Replace("\n", "\n ")); + if (this.USInternationalAchPriorityRequirement != null) + sb.Append(USInternationalAchPriorityRequirement.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferRouteRequirementsInnerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferRouteRequirementsInner Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AdditionalBankIdentificationRequirement? additionalBankIdentificationRequirement = default; + AddressRequirement? addressRequirement = default; + AmountMinMaxRequirement? amountMinMaxRequirement = default; + AmountNonZeroDecimalsRequirement? amountNonZeroDecimalsRequirement = default; + BankAccountIdentificationTypeRequirement? bankAccountIdentificationTypeRequirement = default; + IbanAccountIdentificationRequirement? ibanAccountIdentificationRequirement = default; + PaymentInstrumentRequirement? paymentInstrumentRequirement = default; + USInstantPayoutAddressRequirement? uSInstantPayoutAddressRequirement = default; + USInternationalAchAddressRequirement? uSInternationalAchAddressRequirement = default; + USInternationalAchPriorityRequirement? uSInternationalAchPriorityRequirement = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAdditionalBankIdentificationRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAdditionalBankIdentificationRequirement, jsonSerializerOptions, out additionalBankIdentificationRequirement); + + Utf8JsonReader utf8JsonReaderAddressRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAddressRequirement, jsonSerializerOptions, out addressRequirement); + + Utf8JsonReader utf8JsonReaderAmountMinMaxRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAmountMinMaxRequirement, jsonSerializerOptions, out amountMinMaxRequirement); + + Utf8JsonReader utf8JsonReaderAmountNonZeroDecimalsRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAmountNonZeroDecimalsRequirement, jsonSerializerOptions, out amountNonZeroDecimalsRequirement); + + Utf8JsonReader utf8JsonReaderBankAccountIdentificationTypeRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBankAccountIdentificationTypeRequirement, jsonSerializerOptions, out bankAccountIdentificationTypeRequirement); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentificationRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentificationRequirement, jsonSerializerOptions, out ibanAccountIdentificationRequirement); + + Utf8JsonReader utf8JsonReaderPaymentInstrumentRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPaymentInstrumentRequirement, jsonSerializerOptions, out paymentInstrumentRequirement); + + Utf8JsonReader utf8JsonReaderUSInstantPayoutAddressRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSInstantPayoutAddressRequirement, jsonSerializerOptions, out uSInstantPayoutAddressRequirement); + + Utf8JsonReader utf8JsonReaderUSInternationalAchAddressRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSInternationalAchAddressRequirement, jsonSerializerOptions, out uSInternationalAchAddressRequirement); + + Utf8JsonReader utf8JsonReaderUSInternationalAchPriorityRequirement = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSInternationalAchPriorityRequirement, jsonSerializerOptions, out uSInternationalAchPriorityRequirement); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (additionalBankIdentificationRequirement?.Type != null) + return new TransferRouteRequirementsInner(additionalBankIdentificationRequirement); + + if (addressRequirement?.Type != null) + return new TransferRouteRequirementsInner(addressRequirement); + + if (amountMinMaxRequirement?.Type != null) + return new TransferRouteRequirementsInner(amountMinMaxRequirement); + + if (amountNonZeroDecimalsRequirement?.Type != null) + return new TransferRouteRequirementsInner(amountNonZeroDecimalsRequirement); + + if (bankAccountIdentificationTypeRequirement?.Type != null) + return new TransferRouteRequirementsInner(bankAccountIdentificationTypeRequirement); + + if (ibanAccountIdentificationRequirement?.Type != null) + return new TransferRouteRequirementsInner(ibanAccountIdentificationRequirement); + + if (paymentInstrumentRequirement?.Type != null) + return new TransferRouteRequirementsInner(paymentInstrumentRequirement); + + if (uSInstantPayoutAddressRequirement?.Type != null) + return new TransferRouteRequirementsInner(uSInstantPayoutAddressRequirement); + + if (uSInternationalAchAddressRequirement?.Type != null) + return new TransferRouteRequirementsInner(uSInternationalAchAddressRequirement); + + if (uSInternationalAchPriorityRequirement?.Type != null) + return new TransferRouteRequirementsInner(uSInternationalAchPriorityRequirement); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferRouteRequirementsInner transferRouteRequirementsInner, JsonSerializerOptions jsonSerializerOptions) + { + if (transferRouteRequirementsInner.AdditionalBankIdentificationRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.AdditionalBankIdentificationRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.AddressRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.AddressRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.AmountMinMaxRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.AmountMinMaxRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.AmountNonZeroDecimalsRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.AmountNonZeroDecimalsRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.BankAccountIdentificationTypeRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.BankAccountIdentificationTypeRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.IbanAccountIdentificationRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.IbanAccountIdentificationRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.PaymentInstrumentRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.PaymentInstrumentRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.USInstantPayoutAddressRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.USInstantPayoutAddressRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.USInternationalAchAddressRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.USInternationalAchAddressRequirement, jsonSerializerOptions); + if (transferRouteRequirementsInner.USInternationalAchPriorityRequirement != null) + JsonSerializer.Serialize(writer, transferRouteRequirementsInner.USInternationalAchPriorityRequirement, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferRouteRequirementsInner, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferRouteRequirementsInner transferRouteRequirementsInner, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferRouteResponse.cs b/Adyen/BalancePlatform/Models/TransferRouteResponse.cs new file mode 100644 index 000000000..da3c2c79c --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferRouteResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// TransferRouteResponse. + /// + public partial class TransferRouteResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of available priorities for a transfer, along with requirements. Use this information to initiate a transfer. + [JsonConstructor] + public TransferRouteResponse(Option?> transferRoutes = default) + { + _TransferRoutesOption = transferRoutes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferRouteResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferRoutesOption { get; private set; } + + /// + /// List of available priorities for a transfer, along with requirements. Use this information to initiate a transfer. + /// + /// List of available priorities for a transfer, along with requirements. Use this information to initiate a transfer. + [JsonPropertyName("transferRoutes")] + public List? TransferRoutes { get { return this._TransferRoutesOption; } set { this._TransferRoutesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferRouteResponse {\n"); + sb.Append(" TransferRoutes: ").Append(TransferRoutes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferRouteResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferRouteResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transferRoutes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferRoutes": + transferRoutes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransferRouteResponse(transferRoutes); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferRouteResponse transferRouteResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferRouteResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferRouteResponse transferRouteResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferRouteResponse._TransferRoutesOption.IsSet) + { + writer.WritePropertyName("transferRoutes"); + JsonSerializer.Serialize(writer, transferRouteResponse.TransferRoutes, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/TransferType.cs b/Adyen/BalancePlatform/Models/TransferType.cs new file mode 100644 index 000000000..d8ef84606 --- /dev/null +++ b/Adyen/BalancePlatform/Models/TransferType.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. + /// + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. + public enum TransferType + { + /// + /// Enum Instant for value: instant + /// + Instant = 1, + + /// + /// Enum All for value: all + /// + All = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class TransferTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TransferType FromString(string value) + { + if (value.Equals("instant")) + return TransferType.Instant; + + if (value.Equals("all")) + return TransferType.All; + + throw new NotImplementedException($"Could not convert value to type TransferType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TransferType? FromStringOrDefault(string value) + { + if (value.Equals("instant")) + return TransferType.Instant; + + if (value.Equals("all")) + return TransferType.All; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TransferType value) + { + if (value == TransferType.Instant) + return "instant"; + + if (value == TransferType.All) + return "all"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TransferTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TransferType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TransferType? result = rawValue == null + ? null + : TransferTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TransferType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferType transferType, JsonSerializerOptions options) + { + writer.WriteStringValue(TransferTypeValueConverter.ToJsonValue(transferType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TransferTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a TransferType from the Json object + /// + /// + /// + /// + /// + public override TransferType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TransferType? result = rawValue == null + ? null + : TransferTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TransferType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferType? transferType, JsonSerializerOptions options) + { + writer.WriteStringValue(transferType.HasValue ? TransferTypeValueConverter.ToJsonValue(transferType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/BalancePlatform/Models/UKLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/UKLocalAccountIdentification.cs new file mode 100644 index 000000000..dc968b6ef --- /dev/null +++ b/Adyen/BalancePlatform/Models/UKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// UKLocalAccountIdentification. + /// + public partial class UKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 8-digit bank account number, without separators or whitespace. + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **ukLocal** (default to TypeEnum.UkLocal) + [JsonConstructor] + public UKLocalAccountIdentification(string accountNumber, string sortCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + SortCode = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UkLocal - ukLocal + /// + public static readonly TypeEnum UkLocal = new("ukLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ukLocal" => TypeEnum.UkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UkLocal) + return "ukLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 8-digit bank account number, without separators or whitespace. + /// + /// The 8-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string SortCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 8.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 8.", new [] { "AccountNumber" }); + } + + // SortCode (string) maxLength + if (this.SortCode != null && this.SortCode.Length > 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be less than 6.", new [] { "SortCode" }); + } + + // SortCode (string) minLength + if (this.SortCode != null && this.SortCode.Length < 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be greater than 6.", new [] { "SortCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(accountNumber)); + + if (!sortCode.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(sortCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(type)); + + return new UKLocalAccountIdentification(accountNumber.Value!, sortCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uKLocalAccountIdentification.AccountNumber); + + if (uKLocalAccountIdentification.SortCode != null) + writer.WriteString("sortCode", uKLocalAccountIdentification.SortCode); + + if (uKLocalAccountIdentification.Type != null) + { + string? typeRawValue = UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/USInstantPayoutAddressRequirement.cs b/Adyen/BalancePlatform/Models/USInstantPayoutAddressRequirement.cs new file mode 100644 index 000000000..f28aa129f --- /dev/null +++ b/Adyen/BalancePlatform/Models/USInstantPayoutAddressRequirement.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// USInstantPayoutAddressRequirement. + /// + public partial class USInstantPayoutAddressRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies that you must provide complete street addresses for the party and counterParty for transactions greater than USD 3000. + /// **usInstantPayoutAddressRequirement** (default to TypeEnum.UsInstantPayoutAddressRequirement) + [JsonConstructor] + public USInstantPayoutAddressRequirement(Option description = default, TypeEnum type = default) + { + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USInstantPayoutAddressRequirement() + { + } + + partial void OnCreated(); + + /// + /// **usInstantPayoutAddressRequirement** + /// + /// **usInstantPayoutAddressRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsInstantPayoutAddressRequirement - usInstantPayoutAddressRequirement + /// + public static readonly TypeEnum UsInstantPayoutAddressRequirement = new("usInstantPayoutAddressRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usInstantPayoutAddressRequirement" => TypeEnum.UsInstantPayoutAddressRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsInstantPayoutAddressRequirement) + return "usInstantPayoutAddressRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usInstantPayoutAddressRequirement** + /// + /// **usInstantPayoutAddressRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies that you must provide complete street addresses for the party and counterParty for transactions greater than USD 3000. + /// + /// Specifies that you must provide complete street addresses for the party and counterParty for transactions greater than USD 3000. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USInstantPayoutAddressRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USInstantPayoutAddressRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USInstantPayoutAddressRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USInstantPayoutAddressRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USInstantPayoutAddressRequirement.", nameof(type)); + + return new USInstantPayoutAddressRequirement(description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USInstantPayoutAddressRequirement uSInstantPayoutAddressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSInstantPayoutAddressRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USInstantPayoutAddressRequirement uSInstantPayoutAddressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSInstantPayoutAddressRequirement._DescriptionOption.IsSet) + if (uSInstantPayoutAddressRequirement.Description != null) + writer.WriteString("description", uSInstantPayoutAddressRequirement.Description); + + if (uSInstantPayoutAddressRequirement.Type != null) + { + string? typeRawValue = USInstantPayoutAddressRequirement.TypeEnum.ToJsonValue(uSInstantPayoutAddressRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/USInternationalAchAddressRequirement.cs b/Adyen/BalancePlatform/Models/USInternationalAchAddressRequirement.cs new file mode 100644 index 000000000..46a03949b --- /dev/null +++ b/Adyen/BalancePlatform/Models/USInternationalAchAddressRequirement.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// USInternationalAchAddressRequirement. + /// + public partial class USInternationalAchAddressRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies that you must provide a complete street address for International ACH (IAT) transactions. + /// **usInternationalAchAddressRequirement** (default to TypeEnum.UsInternationalAchAddressRequirement) + [JsonConstructor] + public USInternationalAchAddressRequirement(Option description = default, TypeEnum type = default) + { + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USInternationalAchAddressRequirement() + { + } + + partial void OnCreated(); + + /// + /// **usInternationalAchAddressRequirement** + /// + /// **usInternationalAchAddressRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsInternationalAchAddressRequirement - usInternationalAchAddressRequirement + /// + public static readonly TypeEnum UsInternationalAchAddressRequirement = new("usInternationalAchAddressRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usInternationalAchAddressRequirement" => TypeEnum.UsInternationalAchAddressRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsInternationalAchAddressRequirement) + return "usInternationalAchAddressRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usInternationalAchAddressRequirement** + /// + /// **usInternationalAchAddressRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies that you must provide a complete street address for International ACH (IAT) transactions. + /// + /// Specifies that you must provide a complete street address for International ACH (IAT) transactions. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USInternationalAchAddressRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USInternationalAchAddressRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USInternationalAchAddressRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USInternationalAchAddressRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USInternationalAchAddressRequirement.", nameof(type)); + + return new USInternationalAchAddressRequirement(description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USInternationalAchAddressRequirement uSInternationalAchAddressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSInternationalAchAddressRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USInternationalAchAddressRequirement uSInternationalAchAddressRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSInternationalAchAddressRequirement._DescriptionOption.IsSet) + if (uSInternationalAchAddressRequirement.Description != null) + writer.WriteString("description", uSInternationalAchAddressRequirement.Description); + + if (uSInternationalAchAddressRequirement.Type != null) + { + string? typeRawValue = USInternationalAchAddressRequirement.TypeEnum.ToJsonValue(uSInternationalAchAddressRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/USInternationalAchPriorityRequirement.cs b/Adyen/BalancePlatform/Models/USInternationalAchPriorityRequirement.cs new file mode 100644 index 000000000..859fe471c --- /dev/null +++ b/Adyen/BalancePlatform/Models/USInternationalAchPriorityRequirement.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// USInternationalAchPriorityRequirement. + /// + public partial class USInternationalAchPriorityRequirement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies that transactions deemed to be International ACH (IAT) per OFAC/NACHA rules cannot have fast priority. + /// **usInternationalAchPriorityRequirement** (default to TypeEnum.UsInternationalAchPriorityRequirement) + [JsonConstructor] + public USInternationalAchPriorityRequirement(Option description = default, TypeEnum type = default) + { + _DescriptionOption = description; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USInternationalAchPriorityRequirement() + { + } + + partial void OnCreated(); + + /// + /// **usInternationalAchPriorityRequirement** + /// + /// **usInternationalAchPriorityRequirement** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsInternationalAchPriorityRequirement - usInternationalAchPriorityRequirement + /// + public static readonly TypeEnum UsInternationalAchPriorityRequirement = new("usInternationalAchPriorityRequirement"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usInternationalAchPriorityRequirement" => TypeEnum.UsInternationalAchPriorityRequirement, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsInternationalAchPriorityRequirement) + return "usInternationalAchPriorityRequirement"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usInternationalAchPriorityRequirement** + /// + /// **usInternationalAchPriorityRequirement** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Specifies that transactions deemed to be International ACH (IAT) per OFAC/NACHA rules cannot have fast priority. + /// + /// Specifies that transactions deemed to be International ACH (IAT) per OFAC/NACHA rules cannot have fast priority. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USInternationalAchPriorityRequirement {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USInternationalAchPriorityRequirementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USInternationalAchPriorityRequirement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USInternationalAchPriorityRequirement.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USInternationalAchPriorityRequirement.", nameof(type)); + + return new USInternationalAchPriorityRequirement(description, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USInternationalAchPriorityRequirement uSInternationalAchPriorityRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSInternationalAchPriorityRequirement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USInternationalAchPriorityRequirement uSInternationalAchPriorityRequirement, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSInternationalAchPriorityRequirement._DescriptionOption.IsSet) + if (uSInternationalAchPriorityRequirement.Description != null) + writer.WriteString("description", uSInternationalAchPriorityRequirement.Description); + + if (uSInternationalAchPriorityRequirement.Type != null) + { + string? typeRawValue = USInternationalAchPriorityRequirement.TypeEnum.ToJsonValue(uSInternationalAchPriorityRequirement.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/USLocalAccountIdentification.cs b/Adyen/BalancePlatform/Models/USLocalAccountIdentification.cs new file mode 100644 index 000000000..40e552a76 --- /dev/null +++ b/Adyen/BalancePlatform/Models/USLocalAccountIdentification.cs @@ -0,0 +1,464 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// USLocalAccountIdentification. + /// + public partial class USLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **usLocal** (default to TypeEnum.UsLocal) + [JsonConstructor] + public USLocalAccountIdentification(string accountNumber, string routingNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + RoutingNumber = routingNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsLocal - usLocal + /// + public static readonly TypeEnum UsLocal = new("usLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usLocal" => TypeEnum.UsLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsLocal) + return "usLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string RoutingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 18) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 18.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // RoutingNumber (string) maxLength + if (this.RoutingNumber != null && this.RoutingNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be less than 9.", new [] { "RoutingNumber" }); + } + + // RoutingNumber (string) minLength + if (this.RoutingNumber != null && this.RoutingNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be greater than 9.", new [] { "RoutingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option routingNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(USLocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(accountNumber)); + + if (!routingNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(routingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(type)); + + return new USLocalAccountIdentification(accountNumber.Value!, routingNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uSLocalAccountIdentification.AccountNumber); + + if (uSLocalAccountIdentification.RoutingNumber != null) + writer.WriteString("routingNumber", uSLocalAccountIdentification.RoutingNumber); + + if (uSLocalAccountIdentification._AccountTypeOption.IsSet && uSLocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (uSLocalAccountIdentification.Type != null) + { + string? typeRawValue = USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/UpdateNetworkTokenRequest.cs b/Adyen/BalancePlatform/Models/UpdateNetworkTokenRequest.cs new file mode 100644 index 000000000..7a8deb5e3 --- /dev/null +++ b/Adyen/BalancePlatform/Models/UpdateNetworkTokenRequest.cs @@ -0,0 +1,292 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// UpdateNetworkTokenRequest. + /// + public partial class UpdateNetworkTokenRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The new status of the network token. Possible values: **active**, **suspended**, **closed**. The **closed** status is final and cannot be changed. + [JsonConstructor] + public UpdateNetworkTokenRequest(Option status = default) + { + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateNetworkTokenRequest() + { + } + + partial void OnCreated(); + + /// + /// The new status of the network token. Possible values: **active**, **suspended**, **closed**. The **closed** status is final and cannot be changed. + /// + /// The new status of the network token. Possible values: **active**, **suspended**, **closed**. The **closed** status is final and cannot be changed. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "suspended" => StatusEnum.Suspended, + "closed" => StatusEnum.Closed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + if (value == StatusEnum.Closed) + return "closed"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The new status of the network token. Possible values: **active**, **suspended**, **closed**. The **closed** status is final and cannot be changed. + /// + /// The new status of the network token. Possible values: **active**, **suspended**, **closed**. The **closed** status is final and cannot be changed. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateNetworkTokenRequest {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateNetworkTokenRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateNetworkTokenRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(UpdateNetworkTokenRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new UpdateNetworkTokenRequest(status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateNetworkTokenRequest updateNetworkTokenRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateNetworkTokenRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateNetworkTokenRequest updateNetworkTokenRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateNetworkTokenRequest._StatusOption.IsSet && updateNetworkTokenRequest.Status != null) + { + string? statusRawValue = UpdateNetworkTokenRequest.StatusEnum.ToJsonValue(updateNetworkTokenRequest._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/UpdatePaymentInstrument.cs b/Adyen/BalancePlatform/Models/UpdatePaymentInstrument.cs new file mode 100644 index 000000000..0735fcafa --- /dev/null +++ b/Adyen/BalancePlatform/Models/UpdatePaymentInstrument.cs @@ -0,0 +1,920 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// UpdatePaymentInstrument. + /// + public partial class UpdatePaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// The unique identifier of the payment instrument. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// bankAccount + /// card + /// Your description for the payment instrument, maximum 300 characters. + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// Your reference for the payment instrument, maximum 150 characters. + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConstructor] + public UpdatePaymentInstrument(string balanceAccountId, string id, string issuingCountryCode, TypeEnum type, Option?> additionalBankAccountIdentifications = default, Option bankAccount = default, Option card = default, Option description = default, Option paymentInstrumentGroupId = default, Option reference = default, Option replacedById = default, Option replacementOfId = default, Option status = default, Option statusComment = default, Option statusReason = default) + { + BalanceAccountId = balanceAccountId; + Id = id; + IssuingCountryCode = issuingCountryCode; + Type = type; + _AdditionalBankAccountIdentificationsOption = additionalBankAccountIdentifications; + _BankAccountOption = bankAccount; + _CardOption = card; + _DescriptionOption = description; + _PaymentInstrumentGroupIdOption = paymentInstrumentGroupId; + _ReferenceOption = reference; + _ReplacedByIdOption = replacedById; + _ReplacementOfIdOption = replacementOfId; + _StatusOption = status; + _StatusCommentOption = statusComment; + _StatusReasonOption = statusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdatePaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "card" => TypeEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.Card) + return "card"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConverter(typeof(StatusReasonEnumJsonConverter))] + public class StatusReasonEnum : IEnum + { + /// + /// Returns the value of the StatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// StatusReasonEnum.AccountClosure - accountClosure + /// + public static readonly StatusReasonEnum AccountClosure = new("accountClosure"); + + /// + /// StatusReasonEnum.Damaged - damaged + /// + public static readonly StatusReasonEnum Damaged = new("damaged"); + + /// + /// StatusReasonEnum.EndOfLife - endOfLife + /// + public static readonly StatusReasonEnum EndOfLife = new("endOfLife"); + + /// + /// StatusReasonEnum.Expired - expired + /// + public static readonly StatusReasonEnum Expired = new("expired"); + + /// + /// StatusReasonEnum.Lost - lost + /// + public static readonly StatusReasonEnum Lost = new("lost"); + + /// + /// StatusReasonEnum.Other - other + /// + public static readonly StatusReasonEnum Other = new("other"); + + /// + /// StatusReasonEnum.Stolen - stolen + /// + public static readonly StatusReasonEnum Stolen = new("stolen"); + + /// + /// StatusReasonEnum.SuspectedFraud - suspectedFraud + /// + public static readonly StatusReasonEnum SuspectedFraud = new("suspectedFraud"); + + /// + /// StatusReasonEnum.TransactionRule - transactionRule + /// + public static readonly StatusReasonEnum TransactionRule = new("transactionRule"); + + private StatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusReasonEnum?(string? value) => value == null ? null : new StatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusReasonEnum? option) => option?.Value; + + public static bool operator ==(StatusReasonEnum? left, StatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusReasonEnum? left, StatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountClosure" => StatusReasonEnum.AccountClosure, + "damaged" => StatusReasonEnum.Damaged, + "endOfLife" => StatusReasonEnum.EndOfLife, + "expired" => StatusReasonEnum.Expired, + "lost" => StatusReasonEnum.Lost, + "other" => StatusReasonEnum.Other, + "stolen" => StatusReasonEnum.Stolen, + "suspectedFraud" => StatusReasonEnum.SuspectedFraud, + "transactionRule" => StatusReasonEnum.TransactionRule, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == StatusReasonEnum.AccountClosure) + return "accountClosure"; + + if (value == StatusReasonEnum.Damaged) + return "damaged"; + + if (value == StatusReasonEnum.EndOfLife) + return "endOfLife"; + + if (value == StatusReasonEnum.Expired) + return "expired"; + + if (value == StatusReasonEnum.Lost) + return "lost"; + + if (value == StatusReasonEnum.Other) + return "other"; + + if (value == StatusReasonEnum.Stolen) + return "stolen"; + + if (value == StatusReasonEnum.SuspectedFraud) + return "suspectedFraud"; + + if (value == StatusReasonEnum.TransactionRule) + return "transactionRule"; + + return null; + } + + /// + /// JsonConverter for writing StatusReasonEnum. + /// + public class StatusReasonEnumJsonConverter : JsonConverter + { + public override StatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusReasonEnum.FromStringOrDefault(value) ?? new StatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusReasonOption { get; private set; } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonPropertyName("statusReason")] + public StatusReasonEnum? StatusReason { get { return this._StatusReasonOption; } set { this._StatusReasonOption = new(value); } } + + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// The unique identifier of the payment instrument. + /// + /// The unique identifier of the payment instrument. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + [JsonPropertyName("issuingCountryCode")] + public string IssuingCountryCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalBankAccountIdentificationsOption { get; private set; } + + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + [JsonPropertyName("additionalBankAccountIdentifications")] + [Obsolete("Deprecated since Configuration API v2. Please use `bankAccount` object instead")] + public List? AdditionalBankAccountIdentifications { get { return this._AdditionalBankAccountIdentificationsOption; } set { this._AdditionalBankAccountIdentificationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountDetails? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument, maximum 300 characters. + /// + /// Your description for the payment instrument, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentGroupIdOption { get; private set; } + + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + [JsonPropertyName("paymentInstrumentGroupId")] + public string? PaymentInstrumentGroupId { get { return this._PaymentInstrumentGroupIdOption; } set { this._PaymentInstrumentGroupIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument, maximum 150 characters. + /// + /// Your reference for the payment instrument, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacedByIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + [JsonPropertyName("replacedById")] + public string? ReplacedById { get { return this._ReplacedByIdOption; } set { this._ReplacedByIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacementOfIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + [JsonPropertyName("replacementOfId")] + public string? ReplacementOfId { get { return this._ReplacementOfIdOption; } set { this._ReplacementOfIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusCommentOption { get; private set; } + + /// + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + /// + /// Comment for the status of the payment instrument. Required if `statusReason` is **other**. + [JsonPropertyName("statusComment")] + public string? StatusComment { get { return this._StatusCommentOption; } set { this._StatusCommentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdatePaymentInstrument {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalBankAccountIdentifications: ").Append(AdditionalBankAccountIdentifications).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrumentGroupId: ").Append(PaymentInstrumentGroupId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReplacedById: ").Append(ReplacedById).Append("\n"); + sb.Append(" ReplacementOfId: ").Append(ReplacementOfId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); + sb.Append(" StatusReason: ").Append(StatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdatePaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdatePaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option id = default; + Option issuingCountryCode = default; + Option type = default; + Option?> additionalBankAccountIdentifications = default; + Option bankAccount = default; + Option card = default; + Option description = default; + Option paymentInstrumentGroupId = default; + Option reference = default; + Option replacedById = default; + Option replacementOfId = default; + Option status = default; + Option statusComment = default; + Option statusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UpdatePaymentInstrument.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "additionalBankAccountIdentifications": + additionalBankAccountIdentifications = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentGroupId": + paymentInstrumentGroupId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "replacedById": + replacedById = new Option(utf8JsonReader.GetString()!); + break; + case "replacementOfId": + replacementOfId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(UpdatePaymentInstrument.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "statusComment": + statusComment = new Option(utf8JsonReader.GetString()!); + break; + case "statusReason": + string? statusReasonRawValue = utf8JsonReader.GetString(); + statusReason = new Option(UpdatePaymentInstrument.StatusReasonEnum.FromStringOrDefault(statusReasonRawValue)); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class UpdatePaymentInstrument.", nameof(balanceAccountId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class UpdatePaymentInstrument.", nameof(id)); + + if (!issuingCountryCode.IsSet) + throw new ArgumentException("Property is required for class UpdatePaymentInstrument.", nameof(issuingCountryCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UpdatePaymentInstrument.", nameof(type)); + + return new UpdatePaymentInstrument(balanceAccountId.Value!, id.Value!, issuingCountryCode.Value!, type.Value!.Value!, additionalBankAccountIdentifications, bankAccount, card, description, paymentInstrumentGroupId, reference, replacedById, replacementOfId, status, statusComment, statusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdatePaymentInstrument updatePaymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updatePaymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdatePaymentInstrument updatePaymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (updatePaymentInstrument.BalanceAccountId != null) + writer.WriteString("balanceAccountId", updatePaymentInstrument.BalanceAccountId); + + if (updatePaymentInstrument.Id != null) + writer.WriteString("id", updatePaymentInstrument.Id); + + if (updatePaymentInstrument.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", updatePaymentInstrument.IssuingCountryCode); + + if (updatePaymentInstrument.Type != null) + { + string? typeRawValue = UpdatePaymentInstrument.TypeEnum.ToJsonValue(updatePaymentInstrument.Type); + writer.WriteString("type", typeRawValue); + } + + if (updatePaymentInstrument._AdditionalBankAccountIdentificationsOption.IsSet) + { + writer.WritePropertyName("additionalBankAccountIdentifications"); + JsonSerializer.Serialize(writer, updatePaymentInstrument.AdditionalBankAccountIdentifications, jsonSerializerOptions); + } + if (updatePaymentInstrument._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, updatePaymentInstrument.BankAccount, jsonSerializerOptions); + } + if (updatePaymentInstrument._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, updatePaymentInstrument.Card, jsonSerializerOptions); + } + if (updatePaymentInstrument._DescriptionOption.IsSet) + if (updatePaymentInstrument.Description != null) + writer.WriteString("description", updatePaymentInstrument.Description); + + if (updatePaymentInstrument._PaymentInstrumentGroupIdOption.IsSet) + if (updatePaymentInstrument.PaymentInstrumentGroupId != null) + writer.WriteString("paymentInstrumentGroupId", updatePaymentInstrument.PaymentInstrumentGroupId); + + if (updatePaymentInstrument._ReferenceOption.IsSet) + if (updatePaymentInstrument.Reference != null) + writer.WriteString("reference", updatePaymentInstrument.Reference); + + if (updatePaymentInstrument._ReplacedByIdOption.IsSet) + if (updatePaymentInstrument.ReplacedById != null) + writer.WriteString("replacedById", updatePaymentInstrument.ReplacedById); + + if (updatePaymentInstrument._ReplacementOfIdOption.IsSet) + if (updatePaymentInstrument.ReplacementOfId != null) + writer.WriteString("replacementOfId", updatePaymentInstrument.ReplacementOfId); + + if (updatePaymentInstrument._StatusOption.IsSet && updatePaymentInstrument.Status != null) + { + string? statusRawValue = UpdatePaymentInstrument.StatusEnum.ToJsonValue(updatePaymentInstrument._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (updatePaymentInstrument._StatusCommentOption.IsSet) + if (updatePaymentInstrument.StatusComment != null) + writer.WriteString("statusComment", updatePaymentInstrument.StatusComment); + + if (updatePaymentInstrument._StatusReasonOption.IsSet && updatePaymentInstrument.StatusReason != null) + { + string? statusReasonRawValue = UpdatePaymentInstrument.StatusReasonEnum.ToJsonValue(updatePaymentInstrument._StatusReasonOption.Value!.Value); + writer.WriteString("statusReason", statusReasonRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/UpdateSweepConfigurationV2.cs b/Adyen/BalancePlatform/Models/UpdateSweepConfigurationV2.cs new file mode 100644 index 000000000..c60016ef0 --- /dev/null +++ b/Adyen/BalancePlatform/Models/UpdateSweepConfigurationV2.cs @@ -0,0 +1,1343 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// UpdateSweepConfigurationV2. + /// + public partial class UpdateSweepConfigurationV2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// counterparty + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// The unique identifier of the sweep. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The reason for disabling the sweep. + /// The human readable reason for disabling the sweep. + /// Your reference for the sweep configuration. + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// schedule + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// sweepAmount + /// targetAmount + /// triggerAmount + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. (default to TypeEnum.Push) + [JsonConstructor] + public UpdateSweepConfigurationV2(Option category = default, Option counterparty = default, Option currency = default, Option description = default, Option id = default, Option?> priorities = default, Option reason = default, Option reasonDetail = default, Option reference = default, Option referenceForBeneficiary = default, Option schedule = default, Option status = default, Option sweepAmount = default, Option targetAmount = default, Option triggerAmount = default, Option type = default) + { + _CategoryOption = category; + _CounterpartyOption = counterparty; + _CurrencyOption = currency; + _DescriptionOption = description; + _IdOption = id; + _PrioritiesOption = priorities; + _ReasonOption = reason; + _ReasonDetailOption = reasonDetail; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _ScheduleOption = schedule; + _StatusOption = status; + _SweepAmountOption = sweepAmount; + _TargetAmountOption = targetAmount; + _TriggerAmountOption = triggerAmount; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateSweepConfigurationV2() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "internal" => CategoryEnum.Internal, + "platformPayment" => CategoryEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Pull - pull + /// + public static readonly TypeEnum Pull = new("pull"); + + /// + /// TypeEnum.Push - push + /// + public static readonly TypeEnum Push = new("push"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pull" => TypeEnum.Pull, + "push" => TypeEnum.Push, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Pull) + return "pull"; + + if (value == TypeEnum.Push) + return "push"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public SweepCounterparty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// The unique identifier of the sweep. + /// + /// The unique identifier of the sweep. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonDetailOption { get; } + + /// + /// The human readable reason for disabling the sweep. + /// + /// The human readable reason for disabling the sweep. + [JsonPropertyName("reasonDetail")] + public string? ReasonDetail { get { return this._ReasonDetailOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the sweep configuration. + /// + /// Your reference for the sweep configuration. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScheduleOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("schedule")] + public SweepSchedule? Schedule { get { return this._ScheduleOption; } set { this._ScheduleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SweepAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sweepAmount")] + public Amount? SweepAmount { get { return this._SweepAmountOption; } set { this._SweepAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("targetAmount")] + public Amount? TargetAmount { get { return this._TargetAmountOption; } set { this._TargetAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TriggerAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("triggerAmount")] + public Amount? TriggerAmount { get { return this._TriggerAmountOption; } set { this._TriggerAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateSweepConfigurationV2 {\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" ReasonDetail: ").Append(ReasonDetail).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Schedule: ").Append(Schedule).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SweepAmount: ").Append(SweepAmount).Append("\n"); + sb.Append(" TargetAmount: ").Append(TargetAmount).Append("\n"); + sb.Append(" TriggerAmount: ").Append(TriggerAmount).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + // ReferenceForBeneficiary (string) maxLength + if (this.ReferenceForBeneficiary != null && this.ReferenceForBeneficiary.Length > 80) + { + yield return new ValidationResult("Invalid value for ReferenceForBeneficiary, length must be less than 80.", new [] { "ReferenceForBeneficiary" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateSweepConfigurationV2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateSweepConfigurationV2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option category = default; + Option counterparty = default; + Option currency = default; + Option description = default; + Option id = default; + Option?> priorities = default; + Option reason = default; + Option reasonDetail = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option schedule = default; + Option status = default; + Option sweepAmount = default; + Option targetAmount = default; + Option triggerAmount = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(UpdateSweepConfigurationV2.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(UpdateSweepConfigurationV2.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reasonDetail": + reasonDetail = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "schedule": + schedule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(UpdateSweepConfigurationV2.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "sweepAmount": + sweepAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "targetAmount": + targetAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "triggerAmount": + triggerAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UpdateSweepConfigurationV2.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new UpdateSweepConfigurationV2(category, counterparty, currency, description, id, priorities, reason, reasonDetail, reference, referenceForBeneficiary, schedule, status, sweepAmount, targetAmount, triggerAmount, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateSweepConfigurationV2 updateSweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateSweepConfigurationV2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateSweepConfigurationV2 updateSweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateSweepConfigurationV2._CategoryOption.IsSet && updateSweepConfigurationV2.Category != null) + { + string? categoryRawValue = UpdateSweepConfigurationV2.CategoryEnum.ToJsonValue(updateSweepConfigurationV2._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (updateSweepConfigurationV2._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.Counterparty, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._CurrencyOption.IsSet) + if (updateSweepConfigurationV2.Currency != null) + writer.WriteString("currency", updateSweepConfigurationV2.Currency); + + if (updateSweepConfigurationV2._DescriptionOption.IsSet) + if (updateSweepConfigurationV2.Description != null) + writer.WriteString("description", updateSweepConfigurationV2.Description); + + if (updateSweepConfigurationV2._IdOption.IsSet) + if (updateSweepConfigurationV2.Id != null) + writer.WriteString("id", updateSweepConfigurationV2.Id); + + if (updateSweepConfigurationV2._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.Priorities, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._ReasonOption.IsSet && updateSweepConfigurationV2.Reason != null) + { + string? reasonRawValue = UpdateSweepConfigurationV2.ReasonEnum.ToJsonValue(updateSweepConfigurationV2._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (updateSweepConfigurationV2._ReasonDetailOption.IsSet) + if (updateSweepConfigurationV2.ReasonDetail != null) + writer.WriteString("reasonDetail", updateSweepConfigurationV2.ReasonDetail); + + if (updateSweepConfigurationV2._ReferenceOption.IsSet) + if (updateSweepConfigurationV2.Reference != null) + writer.WriteString("reference", updateSweepConfigurationV2.Reference); + + if (updateSweepConfigurationV2._ReferenceForBeneficiaryOption.IsSet) + if (updateSweepConfigurationV2.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", updateSweepConfigurationV2.ReferenceForBeneficiary); + + if (updateSweepConfigurationV2._ScheduleOption.IsSet) + { + writer.WritePropertyName("schedule"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.Schedule, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._StatusOption.IsSet && updateSweepConfigurationV2.Status != null) + { + string? statusRawValue = UpdateSweepConfigurationV2.StatusEnum.ToJsonValue(updateSweepConfigurationV2._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (updateSweepConfigurationV2._SweepAmountOption.IsSet) + { + writer.WritePropertyName("sweepAmount"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.SweepAmount, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._TargetAmountOption.IsSet) + { + writer.WritePropertyName("targetAmount"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.TargetAmount, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._TriggerAmountOption.IsSet) + { + writer.WritePropertyName("triggerAmount"); + JsonSerializer.Serialize(writer, updateSweepConfigurationV2.TriggerAmount, jsonSerializerOptions); + } + if (updateSweepConfigurationV2._TypeOption.IsSet && updateSweepConfigurationV2.Type != null) + { + string? typeRawValue = UpdateSweepConfigurationV2.TypeEnum.ToJsonValue(updateSweepConfigurationV2._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/VerificationDeadline.cs b/Adyen/BalancePlatform/Models/VerificationDeadline.cs new file mode 100644 index 000000000..98c2d0719 --- /dev/null +++ b/Adyen/BalancePlatform/Models/VerificationDeadline.cs @@ -0,0 +1,800 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// VerificationDeadline. + /// + public partial class VerificationDeadline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The names of the capabilities to be disallowed. + /// The date that verification is due by before capabilities are disallowed. + /// The unique identifiers of the bank account(s) that the deadline applies to + [JsonConstructor] + internal VerificationDeadline(List capabilities, DateTimeOffset expiresAt, Option?> entityIds = default) + { + Capabilities = capabilities; + ExpiresAt = expiresAt; + _EntityIdsOption = entityIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + internal VerificationDeadline() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The names of the capabilities to be disallowed. + /// + /// The names of the capabilities to be disallowed. + [JsonPropertyName("capabilities")] + public List Capabilities { get; } + + /// + /// The date that verification is due by before capabilities are disallowed. + /// + /// The date that verification is due by before capabilities are disallowed. + [JsonPropertyName("expiresAt")] + public DateTimeOffset ExpiresAt { get; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityIdsOption { get; } + + /// + /// The unique identifiers of the bank account(s) that the deadline applies to + /// + /// The unique identifiers of the bank account(s) that the deadline applies to + [JsonPropertyName("entityIds")] + public List? EntityIds { get { return this._EntityIdsOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationDeadline {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" EntityIds: ").Append(EntityIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationDeadlineJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationDeadline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option expiresAt = default; + Option?> entityIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityIds": + entityIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!capabilities.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(capabilities)); + + if (!expiresAt.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(expiresAt)); + + return new VerificationDeadline(capabilities.Value!, expiresAt.Value!.Value!, entityIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationDeadline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationDeadline.Capabilities, jsonSerializerOptions); + writer.WriteString("expiresAt", verificationDeadline.ExpiresAt.ToString(ExpiresAtFormat)); + + if (verificationDeadline._EntityIdsOption.IsSet) + { + writer.WritePropertyName("entityIds"); + JsonSerializer.Serialize(writer, verificationDeadline.EntityIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/VerificationError.cs b/Adyen/BalancePlatform/Models/VerificationError.cs new file mode 100644 index 000000000..24f72e3a7 --- /dev/null +++ b/Adyen/BalancePlatform/Models/VerificationError.cs @@ -0,0 +1,1008 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// VerificationError. + /// + public partial class VerificationError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the capabilities that the verification error applies to. + /// The verification error code. + /// A description of the error. + /// Contains the actions that you can take to resolve the verification error. + /// Contains more granular information about the verification error. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConstructor] + public VerificationError(Option?> capabilities = default, Option code = default, Option message = default, Option?> remediatingActions = default, Option?> subErrors = default, Option type = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _RemediatingActionsOption = remediatingActions; + _SubErrorsOption = subErrors; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationError() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains the capabilities that the verification error applies to. + /// + /// Contains the capabilities that the verification error applies to. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of the error. + /// + /// A description of the error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// Contains the actions that you can take to resolve the verification error. + /// + /// Contains the actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubErrorsOption { get; private set; } + + /// + /// Contains more granular information about the verification error. + /// + /// Contains more granular information about the verification error. + [JsonPropertyName("subErrors")] + public List? SubErrors { get { return this._SubErrorsOption; } set { this._SubErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationError {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append(" SubErrors: ").Append(SubErrors).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option?> remediatingActions = default; + Option?> subErrors = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subErrors": + subErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationError.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new VerificationError(capabilities, code, message, remediatingActions, subErrors, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationError._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationError.Capabilities, jsonSerializerOptions); + } + if (verificationError._CodeOption.IsSet) + if (verificationError.Code != null) + writer.WriteString("code", verificationError.Code); + + if (verificationError._MessageOption.IsSet) + if (verificationError.Message != null) + writer.WriteString("message", verificationError.Message); + + if (verificationError._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationError.RemediatingActions, jsonSerializerOptions); + } + if (verificationError._SubErrorsOption.IsSet) + { + writer.WritePropertyName("subErrors"); + JsonSerializer.Serialize(writer, verificationError.SubErrors, jsonSerializerOptions); + } + if (verificationError._TypeOption.IsSet && verificationError.Type != null) + { + string? typeRawValue = VerificationError.TypeEnum.ToJsonValue(verificationError._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/VerificationErrorRecursive.cs b/Adyen/BalancePlatform/Models/VerificationErrorRecursive.cs new file mode 100644 index 000000000..e786f846a --- /dev/null +++ b/Adyen/BalancePlatform/Models/VerificationErrorRecursive.cs @@ -0,0 +1,983 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// VerificationErrorRecursive. + /// + public partial class VerificationErrorRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the capabilities that the verification error applies to. + /// The verification error code. + /// A description of the error. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// Contains the actions that you can take to resolve the verification error. + [JsonConstructor] + public VerificationErrorRecursive(Option?> capabilities = default, Option code = default, Option message = default, Option type = default, Option?> remediatingActions = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _TypeOption = type; + _RemediatingActionsOption = remediatingActions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationErrorRecursive() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains the capabilities that the verification error applies to. + /// + /// Contains the capabilities that the verification error applies to. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of the error. + /// + /// A description of the error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// Contains the actions that you can take to resolve the verification error. + /// + /// Contains the actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationErrorRecursive {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationErrorRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option type = default; + Option?> remediatingActions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationErrorRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new VerificationErrorRecursive(capabilities, code, message, type, remediatingActions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationErrorRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationErrorRecursive._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.Capabilities, jsonSerializerOptions); + } + if (verificationErrorRecursive._CodeOption.IsSet) + if (verificationErrorRecursive.Code != null) + writer.WriteString("code", verificationErrorRecursive.Code); + + if (verificationErrorRecursive._MessageOption.IsSet) + if (verificationErrorRecursive.Message != null) + writer.WriteString("message", verificationErrorRecursive.Message); + + if (verificationErrorRecursive._TypeOption.IsSet && verificationErrorRecursive.Type != null) + { + string? typeRawValue = VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (verificationErrorRecursive._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.RemediatingActions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/WalletProviderAccountScoreRestriction.cs b/Adyen/BalancePlatform/Models/WalletProviderAccountScoreRestriction.cs new file mode 100644 index 000000000..f32e44bcc --- /dev/null +++ b/Adyen/BalancePlatform/Models/WalletProviderAccountScoreRestriction.cs @@ -0,0 +1,194 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// WalletProviderAccountScoreRestriction. + /// + public partial class WalletProviderAccountScoreRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public WalletProviderAccountScoreRestriction(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WalletProviderAccountScoreRestriction() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public int? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WalletProviderAccountScoreRestriction {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WalletProviderAccountScoreRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WalletProviderAccountScoreRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class WalletProviderAccountScoreRestriction.", nameof(operation)); + + return new WalletProviderAccountScoreRestriction(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WalletProviderAccountScoreRestriction walletProviderAccountScoreRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, walletProviderAccountScoreRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WalletProviderAccountScoreRestriction walletProviderAccountScoreRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (walletProviderAccountScoreRestriction.Operation != null) + writer.WriteString("operation", walletProviderAccountScoreRestriction.Operation); + + if (walletProviderAccountScoreRestriction._ValueOption.IsSet) + writer.WriteNumber("value", walletProviderAccountScoreRestriction._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/WalletProviderDeviceScore.cs b/Adyen/BalancePlatform/Models/WalletProviderDeviceScore.cs new file mode 100644 index 000000000..957a08bea --- /dev/null +++ b/Adyen/BalancePlatform/Models/WalletProviderDeviceScore.cs @@ -0,0 +1,194 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// WalletProviderDeviceScore. + /// + public partial class WalletProviderDeviceScore : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public WalletProviderDeviceScore(string operation, Option value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WalletProviderDeviceScore() + { + } + + partial void OnCreated(); + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public int? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WalletProviderDeviceScore {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WalletProviderDeviceScoreJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WalletProviderDeviceScore Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class WalletProviderDeviceScore.", nameof(operation)); + + return new WalletProviderDeviceScore(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WalletProviderDeviceScore walletProviderDeviceScore, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, walletProviderDeviceScore, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WalletProviderDeviceScore walletProviderDeviceScore, JsonSerializerOptions jsonSerializerOptions) + { + + if (walletProviderDeviceScore.Operation != null) + writer.WriteString("operation", walletProviderDeviceScore.Operation); + + if (walletProviderDeviceScore._ValueOption.IsSet) + writer.WriteNumber("value", walletProviderDeviceScore._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/BalancePlatform/Models/WalletProviderDeviceType.cs b/Adyen/BalancePlatform/Models/WalletProviderDeviceType.cs new file mode 100644 index 000000000..a58884bea --- /dev/null +++ b/Adyen/BalancePlatform/Models/WalletProviderDeviceType.cs @@ -0,0 +1,353 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// WalletProviderDeviceType. + /// + public partial class WalletProviderDeviceType : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines how the condition must be evaluated. + /// value + [JsonConstructor] + public WalletProviderDeviceType(string operation, Option?> value = default) + { + Operation = operation; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WalletProviderDeviceType() + { + } + + partial void OnCreated(); + + /// + /// Defines Value. + /// + [JsonConverter(typeof(ValueEnumJsonConverter))] + public class ValueEnum : IEnum + { + /// + /// Returns the value of the ValueEnum. + /// + public string? Value { get; set; } + + /// + /// ValueEnum.CARD - CARD + /// + public static readonly ValueEnum CARD = new("CARD"); + + /// + /// ValueEnum.MOBILEPHONE - MOBILE_PHONE + /// + public static readonly ValueEnum MOBILEPHONE = new("MOBILE_PHONE"); + + /// + /// ValueEnum.OTHER - OTHER + /// + public static readonly ValueEnum OTHER = new("OTHER"); + + /// + /// ValueEnum.PC - PC + /// + public static readonly ValueEnum PC = new("PC"); + + /// + /// ValueEnum.TABLETOREREADER - TABLET_OR_EREADER + /// + public static readonly ValueEnum TABLETOREREADER = new("TABLET_OR_EREADER"); + + /// + /// ValueEnum.UNKNOWN - UNKNOWN + /// + public static readonly ValueEnum UNKNOWN = new("UNKNOWN"); + + /// + /// ValueEnum.WATCHORWRISTBAND - WATCH_OR_WRISTBAND + /// + public static readonly ValueEnum WATCHORWRISTBAND = new("WATCH_OR_WRISTBAND"); + + /// + /// ValueEnum.WEARABLE - WEARABLE + /// + public static readonly ValueEnum WEARABLE = new("WEARABLE"); + + private ValueEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ValueEnum?(string? value) => value == null ? null : new ValueEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ValueEnum? option) => option?.Value; + + public static bool operator ==(ValueEnum? left, ValueEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ValueEnum? left, ValueEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ValueEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ValueEnum? FromStringOrDefault(string value) + { + return value switch { + "CARD" => ValueEnum.CARD, + "MOBILE_PHONE" => ValueEnum.MOBILEPHONE, + "OTHER" => ValueEnum.OTHER, + "PC" => ValueEnum.PC, + "TABLET_OR_EREADER" => ValueEnum.TABLETOREREADER, + "UNKNOWN" => ValueEnum.UNKNOWN, + "WATCH_OR_WRISTBAND" => ValueEnum.WATCHORWRISTBAND, + "WEARABLE" => ValueEnum.WEARABLE, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ValueEnum? value) + { + if (value == null) + return null; + + if (value == ValueEnum.CARD) + return "CARD"; + + if (value == ValueEnum.MOBILEPHONE) + return "MOBILE_PHONE"; + + if (value == ValueEnum.OTHER) + return "OTHER"; + + if (value == ValueEnum.PC) + return "PC"; + + if (value == ValueEnum.TABLETOREREADER) + return "TABLET_OR_EREADER"; + + if (value == ValueEnum.UNKNOWN) + return "UNKNOWN"; + + if (value == ValueEnum.WATCHORWRISTBAND) + return "WATCH_OR_WRISTBAND"; + + if (value == ValueEnum.WEARABLE) + return "WEARABLE"; + + return null; + } + + /// + /// JsonConverter for writing ValueEnum. + /// + public class ValueEnumJsonConverter : JsonConverter + { + public override ValueEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ValueEnum.FromStringOrDefault(value) ?? new ValueEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ValueEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ValueEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines how the condition must be evaluated. + /// + /// Defines how the condition must be evaluated. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValueOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("value")] + public List? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WalletProviderDeviceType {\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WalletProviderDeviceTypeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WalletProviderDeviceType Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option operation = default; + Option?> value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class WalletProviderDeviceType.", nameof(operation)); + + return new WalletProviderDeviceType(operation.Value!, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WalletProviderDeviceType walletProviderDeviceType, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, walletProviderDeviceType, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WalletProviderDeviceType walletProviderDeviceType, JsonSerializerOptions jsonSerializerOptions) + { + + if (walletProviderDeviceType.Operation != null) + writer.WriteString("operation", walletProviderDeviceType.Operation); + + if (walletProviderDeviceType._ValueOption.IsSet) + { + writer.WritePropertyName("value"); + JsonSerializer.Serialize(writer, walletProviderDeviceType.Value, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Models/WebhookSetting.cs b/Adyen/BalancePlatform/Models/WebhookSetting.cs new file mode 100644 index 000000000..dc3ce99d6 --- /dev/null +++ b/Adyen/BalancePlatform/Models/WebhookSetting.cs @@ -0,0 +1,274 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// WebhookSetting. + /// + public partial class WebhookSetting : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The unique identifier of the webhook setting. + /// status + /// target + [JsonConstructor] + public WebhookSetting(string currency, string id, string status, Target target) + { + Currency = currency; + Id = id; + Status = status; + Target = target; + Type = (SettingType)Enum.Parse(typeof(SettingType), this.GetType().Name); + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WebhookSetting() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The unique identifier of the webhook setting. + /// + /// The unique identifier of the webhook setting. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// . + /// + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("target")] + public Target Target { get; set; } + + /// + /// The discriminator. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public SettingType Type { get; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WebhookSetting {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Target: ").Append(Target).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 1) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 1.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebhookSettingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WebhookSetting Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option id = default; + Option status = default; + Option target = default; + Option type = default; + + string? discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "type"); + + if (discriminator != null && discriminator.Equals("BalanceWebhookSetting")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "target": + target = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(SettingTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class WebhookSetting.", nameof(currency)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WebhookSetting.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class WebhookSetting.", nameof(status)); + + if (!target.IsSet) + throw new ArgumentException("Property is required for class WebhookSetting.", nameof(target)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class WebhookSetting.", nameof(type)); + + return new WebhookSetting(currency.Value!, id.Value!, status.Value!, target.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WebhookSetting webhookSetting, JsonSerializerOptions jsonSerializerOptions) + { + if (webhookSetting is BalanceWebhookSetting balanceWebhookSetting){ + JsonSerializer.Serialize(writer, balanceWebhookSetting, jsonSerializerOptions); + return; + } + + + writer.WriteStartObject(); + + WriteProperties(writer, webhookSetting, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WebhookSetting webhookSetting, JsonSerializerOptions jsonSerializerOptions) + { + + if (webhookSetting.Currency != null) + writer.WriteString("currency", webhookSetting.Currency); + + if (webhookSetting.Id != null) + writer.WriteString("id", webhookSetting.Id); + + if (webhookSetting.Status != null) + writer.WriteString("status", webhookSetting.Status); + + writer.WritePropertyName("target"); + JsonSerializer.Serialize(writer, webhookSetting.Target, jsonSerializerOptions); + if (webhookSetting.Type != null) + writer.WriteString("type", SettingTypeValueConverter.ToJsonValue(webhookSetting.Type)); + } + } +} diff --git a/Adyen/BalancePlatform/Models/WebhookSettings.cs b/Adyen/BalancePlatform/Models/WebhookSettings.cs new file mode 100644 index 000000000..b89113eb9 --- /dev/null +++ b/Adyen/BalancePlatform/Models/WebhookSettings.cs @@ -0,0 +1,179 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalancePlatform.Client; + +namespace Adyen.BalancePlatform.Models +{ + /// + /// WebhookSettings. + /// + public partial class WebhookSettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of webhook settings. + [JsonConstructor] + public WebhookSettings(Option?> varWebhookSettings = default) + { + _VarWebhookSettingsOption = varWebhookSettings; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WebhookSettings() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VarWebhookSettingsOption { get; private set; } + + /// + /// The list of webhook settings. + /// + /// The list of webhook settings. + [JsonPropertyName("webhookSettings")] + public List? VarWebhookSettings { get { return this._VarWebhookSettingsOption; } set { this._VarWebhookSettingsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WebhookSettings {\n"); + sb.Append(" VarWebhookSettings: ").Append(VarWebhookSettings).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebhookSettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WebhookSettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> varWebhookSettings = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "webhookSettings": + varWebhookSettings = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new WebhookSettings(varWebhookSettings); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WebhookSettings webhookSettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, webhookSettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WebhookSettings webhookSettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (webhookSettings._VarWebhookSettingsOption.IsSet) + { + writer.WritePropertyName("webhookSettings"); + JsonSerializer.Serialize(writer, webhookSettings.VarWebhookSettings, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/BalancePlatform/Services/AccountHoldersService.cs b/Adyen/BalancePlatform/Services/AccountHoldersService.cs new file mode 100644 index 000000000..cecdb758c --- /dev/null +++ b/Adyen/BalancePlatform/Services/AccountHoldersService.cs @@ -0,0 +1,2742 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAccountHoldersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AccountHoldersServiceEvents Events { get; } + + /// + /// Create an account holder + /// + /// + /// Creates an account holder linked to a [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateAccountHolderAsync(AccountHolderInfo accountHolderInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an account holder + /// + /// + /// Returns an account holder. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// . + /// . + /// of . + Task GetAccountHolderAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all balance accounts of an account holder + /// + /// + /// Returns a paginated list of the balance accounts associated with an account holder. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 balance accounts and skip the first 10, use `/accountHolders/{id}/balanceAccounts?limit=5&offset=10`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// The number of items that you want to skip. + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. + /// . + /// . + /// of . + Task GetAllBalanceAccountsOfAccountHolderAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transaction rules for an account holder + /// + /// + /// Returns a list of transaction rules associated with an account holder. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// . + /// . + /// of . + Task GetAllTransactionRulesForAccountHolderAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a tax form + /// + /// + /// Generates a tax form for account holders operating in the US. For more information, refer to US tax forms for [marketplaces](https://docs.adyen.com/marketplaces/us-tax-forms/) or [platforms](https://docs.adyen.com/platforms/us-tax-forms/) . + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// The type of tax form you want to retrieve. Accepted values are **US1099k** and **US1099nec** + /// The tax year in YYYY format for the tax form you want to retrieve + /// The legal entity reference whose tax form you want to retrieve + /// . + /// . + /// of . + Task GetTaxFormAsync(string id, string formType, int year, Option legalEntityId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an account holder + /// + /// + /// Updates an account holder. When updating an account holder resource, if a parameter is not provided in the request, it is left unchanged. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// + /// . + /// . + /// of . + Task UpdateAccountHolderAsync(string id, AccountHolderUpdateRequest accountHolderUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateAccountHolderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAccountHolderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllBalanceAccountsOfAccountHolderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionRulesForAccountHolderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTaxFormApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateAccountHolderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AccountHoldersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateAccountHolder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateAccountHolder; + + internal void ExecuteOnCreateAccountHolder(AccountHoldersService.CreateAccountHolderApiResponse apiResponse) + { + OnCreateAccountHolder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateAccountHolder(Exception exception) + { + OnErrorCreateAccountHolder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAccountHolder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAccountHolder; + + internal void ExecuteOnGetAccountHolder(AccountHoldersService.GetAccountHolderApiResponse apiResponse) + { + OnGetAccountHolder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAccountHolder(Exception exception) + { + OnErrorGetAccountHolder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllBalanceAccountsOfAccountHolder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllBalanceAccountsOfAccountHolder; + + internal void ExecuteOnGetAllBalanceAccountsOfAccountHolder(AccountHoldersService.GetAllBalanceAccountsOfAccountHolderApiResponse apiResponse) + { + OnGetAllBalanceAccountsOfAccountHolder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllBalanceAccountsOfAccountHolder(Exception exception) + { + OnErrorGetAllBalanceAccountsOfAccountHolder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactionRulesForAccountHolder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactionRulesForAccountHolder; + + internal void ExecuteOnGetAllTransactionRulesForAccountHolder(AccountHoldersService.GetAllTransactionRulesForAccountHolderApiResponse apiResponse) + { + OnGetAllTransactionRulesForAccountHolder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactionRulesForAccountHolder(Exception exception) + { + OnErrorGetAllTransactionRulesForAccountHolder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTaxForm; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTaxForm; + + internal void ExecuteOnGetTaxForm(AccountHoldersService.GetTaxFormApiResponse apiResponse) + { + OnGetTaxForm?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTaxForm(Exception exception) + { + OnErrorGetTaxForm?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateAccountHolder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateAccountHolder; + + internal void ExecuteOnUpdateAccountHolder(AccountHoldersService.UpdateAccountHolderApiResponse apiResponse) + { + OnUpdateAccountHolder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateAccountHolder(Exception exception) + { + OnErrorUpdateAccountHolder?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AccountHoldersService : IAccountHoldersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AccountHoldersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AccountHoldersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AccountHoldersServiceEvents accountHoldersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = accountHoldersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an account holder Creates an account holder linked to a [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateAccountHolderAsync(AccountHolderInfo accountHolderInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (accountHolderInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(accountHolderInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateAccountHolderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateAccountHolder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateAccountHolder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateAccountHolderApiResponse : Adyen.Core.Client.ApiResponse, ICreateAccountHolderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AccountHolder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AccountHolder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an account holder Returns an account holder. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAccountHolderAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAccountHolderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAccountHolder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAccountHolder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAccountHolderApiResponse : Adyen.Core.Client.ApiResponse, IGetAccountHolderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AccountHolder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AccountHolder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all balance accounts of an account holder Returns a paginated list of the balance accounts associated with an account holder. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 balance accounts and skip the first 10, use `/accountHolders/{id}/balanceAccounts?limit=5&offset=10`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// The number of items that you want to skip. () + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllBalanceAccountsOfAccountHolderAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders/{id}/balanceAccounts" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders/{id}/balanceAccounts"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllBalanceAccountsOfAccountHolderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders/{id}/balanceAccounts", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllBalanceAccountsOfAccountHolder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllBalanceAccountsOfAccountHolder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllBalanceAccountsOfAccountHolderApiResponse : Adyen.Core.Client.ApiResponse, IGetAllBalanceAccountsOfAccountHolderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllBalanceAccountsOfAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllBalanceAccountsOfAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaginatedBalanceAccountsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaginatedBalanceAccountsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transaction rules for an account holder Returns a list of transaction rules associated with an account holder. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionRulesForAccountHolderAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders/{id}/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders/{id}/transactionRules"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionRulesForAccountHolderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders/{id}/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactionRulesForAccountHolder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactionRulesForAccountHolder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionRulesForAccountHolderApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionRulesForAccountHolderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRulesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRulesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a tax form Generates a tax form for account holders operating in the US. For more information, refer to US tax forms for [marketplaces](https://docs.adyen.com/marketplaces/us-tax-forms/) or [platforms](https://docs.adyen.com/platforms/us-tax-forms/) . + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// The type of tax form you want to retrieve. Accepted values are **US1099k** and **US1099nec** + /// The tax year in YYYY format for the tax form you want to retrieve + /// The legal entity reference whose tax form you want to retrieve () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTaxFormAsync(string id, string formType, int year, Option legalEntityId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders/{id}/taxForms" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders/{id}/taxForms"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["formType"] = ClientUtils.ParameterToString(formType); + parseQueryString["year"] = ClientUtils.ParameterToString(year); + + if (legalEntityId.IsSet) + parseQueryString["legalEntityId"] = ClientUtils.ParameterToString(legalEntityId.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTaxFormApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders/{id}/taxForms", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTaxForm(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTaxForm(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTaxFormApiResponse : Adyen.Core.Client.ApiResponse, IGetTaxFormApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTaxFormApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTaxFormApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.GetTaxFormResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.GetTaxFormResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update an account holder Updates an account holder. When updating an account holder resource, if a parameter is not provided in the request, it is left unchanged. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the account holder. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateAccountHolderAsync(string id, AccountHolderUpdateRequest accountHolderUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/accountHolders/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/accountHolders/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (accountHolderUpdateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(accountHolderUpdateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateAccountHolderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/accountHolders/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateAccountHolder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateAccountHolder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateAccountHolderApiResponse : Adyen.Core.Client.ApiResponse, IUpdateAccountHolderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAccountHolderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AccountHolder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AccountHolder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/AuthorizedCardUsersService.cs b/Adyen/BalancePlatform/Services/AuthorizedCardUsersService.cs new file mode 100644 index 000000000..7ebc5a469 --- /dev/null +++ b/Adyen/BalancePlatform/Services/AuthorizedCardUsersService.cs @@ -0,0 +1,1473 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAuthorizedCardUsersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AuthorizedCardUsersServiceEvents Events { get; } + + /// + /// Create authorized users for a card. + /// + /// + /// Assigns authorized users to a card. Users must have the **authorisedPaymentInstrumentUser** capability to be able to use the card. + /// + /// Thrown when fails to make API call. + /// + /// + /// . + /// . + /// of . + Task CreateAuthorisedCardUsersAsync(string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete the authorized users for a card. + /// + /// + /// Deletes the list of authorized users assigned to a card. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task DeleteAuthorisedCardUsersAsync(string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get authorized users for a card. + /// + /// + /// Returns the authorized users for a card. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task GetAllAuthorisedCardUsersAsync(string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the authorized users for a card. + /// + /// + /// Updates the list of authorized users for a card. >This request replaces all existing authorized users for the card. + /// + /// Thrown when fails to make API call. + /// + /// + /// . + /// . + /// of . + Task UpdateAuthorisedCardUsersAsync(string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateAuthorisedCardUsersApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteAuthorisedCardUsersApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllAuthorisedCardUsersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateAuthorisedCardUsersApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AuthorizedCardUsersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateAuthorisedCardUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateAuthorisedCardUsers; + + internal void ExecuteOnCreateAuthorisedCardUsers(AuthorizedCardUsersService.CreateAuthorisedCardUsersApiResponse apiResponse) + { + OnCreateAuthorisedCardUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateAuthorisedCardUsers(Exception exception) + { + OnErrorCreateAuthorisedCardUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteAuthorisedCardUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteAuthorisedCardUsers; + + internal void ExecuteOnDeleteAuthorisedCardUsers(AuthorizedCardUsersService.DeleteAuthorisedCardUsersApiResponse apiResponse) + { + OnDeleteAuthorisedCardUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteAuthorisedCardUsers(Exception exception) + { + OnErrorDeleteAuthorisedCardUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllAuthorisedCardUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllAuthorisedCardUsers; + + internal void ExecuteOnGetAllAuthorisedCardUsers(AuthorizedCardUsersService.GetAllAuthorisedCardUsersApiResponse apiResponse) + { + OnGetAllAuthorisedCardUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllAuthorisedCardUsers(Exception exception) + { + OnErrorGetAllAuthorisedCardUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateAuthorisedCardUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateAuthorisedCardUsers; + + internal void ExecuteOnUpdateAuthorisedCardUsers(AuthorizedCardUsersService.UpdateAuthorisedCardUsersApiResponse apiResponse) + { + OnUpdateAuthorisedCardUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateAuthorisedCardUsers(Exception exception) + { + OnErrorUpdateAuthorisedCardUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AuthorizedCardUsersService : IAuthorizedCardUsersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AuthorizedCardUsersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AuthorizedCardUsersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AuthorizedCardUsersServiceEvents authorizedCardUsersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = authorizedCardUsersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create authorized users for a card. Assigns authorized users to a card. Users must have the **authorisedPaymentInstrumentUser** capability to be able to use the card. + /// + /// Thrown when fails to make API call. + /// + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateAuthorisedCardUsersAsync(string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentInstrumentId%7D", Uri.EscapeDataString(paymentInstrumentId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (authorisedCardUsers as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(authorisedCardUsers, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateAuthorisedCardUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateAuthorisedCardUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateAuthorisedCardUsers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateAuthorisedCardUsersApiResponse : Adyen.Core.Client.ApiResponse, ICreateAuthorisedCardUsersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete the authorized users for a card. Deletes the list of authorized users assigned to a card. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteAuthorisedCardUsersAsync(string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentInstrumentId%7D", Uri.EscapeDataString(paymentInstrumentId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteAuthorisedCardUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteAuthorisedCardUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteAuthorisedCardUsers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteAuthorisedCardUsersApiResponse : Adyen.Core.Client.ApiResponse, IDeleteAuthorisedCardUsersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get authorized users for a card. Returns the authorized users for a card. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllAuthorisedCardUsersAsync(string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentInstrumentId%7D", Uri.EscapeDataString(paymentInstrumentId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllAuthorisedCardUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllAuthorisedCardUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllAuthorisedCardUsers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllAuthorisedCardUsersApiResponse : Adyen.Core.Client.ApiResponse, IGetAllAuthorisedCardUsersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AuthorisedCardUsers? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AuthorisedCardUsers? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the authorized users for a card. Updates the list of authorized users for a card. >This request replaces all existing authorized users for the card. + /// + /// Thrown when fails to make API call. + /// + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateAuthorisedCardUsersAsync(string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentInstrumentId%7D", Uri.EscapeDataString(paymentInstrumentId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (authorisedCardUsers as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(authorisedCardUsers, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateAuthorisedCardUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateAuthorisedCardUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateAuthorisedCardUsers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateAuthorisedCardUsersApiResponse : Adyen.Core.Client.ApiResponse, IUpdateAuthorisedCardUsersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAuthorisedCardUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/BalanceAccountsService.cs b/Adyen/BalancePlatform/Services/BalanceAccountsService.cs new file mode 100644 index 000000000..36fd90b0c --- /dev/null +++ b/Adyen/BalancePlatform/Services/BalanceAccountsService.cs @@ -0,0 +1,4482 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBalanceAccountsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BalanceAccountsServiceEvents Events { get; } + + /// + /// Create a balance account + /// + /// + /// Creates a balance account that holds the funds of the associated account holder. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateBalanceAccountAsync(BalanceAccountInfo balanceAccountInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a sweep + /// + /// + /// Creates a sweep that results in moving funds from or to a balance account. A sweep pulls in or pushes out funds based on a defined schedule, amount, currency, and a source or a destination. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// . + /// . + /// of . + Task CreateSweepAsync(string balanceAccountId, CreateSweepConfigurationV2 createSweepConfigurationV2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a sweep + /// + /// + /// Deletes a sweep for a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// . + /// . + /// of . + Task DeleteSweepAsync(string balanceAccountId, string sweepId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all sweeps for a balance account + /// + /// + /// Returns a list of the sweeps configured for a balance account. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 sweeps and to skip the first 10, use `/balanceAccounts/{balanceAccountId}/sweeps?limit=5&offset=10`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The number of items that you want to skip. + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. + /// . + /// . + /// of . + Task GetAllSweepsForBalanceAccountAsync(string balanceAccountId, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transaction rules for a balance account + /// + /// + /// Returns a list of transaction rules associated with a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// . + /// . + /// of . + Task GetAllTransactionRulesForBalanceAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a balance account + /// + /// + /// Returns a balance account and its balances for the default currency and other currencies with a non-zero balance. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// . + /// . + /// of . + Task GetBalanceAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get payment instruments linked to a balance account + /// + /// + /// Returns a paginated list of the payment instruments associated with a balance account. To fetch multiple pages, use the query parameters.For example, to limit the page to 3 payment instruments which are in active status and to skip the first 6, use `/balanceAccounts/{id}/paymentInstruments?limit=3&offset=6&status=active`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The number of items that you want to skip. + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. + /// The status of the payment instruments that you want to get. By default, the response includes payment instruments with any status. + /// . + /// . + /// of . + Task GetPaymentInstrumentsLinkedToBalanceAccountAsync(string id, Option offset = default, Option limit = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a sweep + /// + /// + /// Returns a sweep. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// . + /// . + /// of . + Task GetSweepAsync(string balanceAccountId, string sweepId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a balance account + /// + /// + /// Updates a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// . + /// . + /// of . + Task UpdateBalanceAccountAsync(string id, BalanceAccountUpdateRequest balanceAccountUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a sweep + /// + /// + /// Updates a sweep. When updating a sweep resource, note that if a request parameter is not provided, the parameter is left unchanged. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// + /// . + /// . + /// of . + Task UpdateSweepAsync(string balanceAccountId, string sweepId, UpdateSweepConfigurationV2 updateSweepConfigurationV2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateSweepApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteSweepApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllSweepsForBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionRulesForBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPaymentInstrumentsLinkedToBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetSweepApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateBalanceAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateSweepApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BalanceAccountsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateBalanceAccount; + + internal void ExecuteOnCreateBalanceAccount(BalanceAccountsService.CreateBalanceAccountApiResponse apiResponse) + { + OnCreateBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateBalanceAccount(Exception exception) + { + OnErrorCreateBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateSweep; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateSweep; + + internal void ExecuteOnCreateSweep(BalanceAccountsService.CreateSweepApiResponse apiResponse) + { + OnCreateSweep?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateSweep(Exception exception) + { + OnErrorCreateSweep?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteSweep; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteSweep; + + internal void ExecuteOnDeleteSweep(BalanceAccountsService.DeleteSweepApiResponse apiResponse) + { + OnDeleteSweep?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteSweep(Exception exception) + { + OnErrorDeleteSweep?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllSweepsForBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllSweepsForBalanceAccount; + + internal void ExecuteOnGetAllSweepsForBalanceAccount(BalanceAccountsService.GetAllSweepsForBalanceAccountApiResponse apiResponse) + { + OnGetAllSweepsForBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllSweepsForBalanceAccount(Exception exception) + { + OnErrorGetAllSweepsForBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactionRulesForBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactionRulesForBalanceAccount; + + internal void ExecuteOnGetAllTransactionRulesForBalanceAccount(BalanceAccountsService.GetAllTransactionRulesForBalanceAccountApiResponse apiResponse) + { + OnGetAllTransactionRulesForBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactionRulesForBalanceAccount(Exception exception) + { + OnErrorGetAllTransactionRulesForBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetBalanceAccount; + + internal void ExecuteOnGetBalanceAccount(BalanceAccountsService.GetBalanceAccountApiResponse apiResponse) + { + OnGetBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetBalanceAccount(Exception exception) + { + OnErrorGetBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPaymentInstrumentsLinkedToBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPaymentInstrumentsLinkedToBalanceAccount; + + internal void ExecuteOnGetPaymentInstrumentsLinkedToBalanceAccount(BalanceAccountsService.GetPaymentInstrumentsLinkedToBalanceAccountApiResponse apiResponse) + { + OnGetPaymentInstrumentsLinkedToBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPaymentInstrumentsLinkedToBalanceAccount(Exception exception) + { + OnErrorGetPaymentInstrumentsLinkedToBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetSweep; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetSweep; + + internal void ExecuteOnGetSweep(BalanceAccountsService.GetSweepApiResponse apiResponse) + { + OnGetSweep?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetSweep(Exception exception) + { + OnErrorGetSweep?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateBalanceAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateBalanceAccount; + + internal void ExecuteOnUpdateBalanceAccount(BalanceAccountsService.UpdateBalanceAccountApiResponse apiResponse) + { + OnUpdateBalanceAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateBalanceAccount(Exception exception) + { + OnErrorUpdateBalanceAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateSweep; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateSweep; + + internal void ExecuteOnUpdateSweep(BalanceAccountsService.UpdateSweepApiResponse apiResponse) + { + OnUpdateSweep?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateSweep(Exception exception) + { + OnErrorUpdateSweep?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BalanceAccountsService : IBalanceAccountsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BalanceAccountsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BalanceAccountsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BalanceAccountsServiceEvents balanceAccountsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = balanceAccountsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a balance account Creates a balance account that holds the funds of the associated account holder. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateBalanceAccountAsync(BalanceAccountInfo balanceAccountInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceAccountInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceAccountInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, ICreateBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.BalanceAccount? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BalanceAccount? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a sweep Creates a sweep that results in moving funds from or to a balance account. A sweep pulls in or pushes out funds based on a defined schedule, amount, currency, and a source or a destination. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateSweepAsync(string balanceAccountId, CreateSweepConfigurationV2 createSweepConfigurationV2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{balanceAccountId}/sweeps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{balanceAccountId}/sweeps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalanceAccountId%7D", Uri.EscapeDataString(balanceAccountId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createSweepConfigurationV2 as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createSweepConfigurationV2, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateSweepApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{balanceAccountId}/sweeps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateSweep(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateSweep(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateSweepApiResponse : Adyen.Core.Client.ApiResponse, ICreateSweepApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.SweepConfigurationV2? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.SweepConfigurationV2? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a sweep Deletes a sweep for a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteSweepAsync(string balanceAccountId, string sweepId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalanceAccountId%7D", Uri.EscapeDataString(balanceAccountId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsweepId%7D", Uri.EscapeDataString(sweepId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteSweepApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteSweep(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteSweep(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteSweepApiResponse : Adyen.Core.Client.ApiResponse, IDeleteSweepApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all sweeps for a balance account Returns a list of the sweeps configured for a balance account. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 sweeps and to skip the first 10, use `/balanceAccounts/{balanceAccountId}/sweeps?limit=5&offset=10`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The number of items that you want to skip. () + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllSweepsForBalanceAccountAsync(string balanceAccountId, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{balanceAccountId}/sweeps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{balanceAccountId}/sweeps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalanceAccountId%7D", Uri.EscapeDataString(balanceAccountId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllSweepsForBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{balanceAccountId}/sweeps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllSweepsForBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllSweepsForBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllSweepsForBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetAllSweepsForBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllSweepsForBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllSweepsForBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.BalanceSweepConfigurationsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BalanceSweepConfigurationsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transaction rules for a balance account Returns a list of transaction rules associated with a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionRulesForBalanceAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transactionRules"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionRulesForBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactionRulesForBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactionRulesForBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionRulesForBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionRulesForBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRulesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRulesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a balance account Returns a balance account and its balances for the default currency and other currencies with a non-zero balance. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetBalanceAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.BalanceAccount? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BalanceAccount? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get payment instruments linked to a balance account Returns a paginated list of the payment instruments associated with a balance account. To fetch multiple pages, use the query parameters.For example, to limit the page to 3 payment instruments which are in active status and to skip the first 6, use `/balanceAccounts/{id}/paymentInstruments?limit=3&offset=6&status=active`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The number of items that you want to skip. () + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. () + /// The status of the payment instruments that you want to get. By default, the response includes payment instruments with any status. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPaymentInstrumentsLinkedToBalanceAccountAsync(string id, Option offset = default, Option limit = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/paymentInstruments" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/paymentInstruments"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPaymentInstrumentsLinkedToBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/paymentInstruments", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPaymentInstrumentsLinkedToBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPaymentInstrumentsLinkedToBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPaymentInstrumentsLinkedToBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetPaymentInstrumentsLinkedToBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentsLinkedToBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentsLinkedToBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaginatedPaymentInstrumentsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaginatedPaymentInstrumentsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a sweep Returns a sweep. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetSweepAsync(string balanceAccountId, string sweepId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalanceAccountId%7D", Uri.EscapeDataString(balanceAccountId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsweepId%7D", Uri.EscapeDataString(sweepId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetSweepApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetSweep(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetSweep(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetSweepApiResponse : Adyen.Core.Client.ApiResponse, IGetSweepApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.SweepConfigurationV2? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.SweepConfigurationV2? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a balance account Updates a balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateBalanceAccountAsync(string id, BalanceAccountUpdateRequest balanceAccountUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceAccountUpdateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceAccountUpdateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateBalanceAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateBalanceAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateBalanceAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateBalanceAccountApiResponse : Adyen.Core.Client.ApiResponse, IUpdateBalanceAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateBalanceAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.BalanceAccount? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BalanceAccount? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a sweep Updates a sweep. When updating a sweep resource, note that if a request parameter is not provided, the parameter is left unchanged. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the sweep. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateSweepAsync(string balanceAccountId, string sweepId, UpdateSweepConfigurationV2 updateSweepConfigurationV2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalanceAccountId%7D", Uri.EscapeDataString(balanceAccountId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsweepId%7D", Uri.EscapeDataString(sweepId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateSweepConfigurationV2 as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateSweepConfigurationV2, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateSweepApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateSweep(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateSweep(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateSweepApiResponse : Adyen.Core.Client.ApiResponse, IUpdateSweepApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSweepApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.SweepConfigurationV2? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.SweepConfigurationV2? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/BalancesService.cs b/Adyen/BalancePlatform/Services/BalancesService.cs new file mode 100644 index 000000000..eb6b8cc7b --- /dev/null +++ b/Adyen/BalancePlatform/Services/BalancesService.cs @@ -0,0 +1,2470 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBalancesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BalancesServiceEvents Events { get; } + + /// + /// Create a balance webhook setting + /// + /// + /// Configures the criteria for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/1/post/balancePlatform.balanceAccount.balance.updated). Adyen sends balance webhooks to notify you of balance changes in your balance platform. They can be triggered when the balance reaches, exceeds, or drops below a specific value in a specific currency. You can get notified about balance changes in your entire balance platform, in the balance accounts of a specific user, or a specific balance account. The hierarchy between the webhook settings are based on the following business logic: * Settings on a higher level apply to all lower level resources (balance platform > account holder > balance acocunt). * The most granular setting overrides higher level settings (balance account > account holder > balance platform). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// + /// . + /// . + /// of . + Task CreateWebhookSettingAsync(string balancePlatformId, string webhookId, BalanceWebhookSettingInfo balanceWebhookSettingInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a balance webhook setting by id + /// + /// + /// Deletes a balance webhook setting that contains the conditions for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// . + /// . + /// of . + Task DeleteWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all balance webhook settings + /// + /// + /// Returns all balance webhook settings configured for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// . + /// . + /// of . + Task GetAllWebhookSettingsAsync(string balancePlatformId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a balance webhook setting by id + /// + /// + /// Returns the details of a specific balance webhook setting configured for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// . + /// . + /// of . + Task GetWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a balance webhook setting by id + /// + /// + /// Updates the conditions the balance change needs to meet for Adyen to send a [balance webhook](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// + /// . + /// . + /// of . + Task UpdateWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, BalanceWebhookSettingInfoUpdate balanceWebhookSettingInfoUpdate, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateWebhookSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteWebhookSettingApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllWebhookSettingsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetWebhookSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateWebhookSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BalancesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateWebhookSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateWebhookSetting; + + internal void ExecuteOnCreateWebhookSetting(BalancesService.CreateWebhookSettingApiResponse apiResponse) + { + OnCreateWebhookSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateWebhookSetting(Exception exception) + { + OnErrorCreateWebhookSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteWebhookSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteWebhookSetting; + + internal void ExecuteOnDeleteWebhookSetting(BalancesService.DeleteWebhookSettingApiResponse apiResponse) + { + OnDeleteWebhookSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteWebhookSetting(Exception exception) + { + OnErrorDeleteWebhookSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllWebhookSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllWebhookSettings; + + internal void ExecuteOnGetAllWebhookSettings(BalancesService.GetAllWebhookSettingsApiResponse apiResponse) + { + OnGetAllWebhookSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllWebhookSettings(Exception exception) + { + OnErrorGetAllWebhookSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetWebhookSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetWebhookSetting; + + internal void ExecuteOnGetWebhookSetting(BalancesService.GetWebhookSettingApiResponse apiResponse) + { + OnGetWebhookSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWebhookSetting(Exception exception) + { + OnErrorGetWebhookSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateWebhookSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateWebhookSetting; + + internal void ExecuteOnUpdateWebhookSetting(BalancesService.UpdateWebhookSettingApiResponse apiResponse) + { + OnUpdateWebhookSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateWebhookSetting(Exception exception) + { + OnErrorUpdateWebhookSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BalancesService : IBalancesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BalancesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BalancesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BalancesServiceEvents balancesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = balancesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a balance webhook setting Configures the criteria for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/1/post/balancePlatform.balanceAccount.balance.updated). Adyen sends balance webhooks to notify you of balance changes in your balance platform. They can be triggered when the balance reaches, exceeds, or drops below a specific value in a specific currency. You can get notified about balance changes in your entire balance platform, in the balance accounts of a specific user, or a specific balance account. The hierarchy between the webhook settings are based on the following business logic: * Settings on a higher level apply to all lower level resources (balance platform > account holder > balance acocunt). * The most granular setting overrides higher level settings (balance account > account holder > balance platform). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateWebhookSettingAsync(string balancePlatformId, string webhookId, BalanceWebhookSettingInfo balanceWebhookSettingInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalancePlatformId%7D", Uri.EscapeDataString(balancePlatformId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceWebhookSettingInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceWebhookSettingInfo, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateWebhookSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateWebhookSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateWebhookSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateWebhookSettingApiResponse : Adyen.Core.Client.ApiResponse, ICreateWebhookSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.WebhookSetting? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.WebhookSetting? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a balance webhook setting by id Deletes a balance webhook setting that contains the conditions for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalancePlatformId%7D", Uri.EscapeDataString(balancePlatformId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsettingId%7D", Uri.EscapeDataString(settingId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteWebhookSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteWebhookSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteWebhookSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteWebhookSettingApiResponse : Adyen.Core.Client.ApiResponse, IDeleteWebhookSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all balance webhook settings Returns all balance webhook settings configured for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllWebhookSettingsAsync(string balancePlatformId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalancePlatformId%7D", Uri.EscapeDataString(balancePlatformId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllWebhookSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllWebhookSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllWebhookSettings(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllWebhookSettingsApiResponse : Adyen.Core.Client.ApiResponse, IGetAllWebhookSettingsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllWebhookSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllWebhookSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.WebhookSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.WebhookSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a balance webhook setting by id Returns the details of a specific balance webhook setting configured for triggering [balance webhooks](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalancePlatformId%7D", Uri.EscapeDataString(balancePlatformId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsettingId%7D", Uri.EscapeDataString(settingId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetWebhookSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetWebhookSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetWebhookSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetWebhookSettingApiResponse : Adyen.Core.Client.ApiResponse, IGetWebhookSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.WebhookSetting? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.WebhookSetting? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a balance webhook setting by id Updates the conditions the balance change needs to meet for Adyen to send a [balance webhook](https://docs.adyen.com/api-explorer/balance-webhooks/latest/post/balanceAccount.balance.updated). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the balance webhook. + /// The unique identifier of the balance webhook setting. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateWebhookSettingAsync(string balancePlatformId, string webhookId, string settingId, BalanceWebhookSettingInfoUpdate balanceWebhookSettingInfoUpdate, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BbalancePlatformId%7D", Uri.EscapeDataString(balancePlatformId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsettingId%7D", Uri.EscapeDataString(settingId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceWebhookSettingInfoUpdate as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceWebhookSettingInfoUpdate, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateWebhookSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateWebhookSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateWebhookSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateWebhookSettingApiResponse : Adyen.Core.Client.ApiResponse, IUpdateWebhookSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateWebhookSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.WebhookSetting? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.WebhookSetting? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/BankAccountValidationService.cs b/Adyen/BalancePlatform/Services/BankAccountValidationService.cs new file mode 100644 index 000000000..c5c34917d --- /dev/null +++ b/Adyen/BalancePlatform/Services/BankAccountValidationService.cs @@ -0,0 +1,467 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBankAccountValidationService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BankAccountValidationServiceEvents Events { get; } + + /// + /// Validate a bank account + /// + /// + /// Validates bank account identification details. You can use this endpoint to validate bank account details before you [make a transfer](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) or [create a transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ValidateBankAccountIdentificationAsync(BankAccountIdentificationValidationRequest bankAccountIdentificationValidationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IValidateBankAccountIdentificationApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BankAccountValidationServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnValidateBankAccountIdentification; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorValidateBankAccountIdentification; + + internal void ExecuteOnValidateBankAccountIdentification(BankAccountValidationService.ValidateBankAccountIdentificationApiResponse apiResponse) + { + OnValidateBankAccountIdentification?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorValidateBankAccountIdentification(Exception exception) + { + OnErrorValidateBankAccountIdentification?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BankAccountValidationService : IBankAccountValidationService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BankAccountValidationServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BankAccountValidationService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BankAccountValidationServiceEvents bankAccountValidationServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = bankAccountValidationServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Validate a bank account Validates bank account identification details. You can use this endpoint to validate bank account details before you [make a transfer](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) or [create a transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ValidateBankAccountIdentificationAsync(BankAccountIdentificationValidationRequest bankAccountIdentificationValidationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/validateBankAccountIdentification" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/validateBankAccountIdentification"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (bankAccountIdentificationValidationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(bankAccountIdentificationValidationRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ValidateBankAccountIdentificationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/validateBankAccountIdentification", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnValidateBankAccountIdentification(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorValidateBankAccountIdentification(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ValidateBankAccountIdentificationApiResponse : Adyen.Core.Client.ApiResponse, IValidateBankAccountIdentificationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ValidateBankAccountIdentificationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ValidateBankAccountIdentificationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/CardOrdersService.cs b/Adyen/BalancePlatform/Services/CardOrdersService.cs new file mode 100644 index 000000000..44e41c924 --- /dev/null +++ b/Adyen/BalancePlatform/Services/CardOrdersService.cs @@ -0,0 +1,937 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ICardOrdersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + CardOrdersServiceEvents Events { get; } + + /// + /// Get card order items + /// + /// + /// Returns the item list of a specific card order. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the card order. + /// Specifies the position of an element in a list of card orders. The response includes a list of card order items that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card order items. + /// The number of card order items returned per page. **Default:** 10. + /// . + /// . + /// of . + Task GetCardOrderItemsAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of card orders + /// + /// + /// Returns a paginated list of card orders. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the card order. + /// The unique identifier of the card manufacturer profile. + /// The status of the card order. + /// The unique code of the card manufacturer profile. Possible values: **mcmaestro**, **mc**, **visa**, **mcdebit**. + /// Only include card orders that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// Only include card orders that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// Only include card orders that have been locked on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// Only include card orders that have been locked on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// The service center at which the card is issued. The value is case-sensitive. + /// Specifies the position of an element in a list of card orders. The response includes a list of card orders that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card orders. + /// The number of card orders returned per page. **Default:** 10. + /// . + /// . + /// of . + Task ListCardOrdersAsync(Option id = default, Option cardManufacturingProfileId = default, Option status = default, Option txVariantCode = default, Option createdSince = default, Option createdUntil = default, Option lockedSince = default, Option lockedUntil = default, Option serviceCenter = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetCardOrderItemsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListCardOrdersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class CardOrdersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetCardOrderItems; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetCardOrderItems; + + internal void ExecuteOnGetCardOrderItems(CardOrdersService.GetCardOrderItemsApiResponse apiResponse) + { + OnGetCardOrderItems?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCardOrderItems(Exception exception) + { + OnErrorGetCardOrderItems?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListCardOrders; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListCardOrders; + + internal void ExecuteOnListCardOrders(CardOrdersService.ListCardOrdersApiResponse apiResponse) + { + OnListCardOrders?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListCardOrders(Exception exception) + { + OnErrorListCardOrders?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class CardOrdersService : ICardOrdersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public CardOrdersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public CardOrdersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, CardOrdersServiceEvents cardOrdersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = cardOrdersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get card order items Returns the item list of a specific card order. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the card order. + /// Specifies the position of an element in a list of card orders. The response includes a list of card order items that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card order items. () + /// The number of card order items returned per page. **Default:** 10. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetCardOrderItemsAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cardorders/{id}/items" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cardorders/{id}/items"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetCardOrderItemsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cardorders/{id}/items", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetCardOrderItems(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetCardOrderItems(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetCardOrderItemsApiResponse : Adyen.Core.Client.ApiResponse, IGetCardOrderItemsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCardOrderItemsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCardOrderItemsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaginatedGetCardOrderItemResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaginatedGetCardOrderItemResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of card orders Returns a paginated list of card orders. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the card order. () + /// The unique identifier of the card manufacturer profile. () + /// The status of the card order. () + /// The unique code of the card manufacturer profile. Possible values: **mcmaestro**, **mc**, **visa**, **mcdebit**. () + /// Only include card orders that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. () + /// Only include card orders that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. () + /// Only include card orders that have been locked on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. () + /// Only include card orders that have been locked on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. () + /// The service center at which the card is issued. The value is case-sensitive. () + /// Specifies the position of an element in a list of card orders. The response includes a list of card orders that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card orders. () + /// The number of card orders returned per page. **Default:** 10. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListCardOrdersAsync(Option id = default, Option cardManufacturingProfileId = default, Option status = default, Option txVariantCode = default, Option createdSince = default, Option createdUntil = default, Option lockedSince = default, Option lockedUntil = default, Option serviceCenter = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cardorders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cardorders"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (id.IsSet) + parseQueryString["id"] = ClientUtils.ParameterToString(id.Value); + + if (cardManufacturingProfileId.IsSet) + parseQueryString["cardManufacturingProfileId"] = ClientUtils.ParameterToString(cardManufacturingProfileId.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + if (txVariantCode.IsSet) + parseQueryString["txVariantCode"] = ClientUtils.ParameterToString(txVariantCode.Value); + + if (createdSince.IsSet) + parseQueryString["createdSince"] = ClientUtils.ParameterToString(createdSince.Value); + + if (createdUntil.IsSet) + parseQueryString["createdUntil"] = ClientUtils.ParameterToString(createdUntil.Value); + + if (lockedSince.IsSet) + parseQueryString["lockedSince"] = ClientUtils.ParameterToString(lockedSince.Value); + + if (lockedUntil.IsSet) + parseQueryString["lockedUntil"] = ClientUtils.ParameterToString(lockedUntil.Value); + + if (serviceCenter.IsSet) + parseQueryString["serviceCenter"] = ClientUtils.ParameterToString(serviceCenter.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListCardOrdersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cardorders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListCardOrders(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListCardOrders(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListCardOrdersApiResponse : Adyen.Core.Client.ApiResponse, IListCardOrdersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListCardOrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListCardOrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaginatedGetCardOrderResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaginatedGetCardOrderResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/GrantAccountsService.cs b/Adyen/BalancePlatform/Services/GrantAccountsService.cs new file mode 100644 index 000000000..26d009b07 --- /dev/null +++ b/Adyen/BalancePlatform/Services/GrantAccountsService.cs @@ -0,0 +1,529 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IGrantAccountsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + GrantAccountsServiceEvents Events { get; } + + /// + /// Get a grant account + /// + /// + /// Returns the details of the [grant account](https://docs.adyen.com/platforms/capital#grant-account). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant account. + /// . + /// . + /// of . + [Obsolete("Deprecated since Configuration API v2. Use the `/grantAccounts/{id}` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/get/grantAccounts/(id)) instead.")] + Task GetGrantAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetGrantAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class GrantAccountsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetGrantAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetGrantAccount; + + internal void ExecuteOnGetGrantAccount(GrantAccountsService.GetGrantAccountApiResponse apiResponse) + { + OnGetGrantAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetGrantAccount(Exception exception) + { + OnErrorGetGrantAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class GrantAccountsService : IGrantAccountsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public GrantAccountsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public GrantAccountsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, GrantAccountsServiceEvents grantAccountsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = grantAccountsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a grant account Returns the details of the [grant account](https://docs.adyen.com/platforms/capital#grant-account). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetGrantAccountAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grantAccounts/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grantAccounts/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetGrantAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grantAccounts/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetGrantAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetGrantAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetGrantAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetGrantAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.CapitalGrantAccount? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.CapitalGrantAccount? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/GrantOffersService.cs b/Adyen/BalancePlatform/Services/GrantOffersService.cs new file mode 100644 index 000000000..a5d3e0bf4 --- /dev/null +++ b/Adyen/BalancePlatform/Services/GrantOffersService.cs @@ -0,0 +1,964 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IGrantOffersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + GrantOffersServiceEvents Events { get; } + + /// + /// Get all available grant offers + /// + /// + /// Returns a list of all [grant offers](https://docs.adyen.com/platforms/capital#grant-offers) available for `accountHolderId` specified as a query parameter. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant account. + /// . + /// . + /// of . + [Obsolete("Deprecated since Configuration API v2. Use the `/grantOffers` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/get/grantOffers) instead.")] + Task GetAllAvailableGrantOffersAsync(string accountHolderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a grant offer + /// + /// + /// Returns the details of a single grant offer. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant offer. + /// . + /// . + /// of . + [Obsolete("Deprecated since Configuration API v2. Use the `/grantOffers/{id}` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/get/grantOffers/(id)) instead.")] + Task GetGrantOfferAsync(string grantOfferId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetAllAvailableGrantOffersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetGrantOfferApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class GrantOffersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllAvailableGrantOffers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllAvailableGrantOffers; + + internal void ExecuteOnGetAllAvailableGrantOffers(GrantOffersService.GetAllAvailableGrantOffersApiResponse apiResponse) + { + OnGetAllAvailableGrantOffers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllAvailableGrantOffers(Exception exception) + { + OnErrorGetAllAvailableGrantOffers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetGrantOffer; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetGrantOffer; + + internal void ExecuteOnGetGrantOffer(GrantOffersService.GetGrantOfferApiResponse apiResponse) + { + OnGetGrantOffer?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetGrantOffer(Exception exception) + { + OnErrorGetGrantOffer?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class GrantOffersService : IGrantOffersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public GrantOffersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public GrantOffersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, GrantOffersServiceEvents grantOffersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = grantOffersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get all available grant offers Returns a list of all [grant offers](https://docs.adyen.com/platforms/capital#grant-offers) available for `accountHolderId` specified as a query parameter. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllAvailableGrantOffersAsync(string accountHolderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grantOffers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grantOffers"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["accountHolderId"] = ClientUtils.ParameterToString(accountHolderId); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllAvailableGrantOffersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grantOffers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllAvailableGrantOffers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllAvailableGrantOffers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllAvailableGrantOffersApiResponse : Adyen.Core.Client.ApiResponse, IGetAllAvailableGrantOffersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAvailableGrantOffersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAvailableGrantOffersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.GrantOffers? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.GrantOffers? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a grant offer Returns the details of a single grant offer. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant offer. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetGrantOfferAsync(string grantOfferId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grantOffers/{grantOfferId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grantOffers/{grantOfferId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BgrantOfferId%7D", Uri.EscapeDataString(grantOfferId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetGrantOfferApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grantOffers/{grantOfferId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetGrantOffer(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetGrantOffer(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetGrantOfferApiResponse : Adyen.Core.Client.ApiResponse, IGetGrantOfferApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantOfferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantOfferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.GrantOffer? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.GrantOffer? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/ManageCardPINService.cs b/Adyen/BalancePlatform/Services/ManageCardPINService.cs new file mode 100644 index 000000000..9c6dc5d8b --- /dev/null +++ b/Adyen/BalancePlatform/Services/ManageCardPINService.cs @@ -0,0 +1,1297 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IManageCardPINService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ManageCardPINServiceEvents Events { get; } + + /// + /// Change a card PIN + /// + /// + /// Changes the personal identification number (PIN) of a specified card. To make this request, your API credential must have the following role: * Bank Issuing PIN Change Webservice role + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ChangeCardPinAsync(PinChangeRequest pinChangeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an RSA public key + /// + /// + /// Get an [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) public key to encrypt or decrypt card data. You need the RSA public key to generate the `encryptedKey` required to: - [Change a PIN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/pins/change). - [Reveal a PIN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/pins/reveal). - [Reveal a PAN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/paymentInstruments/reveal). + /// + /// Thrown when fails to make API call. + /// The purpose of the public key. Possible values: **pinChange**, **pinReveal**, **panReveal**. Default value: **pinReveal**. + /// The encoding format of public key. Possible values: **jwk**, **pem**. Default value: **pem**. + /// . + /// . + /// of . + Task PublicKeyAsync(Option purpose = default, Option format = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Reveal a card PIN + /// + /// + /// Returns an encrypted PIN block that contains the PIN of a specified card. You can use the decrypted data to reveal the PIN in your user interface. To make this request, your API credential must have the following role: * Bank Issuing PIN Reveal Webservice role + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task RevealCardPinAsync(RevealPinRequest revealPinRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IChangeCardPinApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IPublicKeyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRevealCardPinApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ManageCardPINServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnChangeCardPin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorChangeCardPin; + + internal void ExecuteOnChangeCardPin(ManageCardPINService.ChangeCardPinApiResponse apiResponse) + { + OnChangeCardPin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorChangeCardPin(Exception exception) + { + OnErrorChangeCardPin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPublicKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPublicKey; + + internal void ExecuteOnPublicKey(ManageCardPINService.PublicKeyApiResponse apiResponse) + { + OnPublicKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPublicKey(Exception exception) + { + OnErrorPublicKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRevealCardPin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRevealCardPin; + + internal void ExecuteOnRevealCardPin(ManageCardPINService.RevealCardPinApiResponse apiResponse) + { + OnRevealCardPin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRevealCardPin(Exception exception) + { + OnErrorRevealCardPin?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ManageCardPINService : IManageCardPINService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ManageCardPINServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ManageCardPINService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ManageCardPINServiceEvents manageCardPINServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = manageCardPINServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Change a card PIN Changes the personal identification number (PIN) of a specified card. To make this request, your API credential must have the following role: * Bank Issuing PIN Change Webservice role + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ChangeCardPinAsync(PinChangeRequest pinChangeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/pins/change" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/pins/change"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (pinChangeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(pinChangeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ChangeCardPinApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/pins/change", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnChangeCardPin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorChangeCardPin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ChangeCardPinApiResponse : Adyen.Core.Client.ApiResponse, IChangeCardPinApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ChangeCardPinApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ChangeCardPinApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PinChangeResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PinChangeResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an RSA public key Get an [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) public key to encrypt or decrypt card data. You need the RSA public key to generate the `encryptedKey` required to: - [Change a PIN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/pins/change). - [Reveal a PIN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/pins/reveal). - [Reveal a PAN](https://docs.adyen.com/api-explorer/balanceplatform/2/post/paymentInstruments/reveal). + /// + /// Thrown when fails to make API call. + /// The purpose of the public key. Possible values: **pinChange**, **pinReveal**, **panReveal**. Default value: **pinReveal**. () + /// The encoding format of public key. Possible values: **jwk**, **pem**. Default value: **pem**. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PublicKeyAsync(Option purpose = default, Option format = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/publicKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/publicKey"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (purpose.IsSet) + parseQueryString["purpose"] = ClientUtils.ParameterToString(purpose.Value); + + if (format.IsSet) + parseQueryString["format"] = ClientUtils.ParameterToString(format.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PublicKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/publicKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPublicKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPublicKey(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PublicKeyApiResponse : Adyen.Core.Client.ApiResponse, IPublicKeyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PublicKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PublicKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PublicKeyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PublicKeyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Reveal a card PIN Returns an encrypted PIN block that contains the PIN of a specified card. You can use the decrypted data to reveal the PIN in your user interface. To make this request, your API credential must have the following role: * Bank Issuing PIN Reveal Webservice role + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RevealCardPinAsync(RevealPinRequest revealPinRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/pins/reveal" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/pins/reveal"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (revealPinRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(revealPinRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RevealCardPinApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/pins/reveal", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRevealCardPin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRevealCardPin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RevealCardPinApiResponse : Adyen.Core.Client.ApiResponse, IRevealCardPinApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevealCardPinApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevealCardPinApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.RevealPinResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RevealPinResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/ManageSCADevicesService.cs b/Adyen/BalancePlatform/Services/ManageSCADevicesService.cs new file mode 100644 index 000000000..7c07040f5 --- /dev/null +++ b/Adyen/BalancePlatform/Services/ManageSCADevicesService.cs @@ -0,0 +1,2739 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IManageSCADevicesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ManageSCADevicesServiceEvents Events { get; } + + /// + /// Complete an association between an SCA device and a resource + /// + /// + /// Completes an association between a user's registered SCA device and an Adyen resource. For example, you can associate an SCA device with additional [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). To complete the association, this endpoint validates the authentication data of the registered device. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// + /// . + /// . + /// of . + Task CompleteAssociationBetweenScaDeviceAndResourceAsync(string deviceId, AssociationFinaliseRequest associationFinaliseRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Complete the registration of an SCA device + /// + /// + /// Completes the registration of an SCA device by validating the authentication data of the device. You can register SCA devices for [business accounts](https://docs.adyen.com/platforms/business-accounts/sca) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device. You obtain this `id` in the response of a POST [/registeredDevices](https://docs.adyen.com/api-explorer/balanceplatform/2/post/registeredDevices#responses-200-id) request. + /// + /// . + /// . + /// of . + Task CompleteRegistrationOfScaDeviceAsync(string id, RegisterSCARequest registerSCARequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a registration of an SCA device + /// + /// + /// Deletes an SCA device from the list of registered devices of a specific payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device. + /// The unique identifier of the payment instrument linked to the SCA device. + /// . + /// . + /// of . + Task DeleteRegistrationOfScaDeviceAsync(string id, string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Initiate an association between an SCA device and a resource + /// + /// + /// Initiates an association between a user's registered SCA device and an Adyen resource. For example, you can associate an SCA device with additional [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// + /// . + /// . + /// of . + Task InitiateAssociationBetweenScaDeviceAndResourceAsync(string deviceId, AssociationInitiateRequest associationInitiateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Initiate the registration of an SCA device + /// + /// + /// Initiates the registration of a user's device for Strong Customer Authentication (SCA). You can register SCA devices for [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). For a successful request, the device must be eligible for SCA. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task InitiateRegistrationOfScaDeviceAsync(RegisterSCARequest registerSCARequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of registered SCA devices + /// + /// + /// Get a paginated list of the SCA devices you have currently registered for a specific payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of a payment instrument. It limits the returned list to SCA devices associated to this payment instrument. + /// The index of the page to retrieve. The index of the first page is 0 (zero). Default: 0. + /// The number of items to have on a page. Default: 20. Maximum: 100. + /// . + /// . + /// of . + Task ListRegisteredScaDevicesAsync(string paymentInstrumentId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICompleteAssociationBetweenScaDeviceAndResourceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICompleteRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IInitiateAssociationBetweenScaDeviceAndResourceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IInitiateRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListRegisteredScaDevicesApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ManageSCADevicesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCompleteAssociationBetweenScaDeviceAndResource; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCompleteAssociationBetweenScaDeviceAndResource; + + internal void ExecuteOnCompleteAssociationBetweenScaDeviceAndResource(ManageSCADevicesService.CompleteAssociationBetweenScaDeviceAndResourceApiResponse apiResponse) + { + OnCompleteAssociationBetweenScaDeviceAndResource?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCompleteAssociationBetweenScaDeviceAndResource(Exception exception) + { + OnErrorCompleteAssociationBetweenScaDeviceAndResource?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCompleteRegistrationOfScaDevice; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCompleteRegistrationOfScaDevice; + + internal void ExecuteOnCompleteRegistrationOfScaDevice(ManageSCADevicesService.CompleteRegistrationOfScaDeviceApiResponse apiResponse) + { + OnCompleteRegistrationOfScaDevice?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCompleteRegistrationOfScaDevice(Exception exception) + { + OnErrorCompleteRegistrationOfScaDevice?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteRegistrationOfScaDevice; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteRegistrationOfScaDevice; + + internal void ExecuteOnDeleteRegistrationOfScaDevice(ManageSCADevicesService.DeleteRegistrationOfScaDeviceApiResponse apiResponse) + { + OnDeleteRegistrationOfScaDevice?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteRegistrationOfScaDevice(Exception exception) + { + OnErrorDeleteRegistrationOfScaDevice?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnInitiateAssociationBetweenScaDeviceAndResource; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorInitiateAssociationBetweenScaDeviceAndResource; + + internal void ExecuteOnInitiateAssociationBetweenScaDeviceAndResource(ManageSCADevicesService.InitiateAssociationBetweenScaDeviceAndResourceApiResponse apiResponse) + { + OnInitiateAssociationBetweenScaDeviceAndResource?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorInitiateAssociationBetweenScaDeviceAndResource(Exception exception) + { + OnErrorInitiateAssociationBetweenScaDeviceAndResource?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnInitiateRegistrationOfScaDevice; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorInitiateRegistrationOfScaDevice; + + internal void ExecuteOnInitiateRegistrationOfScaDevice(ManageSCADevicesService.InitiateRegistrationOfScaDeviceApiResponse apiResponse) + { + OnInitiateRegistrationOfScaDevice?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorInitiateRegistrationOfScaDevice(Exception exception) + { + OnErrorInitiateRegistrationOfScaDevice?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListRegisteredScaDevices; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListRegisteredScaDevices; + + internal void ExecuteOnListRegisteredScaDevices(ManageSCADevicesService.ListRegisteredScaDevicesApiResponse apiResponse) + { + OnListRegisteredScaDevices?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListRegisteredScaDevices(Exception exception) + { + OnErrorListRegisteredScaDevices?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ManageSCADevicesService : IManageSCADevicesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ManageSCADevicesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ManageSCADevicesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ManageSCADevicesServiceEvents manageSCADevicesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = manageSCADevicesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Complete an association between an SCA device and a resource Completes an association between a user's registered SCA device and an Adyen resource. For example, you can associate an SCA device with additional [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). To complete the association, this endpoint validates the authentication data of the registered device. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CompleteAssociationBetweenScaDeviceAndResourceAsync(string deviceId, AssociationFinaliseRequest associationFinaliseRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices/{deviceId}/associations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices/{deviceId}/associations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BdeviceId%7D", Uri.EscapeDataString(deviceId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (associationFinaliseRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(associationFinaliseRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CompleteAssociationBetweenScaDeviceAndResourceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices/{deviceId}/associations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCompleteAssociationBetweenScaDeviceAndResource(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCompleteAssociationBetweenScaDeviceAndResource(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CompleteAssociationBetweenScaDeviceAndResourceApiResponse : Adyen.Core.Client.ApiResponse, ICompleteAssociationBetweenScaDeviceAndResourceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CompleteAssociationBetweenScaDeviceAndResourceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CompleteAssociationBetweenScaDeviceAndResourceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AssociationFinaliseResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AssociationFinaliseResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Complete the registration of an SCA device Completes the registration of an SCA device by validating the authentication data of the device. You can register SCA devices for [business accounts](https://docs.adyen.com/platforms/business-accounts/sca) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device. You obtain this `id` in the response of a POST [/registeredDevices](https://docs.adyen.com/api-explorer/balanceplatform/2/post/registeredDevices#responses-200-id) request. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CompleteRegistrationOfScaDeviceAsync(string id, RegisterSCARequest registerSCARequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (registerSCARequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(registerSCARequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CompleteRegistrationOfScaDeviceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCompleteRegistrationOfScaDevice(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCompleteRegistrationOfScaDevice(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CompleteRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.ApiResponse, ICompleteRegistrationOfScaDeviceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CompleteRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CompleteRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.RegisterSCAFinalResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RegisterSCAFinalResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a registration of an SCA device Deletes an SCA device from the list of registered devices of a specific payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device. + /// The unique identifier of the payment instrument linked to the SCA device. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteRegistrationOfScaDeviceAsync(string id, string paymentInstrumentId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["paymentInstrumentId"] = ClientUtils.ParameterToString(paymentInstrumentId); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteRegistrationOfScaDeviceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteRegistrationOfScaDevice(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteRegistrationOfScaDevice(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.ApiResponse, IDeleteRegistrationOfScaDeviceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Initiate an association between an SCA device and a resource Initiates an association between a user's registered SCA device and an Adyen resource. For example, you can associate an SCA device with additional [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task InitiateAssociationBetweenScaDeviceAndResourceAsync(string deviceId, AssociationInitiateRequest associationInitiateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices/{deviceId}/associations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices/{deviceId}/associations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BdeviceId%7D", Uri.EscapeDataString(deviceId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (associationInitiateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(associationInitiateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + InitiateAssociationBetweenScaDeviceAndResourceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices/{deviceId}/associations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnInitiateAssociationBetweenScaDeviceAndResource(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorInitiateAssociationBetweenScaDeviceAndResource(exception); + throw; + } + } + + /// + /// The . + /// + public partial class InitiateAssociationBetweenScaDeviceAndResourceApiResponse : Adyen.Core.Client.ApiResponse, IInitiateAssociationBetweenScaDeviceAndResourceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public InitiateAssociationBetweenScaDeviceAndResourceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public InitiateAssociationBetweenScaDeviceAndResourceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.AssociationInitiateResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.AssociationInitiateResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Initiate the registration of an SCA device Initiates the registration of a user's device for Strong Customer Authentication (SCA). You can register SCA devices for [business accounts](https://docs.adyen.com/platforms/business-accounts/sca/register-devices) or [Adyen-issued cards](https://docs.adyen.com/issuing/3d-secure/oob-auth-sdk/register-devices). For a successful request, the device must be eligible for SCA. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task InitiateRegistrationOfScaDeviceAsync(RegisterSCARequest registerSCARequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (registerSCARequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(registerSCARequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + InitiateRegistrationOfScaDeviceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnInitiateRegistrationOfScaDevice(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorInitiateRegistrationOfScaDevice(exception); + throw; + } + } + + /// + /// The . + /// + public partial class InitiateRegistrationOfScaDeviceApiResponse : Adyen.Core.Client.ApiResponse, IInitiateRegistrationOfScaDeviceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public InitiateRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public InitiateRegistrationOfScaDeviceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.RegisterSCAResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RegisterSCAResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of registered SCA devices Get a paginated list of the SCA devices you have currently registered for a specific payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of a payment instrument. It limits the returned list to SCA devices associated to this payment instrument. + /// The index of the page to retrieve. The index of the first page is 0 (zero). Default: 0. () + /// The number of items to have on a page. Default: 20. Maximum: 100. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListRegisteredScaDevicesAsync(string paymentInstrumentId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/registeredDevices" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/registeredDevices"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["paymentInstrumentId"] = ClientUtils.ParameterToString(paymentInstrumentId); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListRegisteredScaDevicesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/registeredDevices", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListRegisteredScaDevices(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListRegisteredScaDevices(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListRegisteredScaDevicesApiResponse : Adyen.Core.Client.ApiResponse, IListRegisteredScaDevicesApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListRegisteredScaDevicesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListRegisteredScaDevicesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.SearchRegisteredDevicesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.SearchRegisteredDevicesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/NetworkTokensService.cs b/Adyen/BalancePlatform/Services/NetworkTokensService.cs new file mode 100644 index 000000000..873b9090e --- /dev/null +++ b/Adyen/BalancePlatform/Services/NetworkTokensService.cs @@ -0,0 +1,857 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface INetworkTokensService : IAdyenApiService + { + /// + /// The class containing the events. + /// + NetworkTokensServiceEvents Events { get; } + + /// + /// Get a network token + /// + /// + /// Returns the details of a network token. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the network token. + /// . + /// . + /// of . + Task GetNetworkTokenAsync(string networkTokenId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a network token + /// + /// + /// Updates the status of the network token. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the network token. + /// + /// . + /// . + /// of . + Task UpdateNetworkTokenAsync(string networkTokenId, UpdateNetworkTokenRequest updateNetworkTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetNetworkTokenApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateNetworkTokenApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 202 Accepted. + /// + /// + bool IsAccepted { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class NetworkTokensServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetNetworkToken; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetNetworkToken; + + internal void ExecuteOnGetNetworkToken(NetworkTokensService.GetNetworkTokenApiResponse apiResponse) + { + OnGetNetworkToken?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetNetworkToken(Exception exception) + { + OnErrorGetNetworkToken?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateNetworkToken; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateNetworkToken; + + internal void ExecuteOnUpdateNetworkToken(NetworkTokensService.UpdateNetworkTokenApiResponse apiResponse) + { + OnUpdateNetworkToken?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateNetworkToken(Exception exception) + { + OnErrorUpdateNetworkToken?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class NetworkTokensService : INetworkTokensService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public NetworkTokensServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public NetworkTokensService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, NetworkTokensServiceEvents networkTokensServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = networkTokensServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a network token Returns the details of a network token. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the network token. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetNetworkTokenAsync(string networkTokenId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/networkTokens/{networkTokenId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/networkTokens/{networkTokenId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BnetworkTokenId%7D", Uri.EscapeDataString(networkTokenId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetNetworkTokenApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/networkTokens/{networkTokenId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetNetworkToken(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetNetworkToken(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetNetworkTokenApiResponse : Adyen.Core.Client.ApiResponse, IGetNetworkTokenApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetNetworkTokenApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetNetworkTokenApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.GetNetworkTokenResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.GetNetworkTokenResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a network token Updates the status of the network token. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the network token. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateNetworkTokenAsync(string networkTokenId, UpdateNetworkTokenRequest updateNetworkTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/networkTokens/{networkTokenId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/networkTokens/{networkTokenId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BnetworkTokenId%7D", Uri.EscapeDataString(networkTokenId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateNetworkTokenRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateNetworkTokenRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateNetworkTokenApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/networkTokens/{networkTokenId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateNetworkToken(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateNetworkToken(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateNetworkTokenApiResponse : Adyen.Core.Client.ApiResponse, IUpdateNetworkTokenApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateNetworkTokenApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateNetworkTokenApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 202 Accepted. + /// + /// + public bool IsAccepted => 202 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/PaymentInstrumentGroupsService.cs b/Adyen/BalancePlatform/Services/PaymentInstrumentGroupsService.cs new file mode 100644 index 000000000..52464c37b --- /dev/null +++ b/Adyen/BalancePlatform/Services/PaymentInstrumentGroupsService.cs @@ -0,0 +1,1405 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentInstrumentGroupsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentInstrumentGroupsServiceEvents Events { get; } + + /// + /// Create a payment instrument group + /// + /// + /// Creates a payment instrument group to associate and group payment instrument resources together. You can apply a transaction rule to a payment instrument group. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreatePaymentInstrumentGroupAsync(PaymentInstrumentGroupInfo paymentInstrumentGroupInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transaction rules for a payment instrument group + /// + /// + /// Returns a list of all the transaction rules associated with a payment instrument group. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument group. + /// . + /// . + /// of . + Task GetAllTransactionRulesForPaymentInstrumentGroupAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a payment instrument group + /// + /// + /// Returns the details of a payment instrument group. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument group. + /// . + /// . + /// of . + Task GetPaymentInstrumentGroupAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreatePaymentInstrumentGroupApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionRulesForPaymentInstrumentGroupApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPaymentInstrumentGroupApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentInstrumentGroupsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreatePaymentInstrumentGroup; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreatePaymentInstrumentGroup; + + internal void ExecuteOnCreatePaymentInstrumentGroup(PaymentInstrumentGroupsService.CreatePaymentInstrumentGroupApiResponse apiResponse) + { + OnCreatePaymentInstrumentGroup?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreatePaymentInstrumentGroup(Exception exception) + { + OnErrorCreatePaymentInstrumentGroup?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactionRulesForPaymentInstrumentGroup; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactionRulesForPaymentInstrumentGroup; + + internal void ExecuteOnGetAllTransactionRulesForPaymentInstrumentGroup(PaymentInstrumentGroupsService.GetAllTransactionRulesForPaymentInstrumentGroupApiResponse apiResponse) + { + OnGetAllTransactionRulesForPaymentInstrumentGroup?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactionRulesForPaymentInstrumentGroup(Exception exception) + { + OnErrorGetAllTransactionRulesForPaymentInstrumentGroup?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPaymentInstrumentGroup; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPaymentInstrumentGroup; + + internal void ExecuteOnGetPaymentInstrumentGroup(PaymentInstrumentGroupsService.GetPaymentInstrumentGroupApiResponse apiResponse) + { + OnGetPaymentInstrumentGroup?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPaymentInstrumentGroup(Exception exception) + { + OnErrorGetPaymentInstrumentGroup?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentInstrumentGroupsService : IPaymentInstrumentGroupsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentInstrumentGroupsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentInstrumentGroupsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentInstrumentGroupsServiceEvents paymentInstrumentGroupsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentInstrumentGroupsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a payment instrument group Creates a payment instrument group to associate and group payment instrument resources together. You can apply a transaction rule to a payment instrument group. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreatePaymentInstrumentGroupAsync(PaymentInstrumentGroupInfo paymentInstrumentGroupInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstrumentGroups" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstrumentGroups"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentInstrumentGroupInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentInstrumentGroupInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreatePaymentInstrumentGroupApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstrumentGroups", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreatePaymentInstrumentGroup(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreatePaymentInstrumentGroup(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreatePaymentInstrumentGroupApiResponse : Adyen.Core.Client.ApiResponse, ICreatePaymentInstrumentGroupApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrumentGroup? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrumentGroup? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transaction rules for a payment instrument group Returns a list of all the transaction rules associated with a payment instrument group. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument group. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionRulesForPaymentInstrumentGroupAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstrumentGroups/{id}/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstrumentGroups/{id}/transactionRules"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionRulesForPaymentInstrumentGroupApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstrumentGroups/{id}/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactionRulesForPaymentInstrumentGroup(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactionRulesForPaymentInstrumentGroup(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionRulesForPaymentInstrumentGroupApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionRulesForPaymentInstrumentGroupApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForPaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForPaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRulesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRulesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a payment instrument group Returns the details of a payment instrument group. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument group. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPaymentInstrumentGroupAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstrumentGroups/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstrumentGroups/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPaymentInstrumentGroupApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstrumentGroups/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPaymentInstrumentGroup(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPaymentInstrumentGroup(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPaymentInstrumentGroupApiResponse : Adyen.Core.Client.ApiResponse, IGetPaymentInstrumentGroupApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentGroupApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrumentGroup? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrumentGroup? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/PaymentInstrumentsService.cs b/Adyen/BalancePlatform/Services/PaymentInstrumentsService.cs new file mode 100644 index 000000000..50e7a194a --- /dev/null +++ b/Adyen/BalancePlatform/Services/PaymentInstrumentsService.cs @@ -0,0 +1,4042 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentInstrumentsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentInstrumentsServiceEvents Events { get; } + + /// + /// Create network token provisioning data + /// + /// + /// Create provisioning data for a network token. Use the provisioning data to add a user's payment instrument to their digital wallet. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// + /// . + /// . + /// of . + Task CreateNetworkTokenProvisioningDataAsync(string id, NetworkTokenActivationDataRequest networkTokenActivationDataRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a payment instrument + /// + /// + /// Creates a payment instrument to issue a physical card, a virtual card, or a business account to your user. For more information, refer to [Issue cards](https://docs.adyen.com/issuing/create-cards) or [Issue business accounts](https://docs.adyen.com/platforms/business-accounts). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreatePaymentInstrumentAsync(PaymentInstrumentInfo paymentInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transaction rules for a payment instrument + /// + /// + /// Returns a list of transaction rules associated with a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of . + Task GetAllTransactionRulesForPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get network token activation data + /// + /// + /// Get the network token activation data for a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of . + Task GetNetworkTokenActivationDataAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the PAN of a payment instrument + /// + /// + /// Returns the primary account number (PAN) of a payment instrument. To make this request, your API credential must have the following [role](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service#api-permissions): * Balance Platform BCL PCI role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of . + Task GetPanOfPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a payment instrument + /// + /// + /// Returns the details of a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of . + Task GetPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List network tokens + /// + /// + /// List the network tokens connected to a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of . + Task ListNetworkTokensAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Reveal the data of a payment instrument + /// + /// + /// Returns the encrypted data of a specified payment instrument. These data include: - The primary account number (PAN) - The card verification code (CVC) - The expiry date You can decrypt the data to reveal it in your user interface. To make this request, your API credential must have the following role: * Bank Issuing PAN Reveal Webservice role + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task RevealDataOfPaymentInstrumentAsync(PaymentInstrumentRevealRequest paymentInstrumentRevealRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a payment instrument + /// + /// + /// Updates a payment instrument. Once a payment instrument is already active, you can only update its status. However, for cards created with **inactive** status, you can still update the balance account associated with the card. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// + /// . + /// . + /// of . + Task UpdatePaymentInstrumentAsync(string id, PaymentInstrumentUpdateRequest paymentInstrumentUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateNetworkTokenProvisioningDataApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreatePaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionRulesForPaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetNetworkTokenActivationDataApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPanOfPaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListNetworkTokensApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRevealDataOfPaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdatePaymentInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentInstrumentsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateNetworkTokenProvisioningData; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateNetworkTokenProvisioningData; + + internal void ExecuteOnCreateNetworkTokenProvisioningData(PaymentInstrumentsService.CreateNetworkTokenProvisioningDataApiResponse apiResponse) + { + OnCreateNetworkTokenProvisioningData?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateNetworkTokenProvisioningData(Exception exception) + { + OnErrorCreateNetworkTokenProvisioningData?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreatePaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreatePaymentInstrument; + + internal void ExecuteOnCreatePaymentInstrument(PaymentInstrumentsService.CreatePaymentInstrumentApiResponse apiResponse) + { + OnCreatePaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreatePaymentInstrument(Exception exception) + { + OnErrorCreatePaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactionRulesForPaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactionRulesForPaymentInstrument; + + internal void ExecuteOnGetAllTransactionRulesForPaymentInstrument(PaymentInstrumentsService.GetAllTransactionRulesForPaymentInstrumentApiResponse apiResponse) + { + OnGetAllTransactionRulesForPaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactionRulesForPaymentInstrument(Exception exception) + { + OnErrorGetAllTransactionRulesForPaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetNetworkTokenActivationData; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetNetworkTokenActivationData; + + internal void ExecuteOnGetNetworkTokenActivationData(PaymentInstrumentsService.GetNetworkTokenActivationDataApiResponse apiResponse) + { + OnGetNetworkTokenActivationData?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetNetworkTokenActivationData(Exception exception) + { + OnErrorGetNetworkTokenActivationData?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPanOfPaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPanOfPaymentInstrument; + + internal void ExecuteOnGetPanOfPaymentInstrument(PaymentInstrumentsService.GetPanOfPaymentInstrumentApiResponse apiResponse) + { + OnGetPanOfPaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPanOfPaymentInstrument(Exception exception) + { + OnErrorGetPanOfPaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPaymentInstrument; + + internal void ExecuteOnGetPaymentInstrument(PaymentInstrumentsService.GetPaymentInstrumentApiResponse apiResponse) + { + OnGetPaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPaymentInstrument(Exception exception) + { + OnErrorGetPaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListNetworkTokens; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListNetworkTokens; + + internal void ExecuteOnListNetworkTokens(PaymentInstrumentsService.ListNetworkTokensApiResponse apiResponse) + { + OnListNetworkTokens?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListNetworkTokens(Exception exception) + { + OnErrorListNetworkTokens?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRevealDataOfPaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRevealDataOfPaymentInstrument; + + internal void ExecuteOnRevealDataOfPaymentInstrument(PaymentInstrumentsService.RevealDataOfPaymentInstrumentApiResponse apiResponse) + { + OnRevealDataOfPaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRevealDataOfPaymentInstrument(Exception exception) + { + OnErrorRevealDataOfPaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdatePaymentInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdatePaymentInstrument; + + internal void ExecuteOnUpdatePaymentInstrument(PaymentInstrumentsService.UpdatePaymentInstrumentApiResponse apiResponse) + { + OnUpdatePaymentInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePaymentInstrument(Exception exception) + { + OnErrorUpdatePaymentInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentInstrumentsService : IPaymentInstrumentsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentInstrumentsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentInstrumentsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentInstrumentsServiceEvents paymentInstrumentsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentInstrumentsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create network token provisioning data Create provisioning data for a network token. Use the provisioning data to add a user's payment instrument to their digital wallet. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateNetworkTokenProvisioningDataAsync(string id, NetworkTokenActivationDataRequest networkTokenActivationDataRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}/networkTokenActivationData" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}/networkTokenActivationData"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (networkTokenActivationDataRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(networkTokenActivationDataRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateNetworkTokenProvisioningDataApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}/networkTokenActivationData", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateNetworkTokenProvisioningData(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateNetworkTokenProvisioningData(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateNetworkTokenProvisioningDataApiResponse : Adyen.Core.Client.ApiResponse, ICreateNetworkTokenProvisioningDataApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateNetworkTokenProvisioningDataApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateNetworkTokenProvisioningDataApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.NetworkTokenActivationDataResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.NetworkTokenActivationDataResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a payment instrument Creates a payment instrument to issue a physical card, a virtual card, or a business account to your user. For more information, refer to [Issue cards](https://docs.adyen.com/issuing/create-cards) or [Issue business accounts](https://docs.adyen.com/platforms/business-accounts). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreatePaymentInstrumentAsync(PaymentInstrumentInfo paymentInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentInstrumentInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentInstrumentInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreatePaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreatePaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreatePaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreatePaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, ICreatePaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transaction rules for a payment instrument Returns a list of transaction rules associated with a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionRulesForPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}/transactionRules"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionRulesForPaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactionRulesForPaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactionRulesForPaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionRulesForPaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionRulesForPaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRulesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRulesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get network token activation data Get the network token activation data for a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetNetworkTokenActivationDataAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}/networkTokenActivationData" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}/networkTokenActivationData"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetNetworkTokenActivationDataApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}/networkTokenActivationData", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetNetworkTokenActivationData(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetNetworkTokenActivationData(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetNetworkTokenActivationDataApiResponse : Adyen.Core.Client.ApiResponse, IGetNetworkTokenActivationDataApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetNetworkTokenActivationDataApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetNetworkTokenActivationDataApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.NetworkTokenActivationDataResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.NetworkTokenActivationDataResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the PAN of a payment instrument Returns the primary account number (PAN) of a payment instrument. To make this request, your API credential must have the following [role](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service#api-permissions): * Balance Platform BCL PCI role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPanOfPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}/reveal" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}/reveal"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPanOfPaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}/reveal", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPanOfPaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPanOfPaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPanOfPaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IGetPanOfPaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPanOfPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPanOfPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrumentRevealInfo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrumentRevealInfo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a payment instrument Returns the details of a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPaymentInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IGetPaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// List network tokens List the network tokens connected to a payment instrument. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListNetworkTokensAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}/networkTokens" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}/networkTokens"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListNetworkTokensApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}/networkTokens", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListNetworkTokens(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListNetworkTokens(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListNetworkTokensApiResponse : Adyen.Core.Client.ApiResponse, IListNetworkTokensApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListNetworkTokensApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListNetworkTokensApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.ListNetworkTokensResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.ListNetworkTokensResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Reveal the data of a payment instrument Returns the encrypted data of a specified payment instrument. These data include: - The primary account number (PAN) - The card verification code (CVC) - The expiry date You can decrypt the data to reveal it in your user interface. To make this request, your API credential must have the following role: * Bank Issuing PAN Reveal Webservice role + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RevealDataOfPaymentInstrumentAsync(PaymentInstrumentRevealRequest paymentInstrumentRevealRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/reveal" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/reveal"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentInstrumentRevealRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentInstrumentRevealRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RevealDataOfPaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/reveal", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRevealDataOfPaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRevealDataOfPaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RevealDataOfPaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IRevealDataOfPaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevealDataOfPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevealDataOfPaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaymentInstrumentRevealResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaymentInstrumentRevealResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a payment instrument Updates a payment instrument. Once a payment instrument is already active, you can only update its status. However, for cards created with **inactive** status, you can still update the balance account associated with the card. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment instrument. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdatePaymentInstrumentAsync(string id, PaymentInstrumentUpdateRequest paymentInstrumentUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentInstruments/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentInstruments/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentInstrumentUpdateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentInstrumentUpdateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdatePaymentInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentInstruments/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdatePaymentInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdatePaymentInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdatePaymentInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IUpdatePaymentInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.UpdatePaymentInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.UpdatePaymentInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/PlatformService.cs b/Adyen/BalancePlatform/Services/PlatformService.cs new file mode 100644 index 000000000..670b51949 --- /dev/null +++ b/Adyen/BalancePlatform/Services/PlatformService.cs @@ -0,0 +1,1402 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPlatformService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PlatformServiceEvents Events { get; } + + /// + /// Get all account holders under a balance platform + /// + /// + /// Returns a paginated list of all the account holders that belong to the balance platform. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 account holders and to skip the first 20, use `/balancePlatforms/{id}/accountHolders?limit=5&offset=20`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The number of items that you want to skip. + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. + /// . + /// . + /// of . + Task GetAllAccountHoldersUnderBalancePlatformAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transaction rules for a balance platform + /// + /// + /// Returns a list of transaction rules associated with a balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// . + /// . + /// of . + Task GetAllTransactionRulesForBalancePlatformAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a balance platform + /// + /// + /// Returns a balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// . + /// . + /// of . + Task GetBalancePlatformAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetAllAccountHoldersUnderBalancePlatformApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionRulesForBalancePlatformApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetBalancePlatformApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PlatformServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllAccountHoldersUnderBalancePlatform; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllAccountHoldersUnderBalancePlatform; + + internal void ExecuteOnGetAllAccountHoldersUnderBalancePlatform(PlatformService.GetAllAccountHoldersUnderBalancePlatformApiResponse apiResponse) + { + OnGetAllAccountHoldersUnderBalancePlatform?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllAccountHoldersUnderBalancePlatform(Exception exception) + { + OnErrorGetAllAccountHoldersUnderBalancePlatform?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactionRulesForBalancePlatform; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactionRulesForBalancePlatform; + + internal void ExecuteOnGetAllTransactionRulesForBalancePlatform(PlatformService.GetAllTransactionRulesForBalancePlatformApiResponse apiResponse) + { + OnGetAllTransactionRulesForBalancePlatform?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactionRulesForBalancePlatform(Exception exception) + { + OnErrorGetAllTransactionRulesForBalancePlatform?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetBalancePlatform; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetBalancePlatform; + + internal void ExecuteOnGetBalancePlatform(PlatformService.GetBalancePlatformApiResponse apiResponse) + { + OnGetBalancePlatform?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetBalancePlatform(Exception exception) + { + OnErrorGetBalancePlatform?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PlatformService : IPlatformService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PlatformServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PlatformService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PlatformServiceEvents platformServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = platformServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get all account holders under a balance platform Returns a paginated list of all the account holders that belong to the balance platform. To fetch multiple pages, use the query parameters. For example, to limit the page to 5 account holders and to skip the first 20, use `/balancePlatforms/{id}/accountHolders?limit=5&offset=20`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The number of items that you want to skip. () + /// The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllAccountHoldersUnderBalancePlatformAsync(string id, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/accountHolders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/accountHolders"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllAccountHoldersUnderBalancePlatformApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/accountHolders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllAccountHoldersUnderBalancePlatform(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllAccountHoldersUnderBalancePlatform(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllAccountHoldersUnderBalancePlatformApiResponse : Adyen.Core.Client.ApiResponse, IGetAllAccountHoldersUnderBalancePlatformApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAccountHoldersUnderBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllAccountHoldersUnderBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.PaginatedAccountHoldersResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.PaginatedAccountHoldersResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transaction rules for a balance platform Returns a list of transaction rules associated with a balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionRulesForBalancePlatformAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/transactionRules"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionRulesForBalancePlatformApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactionRulesForBalancePlatform(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactionRulesForBalancePlatform(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionRulesForBalancePlatformApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionRulesForBalancePlatformApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionRulesForBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRulesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRulesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a balance platform Returns a balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetBalancePlatformAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetBalancePlatformApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetBalancePlatform(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetBalancePlatform(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetBalancePlatformApiResponse : Adyen.Core.Client.ApiResponse, IGetBalancePlatformApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalancePlatformApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.BalancePlatform? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BalancePlatform? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/SCAAssociationManagementService.cs b/Adyen/BalancePlatform/Services/SCAAssociationManagementService.cs new file mode 100644 index 000000000..0639fbc17 --- /dev/null +++ b/Adyen/BalancePlatform/Services/SCAAssociationManagementService.cs @@ -0,0 +1,1168 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ISCAAssociationManagementService : IAdyenApiService + { + /// + /// The class containing the events. + /// + SCAAssociationManagementServiceEvents Events { get; } + + /// + /// Approve a pending approval association + /// + /// + /// Approves a previously created association that is in a pending state. + /// + /// Thrown when fails to make API call. + /// The header for authenticating through SCA. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task ApproveAssociationAsync(ApproveAssociationRequest approveAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of devices associated with an entity + /// + /// + /// Returns a paginated list of the SCA devices associated with a specific entity. + /// + /// Thrown when fails to make API call. + /// The type of entity you want to retrieve a list of associations for. Possible values: **accountHolder** or **paymentInstrument**. + /// The unique identifier of the entity. + /// The number of items to have on a page. Default: **5**. + /// The index of the page to retrieve. The index of the first page is **0** (zero). Default: **0**. + /// . + /// . + /// of . + Task ListAssociationsAsync(ScaEntityType entityType, string entityId, int pageSize, int pageNumber, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete association to devices + /// + /// + /// Deletes one or more SCA associations for a device. + /// + /// Thrown when fails to make API call. + /// The header for authenticating through SCA. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task RemoveAssociationAsync(RemoveAssociationRequest removeAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IApproveAssociationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListAssociationsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRemoveAssociationApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class SCAAssociationManagementServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnApproveAssociation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorApproveAssociation; + + internal void ExecuteOnApproveAssociation(SCAAssociationManagementService.ApproveAssociationApiResponse apiResponse) + { + OnApproveAssociation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorApproveAssociation(Exception exception) + { + OnErrorApproveAssociation?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAssociations; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAssociations; + + internal void ExecuteOnListAssociations(SCAAssociationManagementService.ListAssociationsApiResponse apiResponse) + { + OnListAssociations?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAssociations(Exception exception) + { + OnErrorListAssociations?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRemoveAssociation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRemoveAssociation; + + internal void ExecuteOnRemoveAssociation(SCAAssociationManagementService.RemoveAssociationApiResponse apiResponse) + { + OnRemoveAssociation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveAssociation(Exception exception) + { + OnErrorRemoveAssociation?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class SCAAssociationManagementService : ISCAAssociationManagementService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public SCAAssociationManagementServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public SCAAssociationManagementService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, SCAAssociationManagementServiceEvents sCAAssociationManagementServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = sCAAssociationManagementServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Approve a pending approval association Approves a previously created association that is in a pending state. + /// + /// Thrown when fails to make API call. + /// The header for authenticating through SCA. Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ApproveAssociationAsync(ApproveAssociationRequest approveAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaAssociations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaAssociations"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (approveAssociationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(approveAssociationRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ApproveAssociationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaAssociations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnApproveAssociation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorApproveAssociation(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ApproveAssociationApiResponse : Adyen.Core.Client.ApiResponse, IApproveAssociationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApproveAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApproveAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.ApproveAssociationResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.ApproveAssociationResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of devices associated with an entity Returns a paginated list of the SCA devices associated with a specific entity. + /// + /// Thrown when fails to make API call. + /// The type of entity you want to retrieve a list of associations for. Possible values: **accountHolder** or **paymentInstrument**. + /// The unique identifier of the entity. + /// The number of items to have on a page. Default: **5**. + /// The index of the page to retrieve. The index of the first page is **0** (zero). Default: **0**. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAssociationsAsync(ScaEntityType entityType, string entityId, int pageSize, int pageNumber, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaAssociations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaAssociations"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["entityType"] = ClientUtils.ParameterToString(entityType); + parseQueryString["entityId"] = ClientUtils.ParameterToString(entityId); + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize); + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListAssociationsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaAssociations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAssociations(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAssociations(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListAssociationsApiResponse : Adyen.Core.Client.ApiResponse, IListAssociationsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAssociationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAssociationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.ListAssociationsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.ListAssociationsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete association to devices Deletes one or more SCA associations for a device. + /// + /// Thrown when fails to make API call. + /// The header for authenticating through SCA. Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RemoveAssociationAsync(RemoveAssociationRequest removeAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaAssociations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaAssociations"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (removeAssociationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(removeAssociationRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RemoveAssociationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaAssociations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRemoveAssociation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRemoveAssociation(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RemoveAssociationApiResponse : Adyen.Core.Client.ApiResponse, IRemoveAssociationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/SCADeviceManagementService.cs b/Adyen/BalancePlatform/Services/SCADeviceManagementService.cs new file mode 100644 index 000000000..7fceb9d0d --- /dev/null +++ b/Adyen/BalancePlatform/Services/SCADeviceManagementService.cs @@ -0,0 +1,1511 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ISCADeviceManagementService : IAdyenApiService + { + /// + /// The class containing the events. + /// + SCADeviceManagementServiceEvents Events { get; } + + /// + /// Begin SCA device registration + /// + /// + /// Begins the registration process for a new Strong Customer Authentication (SCA) device. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task BeginScaDeviceRegistrationAsync(BeginScaDeviceRegistrationRequest beginScaDeviceRegistrationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Finish registration process for a SCA device + /// + /// + /// Finishes the registration process for a new Strong Customer Authentication (SCA) device. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// + /// . + /// . + /// of . + Task FinishScaDeviceRegistrationAsync(string deviceId, FinishScaDeviceRegistrationRequest finishScaDeviceRegistrationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a new SCA association for a device + /// + /// + /// Creates an association between an SCA-enabled device and an entity, such as an account holder. This action does not guarantee the association is immediately ready for use; its status may be `pendingApproval` if the account holder has existing devices. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// + /// . + /// . + /// of . + Task SubmitScaAssociationAsync(string deviceId, SubmitScaAssociationRequest submitScaAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IBeginScaDeviceRegistrationApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IFinishScaDeviceRegistrationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISubmitScaAssociationApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class SCADeviceManagementServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnBeginScaDeviceRegistration; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorBeginScaDeviceRegistration; + + internal void ExecuteOnBeginScaDeviceRegistration(SCADeviceManagementService.BeginScaDeviceRegistrationApiResponse apiResponse) + { + OnBeginScaDeviceRegistration?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorBeginScaDeviceRegistration(Exception exception) + { + OnErrorBeginScaDeviceRegistration?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnFinishScaDeviceRegistration; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorFinishScaDeviceRegistration; + + internal void ExecuteOnFinishScaDeviceRegistration(SCADeviceManagementService.FinishScaDeviceRegistrationApiResponse apiResponse) + { + OnFinishScaDeviceRegistration?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFinishScaDeviceRegistration(Exception exception) + { + OnErrorFinishScaDeviceRegistration?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSubmitScaAssociation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSubmitScaAssociation; + + internal void ExecuteOnSubmitScaAssociation(SCADeviceManagementService.SubmitScaAssociationApiResponse apiResponse) + { + OnSubmitScaAssociation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSubmitScaAssociation(Exception exception) + { + OnErrorSubmitScaAssociation?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class SCADeviceManagementService : ISCADeviceManagementService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public SCADeviceManagementServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public SCADeviceManagementService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, SCADeviceManagementServiceEvents sCADeviceManagementServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = sCADeviceManagementServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Begin SCA device registration Begins the registration process for a new Strong Customer Authentication (SCA) device. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task BeginScaDeviceRegistrationAsync(BeginScaDeviceRegistrationRequest beginScaDeviceRegistrationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaDevices" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaDevices"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (beginScaDeviceRegistrationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(beginScaDeviceRegistrationRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + BeginScaDeviceRegistrationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaDevices", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnBeginScaDeviceRegistration(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorBeginScaDeviceRegistration(exception); + throw; + } + } + + /// + /// The . + /// + public partial class BeginScaDeviceRegistrationApiResponse : Adyen.Core.Client.ApiResponse, IBeginScaDeviceRegistrationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public BeginScaDeviceRegistrationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public BeginScaDeviceRegistrationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.BalancePlatform.Models.BeginScaDeviceRegistrationResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.BeginScaDeviceRegistrationResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Finish registration process for a SCA device Finishes the registration process for a new Strong Customer Authentication (SCA) device. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task FinishScaDeviceRegistrationAsync(string deviceId, FinishScaDeviceRegistrationRequest finishScaDeviceRegistrationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaDevices/{deviceId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaDevices/{deviceId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BdeviceId%7D", Uri.EscapeDataString(deviceId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (finishScaDeviceRegistrationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(finishScaDeviceRegistrationRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + FinishScaDeviceRegistrationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaDevices/{deviceId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnFinishScaDeviceRegistration(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorFinishScaDeviceRegistration(exception); + throw; + } + } + + /// + /// The . + /// + public partial class FinishScaDeviceRegistrationApiResponse : Adyen.Core.Client.ApiResponse, IFinishScaDeviceRegistrationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public FinishScaDeviceRegistrationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public FinishScaDeviceRegistrationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.FinishScaDeviceRegistrationResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.FinishScaDeviceRegistrationResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a new SCA association for a device Creates an association between an SCA-enabled device and an entity, such as an account holder. This action does not guarantee the association is immediately ready for use; its status may be `pendingApproval` if the account holder has existing devices. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the SCA device that you are associating with a resource. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SubmitScaAssociationAsync(string deviceId, SubmitScaAssociationRequest submitScaAssociationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scaDevices/{deviceId}/scaAssociations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scaDevices/{deviceId}/scaAssociations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BdeviceId%7D", Uri.EscapeDataString(deviceId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (submitScaAssociationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(submitScaAssociationRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SubmitScaAssociationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scaDevices/{deviceId}/scaAssociations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSubmitScaAssociation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSubmitScaAssociation(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SubmitScaAssociationApiResponse : Adyen.Core.Client.ApiResponse, ISubmitScaAssociationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SubmitScaAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SubmitScaAssociationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.BalancePlatform.Models.SubmitScaAssociationResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.SubmitScaAssociationResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/TransactionRulesService.cs b/Adyen/BalancePlatform/Services/TransactionRulesService.cs new file mode 100644 index 000000000..983095c19 --- /dev/null +++ b/Adyen/BalancePlatform/Services/TransactionRulesService.cs @@ -0,0 +1,1854 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransactionRulesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransactionRulesServiceEvents Events { get; } + + /// + /// Create a transaction rule + /// + /// + /// Creates a [transaction rule](https://docs.adyen.com/issuing/transaction-rules). When your user makes a transaction with their Adyen-issued card, the transaction is allowed or declined based on the conditions and outcome defined in the transaction rule. You can apply the transaction rule to several cards, such as all the cards in your platform, or to a specific card. For use cases, see [examples](https://docs.adyen.com/issuing/transaction-rules/examples). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateTransactionRuleAsync(TransactionRuleInfo transactionRuleInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a transaction rule + /// + /// + /// Deletes a transaction rule. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// . + /// . + /// of . + Task DeleteTransactionRuleAsync(string transactionRuleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a transaction rule + /// + /// + /// Returns the details of a transaction rule. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// . + /// . + /// of . + Task GetTransactionRuleAsync(string transactionRuleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a transaction rule + /// + /// + /// Updates a transaction rule. * To update only the status of a transaction rule, send only the `status` parameter. All other parameters not provided in the request are left unchanged. * When updating any other parameter, you need to send all existing resource parameters. If you omit a parameter in the request, that parameter is removed from the resource. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// + /// . + /// . + /// of . + Task UpdateTransactionRuleAsync(string transactionRuleId, TransactionRuleInfo transactionRuleInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateTransactionRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteTransactionRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTransactionRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTransactionRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransactionRulesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateTransactionRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateTransactionRule; + + internal void ExecuteOnCreateTransactionRule(TransactionRulesService.CreateTransactionRuleApiResponse apiResponse) + { + OnCreateTransactionRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTransactionRule(Exception exception) + { + OnErrorCreateTransactionRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteTransactionRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteTransactionRule; + + internal void ExecuteOnDeleteTransactionRule(TransactionRulesService.DeleteTransactionRuleApiResponse apiResponse) + { + OnDeleteTransactionRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTransactionRule(Exception exception) + { + OnErrorDeleteTransactionRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransactionRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransactionRule; + + internal void ExecuteOnGetTransactionRule(TransactionRulesService.GetTransactionRuleApiResponse apiResponse) + { + OnGetTransactionRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransactionRule(Exception exception) + { + OnErrorGetTransactionRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTransactionRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTransactionRule; + + internal void ExecuteOnUpdateTransactionRule(TransactionRulesService.UpdateTransactionRuleApiResponse apiResponse) + { + OnUpdateTransactionRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTransactionRule(Exception exception) + { + OnErrorUpdateTransactionRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransactionRulesService : ITransactionRulesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransactionRulesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransactionRulesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransactionRulesServiceEvents transactionRulesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transactionRulesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a transaction rule Creates a [transaction rule](https://docs.adyen.com/issuing/transaction-rules). When your user makes a transaction with their Adyen-issued card, the transaction is allowed or declined based on the conditions and outcome defined in the transaction rule. You can apply the transaction rule to several cards, such as all the cards in your platform, or to a specific card. For use cases, see [examples](https://docs.adyen.com/issuing/transaction-rules/examples). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateTransactionRuleAsync(TransactionRuleInfo transactionRuleInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactionRules" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactionRules"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transactionRuleInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transactionRuleInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateTransactionRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactionRules", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateTransactionRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateTransactionRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateTransactionRuleApiResponse : Adyen.Core.Client.ApiResponse, ICreateTransactionRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRule? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRule? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a transaction rule Deletes a transaction rule. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteTransactionRuleAsync(string transactionRuleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactionRules/{transactionRuleId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactionRules/{transactionRuleId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransactionRuleId%7D", Uri.EscapeDataString(transactionRuleId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteTransactionRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactionRules/{transactionRuleId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteTransactionRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteTransactionRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteTransactionRuleApiResponse : Adyen.Core.Client.ApiResponse, IDeleteTransactionRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRule? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRule? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a transaction rule Returns the details of a transaction rule. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransactionRuleAsync(string transactionRuleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactionRules/{transactionRuleId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactionRules/{transactionRuleId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransactionRuleId%7D", Uri.EscapeDataString(transactionRuleId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTransactionRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactionRules/{transactionRuleId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransactionRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransactionRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTransactionRuleApiResponse : Adyen.Core.Client.ApiResponse, IGetTransactionRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRuleResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRuleResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a transaction rule Updates a transaction rule. * To update only the status of a transaction rule, send only the `status` parameter. All other parameters not provided in the request are left unchanged. * When updating any other parameter, you need to send all existing resource parameters. If you omit a parameter in the request, that parameter is removed from the resource. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction rule. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTransactionRuleAsync(string transactionRuleId, TransactionRuleInfo transactionRuleInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactionRules/{transactionRuleId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactionRules/{transactionRuleId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransactionRuleId%7D", Uri.EscapeDataString(transactionRuleId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transactionRuleInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transactionRuleInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTransactionRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactionRules/{transactionRuleId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTransactionRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTransactionRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTransactionRuleApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTransactionRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTransactionRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransactionRule? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransactionRule? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/TransferLimitsBalanceAccountLevelService.cs b/Adyen/BalancePlatform/Services/TransferLimitsBalanceAccountLevelService.cs new file mode 100644 index 000000000..69b1e2aa8 --- /dev/null +++ b/Adyen/BalancePlatform/Services/TransferLimitsBalanceAccountLevelService.cs @@ -0,0 +1,1958 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransferLimitsBalanceAccountLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransferLimitsBalanceAccountLevelServiceEvents Events { get; } + + /// + /// Approve pending transfer limits + /// + /// + /// Approve transfer limits that are pending SCA authentication. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// Header for authenticating using SCA. - Pass this header parameter using . + /// . + /// . + /// of . + Task ApprovePendingTransferLimitsAsync(string id, ApproveTransferLimitRequest approveTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a transfer limit + /// + /// + /// Create a transfer limit for your balance account using the unique `id` of your balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// Header for authenticating through SCA - Pass this header parameter using . + /// . + /// . + /// of . + Task CreateTransferLimitAsync(string id, CreateTransferLimitRequest createTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a scheduled or pending transfer limit + /// + /// + /// Delete a scheduled or pending transfer limit using its unique `transferLimitId`. You cannot delete an active limit. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of . + Task DeletePendingTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all current transfer limits + /// + /// + /// Get all transfer limits that currently apply to a balance account using the unique `id` of the balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. + /// . + /// . + /// of . + Task GetCurrentTransferLimitsAsync(string id, Option scope = default, Option transferType = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the details of a transfer limit + /// + /// + /// Get the details of a transfer limit using its unique `transferLimitId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of . + Task GetSpecificTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Filter and view the transfer limits + /// + /// + /// Filter and view the transfer limits configured for a balance account using the balance account's unique `id` and the available query parameters. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. + /// . + /// . + /// of . + Task GetTransferLimitsAsync(string id, Option scope = default, Option transferType = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IApprovePendingTransferLimitsApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateTransferLimitApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IDeletePendingTransferLimitApiResponse : Adyen.Core.Client.IApiResponse, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IGetCurrentTransferLimitsApiResponse : Adyen.Core.Client.IApiResponse, IOk, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IGetSpecificTransferLimitApiResponse : Adyen.Core.Client.IApiResponse, IOk, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTransferLimitsApiResponse : Adyen.Core.Client.IApiResponse, IOk, INotFound, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransferLimitsBalanceAccountLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnApprovePendingTransferLimits; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorApprovePendingTransferLimits; + + internal void ExecuteOnApprovePendingTransferLimits(TransferLimitsBalanceAccountLevelService.ApprovePendingTransferLimitsApiResponse apiResponse) + { + OnApprovePendingTransferLimits?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorApprovePendingTransferLimits(Exception exception) + { + OnErrorApprovePendingTransferLimits?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateTransferLimit; + + internal void ExecuteOnCreateTransferLimit(TransferLimitsBalanceAccountLevelService.CreateTransferLimitApiResponse apiResponse) + { + OnCreateTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTransferLimit(Exception exception) + { + OnErrorCreateTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeletePendingTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeletePendingTransferLimit; + + internal void ExecuteOnDeletePendingTransferLimit(TransferLimitsBalanceAccountLevelService.DeletePendingTransferLimitApiResponse apiResponse) + { + OnDeletePendingTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeletePendingTransferLimit(Exception exception) + { + OnErrorDeletePendingTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetCurrentTransferLimits; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetCurrentTransferLimits; + + internal void ExecuteOnGetCurrentTransferLimits(TransferLimitsBalanceAccountLevelService.GetCurrentTransferLimitsApiResponse apiResponse) + { + OnGetCurrentTransferLimits?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCurrentTransferLimits(Exception exception) + { + OnErrorGetCurrentTransferLimits?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetSpecificTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetSpecificTransferLimit; + + internal void ExecuteOnGetSpecificTransferLimit(TransferLimitsBalanceAccountLevelService.GetSpecificTransferLimitApiResponse apiResponse) + { + OnGetSpecificTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetSpecificTransferLimit(Exception exception) + { + OnErrorGetSpecificTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransferLimits; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransferLimits; + + internal void ExecuteOnGetTransferLimits(TransferLimitsBalanceAccountLevelService.GetTransferLimitsApiResponse apiResponse) + { + OnGetTransferLimits?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransferLimits(Exception exception) + { + OnErrorGetTransferLimits?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransferLimitsBalanceAccountLevelService : ITransferLimitsBalanceAccountLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransferLimitsBalanceAccountLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransferLimitsBalanceAccountLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransferLimitsBalanceAccountLevelServiceEvents transferLimitsBalanceAccountLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transferLimitsBalanceAccountLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Approve pending transfer limits Approve transfer limits that are pending SCA authentication. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// Header for authenticating using SCA. () Pass this header parameter in . + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ApprovePendingTransferLimitsAsync(string id, ApproveTransferLimitRequest approveTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits/approve" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits/approve"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (approveTransferLimitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(approveTransferLimitRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ApprovePendingTransferLimitsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits/approve", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnApprovePendingTransferLimits(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorApprovePendingTransferLimits(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ApprovePendingTransferLimitsApiResponse : Adyen.Core.Client.ApiResponse, IApprovePendingTransferLimitsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApprovePendingTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApprovePendingTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a transfer limit Create a transfer limit for your balance account using the unique `id` of your balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// + /// Header for authenticating through SCA () Pass this header parameter in . + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateTransferLimitAsync(string id, CreateTransferLimitRequest createTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createTransferLimitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createTransferLimitRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateTransferLimit(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateTransferLimitApiResponse : Adyen.Core.Client.ApiResponse, ICreateTransferLimitApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransferLimit? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransferLimit? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a scheduled or pending transfer limit Delete a scheduled or pending transfer limit using its unique `transferLimitId`. You cannot delete an active limit. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeletePendingTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits/{transferLimitId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits/{transferLimitId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransferLimitId%7D", Uri.EscapeDataString(transferLimitId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeletePendingTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits/{transferLimitId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeletePendingTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeletePendingTransferLimit(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeletePendingTransferLimitApiResponse : Adyen.Core.Client.ApiResponse, IDeletePendingTransferLimitApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeletePendingTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeletePendingTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all current transfer limits Get all transfer limits that currently apply to a balance account using the unique `id` of the balance account. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. () + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetCurrentTransferLimitsAsync(string id, Option scope = default, Option transferType = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits/current" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits/current"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (scope.IsSet) + parseQueryString["scope"] = ClientUtils.ParameterToString(scope.Value); + + if (transferType.IsSet) + parseQueryString["transferType"] = ClientUtils.ParameterToString(transferType.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetCurrentTransferLimitsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits/current", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetCurrentTransferLimits(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetCurrentTransferLimits(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetCurrentTransferLimitsApiResponse : Adyen.Core.Client.ApiResponse, IGetCurrentTransferLimitsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCurrentTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCurrentTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransferLimitListResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransferLimitListResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the details of a transfer limit Get the details of a transfer limit using its unique `transferLimitId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetSpecificTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits/{transferLimitId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits/{transferLimitId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransferLimitId%7D", Uri.EscapeDataString(transferLimitId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetSpecificTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits/{transferLimitId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetSpecificTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetSpecificTransferLimit(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetSpecificTransferLimitApiResponse : Adyen.Core.Client.ApiResponse, IGetSpecificTransferLimitApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSpecificTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSpecificTransferLimitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransferLimit? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransferLimit? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Filter and view the transfer limits Filter and view the transfer limits configured for a balance account using the balance account's unique `id` and the available query parameters. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance account. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. () + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. () + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransferLimitsAsync(string id, Option scope = default, Option transferType = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balanceAccounts/{id}/transferLimits" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balanceAccounts/{id}/transferLimits"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (scope.IsSet) + parseQueryString["scope"] = ClientUtils.ParameterToString(scope.Value); + + if (transferType.IsSet) + parseQueryString["transferType"] = ClientUtils.ParameterToString(transferType.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTransferLimitsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balanceAccounts/{id}/transferLimits", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransferLimits(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransferLimits(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTransferLimitsApiResponse : Adyen.Core.Client.ApiResponse, IGetTransferLimitsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferLimitsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransferLimitListResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransferLimitListResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalancePlatform/Services/TransferLimitsBalancePlatformLevelService.cs b/Adyen/BalancePlatform/Services/TransferLimitsBalancePlatformLevelService.cs new file mode 100644 index 000000000..6fc92beda --- /dev/null +++ b/Adyen/BalancePlatform/Services/TransferLimitsBalancePlatformLevelService.cs @@ -0,0 +1,536 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransferLimitsBalancePlatformLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransferLimitsBalancePlatformLevelServiceEvents Events { get; } + + /// + /// Create a transfer limit + /// + /// + /// Create a transfer limit for your balance platform using the unique `id` of your balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// + /// . + /// . + /// of . + Task CreateTransferLimitAsync(string id, CreateTransferLimitRequest createTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a scheduled or pending transfer limit + /// + /// + /// Delete a scheduled or pending transfer limit using its unique `transferLimitId`. You cannot delete an active limit. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of . + Task DeletePendingTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the details of a transfer limit + /// + /// + /// Get the details of a transfer limit using its unique `transferLimitId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of . + Task GetSpecificTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Filter and view the transfer limits + /// + /// + /// Filter and view the transfer limits configured for your balance platform using the balance platform's unique `id` and the available query parameters. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. + /// . + /// . + /// of . + Task GetTransferLimitsAsync(string id, Option scope = default, Option transferType = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransferLimitsBalancePlatformLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateTransferLimit; + + internal void ExecuteOnCreateTransferLimit(TransferLimitsBalanceAccountLevelService.CreateTransferLimitApiResponse apiResponse) + { + OnCreateTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTransferLimit(Exception exception) + { + OnErrorCreateTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeletePendingTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeletePendingTransferLimit; + + internal void ExecuteOnDeletePendingTransferLimit(TransferLimitsBalanceAccountLevelService.DeletePendingTransferLimitApiResponse apiResponse) + { + OnDeletePendingTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeletePendingTransferLimit(Exception exception) + { + OnErrorDeletePendingTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetSpecificTransferLimit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetSpecificTransferLimit; + + internal void ExecuteOnGetSpecificTransferLimit(TransferLimitsBalanceAccountLevelService.GetSpecificTransferLimitApiResponse apiResponse) + { + OnGetSpecificTransferLimit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetSpecificTransferLimit(Exception exception) + { + OnErrorGetSpecificTransferLimit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransferLimits; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransferLimits; + + internal void ExecuteOnGetTransferLimits(TransferLimitsBalanceAccountLevelService.GetTransferLimitsApiResponse apiResponse) + { + OnGetTransferLimits?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransferLimits(Exception exception) + { + OnErrorGetTransferLimits?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransferLimitsBalancePlatformLevelService : ITransferLimitsBalancePlatformLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransferLimitsBalancePlatformLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransferLimitsBalancePlatformLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransferLimitsBalancePlatformLevelServiceEvents transferLimitsBalancePlatformLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transferLimitsBalancePlatformLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a transfer limit Create a transfer limit for your balance platform using the unique `id` of your balance platform. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateTransferLimitAsync(string id, CreateTransferLimitRequest createTransferLimitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/transferLimits" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/transferLimits"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createTransferLimitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createTransferLimitRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TransferLimitsBalanceAccountLevelService.CreateTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/transferLimits", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateTransferLimit(exception); + throw; + } + } + /// + /// Delete a scheduled or pending transfer limit Delete a scheduled or pending transfer limit using its unique `transferLimitId`. You cannot delete an active limit. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeletePendingTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/transferLimits/{transferLimitId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/transferLimits/{transferLimitId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransferLimitId%7D", Uri.EscapeDataString(transferLimitId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TransferLimitsBalanceAccountLevelService.DeletePendingTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/transferLimits/{transferLimitId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeletePendingTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeletePendingTransferLimit(exception); + throw; + } + } + /// + /// Get the details of a transfer limit Get the details of a transfer limit using its unique `transferLimitId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The unique identifier of the transfer limit. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetSpecificTransferLimitAsync(string id, string transferLimitId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/transferLimits/{transferLimitId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/transferLimits/{transferLimitId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransferLimitId%7D", Uri.EscapeDataString(transferLimitId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TransferLimitsBalanceAccountLevelService.GetSpecificTransferLimitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/transferLimits/{transferLimitId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetSpecificTransferLimit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetSpecificTransferLimit(exception); + throw; + } + } + /// + /// Filter and view the transfer limits Filter and view the transfer limits configured for your balance platform using the balance platform's unique `id` and the available query parameters. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the balance platform. + /// The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. () + /// The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. () + /// The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransferLimitsAsync(string id, Option scope = default, Option transferType = default, Option status = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/balancePlatforms/{id}/transferLimits" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/balancePlatforms/{id}/transferLimits"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (scope.IsSet) + parseQueryString["scope"] = ClientUtils.ParameterToString(scope.Value); + + if (transferType.IsSet) + parseQueryString["transferType"] = ClientUtils.ParameterToString(transferType.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TransferLimitsBalanceAccountLevelService.GetTransferLimitsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/balancePlatforms/{id}/transferLimits", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransferLimits(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransferLimits(exception); + throw; + } + } + } +} diff --git a/Adyen/BalancePlatform/Services/TransferRoutesService.cs b/Adyen/BalancePlatform/Services/TransferRoutesService.cs new file mode 100644 index 000000000..2dba3adc9 --- /dev/null +++ b/Adyen/BalancePlatform/Services/TransferRoutesService.cs @@ -0,0 +1,499 @@ +// +/* + * Configuration API + * + * The Configuration API allows you to manage your balance platform where you can create account holders, balance accounts, cards, and business accounts. ## Authentication Each request to the Configuration API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BalancePlatform.Client; +using Adyen.BalancePlatform.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BalancePlatform.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransferRoutesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransferRoutesServiceEvents Events { get; } + + /// + /// Calculate transfer routes + /// + /// + /// Returns available transfer routes based on a combination of transfer `country`, `currency`, `counterparty`, and `priorities`. Use this endpoint to find optimal transfer priorities and associated requirements before you [make a transfer](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CalculateTransferRoutesAsync(TransferRouteRequest transferRouteRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICalculateTransferRoutesApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransferRoutesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCalculateTransferRoutes; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCalculateTransferRoutes; + + internal void ExecuteOnCalculateTransferRoutes(TransferRoutesService.CalculateTransferRoutesApiResponse apiResponse) + { + OnCalculateTransferRoutes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCalculateTransferRoutes(Exception exception) + { + OnErrorCalculateTransferRoutes?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransferRoutesService : ITransferRoutesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransferRoutesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransferRoutesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransferRoutesServiceEvents transferRoutesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transferRoutesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Calculate transfer routes Returns available transfer routes based on a combination of transfer `country`, `currency`, `counterparty`, and `priorities`. Use this endpoint to find optimal transfer priorities and associated requirements before you [make a transfer](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CalculateTransferRoutesAsync(TransferRouteRequest transferRouteRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transferRoutes/calculate" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transferRoutes/calculate"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transferRouteRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transferRouteRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CalculateTransferRoutesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transferRoutes/calculate", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCalculateTransferRoutes(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCalculateTransferRoutes(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CalculateTransferRoutesApiResponse : Adyen.Core.Client.ApiResponse, ICalculateTransferRoutesApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CalculateTransferRoutesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CalculateTransferRoutesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BalancePlatform.Models.TransferRouteResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.TransferRouteResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BalancePlatform.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BalancePlatform.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/BalanceWebhooks/Client/ApiKeyToken.cs b/Adyen/BalanceWebhooks/Client/ApiKeyToken.cs new file mode 100644 index 000000000..7ac7e9557 --- /dev/null +++ b/Adyen/BalanceWebhooks/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.BalanceWebhooks.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/BalanceWebhooks/Client/ClientUtils.cs b/Adyen/BalanceWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..4d8757a6f --- /dev/null +++ b/Adyen/BalanceWebhooks/Client/ClientUtils.cs @@ -0,0 +1,315 @@ +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.BalanceWebhooks.Models; +using Models = Adyen.BalanceWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.BalanceWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.BalanceAccountBalanceNotificationRequest.TypeEnum balanceAccountBalanceNotificationRequestTypeEnum) + return Models.BalanceAccountBalanceNotificationRequest.TypeEnum.ToJsonValue(balanceAccountBalanceNotificationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/BalanceWebhooks/Client/HmacKeyToken.cs b/Adyen/BalanceWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..d7f0a4a13 --- /dev/null +++ b/Adyen/BalanceWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.BalanceWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/BalanceWebhooks/Client/HostConfiguration.cs b/Adyen/BalanceWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..7b3550af2 --- /dev/null +++ b/Adyen/BalanceWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,136 @@ +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.BalanceWebhooks.Client; +using Adyen.BalanceWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.BalanceWebhooks.Client +{ + /// + /// Provides hosting configuration for BalanceWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountBalanceNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalanceNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new BalancesJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddBalanceWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/BalanceWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/BalanceWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..a97c6a7e2 --- /dev/null +++ b/Adyen/BalanceWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.BalanceWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/BalanceWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/BalanceWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..1aee848c9 --- /dev/null +++ b/Adyen/BalanceWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.BalanceWebhooks; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the BalanceWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureBalanceWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddBalanceWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/BalanceWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/BalanceWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..4b5254ade --- /dev/null +++ b/Adyen/BalanceWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen BalanceWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddBalanceWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddBalanceWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/BalanceWebhooks/Handlers/BalanceWebhooksHandler.cs b/Adyen/BalanceWebhooks/Handlers/BalanceWebhooksHandler.cs new file mode 100644 index 000000000..b7c49d160 --- /dev/null +++ b/Adyen/BalanceWebhooks/Handlers/BalanceWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.BalanceWebhooks.Client; +using Adyen.BalanceWebhooks.Models; + +namespace Adyen.BalanceWebhooks.Handlers +{ + /// + /// Interface for deserializing BalanceWebhooks webhooks or verify its HMAC signature. + /// + public interface IBalanceWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.BalanceWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + BalanceAccountBalanceNotificationRequest? DeserializeBalanceAccountBalanceNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize BalanceWebhooks or verify the HMAC signature of the webhook. + /// + public partial class BalanceWebhooksHandler : IBalanceWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.BalanceWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing BalanceWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public BalanceWebhooksHandler(Adyen.BalanceWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public BalanceAccountBalanceNotificationRequest? DeserializeBalanceAccountBalanceNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/BalanceWebhooks/Models/BalanceAccountBalanceNotificationRequest.cs b/Adyen/BalanceWebhooks/Models/BalanceAccountBalanceNotificationRequest.cs new file mode 100644 index 000000000..f91095e2f --- /dev/null +++ b/Adyen/BalanceWebhooks/Models/BalanceAccountBalanceNotificationRequest.cs @@ -0,0 +1,336 @@ +// +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Models +{ + /// + /// BalanceAccountBalanceNotificationRequest. + /// + public partial class BalanceAccountBalanceNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public BalanceAccountBalanceNotificationRequest(BalanceNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountBalanceNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformBalanceAccountBalanceUpdated - balancePlatform.balanceAccount.balance.updated + /// + public static readonly TypeEnum BalancePlatformBalanceAccountBalanceUpdated = new("balancePlatform.balanceAccount.balance.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.balanceAccount.balance.updated" => TypeEnum.BalancePlatformBalanceAccountBalanceUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformBalanceAccountBalanceUpdated) + return "balancePlatform.balanceAccount.balance.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public BalanceNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountBalanceNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountBalanceNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountBalanceNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceAccountBalanceNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountBalanceNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountBalanceNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountBalanceNotificationRequest.", nameof(type)); + + return new BalanceAccountBalanceNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountBalanceNotificationRequest balanceAccountBalanceNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountBalanceNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountBalanceNotificationRequest balanceAccountBalanceNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, balanceAccountBalanceNotificationRequest.Data, jsonSerializerOptions); + if (balanceAccountBalanceNotificationRequest.Environment != null) + writer.WriteString("environment", balanceAccountBalanceNotificationRequest.Environment); + + if (balanceAccountBalanceNotificationRequest.Type != null) + { + string? typeRawValue = BalanceAccountBalanceNotificationRequest.TypeEnum.ToJsonValue(balanceAccountBalanceNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (balanceAccountBalanceNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", balanceAccountBalanceNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/BalanceWebhooks/Models/BalanceNotificationData.cs b/Adyen/BalanceWebhooks/Models/BalanceNotificationData.cs new file mode 100644 index 000000000..8386b7aa4 --- /dev/null +++ b/Adyen/BalanceWebhooks/Models/BalanceNotificationData.cs @@ -0,0 +1,307 @@ +// +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Models +{ + /// + /// BalanceNotificationData. + /// + public partial class BalanceNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance account. + /// balances + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// The unique identifier of the balance webhook setting. + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public BalanceNotificationData(string balanceAccountId, Balances balances, string currency, List settingIds, Option balancePlatform = default, Option creationDate = default, Option id = default) + { + BalanceAccountId = balanceAccountId; + Balances = balances; + Currency = currency; + SettingIds = settingIds; + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceNotificationData() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the balance account. + /// + /// The unique identifier of the balance account. + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// . + /// + [JsonPropertyName("balances")] + public Balances Balances { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The unique identifier of the balance webhook setting. + /// + /// The unique identifier of the balance webhook setting. + [JsonPropertyName("settingIds")] + public List SettingIds { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceNotificationData {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" SettingIds: ").Append(SettingIds).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceNotificationDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option balances = default; + Option currency = default; + Option?> settingIds = default; + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "balances": + balances = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "settingIds": + settingIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class BalanceNotificationData.", nameof(balanceAccountId)); + + if (!balances.IsSet) + throw new ArgumentException("Property is required for class BalanceNotificationData.", nameof(balances)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class BalanceNotificationData.", nameof(currency)); + + if (!settingIds.IsSet) + throw new ArgumentException("Property is required for class BalanceNotificationData.", nameof(settingIds)); + + return new BalanceNotificationData(balanceAccountId.Value!, balances.Value!, currency.Value!, settingIds.Value!, balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceNotificationData balanceNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceNotificationData balanceNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceNotificationData.BalanceAccountId != null) + writer.WriteString("balanceAccountId", balanceNotificationData.BalanceAccountId); + + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, balanceNotificationData.Balances, jsonSerializerOptions); + if (balanceNotificationData.Currency != null) + writer.WriteString("currency", balanceNotificationData.Currency); + + writer.WritePropertyName("settingIds"); + JsonSerializer.Serialize(writer, balanceNotificationData.SettingIds, jsonSerializerOptions); + if (balanceNotificationData._BalancePlatformOption.IsSet) + if (balanceNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", balanceNotificationData.BalancePlatform); + + if (balanceNotificationData._CreationDateOption.IsSet) + writer.WriteString("creationDate", balanceNotificationData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (balanceNotificationData._IdOption.IsSet) + if (balanceNotificationData.Id != null) + writer.WriteString("id", balanceNotificationData.Id); + } + } +} diff --git a/Adyen/BalanceWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/BalanceWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..c0a8c0f9b --- /dev/null +++ b/Adyen/BalanceWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/BalanceWebhooks/Models/Balances.cs b/Adyen/BalanceWebhooks/Models/Balances.cs new file mode 100644 index 000000000..fd4143055 --- /dev/null +++ b/Adyen/BalanceWebhooks/Models/Balances.cs @@ -0,0 +1,248 @@ +// +/* + * Balance webhook + * + * Adyen sends webhooks to inform you of balance changes in your balance platform. You can use the [Configuration API](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balancePlatforms/(id)/webhooks/(id)/settings) to set the conditions that a balance change must meet for Adyen to send a balance webhook: - In your entire balance platform - In the balance accounts of specific account holders - In a specific balance account + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BalanceWebhooks.Client; + +namespace Adyen.BalanceWebhooks.Models +{ + /// + /// Balances. + /// + public partial class Balances : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The balance that is available for use. + /// The sum of transactions that have already been settled. + /// The sum of transactions that will be settled in the future. + /// The balance currently held in reserve. + [JsonConstructor] + public Balances(Option available = default, Option balance = default, Option pending = default, Option reserved = default) + { + _AvailableOption = available; + _BalanceOption = balance; + _PendingOption = pending; + _ReservedOption = reserved; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Balances() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvailableOption { get; private set; } + + /// + /// The balance that is available for use. + /// + /// The balance that is available for use. + [JsonPropertyName("available")] + public long? Available { get { return this._AvailableOption; } set { this._AvailableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceOption { get; private set; } + + /// + /// The sum of transactions that have already been settled. + /// + /// The sum of transactions that have already been settled. + [JsonPropertyName("balance")] + public long? Balance { get { return this._BalanceOption; } set { this._BalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PendingOption { get; private set; } + + /// + /// The sum of transactions that will be settled in the future. + /// + /// The sum of transactions that will be settled in the future. + [JsonPropertyName("pending")] + public long? Pending { get { return this._PendingOption; } set { this._PendingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReservedOption { get; private set; } + + /// + /// The balance currently held in reserve. + /// + /// The balance currently held in reserve. + [JsonPropertyName("reserved")] + public long? Reserved { get { return this._ReservedOption; } set { this._ReservedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Balances {\n"); + sb.Append(" Available: ").Append(Available).Append("\n"); + sb.Append(" Balance: ").Append(Balance).Append("\n"); + sb.Append(" Pending: ").Append(Pending).Append("\n"); + sb.Append(" Reserved: ").Append(Reserved).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Balances Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option available = default; + Option balance = default; + Option pending = default; + Option reserved = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "available": + available = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "balance": + balance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "pending": + pending = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "reserved": + reserved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new Balances(available, balance, pending, reserved); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Balances balances, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balances, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Balances balances, JsonSerializerOptions jsonSerializerOptions) + { + + if (balances._AvailableOption.IsSet) + writer.WriteNumber("available", balances._AvailableOption.Value!.Value); + + if (balances._BalanceOption.IsSet) + writer.WriteNumber("balance", balances._BalanceOption.Value!.Value); + + if (balances._PendingOption.IsSet) + writer.WriteNumber("pending", balances._PendingOption.Value!.Value); + + if (balances._ReservedOption.IsSet) + writer.WriteNumber("reserved", balances._ReservedOption.Value!.Value); + } + } +} diff --git a/Adyen/BinLookup/Client/ApiKeyToken.cs b/Adyen/BinLookup/Client/ApiKeyToken.cs new file mode 100644 index 000000000..ce42904f8 --- /dev/null +++ b/Adyen/BinLookup/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.BinLookup.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/BinLookup/Client/ClientUtils.cs b/Adyen/BinLookup/Client/ClientUtils.cs new file mode 100644 index 000000000..3d1ac2790 --- /dev/null +++ b/Adyen/BinLookup/Client/ClientUtils.cs @@ -0,0 +1,319 @@ +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.BinLookup.Models; +using Models = Adyen.BinLookup.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.BinLookup.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.CostEstimateRequest.ShopperInteractionEnum costEstimateRequestShopperInteractionEnum) + return Models.CostEstimateRequest.ShopperInteractionEnum.ToJsonValue(costEstimateRequestShopperInteractionEnum); + if (obj is Models.Recurring.ContractEnum recurringContractEnum) + return Models.Recurring.ContractEnum.ToJsonValue(recurringContractEnum); + if (obj is Models.Recurring.TokenServiceEnum recurringTokenServiceEnum) + return Models.Recurring.TokenServiceEnum.ToJsonValue(recurringTokenServiceEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/BinLookup/Client/HostConfiguration.cs b/Adyen/BinLookup/Client/HostConfiguration.cs new file mode 100644 index 000000000..8d6d0a3c4 --- /dev/null +++ b/Adyen/BinLookup/Client/HostConfiguration.cs @@ -0,0 +1,141 @@ +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.BinLookup.Services; +using Adyen.BinLookup.Client; +using Adyen.BinLookup.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.BinLookup.Client +{ + /// + /// Provides hosting configuration for BinLookup + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/BinLookup/v54"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BinDetailJsonConverter()); + _jsonOptions.Converters.Add(new CardBinJsonConverter()); + _jsonOptions.Converters.Add(new CostEstimateAssumptionsJsonConverter()); + _jsonOptions.Converters.Add(new CostEstimateRequestJsonConverter()); + _jsonOptions.Converters.Add(new CostEstimateResponseJsonConverter()); + _jsonOptions.Converters.Add(new DSPublicKeyDetailJsonConverter()); + _jsonOptions.Converters.Add(new MerchantDetailsJsonConverter()); + _jsonOptions.Converters.Add(new RecurringJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2CardRangeDetailJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSAvailabilityRequestJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSAvailabilityResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddBinLookupHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/BinLookup/Client/JsonSerializerOptionsProvider.cs b/Adyen/BinLookup/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..16f3f6f23 --- /dev/null +++ b/Adyen/BinLookup/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.BinLookup.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/BinLookup/Extensions/HostBuilderExtensions.cs b/Adyen/BinLookup/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..090b8cd81 --- /dev/null +++ b/Adyen/BinLookup/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.BinLookup; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the BinLookup API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureBinLookup(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddBinLookupHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/BinLookup/Extensions/ServiceCollectionExtensions.cs b/Adyen/BinLookup/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..7c8a7860c --- /dev/null +++ b/Adyen/BinLookup/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen BinLookup API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddBinLookupServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddBinLookupHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/BinLookup/Models/Amount.cs b/Adyen/BinLookup/Models/Amount.cs new file mode 100644 index 000000000..9fc1d3bd7 --- /dev/null +++ b/Adyen/BinLookup/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/BinLookup/Models/BinDetail.cs b/Adyen/BinLookup/Models/BinDetail.cs new file mode 100644 index 000000000..ded717b14 --- /dev/null +++ b/Adyen/BinLookup/Models/BinDetail.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// BinDetail. + /// + public partial class BinDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The country where the card was issued. + [JsonConstructor] + public BinDetail(Option issuerCountry = default) + { + _IssuerCountryOption = issuerCountry; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BinDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The country where the card was issued. + /// + /// The country where the card was issued. + [JsonPropertyName("issuerCountry")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BinDetail {\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BinDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BinDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issuerCountry = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BinDetail(issuerCountry); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BinDetail binDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, binDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BinDetail binDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (binDetail._IssuerCountryOption.IsSet) + if (binDetail.IssuerCountry != null) + writer.WriteString("issuerCountry", binDetail.IssuerCountry); + } + } +} diff --git a/Adyen/BinLookup/Models/CardBin.cs b/Adyen/BinLookup/Models/CardBin.cs new file mode 100644 index 000000000..3925aac5f --- /dev/null +++ b/Adyen/BinLookup/Models/CardBin.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// CardBin. + /// + public partial class CardBin : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first 6 digit of the card number. Enable this field via merchant account settings. + /// If true, it indicates a commercial card. Enable this field via merchant account settings. + /// The card funding source. Valid values are: * CHARGE * CREDIT * DEBIT * DEFERRED_DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE > Enable this field via merchant account settings. + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + /// The first 8 digit of the card number. Enable this field via merchant account settings. + /// The issuing bank of the card. + /// The country where the card was issued from. + /// The currency of the card. + /// The payment method associated with the card (e.g. visa, mc, or amex). + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + /// The last four digits of the card number. + [JsonConstructor] + public CardBin(Option bin = default, Option commercial = default, Option fundingSource = default, Option fundsAvailability = default, Option issuerBin = default, Option issuingBank = default, Option issuingCountry = default, Option issuingCurrency = default, Option paymentMethod = default, Option payoutEligible = default, Option summary = default) + { + _BinOption = bin; + _CommercialOption = commercial; + _FundingSourceOption = fundingSource; + _FundsAvailabilityOption = fundsAvailability; + _IssuerBinOption = issuerBin; + _IssuingBankOption = issuingBank; + _IssuingCountryOption = issuingCountry; + _IssuingCurrencyOption = issuingCurrency; + _PaymentMethodOption = paymentMethod; + _PayoutEligibleOption = payoutEligible; + _SummaryOption = summary; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardBin() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinOption { get; private set; } + + /// + /// The first 6 digit of the card number. Enable this field via merchant account settings. + /// + /// The first 6 digit of the card number. Enable this field via merchant account settings. + [JsonPropertyName("bin")] + public string? Bin { get { return this._BinOption; } set { this._BinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CommercialOption { get; private set; } + + /// + /// If true, it indicates a commercial card. Enable this field via merchant account settings. + /// + /// If true, it indicates a commercial card. Enable this field via merchant account settings. + [JsonPropertyName("commercial")] + public bool? Commercial { get { return this._CommercialOption; } set { this._CommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The card funding source. Valid values are: * CHARGE * CREDIT * DEBIT * DEFERRED_DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE > Enable this field via merchant account settings. + /// + /// The card funding source. Valid values are: * CHARGE * CREDIT * DEBIT * DEFERRED_DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE > Enable this field via merchant account settings. + [JsonPropertyName("fundingSource")] + public string? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundsAvailabilityOption { get; private set; } + + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + [JsonPropertyName("fundsAvailability")] + public string? FundsAvailability { get { return this._FundsAvailabilityOption; } set { this._FundsAvailabilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerBinOption { get; private set; } + + /// + /// The first 8 digit of the card number. Enable this field via merchant account settings. + /// + /// The first 8 digit of the card number. Enable this field via merchant account settings. + [JsonPropertyName("issuerBin")] + public string? IssuerBin { get { return this._IssuerBinOption; } set { this._IssuerBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuingBankOption { get; private set; } + + /// + /// The issuing bank of the card. + /// + /// The issuing bank of the card. + [JsonPropertyName("issuingBank")] + public string? IssuingBank { get { return this._IssuingBankOption; } set { this._IssuingBankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuingCountryOption { get; private set; } + + /// + /// The country where the card was issued from. + /// + /// The country where the card was issued from. + [JsonPropertyName("issuingCountry")] + public string? IssuingCountry { get { return this._IssuingCountryOption; } set { this._IssuingCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuingCurrencyOption { get; private set; } + + /// + /// The currency of the card. + /// + /// The currency of the card. + [JsonPropertyName("issuingCurrency")] + public string? IssuingCurrency { get { return this._IssuingCurrencyOption; } set { this._IssuingCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// The payment method associated with the card (e.g. visa, mc, or amex). + /// + /// The payment method associated with the card (e.g. visa, mc, or amex). + [JsonPropertyName("paymentMethod")] + public string? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayoutEligibleOption { get; private set; } + + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) > Returned when you verify a card BIN or estimate costs, and only if `payoutEligible` is different from \"N\" or \"U\". + [JsonPropertyName("payoutEligible")] + public string? PayoutEligible { get { return this._PayoutEligibleOption; } set { this._PayoutEligibleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SummaryOption { get; private set; } + + /// + /// The last four digits of the card number. + /// + /// The last four digits of the card number. + [JsonPropertyName("summary")] + public string? Summary { get { return this._SummaryOption; } set { this._SummaryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardBin {\n"); + sb.Append(" Bin: ").Append(Bin).Append("\n"); + sb.Append(" Commercial: ").Append(Commercial).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" FundsAvailability: ").Append(FundsAvailability).Append("\n"); + sb.Append(" IssuerBin: ").Append(IssuerBin).Append("\n"); + sb.Append(" IssuingBank: ").Append(IssuingBank).Append("\n"); + sb.Append(" IssuingCountry: ").Append(IssuingCountry).Append("\n"); + sb.Append(" IssuingCurrency: ").Append(IssuingCurrency).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PayoutEligible: ").Append(PayoutEligible).Append("\n"); + sb.Append(" Summary: ").Append(Summary).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardBinJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardBin Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bin = default; + Option commercial = default; + Option fundingSource = default; + Option fundsAvailability = default; + Option issuerBin = default; + Option issuingBank = default; + Option issuingCountry = default; + Option issuingCurrency = default; + Option paymentMethod = default; + Option payoutEligible = default; + Option summary = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bin": + bin = new Option(utf8JsonReader.GetString()!); + break; + case "commercial": + commercial = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "fundsAvailability": + fundsAvailability = new Option(utf8JsonReader.GetString()!); + break; + case "issuerBin": + issuerBin = new Option(utf8JsonReader.GetString()!); + break; + case "issuingBank": + issuingBank = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountry": + issuingCountry = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCurrency": + issuingCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "payoutEligible": + payoutEligible = new Option(utf8JsonReader.GetString()!); + break; + case "summary": + summary = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardBin(bin, commercial, fundingSource, fundsAvailability, issuerBin, issuingBank, issuingCountry, issuingCurrency, paymentMethod, payoutEligible, summary); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardBin cardBin, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardBin, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardBin cardBin, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardBin._BinOption.IsSet) + if (cardBin.Bin != null) + writer.WriteString("bin", cardBin.Bin); + + if (cardBin._CommercialOption.IsSet) + writer.WriteBoolean("commercial", cardBin._CommercialOption.Value!.Value); + + if (cardBin._FundingSourceOption.IsSet) + if (cardBin.FundingSource != null) + writer.WriteString("fundingSource", cardBin.FundingSource); + + if (cardBin._FundsAvailabilityOption.IsSet) + if (cardBin.FundsAvailability != null) + writer.WriteString("fundsAvailability", cardBin.FundsAvailability); + + if (cardBin._IssuerBinOption.IsSet) + if (cardBin.IssuerBin != null) + writer.WriteString("issuerBin", cardBin.IssuerBin); + + if (cardBin._IssuingBankOption.IsSet) + if (cardBin.IssuingBank != null) + writer.WriteString("issuingBank", cardBin.IssuingBank); + + if (cardBin._IssuingCountryOption.IsSet) + if (cardBin.IssuingCountry != null) + writer.WriteString("issuingCountry", cardBin.IssuingCountry); + + if (cardBin._IssuingCurrencyOption.IsSet) + if (cardBin.IssuingCurrency != null) + writer.WriteString("issuingCurrency", cardBin.IssuingCurrency); + + if (cardBin._PaymentMethodOption.IsSet) + if (cardBin.PaymentMethod != null) + writer.WriteString("paymentMethod", cardBin.PaymentMethod); + + if (cardBin._PayoutEligibleOption.IsSet) + if (cardBin.PayoutEligible != null) + writer.WriteString("payoutEligible", cardBin.PayoutEligible); + + if (cardBin._SummaryOption.IsSet) + if (cardBin.Summary != null) + writer.WriteString("summary", cardBin.Summary); + } + } +} diff --git a/Adyen/BinLookup/Models/CostEstimateAssumptions.cs b/Adyen/BinLookup/Models/CostEstimateAssumptions.cs new file mode 100644 index 000000000..4e74873e2 --- /dev/null +++ b/Adyen/BinLookup/Models/CostEstimateAssumptions.cs @@ -0,0 +1,224 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// CostEstimateAssumptions. + /// + public partial class CostEstimateAssumptions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// If true, the cardholder is expected to successfully authorise via 3D Secure. + /// If true, the transaction is expected to have valid Level 3 data. + /// If not zero, the number of installments. + [JsonConstructor] + public CostEstimateAssumptions(Option assume3DSecureAuthenticated = default, Option assumeLevel3Data = default, Option installments = default) + { + _Assume3DSecureAuthenticatedOption = assume3DSecureAuthenticated; + _AssumeLevel3DataOption = assumeLevel3Data; + _InstallmentsOption = installments; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CostEstimateAssumptions() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Assume3DSecureAuthenticatedOption { get; private set; } + + /// + /// If true, the cardholder is expected to successfully authorise via 3D Secure. + /// + /// If true, the cardholder is expected to successfully authorise via 3D Secure. + [JsonPropertyName("assume3DSecureAuthenticated")] + public bool? Assume3DSecureAuthenticated { get { return this._Assume3DSecureAuthenticatedOption; } set { this._Assume3DSecureAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssumeLevel3DataOption { get; private set; } + + /// + /// If true, the transaction is expected to have valid Level 3 data. + /// + /// If true, the transaction is expected to have valid Level 3 data. + [JsonPropertyName("assumeLevel3Data")] + public bool? AssumeLevel3Data { get { return this._AssumeLevel3DataOption; } set { this._AssumeLevel3DataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// If not zero, the number of installments. + /// + /// If not zero, the number of installments. + [JsonPropertyName("installments")] + public int? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CostEstimateAssumptions {\n"); + sb.Append(" Assume3DSecureAuthenticated: ").Append(Assume3DSecureAuthenticated).Append("\n"); + sb.Append(" AssumeLevel3Data: ").Append(AssumeLevel3Data).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CostEstimateAssumptionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CostEstimateAssumptions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option assume3DSecureAuthenticated = default; + Option assumeLevel3Data = default; + Option installments = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "assume3DSecureAuthenticated": + assume3DSecureAuthenticated = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "assumeLevel3Data": + assumeLevel3Data = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "installments": + installments = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new CostEstimateAssumptions(assume3DSecureAuthenticated, assumeLevel3Data, installments); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CostEstimateAssumptions costEstimateAssumptions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, costEstimateAssumptions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CostEstimateAssumptions costEstimateAssumptions, JsonSerializerOptions jsonSerializerOptions) + { + + if (costEstimateAssumptions._Assume3DSecureAuthenticatedOption.IsSet) + writer.WriteBoolean("assume3DSecureAuthenticated", costEstimateAssumptions._Assume3DSecureAuthenticatedOption.Value!.Value); + + if (costEstimateAssumptions._AssumeLevel3DataOption.IsSet) + writer.WriteBoolean("assumeLevel3Data", costEstimateAssumptions._AssumeLevel3DataOption.Value!.Value); + + if (costEstimateAssumptions._InstallmentsOption.IsSet) + writer.WriteNumber("installments", costEstimateAssumptions._InstallmentsOption.Value!.Value); + } + } +} diff --git a/Adyen/BinLookup/Models/CostEstimateRequest.cs b/Adyen/BinLookup/Models/CostEstimateRequest.cs new file mode 100644 index 000000000..bfa0f76ad --- /dev/null +++ b/Adyen/BinLookup/Models/CostEstimateRequest.cs @@ -0,0 +1,525 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// CostEstimateRequest. + /// + public partial class CostEstimateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier you want to process the (transaction) request with. + /// assumptions + /// The card number (4-19 characters) for PCI compliant use cases. Do not use any separators. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + /// Encrypted data that stores card information for non PCI-compliant use cases. The encrypted data must be created with the Checkout Card Component or Secured Fields Component, and must contain the `encryptedCardNumber` field. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + /// merchantDetails + /// recurring + /// The `recurringDetailReference` you want to use for this cost estimate. The value `LATEST` can be used to select the most recently stored recurring detail. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the card holder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonConstructor] + public CostEstimateRequest(Amount amount, string merchantAccount, Option assumptions = default, Option cardNumber = default, Option encryptedCardNumber = default, Option merchantDetails = default, Option recurring = default, Option selectedRecurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + _AssumptionsOption = assumptions; + _CardNumberOption = cardNumber; + _EncryptedCardNumberOption = encryptedCardNumber; + _MerchantDetailsOption = merchantDetails; + _RecurringOption = recurring; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CostEstimateRequest() + { + } + + partial void OnCreated(); + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the card holder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the card holder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the card holder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the card holder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier you want to process the (transaction) request with. + /// + /// The merchant account identifier you want to process the (transaction) request with. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssumptionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("assumptions")] + public CostEstimateAssumptions? Assumptions { get { return this._AssumptionsOption; } set { this._AssumptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardNumberOption { get; private set; } + + /// + /// The card number (4-19 characters) for PCI compliant use cases. Do not use any separators. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + /// + /// The card number (4-19 characters) for PCI compliant use cases. Do not use any separators. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + [JsonPropertyName("cardNumber")] + public string? CardNumber { get { return this._CardNumberOption; } set { this._CardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardNumberOption { get; private set; } + + /// + /// Encrypted data that stores card information for non PCI-compliant use cases. The encrypted data must be created with the Checkout Card Component or Secured Fields Component, and must contain the `encryptedCardNumber` field. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + /// + /// Encrypted data that stores card information for non PCI-compliant use cases. The encrypted data must be created with the Checkout Card Component or Secured Fields Component, and must contain the `encryptedCardNumber` field. > Either the `cardNumber` or `encryptedCardNumber` field must be provided in a payment request. + [JsonPropertyName("encryptedCardNumber")] + public string? EncryptedCardNumber { get { return this._EncryptedCardNumberOption; } set { this._EncryptedCardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantDetails")] + public MerchantDetails? MerchantDetails { get { return this._MerchantDetailsOption; } set { this._MerchantDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this cost estimate. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this cost estimate. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CostEstimateRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Assumptions: ").Append(Assumptions).Append("\n"); + sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); + sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); + sb.Append(" MerchantDetails: ").Append(MerchantDetails).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CardNumber (string) maxLength + if (this.CardNumber != null && this.CardNumber.Length > 19) + { + yield return new ValidationResult("Invalid value for CardNumber, length must be less than 19.", new [] { "CardNumber" }); + } + + // CardNumber (string) minLength + if (this.CardNumber != null && this.CardNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for CardNumber, length must be greater than 4.", new [] { "CardNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CostEstimateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CostEstimateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option assumptions = default; + Option cardNumber = default; + Option encryptedCardNumber = default; + Option merchantDetails = default; + Option recurring = default; + Option selectedRecurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "assumptions": + assumptions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardNumber": + cardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCardNumber": + encryptedCardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "merchantDetails": + merchantDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(CostEstimateRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CostEstimateRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CostEstimateRequest.", nameof(merchantAccount)); + + return new CostEstimateRequest(amount.Value!, merchantAccount.Value!, assumptions, cardNumber, encryptedCardNumber, merchantDetails, recurring, selectedRecurringDetailReference, shopperInteraction, shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CostEstimateRequest costEstimateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, costEstimateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CostEstimateRequest costEstimateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, costEstimateRequest.Amount, jsonSerializerOptions); + if (costEstimateRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", costEstimateRequest.MerchantAccount); + + if (costEstimateRequest._AssumptionsOption.IsSet) + { + writer.WritePropertyName("assumptions"); + JsonSerializer.Serialize(writer, costEstimateRequest.Assumptions, jsonSerializerOptions); + } + if (costEstimateRequest._CardNumberOption.IsSet) + if (costEstimateRequest.CardNumber != null) + writer.WriteString("cardNumber", costEstimateRequest.CardNumber); + + if (costEstimateRequest._EncryptedCardNumberOption.IsSet) + if (costEstimateRequest.EncryptedCardNumber != null) + writer.WriteString("encryptedCardNumber", costEstimateRequest.EncryptedCardNumber); + + if (costEstimateRequest._MerchantDetailsOption.IsSet) + { + writer.WritePropertyName("merchantDetails"); + JsonSerializer.Serialize(writer, costEstimateRequest.MerchantDetails, jsonSerializerOptions); + } + if (costEstimateRequest._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, costEstimateRequest.Recurring, jsonSerializerOptions); + } + if (costEstimateRequest._SelectedRecurringDetailReferenceOption.IsSet) + if (costEstimateRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", costEstimateRequest.SelectedRecurringDetailReference); + + if (costEstimateRequest._ShopperInteractionOption.IsSet && costEstimateRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = CostEstimateRequest.ShopperInteractionEnum.ToJsonValue(costEstimateRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (costEstimateRequest._ShopperReferenceOption.IsSet) + if (costEstimateRequest.ShopperReference != null) + writer.WriteString("shopperReference", costEstimateRequest.ShopperReference); + } + } +} diff --git a/Adyen/BinLookup/Models/CostEstimateResponse.cs b/Adyen/BinLookup/Models/CostEstimateResponse.cs new file mode 100644 index 000000000..594f5142c --- /dev/null +++ b/Adyen/BinLookup/Models/CostEstimateResponse.cs @@ -0,0 +1,252 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// CostEstimateResponse. + /// + public partial class CostEstimateResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cardBin + /// costEstimateAmount + /// Adyen's 16-character reference associated with the request. + /// The result of the cost estimation. + [JsonConstructor] + public CostEstimateResponse(Option cardBin = default, Option costEstimateAmount = default, Option costEstimateReference = default, Option resultCode = default) + { + _CardBinOption = cardBin; + _CostEstimateAmountOption = costEstimateAmount; + _CostEstimateReferenceOption = costEstimateReference; + _ResultCodeOption = resultCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CostEstimateResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardBinOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cardBin")] + public CardBin? CardBin { get { return this._CardBinOption; } set { this._CardBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CostEstimateAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("costEstimateAmount")] + public Amount? CostEstimateAmount { get { return this._CostEstimateAmountOption; } set { this._CostEstimateAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CostEstimateReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the request. + /// + /// Adyen's 16-character reference associated with the request. + [JsonPropertyName("costEstimateReference")] + public string? CostEstimateReference { get { return this._CostEstimateReferenceOption; } set { this._CostEstimateReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the cost estimation. + /// + /// The result of the cost estimation. + [JsonPropertyName("resultCode")] + public string? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CostEstimateResponse {\n"); + sb.Append(" CardBin: ").Append(CardBin).Append("\n"); + sb.Append(" CostEstimateAmount: ").Append(CostEstimateAmount).Append("\n"); + sb.Append(" CostEstimateReference: ").Append(CostEstimateReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CostEstimateResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CostEstimateResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardBin = default; + Option costEstimateAmount = default; + Option costEstimateReference = default; + Option resultCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardBin": + cardBin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "costEstimateAmount": + costEstimateAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "costEstimateReference": + costEstimateReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CostEstimateResponse(cardBin, costEstimateAmount, costEstimateReference, resultCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CostEstimateResponse costEstimateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, costEstimateResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CostEstimateResponse costEstimateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (costEstimateResponse._CardBinOption.IsSet) + { + writer.WritePropertyName("cardBin"); + JsonSerializer.Serialize(writer, costEstimateResponse.CardBin, jsonSerializerOptions); + } + if (costEstimateResponse._CostEstimateAmountOption.IsSet) + { + writer.WritePropertyName("costEstimateAmount"); + JsonSerializer.Serialize(writer, costEstimateResponse.CostEstimateAmount, jsonSerializerOptions); + } + if (costEstimateResponse._CostEstimateReferenceOption.IsSet) + if (costEstimateResponse.CostEstimateReference != null) + writer.WriteString("costEstimateReference", costEstimateResponse.CostEstimateReference); + + if (costEstimateResponse._ResultCodeOption.IsSet) + if (costEstimateResponse.ResultCode != null) + writer.WriteString("resultCode", costEstimateResponse.ResultCode); + } + } +} diff --git a/Adyen/BinLookup/Models/DSPublicKeyDetail.cs b/Adyen/BinLookup/Models/DSPublicKeyDetail.cs new file mode 100644 index 000000000..694f262e0 --- /dev/null +++ b/Adyen/BinLookup/Models/DSPublicKeyDetail.cs @@ -0,0 +1,278 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// DSPublicKeyDetail. + /// + public partial class DSPublicKeyDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Card brand. + /// Directory Server (DS) identifier. + /// The version of the mobile 3D Secure 2 SDK. For the possible values, refer to the versions in [Adyen 3DS2 Android](https://github.com/Adyen/adyen-3ds2-android/releases) and [Adyen 3DS2 iOS](https://github.com/Adyen/adyen-3ds2-ios/releases). + /// Public key. The 3D Secure 2 SDK encrypts the device information by using the DS public key. + /// Directory Server root certificates. The 3D Secure 2 SDK verifies the ACS signed content using the rootCertificates. + [JsonConstructor] + public DSPublicKeyDetail(Option brand = default, Option directoryServerId = default, Option fromSDKVersion = default, Option publicKey = default, Option rootCertificates = default) + { + _BrandOption = brand; + _DirectoryServerIdOption = directoryServerId; + _FromSDKVersionOption = fromSDKVersion; + _PublicKeyOption = publicKey; + _RootCertificatesOption = rootCertificates; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DSPublicKeyDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Card brand. + /// + /// Card brand. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectoryServerIdOption { get; private set; } + + /// + /// Directory Server (DS) identifier. + /// + /// Directory Server (DS) identifier. + [JsonPropertyName("directoryServerId")] + public string? DirectoryServerId { get { return this._DirectoryServerIdOption; } set { this._DirectoryServerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FromSDKVersionOption { get; private set; } + + /// + /// The version of the mobile 3D Secure 2 SDK. For the possible values, refer to the versions in [Adyen 3DS2 Android](https://github.com/Adyen/adyen-3ds2-android/releases) and [Adyen 3DS2 iOS](https://github.com/Adyen/adyen-3ds2-ios/releases). + /// + /// The version of the mobile 3D Secure 2 SDK. For the possible values, refer to the versions in [Adyen 3DS2 Android](https://github.com/Adyen/adyen-3ds2-android/releases) and [Adyen 3DS2 iOS](https://github.com/Adyen/adyen-3ds2-ios/releases). + [JsonPropertyName("fromSDKVersion")] + public string? FromSDKVersion { get { return this._FromSDKVersionOption; } set { this._FromSDKVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PublicKeyOption { get; private set; } + + /// + /// Public key. The 3D Secure 2 SDK encrypts the device information by using the DS public key. + /// + /// Public key. The 3D Secure 2 SDK encrypts the device information by using the DS public key. + [JsonPropertyName("publicKey")] + public byte[]? PublicKey { get { return this._PublicKeyOption; } set { this._PublicKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RootCertificatesOption { get; private set; } + + /// + /// Directory Server root certificates. The 3D Secure 2 SDK verifies the ACS signed content using the rootCertificates. + /// + /// Directory Server root certificates. The 3D Secure 2 SDK verifies the ACS signed content using the rootCertificates. + [JsonPropertyName("rootCertificates")] + public string? RootCertificates { get { return this._RootCertificatesOption; } set { this._RootCertificatesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DSPublicKeyDetail {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" DirectoryServerId: ").Append(DirectoryServerId).Append("\n"); + sb.Append(" FromSDKVersion: ").Append(FromSDKVersion).Append("\n"); + sb.Append(" PublicKey: ").Append(PublicKey).Append("\n"); + sb.Append(" RootCertificates: ").Append(RootCertificates).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DSPublicKeyDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DSPublicKeyDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option directoryServerId = default; + Option fromSDKVersion = default; + Option publicKey = default; + Option rootCertificates = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "directoryServerId": + directoryServerId = new Option(utf8JsonReader.GetString()!); + break; + case "fromSDKVersion": + fromSDKVersion = new Option(utf8JsonReader.GetString()!); + break; + case "publicKey": + publicKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "rootCertificates": + rootCertificates = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DSPublicKeyDetail(brand, directoryServerId, fromSDKVersion, publicKey, rootCertificates); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DSPublicKeyDetail dSPublicKeyDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dSPublicKeyDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DSPublicKeyDetail dSPublicKeyDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (dSPublicKeyDetail._BrandOption.IsSet) + if (dSPublicKeyDetail.Brand != null) + writer.WriteString("brand", dSPublicKeyDetail.Brand); + + if (dSPublicKeyDetail._DirectoryServerIdOption.IsSet) + if (dSPublicKeyDetail.DirectoryServerId != null) + writer.WriteString("directoryServerId", dSPublicKeyDetail.DirectoryServerId); + + if (dSPublicKeyDetail._FromSDKVersionOption.IsSet) + if (dSPublicKeyDetail.FromSDKVersion != null) + writer.WriteString("fromSDKVersion", dSPublicKeyDetail.FromSDKVersion); + + if (dSPublicKeyDetail._PublicKeyOption.IsSet) + { + writer.WritePropertyName("publicKey"); + JsonSerializer.Serialize(writer, dSPublicKeyDetail.PublicKey, jsonSerializerOptions); + } + if (dSPublicKeyDetail._RootCertificatesOption.IsSet) + if (dSPublicKeyDetail.RootCertificates != null) + writer.WriteString("rootCertificates", dSPublicKeyDetail.RootCertificates); + } + } +} diff --git a/Adyen/BinLookup/Models/MerchantDetails.cs b/Adyen/BinLookup/Models/MerchantDetails.cs new file mode 100644 index 000000000..8880a72cb --- /dev/null +++ b/Adyen/BinLookup/Models/MerchantDetails.cs @@ -0,0 +1,238 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// MerchantDetails. + /// + public partial class MerchantDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// 2-letter ISO 3166 country code of the card acceptor location. > This parameter is required for the merchants who don't use Adyen as the payment authorisation gateway. + /// If true, indicates that the merchant is enrolled in 3D Secure for the card network. + /// The merchant category code (MCC) is a four-digit number which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. The list of MCCs can be found [here](https://en.wikipedia.org/wiki/Merchant_category_code). + [JsonConstructor] + public MerchantDetails(Option countryCode = default, Option enrolledIn3DSecure = default, Option mcc = default) + { + _CountryCodeOption = countryCode; + _EnrolledIn3DSecureOption = enrolledIn3DSecure; + _MccOption = mcc; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// 2-letter ISO 3166 country code of the card acceptor location. > This parameter is required for the merchants who don't use Adyen as the payment authorisation gateway. + /// + /// 2-letter ISO 3166 country code of the card acceptor location. > This parameter is required for the merchants who don't use Adyen as the payment authorisation gateway. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnrolledIn3DSecureOption { get; private set; } + + /// + /// If true, indicates that the merchant is enrolled in 3D Secure for the card network. + /// + /// If true, indicates that the merchant is enrolled in 3D Secure for the card network. + [JsonPropertyName("enrolledIn3DSecure")] + public bool? EnrolledIn3DSecure { get { return this._EnrolledIn3DSecureOption; } set { this._EnrolledIn3DSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The merchant category code (MCC) is a four-digit number which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. The list of MCCs can be found [here](https://en.wikipedia.org/wiki/Merchant_category_code). + /// + /// The merchant category code (MCC) is a four-digit number which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. The list of MCCs can be found [here](https://en.wikipedia.org/wiki/Merchant_category_code). + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantDetails {\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" EnrolledIn3DSecure: ").Append(EnrolledIn3DSecure).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CountryCode (string) maxLength + if (this.CountryCode != null && this.CountryCode.Length > 2) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be less than 2.", new [] { "CountryCode" }); + } + + // CountryCode (string) minLength + if (this.CountryCode != null && this.CountryCode.Length < 2) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be greater than 2.", new [] { "CountryCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option countryCode = default; + Option enrolledIn3DSecure = default; + Option mcc = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "enrolledIn3DSecure": + enrolledIn3DSecure = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantDetails(countryCode, enrolledIn3DSecure, mcc); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantDetails merchantDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantDetails merchantDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantDetails._CountryCodeOption.IsSet) + if (merchantDetails.CountryCode != null) + writer.WriteString("countryCode", merchantDetails.CountryCode); + + if (merchantDetails._EnrolledIn3DSecureOption.IsSet) + writer.WriteBoolean("enrolledIn3DSecure", merchantDetails._EnrolledIn3DSecureOption.Value!.Value); + + if (merchantDetails._MccOption.IsSet) + if (merchantDetails.Mcc != null) + writer.WriteString("mcc", merchantDetails.Mcc); + } + } +} diff --git a/Adyen/BinLookup/Models/Recurring.cs b/Adyen/BinLookup/Models/Recurring.cs new file mode 100644 index 000000000..b2a74728e --- /dev/null +++ b/Adyen/BinLookup/Models/Recurring.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// Recurring. + /// + public partial class Recurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// A descriptive name for this detail. + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// The name of the token service. + [JsonConstructor] + public Recurring(Option contract = default, Option recurringDetailName = default, Option recurringExpiry = default, Option recurringFrequency = default, Option tokenService = default) + { + _ContractOption = contract; + _RecurringDetailNameOption = recurringDetailName; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _TokenServiceOption = tokenService; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Recurring() + { + } + + partial void OnCreated(); + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonConverter(typeof(ContractEnumJsonConverter))] + public class ContractEnum : IEnum + { + /// + /// Returns the value of the ContractEnum. + /// + public string? Value { get; set; } + + /// + /// ContractEnum.ONECLICK - ONECLICK + /// + public static readonly ContractEnum ONECLICK = new("ONECLICK"); + + /// + /// ContractEnum.ONECLICKRECURRING - ONECLICK,RECURRING + /// + public static readonly ContractEnum ONECLICKRECURRING = new("ONECLICK,RECURRING"); + + /// + /// ContractEnum.RECURRING - RECURRING + /// + public static readonly ContractEnum RECURRING = new("RECURRING"); + + /// + /// ContractEnum.PAYOUT - PAYOUT + /// + public static readonly ContractEnum PAYOUT = new("PAYOUT"); + + /// + /// ContractEnum.EXTERNAL - EXTERNAL + /// + public static readonly ContractEnum EXTERNAL = new("EXTERNAL"); + + private ContractEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractEnum?(string? value) => value == null ? null : new ContractEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractEnum? option) => option?.Value; + + public static bool operator ==(ContractEnum? left, ContractEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractEnum? left, ContractEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractEnum? FromStringOrDefault(string value) + { + return value switch { + "ONECLICK" => ContractEnum.ONECLICK, + "ONECLICK,RECURRING" => ContractEnum.ONECLICKRECURRING, + "RECURRING" => ContractEnum.RECURRING, + "PAYOUT" => ContractEnum.PAYOUT, + "EXTERNAL" => ContractEnum.EXTERNAL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractEnum? value) + { + if (value == null) + return null; + + if (value == ContractEnum.ONECLICK) + return "ONECLICK"; + + if (value == ContractEnum.ONECLICKRECURRING) + return "ONECLICK,RECURRING"; + + if (value == ContractEnum.RECURRING) + return "RECURRING"; + + if (value == ContractEnum.PAYOUT) + return "PAYOUT"; + + if (value == ContractEnum.EXTERNAL) + return "EXTERNAL"; + + return null; + } + + /// + /// JsonConverter for writing ContractEnum. + /// + public class ContractEnumJsonConverter : JsonConverter + { + public override ContractEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractEnum.FromStringOrDefault(value) ?? new ContractEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonPropertyName("contract")] + public ContractEnum? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonConverter(typeof(TokenServiceEnumJsonConverter))] + public class TokenServiceEnum : IEnum + { + /// + /// Returns the value of the TokenServiceEnum. + /// + public string? Value { get; set; } + + /// + /// TokenServiceEnum.VISATOKENSERVICE - VISATOKENSERVICE + /// + public static readonly TokenServiceEnum VISATOKENSERVICE = new("VISATOKENSERVICE"); + + /// + /// TokenServiceEnum.MCTOKENSERVICE - MCTOKENSERVICE + /// + public static readonly TokenServiceEnum MCTOKENSERVICE = new("MCTOKENSERVICE"); + + /// + /// TokenServiceEnum.AMEXTOKENSERVICE - AMEXTOKENSERVICE + /// + public static readonly TokenServiceEnum AMEXTOKENSERVICE = new("AMEXTOKENSERVICE"); + + /// + /// TokenServiceEnum.TOKENSHARING - TOKEN_SHARING + /// + public static readonly TokenServiceEnum TOKENSHARING = new("TOKEN_SHARING"); + + private TokenServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenServiceEnum?(string? value) => value == null ? null : new TokenServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenServiceEnum? option) => option?.Value; + + public static bool operator ==(TokenServiceEnum? left, TokenServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenServiceEnum? left, TokenServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "VISATOKENSERVICE" => TokenServiceEnum.VISATOKENSERVICE, + "MCTOKENSERVICE" => TokenServiceEnum.MCTOKENSERVICE, + "AMEXTOKENSERVICE" => TokenServiceEnum.AMEXTOKENSERVICE, + "TOKEN_SHARING" => TokenServiceEnum.TOKENSHARING, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenServiceEnum? value) + { + if (value == null) + return null; + + if (value == TokenServiceEnum.VISATOKENSERVICE) + return "VISATOKENSERVICE"; + + if (value == TokenServiceEnum.MCTOKENSERVICE) + return "MCTOKENSERVICE"; + + if (value == TokenServiceEnum.AMEXTOKENSERVICE) + return "AMEXTOKENSERVICE"; + + if (value == TokenServiceEnum.TOKENSHARING) + return "TOKEN_SHARING"; + + return null; + } + + /// + /// JsonConverter for writing TokenServiceEnum. + /// + public class TokenServiceEnumJsonConverter : JsonConverter + { + public override TokenServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenServiceEnum.FromStringOrDefault(value) ?? new TokenServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenServiceOption { get; private set; } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonPropertyName("tokenService")] + public TokenServiceEnum? TokenService { get { return this._TokenServiceOption; } set { this._TokenServiceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailNameOption { get; private set; } + + /// + /// A descriptive name for this detail. + /// + /// A descriptive name for this detail. + [JsonPropertyName("recurringDetailName")] + public string? RecurringDetailName { get { return this._RecurringDetailNameOption; } set { this._RecurringDetailNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public DateTimeOffset? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Recurring {\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" TokenService: ").Append(TokenService).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RecurringExpiry. + /// + public static string RecurringExpiryFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Recurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contract = default; + Option recurringDetailName = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option tokenService = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contract": + string? contractRawValue = utf8JsonReader.GetString(); + contract = new Option(Recurring.ContractEnum.FromStringOrDefault(contractRawValue)); + break; + case "recurringDetailName": + recurringDetailName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "tokenService": + string? tokenServiceRawValue = utf8JsonReader.GetString(); + tokenService = new Option(Recurring.TokenServiceEnum.FromStringOrDefault(tokenServiceRawValue)); + break; + default: + break; + } + } + } + + + return new Recurring(contract, recurringDetailName, recurringExpiry, recurringFrequency, tokenService); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurring._ContractOption.IsSet && recurring.Contract != null) + { + string? contractRawValue = Recurring.ContractEnum.ToJsonValue(recurring._ContractOption.Value!.Value); + writer.WriteString("contract", contractRawValue); + } + + if (recurring._RecurringDetailNameOption.IsSet) + if (recurring.RecurringDetailName != null) + writer.WriteString("recurringDetailName", recurring.RecurringDetailName); + + if (recurring._RecurringExpiryOption.IsSet) + writer.WriteString("recurringExpiry", recurring._RecurringExpiryOption.Value!.Value.ToString(RecurringExpiryFormat)); + + if (recurring._RecurringFrequencyOption.IsSet) + if (recurring.RecurringFrequency != null) + writer.WriteString("recurringFrequency", recurring.RecurringFrequency); + + if (recurring._TokenServiceOption.IsSet && recurring.TokenService != null) + { + string? tokenServiceRawValue = Recurring.TokenServiceEnum.ToJsonValue(recurring._TokenServiceOption.Value!.Value); + writer.WriteString("tokenService", tokenServiceRawValue); + } + } + } +} diff --git a/Adyen/BinLookup/Models/ServiceError.cs b/Adyen/BinLookup/Models/ServiceError.cs new file mode 100644 index 000000000..e41500f57 --- /dev/null +++ b/Adyen/BinLookup/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/BinLookup/Models/ThreeDS2CardRangeDetail.cs b/Adyen/BinLookup/Models/ThreeDS2CardRangeDetail.cs new file mode 100644 index 000000000..6f1d8243e --- /dev/null +++ b/Adyen/BinLookup/Models/ThreeDS2CardRangeDetail.cs @@ -0,0 +1,304 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// ThreeDS2CardRangeDetail. + /// + public partial class ThreeDS2CardRangeDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Provides additional information to the 3DS Server. Possible values: - 01 (Authentication is available at ACS) - 02 (Attempts supported by ACS or DS) - 03 (Decoupled authentication supported) - 04 (Whitelisting supported) + /// Card brand. + /// BIN end range. + /// BIN start range. + /// Supported 3D Secure protocol versions + /// In a 3D Secure 2 browser-based flow, this is the URL where you should send the device fingerprint to. + [JsonConstructor] + public ThreeDS2CardRangeDetail(Option?> acsInfoInd = default, Option brandCode = default, Option endRange = default, Option startRange = default, Option?> threeDS2Versions = default, Option threeDSMethodURL = default) + { + _AcsInfoIndOption = acsInfoInd; + _BrandCodeOption = brandCode; + _EndRangeOption = endRange; + _StartRangeOption = startRange; + _ThreeDS2VersionsOption = threeDS2Versions; + _ThreeDSMethodURLOption = threeDSMethodURL; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2CardRangeDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AcsInfoIndOption { get; private set; } + + /// + /// Provides additional information to the 3DS Server. Possible values: - 01 (Authentication is available at ACS) - 02 (Attempts supported by ACS or DS) - 03 (Decoupled authentication supported) - 04 (Whitelisting supported) + /// + /// Provides additional information to the 3DS Server. Possible values: - 01 (Authentication is available at ACS) - 02 (Attempts supported by ACS or DS) - 03 (Decoupled authentication supported) - 04 (Whitelisting supported) + [JsonPropertyName("acsInfoInd")] + public List? AcsInfoInd { get { return this._AcsInfoIndOption; } set { this._AcsInfoIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandCodeOption { get; private set; } + + /// + /// Card brand. + /// + /// Card brand. + [JsonPropertyName("brandCode")] + public string? BrandCode { get { return this._BrandCodeOption; } set { this._BrandCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndRangeOption { get; private set; } + + /// + /// BIN end range. + /// + /// BIN end range. + [JsonPropertyName("endRange")] + public string? EndRange { get { return this._EndRangeOption; } set { this._EndRangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartRangeOption { get; private set; } + + /// + /// BIN start range. + /// + /// BIN start range. + [JsonPropertyName("startRange")] + public string? StartRange { get { return this._StartRangeOption; } set { this._StartRangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ThreeDS2VersionsOption { get; private set; } + + /// + /// Supported 3D Secure protocol versions + /// + /// Supported 3D Secure protocol versions + [JsonPropertyName("threeDS2Versions")] + public List? ThreeDS2Versions { get { return this._ThreeDS2VersionsOption; } set { this._ThreeDS2VersionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSMethodURLOption { get; private set; } + + /// + /// In a 3D Secure 2 browser-based flow, this is the URL where you should send the device fingerprint to. + /// + /// In a 3D Secure 2 browser-based flow, this is the URL where you should send the device fingerprint to. + [JsonPropertyName("threeDSMethodURL")] + public string? ThreeDSMethodURL { get { return this._ThreeDSMethodURLOption; } set { this._ThreeDSMethodURLOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2CardRangeDetail {\n"); + sb.Append(" AcsInfoInd: ").Append(AcsInfoInd).Append("\n"); + sb.Append(" BrandCode: ").Append(BrandCode).Append("\n"); + sb.Append(" EndRange: ").Append(EndRange).Append("\n"); + sb.Append(" StartRange: ").Append(StartRange).Append("\n"); + sb.Append(" ThreeDS2Versions: ").Append(ThreeDS2Versions).Append("\n"); + sb.Append(" ThreeDSMethodURL: ").Append(ThreeDSMethodURL).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2CardRangeDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2CardRangeDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> acsInfoInd = default; + Option brandCode = default; + Option endRange = default; + Option startRange = default; + Option?> threeDS2Versions = default; + Option threeDSMethodURL = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsInfoInd": + acsInfoInd = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "brandCode": + brandCode = new Option(utf8JsonReader.GetString()!); + break; + case "endRange": + endRange = new Option(utf8JsonReader.GetString()!); + break; + case "startRange": + startRange = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2Versions": + threeDS2Versions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSMethodURL": + threeDSMethodURL = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDS2CardRangeDetail(acsInfoInd, brandCode, endRange, startRange, threeDS2Versions, threeDSMethodURL); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2CardRangeDetail threeDS2CardRangeDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2CardRangeDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2CardRangeDetail threeDS2CardRangeDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2CardRangeDetail._AcsInfoIndOption.IsSet) + { + writer.WritePropertyName("acsInfoInd"); + JsonSerializer.Serialize(writer, threeDS2CardRangeDetail.AcsInfoInd, jsonSerializerOptions); + } + if (threeDS2CardRangeDetail._BrandCodeOption.IsSet) + if (threeDS2CardRangeDetail.BrandCode != null) + writer.WriteString("brandCode", threeDS2CardRangeDetail.BrandCode); + + if (threeDS2CardRangeDetail._EndRangeOption.IsSet) + if (threeDS2CardRangeDetail.EndRange != null) + writer.WriteString("endRange", threeDS2CardRangeDetail.EndRange); + + if (threeDS2CardRangeDetail._StartRangeOption.IsSet) + if (threeDS2CardRangeDetail.StartRange != null) + writer.WriteString("startRange", threeDS2CardRangeDetail.StartRange); + + if (threeDS2CardRangeDetail._ThreeDS2VersionsOption.IsSet) + { + writer.WritePropertyName("threeDS2Versions"); + JsonSerializer.Serialize(writer, threeDS2CardRangeDetail.ThreeDS2Versions, jsonSerializerOptions); + } + if (threeDS2CardRangeDetail._ThreeDSMethodURLOption.IsSet) + if (threeDS2CardRangeDetail.ThreeDSMethodURL != null) + writer.WriteString("threeDSMethodURL", threeDS2CardRangeDetail.ThreeDSMethodURL); + } + } +} diff --git a/Adyen/BinLookup/Models/ThreeDSAvailabilityRequest.cs b/Adyen/BinLookup/Models/ThreeDSAvailabilityRequest.cs new file mode 100644 index 000000000..091c753ed --- /dev/null +++ b/Adyen/BinLookup/Models/ThreeDSAvailabilityRequest.cs @@ -0,0 +1,298 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// ThreeDSAvailabilityRequest. + /// + public partial class ThreeDSAvailabilityRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier. + /// This field contains additional data, which may be required for a particular request. The `additionalData` object consists of entries, each of which includes the key and value. + /// List of brands. + /// Card number or BIN. + /// A recurring detail reference corresponding to a card. + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + [JsonConstructor] + public ThreeDSAvailabilityRequest(string merchantAccount, Option?> additionalData = default, Option?> brands = default, Option cardNumber = default, Option recurringDetailReference = default, Option shopperReference = default) + { + MerchantAccount = merchantAccount; + _AdditionalDataOption = additionalData; + _BrandsOption = brands; + _CardNumberOption = cardNumber; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSAvailabilityRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier. + /// + /// The merchant account identifier. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BrandsOption { get; private set; } + + /// + /// List of brands. + /// + /// List of brands. + [JsonPropertyName("brands")] + public List? Brands { get { return this._BrandsOption; } set { this._BrandsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardNumberOption { get; private set; } + + /// + /// Card number or BIN. + /// + /// Card number or BIN. + [JsonPropertyName("cardNumber")] + public string? CardNumber { get { return this._CardNumberOption; } set { this._CardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// A recurring detail reference corresponding to a card. + /// + /// A recurring detail reference corresponding to a card. + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + /// + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSAvailabilityRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Brands: ").Append(Brands).Append("\n"); + sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSAvailabilityRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSAvailabilityRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> additionalData = default; + Option?> brands = default; + Option cardNumber = default; + Option recurringDetailReference = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "brands": + brands = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardNumber": + cardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class ThreeDSAvailabilityRequest.", nameof(merchantAccount)); + + return new ThreeDSAvailabilityRequest(merchantAccount.Value!, additionalData, brands, cardNumber, recurringDetailReference, shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSAvailabilityRequest threeDSAvailabilityRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSAvailabilityRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSAvailabilityRequest threeDSAvailabilityRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSAvailabilityRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", threeDSAvailabilityRequest.MerchantAccount); + + if (threeDSAvailabilityRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, threeDSAvailabilityRequest.AdditionalData, jsonSerializerOptions); + } + if (threeDSAvailabilityRequest._BrandsOption.IsSet) + { + writer.WritePropertyName("brands"); + JsonSerializer.Serialize(writer, threeDSAvailabilityRequest.Brands, jsonSerializerOptions); + } + if (threeDSAvailabilityRequest._CardNumberOption.IsSet) + if (threeDSAvailabilityRequest.CardNumber != null) + writer.WriteString("cardNumber", threeDSAvailabilityRequest.CardNumber); + + if (threeDSAvailabilityRequest._RecurringDetailReferenceOption.IsSet) + if (threeDSAvailabilityRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", threeDSAvailabilityRequest.RecurringDetailReference); + + if (threeDSAvailabilityRequest._ShopperReferenceOption.IsSet) + if (threeDSAvailabilityRequest.ShopperReference != null) + writer.WriteString("shopperReference", threeDSAvailabilityRequest.ShopperReference); + } + } +} diff --git a/Adyen/BinLookup/Models/ThreeDSAvailabilityResponse.cs b/Adyen/BinLookup/Models/ThreeDSAvailabilityResponse.cs new file mode 100644 index 000000000..7ce2ec7ec --- /dev/null +++ b/Adyen/BinLookup/Models/ThreeDSAvailabilityResponse.cs @@ -0,0 +1,277 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.BinLookup.Client; + +namespace Adyen.BinLookup.Models +{ + /// + /// ThreeDSAvailabilityResponse. + /// + public partial class ThreeDSAvailabilityResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// binDetails + /// List of Directory Server (DS) public keys. + /// Indicator if 3D Secure 1 is supported. + /// List of brand and card range pairs. + /// Indicator if 3D Secure 2 is supported. + [JsonConstructor] + public ThreeDSAvailabilityResponse(Option binDetails = default, Option?> dsPublicKeys = default, Option threeDS1Supported = default, Option?> threeDS2CardRangeDetails = default, Option threeDS2supported = default) + { + _BinDetailsOption = binDetails; + _DsPublicKeysOption = dsPublicKeys; + _ThreeDS1SupportedOption = threeDS1Supported; + _ThreeDS2CardRangeDetailsOption = threeDS2CardRangeDetails; + _ThreeDS2supportedOption = threeDS2supported; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSAvailabilityResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("binDetails")] + public BinDetail? BinDetails { get { return this._BinDetailsOption; } set { this._BinDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DsPublicKeysOption { get; private set; } + + /// + /// List of Directory Server (DS) public keys. + /// + /// List of Directory Server (DS) public keys. + [JsonPropertyName("dsPublicKeys")] + public List? DsPublicKeys { get { return this._DsPublicKeysOption; } set { this._DsPublicKeysOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS1SupportedOption { get; private set; } + + /// + /// Indicator if 3D Secure 1 is supported. + /// + /// Indicator if 3D Secure 1 is supported. + [JsonPropertyName("threeDS1Supported")] + public bool? ThreeDS1Supported { get { return this._ThreeDS1SupportedOption; } set { this._ThreeDS1SupportedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ThreeDS2CardRangeDetailsOption { get; private set; } + + /// + /// List of brand and card range pairs. + /// + /// List of brand and card range pairs. + [JsonPropertyName("threeDS2CardRangeDetails")] + public List? ThreeDS2CardRangeDetails { get { return this._ThreeDS2CardRangeDetailsOption; } set { this._ThreeDS2CardRangeDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2supportedOption { get; private set; } + + /// + /// Indicator if 3D Secure 2 is supported. + /// + /// Indicator if 3D Secure 2 is supported. + [JsonPropertyName("threeDS2supported")] + public bool? ThreeDS2supported { get { return this._ThreeDS2supportedOption; } set { this._ThreeDS2supportedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSAvailabilityResponse {\n"); + sb.Append(" BinDetails: ").Append(BinDetails).Append("\n"); + sb.Append(" DsPublicKeys: ").Append(DsPublicKeys).Append("\n"); + sb.Append(" ThreeDS1Supported: ").Append(ThreeDS1Supported).Append("\n"); + sb.Append(" ThreeDS2CardRangeDetails: ").Append(ThreeDS2CardRangeDetails).Append("\n"); + sb.Append(" ThreeDS2supported: ").Append(ThreeDS2supported).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSAvailabilityResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSAvailabilityResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option binDetails = default; + Option?> dsPublicKeys = default; + Option threeDS1Supported = default; + Option?> threeDS2CardRangeDetails = default; + Option threeDS2supported = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "binDetails": + binDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dsPublicKeys": + dsPublicKeys = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS1Supported": + threeDS1Supported = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "threeDS2CardRangeDetails": + threeDS2CardRangeDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2supported": + threeDS2supported = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ThreeDSAvailabilityResponse(binDetails, dsPublicKeys, threeDS1Supported, threeDS2CardRangeDetails, threeDS2supported); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSAvailabilityResponse threeDSAvailabilityResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSAvailabilityResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSAvailabilityResponse threeDSAvailabilityResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSAvailabilityResponse._BinDetailsOption.IsSet) + { + writer.WritePropertyName("binDetails"); + JsonSerializer.Serialize(writer, threeDSAvailabilityResponse.BinDetails, jsonSerializerOptions); + } + if (threeDSAvailabilityResponse._DsPublicKeysOption.IsSet) + { + writer.WritePropertyName("dsPublicKeys"); + JsonSerializer.Serialize(writer, threeDSAvailabilityResponse.DsPublicKeys, jsonSerializerOptions); + } + if (threeDSAvailabilityResponse._ThreeDS1SupportedOption.IsSet) + writer.WriteBoolean("threeDS1Supported", threeDSAvailabilityResponse._ThreeDS1SupportedOption.Value!.Value); + + if (threeDSAvailabilityResponse._ThreeDS2CardRangeDetailsOption.IsSet) + { + writer.WritePropertyName("threeDS2CardRangeDetails"); + JsonSerializer.Serialize(writer, threeDSAvailabilityResponse.ThreeDS2CardRangeDetails, jsonSerializerOptions); + } + if (threeDSAvailabilityResponse._ThreeDS2supportedOption.IsSet) + writer.WriteBoolean("threeDS2supported", threeDSAvailabilityResponse._ThreeDS2supportedOption.Value!.Value); + } + } +} diff --git a/Adyen/BinLookup/Services/BinLookupService.cs b/Adyen/BinLookup/Services/BinLookupService.cs new file mode 100644 index 000000000..d64d1043f --- /dev/null +++ b/Adyen/BinLookup/Services/BinLookupService.cs @@ -0,0 +1,985 @@ +// +/* + * Adyen BinLookup API + * + * The BIN Lookup API provides endpoints for retrieving information, such as cost estimates, and 3D Secure supported version based on a given BIN. ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The BinLookup API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/BinLookup/v54/get3dsAvailability ```## Going live To authneticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/BinLookup/v54/get3dsAvailability ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 54 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.BinLookup.Client; +using Adyen.BinLookup.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.BinLookup.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBinLookupService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BinLookupServiceEvents Events { get; } + + /// + /// Check if 3D Secure is available + /// + /// + /// Verifies whether 3D Secure is available for the specified BIN or card brand. For 3D Secure 2, this endpoint also returns device fingerprinting keys. For more information, refer to [3D Secure 2](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task Get3dsAvailabilityAsync(ThreeDSAvailabilityRequest threeDSAvailabilityRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a fees cost estimate + /// + /// + /// >This API is available only for merchants operating in Australia, the EU, and the UK. Use the Adyen Cost Estimation API to pre-calculate interchange and scheme fee costs. Knowing these costs prior actual payment authorisation gives you an opportunity to charge those costs to the cardholder, if necessary. To retrieve this information, make the call to the `/getCostEstimate` endpoint. The response to this call contains the amount of the interchange and scheme fees charged by the network for this transaction, and also which surcharging policy is possible (based on current regulations). > Since not all information is known in advance (for example, if the cardholder will successfully authenticate via 3D Secure or if you also plan to provide additional Level 2/3 data), the returned amounts are based on a set of assumption criteria you define in the `assumptions` parameter. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task GetCostEstimateAsync(CostEstimateRequest costEstimateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGet3dsAvailabilityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetCostEstimateApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BinLookupServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGet3dsAvailability; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGet3dsAvailability; + + internal void ExecuteOnGet3dsAvailability(BinLookupService.Get3dsAvailabilityApiResponse apiResponse) + { + OnGet3dsAvailability?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGet3dsAvailability(Exception exception) + { + OnErrorGet3dsAvailability?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetCostEstimate; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetCostEstimate; + + internal void ExecuteOnGetCostEstimate(BinLookupService.GetCostEstimateApiResponse apiResponse) + { + OnGetCostEstimate?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCostEstimate(Exception exception) + { + OnErrorGetCostEstimate?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BinLookupService : IBinLookupService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BinLookupServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BinLookupService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BinLookupServiceEvents binLookupServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = binLookupServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Check if 3D Secure is available Verifies whether 3D Secure is available for the specified BIN or card brand. For 3D Secure 2, this endpoint also returns device fingerprinting keys. For more information, refer to [3D Secure 2](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task Get3dsAvailabilityAsync(ThreeDSAvailabilityRequest threeDSAvailabilityRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/get3dsAvailability" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/get3dsAvailability"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (threeDSAvailabilityRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(threeDSAvailabilityRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + Get3dsAvailabilityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/get3dsAvailability", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGet3dsAvailability(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGet3dsAvailability(exception); + throw; + } + } + + /// + /// The . + /// + public partial class Get3dsAvailabilityApiResponse : Adyen.Core.Client.ApiResponse, IGet3dsAvailabilityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Get3dsAvailabilityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Get3dsAvailabilityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BinLookup.Models.ThreeDSAvailabilityResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ThreeDSAvailabilityResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BinLookup.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BinLookup.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BinLookup.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BinLookup.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BinLookup.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a fees cost estimate >This API is available only for merchants operating in Australia, the EU, and the UK. Use the Adyen Cost Estimation API to pre-calculate interchange and scheme fee costs. Knowing these costs prior actual payment authorisation gives you an opportunity to charge those costs to the cardholder, if necessary. To retrieve this information, make the call to the `/getCostEstimate` endpoint. The response to this call contains the amount of the interchange and scheme fees charged by the network for this transaction, and also which surcharging policy is possible (based on current regulations). > Since not all information is known in advance (for example, if the cardholder will successfully authenticate via 3D Secure or if you also plan to provide additional Level 2/3 data), the returned amounts are based on a set of assumption criteria you define in the `assumptions` parameter. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetCostEstimateAsync(CostEstimateRequest costEstimateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/getCostEstimate" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/getCostEstimate"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (costEstimateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(costEstimateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetCostEstimateApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/getCostEstimate", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetCostEstimate(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetCostEstimate(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetCostEstimateApiResponse : Adyen.Core.Client.ApiResponse, IGetCostEstimateApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCostEstimateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCostEstimateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.BinLookup.Models.CostEstimateResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.CostEstimateResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.BinLookup.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.BinLookup.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.BinLookup.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.BinLookup.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.BinLookup.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.BinLookup.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Client/ApiKeyToken.cs b/Adyen/Checkout/Client/ApiKeyToken.cs new file mode 100644 index 000000000..a4310e867 --- /dev/null +++ b/Adyen/Checkout/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Checkout.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Checkout/Client/ClientUtils.cs b/Adyen/Checkout/Client/ClientUtils.cs new file mode 100644 index 000000000..fff97acf0 --- /dev/null +++ b/Adyen/Checkout/Client/ClientUtils.cs @@ -0,0 +1,713 @@ +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Checkout.Models; +using Models = Adyen.Checkout.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Checkout.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AccountInfo.AccountAgeIndicatorEnum accountInfoAccountAgeIndicatorEnum) + return Models.AccountInfo.AccountAgeIndicatorEnum.ToJsonValue(accountInfoAccountAgeIndicatorEnum); + if (obj is Models.AccountInfo.AccountChangeIndicatorEnum accountInfoAccountChangeIndicatorEnum) + return Models.AccountInfo.AccountChangeIndicatorEnum.ToJsonValue(accountInfoAccountChangeIndicatorEnum); + if (obj is Models.AccountInfo.AccountTypeEnum accountInfoAccountTypeEnum) + return Models.AccountInfo.AccountTypeEnum.ToJsonValue(accountInfoAccountTypeEnum); + if (obj is Models.AccountInfo.DeliveryAddressUsageIndicatorEnum accountInfoDeliveryAddressUsageIndicatorEnum) + return Models.AccountInfo.DeliveryAddressUsageIndicatorEnum.ToJsonValue(accountInfoDeliveryAddressUsageIndicatorEnum); + if (obj is Models.AccountInfo.PasswordChangeIndicatorEnum accountInfoPasswordChangeIndicatorEnum) + return Models.AccountInfo.PasswordChangeIndicatorEnum.ToJsonValue(accountInfoPasswordChangeIndicatorEnum); + if (obj is Models.AccountInfo.PaymentAccountIndicatorEnum accountInfoPaymentAccountIndicatorEnum) + return Models.AccountInfo.PaymentAccountIndicatorEnum.ToJsonValue(accountInfoPaymentAccountIndicatorEnum); + if (obj is Models.AcctInfo.ChAccAgeIndEnum acctInfoChAccAgeIndEnum) + return Models.AcctInfo.ChAccAgeIndEnum.ToJsonValue(acctInfoChAccAgeIndEnum); + if (obj is Models.AcctInfo.ChAccChangeIndEnum acctInfoChAccChangeIndEnum) + return Models.AcctInfo.ChAccChangeIndEnum.ToJsonValue(acctInfoChAccChangeIndEnum); + if (obj is Models.AcctInfo.ChAccPwChangeIndEnum acctInfoChAccPwChangeIndEnum) + return Models.AcctInfo.ChAccPwChangeIndEnum.ToJsonValue(acctInfoChAccPwChangeIndEnum); + if (obj is Models.AcctInfo.PaymentAccIndEnum acctInfoPaymentAccIndEnum) + return Models.AcctInfo.PaymentAccIndEnum.ToJsonValue(acctInfoPaymentAccIndEnum); + if (obj is Models.AcctInfo.ShipAddressUsageIndEnum acctInfoShipAddressUsageIndEnum) + return Models.AcctInfo.ShipAddressUsageIndEnum.ToJsonValue(acctInfoShipAddressUsageIndEnum); + if (obj is Models.AcctInfo.ShipNameIndicatorEnum acctInfoShipNameIndicatorEnum) + return Models.AcctInfo.ShipNameIndicatorEnum.ToJsonValue(acctInfoShipNameIndicatorEnum); + if (obj is Models.AcctInfo.SuspiciousAccActivityEnum acctInfoSuspiciousAccActivityEnum) + return Models.AcctInfo.SuspiciousAccActivityEnum.ToJsonValue(acctInfoSuspiciousAccActivityEnum); + if (obj is Models.AchDetails.AccountHolderTypeEnum achDetailsAccountHolderTypeEnum) + return Models.AchDetails.AccountHolderTypeEnum.ToJsonValue(achDetailsAccountHolderTypeEnum); + if (obj is Models.AchDetails.BankAccountTypeEnum achDetailsBankAccountTypeEnum) + return Models.AchDetails.BankAccountTypeEnum.ToJsonValue(achDetailsBankAccountTypeEnum); + if (obj is Models.AchDetails.TypeEnum achDetailsTypeEnum) + return Models.AchDetails.TypeEnum.ToJsonValue(achDetailsTypeEnum); + if (obj is Models.AdditionalData3DSecure.ChallengeWindowSizeEnum additionalData3DSecureChallengeWindowSizeEnum) + return Models.AdditionalData3DSecure.ChallengeWindowSizeEnum.ToJsonValue(additionalData3DSecureChallengeWindowSizeEnum); + if (obj is Models.AdditionalDataCommon.IndustryUsageEnum additionalDataCommonIndustryUsageEnum) + return Models.AdditionalDataCommon.IndustryUsageEnum.ToJsonValue(additionalDataCommonIndustryUsageEnum); + if (obj is Models.AffirmDetails.TypeEnum affirmDetailsTypeEnum) + return Models.AffirmDetails.TypeEnum.ToJsonValue(affirmDetailsTypeEnum); + if (obj is Models.AfterpayDetails.TypeEnum afterpayDetailsTypeEnum) + return Models.AfterpayDetails.TypeEnum.ToJsonValue(afterpayDetailsTypeEnum); + if (obj is Models.AmazonPayDetails.TypeEnum amazonPayDetailsTypeEnum) + return Models.AmazonPayDetails.TypeEnum.ToJsonValue(amazonPayDetailsTypeEnum); + if (obj is Models.AncvDetails.TypeEnum ancvDetailsTypeEnum) + return Models.AncvDetails.TypeEnum.ToJsonValue(ancvDetailsTypeEnum); + if (obj is Models.AndroidPayDetails.TypeEnum androidPayDetailsTypeEnum) + return Models.AndroidPayDetails.TypeEnum.ToJsonValue(androidPayDetailsTypeEnum); + if (obj is Models.ApplePayDetails.FundingSourceEnum applePayDetailsFundingSourceEnum) + return Models.ApplePayDetails.FundingSourceEnum.ToJsonValue(applePayDetailsFundingSourceEnum); + if (obj is Models.ApplePayDetails.TypeEnum applePayDetailsTypeEnum) + return Models.ApplePayDetails.TypeEnum.ToJsonValue(applePayDetailsTypeEnum); + if (obj is Models.ApplePayDonations.FundingSourceEnum applePayDonationsFundingSourceEnum) + return Models.ApplePayDonations.FundingSourceEnum.ToJsonValue(applePayDonationsFundingSourceEnum); + if (obj is Models.ApplePayDonations.TypeEnum applePayDonationsTypeEnum) + return Models.ApplePayDonations.TypeEnum.ToJsonValue(applePayDonationsTypeEnum); + if (obj is Models.AuthenticationData.AttemptAuthenticationEnum authenticationDataAttemptAuthenticationEnum) + return Models.AuthenticationData.AttemptAuthenticationEnum.ToJsonValue(authenticationDataAttemptAuthenticationEnum); + if (obj is Models.BacsDirectDebitDetails.TypeEnum bacsDirectDebitDetailsTypeEnum) + return Models.BacsDirectDebitDetails.TypeEnum.ToJsonValue(bacsDirectDebitDetailsTypeEnum); + if (obj is Models.BalanceCheckRequest.RecurringProcessingModelEnum balanceCheckRequestRecurringProcessingModelEnum) + return Models.BalanceCheckRequest.RecurringProcessingModelEnum.ToJsonValue(balanceCheckRequestRecurringProcessingModelEnum); + if (obj is Models.BalanceCheckRequest.ShopperInteractionEnum balanceCheckRequestShopperInteractionEnum) + return Models.BalanceCheckRequest.ShopperInteractionEnum.ToJsonValue(balanceCheckRequestShopperInteractionEnum); + if (obj is Models.BalanceCheckResponse.ResultCodeEnum balanceCheckResponseResultCodeEnum) + return Models.BalanceCheckResponse.ResultCodeEnum.ToJsonValue(balanceCheckResponseResultCodeEnum); + if (obj is Models.BillDeskDetails.TypeEnum billDeskDetailsTypeEnum) + return Models.BillDeskDetails.TypeEnum.ToJsonValue(billDeskDetailsTypeEnum); + if (obj is Models.BlikDetails.TypeEnum blikDetailsTypeEnum) + return Models.BlikDetails.TypeEnum.ToJsonValue(blikDetailsTypeEnum); + if (obj is Models.CancelOrderResponse.ResultCodeEnum cancelOrderResponseResultCodeEnum) + return Models.CancelOrderResponse.ResultCodeEnum.ToJsonValue(cancelOrderResponseResultCodeEnum); + if (obj is Models.CardDetails.FundingSourceEnum cardDetailsFundingSourceEnum) + return Models.CardDetails.FundingSourceEnum.ToJsonValue(cardDetailsFundingSourceEnum); + if (obj is Models.CardDetails.TypeEnum cardDetailsTypeEnum) + return Models.CardDetails.TypeEnum.ToJsonValue(cardDetailsTypeEnum); + if (obj is Models.CardDonations.FundingSourceEnum cardDonationsFundingSourceEnum) + return Models.CardDonations.FundingSourceEnum.ToJsonValue(cardDonationsFundingSourceEnum); + if (obj is Models.CardDonations.TypeEnum cardDonationsTypeEnum) + return Models.CardDonations.TypeEnum.ToJsonValue(cardDonationsTypeEnum); + if (obj is Models.CashAppDetails.TypeEnum cashAppDetailsTypeEnum) + return Models.CashAppDetails.TypeEnum.ToJsonValue(cashAppDetailsTypeEnum); + if (obj is Models.CellulantDetails.TypeEnum cellulantDetailsTypeEnum) + return Models.CellulantDetails.TypeEnum.ToJsonValue(cellulantDetailsTypeEnum); + if (obj is Models.CheckoutAwaitAction.TypeEnum checkoutAwaitActionTypeEnum) + return Models.CheckoutAwaitAction.TypeEnum.ToJsonValue(checkoutAwaitActionTypeEnum); + if (obj is Models.CheckoutBankAccount.AccountTypeEnum checkoutBankAccountAccountTypeEnum) + return Models.CheckoutBankAccount.AccountTypeEnum.ToJsonValue(checkoutBankAccountAccountTypeEnum); + if (obj is Models.CheckoutBankTransferAction.TypeEnum checkoutBankTransferActionTypeEnum) + return Models.CheckoutBankTransferAction.TypeEnum.ToJsonValue(checkoutBankTransferActionTypeEnum); + if (obj is Models.CheckoutDelegatedAuthenticationAction.TypeEnum checkoutDelegatedAuthenticationActionTypeEnum) + return Models.CheckoutDelegatedAuthenticationAction.TypeEnum.ToJsonValue(checkoutDelegatedAuthenticationActionTypeEnum); + if (obj is Models.CheckoutNativeRedirectAction.TypeEnum checkoutNativeRedirectActionTypeEnum) + return Models.CheckoutNativeRedirectAction.TypeEnum.ToJsonValue(checkoutNativeRedirectActionTypeEnum); + if (obj is Models.CheckoutQrCodeAction.TypeEnum checkoutQrCodeActionTypeEnum) + return Models.CheckoutQrCodeAction.TypeEnum.ToJsonValue(checkoutQrCodeActionTypeEnum); + if (obj is Models.CheckoutRedirectAction.TypeEnum checkoutRedirectActionTypeEnum) + return Models.CheckoutRedirectAction.TypeEnum.ToJsonValue(checkoutRedirectActionTypeEnum); + if (obj is Models.CheckoutSDKAction.TypeEnum checkoutSDKActionTypeEnum) + return Models.CheckoutSDKAction.TypeEnum.ToJsonValue(checkoutSDKActionTypeEnum); + if (obj is Models.CheckoutSessionInstallmentOption.PlansEnum checkoutSessionInstallmentOptionPlansEnum) + return CheckoutSessionInstallmentOption.PlansEnum.ToJsonValue(checkoutSessionInstallmentOptionPlansEnum); + if (obj is Models.CheckoutSessionThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum checkoutSessionThreeDS2RequestDataThreeDSRequestorChallengeIndEnum) + return Models.CheckoutSessionThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(checkoutSessionThreeDS2RequestDataThreeDSRequestorChallengeIndEnum); + if (obj is Models.CheckoutThreeDS2Action.TypeEnum checkoutThreeDS2ActionTypeEnum) + return Models.CheckoutThreeDS2Action.TypeEnum.ToJsonValue(checkoutThreeDS2ActionTypeEnum); + if (obj is Models.CheckoutVoucherAction.TypeEnum checkoutVoucherActionTypeEnum) + return Models.CheckoutVoucherAction.TypeEnum.ToJsonValue(checkoutVoucherActionTypeEnum); + if (obj is Models.CreateCheckoutSessionRequest.ChannelEnum createCheckoutSessionRequestChannelEnum) + return Models.CreateCheckoutSessionRequest.ChannelEnum.ToJsonValue(createCheckoutSessionRequestChannelEnum); + if (obj is Models.CreateCheckoutSessionRequest.ModeEnum createCheckoutSessionRequestModeEnum) + return Models.CreateCheckoutSessionRequest.ModeEnum.ToJsonValue(createCheckoutSessionRequestModeEnum); + if (obj is Models.CreateCheckoutSessionRequest.RecurringProcessingModelEnum createCheckoutSessionRequestRecurringProcessingModelEnum) + return Models.CreateCheckoutSessionRequest.RecurringProcessingModelEnum.ToJsonValue(createCheckoutSessionRequestRecurringProcessingModelEnum); + if (obj is Models.CreateCheckoutSessionRequest.ShopperInteractionEnum createCheckoutSessionRequestShopperInteractionEnum) + return Models.CreateCheckoutSessionRequest.ShopperInteractionEnum.ToJsonValue(createCheckoutSessionRequestShopperInteractionEnum); + if (obj is Models.CreateCheckoutSessionRequest.StoreFiltrationModeEnum createCheckoutSessionRequestStoreFiltrationModeEnum) + return Models.CreateCheckoutSessionRequest.StoreFiltrationModeEnum.ToJsonValue(createCheckoutSessionRequestStoreFiltrationModeEnum); + if (obj is Models.CreateCheckoutSessionRequest.StorePaymentMethodModeEnum createCheckoutSessionRequestStorePaymentMethodModeEnum) + return Models.CreateCheckoutSessionRequest.StorePaymentMethodModeEnum.ToJsonValue(createCheckoutSessionRequestStorePaymentMethodModeEnum); + if (obj is Models.CreateCheckoutSessionResponse.ChannelEnum createCheckoutSessionResponseChannelEnum) + return Models.CreateCheckoutSessionResponse.ChannelEnum.ToJsonValue(createCheckoutSessionResponseChannelEnum); + if (obj is Models.CreateCheckoutSessionResponse.ModeEnum createCheckoutSessionResponseModeEnum) + return Models.CreateCheckoutSessionResponse.ModeEnum.ToJsonValue(createCheckoutSessionResponseModeEnum); + if (obj is Models.CreateCheckoutSessionResponse.RecurringProcessingModelEnum createCheckoutSessionResponseRecurringProcessingModelEnum) + return Models.CreateCheckoutSessionResponse.RecurringProcessingModelEnum.ToJsonValue(createCheckoutSessionResponseRecurringProcessingModelEnum); + if (obj is Models.CreateCheckoutSessionResponse.ShopperInteractionEnum createCheckoutSessionResponseShopperInteractionEnum) + return Models.CreateCheckoutSessionResponse.ShopperInteractionEnum.ToJsonValue(createCheckoutSessionResponseShopperInteractionEnum); + if (obj is Models.CreateCheckoutSessionResponse.StoreFiltrationModeEnum createCheckoutSessionResponseStoreFiltrationModeEnum) + return Models.CreateCheckoutSessionResponse.StoreFiltrationModeEnum.ToJsonValue(createCheckoutSessionResponseStoreFiltrationModeEnum); + if (obj is Models.CreateCheckoutSessionResponse.StorePaymentMethodModeEnum createCheckoutSessionResponseStorePaymentMethodModeEnum) + return Models.CreateCheckoutSessionResponse.StorePaymentMethodModeEnum.ToJsonValue(createCheckoutSessionResponseStorePaymentMethodModeEnum); + if (obj is Models.CreateOrderResponse.ResultCodeEnum createOrderResponseResultCodeEnum) + return Models.CreateOrderResponse.ResultCodeEnum.ToJsonValue(createOrderResponseResultCodeEnum); + if (obj is Models.DeliveryMethod.TypeEnum deliveryMethodTypeEnum) + return Models.DeliveryMethod.TypeEnum.ToJsonValue(deliveryMethodTypeEnum); + if (obj is Models.DeviceRenderOptions.SdkInterfaceEnum deviceRenderOptionsSdkInterfaceEnum) + return Models.DeviceRenderOptions.SdkInterfaceEnum.ToJsonValue(deviceRenderOptionsSdkInterfaceEnum); + if (obj is Models.DeviceRenderOptions.SdkUiTypeEnum deviceRenderOptionsSdkUiTypeEnum) + return DeviceRenderOptions.SdkUiTypeEnum.ToJsonValue(deviceRenderOptionsSdkUiTypeEnum); + if (obj is Models.DokuDetails.TypeEnum dokuDetailsTypeEnum) + return Models.DokuDetails.TypeEnum.ToJsonValue(dokuDetailsTypeEnum); + if (obj is Models.DonationPaymentRequest.ChannelEnum donationPaymentRequestChannelEnum) + return Models.DonationPaymentRequest.ChannelEnum.ToJsonValue(donationPaymentRequestChannelEnum); + if (obj is Models.DonationPaymentRequest.RecurringProcessingModelEnum donationPaymentRequestRecurringProcessingModelEnum) + return Models.DonationPaymentRequest.RecurringProcessingModelEnum.ToJsonValue(donationPaymentRequestRecurringProcessingModelEnum); + if (obj is Models.DonationPaymentRequest.ShopperInteractionEnum donationPaymentRequestShopperInteractionEnum) + return Models.DonationPaymentRequest.ShopperInteractionEnum.ToJsonValue(donationPaymentRequestShopperInteractionEnum); + if (obj is Models.DonationPaymentResponse.StatusEnum donationPaymentResponseStatusEnum) + return Models.DonationPaymentResponse.StatusEnum.ToJsonValue(donationPaymentResponseStatusEnum); + if (obj is Models.DragonpayDetails.TypeEnum dragonpayDetailsTypeEnum) + return Models.DragonpayDetails.TypeEnum.ToJsonValue(dragonpayDetailsTypeEnum); + if (obj is Models.EBankingFinlandDetails.TypeEnum eBankingFinlandDetailsTypeEnum) + return Models.EBankingFinlandDetails.TypeEnum.ToJsonValue(eBankingFinlandDetailsTypeEnum); + if (obj is Models.EcontextVoucherDetails.TypeEnum econtextVoucherDetailsTypeEnum) + return Models.EcontextVoucherDetails.TypeEnum.ToJsonValue(econtextVoucherDetailsTypeEnum); + if (obj is Models.EftDetails.TypeEnum eftDetailsTypeEnum) + return Models.EftDetails.TypeEnum.ToJsonValue(eftDetailsTypeEnum); + if (obj is Models.FastlaneDetails.TypeEnum fastlaneDetailsTypeEnum) + return Models.FastlaneDetails.TypeEnum.ToJsonValue(fastlaneDetailsTypeEnum); + if (obj is Models.FundRecipient.WalletPurposeEnum fundRecipientWalletPurposeEnum) + return Models.FundRecipient.WalletPurposeEnum.ToJsonValue(fundRecipientWalletPurposeEnum); + if (obj is Models.GenericIssuerPaymentMethodDetails.TypeEnum genericIssuerPaymentMethodDetailsTypeEnum) + return Models.GenericIssuerPaymentMethodDetails.TypeEnum.ToJsonValue(genericIssuerPaymentMethodDetailsTypeEnum); + if (obj is Models.GooglePayDetails.FundingSourceEnum googlePayDetailsFundingSourceEnum) + return Models.GooglePayDetails.FundingSourceEnum.ToJsonValue(googlePayDetailsFundingSourceEnum); + if (obj is Models.GooglePayDetails.TypeEnum googlePayDetailsTypeEnum) + return Models.GooglePayDetails.TypeEnum.ToJsonValue(googlePayDetailsTypeEnum); + if (obj is Models.GooglePayDonations.FundingSourceEnum googlePayDonationsFundingSourceEnum) + return Models.GooglePayDonations.FundingSourceEnum.ToJsonValue(googlePayDonationsFundingSourceEnum); + if (obj is Models.GooglePayDonations.TypeEnum googlePayDonationsTypeEnum) + return Models.GooglePayDonations.TypeEnum.ToJsonValue(googlePayDonationsTypeEnum); + if (obj is Models.IdealDetails.TypeEnum idealDetailsTypeEnum) + return Models.IdealDetails.TypeEnum.ToJsonValue(idealDetailsTypeEnum); + if (obj is Models.IdealDonations.TypeEnum idealDonationsTypeEnum) + return Models.IdealDonations.TypeEnum.ToJsonValue(idealDonationsTypeEnum); + if (obj is Models.InstallmentOption.PlansEnum installmentOptionPlansEnum) + return InstallmentOption.PlansEnum.ToJsonValue(installmentOptionPlansEnum); + if (obj is Models.Installments.PlanEnum installmentsPlanEnum) + return Models.Installments.PlanEnum.ToJsonValue(installmentsPlanEnum); + if (obj is Models.KlarnaDetails.TypeEnum klarnaDetailsTypeEnum) + return Models.KlarnaDetails.TypeEnum.ToJsonValue(klarnaDetailsTypeEnum); + if (obj is Models.Mandate.FrequencyEnum mandateFrequencyEnum) + return Models.Mandate.FrequencyEnum.ToJsonValue(mandateFrequencyEnum); + if (obj is Models.Mandate.AmountRuleEnum mandateAmountRuleEnum) + return Models.Mandate.AmountRuleEnum.ToJsonValue(mandateAmountRuleEnum); + if (obj is Models.Mandate.BillingAttemptsRuleEnum mandateBillingAttemptsRuleEnum) + return Models.Mandate.BillingAttemptsRuleEnum.ToJsonValue(mandateBillingAttemptsRuleEnum); + if (obj is Models.MasterpassDetails.FundingSourceEnum masterpassDetailsFundingSourceEnum) + return Models.MasterpassDetails.FundingSourceEnum.ToJsonValue(masterpassDetailsFundingSourceEnum); + if (obj is Models.MasterpassDetails.TypeEnum masterpassDetailsTypeEnum) + return Models.MasterpassDetails.TypeEnum.ToJsonValue(masterpassDetailsTypeEnum); + if (obj is Models.MbwayDetails.TypeEnum mbwayDetailsTypeEnum) + return Models.MbwayDetails.TypeEnum.ToJsonValue(mbwayDetailsTypeEnum); + if (obj is Models.MerchantRiskIndicator.DeliveryAddressIndicatorEnum merchantRiskIndicatorDeliveryAddressIndicatorEnum) + return Models.MerchantRiskIndicator.DeliveryAddressIndicatorEnum.ToJsonValue(merchantRiskIndicatorDeliveryAddressIndicatorEnum); + if (obj is Models.MerchantRiskIndicator.DeliveryTimeframeEnum merchantRiskIndicatorDeliveryTimeframeEnum) + return Models.MerchantRiskIndicator.DeliveryTimeframeEnum.ToJsonValue(merchantRiskIndicatorDeliveryTimeframeEnum); + if (obj is Models.MobilePayDetails.TypeEnum mobilePayDetailsTypeEnum) + return Models.MobilePayDetails.TypeEnum.ToJsonValue(mobilePayDetailsTypeEnum); + if (obj is Models.MolPayDetails.TypeEnum molPayDetailsTypeEnum) + return Models.MolPayDetails.TypeEnum.ToJsonValue(molPayDetailsTypeEnum); + if (obj is Models.OpenInvoiceDetails.TypeEnum openInvoiceDetailsTypeEnum) + return Models.OpenInvoiceDetails.TypeEnum.ToJsonValue(openInvoiceDetailsTypeEnum); + if (obj is Models.PayByBankAISDirectDebitDetails.TypeEnum payByBankAISDirectDebitDetailsTypeEnum) + return Models.PayByBankAISDirectDebitDetails.TypeEnum.ToJsonValue(payByBankAISDirectDebitDetailsTypeEnum); + if (obj is Models.PayByBankDetails.TypeEnum payByBankDetailsTypeEnum) + return Models.PayByBankDetails.TypeEnum.ToJsonValue(payByBankDetailsTypeEnum); + if (obj is Models.PayPalDetails.SubtypeEnum payPalDetailsSubtypeEnum) + return Models.PayPalDetails.SubtypeEnum.ToJsonValue(payPalDetailsSubtypeEnum); + if (obj is Models.PayPalDetails.TypeEnum payPalDetailsTypeEnum) + return Models.PayPalDetails.TypeEnum.ToJsonValue(payPalDetailsTypeEnum); + if (obj is Models.PayPayDetails.TypeEnum payPayDetailsTypeEnum) + return Models.PayPayDetails.TypeEnum.ToJsonValue(payPayDetailsTypeEnum); + if (obj is Models.PayToDetails.TypeEnum payToDetailsTypeEnum) + return Models.PayToDetails.TypeEnum.ToJsonValue(payToDetailsTypeEnum); + if (obj is Models.PayUUpiDetails.TypeEnum payUUpiDetailsTypeEnum) + return Models.PayUUpiDetails.TypeEnum.ToJsonValue(payUUpiDetailsTypeEnum); + if (obj is Models.PayWithGoogleDetails.FundingSourceEnum payWithGoogleDetailsFundingSourceEnum) + return Models.PayWithGoogleDetails.FundingSourceEnum.ToJsonValue(payWithGoogleDetailsFundingSourceEnum); + if (obj is Models.PayWithGoogleDetails.TypeEnum payWithGoogleDetailsTypeEnum) + return Models.PayWithGoogleDetails.TypeEnum.ToJsonValue(payWithGoogleDetailsTypeEnum); + if (obj is Models.PayWithGoogleDonations.FundingSourceEnum payWithGoogleDonationsFundingSourceEnum) + return Models.PayWithGoogleDonations.FundingSourceEnum.ToJsonValue(payWithGoogleDonationsFundingSourceEnum); + if (obj is Models.PayWithGoogleDonations.TypeEnum payWithGoogleDonationsTypeEnum) + return Models.PayWithGoogleDonations.TypeEnum.ToJsonValue(payWithGoogleDonationsTypeEnum); + if (obj is Models.Payment.ResultCodeEnum paymentResultCodeEnum) + return Models.Payment.ResultCodeEnum.ToJsonValue(paymentResultCodeEnum); + if (obj is Models.PaymentAmountUpdateRequest.IndustryUsageEnum paymentAmountUpdateRequestIndustryUsageEnum) + return Models.PaymentAmountUpdateRequest.IndustryUsageEnum.ToJsonValue(paymentAmountUpdateRequestIndustryUsageEnum); + if (obj is Models.PaymentAmountUpdateResponse.StatusEnum paymentAmountUpdateResponseStatusEnum) + return Models.PaymentAmountUpdateResponse.StatusEnum.ToJsonValue(paymentAmountUpdateResponseStatusEnum); + if (obj is Models.PaymentAmountUpdateResponse.IndustryUsageEnum paymentAmountUpdateResponseIndustryUsageEnum) + return Models.PaymentAmountUpdateResponse.IndustryUsageEnum.ToJsonValue(paymentAmountUpdateResponseIndustryUsageEnum); + if (obj is Models.PaymentCancelResponse.StatusEnum paymentCancelResponseStatusEnum) + return Models.PaymentCancelResponse.StatusEnum.ToJsonValue(paymentCancelResponseStatusEnum); + if (obj is Models.PaymentCaptureResponse.StatusEnum paymentCaptureResponseStatusEnum) + return Models.PaymentCaptureResponse.StatusEnum.ToJsonValue(paymentCaptureResponseStatusEnum); + if (obj is Models.PaymentDetails.TypeEnum paymentDetailsTypeEnum) + return Models.PaymentDetails.TypeEnum.ToJsonValue(paymentDetailsTypeEnum); + if (obj is Models.PaymentDetailsResponse.ResultCodeEnum paymentDetailsResponseResultCodeEnum) + return Models.PaymentDetailsResponse.ResultCodeEnum.ToJsonValue(paymentDetailsResponseResultCodeEnum); + if (obj is Models.PaymentLinkRequest.RecurringProcessingModelEnum paymentLinkRequestRecurringProcessingModelEnum) + return Models.PaymentLinkRequest.RecurringProcessingModelEnum.ToJsonValue(paymentLinkRequestRecurringProcessingModelEnum); + if (obj is Models.PaymentLinkRequest.RequiredShopperFieldsEnum paymentLinkRequestRequiredShopperFieldsEnum) + return PaymentLinkRequest.RequiredShopperFieldsEnum.ToJsonValue(paymentLinkRequestRequiredShopperFieldsEnum); + if (obj is Models.PaymentLinkRequest.StorePaymentMethodModeEnum paymentLinkRequestStorePaymentMethodModeEnum) + return Models.PaymentLinkRequest.StorePaymentMethodModeEnum.ToJsonValue(paymentLinkRequestStorePaymentMethodModeEnum); + if (obj is Models.PaymentLinkResponse.StatusEnum paymentLinkResponseStatusEnum) + return Models.PaymentLinkResponse.StatusEnum.ToJsonValue(paymentLinkResponseStatusEnum); + if (obj is Models.PaymentLinkResponse.RecurringProcessingModelEnum paymentLinkResponseRecurringProcessingModelEnum) + return Models.PaymentLinkResponse.RecurringProcessingModelEnum.ToJsonValue(paymentLinkResponseRecurringProcessingModelEnum); + if (obj is Models.PaymentLinkResponse.RequiredShopperFieldsEnum paymentLinkResponseRequiredShopperFieldsEnum) + return PaymentLinkResponse.RequiredShopperFieldsEnum.ToJsonValue(paymentLinkResponseRequiredShopperFieldsEnum); + if (obj is Models.PaymentLinkResponse.StorePaymentMethodModeEnum paymentLinkResponseStorePaymentMethodModeEnum) + return Models.PaymentLinkResponse.StorePaymentMethodModeEnum.ToJsonValue(paymentLinkResponseStorePaymentMethodModeEnum); + if (obj is Models.PaymentMethod.FundingSourceEnum paymentMethodFundingSourceEnum) + return Models.PaymentMethod.FundingSourceEnum.ToJsonValue(paymentMethodFundingSourceEnum); + if (obj is Models.PaymentMethodsRequest.ChannelEnum paymentMethodsRequestChannelEnum) + return Models.PaymentMethodsRequest.ChannelEnum.ToJsonValue(paymentMethodsRequestChannelEnum); + if (obj is Models.PaymentMethodsRequest.StoreFiltrationModeEnum paymentMethodsRequestStoreFiltrationModeEnum) + return Models.PaymentMethodsRequest.StoreFiltrationModeEnum.ToJsonValue(paymentMethodsRequestStoreFiltrationModeEnum); + if (obj is Models.PaymentRefundRequest.MerchantRefundReasonEnum paymentRefundRequestMerchantRefundReasonEnum) + return Models.PaymentRefundRequest.MerchantRefundReasonEnum.ToJsonValue(paymentRefundRequestMerchantRefundReasonEnum); + if (obj is Models.PaymentRefundResponse.StatusEnum paymentRefundResponseStatusEnum) + return Models.PaymentRefundResponse.StatusEnum.ToJsonValue(paymentRefundResponseStatusEnum); + if (obj is Models.PaymentRefundResponse.MerchantRefundReasonEnum paymentRefundResponseMerchantRefundReasonEnum) + return Models.PaymentRefundResponse.MerchantRefundReasonEnum.ToJsonValue(paymentRefundResponseMerchantRefundReasonEnum); + if (obj is Models.PaymentRequest.ChannelEnum paymentRequestChannelEnum) + return Models.PaymentRequest.ChannelEnum.ToJsonValue(paymentRequestChannelEnum); + if (obj is Models.PaymentRequest.EntityTypeEnum paymentRequestEntityTypeEnum) + return Models.PaymentRequest.EntityTypeEnum.ToJsonValue(paymentRequestEntityTypeEnum); + if (obj is Models.PaymentRequest.IndustryUsageEnum paymentRequestIndustryUsageEnum) + return Models.PaymentRequest.IndustryUsageEnum.ToJsonValue(paymentRequestIndustryUsageEnum); + if (obj is Models.PaymentRequest.RecurringProcessingModelEnum paymentRequestRecurringProcessingModelEnum) + return Models.PaymentRequest.RecurringProcessingModelEnum.ToJsonValue(paymentRequestRecurringProcessingModelEnum); + if (obj is Models.PaymentRequest.ShopperInteractionEnum paymentRequestShopperInteractionEnum) + return Models.PaymentRequest.ShopperInteractionEnum.ToJsonValue(paymentRequestShopperInteractionEnum); + if (obj is Models.PaymentResponse.ResultCodeEnum paymentResponseResultCodeEnum) + return Models.PaymentResponse.ResultCodeEnum.ToJsonValue(paymentResponseResultCodeEnum); + if (obj is Models.PaymentReversalResponse.StatusEnum paymentReversalResponseStatusEnum) + return Models.PaymentReversalResponse.StatusEnum.ToJsonValue(paymentReversalResponseStatusEnum); + if (obj is Models.PaymentValidationsNameResponse.StatusEnum paymentValidationsNameResponseStatusEnum) + return Models.PaymentValidationsNameResponse.StatusEnum.ToJsonValue(paymentValidationsNameResponseStatusEnum); + if (obj is Models.PaypalUpdateOrderResponse.StatusEnum paypalUpdateOrderResponseStatusEnum) + return Models.PaypalUpdateOrderResponse.StatusEnum.ToJsonValue(paypalUpdateOrderResponseStatusEnum); + if (obj is Models.PixDetails.TypeEnum pixDetailsTypeEnum) + return Models.PixDetails.TypeEnum.ToJsonValue(pixDetailsTypeEnum); + if (obj is Models.PixRecurring.FrequencyEnum pixRecurringFrequencyEnum) + return Models.PixRecurring.FrequencyEnum.ToJsonValue(pixRecurringFrequencyEnum); + if (obj is Models.PlatformChargebackLogic.BehaviorEnum platformChargebackLogicBehaviorEnum) + return Models.PlatformChargebackLogic.BehaviorEnum.ToJsonValue(platformChargebackLogicBehaviorEnum); + if (obj is Models.PseDetails.TypeEnum pseDetailsTypeEnum) + return Models.PseDetails.TypeEnum.ToJsonValue(pseDetailsTypeEnum); + if (obj is Models.RakutenPayDetails.TypeEnum rakutenPayDetailsTypeEnum) + return Models.RakutenPayDetails.TypeEnum.ToJsonValue(rakutenPayDetailsTypeEnum); + if (obj is Models.RatepayDetails.TypeEnum ratepayDetailsTypeEnum) + return Models.RatepayDetails.TypeEnum.ToJsonValue(ratepayDetailsTypeEnum); + if (obj is Models.Recurring.ContractEnum recurringContractEnum) + return Models.Recurring.ContractEnum.ToJsonValue(recurringContractEnum); + if (obj is Models.Recurring.TokenServiceEnum recurringTokenServiceEnum) + return Models.Recurring.TokenServiceEnum.ToJsonValue(recurringTokenServiceEnum); + if (obj is Models.ResponseAdditionalDataCard.CardProductIdEnum responseAdditionalDataCardCardProductIdEnum) + return Models.ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCardCardProductIdEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudResultTypeEnum responseAdditionalDataCommonFraudResultTypeEnum) + return Models.ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommonFraudResultTypeEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum responseAdditionalDataCommonFraudRiskLevelEnum) + return Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommonFraudRiskLevelEnum); + if (obj is Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum responseAdditionalDataCommonRecurringProcessingModelEnum) + return Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommonRecurringProcessingModelEnum); + if (obj is Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum responseAdditionalDataCommonTokenizationStoreOperationTypeEnum) + return Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommonTokenizationStoreOperationTypeEnum); + if (obj is Models.Result result) + return ResultValueConverter.ToJsonValue(result); + if (obj is Models.RivertyDetails.TypeEnum rivertyDetailsTypeEnum) + return Models.RivertyDetails.TypeEnum.ToJsonValue(rivertyDetailsTypeEnum); + if (obj is Models.SamsungPayDetails.FundingSourceEnum samsungPayDetailsFundingSourceEnum) + return Models.SamsungPayDetails.FundingSourceEnum.ToJsonValue(samsungPayDetailsFundingSourceEnum); + if (obj is Models.SamsungPayDetails.TypeEnum samsungPayDetailsTypeEnum) + return Models.SamsungPayDetails.TypeEnum.ToJsonValue(samsungPayDetailsTypeEnum); + if (obj is Models.SepaDirectDebitDetails.TypeEnum sepaDirectDebitDetailsTypeEnum) + return Models.SepaDirectDebitDetails.TypeEnum.ToJsonValue(sepaDirectDebitDetailsTypeEnum); + if (obj is Models.SessionResultResponse.StatusEnum sessionResultResponseStatusEnum) + return Models.SessionResultResponse.StatusEnum.ToJsonValue(sessionResultResponseStatusEnum); + if (obj is Models.Split.TypeEnum splitTypeEnum) + return Models.Split.TypeEnum.ToJsonValue(splitTypeEnum); + if (obj is Models.StandalonePaymentCancelResponse.StatusEnum standalonePaymentCancelResponseStatusEnum) + return Models.StandalonePaymentCancelResponse.StatusEnum.ToJsonValue(standalonePaymentCancelResponseStatusEnum); + if (obj is Models.StoredPaymentMethodDetails.TypeEnum storedPaymentMethodDetailsTypeEnum) + return Models.StoredPaymentMethodDetails.TypeEnum.ToJsonValue(storedPaymentMethodDetailsTypeEnum); + if (obj is Models.StoredPaymentMethodRequest.RecurringProcessingModelEnum storedPaymentMethodRequestRecurringProcessingModelEnum) + return Models.StoredPaymentMethodRequest.RecurringProcessingModelEnum.ToJsonValue(storedPaymentMethodRequestRecurringProcessingModelEnum); + if (obj is Models.ThreeDS2RequestData.AcctTypeEnum threeDS2RequestDataAcctTypeEnum) + return Models.ThreeDS2RequestData.AcctTypeEnum.ToJsonValue(threeDS2RequestDataAcctTypeEnum); + if (obj is Models.ThreeDS2RequestData.AddrMatchEnum threeDS2RequestDataAddrMatchEnum) + return Models.ThreeDS2RequestData.AddrMatchEnum.ToJsonValue(threeDS2RequestDataAddrMatchEnum); + if (obj is Models.ThreeDS2RequestData.ChallengeIndicatorEnum threeDS2RequestDataChallengeIndicatorEnum) + return Models.ThreeDS2RequestData.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestDataChallengeIndicatorEnum); + if (obj is Models.ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum threeDS2RequestDataThreeDSRequestorChallengeIndEnum) + return Models.ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestDataThreeDSRequestorChallengeIndEnum); + if (obj is Models.ThreeDS2RequestData.TransTypeEnum threeDS2RequestDataTransTypeEnum) + return Models.ThreeDS2RequestData.TransTypeEnum.ToJsonValue(threeDS2RequestDataTransTypeEnum); + if (obj is Models.ThreeDS2RequestData.TransactionTypeEnum threeDS2RequestDataTransactionTypeEnum) + return Models.ThreeDS2RequestData.TransactionTypeEnum.ToJsonValue(threeDS2RequestDataTransactionTypeEnum); + if (obj is Models.ThreeDS2RequestFields.AcctTypeEnum threeDS2RequestFieldsAcctTypeEnum) + return Models.ThreeDS2RequestFields.AcctTypeEnum.ToJsonValue(threeDS2RequestFieldsAcctTypeEnum); + if (obj is Models.ThreeDS2RequestFields.AddrMatchEnum threeDS2RequestFieldsAddrMatchEnum) + return Models.ThreeDS2RequestFields.AddrMatchEnum.ToJsonValue(threeDS2RequestFieldsAddrMatchEnum); + if (obj is Models.ThreeDS2RequestFields.ChallengeIndicatorEnum threeDS2RequestFieldsChallengeIndicatorEnum) + return Models.ThreeDS2RequestFields.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestFieldsChallengeIndicatorEnum); + if (obj is Models.ThreeDS2RequestFields.ThreeDSRequestorChallengeIndEnum threeDS2RequestFieldsThreeDSRequestorChallengeIndEnum) + return Models.ThreeDS2RequestFields.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestFieldsThreeDSRequestorChallengeIndEnum); + if (obj is Models.ThreeDS2RequestFields.TransTypeEnum threeDS2RequestFieldsTransTypeEnum) + return Models.ThreeDS2RequestFields.TransTypeEnum.ToJsonValue(threeDS2RequestFieldsTransTypeEnum); + if (obj is Models.ThreeDS2RequestFields.TransactionTypeEnum threeDS2RequestFieldsTransactionTypeEnum) + return Models.ThreeDS2RequestFields.TransactionTypeEnum.ToJsonValue(threeDS2RequestFieldsTransactionTypeEnum); + if (obj is Models.ThreeDS2Result.ChallengeCancelEnum threeDS2ResultChallengeCancelEnum) + return Models.ThreeDS2Result.ChallengeCancelEnum.ToJsonValue(threeDS2ResultChallengeCancelEnum); + if (obj is Models.ThreeDS2Result.ExemptionIndicatorEnum threeDS2ResultExemptionIndicatorEnum) + return Models.ThreeDS2Result.ExemptionIndicatorEnum.ToJsonValue(threeDS2ResultExemptionIndicatorEnum); + if (obj is Models.ThreeDS2Result.ThreeDSRequestorChallengeIndEnum threeDS2ResultThreeDSRequestorChallengeIndEnum) + return Models.ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2ResultThreeDSRequestorChallengeIndEnum); + if (obj is Models.ThreeDSRequestData.ChallengeWindowSizeEnum threeDSRequestDataChallengeWindowSizeEnum) + return Models.ThreeDSRequestData.ChallengeWindowSizeEnum.ToJsonValue(threeDSRequestDataChallengeWindowSizeEnum); + if (obj is Models.ThreeDSRequestData.DataOnlyEnum threeDSRequestDataDataOnlyEnum) + return Models.ThreeDSRequestData.DataOnlyEnum.ToJsonValue(threeDSRequestDataDataOnlyEnum); + if (obj is Models.ThreeDSRequestData.NativeThreeDSEnum threeDSRequestDataNativeThreeDSEnum) + return Models.ThreeDSRequestData.NativeThreeDSEnum.ToJsonValue(threeDSRequestDataNativeThreeDSEnum); + if (obj is Models.ThreeDSRequestData.ThreeDSVersionEnum threeDSRequestDataThreeDSVersionEnum) + return Models.ThreeDSRequestData.ThreeDSVersionEnum.ToJsonValue(threeDSRequestDataThreeDSVersionEnum); + if (obj is Models.ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum threeDSRequestorAuthenticationInfoThreeDSReqAuthMethodEnum) + return Models.ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.ToJsonValue(threeDSRequestorAuthenticationInfoThreeDSReqAuthMethodEnum); + if (obj is Models.ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum threeDSRequestorPriorAuthenticationInfoThreeDSReqPriorAuthMethodEnum) + return Models.ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.ToJsonValue(threeDSRequestorPriorAuthenticationInfoThreeDSReqPriorAuthMethodEnum); + if (obj is Models.ThreeDSecureData.AuthenticationResponseEnum threeDSecureDataAuthenticationResponseEnum) + return Models.ThreeDSecureData.AuthenticationResponseEnum.ToJsonValue(threeDSecureDataAuthenticationResponseEnum); + if (obj is Models.ThreeDSecureData.ChallengeCancelEnum threeDSecureDataChallengeCancelEnum) + return Models.ThreeDSecureData.ChallengeCancelEnum.ToJsonValue(threeDSecureDataChallengeCancelEnum); + if (obj is Models.ThreeDSecureData.DirectoryResponseEnum threeDSecureDataDirectoryResponseEnum) + return Models.ThreeDSecureData.DirectoryResponseEnum.ToJsonValue(threeDSecureDataDirectoryResponseEnum); + if (obj is Models.TwintDetails.TypeEnum twintDetailsTypeEnum) + return Models.TwintDetails.TypeEnum.ToJsonValue(twintDetailsTypeEnum); + if (obj is Models.UpdatePaymentLinkRequest.StatusEnum updatePaymentLinkRequestStatusEnum) + return Models.UpdatePaymentLinkRequest.StatusEnum.ToJsonValue(updatePaymentLinkRequestStatusEnum); + if (obj is Models.UpiCollectDetails.TypeEnum upiCollectDetailsTypeEnum) + return Models.UpiCollectDetails.TypeEnum.ToJsonValue(upiCollectDetailsTypeEnum); + if (obj is Models.UpiIntentDetails.TypeEnum upiIntentDetailsTypeEnum) + return Models.UpiIntentDetails.TypeEnum.ToJsonValue(upiIntentDetailsTypeEnum); + if (obj is Models.UpiQrDetails.TypeEnum upiQrDetailsTypeEnum) + return Models.UpiQrDetails.TypeEnum.ToJsonValue(upiQrDetailsTypeEnum); + if (obj is Models.VippsDetails.TypeEnum vippsDetailsTypeEnum) + return Models.VippsDetails.TypeEnum.ToJsonValue(vippsDetailsTypeEnum); + if (obj is Models.VisaCheckoutDetails.FundingSourceEnum visaCheckoutDetailsFundingSourceEnum) + return Models.VisaCheckoutDetails.FundingSourceEnum.ToJsonValue(visaCheckoutDetailsFundingSourceEnum); + if (obj is Models.VisaCheckoutDetails.TypeEnum visaCheckoutDetailsTypeEnum) + return Models.VisaCheckoutDetails.TypeEnum.ToJsonValue(visaCheckoutDetailsTypeEnum); + if (obj is Models.WeChatPayDetails.TypeEnum weChatPayDetailsTypeEnum) + return Models.WeChatPayDetails.TypeEnum.ToJsonValue(weChatPayDetailsTypeEnum); + if (obj is Models.WeChatPayMiniProgramDetails.TypeEnum weChatPayMiniProgramDetailsTypeEnum) + return Models.WeChatPayMiniProgramDetails.TypeEnum.ToJsonValue(weChatPayMiniProgramDetailsTypeEnum); + if (obj is Models.ZipDetails.TypeEnum zipDetailsTypeEnum) + return Models.ZipDetails.TypeEnum.ToJsonValue(zipDetailsTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Checkout/Client/HostConfiguration.cs b/Adyen/Checkout/Client/HostConfiguration.cs new file mode 100644 index 000000000..28512953b --- /dev/null +++ b/Adyen/Checkout/Client/HostConfiguration.cs @@ -0,0 +1,371 @@ +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Checkout.Services; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Checkout.Client +{ + /// + /// Provides hosting configuration for Checkout + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://checkout-test.adyen.com/v71"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountInfoJsonConverter()); + _jsonOptions.Converters.Add(new AcctInfoJsonConverter()); + _jsonOptions.Converters.Add(new AchDetailsJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalData3DSecureJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataAirlineJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataCarRentalJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataCommonJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataLevel23JsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataLodgingJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataOpenInvoiceJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataOpiJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRatepayJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRetryJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRiskJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRiskStandaloneJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataSubMerchantJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataTemporaryServicesJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataWalletsJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AffirmDetailsJsonConverter()); + _jsonOptions.Converters.Add(new AfterpayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new AgencyJsonConverter()); + _jsonOptions.Converters.Add(new AirlineJsonConverter()); + _jsonOptions.Converters.Add(new AmazonPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AmountsJsonConverter()); + _jsonOptions.Converters.Add(new AncvDetailsJsonConverter()); + _jsonOptions.Converters.Add(new AndroidPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ApplePayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ApplePayDonationsJsonConverter()); + _jsonOptions.Converters.Add(new ApplePaySessionRequestJsonConverter()); + _jsonOptions.Converters.Add(new ApplePaySessionResponseJsonConverter()); + _jsonOptions.Converters.Add(new ApplicationInfoJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationDataJsonConverter()); + _jsonOptions.Converters.Add(new BacsDirectDebitDetailsJsonConverter()); + _jsonOptions.Converters.Add(new BalanceCheckRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalanceCheckResponseJsonConverter()); + _jsonOptions.Converters.Add(new BillDeskDetailsJsonConverter()); + _jsonOptions.Converters.Add(new BillingAddressJsonConverter()); + _jsonOptions.Converters.Add(new BlikDetailsJsonConverter()); + _jsonOptions.Converters.Add(new BrowserInfoJsonConverter()); + _jsonOptions.Converters.Add(new CancelOrderRequestJsonConverter()); + _jsonOptions.Converters.Add(new CancelOrderResponseJsonConverter()); + _jsonOptions.Converters.Add(new CardBrandDetailsJsonConverter()); + _jsonOptions.Converters.Add(new CardDetailsJsonConverter()); + _jsonOptions.Converters.Add(new CardDetailsRequestJsonConverter()); + _jsonOptions.Converters.Add(new CardDetailsResponseJsonConverter()); + _jsonOptions.Converters.Add(new CardDonationsJsonConverter()); + _jsonOptions.Converters.Add(new CashAppDetailsJsonConverter()); + _jsonOptions.Converters.Add(new CellulantDetailsJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutAwaitActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutBankAccountJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutBankTransferActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutDelegatedAuthenticationActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutNativeRedirectActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutOrderResponseJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutQrCodeActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutRedirectActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutSDKActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutSessionInstallmentOptionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutSessionThreeDS2RequestDataJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutThreeDS2ActionJsonConverter()); + _jsonOptions.Converters.Add(new CheckoutVoucherActionJsonConverter()); + _jsonOptions.Converters.Add(new CommonFieldJsonConverter()); + _jsonOptions.Converters.Add(new CompanyJsonConverter()); + _jsonOptions.Converters.Add(new CreateCheckoutSessionRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateCheckoutSessionResponseJsonConverter()); + _jsonOptions.Converters.Add(new CreateOrderRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateOrderResponseJsonConverter()); + _jsonOptions.Converters.Add(new DefaultErrorResponseEntityJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryAddressJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryMethodJsonConverter()); + _jsonOptions.Converters.Add(new DetailsRequestAuthenticationDataJsonConverter()); + _jsonOptions.Converters.Add(new DeviceRenderOptionsJsonConverter()); + _jsonOptions.Converters.Add(new DokuDetailsJsonConverter()); + _jsonOptions.Converters.Add(new DonationJsonConverter()); + _jsonOptions.Converters.Add(new DonationCampaignJsonConverter()); + _jsonOptions.Converters.Add(new DonationCampaignsRequestJsonConverter()); + _jsonOptions.Converters.Add(new DonationCampaignsResponseJsonConverter()); + _jsonOptions.Converters.Add(new DonationPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new DonationPaymentRequestJsonConverter()); + _jsonOptions.Converters.Add(new DonationPaymentResponseJsonConverter()); + _jsonOptions.Converters.Add(new DragonpayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new EBankingFinlandDetailsJsonConverter()); + _jsonOptions.Converters.Add(new EcontextVoucherDetailsJsonConverter()); + _jsonOptions.Converters.Add(new EftDetailsJsonConverter()); + _jsonOptions.Converters.Add(new EncryptedOrderDataJsonConverter()); + _jsonOptions.Converters.Add(new EnhancedSchemeDataJsonConverter()); + _jsonOptions.Converters.Add(new ExternalPlatformJsonConverter()); + _jsonOptions.Converters.Add(new FastlaneDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ForexQuoteJsonConverter()); + _jsonOptions.Converters.Add(new FraudCheckResultJsonConverter()); + _jsonOptions.Converters.Add(new FraudResultJsonConverter()); + _jsonOptions.Converters.Add(new FundOriginJsonConverter()); + _jsonOptions.Converters.Add(new FundRecipientJsonConverter()); + _jsonOptions.Converters.Add(new GenericIssuerPaymentMethodDetailsJsonConverter()); + _jsonOptions.Converters.Add(new GooglePayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new GooglePayDonationsJsonConverter()); + _jsonOptions.Converters.Add(new IdealDetailsJsonConverter()); + _jsonOptions.Converters.Add(new IdealDonationsJsonConverter()); + _jsonOptions.Converters.Add(new InputDetailJsonConverter()); + _jsonOptions.Converters.Add(new InstallmentOptionJsonConverter()); + _jsonOptions.Converters.Add(new InstallmentsJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new ItemJsonConverter()); + _jsonOptions.Converters.Add(new KlarnaDetailsJsonConverter()); + _jsonOptions.Converters.Add(new LegJsonConverter()); + _jsonOptions.Converters.Add(new LineItemJsonConverter()); + _jsonOptions.Converters.Add(new ListStoredPaymentMethodsResponseJsonConverter()); + _jsonOptions.Converters.Add(new MandateJsonConverter()); + _jsonOptions.Converters.Add(new MasterpassDetailsJsonConverter()); + _jsonOptions.Converters.Add(new MbwayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new MerchantDeviceJsonConverter()); + _jsonOptions.Converters.Add(new MerchantRiskIndicatorJsonConverter()); + _jsonOptions.Converters.Add(new MobilePayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new MolPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new OpenInvoiceDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PassengerJsonConverter()); + _jsonOptions.Converters.Add(new PayByBankAISDirectDebitDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayByBankDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayPalDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayToDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayToPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new PayUUpiDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayWithGoogleDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PayWithGoogleDonationsJsonConverter()); + _jsonOptions.Converters.Add(new PaymentJsonConverter()); + _jsonOptions.Converters.Add(new PaymentAmountUpdateRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentAmountUpdateResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentCancelRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentCancelResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentCaptureRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentCaptureResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentCompletionDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PaymentDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PaymentDetailsRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentDetailsResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentLinkRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentLinkResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodGroupJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodIssuerJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodToStoreJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodUPIAppsJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodsRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodsResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRefundRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRefundResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentResponseActionJsonConverter()); + _jsonOptions.Converters.Add(new PaymentReversalRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentReversalResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentValidationsNameResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentValidationsNameResultRawResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentValidationsNameResultResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentValidationsResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaypalUpdateOrderRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaypalUpdateOrderResponseJsonConverter()); + _jsonOptions.Converters.Add(new PhoneJsonConverter()); + _jsonOptions.Converters.Add(new PixDetailsJsonConverter()); + _jsonOptions.Converters.Add(new PixRecurringJsonConverter()); + _jsonOptions.Converters.Add(new PlatformChargebackLogicJsonConverter()); + _jsonOptions.Converters.Add(new PseDetailsJsonConverter()); + _jsonOptions.Converters.Add(new RakutenPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new RatepayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new RecurringJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalData3DSecureJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataBillingAddressJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCardJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCommonJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataDomesticErrorJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataInstallmentsJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataNetworkTokensJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataOpiJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSepaJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSwishJsonConverter()); + _jsonOptions.Converters.Add(new ResponsePaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new ResultJsonConverter()); + _jsonOptions.Converters.Add(new ResultNullableJsonConverter()); + _jsonOptions.Converters.Add(new RiskDataJsonConverter()); + _jsonOptions.Converters.Add(new RivertyDetailsJsonConverter()); + _jsonOptions.Converters.Add(new SDKEphemPubKeyJsonConverter()); + _jsonOptions.Converters.Add(new SamsungPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new SepaDirectDebitDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new SessionResultResponseJsonConverter()); + _jsonOptions.Converters.Add(new ShopperIdPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new ShopperInteractionDeviceJsonConverter()); + _jsonOptions.Converters.Add(new ShopperNameJsonConverter()); + _jsonOptions.Converters.Add(new SplitJsonConverter()); + _jsonOptions.Converters.Add(new SplitAmountJsonConverter()); + _jsonOptions.Converters.Add(new StandalonePaymentCancelRequestJsonConverter()); + _jsonOptions.Converters.Add(new StandalonePaymentCancelResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new StoredPaymentMethodDetailsJsonConverter()); + _jsonOptions.Converters.Add(new StoredPaymentMethodRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredPaymentMethodResourceJsonConverter()); + _jsonOptions.Converters.Add(new SubInputDetailJsonConverter()); + _jsonOptions.Converters.Add(new SubMerchantJsonConverter()); + _jsonOptions.Converters.Add(new SubMerchantInfoJsonConverter()); + _jsonOptions.Converters.Add(new SurchargeJsonConverter()); + _jsonOptions.Converters.Add(new TaxTotalJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2RequestDataJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2RequestFieldsJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2ResponseDataJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2ResultJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSRequestDataJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSRequestorAuthenticationInfoJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSRequestorPriorAuthenticationInfoJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSecureDataJsonConverter()); + _jsonOptions.Converters.Add(new TicketJsonConverter()); + _jsonOptions.Converters.Add(new TravelAgencyJsonConverter()); + _jsonOptions.Converters.Add(new TwintDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UPIPaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new UpdatePaymentLinkRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpiCollectDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UpiIntentDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UpiQrDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UtilityRequestJsonConverter()); + _jsonOptions.Converters.Add(new UtilityResponseJsonConverter()); + _jsonOptions.Converters.Add(new ValidateShopperIdRequestJsonConverter()); + _jsonOptions.Converters.Add(new ValidateShopperIdResponseJsonConverter()); + _jsonOptions.Converters.Add(new VippsDetailsJsonConverter()); + _jsonOptions.Converters.Add(new VisaCheckoutDetailsJsonConverter()); + _jsonOptions.Converters.Add(new WeChatPayDetailsJsonConverter()); + _jsonOptions.Converters.Add(new WeChatPayMiniProgramDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ZipDetailsJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddCheckoutHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Checkout/Client/JsonSerializerOptionsProvider.cs b/Adyen/Checkout/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..0b7bc32d8 --- /dev/null +++ b/Adyen/Checkout/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Checkout.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Checkout/Extensions/HostBuilderExtensions.cs b/Adyen/Checkout/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..7c5f1cd42 --- /dev/null +++ b/Adyen/Checkout/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Checkout; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Checkout API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureCheckout(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddCheckoutHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Checkout/Extensions/ServiceCollectionExtensions.cs b/Adyen/Checkout/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..2bd21d9ea --- /dev/null +++ b/Adyen/Checkout/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Checkout API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddCheckoutServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddCheckoutHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Checkout/Models/AccountInfo.cs b/Adyen/Checkout/Models/AccountInfo.cs new file mode 100644 index 000000000..e5392a98d --- /dev/null +++ b/Adyen/Checkout/Models/AccountInfo.cs @@ -0,0 +1,1407 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AccountInfo. + /// + public partial class AccountInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Date when the shopper's account was last changed. + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Date when the shopper's account was created. + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// Number of attempts the shopper tried to add a card to their account in the last day. + /// Date the selected delivery address was first used. + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Shopper's home phone number (including the country code). + /// Shopper's mobile phone number (including the country code). + /// Date when the shopper last changed their password. + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + /// Date this payment method was added to the shopper's account. + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Number of successful purchases in the last six months. + /// Whether suspicious activity was recorded on this account. + /// Shopper's work phone number (including the country code). + [JsonConstructor] + public AccountInfo(Option accountAgeIndicator = default, Option accountChangeDate = default, Option accountChangeIndicator = default, Option accountCreationDate = default, Option accountType = default, Option addCardAttemptsDay = default, Option deliveryAddressUsageDate = default, Option deliveryAddressUsageIndicator = default, Option homePhone = default, Option mobilePhone = default, Option passwordChangeDate = default, Option passwordChangeIndicator = default, Option pastTransactionsDay = default, Option pastTransactionsYear = default, Option paymentAccountAge = default, Option paymentAccountIndicator = default, Option purchasesLast6Months = default, Option suspiciousActivity = default, Option workPhone = default) + { + _AccountAgeIndicatorOption = accountAgeIndicator; + _AccountChangeDateOption = accountChangeDate; + _AccountChangeIndicatorOption = accountChangeIndicator; + _AccountCreationDateOption = accountCreationDate; + _AccountTypeOption = accountType; + _AddCardAttemptsDayOption = addCardAttemptsDay; + _DeliveryAddressUsageDateOption = deliveryAddressUsageDate; + _DeliveryAddressUsageIndicatorOption = deliveryAddressUsageIndicator; + _HomePhoneOption = homePhone; + _MobilePhoneOption = mobilePhone; + _PasswordChangeDateOption = passwordChangeDate; + _PasswordChangeIndicatorOption = passwordChangeIndicator; + _PastTransactionsDayOption = pastTransactionsDay; + _PastTransactionsYearOption = pastTransactionsYear; + _PaymentAccountAgeOption = paymentAccountAge; + _PaymentAccountIndicatorOption = paymentAccountIndicator; + _PurchasesLast6MonthsOption = purchasesLast6Months; + _SuspiciousActivityOption = suspiciousActivity; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountInfo() + { + } + + partial void OnCreated(); + + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(AccountAgeIndicatorEnumJsonConverter))] + public class AccountAgeIndicatorEnum : IEnum + { + /// + /// Returns the value of the AccountAgeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// AccountAgeIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly AccountAgeIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// AccountAgeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly AccountAgeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// AccountAgeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly AccountAgeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// AccountAgeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly AccountAgeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// AccountAgeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly AccountAgeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private AccountAgeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountAgeIndicatorEnum?(string? value) => value == null ? null : new AccountAgeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountAgeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(AccountAgeIndicatorEnum? left, AccountAgeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountAgeIndicatorEnum? left, AccountAgeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountAgeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountAgeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => AccountAgeIndicatorEnum.NotApplicable, + "thisTransaction" => AccountAgeIndicatorEnum.ThisTransaction, + "lessThan30Days" => AccountAgeIndicatorEnum.LessThan30Days, + "from30To60Days" => AccountAgeIndicatorEnum.From30To60Days, + "moreThan60Days" => AccountAgeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountAgeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == AccountAgeIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == AccountAgeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == AccountAgeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == AccountAgeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == AccountAgeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing AccountAgeIndicatorEnum. + /// + public class AccountAgeIndicatorEnumJsonConverter : JsonConverter + { + public override AccountAgeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountAgeIndicatorEnum.FromStringOrDefault(value) ?? new AccountAgeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountAgeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountAgeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountAgeIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("accountAgeIndicator")] + public AccountAgeIndicatorEnum? AccountAgeIndicator { get { return this._AccountAgeIndicatorOption; } set { this._AccountAgeIndicatorOption = new(value); } } + + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(AccountChangeIndicatorEnumJsonConverter))] + public class AccountChangeIndicatorEnum : IEnum + { + /// + /// Returns the value of the AccountChangeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// AccountChangeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly AccountChangeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// AccountChangeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly AccountChangeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// AccountChangeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly AccountChangeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// AccountChangeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly AccountChangeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private AccountChangeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountChangeIndicatorEnum?(string? value) => value == null ? null : new AccountChangeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountChangeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(AccountChangeIndicatorEnum? left, AccountChangeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountChangeIndicatorEnum? left, AccountChangeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountChangeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountChangeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "thisTransaction" => AccountChangeIndicatorEnum.ThisTransaction, + "lessThan30Days" => AccountChangeIndicatorEnum.LessThan30Days, + "from30To60Days" => AccountChangeIndicatorEnum.From30To60Days, + "moreThan60Days" => AccountChangeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountChangeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == AccountChangeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == AccountChangeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == AccountChangeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == AccountChangeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing AccountChangeIndicatorEnum. + /// + public class AccountChangeIndicatorEnumJsonConverter : JsonConverter + { + public override AccountChangeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountChangeIndicatorEnum.FromStringOrDefault(value) ?? new AccountChangeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountChangeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountChangeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountChangeIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("accountChangeIndicator")] + public AccountChangeIndicatorEnum? AccountChangeIndicator { get { return this._AccountChangeIndicatorOption; } set { this._AccountChangeIndicatorOption = new(value); } } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.NotApplicable - notApplicable + /// + public static readonly AccountTypeEnum NotApplicable = new("notApplicable"); + + /// + /// AccountTypeEnum.Credit - credit + /// + public static readonly AccountTypeEnum Credit = new("credit"); + + /// + /// AccountTypeEnum.Debit - debit + /// + public static readonly AccountTypeEnum Debit = new("debit"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => AccountTypeEnum.NotApplicable, + "credit" => AccountTypeEnum.Credit, + "debit" => AccountTypeEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.NotApplicable) + return "notApplicable"; + + if (value == AccountTypeEnum.Credit) + return "credit"; + + if (value == AccountTypeEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(DeliveryAddressUsageIndicatorEnumJsonConverter))] + public class DeliveryAddressUsageIndicatorEnum : IEnum + { + /// + /// Returns the value of the DeliveryAddressUsageIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryAddressUsageIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly DeliveryAddressUsageIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// DeliveryAddressUsageIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// DeliveryAddressUsageIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// DeliveryAddressUsageIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private DeliveryAddressUsageIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryAddressUsageIndicatorEnum?(string? value) => value == null ? null : new DeliveryAddressUsageIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryAddressUsageIndicatorEnum? option) => option?.Value; + + public static bool operator ==(DeliveryAddressUsageIndicatorEnum? left, DeliveryAddressUsageIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryAddressUsageIndicatorEnum? left, DeliveryAddressUsageIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryAddressUsageIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryAddressUsageIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "thisTransaction" => DeliveryAddressUsageIndicatorEnum.ThisTransaction, + "lessThan30Days" => DeliveryAddressUsageIndicatorEnum.LessThan30Days, + "from30To60Days" => DeliveryAddressUsageIndicatorEnum.From30To60Days, + "moreThan60Days" => DeliveryAddressUsageIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryAddressUsageIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryAddressUsageIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == DeliveryAddressUsageIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == DeliveryAddressUsageIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == DeliveryAddressUsageIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryAddressUsageIndicatorEnum. + /// + public class DeliveryAddressUsageIndicatorEnumJsonConverter : JsonConverter + { + public override DeliveryAddressUsageIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryAddressUsageIndicatorEnum.FromStringOrDefault(value) ?? new DeliveryAddressUsageIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryAddressUsageIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryAddressUsageIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressUsageIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("deliveryAddressUsageIndicator")] + public DeliveryAddressUsageIndicatorEnum? DeliveryAddressUsageIndicator { get { return this._DeliveryAddressUsageIndicatorOption; } set { this._DeliveryAddressUsageIndicatorOption = new(value); } } + + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(PasswordChangeIndicatorEnumJsonConverter))] + public class PasswordChangeIndicatorEnum : IEnum + { + /// + /// Returns the value of the PasswordChangeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// PasswordChangeIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly PasswordChangeIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// PasswordChangeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly PasswordChangeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// PasswordChangeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly PasswordChangeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// PasswordChangeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly PasswordChangeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// PasswordChangeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly PasswordChangeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private PasswordChangeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PasswordChangeIndicatorEnum?(string? value) => value == null ? null : new PasswordChangeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PasswordChangeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(PasswordChangeIndicatorEnum? left, PasswordChangeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PasswordChangeIndicatorEnum? left, PasswordChangeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PasswordChangeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PasswordChangeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => PasswordChangeIndicatorEnum.NotApplicable, + "thisTransaction" => PasswordChangeIndicatorEnum.ThisTransaction, + "lessThan30Days" => PasswordChangeIndicatorEnum.LessThan30Days, + "from30To60Days" => PasswordChangeIndicatorEnum.From30To60Days, + "moreThan60Days" => PasswordChangeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PasswordChangeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == PasswordChangeIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == PasswordChangeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == PasswordChangeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == PasswordChangeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == PasswordChangeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing PasswordChangeIndicatorEnum. + /// + public class PasswordChangeIndicatorEnumJsonConverter : JsonConverter + { + public override PasswordChangeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PasswordChangeIndicatorEnum.FromStringOrDefault(value) ?? new PasswordChangeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PasswordChangeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PasswordChangeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordChangeIndicatorOption { get; private set; } + + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("passwordChangeIndicator")] + public PasswordChangeIndicatorEnum? PasswordChangeIndicator { get { return this._PasswordChangeIndicatorOption; } set { this._PasswordChangeIndicatorOption = new(value); } } + + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(PaymentAccountIndicatorEnumJsonConverter))] + public class PaymentAccountIndicatorEnum : IEnum + { + /// + /// Returns the value of the PaymentAccountIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentAccountIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly PaymentAccountIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// PaymentAccountIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly PaymentAccountIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// PaymentAccountIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly PaymentAccountIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// PaymentAccountIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly PaymentAccountIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// PaymentAccountIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly PaymentAccountIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private PaymentAccountIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentAccountIndicatorEnum?(string? value) => value == null ? null : new PaymentAccountIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentAccountIndicatorEnum? option) => option?.Value; + + public static bool operator ==(PaymentAccountIndicatorEnum? left, PaymentAccountIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentAccountIndicatorEnum? left, PaymentAccountIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentAccountIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentAccountIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => PaymentAccountIndicatorEnum.NotApplicable, + "thisTransaction" => PaymentAccountIndicatorEnum.ThisTransaction, + "lessThan30Days" => PaymentAccountIndicatorEnum.LessThan30Days, + "from30To60Days" => PaymentAccountIndicatorEnum.From30To60Days, + "moreThan60Days" => PaymentAccountIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentAccountIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == PaymentAccountIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == PaymentAccountIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == PaymentAccountIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == PaymentAccountIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == PaymentAccountIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing PaymentAccountIndicatorEnum. + /// + public class PaymentAccountIndicatorEnumJsonConverter : JsonConverter + { + public override PaymentAccountIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentAccountIndicatorEnum.FromStringOrDefault(value) ?? new PaymentAccountIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentAccountIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentAccountIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("paymentAccountIndicator")] + public PaymentAccountIndicatorEnum? PaymentAccountIndicator { get { return this._PaymentAccountIndicatorOption; } set { this._PaymentAccountIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountChangeDateOption { get; private set; } + + /// + /// Date when the shopper's account was last changed. + /// + /// Date when the shopper's account was last changed. + [JsonPropertyName("accountChangeDate")] + public DateTimeOffset? AccountChangeDate { get { return this._AccountChangeDateOption; } set { this._AccountChangeDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountCreationDateOption { get; private set; } + + /// + /// Date when the shopper's account was created. + /// + /// Date when the shopper's account was created. + [JsonPropertyName("accountCreationDate")] + public DateTimeOffset? AccountCreationDate { get { return this._AccountCreationDateOption; } set { this._AccountCreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddCardAttemptsDayOption { get; private set; } + + /// + /// Number of attempts the shopper tried to add a card to their account in the last day. + /// + /// Number of attempts the shopper tried to add a card to their account in the last day. + [JsonPropertyName("addCardAttemptsDay")] + public int? AddCardAttemptsDay { get { return this._AddCardAttemptsDayOption; } set { this._AddCardAttemptsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressUsageDateOption { get; private set; } + + /// + /// Date the selected delivery address was first used. + /// + /// Date the selected delivery address was first used. + [JsonPropertyName("deliveryAddressUsageDate")] + public DateTimeOffset? DeliveryAddressUsageDate { get { return this._DeliveryAddressUsageDateOption; } set { this._DeliveryAddressUsageDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// Shopper's home phone number (including the country code). + /// + /// Shopper's home phone number (including the country code). + [JsonPropertyName("homePhone")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `ThreeDS2RequestData.homePhone` instead.")] + public string? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// Shopper's mobile phone number (including the country code). + /// + /// Shopper's mobile phone number (including the country code). + [JsonPropertyName("mobilePhone")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `ThreeDS2RequestData.mobilePhone` instead.")] + public string? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordChangeDateOption { get; private set; } + + /// + /// Date when the shopper last changed their password. + /// + /// Date when the shopper last changed their password. + [JsonPropertyName("passwordChangeDate")] + public DateTimeOffset? PasswordChangeDate { get { return this._PasswordChangeDateOption; } set { this._PasswordChangeDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PastTransactionsDayOption { get; private set; } + + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + [JsonPropertyName("pastTransactionsDay")] + public int? PastTransactionsDay { get { return this._PastTransactionsDayOption; } set { this._PastTransactionsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PastTransactionsYearOption { get; private set; } + + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + [JsonPropertyName("pastTransactionsYear")] + public int? PastTransactionsYear { get { return this._PastTransactionsYearOption; } set { this._PastTransactionsYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountAgeOption { get; private set; } + + /// + /// Date this payment method was added to the shopper's account. + /// + /// Date this payment method was added to the shopper's account. + [JsonPropertyName("paymentAccountAge")] + public DateTimeOffset? PaymentAccountAge { get { return this._PaymentAccountAgeOption; } set { this._PaymentAccountAgeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurchasesLast6MonthsOption { get; private set; } + + /// + /// Number of successful purchases in the last six months. + /// + /// Number of successful purchases in the last six months. + [JsonPropertyName("purchasesLast6Months")] + public int? PurchasesLast6Months { get { return this._PurchasesLast6MonthsOption; } set { this._PurchasesLast6MonthsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuspiciousActivityOption { get; private set; } + + /// + /// Whether suspicious activity was recorded on this account. + /// + /// Whether suspicious activity was recorded on this account. + [JsonPropertyName("suspiciousActivity")] + public bool? SuspiciousActivity { get { return this._SuspiciousActivityOption; } set { this._SuspiciousActivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// Shopper's work phone number (including the country code). + /// + /// Shopper's work phone number (including the country code). + [JsonPropertyName("workPhone")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `ThreeDS2RequestData.workPhone` instead.")] + public string? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountInfo {\n"); + sb.Append(" AccountAgeIndicator: ").Append(AccountAgeIndicator).Append("\n"); + sb.Append(" AccountChangeDate: ").Append(AccountChangeDate).Append("\n"); + sb.Append(" AccountChangeIndicator: ").Append(AccountChangeIndicator).Append("\n"); + sb.Append(" AccountCreationDate: ").Append(AccountCreationDate).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" AddCardAttemptsDay: ").Append(AddCardAttemptsDay).Append("\n"); + sb.Append(" DeliveryAddressUsageDate: ").Append(DeliveryAddressUsageDate).Append("\n"); + sb.Append(" DeliveryAddressUsageIndicator: ").Append(DeliveryAddressUsageIndicator).Append("\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" PasswordChangeDate: ").Append(PasswordChangeDate).Append("\n"); + sb.Append(" PasswordChangeIndicator: ").Append(PasswordChangeIndicator).Append("\n"); + sb.Append(" PastTransactionsDay: ").Append(PastTransactionsDay).Append("\n"); + sb.Append(" PastTransactionsYear: ").Append(PastTransactionsYear).Append("\n"); + sb.Append(" PaymentAccountAge: ").Append(PaymentAccountAge).Append("\n"); + sb.Append(" PaymentAccountIndicator: ").Append(PaymentAccountIndicator).Append("\n"); + sb.Append(" PurchasesLast6Months: ").Append(PurchasesLast6Months).Append("\n"); + sb.Append(" SuspiciousActivity: ").Append(SuspiciousActivity).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize AccountChangeDate. + /// + public static string AccountChangeDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize AccountCreationDate. + /// + public static string AccountCreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliveryAddressUsageDate. + /// + public static string DeliveryAddressUsageDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize PasswordChangeDate. + /// + public static string PasswordChangeDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize PaymentAccountAge. + /// + public static string PaymentAccountAgeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountAgeIndicator = default; + Option accountChangeDate = default; + Option accountChangeIndicator = default; + Option accountCreationDate = default; + Option accountType = default; + Option addCardAttemptsDay = default; + Option deliveryAddressUsageDate = default; + Option deliveryAddressUsageIndicator = default; + Option homePhone = default; + Option mobilePhone = default; + Option passwordChangeDate = default; + Option passwordChangeIndicator = default; + Option pastTransactionsDay = default; + Option pastTransactionsYear = default; + Option paymentAccountAge = default; + Option paymentAccountIndicator = default; + Option purchasesLast6Months = default; + Option suspiciousActivity = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountAgeIndicator": + string? accountAgeIndicatorRawValue = utf8JsonReader.GetString(); + accountAgeIndicator = new Option(AccountInfo.AccountAgeIndicatorEnum.FromStringOrDefault(accountAgeIndicatorRawValue)); + break; + case "accountChangeDate": + accountChangeDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "accountChangeIndicator": + string? accountChangeIndicatorRawValue = utf8JsonReader.GetString(); + accountChangeIndicator = new Option(AccountInfo.AccountChangeIndicatorEnum.FromStringOrDefault(accountChangeIndicatorRawValue)); + break; + case "accountCreationDate": + accountCreationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(AccountInfo.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "addCardAttemptsDay": + addCardAttemptsDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "deliveryAddressUsageDate": + deliveryAddressUsageDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddressUsageIndicator": + string? deliveryAddressUsageIndicatorRawValue = utf8JsonReader.GetString(); + deliveryAddressUsageIndicator = new Option(AccountInfo.DeliveryAddressUsageIndicatorEnum.FromStringOrDefault(deliveryAddressUsageIndicatorRawValue)); + break; + case "homePhone": + homePhone = new Option(utf8JsonReader.GetString()!); + break; + case "mobilePhone": + mobilePhone = new Option(utf8JsonReader.GetString()!); + break; + case "passwordChangeDate": + passwordChangeDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "passwordChangeIndicator": + string? passwordChangeIndicatorRawValue = utf8JsonReader.GetString(); + passwordChangeIndicator = new Option(AccountInfo.PasswordChangeIndicatorEnum.FromStringOrDefault(passwordChangeIndicatorRawValue)); + break; + case "pastTransactionsDay": + pastTransactionsDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pastTransactionsYear": + pastTransactionsYear = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "paymentAccountAge": + paymentAccountAge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "paymentAccountIndicator": + string? paymentAccountIndicatorRawValue = utf8JsonReader.GetString(); + paymentAccountIndicator = new Option(AccountInfo.PaymentAccountIndicatorEnum.FromStringOrDefault(paymentAccountIndicatorRawValue)); + break; + case "purchasesLast6Months": + purchasesLast6Months = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "suspiciousActivity": + suspiciousActivity = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "workPhone": + workPhone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AccountInfo(accountAgeIndicator, accountChangeDate, accountChangeIndicator, accountCreationDate, accountType, addCardAttemptsDay, deliveryAddressUsageDate, deliveryAddressUsageIndicator, homePhone, mobilePhone, passwordChangeDate, passwordChangeIndicator, pastTransactionsDay, pastTransactionsYear, paymentAccountAge, paymentAccountIndicator, purchasesLast6Months, suspiciousActivity, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountInfo accountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountInfo accountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountInfo._AccountAgeIndicatorOption.IsSet && accountInfo.AccountAgeIndicator != null) + { + string? accountAgeIndicatorRawValue = AccountInfo.AccountAgeIndicatorEnum.ToJsonValue(accountInfo._AccountAgeIndicatorOption.Value!.Value); + writer.WriteString("accountAgeIndicator", accountAgeIndicatorRawValue); + } + + if (accountInfo._AccountChangeDateOption.IsSet) + writer.WriteString("accountChangeDate", accountInfo._AccountChangeDateOption.Value!.Value.ToString(AccountChangeDateFormat)); + + if (accountInfo._AccountChangeIndicatorOption.IsSet && accountInfo.AccountChangeIndicator != null) + { + string? accountChangeIndicatorRawValue = AccountInfo.AccountChangeIndicatorEnum.ToJsonValue(accountInfo._AccountChangeIndicatorOption.Value!.Value); + writer.WriteString("accountChangeIndicator", accountChangeIndicatorRawValue); + } + + if (accountInfo._AccountCreationDateOption.IsSet) + writer.WriteString("accountCreationDate", accountInfo._AccountCreationDateOption.Value!.Value.ToString(AccountCreationDateFormat)); + + if (accountInfo._AccountTypeOption.IsSet && accountInfo.AccountType != null) + { + string? accountTypeRawValue = AccountInfo.AccountTypeEnum.ToJsonValue(accountInfo._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (accountInfo._AddCardAttemptsDayOption.IsSet) + writer.WriteNumber("addCardAttemptsDay", accountInfo._AddCardAttemptsDayOption.Value!.Value); + + if (accountInfo._DeliveryAddressUsageDateOption.IsSet) + writer.WriteString("deliveryAddressUsageDate", accountInfo._DeliveryAddressUsageDateOption.Value!.Value.ToString(DeliveryAddressUsageDateFormat)); + + if (accountInfo._DeliveryAddressUsageIndicatorOption.IsSet && accountInfo.DeliveryAddressUsageIndicator != null) + { + string? deliveryAddressUsageIndicatorRawValue = AccountInfo.DeliveryAddressUsageIndicatorEnum.ToJsonValue(accountInfo._DeliveryAddressUsageIndicatorOption.Value!.Value); + writer.WriteString("deliveryAddressUsageIndicator", deliveryAddressUsageIndicatorRawValue); + } + + if (accountInfo._HomePhoneOption.IsSet) + if (accountInfo.HomePhone != null) + writer.WriteString("homePhone", accountInfo.HomePhone); + + if (accountInfo._MobilePhoneOption.IsSet) + if (accountInfo.MobilePhone != null) + writer.WriteString("mobilePhone", accountInfo.MobilePhone); + + if (accountInfo._PasswordChangeDateOption.IsSet) + writer.WriteString("passwordChangeDate", accountInfo._PasswordChangeDateOption.Value!.Value.ToString(PasswordChangeDateFormat)); + + if (accountInfo._PasswordChangeIndicatorOption.IsSet && accountInfo.PasswordChangeIndicator != null) + { + string? passwordChangeIndicatorRawValue = AccountInfo.PasswordChangeIndicatorEnum.ToJsonValue(accountInfo._PasswordChangeIndicatorOption.Value!.Value); + writer.WriteString("passwordChangeIndicator", passwordChangeIndicatorRawValue); + } + + if (accountInfo._PastTransactionsDayOption.IsSet) + writer.WriteNumber("pastTransactionsDay", accountInfo._PastTransactionsDayOption.Value!.Value); + + if (accountInfo._PastTransactionsYearOption.IsSet) + writer.WriteNumber("pastTransactionsYear", accountInfo._PastTransactionsYearOption.Value!.Value); + + if (accountInfo._PaymentAccountAgeOption.IsSet) + writer.WriteString("paymentAccountAge", accountInfo._PaymentAccountAgeOption.Value!.Value.ToString(PaymentAccountAgeFormat)); + + if (accountInfo._PaymentAccountIndicatorOption.IsSet && accountInfo.PaymentAccountIndicator != null) + { + string? paymentAccountIndicatorRawValue = AccountInfo.PaymentAccountIndicatorEnum.ToJsonValue(accountInfo._PaymentAccountIndicatorOption.Value!.Value); + writer.WriteString("paymentAccountIndicator", paymentAccountIndicatorRawValue); + } + + if (accountInfo._PurchasesLast6MonthsOption.IsSet) + writer.WriteNumber("purchasesLast6Months", accountInfo._PurchasesLast6MonthsOption.Value!.Value); + + if (accountInfo._SuspiciousActivityOption.IsSet) + writer.WriteBoolean("suspiciousActivity", accountInfo._SuspiciousActivityOption.Value!.Value); + + if (accountInfo._WorkPhoneOption.IsSet) + if (accountInfo.WorkPhone != null) + writer.WriteString("workPhone", accountInfo.WorkPhone); + } + } +} diff --git a/Adyen/Checkout/Models/AcctInfo.cs b/Adyen/Checkout/Models/AcctInfo.cs new file mode 100644 index 000000000..4ec2bb237 --- /dev/null +++ b/Adyen/Checkout/Models/AcctInfo.cs @@ -0,0 +1,1423 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AcctInfo. + /// + public partial class AcctInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + [JsonConstructor] + public AcctInfo(Option chAccAgeInd = default, Option chAccChange = default, Option chAccChangeInd = default, Option chAccPwChange = default, Option chAccPwChangeInd = default, Option chAccString = default, Option nbPurchaseAccount = default, Option paymentAccAge = default, Option paymentAccInd = default, Option provisionAttemptsDay = default, Option shipAddressUsage = default, Option shipAddressUsageInd = default, Option shipNameIndicator = default, Option suspiciousAccActivity = default, Option txnActivityDay = default, Option txnActivityYear = default) + { + _ChAccAgeIndOption = chAccAgeInd; + _ChAccChangeOption = chAccChange; + _ChAccChangeIndOption = chAccChangeInd; + _ChAccPwChangeOption = chAccPwChange; + _ChAccPwChangeIndOption = chAccPwChangeInd; + _ChAccStringOption = chAccString; + _NbPurchaseAccountOption = nbPurchaseAccount; + _PaymentAccAgeOption = paymentAccAge; + _PaymentAccIndOption = paymentAccInd; + _ProvisionAttemptsDayOption = provisionAttemptsDay; + _ShipAddressUsageOption = shipAddressUsage; + _ShipAddressUsageIndOption = shipAddressUsageInd; + _ShipNameIndicatorOption = shipNameIndicator; + _SuspiciousAccActivityOption = suspiciousAccActivity; + _TxnActivityDayOption = txnActivityDay; + _TxnActivityYearOption = txnActivityYear; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcctInfo() + { + } + + partial void OnCreated(); + + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(ChAccAgeIndEnumJsonConverter))] + public class ChAccAgeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccAgeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccAgeIndEnum._01 - 01 + /// + public static readonly ChAccAgeIndEnum _01 = new("01"); + + /// + /// ChAccAgeIndEnum._02 - 02 + /// + public static readonly ChAccAgeIndEnum _02 = new("02"); + + /// + /// ChAccAgeIndEnum._03 - 03 + /// + public static readonly ChAccAgeIndEnum _03 = new("03"); + + /// + /// ChAccAgeIndEnum._04 - 04 + /// + public static readonly ChAccAgeIndEnum _04 = new("04"); + + /// + /// ChAccAgeIndEnum._05 - 05 + /// + public static readonly ChAccAgeIndEnum _05 = new("05"); + + private ChAccAgeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccAgeIndEnum?(string? value) => value == null ? null : new ChAccAgeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccAgeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccAgeIndEnum? left, ChAccAgeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccAgeIndEnum? left, ChAccAgeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccAgeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccAgeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccAgeIndEnum._01, + "02" => ChAccAgeIndEnum._02, + "03" => ChAccAgeIndEnum._03, + "04" => ChAccAgeIndEnum._04, + "05" => ChAccAgeIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccAgeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccAgeIndEnum._01) + return "01"; + + if (value == ChAccAgeIndEnum._02) + return "02"; + + if (value == ChAccAgeIndEnum._03) + return "03"; + + if (value == ChAccAgeIndEnum._04) + return "04"; + + if (value == ChAccAgeIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChAccAgeIndEnum. + /// + public class ChAccAgeIndEnumJsonConverter : JsonConverter + { + public override ChAccAgeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccAgeIndEnum.FromStringOrDefault(value) ?? new ChAccAgeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccAgeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccAgeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccAgeIndOption { get; private set; } + + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("chAccAgeInd")] + public ChAccAgeIndEnum? ChAccAgeInd { get { return this._ChAccAgeIndOption; } set { this._ChAccAgeIndOption = new(value); } } + + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonConverter(typeof(ChAccChangeIndEnumJsonConverter))] + public class ChAccChangeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccChangeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccChangeIndEnum._01 - 01 + /// + public static readonly ChAccChangeIndEnum _01 = new("01"); + + /// + /// ChAccChangeIndEnum._02 - 02 + /// + public static readonly ChAccChangeIndEnum _02 = new("02"); + + /// + /// ChAccChangeIndEnum._03 - 03 + /// + public static readonly ChAccChangeIndEnum _03 = new("03"); + + /// + /// ChAccChangeIndEnum._04 - 04 + /// + public static readonly ChAccChangeIndEnum _04 = new("04"); + + private ChAccChangeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccChangeIndEnum?(string? value) => value == null ? null : new ChAccChangeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccChangeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccChangeIndEnum? left, ChAccChangeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccChangeIndEnum? left, ChAccChangeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccChangeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccChangeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccChangeIndEnum._01, + "02" => ChAccChangeIndEnum._02, + "03" => ChAccChangeIndEnum._03, + "04" => ChAccChangeIndEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccChangeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccChangeIndEnum._01) + return "01"; + + if (value == ChAccChangeIndEnum._02) + return "02"; + + if (value == ChAccChangeIndEnum._03) + return "03"; + + if (value == ChAccChangeIndEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ChAccChangeIndEnum. + /// + public class ChAccChangeIndEnumJsonConverter : JsonConverter + { + public override ChAccChangeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccChangeIndEnum.FromStringOrDefault(value) ?? new ChAccChangeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccChangeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccChangeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccChangeIndOption { get; private set; } + + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonPropertyName("chAccChangeInd")] + public ChAccChangeIndEnum? ChAccChangeInd { get { return this._ChAccChangeIndOption; } set { this._ChAccChangeIndOption = new(value); } } + + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(ChAccPwChangeIndEnumJsonConverter))] + public class ChAccPwChangeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccPwChangeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccPwChangeIndEnum._01 - 01 + /// + public static readonly ChAccPwChangeIndEnum _01 = new("01"); + + /// + /// ChAccPwChangeIndEnum._02 - 02 + /// + public static readonly ChAccPwChangeIndEnum _02 = new("02"); + + /// + /// ChAccPwChangeIndEnum._03 - 03 + /// + public static readonly ChAccPwChangeIndEnum _03 = new("03"); + + /// + /// ChAccPwChangeIndEnum._04 - 04 + /// + public static readonly ChAccPwChangeIndEnum _04 = new("04"); + + /// + /// ChAccPwChangeIndEnum._05 - 05 + /// + public static readonly ChAccPwChangeIndEnum _05 = new("05"); + + private ChAccPwChangeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccPwChangeIndEnum?(string? value) => value == null ? null : new ChAccPwChangeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccPwChangeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccPwChangeIndEnum? left, ChAccPwChangeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccPwChangeIndEnum? left, ChAccPwChangeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccPwChangeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccPwChangeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccPwChangeIndEnum._01, + "02" => ChAccPwChangeIndEnum._02, + "03" => ChAccPwChangeIndEnum._03, + "04" => ChAccPwChangeIndEnum._04, + "05" => ChAccPwChangeIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccPwChangeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccPwChangeIndEnum._01) + return "01"; + + if (value == ChAccPwChangeIndEnum._02) + return "02"; + + if (value == ChAccPwChangeIndEnum._03) + return "03"; + + if (value == ChAccPwChangeIndEnum._04) + return "04"; + + if (value == ChAccPwChangeIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChAccPwChangeIndEnum. + /// + public class ChAccPwChangeIndEnumJsonConverter : JsonConverter + { + public override ChAccPwChangeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccPwChangeIndEnum.FromStringOrDefault(value) ?? new ChAccPwChangeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccPwChangeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccPwChangeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccPwChangeIndOption { get; private set; } + + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("chAccPwChangeInd")] + public ChAccPwChangeIndEnum? ChAccPwChangeInd { get { return this._ChAccPwChangeIndOption; } set { this._ChAccPwChangeIndOption = new(value); } } + + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(PaymentAccIndEnumJsonConverter))] + public class PaymentAccIndEnum : IEnum + { + /// + /// Returns the value of the PaymentAccIndEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentAccIndEnum._01 - 01 + /// + public static readonly PaymentAccIndEnum _01 = new("01"); + + /// + /// PaymentAccIndEnum._02 - 02 + /// + public static readonly PaymentAccIndEnum _02 = new("02"); + + /// + /// PaymentAccIndEnum._03 - 03 + /// + public static readonly PaymentAccIndEnum _03 = new("03"); + + /// + /// PaymentAccIndEnum._04 - 04 + /// + public static readonly PaymentAccIndEnum _04 = new("04"); + + /// + /// PaymentAccIndEnum._05 - 05 + /// + public static readonly PaymentAccIndEnum _05 = new("05"); + + private PaymentAccIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentAccIndEnum?(string? value) => value == null ? null : new PaymentAccIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentAccIndEnum? option) => option?.Value; + + public static bool operator ==(PaymentAccIndEnum? left, PaymentAccIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentAccIndEnum? left, PaymentAccIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentAccIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentAccIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => PaymentAccIndEnum._01, + "02" => PaymentAccIndEnum._02, + "03" => PaymentAccIndEnum._03, + "04" => PaymentAccIndEnum._04, + "05" => PaymentAccIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentAccIndEnum? value) + { + if (value == null) + return null; + + if (value == PaymentAccIndEnum._01) + return "01"; + + if (value == PaymentAccIndEnum._02) + return "02"; + + if (value == PaymentAccIndEnum._03) + return "03"; + + if (value == PaymentAccIndEnum._04) + return "04"; + + if (value == PaymentAccIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing PaymentAccIndEnum. + /// + public class PaymentAccIndEnumJsonConverter : JsonConverter + { + public override PaymentAccIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentAccIndEnum.FromStringOrDefault(value) ?? new PaymentAccIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentAccIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentAccIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccIndOption { get; private set; } + + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("paymentAccInd")] + public PaymentAccIndEnum? PaymentAccInd { get { return this._PaymentAccIndOption; } set { this._PaymentAccIndOption = new(value); } } + + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonConverter(typeof(ShipAddressUsageIndEnumJsonConverter))] + public class ShipAddressUsageIndEnum : IEnum + { + /// + /// Returns the value of the ShipAddressUsageIndEnum. + /// + public string? Value { get; set; } + + /// + /// ShipAddressUsageIndEnum._01 - 01 + /// + public static readonly ShipAddressUsageIndEnum _01 = new("01"); + + /// + /// ShipAddressUsageIndEnum._02 - 02 + /// + public static readonly ShipAddressUsageIndEnum _02 = new("02"); + + /// + /// ShipAddressUsageIndEnum._03 - 03 + /// + public static readonly ShipAddressUsageIndEnum _03 = new("03"); + + /// + /// ShipAddressUsageIndEnum._04 - 04 + /// + public static readonly ShipAddressUsageIndEnum _04 = new("04"); + + private ShipAddressUsageIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShipAddressUsageIndEnum?(string? value) => value == null ? null : new ShipAddressUsageIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShipAddressUsageIndEnum? option) => option?.Value; + + public static bool operator ==(ShipAddressUsageIndEnum? left, ShipAddressUsageIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShipAddressUsageIndEnum? left, ShipAddressUsageIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShipAddressUsageIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShipAddressUsageIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ShipAddressUsageIndEnum._01, + "02" => ShipAddressUsageIndEnum._02, + "03" => ShipAddressUsageIndEnum._03, + "04" => ShipAddressUsageIndEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShipAddressUsageIndEnum? value) + { + if (value == null) + return null; + + if (value == ShipAddressUsageIndEnum._01) + return "01"; + + if (value == ShipAddressUsageIndEnum._02) + return "02"; + + if (value == ShipAddressUsageIndEnum._03) + return "03"; + + if (value == ShipAddressUsageIndEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ShipAddressUsageIndEnum. + /// + public class ShipAddressUsageIndEnumJsonConverter : JsonConverter + { + public override ShipAddressUsageIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShipAddressUsageIndEnum.FromStringOrDefault(value) ?? new ShipAddressUsageIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShipAddressUsageIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShipAddressUsageIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipAddressUsageIndOption { get; private set; } + + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonPropertyName("shipAddressUsageInd")] + public ShipAddressUsageIndEnum? ShipAddressUsageInd { get { return this._ShipAddressUsageIndOption; } set { this._ShipAddressUsageIndOption = new(value); } } + + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + [JsonConverter(typeof(ShipNameIndicatorEnumJsonConverter))] + public class ShipNameIndicatorEnum : IEnum + { + /// + /// Returns the value of the ShipNameIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ShipNameIndicatorEnum._01 - 01 + /// + public static readonly ShipNameIndicatorEnum _01 = new("01"); + + /// + /// ShipNameIndicatorEnum._02 - 02 + /// + public static readonly ShipNameIndicatorEnum _02 = new("02"); + + private ShipNameIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShipNameIndicatorEnum?(string? value) => value == null ? null : new ShipNameIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShipNameIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ShipNameIndicatorEnum? left, ShipNameIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShipNameIndicatorEnum? left, ShipNameIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShipNameIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShipNameIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ShipNameIndicatorEnum._01, + "02" => ShipNameIndicatorEnum._02, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShipNameIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ShipNameIndicatorEnum._01) + return "01"; + + if (value == ShipNameIndicatorEnum._02) + return "02"; + + return null; + } + + /// + /// JsonConverter for writing ShipNameIndicatorEnum. + /// + public class ShipNameIndicatorEnumJsonConverter : JsonConverter + { + public override ShipNameIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShipNameIndicatorEnum.FromStringOrDefault(value) ?? new ShipNameIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShipNameIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShipNameIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipNameIndicatorOption { get; private set; } + + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + [JsonPropertyName("shipNameIndicator")] + public ShipNameIndicatorEnum? ShipNameIndicator { get { return this._ShipNameIndicatorOption; } set { this._ShipNameIndicatorOption = new(value); } } + + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + [JsonConverter(typeof(SuspiciousAccActivityEnumJsonConverter))] + public class SuspiciousAccActivityEnum : IEnum + { + /// + /// Returns the value of the SuspiciousAccActivityEnum. + /// + public string? Value { get; set; } + + /// + /// SuspiciousAccActivityEnum._01 - 01 + /// + public static readonly SuspiciousAccActivityEnum _01 = new("01"); + + /// + /// SuspiciousAccActivityEnum._02 - 02 + /// + public static readonly SuspiciousAccActivityEnum _02 = new("02"); + + private SuspiciousAccActivityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SuspiciousAccActivityEnum?(string? value) => value == null ? null : new SuspiciousAccActivityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SuspiciousAccActivityEnum? option) => option?.Value; + + public static bool operator ==(SuspiciousAccActivityEnum? left, SuspiciousAccActivityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SuspiciousAccActivityEnum? left, SuspiciousAccActivityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SuspiciousAccActivityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SuspiciousAccActivityEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => SuspiciousAccActivityEnum._01, + "02" => SuspiciousAccActivityEnum._02, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SuspiciousAccActivityEnum? value) + { + if (value == null) + return null; + + if (value == SuspiciousAccActivityEnum._01) + return "01"; + + if (value == SuspiciousAccActivityEnum._02) + return "02"; + + return null; + } + + /// + /// JsonConverter for writing SuspiciousAccActivityEnum. + /// + public class SuspiciousAccActivityEnumJsonConverter : JsonConverter + { + public override SuspiciousAccActivityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SuspiciousAccActivityEnum.FromStringOrDefault(value) ?? new SuspiciousAccActivityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SuspiciousAccActivityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SuspiciousAccActivityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuspiciousAccActivityOption { get; private set; } + + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + [JsonPropertyName("suspiciousAccActivity")] + public SuspiciousAccActivityEnum? SuspiciousAccActivity { get { return this._SuspiciousAccActivityOption; } set { this._SuspiciousAccActivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccChangeOption { get; private set; } + + /// + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + /// + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + [JsonPropertyName("chAccChange")] + public string? ChAccChange { get { return this._ChAccChangeOption; } set { this._ChAccChangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccPwChangeOption { get; private set; } + + /// + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + /// + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + [JsonPropertyName("chAccPwChange")] + public string? ChAccPwChange { get { return this._ChAccPwChangeOption; } set { this._ChAccPwChangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccStringOption { get; private set; } + + /// + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("chAccString")] + public string? ChAccString { get { return this._ChAccStringOption; } set { this._ChAccStringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NbPurchaseAccountOption { get; private set; } + + /// + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + /// + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + [JsonPropertyName("nbPurchaseAccount")] + public string? NbPurchaseAccount { get { return this._NbPurchaseAccountOption; } set { this._NbPurchaseAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccAgeOption { get; private set; } + + /// + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("paymentAccAge")] + public string? PaymentAccAge { get { return this._PaymentAccAgeOption; } set { this._PaymentAccAgeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProvisionAttemptsDayOption { get; private set; } + + /// + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + /// + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + [JsonPropertyName("provisionAttemptsDay")] + public string? ProvisionAttemptsDay { get { return this._ProvisionAttemptsDayOption; } set { this._ProvisionAttemptsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipAddressUsageOption { get; private set; } + + /// + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("shipAddressUsage")] + public string? ShipAddressUsage { get { return this._ShipAddressUsageOption; } set { this._ShipAddressUsageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TxnActivityDayOption { get; private set; } + + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + [JsonPropertyName("txnActivityDay")] + public string? TxnActivityDay { get { return this._TxnActivityDayOption; } set { this._TxnActivityDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TxnActivityYearOption { get; private set; } + + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + [JsonPropertyName("txnActivityYear")] + public string? TxnActivityYear { get { return this._TxnActivityYearOption; } set { this._TxnActivityYearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcctInfo {\n"); + sb.Append(" ChAccAgeInd: ").Append(ChAccAgeInd).Append("\n"); + sb.Append(" ChAccChange: ").Append(ChAccChange).Append("\n"); + sb.Append(" ChAccChangeInd: ").Append(ChAccChangeInd).Append("\n"); + sb.Append(" ChAccPwChange: ").Append(ChAccPwChange).Append("\n"); + sb.Append(" ChAccPwChangeInd: ").Append(ChAccPwChangeInd).Append("\n"); + sb.Append(" ChAccString: ").Append(ChAccString).Append("\n"); + sb.Append(" NbPurchaseAccount: ").Append(NbPurchaseAccount).Append("\n"); + sb.Append(" PaymentAccAge: ").Append(PaymentAccAge).Append("\n"); + sb.Append(" PaymentAccInd: ").Append(PaymentAccInd).Append("\n"); + sb.Append(" ProvisionAttemptsDay: ").Append(ProvisionAttemptsDay).Append("\n"); + sb.Append(" ShipAddressUsage: ").Append(ShipAddressUsage).Append("\n"); + sb.Append(" ShipAddressUsageInd: ").Append(ShipAddressUsageInd).Append("\n"); + sb.Append(" ShipNameIndicator: ").Append(ShipNameIndicator).Append("\n"); + sb.Append(" SuspiciousAccActivity: ").Append(SuspiciousAccActivity).Append("\n"); + sb.Append(" TxnActivityDay: ").Append(TxnActivityDay).Append("\n"); + sb.Append(" TxnActivityYear: ").Append(TxnActivityYear).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // TxnActivityDay (string) maxLength + if (this.TxnActivityDay != null && this.TxnActivityDay.Length > 3) + { + yield return new ValidationResult("Invalid value for TxnActivityDay, length must be less than 3.", new [] { "TxnActivityDay" }); + } + + // TxnActivityYear (string) maxLength + if (this.TxnActivityYear != null && this.TxnActivityYear.Length > 3) + { + yield return new ValidationResult("Invalid value for TxnActivityYear, length must be less than 3.", new [] { "TxnActivityYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcctInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcctInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option chAccAgeInd = default; + Option chAccChange = default; + Option chAccChangeInd = default; + Option chAccPwChange = default; + Option chAccPwChangeInd = default; + Option chAccString = default; + Option nbPurchaseAccount = default; + Option paymentAccAge = default; + Option paymentAccInd = default; + Option provisionAttemptsDay = default; + Option shipAddressUsage = default; + Option shipAddressUsageInd = default; + Option shipNameIndicator = default; + Option suspiciousAccActivity = default; + Option txnActivityDay = default; + Option txnActivityYear = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "chAccAgeInd": + string? chAccAgeIndRawValue = utf8JsonReader.GetString(); + chAccAgeInd = new Option(AcctInfo.ChAccAgeIndEnum.FromStringOrDefault(chAccAgeIndRawValue)); + break; + case "chAccChange": + chAccChange = new Option(utf8JsonReader.GetString()!); + break; + case "chAccChangeInd": + string? chAccChangeIndRawValue = utf8JsonReader.GetString(); + chAccChangeInd = new Option(AcctInfo.ChAccChangeIndEnum.FromStringOrDefault(chAccChangeIndRawValue)); + break; + case "chAccPwChange": + chAccPwChange = new Option(utf8JsonReader.GetString()!); + break; + case "chAccPwChangeInd": + string? chAccPwChangeIndRawValue = utf8JsonReader.GetString(); + chAccPwChangeInd = new Option(AcctInfo.ChAccPwChangeIndEnum.FromStringOrDefault(chAccPwChangeIndRawValue)); + break; + case "chAccString": + chAccString = new Option(utf8JsonReader.GetString()!); + break; + case "nbPurchaseAccount": + nbPurchaseAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccAge": + paymentAccAge = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccInd": + string? paymentAccIndRawValue = utf8JsonReader.GetString(); + paymentAccInd = new Option(AcctInfo.PaymentAccIndEnum.FromStringOrDefault(paymentAccIndRawValue)); + break; + case "provisionAttemptsDay": + provisionAttemptsDay = new Option(utf8JsonReader.GetString()!); + break; + case "shipAddressUsage": + shipAddressUsage = new Option(utf8JsonReader.GetString()!); + break; + case "shipAddressUsageInd": + string? shipAddressUsageIndRawValue = utf8JsonReader.GetString(); + shipAddressUsageInd = new Option(AcctInfo.ShipAddressUsageIndEnum.FromStringOrDefault(shipAddressUsageIndRawValue)); + break; + case "shipNameIndicator": + string? shipNameIndicatorRawValue = utf8JsonReader.GetString(); + shipNameIndicator = new Option(AcctInfo.ShipNameIndicatorEnum.FromStringOrDefault(shipNameIndicatorRawValue)); + break; + case "suspiciousAccActivity": + string? suspiciousAccActivityRawValue = utf8JsonReader.GetString(); + suspiciousAccActivity = new Option(AcctInfo.SuspiciousAccActivityEnum.FromStringOrDefault(suspiciousAccActivityRawValue)); + break; + case "txnActivityDay": + txnActivityDay = new Option(utf8JsonReader.GetString()!); + break; + case "txnActivityYear": + txnActivityYear = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AcctInfo(chAccAgeInd, chAccChange, chAccChangeInd, chAccPwChange, chAccPwChangeInd, chAccString, nbPurchaseAccount, paymentAccAge, paymentAccInd, provisionAttemptsDay, shipAddressUsage, shipAddressUsageInd, shipNameIndicator, suspiciousAccActivity, txnActivityDay, txnActivityYear); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcctInfo acctInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acctInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcctInfo acctInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (acctInfo._ChAccAgeIndOption.IsSet && acctInfo.ChAccAgeInd != null) + { + string? chAccAgeIndRawValue = AcctInfo.ChAccAgeIndEnum.ToJsonValue(acctInfo._ChAccAgeIndOption.Value!.Value); + writer.WriteString("chAccAgeInd", chAccAgeIndRawValue); + } + + if (acctInfo._ChAccChangeOption.IsSet) + if (acctInfo.ChAccChange != null) + writer.WriteString("chAccChange", acctInfo.ChAccChange); + + if (acctInfo._ChAccChangeIndOption.IsSet && acctInfo.ChAccChangeInd != null) + { + string? chAccChangeIndRawValue = AcctInfo.ChAccChangeIndEnum.ToJsonValue(acctInfo._ChAccChangeIndOption.Value!.Value); + writer.WriteString("chAccChangeInd", chAccChangeIndRawValue); + } + + if (acctInfo._ChAccPwChangeOption.IsSet) + if (acctInfo.ChAccPwChange != null) + writer.WriteString("chAccPwChange", acctInfo.ChAccPwChange); + + if (acctInfo._ChAccPwChangeIndOption.IsSet && acctInfo.ChAccPwChangeInd != null) + { + string? chAccPwChangeIndRawValue = AcctInfo.ChAccPwChangeIndEnum.ToJsonValue(acctInfo._ChAccPwChangeIndOption.Value!.Value); + writer.WriteString("chAccPwChangeInd", chAccPwChangeIndRawValue); + } + + if (acctInfo._ChAccStringOption.IsSet) + if (acctInfo.ChAccString != null) + writer.WriteString("chAccString", acctInfo.ChAccString); + + if (acctInfo._NbPurchaseAccountOption.IsSet) + if (acctInfo.NbPurchaseAccount != null) + writer.WriteString("nbPurchaseAccount", acctInfo.NbPurchaseAccount); + + if (acctInfo._PaymentAccAgeOption.IsSet) + if (acctInfo.PaymentAccAge != null) + writer.WriteString("paymentAccAge", acctInfo.PaymentAccAge); + + if (acctInfo._PaymentAccIndOption.IsSet && acctInfo.PaymentAccInd != null) + { + string? paymentAccIndRawValue = AcctInfo.PaymentAccIndEnum.ToJsonValue(acctInfo._PaymentAccIndOption.Value!.Value); + writer.WriteString("paymentAccInd", paymentAccIndRawValue); + } + + if (acctInfo._ProvisionAttemptsDayOption.IsSet) + if (acctInfo.ProvisionAttemptsDay != null) + writer.WriteString("provisionAttemptsDay", acctInfo.ProvisionAttemptsDay); + + if (acctInfo._ShipAddressUsageOption.IsSet) + if (acctInfo.ShipAddressUsage != null) + writer.WriteString("shipAddressUsage", acctInfo.ShipAddressUsage); + + if (acctInfo._ShipAddressUsageIndOption.IsSet && acctInfo.ShipAddressUsageInd != null) + { + string? shipAddressUsageIndRawValue = AcctInfo.ShipAddressUsageIndEnum.ToJsonValue(acctInfo._ShipAddressUsageIndOption.Value!.Value); + writer.WriteString("shipAddressUsageInd", shipAddressUsageIndRawValue); + } + + if (acctInfo._ShipNameIndicatorOption.IsSet && acctInfo.ShipNameIndicator != null) + { + string? shipNameIndicatorRawValue = AcctInfo.ShipNameIndicatorEnum.ToJsonValue(acctInfo._ShipNameIndicatorOption.Value!.Value); + writer.WriteString("shipNameIndicator", shipNameIndicatorRawValue); + } + + if (acctInfo._SuspiciousAccActivityOption.IsSet && acctInfo.SuspiciousAccActivity != null) + { + string? suspiciousAccActivityRawValue = AcctInfo.SuspiciousAccActivityEnum.ToJsonValue(acctInfo._SuspiciousAccActivityOption.Value!.Value); + writer.WriteString("suspiciousAccActivity", suspiciousAccActivityRawValue); + } + + if (acctInfo._TxnActivityDayOption.IsSet) + if (acctInfo.TxnActivityDay != null) + writer.WriteString("txnActivityDay", acctInfo.TxnActivityDay); + + if (acctInfo._TxnActivityYearOption.IsSet) + if (acctInfo.TxnActivityYear != null) + writer.WriteString("txnActivityYear", acctInfo.TxnActivityYear); + } + } +} diff --git a/Adyen/Checkout/Models/AchDetails.cs b/Adyen/Checkout/Models/AchDetails.cs new file mode 100644 index 000000000..54508e93a --- /dev/null +++ b/Adyen/Checkout/Models/AchDetails.cs @@ -0,0 +1,822 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AchDetails. + /// + public partial class AchDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The account holder type (personal or business). + /// The bank account number (without separators). + /// The bank account type (checking, savings...). + /// The bank routing number of the account. The field value is `nil` in most cases. + /// The checkout attempt identifier. + /// Encrypted bank account number. The bank account number (without separators). + /// Encrypted location id. The bank routing number of the account. The field value is `nil` in most cases. + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// **ach** (default to TypeEnum.Ach) + [JsonConstructor] + public AchDetails(Option accountHolderType = default, Option bankAccountNumber = default, Option bankAccountType = default, Option bankLocationId = default, Option checkoutAttemptId = default, Option encryptedBankAccountNumber = default, Option encryptedBankLocationId = default, Option ownerName = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option transferInstrumentId = default, Option type = default) + { + _AccountHolderTypeOption = accountHolderType; + _BankAccountNumberOption = bankAccountNumber; + _BankAccountTypeOption = bankAccountType; + _BankLocationIdOption = bankLocationId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _EncryptedBankAccountNumberOption = encryptedBankAccountNumber; + _EncryptedBankLocationIdOption = encryptedBankLocationId; + _OwnerNameOption = ownerName; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TransferInstrumentIdOption = transferInstrumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AchDetails() + { + } + + partial void OnCreated(); + + /// + /// The account holder type (personal or business). + /// + /// The account holder type (personal or business). + [JsonConverter(typeof(AccountHolderTypeEnumJsonConverter))] + public class AccountHolderTypeEnum : IEnum + { + /// + /// Returns the value of the AccountHolderTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountHolderTypeEnum.Business - business + /// + public static readonly AccountHolderTypeEnum Business = new("business"); + + /// + /// AccountHolderTypeEnum.Personal - personal + /// + public static readonly AccountHolderTypeEnum Personal = new("personal"); + + private AccountHolderTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountHolderTypeEnum?(string? value) => value == null ? null : new AccountHolderTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountHolderTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountHolderTypeEnum? left, AccountHolderTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountHolderTypeEnum? left, AccountHolderTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountHolderTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountHolderTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "business" => AccountHolderTypeEnum.Business, + "personal" => AccountHolderTypeEnum.Personal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountHolderTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountHolderTypeEnum.Business) + return "business"; + + if (value == AccountHolderTypeEnum.Personal) + return "personal"; + + return null; + } + + /// + /// JsonConverter for writing AccountHolderTypeEnum. + /// + public class AccountHolderTypeEnumJsonConverter : JsonConverter + { + public override AccountHolderTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountHolderTypeEnum.FromStringOrDefault(value) ?? new AccountHolderTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountHolderTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountHolderTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderTypeOption { get; private set; } + + /// + /// The account holder type (personal or business). + /// + /// The account holder type (personal or business). + [JsonPropertyName("accountHolderType")] + public AccountHolderTypeEnum? AccountHolderType { get { return this._AccountHolderTypeOption; } set { this._AccountHolderTypeOption = new(value); } } + + /// + /// The bank account type (checking, savings...). + /// + /// The bank account type (checking, savings...). + [JsonConverter(typeof(BankAccountTypeEnumJsonConverter))] + public class BankAccountTypeEnum : IEnum + { + /// + /// Returns the value of the BankAccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// BankAccountTypeEnum.Balance - balance + /// + public static readonly BankAccountTypeEnum Balance = new("balance"); + + /// + /// BankAccountTypeEnum.Checking - checking + /// + public static readonly BankAccountTypeEnum Checking = new("checking"); + + /// + /// BankAccountTypeEnum.Deposit - deposit + /// + public static readonly BankAccountTypeEnum Deposit = new("deposit"); + + /// + /// BankAccountTypeEnum.General - general + /// + public static readonly BankAccountTypeEnum General = new("general"); + + /// + /// BankAccountTypeEnum.Other - other + /// + public static readonly BankAccountTypeEnum Other = new("other"); + + /// + /// BankAccountTypeEnum.Payment - payment + /// + public static readonly BankAccountTypeEnum Payment = new("payment"); + + /// + /// BankAccountTypeEnum.Savings - savings + /// + public static readonly BankAccountTypeEnum Savings = new("savings"); + + private BankAccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BankAccountTypeEnum?(string? value) => value == null ? null : new BankAccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BankAccountTypeEnum? option) => option?.Value; + + public static bool operator ==(BankAccountTypeEnum? left, BankAccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BankAccountTypeEnum? left, BankAccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BankAccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BankAccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balance" => BankAccountTypeEnum.Balance, + "checking" => BankAccountTypeEnum.Checking, + "deposit" => BankAccountTypeEnum.Deposit, + "general" => BankAccountTypeEnum.General, + "other" => BankAccountTypeEnum.Other, + "payment" => BankAccountTypeEnum.Payment, + "savings" => BankAccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BankAccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == BankAccountTypeEnum.Balance) + return "balance"; + + if (value == BankAccountTypeEnum.Checking) + return "checking"; + + if (value == BankAccountTypeEnum.Deposit) + return "deposit"; + + if (value == BankAccountTypeEnum.General) + return "general"; + + if (value == BankAccountTypeEnum.Other) + return "other"; + + if (value == BankAccountTypeEnum.Payment) + return "payment"; + + if (value == BankAccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing BankAccountTypeEnum. + /// + public class BankAccountTypeEnumJsonConverter : JsonConverter + { + public override BankAccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BankAccountTypeEnum.FromStringOrDefault(value) ?? new BankAccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BankAccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BankAccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountTypeOption { get; private set; } + + /// + /// The bank account type (checking, savings...). + /// + /// The bank account type (checking, savings...). + [JsonPropertyName("bankAccountType")] + public BankAccountTypeEnum? BankAccountType { get { return this._BankAccountTypeOption; } set { this._BankAccountTypeOption = new(value); } } + + /// + /// **ach** + /// + /// **ach** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ach - ach + /// + public static readonly TypeEnum Ach = new("ach"); + + /// + /// TypeEnum.AchPlaid - ach_plaid + /// + public static readonly TypeEnum AchPlaid = new("ach_plaid"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ach" => TypeEnum.Ach, + "ach_plaid" => TypeEnum.AchPlaid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ach) + return "ach"; + + if (value == TypeEnum.AchPlaid) + return "ach_plaid"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **ach** + /// + /// **ach** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The bank routing number of the account. The field value is `nil` in most cases. + /// + /// The bank routing number of the account. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedBankAccountNumberOption { get; private set; } + + /// + /// Encrypted bank account number. The bank account number (without separators). + /// + /// Encrypted bank account number. The bank account number (without separators). + [JsonPropertyName("encryptedBankAccountNumber")] + public string? EncryptedBankAccountNumber { get { return this._EncryptedBankAccountNumberOption; } set { this._EncryptedBankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedBankLocationIdOption { get; private set; } + + /// + /// Encrypted location id. The bank routing number of the account. The field value is `nil` in most cases. + /// + /// Encrypted location id. The bank routing number of the account. The field value is `nil` in most cases. + [JsonPropertyName("encryptedBankLocationId")] + public string? EncryptedBankLocationId { get { return this._EncryptedBankLocationIdOption; } set { this._EncryptedBankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AchDetails {\n"); + sb.Append(" AccountHolderType: ").Append(AccountHolderType).Append("\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankAccountType: ").Append(BankAccountType).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" EncryptedBankAccountNumber: ").Append(EncryptedBankAccountNumber).Append("\n"); + sb.Append(" EncryptedBankLocationId: ").Append(EncryptedBankLocationId).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AchDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AchDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderType = default; + Option bankAccountNumber = default; + Option bankAccountType = default; + Option bankLocationId = default; + Option checkoutAttemptId = default; + Option encryptedBankAccountNumber = default; + Option encryptedBankLocationId = default; + Option ownerName = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option transferInstrumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderType": + string? accountHolderTypeRawValue = utf8JsonReader.GetString(); + accountHolderType = new Option(AchDetails.AccountHolderTypeEnum.FromStringOrDefault(accountHolderTypeRawValue)); + break; + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccountType": + string? bankAccountTypeRawValue = utf8JsonReader.GetString(); + bankAccountType = new Option(AchDetails.BankAccountTypeEnum.FromStringOrDefault(bankAccountTypeRawValue)); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedBankAccountNumber": + encryptedBankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedBankLocationId": + encryptedBankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AchDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AchDetails(accountHolderType, bankAccountNumber, bankAccountType, bankLocationId, checkoutAttemptId, encryptedBankAccountNumber, encryptedBankLocationId, ownerName, recurringDetailReference, storedPaymentMethodId, transferInstrumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AchDetails achDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, achDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AchDetails achDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (achDetails._AccountHolderTypeOption.IsSet && achDetails.AccountHolderType != null) + { + string? accountHolderTypeRawValue = AchDetails.AccountHolderTypeEnum.ToJsonValue(achDetails._AccountHolderTypeOption.Value!.Value); + writer.WriteString("accountHolderType", accountHolderTypeRawValue); + } + + if (achDetails._BankAccountNumberOption.IsSet) + if (achDetails.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", achDetails.BankAccountNumber); + + if (achDetails._BankAccountTypeOption.IsSet && achDetails.BankAccountType != null) + { + string? bankAccountTypeRawValue = AchDetails.BankAccountTypeEnum.ToJsonValue(achDetails._BankAccountTypeOption.Value!.Value); + writer.WriteString("bankAccountType", bankAccountTypeRawValue); + } + + if (achDetails._BankLocationIdOption.IsSet) + if (achDetails.BankLocationId != null) + writer.WriteString("bankLocationId", achDetails.BankLocationId); + + if (achDetails._CheckoutAttemptIdOption.IsSet) + if (achDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", achDetails.CheckoutAttemptId); + + if (achDetails._EncryptedBankAccountNumberOption.IsSet) + if (achDetails.EncryptedBankAccountNumber != null) + writer.WriteString("encryptedBankAccountNumber", achDetails.EncryptedBankAccountNumber); + + if (achDetails._EncryptedBankLocationIdOption.IsSet) + if (achDetails.EncryptedBankLocationId != null) + writer.WriteString("encryptedBankLocationId", achDetails.EncryptedBankLocationId); + + if (achDetails._OwnerNameOption.IsSet) + if (achDetails.OwnerName != null) + writer.WriteString("ownerName", achDetails.OwnerName); + + if (achDetails._RecurringDetailReferenceOption.IsSet) + if (achDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", achDetails.RecurringDetailReference); + + if (achDetails._StoredPaymentMethodIdOption.IsSet) + if (achDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", achDetails.StoredPaymentMethodId); + + if (achDetails._TransferInstrumentIdOption.IsSet) + if (achDetails.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", achDetails.TransferInstrumentId); + + if (achDetails._TypeOption.IsSet && achDetails.Type != null) + { + string? typeRawValue = AchDetails.TypeEnum.ToJsonValue(achDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalData3DSecure.cs b/Adyen/Checkout/Models/AdditionalData3DSecure.cs new file mode 100644 index 000000000..646f1cd0c --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalData3DSecure.cs @@ -0,0 +1,437 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalData3DSecure. + /// + public partial class AdditionalData3DSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + [JsonConstructor] + public AdditionalData3DSecure(Option allow3DS2 = default, Option challengeWindowSize = default, Option executeThreeD = default, Option mpiImplementationType = default, Option scaExemption = default, Option threeDSVersion = default) + { + _Allow3DS2Option = allow3DS2; + _ChallengeWindowSizeOption = challengeWindowSize; + _ExecuteThreeDOption = executeThreeD; + _MpiImplementationTypeOption = mpiImplementationType; + _ScaExemptionOption = scaExemption; + _ThreeDSVersionOption = threeDSVersion; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalData3DSecure() + { + } + + partial void OnCreated(); + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonConverter(typeof(ChallengeWindowSizeEnumJsonConverter))] + public class ChallengeWindowSizeEnum : IEnum + { + /// + /// Returns the value of the ChallengeWindowSizeEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeWindowSizeEnum._01 - 01 + /// + public static readonly ChallengeWindowSizeEnum _01 = new("01"); + + /// + /// ChallengeWindowSizeEnum._02 - 02 + /// + public static readonly ChallengeWindowSizeEnum _02 = new("02"); + + /// + /// ChallengeWindowSizeEnum._03 - 03 + /// + public static readonly ChallengeWindowSizeEnum _03 = new("03"); + + /// + /// ChallengeWindowSizeEnum._04 - 04 + /// + public static readonly ChallengeWindowSizeEnum _04 = new("04"); + + /// + /// ChallengeWindowSizeEnum._05 - 05 + /// + public static readonly ChallengeWindowSizeEnum _05 = new("05"); + + private ChallengeWindowSizeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeWindowSizeEnum?(string? value) => value == null ? null : new ChallengeWindowSizeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeWindowSizeEnum? option) => option?.Value; + + public static bool operator ==(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeWindowSizeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeWindowSizeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeWindowSizeEnum._01, + "02" => ChallengeWindowSizeEnum._02, + "03" => ChallengeWindowSizeEnum._03, + "04" => ChallengeWindowSizeEnum._04, + "05" => ChallengeWindowSizeEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeWindowSizeEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeWindowSizeEnum._01) + return "01"; + + if (value == ChallengeWindowSizeEnum._02) + return "02"; + + if (value == ChallengeWindowSizeEnum._03) + return "03"; + + if (value == ChallengeWindowSizeEnum._04) + return "04"; + + if (value == ChallengeWindowSizeEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeWindowSizeEnum. + /// + public class ChallengeWindowSizeEnumJsonConverter : JsonConverter + { + public override ChallengeWindowSizeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeWindowSizeEnum.FromStringOrDefault(value) ?? new ChallengeWindowSizeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeWindowSizeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeWindowSizeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeWindowSizeOption { get; private set; } + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonPropertyName("challengeWindowSize")] + public ChallengeWindowSizeEnum? ChallengeWindowSize { get { return this._ChallengeWindowSizeOption; } set { this._ChallengeWindowSizeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Allow3DS2Option { get; private set; } + + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + [JsonPropertyName("allow3DS2")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.threeDSRequestData.nativeThreeDS` instead.")] + public string? Allow3DS2 { get { return this._Allow3DS2Option; } set { this._Allow3DS2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecuteThreeDOption { get; private set; } + + /// + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + /// + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + [JsonPropertyName("executeThreeD")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use [`authenticationData.attemptAuthentication`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments?target=_blank#request-authenticationData-attemptAuthentication) instead")] + public string? ExecuteThreeD { get { return this._ExecuteThreeDOption; } set { this._ExecuteThreeDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiImplementationTypeOption { get; private set; } + + /// + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + /// + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + [JsonPropertyName("mpiImplementationType")] + public string? MpiImplementationType { get { return this._MpiImplementationTypeOption; } set { this._MpiImplementationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaExemptionOption { get; private set; } + + /// + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + [JsonPropertyName("scaExemption")] + public string? ScaExemption { get { return this._ScaExemptionOption; } set { this._ScaExemptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + /// + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalData3DSecure {\n"); + sb.Append(" Allow3DS2: ").Append(Allow3DS2).Append("\n"); + sb.Append(" ChallengeWindowSize: ").Append(ChallengeWindowSize).Append("\n"); + sb.Append(" ExecuteThreeD: ").Append(ExecuteThreeD).Append("\n"); + sb.Append(" MpiImplementationType: ").Append(MpiImplementationType).Append("\n"); + sb.Append(" ScaExemption: ").Append(ScaExemption).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalData3DSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalData3DSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allow3DS2 = default; + Option challengeWindowSize = default; + Option executeThreeD = default; + Option mpiImplementationType = default; + Option scaExemption = default; + Option threeDSVersion = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allow3DS2": + allow3DS2 = new Option(utf8JsonReader.GetString()!); + break; + case "challengeWindowSize": + string? challengeWindowSizeRawValue = utf8JsonReader.GetString(); + challengeWindowSize = new Option(AdditionalData3DSecure.ChallengeWindowSizeEnum.FromStringOrDefault(challengeWindowSizeRawValue)); + break; + case "executeThreeD": + executeThreeD = new Option(utf8JsonReader.GetString()!); + break; + case "mpiImplementationType": + mpiImplementationType = new Option(utf8JsonReader.GetString()!); + break; + case "scaExemption": + scaExemption = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalData3DSecure(allow3DS2, challengeWindowSize, executeThreeD, mpiImplementationType, scaExemption, threeDSVersion); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalData3DSecure additionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalData3DSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalData3DSecure additionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalData3DSecure._Allow3DS2Option.IsSet) + if (additionalData3DSecure.Allow3DS2 != null) + writer.WriteString("allow3DS2", additionalData3DSecure.Allow3DS2); + + if (additionalData3DSecure._ChallengeWindowSizeOption.IsSet && additionalData3DSecure.ChallengeWindowSize != null) + { + string? challengeWindowSizeRawValue = AdditionalData3DSecure.ChallengeWindowSizeEnum.ToJsonValue(additionalData3DSecure._ChallengeWindowSizeOption.Value!.Value); + writer.WriteString("challengeWindowSize", challengeWindowSizeRawValue); + } + + if (additionalData3DSecure._ExecuteThreeDOption.IsSet) + if (additionalData3DSecure.ExecuteThreeD != null) + writer.WriteString("executeThreeD", additionalData3DSecure.ExecuteThreeD); + + if (additionalData3DSecure._MpiImplementationTypeOption.IsSet) + if (additionalData3DSecure.MpiImplementationType != null) + writer.WriteString("mpiImplementationType", additionalData3DSecure.MpiImplementationType); + + if (additionalData3DSecure._ScaExemptionOption.IsSet) + if (additionalData3DSecure.ScaExemption != null) + writer.WriteString("scaExemption", additionalData3DSecure.ScaExemption); + + if (additionalData3DSecure._ThreeDSVersionOption.IsSet) + if (additionalData3DSecure.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", additionalData3DSecure.ThreeDSVersion); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataAirline.cs b/Adyen/Checkout/Models/AdditionalDataAirline.cs new file mode 100644 index 000000000..83daf58f0 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataAirline.cs @@ -0,0 +1,871 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataAirline. + /// + public partial class AdditionalDataAirline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + [JsonConstructor] + public AdditionalDataAirline(string airlinePassengerName, Option airlineAgencyInvoiceNumber = default, Option airlineAgencyPlanName = default, Option airlineAirlineCode = default, Option airlineAirlineDesignatorCode = default, Option airlineBoardingFee = default, Option airlineComputerizedReservationSystem = default, Option airlineCustomerReferenceNumber = default, Option airlineDocumentType = default, Option airlineFlightDate = default, Option airlineIssueDate = default, Option airlineLegCarrierCode = default, Option airlineLegClassOfTravel = default, Option airlineLegDateOfTravel = default, Option airlineLegDepartAirport = default, Option airlineLegDepartTax = default, Option airlineLegDestinationCode = default, Option airlineLegFareBaseCode = default, Option airlineLegFlightNumber = default, Option airlineLegStopOverCode = default, Option airlinePassengerDateOfBirth = default, Option airlinePassengerFirstName = default, Option airlinePassengerLastName = default, Option airlinePassengerPhoneNumber = default, Option airlinePassengerTravellerType = default, Option airlineTicketIssueAddress = default, Option airlineTicketNumber = default, Option airlineTravelAgencyCode = default, Option airlineTravelAgencyName = default) + { + AirlinePassengerName = airlinePassengerName; + _AirlineAgencyInvoiceNumberOption = airlineAgencyInvoiceNumber; + _AirlineAgencyPlanNameOption = airlineAgencyPlanName; + _AirlineAirlineCodeOption = airlineAirlineCode; + _AirlineAirlineDesignatorCodeOption = airlineAirlineDesignatorCode; + _AirlineBoardingFeeOption = airlineBoardingFee; + _AirlineComputerizedReservationSystemOption = airlineComputerizedReservationSystem; + _AirlineCustomerReferenceNumberOption = airlineCustomerReferenceNumber; + _AirlineDocumentTypeOption = airlineDocumentType; + _AirlineFlightDateOption = airlineFlightDate; + _AirlineIssueDateOption = airlineIssueDate; + _AirlineLegCarrierCodeOption = airlineLegCarrierCode; + _AirlineLegClassOfTravelOption = airlineLegClassOfTravel; + _AirlineLegDateOfTravelOption = airlineLegDateOfTravel; + _AirlineLegDepartAirportOption = airlineLegDepartAirport; + _AirlineLegDepartTaxOption = airlineLegDepartTax; + _AirlineLegDestinationCodeOption = airlineLegDestinationCode; + _AirlineLegFareBaseCodeOption = airlineLegFareBaseCode; + _AirlineLegFlightNumberOption = airlineLegFlightNumber; + _AirlineLegStopOverCodeOption = airlineLegStopOverCode; + _AirlinePassengerDateOfBirthOption = airlinePassengerDateOfBirth; + _AirlinePassengerFirstNameOption = airlinePassengerFirstName; + _AirlinePassengerLastNameOption = airlinePassengerLastName; + _AirlinePassengerPhoneNumberOption = airlinePassengerPhoneNumber; + _AirlinePassengerTravellerTypeOption = airlinePassengerTravellerType; + _AirlineTicketIssueAddressOption = airlineTicketIssueAddress; + _AirlineTicketNumberOption = airlineTicketNumber; + _AirlineTravelAgencyCodeOption = airlineTravelAgencyCode; + _AirlineTravelAgencyNameOption = airlineTravelAgencyName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataAirline() + { + } + + partial void OnCreated(); + + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.passenger_name")] + public string AirlinePassengerName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAgencyInvoiceNumberOption { get; private set; } + + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + [JsonPropertyName("airline.agency_invoice_number")] + public string? AirlineAgencyInvoiceNumber { get { return this._AirlineAgencyInvoiceNumberOption; } set { this._AirlineAgencyInvoiceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAgencyPlanNameOption { get; private set; } + + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("airline.agency_plan_name")] + public string? AirlineAgencyPlanName { get { return this._AirlineAgencyPlanNameOption; } set { this._AirlineAgencyPlanNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAirlineCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.airline_code")] + public string? AirlineAirlineCode { get { return this._AirlineAirlineCodeOption; } set { this._AirlineAirlineCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAirlineDesignatorCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.airline_designator_code")] + public string? AirlineAirlineDesignatorCode { get { return this._AirlineAirlineDesignatorCodeOption; } set { this._AirlineAirlineDesignatorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineBoardingFeeOption { get; private set; } + + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + [JsonPropertyName("airline.boarding_fee")] + public string? AirlineBoardingFee { get { return this._AirlineBoardingFeeOption; } set { this._AirlineBoardingFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineComputerizedReservationSystemOption { get; private set; } + + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + [JsonPropertyName("airline.computerized_reservation_system")] + public string? AirlineComputerizedReservationSystem { get { return this._AirlineComputerizedReservationSystemOption; } set { this._AirlineComputerizedReservationSystemOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineCustomerReferenceNumberOption { get; private set; } + + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + [JsonPropertyName("airline.customer_reference_number")] + public string? AirlineCustomerReferenceNumber { get { return this._AirlineCustomerReferenceNumberOption; } set { this._AirlineCustomerReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineDocumentTypeOption { get; private set; } + + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("airline.document_type")] + public string? AirlineDocumentType { get { return this._AirlineDocumentTypeOption; } set { this._AirlineDocumentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineFlightDateOption { get; private set; } + + /// + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + /// + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + [JsonPropertyName("airline.flight_date")] + public string? AirlineFlightDate { get { return this._AirlineFlightDateOption; } set { this._AirlineFlightDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineIssueDateOption { get; private set; } + + /// + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + /// + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + [JsonPropertyName("airline.issue_date")] + public string? AirlineIssueDate { get { return this._AirlineIssueDateOption; } set { this._AirlineIssueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegCarrierCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.carrier_code")] + public string? AirlineLegCarrierCode { get { return this._AirlineLegCarrierCodeOption; } set { this._AirlineLegCarrierCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegClassOfTravelOption { get; private set; } + + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.class_of_travel")] + public string? AirlineLegClassOfTravel { get { return this._AirlineLegClassOfTravelOption; } set { this._AirlineLegClassOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDateOfTravelOption { get; private set; } + + /// + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + /// + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + [JsonPropertyName("airline.leg.date_of_travel")] + public string? AirlineLegDateOfTravel { get { return this._AirlineLegDateOfTravelOption; } set { this._AirlineLegDateOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDepartAirportOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.depart_airport")] + public string? AirlineLegDepartAirport { get { return this._AirlineLegDepartAirportOption; } set { this._AirlineLegDepartAirportOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDepartTaxOption { get; private set; } + + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + [JsonPropertyName("airline.leg.depart_tax")] + public string? AirlineLegDepartTax { get { return this._AirlineLegDepartTaxOption; } set { this._AirlineLegDepartTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDestinationCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.destination_code")] + public string? AirlineLegDestinationCode { get { return this._AirlineLegDestinationCodeOption; } set { this._AirlineLegDestinationCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegFareBaseCodeOption { get; private set; } + + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.fare_base_code")] + public string? AirlineLegFareBaseCode { get { return this._AirlineLegFareBaseCodeOption; } set { this._AirlineLegFareBaseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegFlightNumberOption { get; private set; } + + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.flight_number")] + public string? AirlineLegFlightNumber { get { return this._AirlineLegFlightNumberOption; } set { this._AirlineLegFlightNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegStopOverCodeOption { get; private set; } + + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + [JsonPropertyName("airline.leg.stop_over_code")] + public string? AirlineLegStopOverCode { get { return this._AirlineLegStopOverCodeOption; } set { this._AirlineLegStopOverCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerDateOfBirthOption { get; private set; } + + /// + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + [JsonPropertyName("airline.passenger.date_of_birth")] + public string? AirlinePassengerDateOfBirth { get { return this._AirlinePassengerDateOfBirthOption; } set { this._AirlinePassengerDateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerFirstNameOption { get; private set; } + + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("airline.passenger.first_name")] + public string? AirlinePassengerFirstName { get { return this._AirlinePassengerFirstNameOption; } set { this._AirlinePassengerFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerLastNameOption { get; private set; } + + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("airline.passenger.last_name")] + public string? AirlinePassengerLastName { get { return this._AirlinePassengerLastNameOption; } set { this._AirlinePassengerLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerPhoneNumberOption { get; private set; } + + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + [JsonPropertyName("airline.passenger.phone_number")] + public string? AirlinePassengerPhoneNumber { get { return this._AirlinePassengerPhoneNumberOption; } set { this._AirlinePassengerPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerTravellerTypeOption { get; private set; } + + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + [JsonPropertyName("airline.passenger.traveller_type")] + public string? AirlinePassengerTravellerType { get { return this._AirlinePassengerTravellerTypeOption; } set { this._AirlinePassengerTravellerTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTicketIssueAddressOption { get; private set; } + + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + [JsonPropertyName("airline.ticket_issue_address")] + public string? AirlineTicketIssueAddress { get { return this._AirlineTicketIssueAddressOption; } set { this._AirlineTicketIssueAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTicketNumberOption { get; private set; } + + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.ticket_number")] + public string? AirlineTicketNumber { get { return this._AirlineTicketNumberOption; } set { this._AirlineTicketNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTravelAgencyCodeOption { get; private set; } + + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.travel_agency_code")] + public string? AirlineTravelAgencyCode { get { return this._AirlineTravelAgencyCodeOption; } set { this._AirlineTravelAgencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTravelAgencyNameOption { get; private set; } + + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.travel_agency_name")] + public string? AirlineTravelAgencyName { get { return this._AirlineTravelAgencyNameOption; } set { this._AirlineTravelAgencyNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataAirline {\n"); + sb.Append(" AirlinePassengerName: ").Append(AirlinePassengerName).Append("\n"); + sb.Append(" AirlineAgencyInvoiceNumber: ").Append(AirlineAgencyInvoiceNumber).Append("\n"); + sb.Append(" AirlineAgencyPlanName: ").Append(AirlineAgencyPlanName).Append("\n"); + sb.Append(" AirlineAirlineCode: ").Append(AirlineAirlineCode).Append("\n"); + sb.Append(" AirlineAirlineDesignatorCode: ").Append(AirlineAirlineDesignatorCode).Append("\n"); + sb.Append(" AirlineBoardingFee: ").Append(AirlineBoardingFee).Append("\n"); + sb.Append(" AirlineComputerizedReservationSystem: ").Append(AirlineComputerizedReservationSystem).Append("\n"); + sb.Append(" AirlineCustomerReferenceNumber: ").Append(AirlineCustomerReferenceNumber).Append("\n"); + sb.Append(" AirlineDocumentType: ").Append(AirlineDocumentType).Append("\n"); + sb.Append(" AirlineFlightDate: ").Append(AirlineFlightDate).Append("\n"); + sb.Append(" AirlineIssueDate: ").Append(AirlineIssueDate).Append("\n"); + sb.Append(" AirlineLegCarrierCode: ").Append(AirlineLegCarrierCode).Append("\n"); + sb.Append(" AirlineLegClassOfTravel: ").Append(AirlineLegClassOfTravel).Append("\n"); + sb.Append(" AirlineLegDateOfTravel: ").Append(AirlineLegDateOfTravel).Append("\n"); + sb.Append(" AirlineLegDepartAirport: ").Append(AirlineLegDepartAirport).Append("\n"); + sb.Append(" AirlineLegDepartTax: ").Append(AirlineLegDepartTax).Append("\n"); + sb.Append(" AirlineLegDestinationCode: ").Append(AirlineLegDestinationCode).Append("\n"); + sb.Append(" AirlineLegFareBaseCode: ").Append(AirlineLegFareBaseCode).Append("\n"); + sb.Append(" AirlineLegFlightNumber: ").Append(AirlineLegFlightNumber).Append("\n"); + sb.Append(" AirlineLegStopOverCode: ").Append(AirlineLegStopOverCode).Append("\n"); + sb.Append(" AirlinePassengerDateOfBirth: ").Append(AirlinePassengerDateOfBirth).Append("\n"); + sb.Append(" AirlinePassengerFirstName: ").Append(AirlinePassengerFirstName).Append("\n"); + sb.Append(" AirlinePassengerLastName: ").Append(AirlinePassengerLastName).Append("\n"); + sb.Append(" AirlinePassengerPhoneNumber: ").Append(AirlinePassengerPhoneNumber).Append("\n"); + sb.Append(" AirlinePassengerTravellerType: ").Append(AirlinePassengerTravellerType).Append("\n"); + sb.Append(" AirlineTicketIssueAddress: ").Append(AirlineTicketIssueAddress).Append("\n"); + sb.Append(" AirlineTicketNumber: ").Append(AirlineTicketNumber).Append("\n"); + sb.Append(" AirlineTravelAgencyCode: ").Append(AirlineTravelAgencyCode).Append("\n"); + sb.Append(" AirlineTravelAgencyName: ").Append(AirlineTravelAgencyName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataAirlineJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataAirline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option airlinePassengerName = default; + Option airlineAgencyInvoiceNumber = default; + Option airlineAgencyPlanName = default; + Option airlineAirlineCode = default; + Option airlineAirlineDesignatorCode = default; + Option airlineBoardingFee = default; + Option airlineComputerizedReservationSystem = default; + Option airlineCustomerReferenceNumber = default; + Option airlineDocumentType = default; + Option airlineFlightDate = default; + Option airlineIssueDate = default; + Option airlineLegCarrierCode = default; + Option airlineLegClassOfTravel = default; + Option airlineLegDateOfTravel = default; + Option airlineLegDepartAirport = default; + Option airlineLegDepartTax = default; + Option airlineLegDestinationCode = default; + Option airlineLegFareBaseCode = default; + Option airlineLegFlightNumber = default; + Option airlineLegStopOverCode = default; + Option airlinePassengerDateOfBirth = default; + Option airlinePassengerFirstName = default; + Option airlinePassengerLastName = default; + Option airlinePassengerPhoneNumber = default; + Option airlinePassengerTravellerType = default; + Option airlineTicketIssueAddress = default; + Option airlineTicketNumber = default; + Option airlineTravelAgencyCode = default; + Option airlineTravelAgencyName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "airline.passenger_name": + airlinePassengerName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.agency_invoice_number": + airlineAgencyInvoiceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.agency_plan_name": + airlineAgencyPlanName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.airline_code": + airlineAirlineCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.airline_designator_code": + airlineAirlineDesignatorCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.boarding_fee": + airlineBoardingFee = new Option(utf8JsonReader.GetString()!); + break; + case "airline.computerized_reservation_system": + airlineComputerizedReservationSystem = new Option(utf8JsonReader.GetString()!); + break; + case "airline.customer_reference_number": + airlineCustomerReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.document_type": + airlineDocumentType = new Option(utf8JsonReader.GetString()!); + break; + case "airline.flight_date": + airlineFlightDate = new Option(utf8JsonReader.GetString()!); + break; + case "airline.issue_date": + airlineIssueDate = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.carrier_code": + airlineLegCarrierCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.class_of_travel": + airlineLegClassOfTravel = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.date_of_travel": + airlineLegDateOfTravel = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.depart_airport": + airlineLegDepartAirport = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.depart_tax": + airlineLegDepartTax = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.destination_code": + airlineLegDestinationCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.fare_base_code": + airlineLegFareBaseCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.flight_number": + airlineLegFlightNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.stop_over_code": + airlineLegStopOverCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.date_of_birth": + airlinePassengerDateOfBirth = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.first_name": + airlinePassengerFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.last_name": + airlinePassengerLastName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.phone_number": + airlinePassengerPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.traveller_type": + airlinePassengerTravellerType = new Option(utf8JsonReader.GetString()!); + break; + case "airline.ticket_issue_address": + airlineTicketIssueAddress = new Option(utf8JsonReader.GetString()!); + break; + case "airline.ticket_number": + airlineTicketNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.travel_agency_code": + airlineTravelAgencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.travel_agency_name": + airlineTravelAgencyName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!airlinePassengerName.IsSet) + throw new ArgumentException("Property is required for class AdditionalDataAirline.", nameof(airlinePassengerName)); + + return new AdditionalDataAirline(airlinePassengerName.Value!, airlineAgencyInvoiceNumber, airlineAgencyPlanName, airlineAirlineCode, airlineAirlineDesignatorCode, airlineBoardingFee, airlineComputerizedReservationSystem, airlineCustomerReferenceNumber, airlineDocumentType, airlineFlightDate, airlineIssueDate, airlineLegCarrierCode, airlineLegClassOfTravel, airlineLegDateOfTravel, airlineLegDepartAirport, airlineLegDepartTax, airlineLegDestinationCode, airlineLegFareBaseCode, airlineLegFlightNumber, airlineLegStopOverCode, airlinePassengerDateOfBirth, airlinePassengerFirstName, airlinePassengerLastName, airlinePassengerPhoneNumber, airlinePassengerTravellerType, airlineTicketIssueAddress, airlineTicketNumber, airlineTravelAgencyCode, airlineTravelAgencyName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataAirline additionalDataAirline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataAirline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataAirline additionalDataAirline, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataAirline.AirlinePassengerName != null) + writer.WriteString("airline.passenger_name", additionalDataAirline.AirlinePassengerName); + + if (additionalDataAirline._AirlineAgencyInvoiceNumberOption.IsSet) + if (additionalDataAirline.AirlineAgencyInvoiceNumber != null) + writer.WriteString("airline.agency_invoice_number", additionalDataAirline.AirlineAgencyInvoiceNumber); + + if (additionalDataAirline._AirlineAgencyPlanNameOption.IsSet) + if (additionalDataAirline.AirlineAgencyPlanName != null) + writer.WriteString("airline.agency_plan_name", additionalDataAirline.AirlineAgencyPlanName); + + if (additionalDataAirline._AirlineAirlineCodeOption.IsSet) + if (additionalDataAirline.AirlineAirlineCode != null) + writer.WriteString("airline.airline_code", additionalDataAirline.AirlineAirlineCode); + + if (additionalDataAirline._AirlineAirlineDesignatorCodeOption.IsSet) + if (additionalDataAirline.AirlineAirlineDesignatorCode != null) + writer.WriteString("airline.airline_designator_code", additionalDataAirline.AirlineAirlineDesignatorCode); + + if (additionalDataAirline._AirlineBoardingFeeOption.IsSet) + if (additionalDataAirline.AirlineBoardingFee != null) + writer.WriteString("airline.boarding_fee", additionalDataAirline.AirlineBoardingFee); + + if (additionalDataAirline._AirlineComputerizedReservationSystemOption.IsSet) + if (additionalDataAirline.AirlineComputerizedReservationSystem != null) + writer.WriteString("airline.computerized_reservation_system", additionalDataAirline.AirlineComputerizedReservationSystem); + + if (additionalDataAirline._AirlineCustomerReferenceNumberOption.IsSet) + if (additionalDataAirline.AirlineCustomerReferenceNumber != null) + writer.WriteString("airline.customer_reference_number", additionalDataAirline.AirlineCustomerReferenceNumber); + + if (additionalDataAirline._AirlineDocumentTypeOption.IsSet) + if (additionalDataAirline.AirlineDocumentType != null) + writer.WriteString("airline.document_type", additionalDataAirline.AirlineDocumentType); + + if (additionalDataAirline._AirlineFlightDateOption.IsSet) + if (additionalDataAirline.AirlineFlightDate != null) + writer.WriteString("airline.flight_date", additionalDataAirline.AirlineFlightDate); + + if (additionalDataAirline._AirlineIssueDateOption.IsSet) + if (additionalDataAirline.AirlineIssueDate != null) + writer.WriteString("airline.issue_date", additionalDataAirline.AirlineIssueDate); + + if (additionalDataAirline._AirlineLegCarrierCodeOption.IsSet) + if (additionalDataAirline.AirlineLegCarrierCode != null) + writer.WriteString("airline.leg.carrier_code", additionalDataAirline.AirlineLegCarrierCode); + + if (additionalDataAirline._AirlineLegClassOfTravelOption.IsSet) + if (additionalDataAirline.AirlineLegClassOfTravel != null) + writer.WriteString("airline.leg.class_of_travel", additionalDataAirline.AirlineLegClassOfTravel); + + if (additionalDataAirline._AirlineLegDateOfTravelOption.IsSet) + if (additionalDataAirline.AirlineLegDateOfTravel != null) + writer.WriteString("airline.leg.date_of_travel", additionalDataAirline.AirlineLegDateOfTravel); + + if (additionalDataAirline._AirlineLegDepartAirportOption.IsSet) + if (additionalDataAirline.AirlineLegDepartAirport != null) + writer.WriteString("airline.leg.depart_airport", additionalDataAirline.AirlineLegDepartAirport); + + if (additionalDataAirline._AirlineLegDepartTaxOption.IsSet) + if (additionalDataAirline.AirlineLegDepartTax != null) + writer.WriteString("airline.leg.depart_tax", additionalDataAirline.AirlineLegDepartTax); + + if (additionalDataAirline._AirlineLegDestinationCodeOption.IsSet) + if (additionalDataAirline.AirlineLegDestinationCode != null) + writer.WriteString("airline.leg.destination_code", additionalDataAirline.AirlineLegDestinationCode); + + if (additionalDataAirline._AirlineLegFareBaseCodeOption.IsSet) + if (additionalDataAirline.AirlineLegFareBaseCode != null) + writer.WriteString("airline.leg.fare_base_code", additionalDataAirline.AirlineLegFareBaseCode); + + if (additionalDataAirline._AirlineLegFlightNumberOption.IsSet) + if (additionalDataAirline.AirlineLegFlightNumber != null) + writer.WriteString("airline.leg.flight_number", additionalDataAirline.AirlineLegFlightNumber); + + if (additionalDataAirline._AirlineLegStopOverCodeOption.IsSet) + if (additionalDataAirline.AirlineLegStopOverCode != null) + writer.WriteString("airline.leg.stop_over_code", additionalDataAirline.AirlineLegStopOverCode); + + if (additionalDataAirline._AirlinePassengerDateOfBirthOption.IsSet) + if (additionalDataAirline.AirlinePassengerDateOfBirth != null) + writer.WriteString("airline.passenger.date_of_birth", additionalDataAirline.AirlinePassengerDateOfBirth); + + if (additionalDataAirline._AirlinePassengerFirstNameOption.IsSet) + if (additionalDataAirline.AirlinePassengerFirstName != null) + writer.WriteString("airline.passenger.first_name", additionalDataAirline.AirlinePassengerFirstName); + + if (additionalDataAirline._AirlinePassengerLastNameOption.IsSet) + if (additionalDataAirline.AirlinePassengerLastName != null) + writer.WriteString("airline.passenger.last_name", additionalDataAirline.AirlinePassengerLastName); + + if (additionalDataAirline._AirlinePassengerPhoneNumberOption.IsSet) + if (additionalDataAirline.AirlinePassengerPhoneNumber != null) + writer.WriteString("airline.passenger.phone_number", additionalDataAirline.AirlinePassengerPhoneNumber); + + if (additionalDataAirline._AirlinePassengerTravellerTypeOption.IsSet) + if (additionalDataAirline.AirlinePassengerTravellerType != null) + writer.WriteString("airline.passenger.traveller_type", additionalDataAirline.AirlinePassengerTravellerType); + + if (additionalDataAirline._AirlineTicketIssueAddressOption.IsSet) + if (additionalDataAirline.AirlineTicketIssueAddress != null) + writer.WriteString("airline.ticket_issue_address", additionalDataAirline.AirlineTicketIssueAddress); + + if (additionalDataAirline._AirlineTicketNumberOption.IsSet) + if (additionalDataAirline.AirlineTicketNumber != null) + writer.WriteString("airline.ticket_number", additionalDataAirline.AirlineTicketNumber); + + if (additionalDataAirline._AirlineTravelAgencyCodeOption.IsSet) + if (additionalDataAirline.AirlineTravelAgencyCode != null) + writer.WriteString("airline.travel_agency_code", additionalDataAirline.AirlineTravelAgencyCode); + + if (additionalDataAirline._AirlineTravelAgencyNameOption.IsSet) + if (additionalDataAirline.AirlineTravelAgencyName != null) + writer.WriteString("airline.travel_agency_name", additionalDataAirline.AirlineTravelAgencyName); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataCarRental.cs b/Adyen/Checkout/Models/AdditionalDataCarRental.cs new file mode 100644 index 000000000..1dfa6ee12 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataCarRental.cs @@ -0,0 +1,727 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataCarRental. + /// + public partial class AdditionalDataCarRental : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The pick-up date. * Date format: `yyyyMMdd` + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + [JsonConstructor] + public AdditionalDataCarRental(Option carRentalCheckOutDate = default, Option carRentalCustomerServiceTollFreeNumber = default, Option carRentalDaysRented = default, Option carRentalFuelCharges = default, Option carRentalInsuranceCharges = default, Option carRentalLocationCity = default, Option carRentalLocationCountry = default, Option carRentalLocationStateProvince = default, Option carRentalNoShowIndicator = default, Option carRentalOneWayDropOffCharges = default, Option carRentalRate = default, Option carRentalRateIndicator = default, Option carRentalRentalAgreementNumber = default, Option carRentalRentalClassId = default, Option carRentalRenterName = default, Option carRentalReturnCity = default, Option carRentalReturnCountry = default, Option carRentalReturnDate = default, Option carRentalReturnLocationId = default, Option carRentalReturnStateProvince = default, Option carRentalTaxExemptIndicator = default, Option travelEntertainmentAuthDataDuration = default, Option travelEntertainmentAuthDataMarket = default) + { + _CarRentalCheckOutDateOption = carRentalCheckOutDate; + _CarRentalCustomerServiceTollFreeNumberOption = carRentalCustomerServiceTollFreeNumber; + _CarRentalDaysRentedOption = carRentalDaysRented; + _CarRentalFuelChargesOption = carRentalFuelCharges; + _CarRentalInsuranceChargesOption = carRentalInsuranceCharges; + _CarRentalLocationCityOption = carRentalLocationCity; + _CarRentalLocationCountryOption = carRentalLocationCountry; + _CarRentalLocationStateProvinceOption = carRentalLocationStateProvince; + _CarRentalNoShowIndicatorOption = carRentalNoShowIndicator; + _CarRentalOneWayDropOffChargesOption = carRentalOneWayDropOffCharges; + _CarRentalRateOption = carRentalRate; + _CarRentalRateIndicatorOption = carRentalRateIndicator; + _CarRentalRentalAgreementNumberOption = carRentalRentalAgreementNumber; + _CarRentalRentalClassIdOption = carRentalRentalClassId; + _CarRentalRenterNameOption = carRentalRenterName; + _CarRentalReturnCityOption = carRentalReturnCity; + _CarRentalReturnCountryOption = carRentalReturnCountry; + _CarRentalReturnDateOption = carRentalReturnDate; + _CarRentalReturnLocationIdOption = carRentalReturnLocationId; + _CarRentalReturnStateProvinceOption = carRentalReturnStateProvince; + _CarRentalTaxExemptIndicatorOption = carRentalTaxExemptIndicator; + _TravelEntertainmentAuthDataDurationOption = travelEntertainmentAuthDataDuration; + _TravelEntertainmentAuthDataMarketOption = travelEntertainmentAuthDataMarket; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataCarRental() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalCheckOutDateOption { get; private set; } + + /// + /// The pick-up date. * Date format: `yyyyMMdd` + /// + /// The pick-up date. * Date format: `yyyyMMdd` + [JsonPropertyName("carRental.checkOutDate")] + public string? CarRentalCheckOutDate { get { return this._CarRentalCheckOutDateOption; } set { this._CarRentalCheckOutDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalCustomerServiceTollFreeNumberOption { get; private set; } + + /// + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + /// + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + [JsonPropertyName("carRental.customerServiceTollFreeNumber")] + public string? CarRentalCustomerServiceTollFreeNumber { get { return this._CarRentalCustomerServiceTollFreeNumberOption; } set { this._CarRentalCustomerServiceTollFreeNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalDaysRentedOption { get; private set; } + + /// + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + /// + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + [JsonPropertyName("carRental.daysRented")] + public string? CarRentalDaysRented { get { return this._CarRentalDaysRentedOption; } set { this._CarRentalDaysRentedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalFuelChargesOption { get; private set; } + + /// + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + /// + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + [JsonPropertyName("carRental.fuelCharges")] + public string? CarRentalFuelCharges { get { return this._CarRentalFuelChargesOption; } set { this._CarRentalFuelChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalInsuranceChargesOption { get; private set; } + + /// + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + /// + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.insuranceCharges")] + public string? CarRentalInsuranceCharges { get { return this._CarRentalInsuranceChargesOption; } set { this._CarRentalInsuranceChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationCityOption { get; private set; } + + /// + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.locationCity")] + public string? CarRentalLocationCity { get { return this._CarRentalLocationCityOption; } set { this._CarRentalLocationCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationCountryOption { get; private set; } + + /// + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + [JsonPropertyName("carRental.locationCountry")] + public string? CarRentalLocationCountry { get { return this._CarRentalLocationCountryOption; } set { this._CarRentalLocationCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationStateProvinceOption { get; private set; } + + /// + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.locationStateProvince")] + public string? CarRentalLocationStateProvince { get { return this._CarRentalLocationStateProvinceOption; } set { this._CarRentalLocationStateProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalNoShowIndicatorOption { get; private set; } + + /// + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + /// + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + [JsonPropertyName("carRental.noShowIndicator")] + public string? CarRentalNoShowIndicator { get { return this._CarRentalNoShowIndicatorOption; } set { this._CarRentalNoShowIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalOneWayDropOffChargesOption { get; private set; } + + /// + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + /// + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + [JsonPropertyName("carRental.oneWayDropOffCharges")] + public string? CarRentalOneWayDropOffCharges { get { return this._CarRentalOneWayDropOffChargesOption; } set { this._CarRentalOneWayDropOffChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRateOption { get; private set; } + + /// + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + /// + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + [JsonPropertyName("carRental.rate")] + public string? CarRentalRate { get { return this._CarRentalRateOption; } set { this._CarRentalRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRateIndicatorOption { get; private set; } + + /// + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + /// + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + [JsonPropertyName("carRental.rateIndicator")] + public string? CarRentalRateIndicator { get { return this._CarRentalRateIndicatorOption; } set { this._CarRentalRateIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRentalAgreementNumberOption { get; private set; } + + /// + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.rentalAgreementNumber")] + public string? CarRentalRentalAgreementNumber { get { return this._CarRentalRentalAgreementNumberOption; } set { this._CarRentalRentalAgreementNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRentalClassIdOption { get; private set; } + + /// + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.rentalClassId")] + public string? CarRentalRentalClassId { get { return this._CarRentalRentalClassIdOption; } set { this._CarRentalRentalClassIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRenterNameOption { get; private set; } + + /// + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.renterName")] + public string? CarRentalRenterName { get { return this._CarRentalRenterNameOption; } set { this._CarRentalRenterNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnCityOption { get; private set; } + + /// + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnCity")] + public string? CarRentalReturnCity { get { return this._CarRentalReturnCityOption; } set { this._CarRentalReturnCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnCountryOption { get; private set; } + + /// + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + [JsonPropertyName("carRental.returnCountry")] + public string? CarRentalReturnCountry { get { return this._CarRentalReturnCountryOption; } set { this._CarRentalReturnCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnDateOption { get; private set; } + + /// + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + /// + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + [JsonPropertyName("carRental.returnDate")] + public string? CarRentalReturnDate { get { return this._CarRentalReturnDateOption; } set { this._CarRentalReturnDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnLocationIdOption { get; private set; } + + /// + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnLocationId")] + public string? CarRentalReturnLocationId { get { return this._CarRentalReturnLocationIdOption; } set { this._CarRentalReturnLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnStateProvinceOption { get; private set; } + + /// + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnStateProvince")] + public string? CarRentalReturnStateProvince { get { return this._CarRentalReturnStateProvinceOption; } set { this._CarRentalReturnStateProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalTaxExemptIndicatorOption { get; private set; } + + /// + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + /// + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + [JsonPropertyName("carRental.taxExemptIndicator")] + public string? CarRentalTaxExemptIndicator { get { return this._CarRentalTaxExemptIndicatorOption; } set { this._CarRentalTaxExemptIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataDurationOption { get; private set; } + + /// + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + /// + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + [JsonPropertyName("travelEntertainmentAuthData.duration")] + public string? TravelEntertainmentAuthDataDuration { get { return this._TravelEntertainmentAuthDataDurationOption; } set { this._TravelEntertainmentAuthDataDurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataMarketOption { get; private set; } + + /// + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + /// + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + [JsonPropertyName("travelEntertainmentAuthData.market")] + public string? TravelEntertainmentAuthDataMarket { get { return this._TravelEntertainmentAuthDataMarketOption; } set { this._TravelEntertainmentAuthDataMarketOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataCarRental {\n"); + sb.Append(" CarRentalCheckOutDate: ").Append(CarRentalCheckOutDate).Append("\n"); + sb.Append(" CarRentalCustomerServiceTollFreeNumber: ").Append(CarRentalCustomerServiceTollFreeNumber).Append("\n"); + sb.Append(" CarRentalDaysRented: ").Append(CarRentalDaysRented).Append("\n"); + sb.Append(" CarRentalFuelCharges: ").Append(CarRentalFuelCharges).Append("\n"); + sb.Append(" CarRentalInsuranceCharges: ").Append(CarRentalInsuranceCharges).Append("\n"); + sb.Append(" CarRentalLocationCity: ").Append(CarRentalLocationCity).Append("\n"); + sb.Append(" CarRentalLocationCountry: ").Append(CarRentalLocationCountry).Append("\n"); + sb.Append(" CarRentalLocationStateProvince: ").Append(CarRentalLocationStateProvince).Append("\n"); + sb.Append(" CarRentalNoShowIndicator: ").Append(CarRentalNoShowIndicator).Append("\n"); + sb.Append(" CarRentalOneWayDropOffCharges: ").Append(CarRentalOneWayDropOffCharges).Append("\n"); + sb.Append(" CarRentalRate: ").Append(CarRentalRate).Append("\n"); + sb.Append(" CarRentalRateIndicator: ").Append(CarRentalRateIndicator).Append("\n"); + sb.Append(" CarRentalRentalAgreementNumber: ").Append(CarRentalRentalAgreementNumber).Append("\n"); + sb.Append(" CarRentalRentalClassId: ").Append(CarRentalRentalClassId).Append("\n"); + sb.Append(" CarRentalRenterName: ").Append(CarRentalRenterName).Append("\n"); + sb.Append(" CarRentalReturnCity: ").Append(CarRentalReturnCity).Append("\n"); + sb.Append(" CarRentalReturnCountry: ").Append(CarRentalReturnCountry).Append("\n"); + sb.Append(" CarRentalReturnDate: ").Append(CarRentalReturnDate).Append("\n"); + sb.Append(" CarRentalReturnLocationId: ").Append(CarRentalReturnLocationId).Append("\n"); + sb.Append(" CarRentalReturnStateProvince: ").Append(CarRentalReturnStateProvince).Append("\n"); + sb.Append(" CarRentalTaxExemptIndicator: ").Append(CarRentalTaxExemptIndicator).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataDuration: ").Append(TravelEntertainmentAuthDataDuration).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataMarket: ").Append(TravelEntertainmentAuthDataMarket).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataCarRentalJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataCarRental Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option carRentalCheckOutDate = default; + Option carRentalCustomerServiceTollFreeNumber = default; + Option carRentalDaysRented = default; + Option carRentalFuelCharges = default; + Option carRentalInsuranceCharges = default; + Option carRentalLocationCity = default; + Option carRentalLocationCountry = default; + Option carRentalLocationStateProvince = default; + Option carRentalNoShowIndicator = default; + Option carRentalOneWayDropOffCharges = default; + Option carRentalRate = default; + Option carRentalRateIndicator = default; + Option carRentalRentalAgreementNumber = default; + Option carRentalRentalClassId = default; + Option carRentalRenterName = default; + Option carRentalReturnCity = default; + Option carRentalReturnCountry = default; + Option carRentalReturnDate = default; + Option carRentalReturnLocationId = default; + Option carRentalReturnStateProvince = default; + Option carRentalTaxExemptIndicator = default; + Option travelEntertainmentAuthDataDuration = default; + Option travelEntertainmentAuthDataMarket = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "carRental.checkOutDate": + carRentalCheckOutDate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.customerServiceTollFreeNumber": + carRentalCustomerServiceTollFreeNumber = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.daysRented": + carRentalDaysRented = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.fuelCharges": + carRentalFuelCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.insuranceCharges": + carRentalInsuranceCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationCity": + carRentalLocationCity = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationCountry": + carRentalLocationCountry = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationStateProvince": + carRentalLocationStateProvince = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.noShowIndicator": + carRentalNoShowIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.oneWayDropOffCharges": + carRentalOneWayDropOffCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rate": + carRentalRate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rateIndicator": + carRentalRateIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rentalAgreementNumber": + carRentalRentalAgreementNumber = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rentalClassId": + carRentalRentalClassId = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.renterName": + carRentalRenterName = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnCity": + carRentalReturnCity = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnCountry": + carRentalReturnCountry = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnDate": + carRentalReturnDate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnLocationId": + carRentalReturnLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnStateProvince": + carRentalReturnStateProvince = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.taxExemptIndicator": + carRentalTaxExemptIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.duration": + travelEntertainmentAuthDataDuration = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.market": + travelEntertainmentAuthDataMarket = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataCarRental(carRentalCheckOutDate, carRentalCustomerServiceTollFreeNumber, carRentalDaysRented, carRentalFuelCharges, carRentalInsuranceCharges, carRentalLocationCity, carRentalLocationCountry, carRentalLocationStateProvince, carRentalNoShowIndicator, carRentalOneWayDropOffCharges, carRentalRate, carRentalRateIndicator, carRentalRentalAgreementNumber, carRentalRentalClassId, carRentalRenterName, carRentalReturnCity, carRentalReturnCountry, carRentalReturnDate, carRentalReturnLocationId, carRentalReturnStateProvince, carRentalTaxExemptIndicator, travelEntertainmentAuthDataDuration, travelEntertainmentAuthDataMarket); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataCarRental additionalDataCarRental, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataCarRental, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataCarRental additionalDataCarRental, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataCarRental._CarRentalCheckOutDateOption.IsSet) + if (additionalDataCarRental.CarRentalCheckOutDate != null) + writer.WriteString("carRental.checkOutDate", additionalDataCarRental.CarRentalCheckOutDate); + + if (additionalDataCarRental._CarRentalCustomerServiceTollFreeNumberOption.IsSet) + if (additionalDataCarRental.CarRentalCustomerServiceTollFreeNumber != null) + writer.WriteString("carRental.customerServiceTollFreeNumber", additionalDataCarRental.CarRentalCustomerServiceTollFreeNumber); + + if (additionalDataCarRental._CarRentalDaysRentedOption.IsSet) + if (additionalDataCarRental.CarRentalDaysRented != null) + writer.WriteString("carRental.daysRented", additionalDataCarRental.CarRentalDaysRented); + + if (additionalDataCarRental._CarRentalFuelChargesOption.IsSet) + if (additionalDataCarRental.CarRentalFuelCharges != null) + writer.WriteString("carRental.fuelCharges", additionalDataCarRental.CarRentalFuelCharges); + + if (additionalDataCarRental._CarRentalInsuranceChargesOption.IsSet) + if (additionalDataCarRental.CarRentalInsuranceCharges != null) + writer.WriteString("carRental.insuranceCharges", additionalDataCarRental.CarRentalInsuranceCharges); + + if (additionalDataCarRental._CarRentalLocationCityOption.IsSet) + if (additionalDataCarRental.CarRentalLocationCity != null) + writer.WriteString("carRental.locationCity", additionalDataCarRental.CarRentalLocationCity); + + if (additionalDataCarRental._CarRentalLocationCountryOption.IsSet) + if (additionalDataCarRental.CarRentalLocationCountry != null) + writer.WriteString("carRental.locationCountry", additionalDataCarRental.CarRentalLocationCountry); + + if (additionalDataCarRental._CarRentalLocationStateProvinceOption.IsSet) + if (additionalDataCarRental.CarRentalLocationStateProvince != null) + writer.WriteString("carRental.locationStateProvince", additionalDataCarRental.CarRentalLocationStateProvince); + + if (additionalDataCarRental._CarRentalNoShowIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalNoShowIndicator != null) + writer.WriteString("carRental.noShowIndicator", additionalDataCarRental.CarRentalNoShowIndicator); + + if (additionalDataCarRental._CarRentalOneWayDropOffChargesOption.IsSet) + if (additionalDataCarRental.CarRentalOneWayDropOffCharges != null) + writer.WriteString("carRental.oneWayDropOffCharges", additionalDataCarRental.CarRentalOneWayDropOffCharges); + + if (additionalDataCarRental._CarRentalRateOption.IsSet) + if (additionalDataCarRental.CarRentalRate != null) + writer.WriteString("carRental.rate", additionalDataCarRental.CarRentalRate); + + if (additionalDataCarRental._CarRentalRateIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalRateIndicator != null) + writer.WriteString("carRental.rateIndicator", additionalDataCarRental.CarRentalRateIndicator); + + if (additionalDataCarRental._CarRentalRentalAgreementNumberOption.IsSet) + if (additionalDataCarRental.CarRentalRentalAgreementNumber != null) + writer.WriteString("carRental.rentalAgreementNumber", additionalDataCarRental.CarRentalRentalAgreementNumber); + + if (additionalDataCarRental._CarRentalRentalClassIdOption.IsSet) + if (additionalDataCarRental.CarRentalRentalClassId != null) + writer.WriteString("carRental.rentalClassId", additionalDataCarRental.CarRentalRentalClassId); + + if (additionalDataCarRental._CarRentalRenterNameOption.IsSet) + if (additionalDataCarRental.CarRentalRenterName != null) + writer.WriteString("carRental.renterName", additionalDataCarRental.CarRentalRenterName); + + if (additionalDataCarRental._CarRentalReturnCityOption.IsSet) + if (additionalDataCarRental.CarRentalReturnCity != null) + writer.WriteString("carRental.returnCity", additionalDataCarRental.CarRentalReturnCity); + + if (additionalDataCarRental._CarRentalReturnCountryOption.IsSet) + if (additionalDataCarRental.CarRentalReturnCountry != null) + writer.WriteString("carRental.returnCountry", additionalDataCarRental.CarRentalReturnCountry); + + if (additionalDataCarRental._CarRentalReturnDateOption.IsSet) + if (additionalDataCarRental.CarRentalReturnDate != null) + writer.WriteString("carRental.returnDate", additionalDataCarRental.CarRentalReturnDate); + + if (additionalDataCarRental._CarRentalReturnLocationIdOption.IsSet) + if (additionalDataCarRental.CarRentalReturnLocationId != null) + writer.WriteString("carRental.returnLocationId", additionalDataCarRental.CarRentalReturnLocationId); + + if (additionalDataCarRental._CarRentalReturnStateProvinceOption.IsSet) + if (additionalDataCarRental.CarRentalReturnStateProvince != null) + writer.WriteString("carRental.returnStateProvince", additionalDataCarRental.CarRentalReturnStateProvince); + + if (additionalDataCarRental._CarRentalTaxExemptIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalTaxExemptIndicator != null) + writer.WriteString("carRental.taxExemptIndicator", additionalDataCarRental.CarRentalTaxExemptIndicator); + + if (additionalDataCarRental._TravelEntertainmentAuthDataDurationOption.IsSet) + if (additionalDataCarRental.TravelEntertainmentAuthDataDuration != null) + writer.WriteString("travelEntertainmentAuthData.duration", additionalDataCarRental.TravelEntertainmentAuthDataDuration); + + if (additionalDataCarRental._TravelEntertainmentAuthDataMarketOption.IsSet) + if (additionalDataCarRental.TravelEntertainmentAuthDataMarket != null) + writer.WriteString("travelEntertainmentAuthData.market", additionalDataCarRental.TravelEntertainmentAuthDataMarket); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataCommon.cs b/Adyen/Checkout/Models/AdditionalDataCommon.cs new file mode 100644 index 000000000..130c21264 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataCommon.cs @@ -0,0 +1,783 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataCommon. + /// + public partial class AdditionalDataCommon : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + [JsonConstructor] + public AdditionalDataCommon(Option requestedTestAcquirerResponseCode = default, Option requestedTestErrorResponseCode = default, Option allowPartialAuth = default, Option authorisationType = default, Option autoRescue = default, Option customRoutingFlag = default, Option industryUsage = default, Option manualCapture = default, Option maxDaysToRescue = default, Option networkTxReference = default, Option overwriteBrand = default, Option subMerchantCity = default, Option subMerchantCountry = default, Option subMerchantEmail = default, Option subMerchantID = default, Option subMerchantName = default, Option subMerchantPhoneNumber = default, Option subMerchantPostalCode = default, Option subMerchantState = default, Option subMerchantStreet = default, Option subMerchantTaxId = default) + { + _RequestedTestAcquirerResponseCodeOption = requestedTestAcquirerResponseCode; + _RequestedTestErrorResponseCodeOption = requestedTestErrorResponseCode; + _AllowPartialAuthOption = allowPartialAuth; + _AuthorisationTypeOption = authorisationType; + _AutoRescueOption = autoRescue; + _CustomRoutingFlagOption = customRoutingFlag; + _IndustryUsageOption = industryUsage; + _ManualCaptureOption = manualCapture; + _MaxDaysToRescueOption = maxDaysToRescue; + _NetworkTxReferenceOption = networkTxReference; + _OverwriteBrandOption = overwriteBrand; + _SubMerchantCityOption = subMerchantCity; + _SubMerchantCountryOption = subMerchantCountry; + _SubMerchantEmailOption = subMerchantEmail; + _SubMerchantIDOption = subMerchantID; + _SubMerchantNameOption = subMerchantName; + _SubMerchantPhoneNumberOption = subMerchantPhoneNumber; + _SubMerchantPostalCodeOption = subMerchantPostalCode; + _SubMerchantStateOption = subMerchantState; + _SubMerchantStreetOption = subMerchantStreet; + _SubMerchantTaxIdOption = subMerchantTaxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataCommon() + { + } + + partial void OnCreated(); + + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + [JsonConverter(typeof(IndustryUsageEnumJsonConverter))] + public class IndustryUsageEnum : IEnum + { + /// + /// Returns the value of the IndustryUsageEnum. + /// + public string? Value { get; set; } + + /// + /// IndustryUsageEnum.NoShow - NoShow + /// + public static readonly IndustryUsageEnum NoShow = new("NoShow"); + + /// + /// IndustryUsageEnum.DelayedCharge - DelayedCharge + /// + public static readonly IndustryUsageEnum DelayedCharge = new("DelayedCharge"); + + private IndustryUsageEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IndustryUsageEnum?(string? value) => value == null ? null : new IndustryUsageEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IndustryUsageEnum? option) => option?.Value; + + public static bool operator ==(IndustryUsageEnum? left, IndustryUsageEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IndustryUsageEnum? left, IndustryUsageEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IndustryUsageEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IndustryUsageEnum? FromStringOrDefault(string value) + { + return value switch { + "NoShow" => IndustryUsageEnum.NoShow, + "DelayedCharge" => IndustryUsageEnum.DelayedCharge, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IndustryUsageEnum? value) + { + if (value == null) + return null; + + if (value == IndustryUsageEnum.NoShow) + return "NoShow"; + + if (value == IndustryUsageEnum.DelayedCharge) + return "DelayedCharge"; + + return null; + } + + /// + /// JsonConverter for writing IndustryUsageEnum. + /// + public class IndustryUsageEnumJsonConverter : JsonConverter + { + public override IndustryUsageEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IndustryUsageEnum.FromStringOrDefault(value) ?? new IndustryUsageEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IndustryUsageEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IndustryUsageEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryUsageOption { get; private set; } + + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + [JsonPropertyName("industryUsage")] + public IndustryUsageEnum? IndustryUsage { get { return this._IndustryUsageOption; } set { this._IndustryUsageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedTestAcquirerResponseCodeOption { get; private set; } + + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + [JsonPropertyName("RequestedTestAcquirerResponseCode")] + public string? RequestedTestAcquirerResponseCode { get { return this._RequestedTestAcquirerResponseCodeOption; } set { this._RequestedTestAcquirerResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedTestErrorResponseCodeOption { get; private set; } + + /// + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + /// + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + [JsonPropertyName("RequestedTestErrorResponseCode")] + public string? RequestedTestErrorResponseCode { get { return this._RequestedTestErrorResponseCodeOption; } set { this._RequestedTestErrorResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowPartialAuthOption { get; private set; } + + /// + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + /// + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + [JsonPropertyName("allowPartialAuth")] + public string? AllowPartialAuth { get { return this._AllowPartialAuthOption; } set { this._AllowPartialAuthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTypeOption { get; private set; } + + /// + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + /// + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + [JsonPropertyName("authorisationType")] + public string? AuthorisationType { get { return this._AuthorisationTypeOption; } set { this._AuthorisationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AutoRescueOption { get; private set; } + + /// + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + /// + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + [JsonPropertyName("autoRescue")] + public string? AutoRescue { get { return this._AutoRescueOption; } set { this._AutoRescueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomRoutingFlagOption { get; private set; } + + /// + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("customRoutingFlag")] + public string? CustomRoutingFlag { get { return this._CustomRoutingFlagOption; } set { this._CustomRoutingFlagOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ManualCaptureOption { get; private set; } + + /// + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + /// + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + [JsonPropertyName("manualCapture")] + public string? ManualCapture { get { return this._ManualCaptureOption; } set { this._ManualCaptureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxDaysToRescueOption { get; private set; } + + /// + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + /// + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + [JsonPropertyName("maxDaysToRescue")] + public string? MaxDaysToRescue { get { return this._MaxDaysToRescueOption; } set { this._MaxDaysToRescueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + /// + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OverwriteBrandOption { get; private set; } + + /// + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + /// + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + [JsonPropertyName("overwriteBrand")] + public string? OverwriteBrand { get { return this._OverwriteBrandOption; } set { this._OverwriteBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantCityOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + [JsonPropertyName("subMerchantCity")] + public string? SubMerchantCity { get { return this._SubMerchantCityOption; } set { this._SubMerchantCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantCountryOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + [JsonPropertyName("subMerchantCountry")] + public string? SubMerchantCountry { get { return this._SubMerchantCountryOption; } set { this._SubMerchantCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantEmailOption { get; private set; } + + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + [JsonPropertyName("subMerchantEmail")] + public string? SubMerchantEmail { get { return this._SubMerchantEmailOption; } set { this._SubMerchantEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantIDOption { get; private set; } + + /// + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + /// + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + [JsonPropertyName("subMerchantID")] + public string? SubMerchantID { get { return this._SubMerchantIDOption; } set { this._SubMerchantIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantNameOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + [JsonPropertyName("subMerchantName")] + public string? SubMerchantName { get { return this._SubMerchantNameOption; } set { this._SubMerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantPhoneNumberOption { get; private set; } + + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + [JsonPropertyName("subMerchantPhoneNumber")] + public string? SubMerchantPhoneNumber { get { return this._SubMerchantPhoneNumberOption; } set { this._SubMerchantPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantPostalCodeOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + [JsonPropertyName("subMerchantPostalCode")] + public string? SubMerchantPostalCode { get { return this._SubMerchantPostalCodeOption; } set { this._SubMerchantPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantStateOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + [JsonPropertyName("subMerchantState")] + public string? SubMerchantState { get { return this._SubMerchantStateOption; } set { this._SubMerchantStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantStreetOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + [JsonPropertyName("subMerchantStreet")] + public string? SubMerchantStreet { get { return this._SubMerchantStreetOption; } set { this._SubMerchantStreetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantTaxIdOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + [JsonPropertyName("subMerchantTaxId")] + public string? SubMerchantTaxId { get { return this._SubMerchantTaxIdOption; } set { this._SubMerchantTaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataCommon {\n"); + sb.Append(" RequestedTestAcquirerResponseCode: ").Append(RequestedTestAcquirerResponseCode).Append("\n"); + sb.Append(" RequestedTestErrorResponseCode: ").Append(RequestedTestErrorResponseCode).Append("\n"); + sb.Append(" AllowPartialAuth: ").Append(AllowPartialAuth).Append("\n"); + sb.Append(" AuthorisationType: ").Append(AuthorisationType).Append("\n"); + sb.Append(" AutoRescue: ").Append(AutoRescue).Append("\n"); + sb.Append(" CustomRoutingFlag: ").Append(CustomRoutingFlag).Append("\n"); + sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); + sb.Append(" ManualCapture: ").Append(ManualCapture).Append("\n"); + sb.Append(" MaxDaysToRescue: ").Append(MaxDaysToRescue).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OverwriteBrand: ").Append(OverwriteBrand).Append("\n"); + sb.Append(" SubMerchantCity: ").Append(SubMerchantCity).Append("\n"); + sb.Append(" SubMerchantCountry: ").Append(SubMerchantCountry).Append("\n"); + sb.Append(" SubMerchantEmail: ").Append(SubMerchantEmail).Append("\n"); + sb.Append(" SubMerchantID: ").Append(SubMerchantID).Append("\n"); + sb.Append(" SubMerchantName: ").Append(SubMerchantName).Append("\n"); + sb.Append(" SubMerchantPhoneNumber: ").Append(SubMerchantPhoneNumber).Append("\n"); + sb.Append(" SubMerchantPostalCode: ").Append(SubMerchantPostalCode).Append("\n"); + sb.Append(" SubMerchantState: ").Append(SubMerchantState).Append("\n"); + sb.Append(" SubMerchantStreet: ").Append(SubMerchantStreet).Append("\n"); + sb.Append(" SubMerchantTaxId: ").Append(SubMerchantTaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataCommonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataCommon Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requestedTestAcquirerResponseCode = default; + Option requestedTestErrorResponseCode = default; + Option allowPartialAuth = default; + Option authorisationType = default; + Option autoRescue = default; + Option customRoutingFlag = default; + Option industryUsage = default; + Option manualCapture = default; + Option maxDaysToRescue = default; + Option networkTxReference = default; + Option overwriteBrand = default; + Option subMerchantCity = default; + Option subMerchantCountry = default; + Option subMerchantEmail = default; + Option subMerchantID = default; + Option subMerchantName = default; + Option subMerchantPhoneNumber = default; + Option subMerchantPostalCode = default; + Option subMerchantState = default; + Option subMerchantStreet = default; + Option subMerchantTaxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "RequestedTestAcquirerResponseCode": + requestedTestAcquirerResponseCode = new Option(utf8JsonReader.GetString()!); + break; + case "RequestedTestErrorResponseCode": + requestedTestErrorResponseCode = new Option(utf8JsonReader.GetString()!); + break; + case "allowPartialAuth": + allowPartialAuth = new Option(utf8JsonReader.GetString()!); + break; + case "authorisationType": + authorisationType = new Option(utf8JsonReader.GetString()!); + break; + case "autoRescue": + autoRescue = new Option(utf8JsonReader.GetString()!); + break; + case "customRoutingFlag": + customRoutingFlag = new Option(utf8JsonReader.GetString()!); + break; + case "industryUsage": + string? industryUsageRawValue = utf8JsonReader.GetString(); + industryUsage = new Option(AdditionalDataCommon.IndustryUsageEnum.FromStringOrDefault(industryUsageRawValue)); + break; + case "manualCapture": + manualCapture = new Option(utf8JsonReader.GetString()!); + break; + case "maxDaysToRescue": + maxDaysToRescue = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "overwriteBrand": + overwriteBrand = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantCity": + subMerchantCity = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantCountry": + subMerchantCountry = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantEmail": + subMerchantEmail = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantID": + subMerchantID = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantName": + subMerchantName = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantPhoneNumber": + subMerchantPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantPostalCode": + subMerchantPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantState": + subMerchantState = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantStreet": + subMerchantStreet = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantTaxId": + subMerchantTaxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataCommon(requestedTestAcquirerResponseCode, requestedTestErrorResponseCode, allowPartialAuth, authorisationType, autoRescue, customRoutingFlag, industryUsage, manualCapture, maxDaysToRescue, networkTxReference, overwriteBrand, subMerchantCity, subMerchantCountry, subMerchantEmail, subMerchantID, subMerchantName, subMerchantPhoneNumber, subMerchantPostalCode, subMerchantState, subMerchantStreet, subMerchantTaxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataCommon additionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataCommon, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataCommon additionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataCommon._RequestedTestAcquirerResponseCodeOption.IsSet) + if (additionalDataCommon.RequestedTestAcquirerResponseCode != null) + writer.WriteString("RequestedTestAcquirerResponseCode", additionalDataCommon.RequestedTestAcquirerResponseCode); + + if (additionalDataCommon._RequestedTestErrorResponseCodeOption.IsSet) + if (additionalDataCommon.RequestedTestErrorResponseCode != null) + writer.WriteString("RequestedTestErrorResponseCode", additionalDataCommon.RequestedTestErrorResponseCode); + + if (additionalDataCommon._AllowPartialAuthOption.IsSet) + if (additionalDataCommon.AllowPartialAuth != null) + writer.WriteString("allowPartialAuth", additionalDataCommon.AllowPartialAuth); + + if (additionalDataCommon._AuthorisationTypeOption.IsSet) + if (additionalDataCommon.AuthorisationType != null) + writer.WriteString("authorisationType", additionalDataCommon.AuthorisationType); + + if (additionalDataCommon._AutoRescueOption.IsSet) + if (additionalDataCommon.AutoRescue != null) + writer.WriteString("autoRescue", additionalDataCommon.AutoRescue); + + if (additionalDataCommon._CustomRoutingFlagOption.IsSet) + if (additionalDataCommon.CustomRoutingFlag != null) + writer.WriteString("customRoutingFlag", additionalDataCommon.CustomRoutingFlag); + + if (additionalDataCommon._IndustryUsageOption.IsSet && additionalDataCommon.IndustryUsage != null) + { + string? industryUsageRawValue = AdditionalDataCommon.IndustryUsageEnum.ToJsonValue(additionalDataCommon._IndustryUsageOption.Value!.Value); + writer.WriteString("industryUsage", industryUsageRawValue); + } + + if (additionalDataCommon._ManualCaptureOption.IsSet) + if (additionalDataCommon.ManualCapture != null) + writer.WriteString("manualCapture", additionalDataCommon.ManualCapture); + + if (additionalDataCommon._MaxDaysToRescueOption.IsSet) + if (additionalDataCommon.MaxDaysToRescue != null) + writer.WriteString("maxDaysToRescue", additionalDataCommon.MaxDaysToRescue); + + if (additionalDataCommon._NetworkTxReferenceOption.IsSet) + if (additionalDataCommon.NetworkTxReference != null) + writer.WriteString("networkTxReference", additionalDataCommon.NetworkTxReference); + + if (additionalDataCommon._OverwriteBrandOption.IsSet) + if (additionalDataCommon.OverwriteBrand != null) + writer.WriteString("overwriteBrand", additionalDataCommon.OverwriteBrand); + + if (additionalDataCommon._SubMerchantCityOption.IsSet) + if (additionalDataCommon.SubMerchantCity != null) + writer.WriteString("subMerchantCity", additionalDataCommon.SubMerchantCity); + + if (additionalDataCommon._SubMerchantCountryOption.IsSet) + if (additionalDataCommon.SubMerchantCountry != null) + writer.WriteString("subMerchantCountry", additionalDataCommon.SubMerchantCountry); + + if (additionalDataCommon._SubMerchantEmailOption.IsSet) + if (additionalDataCommon.SubMerchantEmail != null) + writer.WriteString("subMerchantEmail", additionalDataCommon.SubMerchantEmail); + + if (additionalDataCommon._SubMerchantIDOption.IsSet) + if (additionalDataCommon.SubMerchantID != null) + writer.WriteString("subMerchantID", additionalDataCommon.SubMerchantID); + + if (additionalDataCommon._SubMerchantNameOption.IsSet) + if (additionalDataCommon.SubMerchantName != null) + writer.WriteString("subMerchantName", additionalDataCommon.SubMerchantName); + + if (additionalDataCommon._SubMerchantPhoneNumberOption.IsSet) + if (additionalDataCommon.SubMerchantPhoneNumber != null) + writer.WriteString("subMerchantPhoneNumber", additionalDataCommon.SubMerchantPhoneNumber); + + if (additionalDataCommon._SubMerchantPostalCodeOption.IsSet) + if (additionalDataCommon.SubMerchantPostalCode != null) + writer.WriteString("subMerchantPostalCode", additionalDataCommon.SubMerchantPostalCode); + + if (additionalDataCommon._SubMerchantStateOption.IsSet) + if (additionalDataCommon.SubMerchantState != null) + writer.WriteString("subMerchantState", additionalDataCommon.SubMerchantState); + + if (additionalDataCommon._SubMerchantStreetOption.IsSet) + if (additionalDataCommon.SubMerchantStreet != null) + writer.WriteString("subMerchantStreet", additionalDataCommon.SubMerchantStreet); + + if (additionalDataCommon._SubMerchantTaxIdOption.IsSet) + if (additionalDataCommon.SubMerchantTaxId != null) + writer.WriteString("subMerchantTaxId", additionalDataCommon.SubMerchantTaxId); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataLevel23.cs b/Adyen/Checkout/Models/AdditionalDataLevel23.cs new file mode 100644 index 000000000..e8efc7b07 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataLevel23.cs @@ -0,0 +1,577 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataLevel23. + /// + public partial class AdditionalDataLevel23 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + [JsonConstructor] + public AdditionalDataLevel23(Option enhancedSchemeDataCustomerReference = default, Option enhancedSchemeDataDestinationCountryCode = default, Option enhancedSchemeDataDestinationPostalCode = default, Option enhancedSchemeDataDestinationStateProvinceCode = default, Option enhancedSchemeDataDutyAmount = default, Option enhancedSchemeDataFreightAmount = default, Option enhancedSchemeDataItemDetailLineItemNrCommodityCode = default, Option enhancedSchemeDataItemDetailLineItemNrDescription = default, Option enhancedSchemeDataItemDetailLineItemNrDiscountAmount = default, Option enhancedSchemeDataItemDetailLineItemNrProductCode = default, Option enhancedSchemeDataItemDetailLineItemNrQuantity = default, Option enhancedSchemeDataItemDetailLineItemNrTotalAmount = default, Option enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = default, Option enhancedSchemeDataItemDetailLineItemNrUnitPrice = default, Option enhancedSchemeDataOrderDate = default, Option enhancedSchemeDataShipFromPostalCode = default, Option enhancedSchemeDataTotalTaxAmount = default) + { + _EnhancedSchemeDataCustomerReferenceOption = enhancedSchemeDataCustomerReference; + _EnhancedSchemeDataDestinationCountryCodeOption = enhancedSchemeDataDestinationCountryCode; + _EnhancedSchemeDataDestinationPostalCodeOption = enhancedSchemeDataDestinationPostalCode; + _EnhancedSchemeDataDestinationStateProvinceCodeOption = enhancedSchemeDataDestinationStateProvinceCode; + _EnhancedSchemeDataDutyAmountOption = enhancedSchemeDataDutyAmount; + _EnhancedSchemeDataFreightAmountOption = enhancedSchemeDataFreightAmount; + _EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption = enhancedSchemeDataItemDetailLineItemNrCommodityCode; + _EnhancedSchemeDataItemDetailLineItemNrDescriptionOption = enhancedSchemeDataItemDetailLineItemNrDescription; + _EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption = enhancedSchemeDataItemDetailLineItemNrDiscountAmount; + _EnhancedSchemeDataItemDetailLineItemNrProductCodeOption = enhancedSchemeDataItemDetailLineItemNrProductCode; + _EnhancedSchemeDataItemDetailLineItemNrQuantityOption = enhancedSchemeDataItemDetailLineItemNrQuantity; + _EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption = enhancedSchemeDataItemDetailLineItemNrTotalAmount; + _EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption = enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure; + _EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption = enhancedSchemeDataItemDetailLineItemNrUnitPrice; + _EnhancedSchemeDataOrderDateOption = enhancedSchemeDataOrderDate; + _EnhancedSchemeDataShipFromPostalCodeOption = enhancedSchemeDataShipFromPostalCode; + _EnhancedSchemeDataTotalTaxAmountOption = enhancedSchemeDataTotalTaxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataLevel23() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataCustomerReferenceOption { get; private set; } + + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.customerReference")] + public string? EnhancedSchemeDataCustomerReference { get { return this._EnhancedSchemeDataCustomerReferenceOption; } set { this._EnhancedSchemeDataCustomerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationCountryCodeOption { get; private set; } + + /// + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + /// + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + [JsonPropertyName("enhancedSchemeData.destinationCountryCode")] + public string? EnhancedSchemeDataDestinationCountryCode { get { return this._EnhancedSchemeDataDestinationCountryCodeOption; } set { this._EnhancedSchemeDataDestinationCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationPostalCodeOption { get; private set; } + + /// + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + [JsonPropertyName("enhancedSchemeData.destinationPostalCode")] + public string? EnhancedSchemeDataDestinationPostalCode { get { return this._EnhancedSchemeDataDestinationPostalCodeOption; } set { this._EnhancedSchemeDataDestinationPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationStateProvinceCodeOption { get; private set; } + + /// + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + /// + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + [JsonPropertyName("enhancedSchemeData.destinationStateProvinceCode")] + public string? EnhancedSchemeDataDestinationStateProvinceCode { get { return this._EnhancedSchemeDataDestinationStateProvinceCodeOption; } set { this._EnhancedSchemeDataDestinationStateProvinceCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDutyAmountOption { get; private set; } + + /// + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.dutyAmount")] + public string? EnhancedSchemeDataDutyAmount { get { return this._EnhancedSchemeDataDutyAmountOption; } set { this._EnhancedSchemeDataDutyAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataFreightAmountOption { get; private set; } + + /// + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.freightAmount")] + public string? EnhancedSchemeDataFreightAmount { get { return this._EnhancedSchemeDataFreightAmountOption; } set { this._EnhancedSchemeDataFreightAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption { get; private set; } + + /// + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].commodityCode")] + public string? EnhancedSchemeDataItemDetailLineItemNrCommodityCode { get { return this._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrDescriptionOption { get; private set; } + + /// + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].description")] + public string? EnhancedSchemeDataItemDetailLineItemNrDescription { get { return this._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption { get; private set; } + + /// + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].discountAmount")] + public string? EnhancedSchemeDataItemDetailLineItemNrDiscountAmount { get { return this._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrProductCodeOption { get; private set; } + + /// + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].productCode")] + public string? EnhancedSchemeDataItemDetailLineItemNrProductCode { get { return this._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrQuantityOption { get; private set; } + + /// + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + /// + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].quantity")] + public string? EnhancedSchemeDataItemDetailLineItemNrQuantity { get { return this._EnhancedSchemeDataItemDetailLineItemNrQuantityOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrQuantityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption { get; private set; } + + /// + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].totalAmount")] + public string? EnhancedSchemeDataItemDetailLineItemNrTotalAmount { get { return this._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption { get; private set; } + + /// + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure")] + public string? EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure { get { return this._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption { get; private set; } + + /// + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + /// + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].unitPrice")] + public string? EnhancedSchemeDataItemDetailLineItemNrUnitPrice { get { return this._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOrderDateOption { get; private set; } + + /// + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + /// + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + [JsonPropertyName("enhancedSchemeData.orderDate")] + public string? EnhancedSchemeDataOrderDate { get { return this._EnhancedSchemeDataOrderDateOption; } set { this._EnhancedSchemeDataOrderDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataShipFromPostalCodeOption { get; private set; } + + /// + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + [JsonPropertyName("enhancedSchemeData.shipFromPostalCode")] + public string? EnhancedSchemeDataShipFromPostalCode { get { return this._EnhancedSchemeDataShipFromPostalCodeOption; } set { this._EnhancedSchemeDataShipFromPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTotalTaxAmountOption { get; private set; } + + /// + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + /// + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + [JsonPropertyName("enhancedSchemeData.totalTaxAmount")] + public string? EnhancedSchemeDataTotalTaxAmount { get { return this._EnhancedSchemeDataTotalTaxAmountOption; } set { this._EnhancedSchemeDataTotalTaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataLevel23 {\n"); + sb.Append(" EnhancedSchemeDataCustomerReference: ").Append(EnhancedSchemeDataCustomerReference).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationCountryCode: ").Append(EnhancedSchemeDataDestinationCountryCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationPostalCode: ").Append(EnhancedSchemeDataDestinationPostalCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationStateProvinceCode: ").Append(EnhancedSchemeDataDestinationStateProvinceCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDutyAmount: ").Append(EnhancedSchemeDataDutyAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataFreightAmount: ").Append(EnhancedSchemeDataFreightAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrCommodityCode: ").Append(EnhancedSchemeDataItemDetailLineItemNrCommodityCode).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrDescription: ").Append(EnhancedSchemeDataItemDetailLineItemNrDescription).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrDiscountAmount: ").Append(EnhancedSchemeDataItemDetailLineItemNrDiscountAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrProductCode: ").Append(EnhancedSchemeDataItemDetailLineItemNrProductCode).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrQuantity: ").Append(EnhancedSchemeDataItemDetailLineItemNrQuantity).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrTotalAmount: ").Append(EnhancedSchemeDataItemDetailLineItemNrTotalAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure: ").Append(EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrUnitPrice: ").Append(EnhancedSchemeDataItemDetailLineItemNrUnitPrice).Append("\n"); + sb.Append(" EnhancedSchemeDataOrderDate: ").Append(EnhancedSchemeDataOrderDate).Append("\n"); + sb.Append(" EnhancedSchemeDataShipFromPostalCode: ").Append(EnhancedSchemeDataShipFromPostalCode).Append("\n"); + sb.Append(" EnhancedSchemeDataTotalTaxAmount: ").Append(EnhancedSchemeDataTotalTaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataLevel23JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataLevel23 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enhancedSchemeDataCustomerReference = default; + Option enhancedSchemeDataDestinationCountryCode = default; + Option enhancedSchemeDataDestinationPostalCode = default; + Option enhancedSchemeDataDestinationStateProvinceCode = default; + Option enhancedSchemeDataDutyAmount = default; + Option enhancedSchemeDataFreightAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrCommodityCode = default; + Option enhancedSchemeDataItemDetailLineItemNrDescription = default; + Option enhancedSchemeDataItemDetailLineItemNrDiscountAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrProductCode = default; + Option enhancedSchemeDataItemDetailLineItemNrQuantity = default; + Option enhancedSchemeDataItemDetailLineItemNrTotalAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = default; + Option enhancedSchemeDataItemDetailLineItemNrUnitPrice = default; + Option enhancedSchemeDataOrderDate = default; + Option enhancedSchemeDataShipFromPostalCode = default; + Option enhancedSchemeDataTotalTaxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enhancedSchemeData.customerReference": + enhancedSchemeDataCustomerReference = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationCountryCode": + enhancedSchemeDataDestinationCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationPostalCode": + enhancedSchemeDataDestinationPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationStateProvinceCode": + enhancedSchemeDataDestinationStateProvinceCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.dutyAmount": + enhancedSchemeDataDutyAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.freightAmount": + enhancedSchemeDataFreightAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].commodityCode": + enhancedSchemeDataItemDetailLineItemNrCommodityCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].description": + enhancedSchemeDataItemDetailLineItemNrDescription = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].discountAmount": + enhancedSchemeDataItemDetailLineItemNrDiscountAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].productCode": + enhancedSchemeDataItemDetailLineItemNrProductCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].quantity": + enhancedSchemeDataItemDetailLineItemNrQuantity = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].totalAmount": + enhancedSchemeDataItemDetailLineItemNrTotalAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure": + enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].unitPrice": + enhancedSchemeDataItemDetailLineItemNrUnitPrice = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.orderDate": + enhancedSchemeDataOrderDate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.shipFromPostalCode": + enhancedSchemeDataShipFromPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.totalTaxAmount": + enhancedSchemeDataTotalTaxAmount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataLevel23(enhancedSchemeDataCustomerReference, enhancedSchemeDataDestinationCountryCode, enhancedSchemeDataDestinationPostalCode, enhancedSchemeDataDestinationStateProvinceCode, enhancedSchemeDataDutyAmount, enhancedSchemeDataFreightAmount, enhancedSchemeDataItemDetailLineItemNrCommodityCode, enhancedSchemeDataItemDetailLineItemNrDescription, enhancedSchemeDataItemDetailLineItemNrDiscountAmount, enhancedSchemeDataItemDetailLineItemNrProductCode, enhancedSchemeDataItemDetailLineItemNrQuantity, enhancedSchemeDataItemDetailLineItemNrTotalAmount, enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure, enhancedSchemeDataItemDetailLineItemNrUnitPrice, enhancedSchemeDataOrderDate, enhancedSchemeDataShipFromPostalCode, enhancedSchemeDataTotalTaxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataLevel23 additionalDataLevel23, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataLevel23, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataLevel23 additionalDataLevel23, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataLevel23._EnhancedSchemeDataCustomerReferenceOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataCustomerReference != null) + writer.WriteString("enhancedSchemeData.customerReference", additionalDataLevel23.EnhancedSchemeDataCustomerReference); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationCountryCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationCountryCode != null) + writer.WriteString("enhancedSchemeData.destinationCountryCode", additionalDataLevel23.EnhancedSchemeDataDestinationCountryCode); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationPostalCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationPostalCode != null) + writer.WriteString("enhancedSchemeData.destinationPostalCode", additionalDataLevel23.EnhancedSchemeDataDestinationPostalCode); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationStateProvinceCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationStateProvinceCode != null) + writer.WriteString("enhancedSchemeData.destinationStateProvinceCode", additionalDataLevel23.EnhancedSchemeDataDestinationStateProvinceCode); + + if (additionalDataLevel23._EnhancedSchemeDataDutyAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDutyAmount != null) + writer.WriteString("enhancedSchemeData.dutyAmount", additionalDataLevel23.EnhancedSchemeDataDutyAmount); + + if (additionalDataLevel23._EnhancedSchemeDataFreightAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataFreightAmount != null) + writer.WriteString("enhancedSchemeData.freightAmount", additionalDataLevel23.EnhancedSchemeDataFreightAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrCommodityCode != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].commodityCode", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrCommodityCode); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDescription != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].description", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDescription); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDiscountAmount != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].discountAmount", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDiscountAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrProductCode != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].productCode", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrProductCode); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrQuantityOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrQuantity != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].quantity", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrQuantity); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrTotalAmount != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].totalAmount", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrTotalAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitPrice != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].unitPrice", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitPrice); + + if (additionalDataLevel23._EnhancedSchemeDataOrderDateOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataOrderDate != null) + writer.WriteString("enhancedSchemeData.orderDate", additionalDataLevel23.EnhancedSchemeDataOrderDate); + + if (additionalDataLevel23._EnhancedSchemeDataShipFromPostalCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataShipFromPostalCode != null) + writer.WriteString("enhancedSchemeData.shipFromPostalCode", additionalDataLevel23.EnhancedSchemeDataShipFromPostalCode); + + if (additionalDataLevel23._EnhancedSchemeDataTotalTaxAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataTotalTaxAmount != null) + writer.WriteString("enhancedSchemeData.totalTaxAmount", additionalDataLevel23.EnhancedSchemeDataTotalTaxAmount); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataLodging.cs b/Adyen/Checkout/Models/AdditionalDataLodging.cs new file mode 100644 index 000000000..6b09ef29d --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataLodging.cs @@ -0,0 +1,577 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataLodging. + /// + public partial class AdditionalDataLodging : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + [JsonConstructor] + public AdditionalDataLodging(Option lodgingSpecialProgramCode = default, Option lodgingCheckInDate = default, Option lodgingCheckOutDate = default, Option lodgingCustomerServiceTollFreeNumber = default, Option lodgingFireSafetyActIndicator = default, Option lodgingFolioCashAdvances = default, Option lodgingFolioNumber = default, Option lodgingFoodBeverageCharges = default, Option lodgingNoShowIndicator = default, Option lodgingPrepaidExpenses = default, Option lodgingPropertyPhoneNumber = default, Option lodgingRoom1NumberOfNights = default, Option lodgingRoom1Rate = default, Option lodgingTotalRoomTax = default, Option lodgingTotalTax = default, Option travelEntertainmentAuthDataDuration = default, Option travelEntertainmentAuthDataMarket = default) + { + _LodgingSpecialProgramCodeOption = lodgingSpecialProgramCode; + _LodgingCheckInDateOption = lodgingCheckInDate; + _LodgingCheckOutDateOption = lodgingCheckOutDate; + _LodgingCustomerServiceTollFreeNumberOption = lodgingCustomerServiceTollFreeNumber; + _LodgingFireSafetyActIndicatorOption = lodgingFireSafetyActIndicator; + _LodgingFolioCashAdvancesOption = lodgingFolioCashAdvances; + _LodgingFolioNumberOption = lodgingFolioNumber; + _LodgingFoodBeverageChargesOption = lodgingFoodBeverageCharges; + _LodgingNoShowIndicatorOption = lodgingNoShowIndicator; + _LodgingPrepaidExpensesOption = lodgingPrepaidExpenses; + _LodgingPropertyPhoneNumberOption = lodgingPropertyPhoneNumber; + _LodgingRoom1NumberOfNightsOption = lodgingRoom1NumberOfNights; + _LodgingRoom1RateOption = lodgingRoom1Rate; + _LodgingTotalRoomTaxOption = lodgingTotalRoomTax; + _LodgingTotalTaxOption = lodgingTotalTax; + _TravelEntertainmentAuthDataDurationOption = travelEntertainmentAuthDataDuration; + _TravelEntertainmentAuthDataMarketOption = travelEntertainmentAuthDataMarket; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataLodging() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingSpecialProgramCodeOption { get; private set; } + + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + [JsonPropertyName("lodging.SpecialProgramCode")] + public string? LodgingSpecialProgramCode { get { return this._LodgingSpecialProgramCodeOption; } set { this._LodgingSpecialProgramCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCheckInDateOption { get; private set; } + + /// + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + [JsonPropertyName("lodging.checkInDate")] + public string? LodgingCheckInDate { get { return this._LodgingCheckInDateOption; } set { this._LodgingCheckInDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCheckOutDateOption { get; private set; } + + /// + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + [JsonPropertyName("lodging.checkOutDate")] + public string? LodgingCheckOutDate { get { return this._LodgingCheckOutDateOption; } set { this._LodgingCheckOutDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCustomerServiceTollFreeNumberOption { get; private set; } + + /// + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + [JsonPropertyName("lodging.customerServiceTollFreeNumber")] + public string? LodgingCustomerServiceTollFreeNumber { get { return this._LodgingCustomerServiceTollFreeNumberOption; } set { this._LodgingCustomerServiceTollFreeNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFireSafetyActIndicatorOption { get; private set; } + + /// + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + /// + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + [JsonPropertyName("lodging.fireSafetyActIndicator")] + public string? LodgingFireSafetyActIndicator { get { return this._LodgingFireSafetyActIndicatorOption; } set { this._LodgingFireSafetyActIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFolioCashAdvancesOption { get; private set; } + + /// + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.folioCashAdvances")] + public string? LodgingFolioCashAdvances { get { return this._LodgingFolioCashAdvancesOption; } set { this._LodgingFolioCashAdvancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFolioNumberOption { get; private set; } + + /// + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + /// + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + [JsonPropertyName("lodging.folioNumber")] + public string? LodgingFolioNumber { get { return this._LodgingFolioNumberOption; } set { this._LodgingFolioNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFoodBeverageChargesOption { get; private set; } + + /// + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.foodBeverageCharges")] + public string? LodgingFoodBeverageCharges { get { return this._LodgingFoodBeverageChargesOption; } set { this._LodgingFoodBeverageChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingNoShowIndicatorOption { get; private set; } + + /// + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + /// + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + [JsonPropertyName("lodging.noShowIndicator")] + public string? LodgingNoShowIndicator { get { return this._LodgingNoShowIndicatorOption; } set { this._LodgingNoShowIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingPrepaidExpensesOption { get; private set; } + + /// + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + /// + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.prepaidExpenses")] + public string? LodgingPrepaidExpenses { get { return this._LodgingPrepaidExpensesOption; } set { this._LodgingPrepaidExpensesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingPropertyPhoneNumberOption { get; private set; } + + /// + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + [JsonPropertyName("lodging.propertyPhoneNumber")] + public string? LodgingPropertyPhoneNumber { get { return this._LodgingPropertyPhoneNumberOption; } set { this._LodgingPropertyPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingRoom1NumberOfNightsOption { get; private set; } + + /// + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + /// + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + [JsonPropertyName("lodging.room1.numberOfNights")] + public string? LodgingRoom1NumberOfNights { get { return this._LodgingRoom1NumberOfNightsOption; } set { this._LodgingRoom1NumberOfNightsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingRoom1RateOption { get; private set; } + + /// + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.room1.rate")] + public string? LodgingRoom1Rate { get { return this._LodgingRoom1RateOption; } set { this._LodgingRoom1RateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingTotalRoomTaxOption { get; private set; } + + /// + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.totalRoomTax")] + public string? LodgingTotalRoomTax { get { return this._LodgingTotalRoomTaxOption; } set { this._LodgingTotalRoomTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingTotalTaxOption { get; private set; } + + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.totalTax")] + public string? LodgingTotalTax { get { return this._LodgingTotalTaxOption; } set { this._LodgingTotalTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataDurationOption { get; private set; } + + /// + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + /// + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + [JsonPropertyName("travelEntertainmentAuthData.duration")] + public string? TravelEntertainmentAuthDataDuration { get { return this._TravelEntertainmentAuthDataDurationOption; } set { this._TravelEntertainmentAuthDataDurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataMarketOption { get; private set; } + + /// + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + /// + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + [JsonPropertyName("travelEntertainmentAuthData.market")] + public string? TravelEntertainmentAuthDataMarket { get { return this._TravelEntertainmentAuthDataMarketOption; } set { this._TravelEntertainmentAuthDataMarketOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataLodging {\n"); + sb.Append(" LodgingSpecialProgramCode: ").Append(LodgingSpecialProgramCode).Append("\n"); + sb.Append(" LodgingCheckInDate: ").Append(LodgingCheckInDate).Append("\n"); + sb.Append(" LodgingCheckOutDate: ").Append(LodgingCheckOutDate).Append("\n"); + sb.Append(" LodgingCustomerServiceTollFreeNumber: ").Append(LodgingCustomerServiceTollFreeNumber).Append("\n"); + sb.Append(" LodgingFireSafetyActIndicator: ").Append(LodgingFireSafetyActIndicator).Append("\n"); + sb.Append(" LodgingFolioCashAdvances: ").Append(LodgingFolioCashAdvances).Append("\n"); + sb.Append(" LodgingFolioNumber: ").Append(LodgingFolioNumber).Append("\n"); + sb.Append(" LodgingFoodBeverageCharges: ").Append(LodgingFoodBeverageCharges).Append("\n"); + sb.Append(" LodgingNoShowIndicator: ").Append(LodgingNoShowIndicator).Append("\n"); + sb.Append(" LodgingPrepaidExpenses: ").Append(LodgingPrepaidExpenses).Append("\n"); + sb.Append(" LodgingPropertyPhoneNumber: ").Append(LodgingPropertyPhoneNumber).Append("\n"); + sb.Append(" LodgingRoom1NumberOfNights: ").Append(LodgingRoom1NumberOfNights).Append("\n"); + sb.Append(" LodgingRoom1Rate: ").Append(LodgingRoom1Rate).Append("\n"); + sb.Append(" LodgingTotalRoomTax: ").Append(LodgingTotalRoomTax).Append("\n"); + sb.Append(" LodgingTotalTax: ").Append(LodgingTotalTax).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataDuration: ").Append(TravelEntertainmentAuthDataDuration).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataMarket: ").Append(TravelEntertainmentAuthDataMarket).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataLodgingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataLodging Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lodgingSpecialProgramCode = default; + Option lodgingCheckInDate = default; + Option lodgingCheckOutDate = default; + Option lodgingCustomerServiceTollFreeNumber = default; + Option lodgingFireSafetyActIndicator = default; + Option lodgingFolioCashAdvances = default; + Option lodgingFolioNumber = default; + Option lodgingFoodBeverageCharges = default; + Option lodgingNoShowIndicator = default; + Option lodgingPrepaidExpenses = default; + Option lodgingPropertyPhoneNumber = default; + Option lodgingRoom1NumberOfNights = default; + Option lodgingRoom1Rate = default; + Option lodgingTotalRoomTax = default; + Option lodgingTotalTax = default; + Option travelEntertainmentAuthDataDuration = default; + Option travelEntertainmentAuthDataMarket = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "lodging.SpecialProgramCode": + lodgingSpecialProgramCode = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.checkInDate": + lodgingCheckInDate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.checkOutDate": + lodgingCheckOutDate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.customerServiceTollFreeNumber": + lodgingCustomerServiceTollFreeNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.fireSafetyActIndicator": + lodgingFireSafetyActIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.folioCashAdvances": + lodgingFolioCashAdvances = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.folioNumber": + lodgingFolioNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.foodBeverageCharges": + lodgingFoodBeverageCharges = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.noShowIndicator": + lodgingNoShowIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.prepaidExpenses": + lodgingPrepaidExpenses = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.propertyPhoneNumber": + lodgingPropertyPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.room1.numberOfNights": + lodgingRoom1NumberOfNights = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.room1.rate": + lodgingRoom1Rate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.totalRoomTax": + lodgingTotalRoomTax = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.totalTax": + lodgingTotalTax = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.duration": + travelEntertainmentAuthDataDuration = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.market": + travelEntertainmentAuthDataMarket = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataLodging(lodgingSpecialProgramCode, lodgingCheckInDate, lodgingCheckOutDate, lodgingCustomerServiceTollFreeNumber, lodgingFireSafetyActIndicator, lodgingFolioCashAdvances, lodgingFolioNumber, lodgingFoodBeverageCharges, lodgingNoShowIndicator, lodgingPrepaidExpenses, lodgingPropertyPhoneNumber, lodgingRoom1NumberOfNights, lodgingRoom1Rate, lodgingTotalRoomTax, lodgingTotalTax, travelEntertainmentAuthDataDuration, travelEntertainmentAuthDataMarket); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataLodging additionalDataLodging, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataLodging, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataLodging additionalDataLodging, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataLodging._LodgingSpecialProgramCodeOption.IsSet) + if (additionalDataLodging.LodgingSpecialProgramCode != null) + writer.WriteString("lodging.SpecialProgramCode", additionalDataLodging.LodgingSpecialProgramCode); + + if (additionalDataLodging._LodgingCheckInDateOption.IsSet) + if (additionalDataLodging.LodgingCheckInDate != null) + writer.WriteString("lodging.checkInDate", additionalDataLodging.LodgingCheckInDate); + + if (additionalDataLodging._LodgingCheckOutDateOption.IsSet) + if (additionalDataLodging.LodgingCheckOutDate != null) + writer.WriteString("lodging.checkOutDate", additionalDataLodging.LodgingCheckOutDate); + + if (additionalDataLodging._LodgingCustomerServiceTollFreeNumberOption.IsSet) + if (additionalDataLodging.LodgingCustomerServiceTollFreeNumber != null) + writer.WriteString("lodging.customerServiceTollFreeNumber", additionalDataLodging.LodgingCustomerServiceTollFreeNumber); + + if (additionalDataLodging._LodgingFireSafetyActIndicatorOption.IsSet) + if (additionalDataLodging.LodgingFireSafetyActIndicator != null) + writer.WriteString("lodging.fireSafetyActIndicator", additionalDataLodging.LodgingFireSafetyActIndicator); + + if (additionalDataLodging._LodgingFolioCashAdvancesOption.IsSet) + if (additionalDataLodging.LodgingFolioCashAdvances != null) + writer.WriteString("lodging.folioCashAdvances", additionalDataLodging.LodgingFolioCashAdvances); + + if (additionalDataLodging._LodgingFolioNumberOption.IsSet) + if (additionalDataLodging.LodgingFolioNumber != null) + writer.WriteString("lodging.folioNumber", additionalDataLodging.LodgingFolioNumber); + + if (additionalDataLodging._LodgingFoodBeverageChargesOption.IsSet) + if (additionalDataLodging.LodgingFoodBeverageCharges != null) + writer.WriteString("lodging.foodBeverageCharges", additionalDataLodging.LodgingFoodBeverageCharges); + + if (additionalDataLodging._LodgingNoShowIndicatorOption.IsSet) + if (additionalDataLodging.LodgingNoShowIndicator != null) + writer.WriteString("lodging.noShowIndicator", additionalDataLodging.LodgingNoShowIndicator); + + if (additionalDataLodging._LodgingPrepaidExpensesOption.IsSet) + if (additionalDataLodging.LodgingPrepaidExpenses != null) + writer.WriteString("lodging.prepaidExpenses", additionalDataLodging.LodgingPrepaidExpenses); + + if (additionalDataLodging._LodgingPropertyPhoneNumberOption.IsSet) + if (additionalDataLodging.LodgingPropertyPhoneNumber != null) + writer.WriteString("lodging.propertyPhoneNumber", additionalDataLodging.LodgingPropertyPhoneNumber); + + if (additionalDataLodging._LodgingRoom1NumberOfNightsOption.IsSet) + if (additionalDataLodging.LodgingRoom1NumberOfNights != null) + writer.WriteString("lodging.room1.numberOfNights", additionalDataLodging.LodgingRoom1NumberOfNights); + + if (additionalDataLodging._LodgingRoom1RateOption.IsSet) + if (additionalDataLodging.LodgingRoom1Rate != null) + writer.WriteString("lodging.room1.rate", additionalDataLodging.LodgingRoom1Rate); + + if (additionalDataLodging._LodgingTotalRoomTaxOption.IsSet) + if (additionalDataLodging.LodgingTotalRoomTax != null) + writer.WriteString("lodging.totalRoomTax", additionalDataLodging.LodgingTotalRoomTax); + + if (additionalDataLodging._LodgingTotalTaxOption.IsSet) + if (additionalDataLodging.LodgingTotalTax != null) + writer.WriteString("lodging.totalTax", additionalDataLodging.LodgingTotalTax); + + if (additionalDataLodging._TravelEntertainmentAuthDataDurationOption.IsSet) + if (additionalDataLodging.TravelEntertainmentAuthDataDuration != null) + writer.WriteString("travelEntertainmentAuthData.duration", additionalDataLodging.TravelEntertainmentAuthDataDuration); + + if (additionalDataLodging._TravelEntertainmentAuthDataMarketOption.IsSet) + if (additionalDataLodging.TravelEntertainmentAuthDataMarket != null) + writer.WriteString("travelEntertainmentAuthData.market", additionalDataLodging.TravelEntertainmentAuthDataMarket); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataOpenInvoice.cs b/Adyen/Checkout/Models/AdditionalDataOpenInvoice.cs new file mode 100644 index 000000000..abc8b66ff --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataOpenInvoice.cs @@ -0,0 +1,602 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataOpenInvoice. + /// + public partial class AdditionalDataOpenInvoice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// The three-character ISO currency code. + /// A text description of the product the invoice line refers to. + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + /// The VAT due for one item in the invoice line, represented in minor units. + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + /// The number of units purchased of a specific product. + /// Name of the shipping company handling the the return shipment. + /// The tracking number for the return of the shipment. + /// URI where the customer can track the return of their shipment. + /// Name of the shipping company handling the delivery. + /// Shipping method. + /// The tracking number for the shipment. + /// URI where the customer can track their shipment. + [JsonConstructor] + public AdditionalDataOpenInvoice(Option openinvoicedataMerchantData = default, Option openinvoicedataNumberOfLines = default, Option openinvoicedataRecipientFirstName = default, Option openinvoicedataRecipientLastName = default, Option openinvoicedataLineItemNrCurrencyCode = default, Option openinvoicedataLineItemNrDescription = default, Option openinvoicedataLineItemNrItemAmount = default, Option openinvoicedataLineItemNrItemId = default, Option openinvoicedataLineItemNrItemVatAmount = default, Option openinvoicedataLineItemNrItemVatPercentage = default, Option openinvoicedataLineItemNrNumberOfItems = default, Option openinvoicedataLineItemNrReturnShippingCompany = default, Option openinvoicedataLineItemNrReturnTrackingNumber = default, Option openinvoicedataLineItemNrReturnTrackingUri = default, Option openinvoicedataLineItemNrShippingCompany = default, Option openinvoicedataLineItemNrShippingMethod = default, Option openinvoicedataLineItemNrTrackingNumber = default, Option openinvoicedataLineItemNrTrackingUri = default) + { + _OpeninvoicedataMerchantDataOption = openinvoicedataMerchantData; + _OpeninvoicedataNumberOfLinesOption = openinvoicedataNumberOfLines; + _OpeninvoicedataRecipientFirstNameOption = openinvoicedataRecipientFirstName; + _OpeninvoicedataRecipientLastNameOption = openinvoicedataRecipientLastName; + _OpeninvoicedataLineItemNrCurrencyCodeOption = openinvoicedataLineItemNrCurrencyCode; + _OpeninvoicedataLineItemNrDescriptionOption = openinvoicedataLineItemNrDescription; + _OpeninvoicedataLineItemNrItemAmountOption = openinvoicedataLineItemNrItemAmount; + _OpeninvoicedataLineItemNrItemIdOption = openinvoicedataLineItemNrItemId; + _OpeninvoicedataLineItemNrItemVatAmountOption = openinvoicedataLineItemNrItemVatAmount; + _OpeninvoicedataLineItemNrItemVatPercentageOption = openinvoicedataLineItemNrItemVatPercentage; + _OpeninvoicedataLineItemNrNumberOfItemsOption = openinvoicedataLineItemNrNumberOfItems; + _OpeninvoicedataLineItemNrReturnShippingCompanyOption = openinvoicedataLineItemNrReturnShippingCompany; + _OpeninvoicedataLineItemNrReturnTrackingNumberOption = openinvoicedataLineItemNrReturnTrackingNumber; + _OpeninvoicedataLineItemNrReturnTrackingUriOption = openinvoicedataLineItemNrReturnTrackingUri; + _OpeninvoicedataLineItemNrShippingCompanyOption = openinvoicedataLineItemNrShippingCompany; + _OpeninvoicedataLineItemNrShippingMethodOption = openinvoicedataLineItemNrShippingMethod; + _OpeninvoicedataLineItemNrTrackingNumberOption = openinvoicedataLineItemNrTrackingNumber; + _OpeninvoicedataLineItemNrTrackingUriOption = openinvoicedataLineItemNrTrackingUri; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataOpenInvoice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataMerchantDataOption { get; private set; } + + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + [JsonPropertyName("openinvoicedata.merchantData")] + public string? OpeninvoicedataMerchantData { get { return this._OpeninvoicedataMerchantDataOption; } set { this._OpeninvoicedataMerchantDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataNumberOfLinesOption { get; private set; } + + /// + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + /// + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + [JsonPropertyName("openinvoicedata.numberOfLines")] + public string? OpeninvoicedataNumberOfLines { get { return this._OpeninvoicedataNumberOfLinesOption; } set { this._OpeninvoicedataNumberOfLinesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataRecipientFirstNameOption { get; private set; } + + /// + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + [JsonPropertyName("openinvoicedata.recipientFirstName")] + public string? OpeninvoicedataRecipientFirstName { get { return this._OpeninvoicedataRecipientFirstNameOption; } set { this._OpeninvoicedataRecipientFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataRecipientLastNameOption { get; private set; } + + /// + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + [JsonPropertyName("openinvoicedata.recipientLastName")] + public string? OpeninvoicedataRecipientLastName { get { return this._OpeninvoicedataRecipientLastNameOption; } set { this._OpeninvoicedataRecipientLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrCurrencyCodeOption { get; private set; } + + /// + /// The three-character ISO currency code. + /// + /// The three-character ISO currency code. + [JsonPropertyName("openinvoicedataLine[itemNr].currencyCode")] + public string? OpeninvoicedataLineItemNrCurrencyCode { get { return this._OpeninvoicedataLineItemNrCurrencyCodeOption; } set { this._OpeninvoicedataLineItemNrCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrDescriptionOption { get; private set; } + + /// + /// A text description of the product the invoice line refers to. + /// + /// A text description of the product the invoice line refers to. + [JsonPropertyName("openinvoicedataLine[itemNr].description")] + public string? OpeninvoicedataLineItemNrDescription { get { return this._OpeninvoicedataLineItemNrDescriptionOption; } set { this._OpeninvoicedataLineItemNrDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemAmountOption { get; private set; } + + /// + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + /// + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + [JsonPropertyName("openinvoicedataLine[itemNr].itemAmount")] + public string? OpeninvoicedataLineItemNrItemAmount { get { return this._OpeninvoicedataLineItemNrItemAmountOption; } set { this._OpeninvoicedataLineItemNrItemAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemIdOption { get; private set; } + + /// + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + /// + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + [JsonPropertyName("openinvoicedataLine[itemNr].itemId")] + public string? OpeninvoicedataLineItemNrItemId { get { return this._OpeninvoicedataLineItemNrItemIdOption; } set { this._OpeninvoicedataLineItemNrItemIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemVatAmountOption { get; private set; } + + /// + /// The VAT due for one item in the invoice line, represented in minor units. + /// + /// The VAT due for one item in the invoice line, represented in minor units. + [JsonPropertyName("openinvoicedataLine[itemNr].itemVatAmount")] + public string? OpeninvoicedataLineItemNrItemVatAmount { get { return this._OpeninvoicedataLineItemNrItemVatAmountOption; } set { this._OpeninvoicedataLineItemNrItemVatAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemVatPercentageOption { get; private set; } + + /// + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + /// + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + [JsonPropertyName("openinvoicedataLine[itemNr].itemVatPercentage")] + public string? OpeninvoicedataLineItemNrItemVatPercentage { get { return this._OpeninvoicedataLineItemNrItemVatPercentageOption; } set { this._OpeninvoicedataLineItemNrItemVatPercentageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrNumberOfItemsOption { get; private set; } + + /// + /// The number of units purchased of a specific product. + /// + /// The number of units purchased of a specific product. + [JsonPropertyName("openinvoicedataLine[itemNr].numberOfItems")] + public string? OpeninvoicedataLineItemNrNumberOfItems { get { return this._OpeninvoicedataLineItemNrNumberOfItemsOption; } set { this._OpeninvoicedataLineItemNrNumberOfItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnShippingCompanyOption { get; private set; } + + /// + /// Name of the shipping company handling the the return shipment. + /// + /// Name of the shipping company handling the the return shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnShippingCompany")] + public string? OpeninvoicedataLineItemNrReturnShippingCompany { get { return this._OpeninvoicedataLineItemNrReturnShippingCompanyOption; } set { this._OpeninvoicedataLineItemNrReturnShippingCompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnTrackingNumberOption { get; private set; } + + /// + /// The tracking number for the return of the shipment. + /// + /// The tracking number for the return of the shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnTrackingNumber")] + public string? OpeninvoicedataLineItemNrReturnTrackingNumber { get { return this._OpeninvoicedataLineItemNrReturnTrackingNumberOption; } set { this._OpeninvoicedataLineItemNrReturnTrackingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnTrackingUriOption { get; private set; } + + /// + /// URI where the customer can track the return of their shipment. + /// + /// URI where the customer can track the return of their shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnTrackingUri")] + public string? OpeninvoicedataLineItemNrReturnTrackingUri { get { return this._OpeninvoicedataLineItemNrReturnTrackingUriOption; } set { this._OpeninvoicedataLineItemNrReturnTrackingUriOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrShippingCompanyOption { get; private set; } + + /// + /// Name of the shipping company handling the delivery. + /// + /// Name of the shipping company handling the delivery. + [JsonPropertyName("openinvoicedataLine[itemNr].shippingCompany")] + public string? OpeninvoicedataLineItemNrShippingCompany { get { return this._OpeninvoicedataLineItemNrShippingCompanyOption; } set { this._OpeninvoicedataLineItemNrShippingCompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrShippingMethodOption { get; private set; } + + /// + /// Shipping method. + /// + /// Shipping method. + [JsonPropertyName("openinvoicedataLine[itemNr].shippingMethod")] + public string? OpeninvoicedataLineItemNrShippingMethod { get { return this._OpeninvoicedataLineItemNrShippingMethodOption; } set { this._OpeninvoicedataLineItemNrShippingMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrTrackingNumberOption { get; private set; } + + /// + /// The tracking number for the shipment. + /// + /// The tracking number for the shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].trackingNumber")] + public string? OpeninvoicedataLineItemNrTrackingNumber { get { return this._OpeninvoicedataLineItemNrTrackingNumberOption; } set { this._OpeninvoicedataLineItemNrTrackingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrTrackingUriOption { get; private set; } + + /// + /// URI where the customer can track their shipment. + /// + /// URI where the customer can track their shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].trackingUri")] + public string? OpeninvoicedataLineItemNrTrackingUri { get { return this._OpeninvoicedataLineItemNrTrackingUriOption; } set { this._OpeninvoicedataLineItemNrTrackingUriOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataOpenInvoice {\n"); + sb.Append(" OpeninvoicedataMerchantData: ").Append(OpeninvoicedataMerchantData).Append("\n"); + sb.Append(" OpeninvoicedataNumberOfLines: ").Append(OpeninvoicedataNumberOfLines).Append("\n"); + sb.Append(" OpeninvoicedataRecipientFirstName: ").Append(OpeninvoicedataRecipientFirstName).Append("\n"); + sb.Append(" OpeninvoicedataRecipientLastName: ").Append(OpeninvoicedataRecipientLastName).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrCurrencyCode: ").Append(OpeninvoicedataLineItemNrCurrencyCode).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrDescription: ").Append(OpeninvoicedataLineItemNrDescription).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemAmount: ").Append(OpeninvoicedataLineItemNrItemAmount).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemId: ").Append(OpeninvoicedataLineItemNrItemId).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemVatAmount: ").Append(OpeninvoicedataLineItemNrItemVatAmount).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemVatPercentage: ").Append(OpeninvoicedataLineItemNrItemVatPercentage).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrNumberOfItems: ").Append(OpeninvoicedataLineItemNrNumberOfItems).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnShippingCompany: ").Append(OpeninvoicedataLineItemNrReturnShippingCompany).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnTrackingNumber: ").Append(OpeninvoicedataLineItemNrReturnTrackingNumber).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnTrackingUri: ").Append(OpeninvoicedataLineItemNrReturnTrackingUri).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrShippingCompany: ").Append(OpeninvoicedataLineItemNrShippingCompany).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrShippingMethod: ").Append(OpeninvoicedataLineItemNrShippingMethod).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrTrackingNumber: ").Append(OpeninvoicedataLineItemNrTrackingNumber).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrTrackingUri: ").Append(OpeninvoicedataLineItemNrTrackingUri).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataOpenInvoiceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataOpenInvoice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option openinvoicedataMerchantData = default; + Option openinvoicedataNumberOfLines = default; + Option openinvoicedataRecipientFirstName = default; + Option openinvoicedataRecipientLastName = default; + Option openinvoicedataLineItemNrCurrencyCode = default; + Option openinvoicedataLineItemNrDescription = default; + Option openinvoicedataLineItemNrItemAmount = default; + Option openinvoicedataLineItemNrItemId = default; + Option openinvoicedataLineItemNrItemVatAmount = default; + Option openinvoicedataLineItemNrItemVatPercentage = default; + Option openinvoicedataLineItemNrNumberOfItems = default; + Option openinvoicedataLineItemNrReturnShippingCompany = default; + Option openinvoicedataLineItemNrReturnTrackingNumber = default; + Option openinvoicedataLineItemNrReturnTrackingUri = default; + Option openinvoicedataLineItemNrShippingCompany = default; + Option openinvoicedataLineItemNrShippingMethod = default; + Option openinvoicedataLineItemNrTrackingNumber = default; + Option openinvoicedataLineItemNrTrackingUri = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "openinvoicedata.merchantData": + openinvoicedataMerchantData = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.numberOfLines": + openinvoicedataNumberOfLines = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.recipientFirstName": + openinvoicedataRecipientFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.recipientLastName": + openinvoicedataRecipientLastName = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].currencyCode": + openinvoicedataLineItemNrCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].description": + openinvoicedataLineItemNrDescription = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemAmount": + openinvoicedataLineItemNrItemAmount = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemId": + openinvoicedataLineItemNrItemId = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemVatAmount": + openinvoicedataLineItemNrItemVatAmount = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemVatPercentage": + openinvoicedataLineItemNrItemVatPercentage = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].numberOfItems": + openinvoicedataLineItemNrNumberOfItems = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnShippingCompany": + openinvoicedataLineItemNrReturnShippingCompany = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnTrackingNumber": + openinvoicedataLineItemNrReturnTrackingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnTrackingUri": + openinvoicedataLineItemNrReturnTrackingUri = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].shippingCompany": + openinvoicedataLineItemNrShippingCompany = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].shippingMethod": + openinvoicedataLineItemNrShippingMethod = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].trackingNumber": + openinvoicedataLineItemNrTrackingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].trackingUri": + openinvoicedataLineItemNrTrackingUri = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataOpenInvoice(openinvoicedataMerchantData, openinvoicedataNumberOfLines, openinvoicedataRecipientFirstName, openinvoicedataRecipientLastName, openinvoicedataLineItemNrCurrencyCode, openinvoicedataLineItemNrDescription, openinvoicedataLineItemNrItemAmount, openinvoicedataLineItemNrItemId, openinvoicedataLineItemNrItemVatAmount, openinvoicedataLineItemNrItemVatPercentage, openinvoicedataLineItemNrNumberOfItems, openinvoicedataLineItemNrReturnShippingCompany, openinvoicedataLineItemNrReturnTrackingNumber, openinvoicedataLineItemNrReturnTrackingUri, openinvoicedataLineItemNrShippingCompany, openinvoicedataLineItemNrShippingMethod, openinvoicedataLineItemNrTrackingNumber, openinvoicedataLineItemNrTrackingUri); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataOpenInvoice additionalDataOpenInvoice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataOpenInvoice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataOpenInvoice additionalDataOpenInvoice, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataOpenInvoice._OpeninvoicedataMerchantDataOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataMerchantData != null) + writer.WriteString("openinvoicedata.merchantData", additionalDataOpenInvoice.OpeninvoicedataMerchantData); + + if (additionalDataOpenInvoice._OpeninvoicedataNumberOfLinesOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataNumberOfLines != null) + writer.WriteString("openinvoicedata.numberOfLines", additionalDataOpenInvoice.OpeninvoicedataNumberOfLines); + + if (additionalDataOpenInvoice._OpeninvoicedataRecipientFirstNameOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataRecipientFirstName != null) + writer.WriteString("openinvoicedata.recipientFirstName", additionalDataOpenInvoice.OpeninvoicedataRecipientFirstName); + + if (additionalDataOpenInvoice._OpeninvoicedataRecipientLastNameOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataRecipientLastName != null) + writer.WriteString("openinvoicedata.recipientLastName", additionalDataOpenInvoice.OpeninvoicedataRecipientLastName); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrCurrencyCodeOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrCurrencyCode != null) + writer.WriteString("openinvoicedataLine[itemNr].currencyCode", additionalDataOpenInvoice.OpeninvoicedataLineItemNrCurrencyCode); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrDescriptionOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrDescription != null) + writer.WriteString("openinvoicedataLine[itemNr].description", additionalDataOpenInvoice.OpeninvoicedataLineItemNrDescription); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemAmountOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemAmount != null) + writer.WriteString("openinvoicedataLine[itemNr].itemAmount", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemAmount); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemIdOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemId != null) + writer.WriteString("openinvoicedataLine[itemNr].itemId", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemId); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemVatAmountOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatAmount != null) + writer.WriteString("openinvoicedataLine[itemNr].itemVatAmount", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatAmount); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemVatPercentageOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatPercentage != null) + writer.WriteString("openinvoicedataLine[itemNr].itemVatPercentage", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatPercentage); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrNumberOfItemsOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrNumberOfItems != null) + writer.WriteString("openinvoicedataLine[itemNr].numberOfItems", additionalDataOpenInvoice.OpeninvoicedataLineItemNrNumberOfItems); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnShippingCompanyOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnShippingCompany != null) + writer.WriteString("openinvoicedataLine[itemNr].returnShippingCompany", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnShippingCompany); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnTrackingNumberOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingNumber != null) + writer.WriteString("openinvoicedataLine[itemNr].returnTrackingNumber", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingNumber); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnTrackingUriOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingUri != null) + writer.WriteString("openinvoicedataLine[itemNr].returnTrackingUri", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingUri); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrShippingCompanyOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingCompany != null) + writer.WriteString("openinvoicedataLine[itemNr].shippingCompany", additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingCompany); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrShippingMethodOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingMethod != null) + writer.WriteString("openinvoicedataLine[itemNr].shippingMethod", additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingMethod); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrTrackingNumberOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingNumber != null) + writer.WriteString("openinvoicedataLine[itemNr].trackingNumber", additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingNumber); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrTrackingUriOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingUri != null) + writer.WriteString("openinvoicedataLine[itemNr].trackingUri", additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingUri); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataOpi.cs b/Adyen/Checkout/Models/AdditionalDataOpi.cs new file mode 100644 index 000000000..0aa56b553 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataOpi.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataOpi. + /// + public partial class AdditionalDataOpi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonConstructor] + public AdditionalDataOpi(Option opiIncludeTransToken = default) + { + _OpiIncludeTransTokenOption = opiIncludeTransToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataOpi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiIncludeTransTokenOption { get; private set; } + + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonPropertyName("opi.includeTransToken")] + public string? OpiIncludeTransToken { get { return this._OpiIncludeTransTokenOption; } set { this._OpiIncludeTransTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataOpi {\n"); + sb.Append(" OpiIncludeTransToken: ").Append(OpiIncludeTransToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataOpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataOpi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option opiIncludeTransToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "opi.includeTransToken": + opiIncludeTransToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataOpi(opiIncludeTransToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataOpi additionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataOpi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataOpi additionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataOpi._OpiIncludeTransTokenOption.IsSet) + if (additionalDataOpi.OpiIncludeTransToken != null) + writer.WriteString("opi.includeTransToken", additionalDataOpi.OpiIncludeTransToken); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataRatepay.cs b/Adyen/Checkout/Models/AdditionalDataRatepay.cs new file mode 100644 index 000000000..7624feda0 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataRatepay.cs @@ -0,0 +1,352 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataRatepay. + /// + public partial class AdditionalDataRatepay : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Amount the customer has to pay each month. + /// Interest rate of this installment. + /// Amount of the last installment. + /// Calendar day of the first payment. + /// Date the merchant delivered the goods to the customer. + /// Date by which the customer must settle the payment. + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + /// Identification name or number for the invoice, defined by the merchant. + [JsonConstructor] + public AdditionalDataRatepay(Option ratepayInstallmentAmount = default, Option ratepayInterestRate = default, Option ratepayLastInstallmentAmount = default, Option ratepayPaymentFirstday = default, Option ratepaydataDeliveryDate = default, Option ratepaydataDueDate = default, Option ratepaydataInvoiceDate = default, Option ratepaydataInvoiceId = default) + { + _RatepayInstallmentAmountOption = ratepayInstallmentAmount; + _RatepayInterestRateOption = ratepayInterestRate; + _RatepayLastInstallmentAmountOption = ratepayLastInstallmentAmount; + _RatepayPaymentFirstdayOption = ratepayPaymentFirstday; + _RatepaydataDeliveryDateOption = ratepaydataDeliveryDate; + _RatepaydataDueDateOption = ratepaydataDueDate; + _RatepaydataInvoiceDateOption = ratepaydataInvoiceDate; + _RatepaydataInvoiceIdOption = ratepaydataInvoiceId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRatepay() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayInstallmentAmountOption { get; private set; } + + /// + /// Amount the customer has to pay each month. + /// + /// Amount the customer has to pay each month. + [JsonPropertyName("ratepay.installmentAmount")] + public string? RatepayInstallmentAmount { get { return this._RatepayInstallmentAmountOption; } set { this._RatepayInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayInterestRateOption { get; private set; } + + /// + /// Interest rate of this installment. + /// + /// Interest rate of this installment. + [JsonPropertyName("ratepay.interestRate")] + public string? RatepayInterestRate { get { return this._RatepayInterestRateOption; } set { this._RatepayInterestRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayLastInstallmentAmountOption { get; private set; } + + /// + /// Amount of the last installment. + /// + /// Amount of the last installment. + [JsonPropertyName("ratepay.lastInstallmentAmount")] + public string? RatepayLastInstallmentAmount { get { return this._RatepayLastInstallmentAmountOption; } set { this._RatepayLastInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayPaymentFirstdayOption { get; private set; } + + /// + /// Calendar day of the first payment. + /// + /// Calendar day of the first payment. + [JsonPropertyName("ratepay.paymentFirstday")] + public string? RatepayPaymentFirstday { get { return this._RatepayPaymentFirstdayOption; } set { this._RatepayPaymentFirstdayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataDeliveryDateOption { get; private set; } + + /// + /// Date the merchant delivered the goods to the customer. + /// + /// Date the merchant delivered the goods to the customer. + [JsonPropertyName("ratepaydata.deliveryDate")] + public string? RatepaydataDeliveryDate { get { return this._RatepaydataDeliveryDateOption; } set { this._RatepaydataDeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataDueDateOption { get; private set; } + + /// + /// Date by which the customer must settle the payment. + /// + /// Date by which the customer must settle the payment. + [JsonPropertyName("ratepaydata.dueDate")] + public string? RatepaydataDueDate { get { return this._RatepaydataDueDateOption; } set { this._RatepaydataDueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataInvoiceDateOption { get; private set; } + + /// + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + /// + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + [JsonPropertyName("ratepaydata.invoiceDate")] + public string? RatepaydataInvoiceDate { get { return this._RatepaydataInvoiceDateOption; } set { this._RatepaydataInvoiceDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataInvoiceIdOption { get; private set; } + + /// + /// Identification name or number for the invoice, defined by the merchant. + /// + /// Identification name or number for the invoice, defined by the merchant. + [JsonPropertyName("ratepaydata.invoiceId")] + public string? RatepaydataInvoiceId { get { return this._RatepaydataInvoiceIdOption; } set { this._RatepaydataInvoiceIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRatepay {\n"); + sb.Append(" RatepayInstallmentAmount: ").Append(RatepayInstallmentAmount).Append("\n"); + sb.Append(" RatepayInterestRate: ").Append(RatepayInterestRate).Append("\n"); + sb.Append(" RatepayLastInstallmentAmount: ").Append(RatepayLastInstallmentAmount).Append("\n"); + sb.Append(" RatepayPaymentFirstday: ").Append(RatepayPaymentFirstday).Append("\n"); + sb.Append(" RatepaydataDeliveryDate: ").Append(RatepaydataDeliveryDate).Append("\n"); + sb.Append(" RatepaydataDueDate: ").Append(RatepaydataDueDate).Append("\n"); + sb.Append(" RatepaydataInvoiceDate: ").Append(RatepaydataInvoiceDate).Append("\n"); + sb.Append(" RatepaydataInvoiceId: ").Append(RatepaydataInvoiceId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRatepayJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRatepay Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option ratepayInstallmentAmount = default; + Option ratepayInterestRate = default; + Option ratepayLastInstallmentAmount = default; + Option ratepayPaymentFirstday = default; + Option ratepaydataDeliveryDate = default; + Option ratepaydataDueDate = default; + Option ratepaydataInvoiceDate = default; + Option ratepaydataInvoiceId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ratepay.installmentAmount": + ratepayInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.interestRate": + ratepayInterestRate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.lastInstallmentAmount": + ratepayLastInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.paymentFirstday": + ratepayPaymentFirstday = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.deliveryDate": + ratepaydataDeliveryDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.dueDate": + ratepaydataDueDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.invoiceDate": + ratepaydataInvoiceDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.invoiceId": + ratepaydataInvoiceId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRatepay(ratepayInstallmentAmount, ratepayInterestRate, ratepayLastInstallmentAmount, ratepayPaymentFirstday, ratepaydataDeliveryDate, ratepaydataDueDate, ratepaydataInvoiceDate, ratepaydataInvoiceId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRatepay additionalDataRatepay, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRatepay, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRatepay additionalDataRatepay, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRatepay._RatepayInstallmentAmountOption.IsSet) + if (additionalDataRatepay.RatepayInstallmentAmount != null) + writer.WriteString("ratepay.installmentAmount", additionalDataRatepay.RatepayInstallmentAmount); + + if (additionalDataRatepay._RatepayInterestRateOption.IsSet) + if (additionalDataRatepay.RatepayInterestRate != null) + writer.WriteString("ratepay.interestRate", additionalDataRatepay.RatepayInterestRate); + + if (additionalDataRatepay._RatepayLastInstallmentAmountOption.IsSet) + if (additionalDataRatepay.RatepayLastInstallmentAmount != null) + writer.WriteString("ratepay.lastInstallmentAmount", additionalDataRatepay.RatepayLastInstallmentAmount); + + if (additionalDataRatepay._RatepayPaymentFirstdayOption.IsSet) + if (additionalDataRatepay.RatepayPaymentFirstday != null) + writer.WriteString("ratepay.paymentFirstday", additionalDataRatepay.RatepayPaymentFirstday); + + if (additionalDataRatepay._RatepaydataDeliveryDateOption.IsSet) + if (additionalDataRatepay.RatepaydataDeliveryDate != null) + writer.WriteString("ratepaydata.deliveryDate", additionalDataRatepay.RatepaydataDeliveryDate); + + if (additionalDataRatepay._RatepaydataDueDateOption.IsSet) + if (additionalDataRatepay.RatepaydataDueDate != null) + writer.WriteString("ratepaydata.dueDate", additionalDataRatepay.RatepaydataDueDate); + + if (additionalDataRatepay._RatepaydataInvoiceDateOption.IsSet) + if (additionalDataRatepay.RatepaydataInvoiceDate != null) + writer.WriteString("ratepaydata.invoiceDate", additionalDataRatepay.RatepaydataInvoiceDate); + + if (additionalDataRatepay._RatepaydataInvoiceIdOption.IsSet) + if (additionalDataRatepay.RatepaydataInvoiceId != null) + writer.WriteString("ratepaydata.invoiceId", additionalDataRatepay.RatepaydataInvoiceId); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataRetry.cs b/Adyen/Checkout/Models/AdditionalDataRetry.cs new file mode 100644 index 000000000..724259455 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataRetry.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataRetry. + /// + public partial class AdditionalDataRetry : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonConstructor] + public AdditionalDataRetry(Option retryChainAttemptNumber = default, Option retryOrderAttemptNumber = default, Option retrySkipRetry = default) + { + _RetryChainAttemptNumberOption = retryChainAttemptNumber; + _RetryOrderAttemptNumberOption = retryOrderAttemptNumber; + _RetrySkipRetryOption = retrySkipRetry; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRetry() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetryChainAttemptNumberOption { get; private set; } + + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.chainAttemptNumber")] + public string? RetryChainAttemptNumber { get { return this._RetryChainAttemptNumberOption; } set { this._RetryChainAttemptNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetryOrderAttemptNumberOption { get; private set; } + + /// + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.orderAttemptNumber")] + public string? RetryOrderAttemptNumber { get { return this._RetryOrderAttemptNumberOption; } set { this._RetryOrderAttemptNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetrySkipRetryOption { get; private set; } + + /// + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.skipRetry")] + public string? RetrySkipRetry { get { return this._RetrySkipRetryOption; } set { this._RetrySkipRetryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRetry {\n"); + sb.Append(" RetryChainAttemptNumber: ").Append(RetryChainAttemptNumber).Append("\n"); + sb.Append(" RetryOrderAttemptNumber: ").Append(RetryOrderAttemptNumber).Append("\n"); + sb.Append(" RetrySkipRetry: ").Append(RetrySkipRetry).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRetryJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRetry Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option retryChainAttemptNumber = default; + Option retryOrderAttemptNumber = default; + Option retrySkipRetry = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "retry.chainAttemptNumber": + retryChainAttemptNumber = new Option(utf8JsonReader.GetString()!); + break; + case "retry.orderAttemptNumber": + retryOrderAttemptNumber = new Option(utf8JsonReader.GetString()!); + break; + case "retry.skipRetry": + retrySkipRetry = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRetry(retryChainAttemptNumber, retryOrderAttemptNumber, retrySkipRetry); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRetry additionalDataRetry, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRetry, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRetry additionalDataRetry, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRetry._RetryChainAttemptNumberOption.IsSet) + if (additionalDataRetry.RetryChainAttemptNumber != null) + writer.WriteString("retry.chainAttemptNumber", additionalDataRetry.RetryChainAttemptNumber); + + if (additionalDataRetry._RetryOrderAttemptNumberOption.IsSet) + if (additionalDataRetry.RetryOrderAttemptNumber != null) + writer.WriteString("retry.orderAttemptNumber", additionalDataRetry.RetryOrderAttemptNumber); + + if (additionalDataRetry._RetrySkipRetryOption.IsSet) + if (additionalDataRetry.RetrySkipRetry != null) + writer.WriteString("retry.skipRetry", additionalDataRetry.RetrySkipRetry); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataRisk.cs b/Adyen/Checkout/Models/AdditionalDataRisk.cs new file mode 100644 index 000000000..560349877 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataRisk.cs @@ -0,0 +1,677 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataRisk. + /// + public partial class AdditionalDataRisk : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// Brand of the item. + /// Category of the item. + /// Color of the item. + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// ID of the item. + /// Manufacturer of the item. + /// A text description of the product the invoice line refers to. + /// Quantity of the item purchased. + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// Size of the item. + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + /// Code of the promotion. + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + /// Name of the promotion. + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + [JsonConstructor] + public AdditionalDataRisk(Option riskdataCustomFieldName = default, Option riskdataBasketItemItemNrAmountPerItem = default, Option riskdataBasketItemItemNrBrand = default, Option riskdataBasketItemItemNrCategory = default, Option riskdataBasketItemItemNrColor = default, Option riskdataBasketItemItemNrCurrency = default, Option riskdataBasketItemItemNrItemID = default, Option riskdataBasketItemItemNrManufacturer = default, Option riskdataBasketItemItemNrProductTitle = default, Option riskdataBasketItemItemNrQuantity = default, Option riskdataBasketItemItemNrReceiverEmail = default, Option riskdataBasketItemItemNrSize = default, Option riskdataBasketItemItemNrSku = default, Option riskdataBasketItemItemNrUpc = default, Option riskdataPromotionsPromotionItemNrPromotionCode = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountAmount = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = default, Option riskdataPromotionsPromotionItemNrPromotionName = default, Option riskdataRiskProfileReference = default, Option riskdataSkipRisk = default) + { + _RiskdataCustomFieldNameOption = riskdataCustomFieldName; + _RiskdataBasketItemItemNrAmountPerItemOption = riskdataBasketItemItemNrAmountPerItem; + _RiskdataBasketItemItemNrBrandOption = riskdataBasketItemItemNrBrand; + _RiskdataBasketItemItemNrCategoryOption = riskdataBasketItemItemNrCategory; + _RiskdataBasketItemItemNrColorOption = riskdataBasketItemItemNrColor; + _RiskdataBasketItemItemNrCurrencyOption = riskdataBasketItemItemNrCurrency; + _RiskdataBasketItemItemNrItemIDOption = riskdataBasketItemItemNrItemID; + _RiskdataBasketItemItemNrManufacturerOption = riskdataBasketItemItemNrManufacturer; + _RiskdataBasketItemItemNrProductTitleOption = riskdataBasketItemItemNrProductTitle; + _RiskdataBasketItemItemNrQuantityOption = riskdataBasketItemItemNrQuantity; + _RiskdataBasketItemItemNrReceiverEmailOption = riskdataBasketItemItemNrReceiverEmail; + _RiskdataBasketItemItemNrSizeOption = riskdataBasketItemItemNrSize; + _RiskdataBasketItemItemNrSkuOption = riskdataBasketItemItemNrSku; + _RiskdataBasketItemItemNrUpcOption = riskdataBasketItemItemNrUpc; + _RiskdataPromotionsPromotionItemNrPromotionCodeOption = riskdataPromotionsPromotionItemNrPromotionCode; + _RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption = riskdataPromotionsPromotionItemNrPromotionDiscountAmount; + _RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption = riskdataPromotionsPromotionItemNrPromotionDiscountCurrency; + _RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption = riskdataPromotionsPromotionItemNrPromotionDiscountPercentage; + _RiskdataPromotionsPromotionItemNrPromotionNameOption = riskdataPromotionsPromotionItemNrPromotionName; + _RiskdataRiskProfileReferenceOption = riskdataRiskProfileReference; + _RiskdataSkipRiskOption = riskdataSkipRisk; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRisk() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataCustomFieldNameOption { get; private set; } + + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + [JsonPropertyName("riskdata.[customFieldName]")] + public string? RiskdataCustomFieldName { get { return this._RiskdataCustomFieldNameOption; } set { this._RiskdataCustomFieldNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrAmountPerItemOption { get; private set; } + + /// + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("riskdata.basket.item[itemNr].amountPerItem")] + public string? RiskdataBasketItemItemNrAmountPerItem { get { return this._RiskdataBasketItemItemNrAmountPerItemOption; } set { this._RiskdataBasketItemItemNrAmountPerItemOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrBrandOption { get; private set; } + + /// + /// Brand of the item. + /// + /// Brand of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].brand")] + public string? RiskdataBasketItemItemNrBrand { get { return this._RiskdataBasketItemItemNrBrandOption; } set { this._RiskdataBasketItemItemNrBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrCategoryOption { get; private set; } + + /// + /// Category of the item. + /// + /// Category of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].category")] + public string? RiskdataBasketItemItemNrCategory { get { return this._RiskdataBasketItemItemNrCategoryOption; } set { this._RiskdataBasketItemItemNrCategoryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrColorOption { get; private set; } + + /// + /// Color of the item. + /// + /// Color of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].color")] + public string? RiskdataBasketItemItemNrColor { get { return this._RiskdataBasketItemItemNrColorOption; } set { this._RiskdataBasketItemItemNrColorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrCurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("riskdata.basket.item[itemNr].currency")] + public string? RiskdataBasketItemItemNrCurrency { get { return this._RiskdataBasketItemItemNrCurrencyOption; } set { this._RiskdataBasketItemItemNrCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrItemIDOption { get; private set; } + + /// + /// ID of the item. + /// + /// ID of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].itemID")] + public string? RiskdataBasketItemItemNrItemID { get { return this._RiskdataBasketItemItemNrItemIDOption; } set { this._RiskdataBasketItemItemNrItemIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrManufacturerOption { get; private set; } + + /// + /// Manufacturer of the item. + /// + /// Manufacturer of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].manufacturer")] + public string? RiskdataBasketItemItemNrManufacturer { get { return this._RiskdataBasketItemItemNrManufacturerOption; } set { this._RiskdataBasketItemItemNrManufacturerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrProductTitleOption { get; private set; } + + /// + /// A text description of the product the invoice line refers to. + /// + /// A text description of the product the invoice line refers to. + [JsonPropertyName("riskdata.basket.item[itemNr].productTitle")] + public string? RiskdataBasketItemItemNrProductTitle { get { return this._RiskdataBasketItemItemNrProductTitleOption; } set { this._RiskdataBasketItemItemNrProductTitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrQuantityOption { get; private set; } + + /// + /// Quantity of the item purchased. + /// + /// Quantity of the item purchased. + [JsonPropertyName("riskdata.basket.item[itemNr].quantity")] + public string? RiskdataBasketItemItemNrQuantity { get { return this._RiskdataBasketItemItemNrQuantityOption; } set { this._RiskdataBasketItemItemNrQuantityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrReceiverEmailOption { get; private set; } + + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + [JsonPropertyName("riskdata.basket.item[itemNr].receiverEmail")] + public string? RiskdataBasketItemItemNrReceiverEmail { get { return this._RiskdataBasketItemItemNrReceiverEmailOption; } set { this._RiskdataBasketItemItemNrReceiverEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrSizeOption { get; private set; } + + /// + /// Size of the item. + /// + /// Size of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].size")] + public string? RiskdataBasketItemItemNrSize { get { return this._RiskdataBasketItemItemNrSizeOption; } set { this._RiskdataBasketItemItemNrSizeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrSkuOption { get; private set; } + + /// + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + /// + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + [JsonPropertyName("riskdata.basket.item[itemNr].sku")] + public string? RiskdataBasketItemItemNrSku { get { return this._RiskdataBasketItemItemNrSkuOption; } set { this._RiskdataBasketItemItemNrSkuOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrUpcOption { get; private set; } + + /// + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + /// + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + [JsonPropertyName("riskdata.basket.item[itemNr].upc")] + public string? RiskdataBasketItemItemNrUpc { get { return this._RiskdataBasketItemItemNrUpcOption; } set { this._RiskdataBasketItemItemNrUpcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionCodeOption { get; private set; } + + /// + /// Code of the promotion. + /// + /// Code of the promotion. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionCode")] + public string? RiskdataPromotionsPromotionItemNrPromotionCode { get { return this._RiskdataPromotionsPromotionItemNrPromotionCodeOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption { get; private set; } + + /// + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountAmount")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountAmount { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountCurrency")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption { get; private set; } + + /// + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + /// + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountPercentage")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionNameOption { get; private set; } + + /// + /// Name of the promotion. + /// + /// Name of the promotion. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionName")] + public string? RiskdataPromotionsPromotionItemNrPromotionName { get { return this._RiskdataPromotionsPromotionItemNrPromotionNameOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataRiskProfileReferenceOption { get; private set; } + + /// + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + /// + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + [JsonPropertyName("riskdata.riskProfileReference")] + public string? RiskdataRiskProfileReference { get { return this._RiskdataRiskProfileReferenceOption; } set { this._RiskdataRiskProfileReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataSkipRiskOption { get; private set; } + + /// + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + /// + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + [JsonPropertyName("riskdata.skipRisk")] + public string? RiskdataSkipRisk { get { return this._RiskdataSkipRiskOption; } set { this._RiskdataSkipRiskOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRisk {\n"); + sb.Append(" RiskdataCustomFieldName: ").Append(RiskdataCustomFieldName).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrAmountPerItem: ").Append(RiskdataBasketItemItemNrAmountPerItem).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrBrand: ").Append(RiskdataBasketItemItemNrBrand).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrCategory: ").Append(RiskdataBasketItemItemNrCategory).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrColor: ").Append(RiskdataBasketItemItemNrColor).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrCurrency: ").Append(RiskdataBasketItemItemNrCurrency).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrItemID: ").Append(RiskdataBasketItemItemNrItemID).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrManufacturer: ").Append(RiskdataBasketItemItemNrManufacturer).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrProductTitle: ").Append(RiskdataBasketItemItemNrProductTitle).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrQuantity: ").Append(RiskdataBasketItemItemNrQuantity).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrReceiverEmail: ").Append(RiskdataBasketItemItemNrReceiverEmail).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrSize: ").Append(RiskdataBasketItemItemNrSize).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrSku: ").Append(RiskdataBasketItemItemNrSku).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrUpc: ").Append(RiskdataBasketItemItemNrUpc).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionCode: ").Append(RiskdataPromotionsPromotionItemNrPromotionCode).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountAmount: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountAmount).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionName: ").Append(RiskdataPromotionsPromotionItemNrPromotionName).Append("\n"); + sb.Append(" RiskdataRiskProfileReference: ").Append(RiskdataRiskProfileReference).Append("\n"); + sb.Append(" RiskdataSkipRisk: ").Append(RiskdataSkipRisk).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRiskJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRisk Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option riskdataCustomFieldName = default; + Option riskdataBasketItemItemNrAmountPerItem = default; + Option riskdataBasketItemItemNrBrand = default; + Option riskdataBasketItemItemNrCategory = default; + Option riskdataBasketItemItemNrColor = default; + Option riskdataBasketItemItemNrCurrency = default; + Option riskdataBasketItemItemNrItemID = default; + Option riskdataBasketItemItemNrManufacturer = default; + Option riskdataBasketItemItemNrProductTitle = default; + Option riskdataBasketItemItemNrQuantity = default; + Option riskdataBasketItemItemNrReceiverEmail = default; + Option riskdataBasketItemItemNrSize = default; + Option riskdataBasketItemItemNrSku = default; + Option riskdataBasketItemItemNrUpc = default; + Option riskdataPromotionsPromotionItemNrPromotionCode = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountAmount = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = default; + Option riskdataPromotionsPromotionItemNrPromotionName = default; + Option riskdataRiskProfileReference = default; + Option riskdataSkipRisk = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "riskdata.[customFieldName]": + riskdataCustomFieldName = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].amountPerItem": + riskdataBasketItemItemNrAmountPerItem = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].brand": + riskdataBasketItemItemNrBrand = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].category": + riskdataBasketItemItemNrCategory = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].color": + riskdataBasketItemItemNrColor = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].currency": + riskdataBasketItemItemNrCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].itemID": + riskdataBasketItemItemNrItemID = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].manufacturer": + riskdataBasketItemItemNrManufacturer = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].productTitle": + riskdataBasketItemItemNrProductTitle = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].quantity": + riskdataBasketItemItemNrQuantity = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].receiverEmail": + riskdataBasketItemItemNrReceiverEmail = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].size": + riskdataBasketItemItemNrSize = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].sku": + riskdataBasketItemItemNrSku = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].upc": + riskdataBasketItemItemNrUpc = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionCode": + riskdataPromotionsPromotionItemNrPromotionCode = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountAmount": + riskdataPromotionsPromotionItemNrPromotionDiscountAmount = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountCurrency": + riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountPercentage": + riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionName": + riskdataPromotionsPromotionItemNrPromotionName = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.riskProfileReference": + riskdataRiskProfileReference = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.skipRisk": + riskdataSkipRisk = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRisk(riskdataCustomFieldName, riskdataBasketItemItemNrAmountPerItem, riskdataBasketItemItemNrBrand, riskdataBasketItemItemNrCategory, riskdataBasketItemItemNrColor, riskdataBasketItemItemNrCurrency, riskdataBasketItemItemNrItemID, riskdataBasketItemItemNrManufacturer, riskdataBasketItemItemNrProductTitle, riskdataBasketItemItemNrQuantity, riskdataBasketItemItemNrReceiverEmail, riskdataBasketItemItemNrSize, riskdataBasketItemItemNrSku, riskdataBasketItemItemNrUpc, riskdataPromotionsPromotionItemNrPromotionCode, riskdataPromotionsPromotionItemNrPromotionDiscountAmount, riskdataPromotionsPromotionItemNrPromotionDiscountCurrency, riskdataPromotionsPromotionItemNrPromotionDiscountPercentage, riskdataPromotionsPromotionItemNrPromotionName, riskdataRiskProfileReference, riskdataSkipRisk); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRisk additionalDataRisk, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRisk, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRisk additionalDataRisk, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRisk._RiskdataCustomFieldNameOption.IsSet) + if (additionalDataRisk.RiskdataCustomFieldName != null) + writer.WriteString("riskdata.[customFieldName]", additionalDataRisk.RiskdataCustomFieldName); + + if (additionalDataRisk._RiskdataBasketItemItemNrAmountPerItemOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrAmountPerItem != null) + writer.WriteString("riskdata.basket.item[itemNr].amountPerItem", additionalDataRisk.RiskdataBasketItemItemNrAmountPerItem); + + if (additionalDataRisk._RiskdataBasketItemItemNrBrandOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrBrand != null) + writer.WriteString("riskdata.basket.item[itemNr].brand", additionalDataRisk.RiskdataBasketItemItemNrBrand); + + if (additionalDataRisk._RiskdataBasketItemItemNrCategoryOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrCategory != null) + writer.WriteString("riskdata.basket.item[itemNr].category", additionalDataRisk.RiskdataBasketItemItemNrCategory); + + if (additionalDataRisk._RiskdataBasketItemItemNrColorOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrColor != null) + writer.WriteString("riskdata.basket.item[itemNr].color", additionalDataRisk.RiskdataBasketItemItemNrColor); + + if (additionalDataRisk._RiskdataBasketItemItemNrCurrencyOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrCurrency != null) + writer.WriteString("riskdata.basket.item[itemNr].currency", additionalDataRisk.RiskdataBasketItemItemNrCurrency); + + if (additionalDataRisk._RiskdataBasketItemItemNrItemIDOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrItemID != null) + writer.WriteString("riskdata.basket.item[itemNr].itemID", additionalDataRisk.RiskdataBasketItemItemNrItemID); + + if (additionalDataRisk._RiskdataBasketItemItemNrManufacturerOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrManufacturer != null) + writer.WriteString("riskdata.basket.item[itemNr].manufacturer", additionalDataRisk.RiskdataBasketItemItemNrManufacturer); + + if (additionalDataRisk._RiskdataBasketItemItemNrProductTitleOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrProductTitle != null) + writer.WriteString("riskdata.basket.item[itemNr].productTitle", additionalDataRisk.RiskdataBasketItemItemNrProductTitle); + + if (additionalDataRisk._RiskdataBasketItemItemNrQuantityOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrQuantity != null) + writer.WriteString("riskdata.basket.item[itemNr].quantity", additionalDataRisk.RiskdataBasketItemItemNrQuantity); + + if (additionalDataRisk._RiskdataBasketItemItemNrReceiverEmailOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrReceiverEmail != null) + writer.WriteString("riskdata.basket.item[itemNr].receiverEmail", additionalDataRisk.RiskdataBasketItemItemNrReceiverEmail); + + if (additionalDataRisk._RiskdataBasketItemItemNrSizeOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrSize != null) + writer.WriteString("riskdata.basket.item[itemNr].size", additionalDataRisk.RiskdataBasketItemItemNrSize); + + if (additionalDataRisk._RiskdataBasketItemItemNrSkuOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrSku != null) + writer.WriteString("riskdata.basket.item[itemNr].sku", additionalDataRisk.RiskdataBasketItemItemNrSku); + + if (additionalDataRisk._RiskdataBasketItemItemNrUpcOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrUpc != null) + writer.WriteString("riskdata.basket.item[itemNr].upc", additionalDataRisk.RiskdataBasketItemItemNrUpc); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionCodeOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionCode != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionCode", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionCode); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountAmount != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountAmount", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountAmount); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountCurrency", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountPercentage", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionNameOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionName != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionName", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionName); + + if (additionalDataRisk._RiskdataRiskProfileReferenceOption.IsSet) + if (additionalDataRisk.RiskdataRiskProfileReference != null) + writer.WriteString("riskdata.riskProfileReference", additionalDataRisk.RiskdataRiskProfileReference); + + if (additionalDataRisk._RiskdataSkipRiskOption.IsSet) + if (additionalDataRisk.RiskdataSkipRisk != null) + writer.WriteString("riskdata.skipRisk", additionalDataRisk.RiskdataSkipRisk); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataRiskStandalone.cs b/Adyen/Checkout/Models/AdditionalDataRiskStandalone.cs new file mode 100644 index 000000000..d68897de3 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataRiskStandalone.cs @@ -0,0 +1,527 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataRiskStandalone. + /// + public partial class AdditionalDataRiskStandalone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + /// Shopper's email. + /// Shopper's first name. + /// Shopper's last name. + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + /// Shopper's phone number. + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + /// Unique transaction ID of the payment. + /// Raw AVS result received from the acquirer, where available. Example: D + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + /// Raw CVC result received from the acquirer, where available. Example: 1 + /// Unique identifier or token for the shopper's card details. + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// Required for PayPal payments only. The only supported value is: **paypal**. + [JsonConstructor] + public AdditionalDataRiskStandalone(Option payPalCountryCode = default, Option payPalEmailId = default, Option payPalFirstName = default, Option payPalLastName = default, Option payPalPayerId = default, Option payPalPhone = default, Option payPalProtectionEligibility = default, Option payPalTransactionId = default, Option avsResultRaw = default, Option bin = default, Option cvcResultRaw = default, Option riskToken = default, Option threeDAuthenticated = default, Option threeDOffered = default, Option tokenDataType = default) + { + _PayPalCountryCodeOption = payPalCountryCode; + _PayPalEmailIdOption = payPalEmailId; + _PayPalFirstNameOption = payPalFirstName; + _PayPalLastNameOption = payPalLastName; + _PayPalPayerIdOption = payPalPayerId; + _PayPalPhoneOption = payPalPhone; + _PayPalProtectionEligibilityOption = payPalProtectionEligibility; + _PayPalTransactionIdOption = payPalTransactionId; + _AvsResultRawOption = avsResultRaw; + _BinOption = bin; + _CvcResultRawOption = cvcResultRaw; + _RiskTokenOption = riskToken; + _ThreeDAuthenticatedOption = threeDAuthenticated; + _ThreeDOfferedOption = threeDOffered; + _TokenDataTypeOption = tokenDataType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRiskStandalone() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalCountryCodeOption { get; private set; } + + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + [JsonPropertyName("PayPal.CountryCode")] + public string? PayPalCountryCode { get { return this._PayPalCountryCodeOption; } set { this._PayPalCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalEmailIdOption { get; private set; } + + /// + /// Shopper's email. + /// + /// Shopper's email. + [JsonPropertyName("PayPal.EmailId")] + public string? PayPalEmailId { get { return this._PayPalEmailIdOption; } set { this._PayPalEmailIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalFirstNameOption { get; private set; } + + /// + /// Shopper's first name. + /// + /// Shopper's first name. + [JsonPropertyName("PayPal.FirstName")] + public string? PayPalFirstName { get { return this._PayPalFirstNameOption; } set { this._PayPalFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalLastNameOption { get; private set; } + + /// + /// Shopper's last name. + /// + /// Shopper's last name. + [JsonPropertyName("PayPal.LastName")] + public string? PayPalLastName { get { return this._PayPalLastNameOption; } set { this._PayPalLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalPayerIdOption { get; private set; } + + /// + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + /// + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + [JsonPropertyName("PayPal.PayerId")] + public string? PayPalPayerId { get { return this._PayPalPayerIdOption; } set { this._PayPalPayerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalPhoneOption { get; private set; } + + /// + /// Shopper's phone number. + /// + /// Shopper's phone number. + [JsonPropertyName("PayPal.Phone")] + public string? PayPalPhone { get { return this._PayPalPhoneOption; } set { this._PayPalPhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalProtectionEligibilityOption { get; private set; } + + /// + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + /// + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + [JsonPropertyName("PayPal.ProtectionEligibility")] + public string? PayPalProtectionEligibility { get { return this._PayPalProtectionEligibilityOption; } set { this._PayPalProtectionEligibilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalTransactionIdOption { get; private set; } + + /// + /// Unique transaction ID of the payment. + /// + /// Unique transaction ID of the payment. + [JsonPropertyName("PayPal.TransactionId")] + public string? PayPalTransactionId { get { return this._PayPalTransactionIdOption; } set { this._PayPalTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultRawOption { get; private set; } + + /// + /// Raw AVS result received from the acquirer, where available. Example: D + /// + /// Raw AVS result received from the acquirer, where available. Example: D + [JsonPropertyName("avsResultRaw")] + public string? AvsResultRaw { get { return this._AvsResultRawOption; } set { this._AvsResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinOption { get; private set; } + + /// + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + /// + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + [JsonPropertyName("bin")] + public string? Bin { get { return this._BinOption; } set { this._BinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultRawOption { get; private set; } + + /// + /// Raw CVC result received from the acquirer, where available. Example: 1 + /// + /// Raw CVC result received from the acquirer, where available. Example: 1 + [JsonPropertyName("cvcResultRaw")] + public string? CvcResultRaw { get { return this._CvcResultRawOption; } set { this._CvcResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskTokenOption { get; private set; } + + /// + /// Unique identifier or token for the shopper's card details. + /// + /// Unique identifier or token for the shopper's card details. + [JsonPropertyName("riskToken")] + public string? RiskToken { get { return this._RiskTokenOption; } set { this._RiskTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + [JsonPropertyName("threeDAuthenticated")] + public string? ThreeDAuthenticated { get { return this._ThreeDAuthenticatedOption; } set { this._ThreeDAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + [JsonPropertyName("threeDOffered")] + public string? ThreeDOffered { get { return this._ThreeDOfferedOption; } set { this._ThreeDOfferedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenDataTypeOption { get; private set; } + + /// + /// Required for PayPal payments only. The only supported value is: **paypal**. + /// + /// Required for PayPal payments only. The only supported value is: **paypal**. + [JsonPropertyName("tokenDataType")] + public string? TokenDataType { get { return this._TokenDataTypeOption; } set { this._TokenDataTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRiskStandalone {\n"); + sb.Append(" PayPalCountryCode: ").Append(PayPalCountryCode).Append("\n"); + sb.Append(" PayPalEmailId: ").Append(PayPalEmailId).Append("\n"); + sb.Append(" PayPalFirstName: ").Append(PayPalFirstName).Append("\n"); + sb.Append(" PayPalLastName: ").Append(PayPalLastName).Append("\n"); + sb.Append(" PayPalPayerId: ").Append(PayPalPayerId).Append("\n"); + sb.Append(" PayPalPhone: ").Append(PayPalPhone).Append("\n"); + sb.Append(" PayPalProtectionEligibility: ").Append(PayPalProtectionEligibility).Append("\n"); + sb.Append(" PayPalTransactionId: ").Append(PayPalTransactionId).Append("\n"); + sb.Append(" AvsResultRaw: ").Append(AvsResultRaw).Append("\n"); + sb.Append(" Bin: ").Append(Bin).Append("\n"); + sb.Append(" CvcResultRaw: ").Append(CvcResultRaw).Append("\n"); + sb.Append(" RiskToken: ").Append(RiskToken).Append("\n"); + sb.Append(" ThreeDAuthenticated: ").Append(ThreeDAuthenticated).Append("\n"); + sb.Append(" ThreeDOffered: ").Append(ThreeDOffered).Append("\n"); + sb.Append(" TokenDataType: ").Append(TokenDataType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRiskStandaloneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRiskStandalone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option payPalCountryCode = default; + Option payPalEmailId = default; + Option payPalFirstName = default; + Option payPalLastName = default; + Option payPalPayerId = default; + Option payPalPhone = default; + Option payPalProtectionEligibility = default; + Option payPalTransactionId = default; + Option avsResultRaw = default; + Option bin = default; + Option cvcResultRaw = default; + Option riskToken = default; + Option threeDAuthenticated = default; + Option threeDOffered = default; + Option tokenDataType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "PayPal.CountryCode": + payPalCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.EmailId": + payPalEmailId = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.FirstName": + payPalFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.LastName": + payPalLastName = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.PayerId": + payPalPayerId = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.Phone": + payPalPhone = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.ProtectionEligibility": + payPalProtectionEligibility = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.TransactionId": + payPalTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "avsResultRaw": + avsResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "bin": + bin = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResultRaw": + cvcResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "riskToken": + riskToken = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticated": + threeDAuthenticated = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOffered": + threeDOffered = new Option(utf8JsonReader.GetString()!); + break; + case "tokenDataType": + tokenDataType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRiskStandalone(payPalCountryCode, payPalEmailId, payPalFirstName, payPalLastName, payPalPayerId, payPalPhone, payPalProtectionEligibility, payPalTransactionId, avsResultRaw, bin, cvcResultRaw, riskToken, threeDAuthenticated, threeDOffered, tokenDataType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRiskStandalone additionalDataRiskStandalone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRiskStandalone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRiskStandalone additionalDataRiskStandalone, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRiskStandalone._PayPalCountryCodeOption.IsSet) + if (additionalDataRiskStandalone.PayPalCountryCode != null) + writer.WriteString("PayPal.CountryCode", additionalDataRiskStandalone.PayPalCountryCode); + + if (additionalDataRiskStandalone._PayPalEmailIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalEmailId != null) + writer.WriteString("PayPal.EmailId", additionalDataRiskStandalone.PayPalEmailId); + + if (additionalDataRiskStandalone._PayPalFirstNameOption.IsSet) + if (additionalDataRiskStandalone.PayPalFirstName != null) + writer.WriteString("PayPal.FirstName", additionalDataRiskStandalone.PayPalFirstName); + + if (additionalDataRiskStandalone._PayPalLastNameOption.IsSet) + if (additionalDataRiskStandalone.PayPalLastName != null) + writer.WriteString("PayPal.LastName", additionalDataRiskStandalone.PayPalLastName); + + if (additionalDataRiskStandalone._PayPalPayerIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalPayerId != null) + writer.WriteString("PayPal.PayerId", additionalDataRiskStandalone.PayPalPayerId); + + if (additionalDataRiskStandalone._PayPalPhoneOption.IsSet) + if (additionalDataRiskStandalone.PayPalPhone != null) + writer.WriteString("PayPal.Phone", additionalDataRiskStandalone.PayPalPhone); + + if (additionalDataRiskStandalone._PayPalProtectionEligibilityOption.IsSet) + if (additionalDataRiskStandalone.PayPalProtectionEligibility != null) + writer.WriteString("PayPal.ProtectionEligibility", additionalDataRiskStandalone.PayPalProtectionEligibility); + + if (additionalDataRiskStandalone._PayPalTransactionIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalTransactionId != null) + writer.WriteString("PayPal.TransactionId", additionalDataRiskStandalone.PayPalTransactionId); + + if (additionalDataRiskStandalone._AvsResultRawOption.IsSet) + if (additionalDataRiskStandalone.AvsResultRaw != null) + writer.WriteString("avsResultRaw", additionalDataRiskStandalone.AvsResultRaw); + + if (additionalDataRiskStandalone._BinOption.IsSet) + if (additionalDataRiskStandalone.Bin != null) + writer.WriteString("bin", additionalDataRiskStandalone.Bin); + + if (additionalDataRiskStandalone._CvcResultRawOption.IsSet) + if (additionalDataRiskStandalone.CvcResultRaw != null) + writer.WriteString("cvcResultRaw", additionalDataRiskStandalone.CvcResultRaw); + + if (additionalDataRiskStandalone._RiskTokenOption.IsSet) + if (additionalDataRiskStandalone.RiskToken != null) + writer.WriteString("riskToken", additionalDataRiskStandalone.RiskToken); + + if (additionalDataRiskStandalone._ThreeDAuthenticatedOption.IsSet) + if (additionalDataRiskStandalone.ThreeDAuthenticated != null) + writer.WriteString("threeDAuthenticated", additionalDataRiskStandalone.ThreeDAuthenticated); + + if (additionalDataRiskStandalone._ThreeDOfferedOption.IsSet) + if (additionalDataRiskStandalone.ThreeDOffered != null) + writer.WriteString("threeDOffered", additionalDataRiskStandalone.ThreeDOffered); + + if (additionalDataRiskStandalone._TokenDataTypeOption.IsSet) + if (additionalDataRiskStandalone.TokenDataType != null) + writer.WriteString("tokenDataType", additionalDataRiskStandalone.TokenDataType); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataSubMerchant.cs b/Adyen/Checkout/Models/AdditionalDataSubMerchant.cs new file mode 100644 index 000000000..e2ddd5d39 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataSubMerchant.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataSubMerchant. + /// + public partial class AdditionalDataSubMerchant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonConstructor] + public AdditionalDataSubMerchant(Option subMerchantNumberOfSubSellers = default, Option subMerchantSubSellerSubSellerNrCity = default, Option subMerchantSubSellerSubSellerNrCountry = default, Option subMerchantSubSellerSubSellerNrEmail = default, Option subMerchantSubSellerSubSellerNrId = default, Option subMerchantSubSellerSubSellerNrMcc = default, Option subMerchantSubSellerSubSellerNrName = default, Option subMerchantSubSellerSubSellerNrPhoneNumber = default, Option subMerchantSubSellerSubSellerNrPostalCode = default, Option subMerchantSubSellerSubSellerNrState = default, Option subMerchantSubSellerSubSellerNrStreet = default, Option subMerchantSubSellerSubSellerNrTaxId = default) + { + _SubMerchantNumberOfSubSellersOption = subMerchantNumberOfSubSellers; + _SubMerchantSubSellerSubSellerNrCityOption = subMerchantSubSellerSubSellerNrCity; + _SubMerchantSubSellerSubSellerNrCountryOption = subMerchantSubSellerSubSellerNrCountry; + _SubMerchantSubSellerSubSellerNrEmailOption = subMerchantSubSellerSubSellerNrEmail; + _SubMerchantSubSellerSubSellerNrIdOption = subMerchantSubSellerSubSellerNrId; + _SubMerchantSubSellerSubSellerNrMccOption = subMerchantSubSellerSubSellerNrMcc; + _SubMerchantSubSellerSubSellerNrNameOption = subMerchantSubSellerSubSellerNrName; + _SubMerchantSubSellerSubSellerNrPhoneNumberOption = subMerchantSubSellerSubSellerNrPhoneNumber; + _SubMerchantSubSellerSubSellerNrPostalCodeOption = subMerchantSubSellerSubSellerNrPostalCode; + _SubMerchantSubSellerSubSellerNrStateOption = subMerchantSubSellerSubSellerNrState; + _SubMerchantSubSellerSubSellerNrStreetOption = subMerchantSubSellerSubSellerNrStreet; + _SubMerchantSubSellerSubSellerNrTaxIdOption = subMerchantSubSellerSubSellerNrTaxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataSubMerchant() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantNumberOfSubSellersOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + [JsonPropertyName("subMerchant.numberOfSubSellers")] + public string? SubMerchantNumberOfSubSellers { get { return this._SubMerchantNumberOfSubSellersOption; } set { this._SubMerchantNumberOfSubSellersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrCityOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].city")] + public string? SubMerchantSubSellerSubSellerNrCity { get { return this._SubMerchantSubSellerSubSellerNrCityOption; } set { this._SubMerchantSubSellerSubSellerNrCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrCountryOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].country")] + public string? SubMerchantSubSellerSubSellerNrCountry { get { return this._SubMerchantSubSellerSubSellerNrCountryOption; } set { this._SubMerchantSubSellerSubSellerNrCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrEmailOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].email")] + public string? SubMerchantSubSellerSubSellerNrEmail { get { return this._SubMerchantSubSellerSubSellerNrEmailOption; } set { this._SubMerchantSubSellerSubSellerNrEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrIdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].id")] + public string? SubMerchantSubSellerSubSellerNrId { get { return this._SubMerchantSubSellerSubSellerNrIdOption; } set { this._SubMerchantSubSellerSubSellerNrIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrMccOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("subMerchant.subSeller[subSellerNr].mcc")] + public string? SubMerchantSubSellerSubSellerNrMcc { get { return this._SubMerchantSubSellerSubSellerNrMccOption; } set { this._SubMerchantSubSellerSubSellerNrMccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrNameOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].name")] + public string? SubMerchantSubSellerSubSellerNrName { get { return this._SubMerchantSubSellerSubSellerNrNameOption; } set { this._SubMerchantSubSellerSubSellerNrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrPhoneNumberOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + /// + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].phoneNumber")] + public string? SubMerchantSubSellerSubSellerNrPhoneNumber { get { return this._SubMerchantSubSellerSubSellerNrPhoneNumberOption; } set { this._SubMerchantSubSellerSubSellerNrPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrPostalCodeOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + /// + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + [JsonPropertyName("subMerchant.subSeller[subSellerNr].postalCode")] + public string? SubMerchantSubSellerSubSellerNrPostalCode { get { return this._SubMerchantSubSellerSubSellerNrPostalCodeOption; } set { this._SubMerchantSubSellerSubSellerNrPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrStateOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + /// + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].state")] + public string? SubMerchantSubSellerSubSellerNrState { get { return this._SubMerchantSubSellerSubSellerNrStateOption; } set { this._SubMerchantSubSellerSubSellerNrStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrStreetOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + /// + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].street")] + public string? SubMerchantSubSellerSubSellerNrStreet { get { return this._SubMerchantSubSellerSubSellerNrStreetOption; } set { this._SubMerchantSubSellerSubSellerNrStreetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrTaxIdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonPropertyName("subMerchant.subSeller[subSellerNr].taxId")] + public string? SubMerchantSubSellerSubSellerNrTaxId { get { return this._SubMerchantSubSellerSubSellerNrTaxIdOption; } set { this._SubMerchantSubSellerSubSellerNrTaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataSubMerchant {\n"); + sb.Append(" SubMerchantNumberOfSubSellers: ").Append(SubMerchantNumberOfSubSellers).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrCity: ").Append(SubMerchantSubSellerSubSellerNrCity).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrCountry: ").Append(SubMerchantSubSellerSubSellerNrCountry).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrEmail: ").Append(SubMerchantSubSellerSubSellerNrEmail).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrId: ").Append(SubMerchantSubSellerSubSellerNrId).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrMcc: ").Append(SubMerchantSubSellerSubSellerNrMcc).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrName: ").Append(SubMerchantSubSellerSubSellerNrName).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrPhoneNumber: ").Append(SubMerchantSubSellerSubSellerNrPhoneNumber).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrPostalCode: ").Append(SubMerchantSubSellerSubSellerNrPostalCode).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrState: ").Append(SubMerchantSubSellerSubSellerNrState).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrStreet: ").Append(SubMerchantSubSellerSubSellerNrStreet).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrTaxId: ").Append(SubMerchantSubSellerSubSellerNrTaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataSubMerchantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataSubMerchant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option subMerchantNumberOfSubSellers = default; + Option subMerchantSubSellerSubSellerNrCity = default; + Option subMerchantSubSellerSubSellerNrCountry = default; + Option subMerchantSubSellerSubSellerNrEmail = default; + Option subMerchantSubSellerSubSellerNrId = default; + Option subMerchantSubSellerSubSellerNrMcc = default; + Option subMerchantSubSellerSubSellerNrName = default; + Option subMerchantSubSellerSubSellerNrPhoneNumber = default; + Option subMerchantSubSellerSubSellerNrPostalCode = default; + Option subMerchantSubSellerSubSellerNrState = default; + Option subMerchantSubSellerSubSellerNrStreet = default; + Option subMerchantSubSellerSubSellerNrTaxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "subMerchant.numberOfSubSellers": + subMerchantNumberOfSubSellers = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].city": + subMerchantSubSellerSubSellerNrCity = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].country": + subMerchantSubSellerSubSellerNrCountry = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].email": + subMerchantSubSellerSubSellerNrEmail = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].id": + subMerchantSubSellerSubSellerNrId = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].mcc": + subMerchantSubSellerSubSellerNrMcc = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].name": + subMerchantSubSellerSubSellerNrName = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].phoneNumber": + subMerchantSubSellerSubSellerNrPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].postalCode": + subMerchantSubSellerSubSellerNrPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].state": + subMerchantSubSellerSubSellerNrState = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].street": + subMerchantSubSellerSubSellerNrStreet = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].taxId": + subMerchantSubSellerSubSellerNrTaxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataSubMerchant(subMerchantNumberOfSubSellers, subMerchantSubSellerSubSellerNrCity, subMerchantSubSellerSubSellerNrCountry, subMerchantSubSellerSubSellerNrEmail, subMerchantSubSellerSubSellerNrId, subMerchantSubSellerSubSellerNrMcc, subMerchantSubSellerSubSellerNrName, subMerchantSubSellerSubSellerNrPhoneNumber, subMerchantSubSellerSubSellerNrPostalCode, subMerchantSubSellerSubSellerNrState, subMerchantSubSellerSubSellerNrStreet, subMerchantSubSellerSubSellerNrTaxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataSubMerchant additionalDataSubMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataSubMerchant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataSubMerchant additionalDataSubMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataSubMerchant._SubMerchantNumberOfSubSellersOption.IsSet) + if (additionalDataSubMerchant.SubMerchantNumberOfSubSellers != null) + writer.WriteString("subMerchant.numberOfSubSellers", additionalDataSubMerchant.SubMerchantNumberOfSubSellers); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrCityOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCity != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].city", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCity); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrCountryOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCountry != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].country", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCountry); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrEmailOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrEmail != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].email", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrEmail); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrIdOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrId != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].id", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrId); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrMccOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrMcc != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].mcc", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrMcc); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrNameOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrName != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].name", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrName); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrPhoneNumberOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPhoneNumber != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].phoneNumber", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPhoneNumber); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrPostalCodeOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPostalCode != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].postalCode", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPostalCode); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrStateOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrState != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].state", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrState); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrStreetOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrStreet != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].street", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrStreet); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrTaxIdOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrTaxId != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].taxId", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrTaxId); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataTemporaryServices.cs b/Adyen/Checkout/Models/AdditionalDataTemporaryServices.cs new file mode 100644 index 000000000..b07d2465e --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataTemporaryServices.cs @@ -0,0 +1,377 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataTemporaryServices. + /// + public partial class AdditionalDataTemporaryServices : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + [JsonConstructor] + public AdditionalDataTemporaryServices(Option enhancedSchemeDataCustomerReference = default, Option enhancedSchemeDataEmployeeName = default, Option enhancedSchemeDataJobDescription = default, Option enhancedSchemeDataRegularHoursRate = default, Option enhancedSchemeDataRegularHoursWorked = default, Option enhancedSchemeDataRequestName = default, Option enhancedSchemeDataTempStartDate = default, Option enhancedSchemeDataTempWeekEnding = default, Option enhancedSchemeDataTotalTaxAmount = default) + { + _EnhancedSchemeDataCustomerReferenceOption = enhancedSchemeDataCustomerReference; + _EnhancedSchemeDataEmployeeNameOption = enhancedSchemeDataEmployeeName; + _EnhancedSchemeDataJobDescriptionOption = enhancedSchemeDataJobDescription; + _EnhancedSchemeDataRegularHoursRateOption = enhancedSchemeDataRegularHoursRate; + _EnhancedSchemeDataRegularHoursWorkedOption = enhancedSchemeDataRegularHoursWorked; + _EnhancedSchemeDataRequestNameOption = enhancedSchemeDataRequestName; + _EnhancedSchemeDataTempStartDateOption = enhancedSchemeDataTempStartDate; + _EnhancedSchemeDataTempWeekEndingOption = enhancedSchemeDataTempWeekEnding; + _EnhancedSchemeDataTotalTaxAmountOption = enhancedSchemeDataTotalTaxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataTemporaryServices() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataCustomerReferenceOption { get; private set; } + + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + [JsonPropertyName("enhancedSchemeData.customerReference")] + public string? EnhancedSchemeDataCustomerReference { get { return this._EnhancedSchemeDataCustomerReferenceOption; } set { this._EnhancedSchemeDataCustomerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataEmployeeNameOption { get; private set; } + + /// + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + /// + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.employeeName")] + public string? EnhancedSchemeDataEmployeeName { get { return this._EnhancedSchemeDataEmployeeNameOption; } set { this._EnhancedSchemeDataEmployeeNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataJobDescriptionOption { get; private set; } + + /// + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + /// + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.jobDescription")] + public string? EnhancedSchemeDataJobDescription { get { return this._EnhancedSchemeDataJobDescriptionOption; } set { this._EnhancedSchemeDataJobDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRegularHoursRateOption { get; private set; } + + /// + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + /// + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + [JsonPropertyName("enhancedSchemeData.regularHoursRate")] + public string? EnhancedSchemeDataRegularHoursRate { get { return this._EnhancedSchemeDataRegularHoursRateOption; } set { this._EnhancedSchemeDataRegularHoursRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRegularHoursWorkedOption { get; private set; } + + /// + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + /// + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + [JsonPropertyName("enhancedSchemeData.regularHoursWorked")] + public string? EnhancedSchemeDataRegularHoursWorked { get { return this._EnhancedSchemeDataRegularHoursWorkedOption; } set { this._EnhancedSchemeDataRegularHoursWorkedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRequestNameOption { get; private set; } + + /// + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + /// + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + [JsonPropertyName("enhancedSchemeData.requestName")] + public string? EnhancedSchemeDataRequestName { get { return this._EnhancedSchemeDataRequestNameOption; } set { this._EnhancedSchemeDataRequestNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTempStartDateOption { get; private set; } + + /// + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + /// + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + [JsonPropertyName("enhancedSchemeData.tempStartDate")] + public string? EnhancedSchemeDataTempStartDate { get { return this._EnhancedSchemeDataTempStartDateOption; } set { this._EnhancedSchemeDataTempStartDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTempWeekEndingOption { get; private set; } + + /// + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + /// + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + [JsonPropertyName("enhancedSchemeData.tempWeekEnding")] + public string? EnhancedSchemeDataTempWeekEnding { get { return this._EnhancedSchemeDataTempWeekEndingOption; } set { this._EnhancedSchemeDataTempWeekEndingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTotalTaxAmountOption { get; private set; } + + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + [JsonPropertyName("enhancedSchemeData.totalTaxAmount")] + public string? EnhancedSchemeDataTotalTaxAmount { get { return this._EnhancedSchemeDataTotalTaxAmountOption; } set { this._EnhancedSchemeDataTotalTaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataTemporaryServices {\n"); + sb.Append(" EnhancedSchemeDataCustomerReference: ").Append(EnhancedSchemeDataCustomerReference).Append("\n"); + sb.Append(" EnhancedSchemeDataEmployeeName: ").Append(EnhancedSchemeDataEmployeeName).Append("\n"); + sb.Append(" EnhancedSchemeDataJobDescription: ").Append(EnhancedSchemeDataJobDescription).Append("\n"); + sb.Append(" EnhancedSchemeDataRegularHoursRate: ").Append(EnhancedSchemeDataRegularHoursRate).Append("\n"); + sb.Append(" EnhancedSchemeDataRegularHoursWorked: ").Append(EnhancedSchemeDataRegularHoursWorked).Append("\n"); + sb.Append(" EnhancedSchemeDataRequestName: ").Append(EnhancedSchemeDataRequestName).Append("\n"); + sb.Append(" EnhancedSchemeDataTempStartDate: ").Append(EnhancedSchemeDataTempStartDate).Append("\n"); + sb.Append(" EnhancedSchemeDataTempWeekEnding: ").Append(EnhancedSchemeDataTempWeekEnding).Append("\n"); + sb.Append(" EnhancedSchemeDataTotalTaxAmount: ").Append(EnhancedSchemeDataTotalTaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataTemporaryServicesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataTemporaryServices Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enhancedSchemeDataCustomerReference = default; + Option enhancedSchemeDataEmployeeName = default; + Option enhancedSchemeDataJobDescription = default; + Option enhancedSchemeDataRegularHoursRate = default; + Option enhancedSchemeDataRegularHoursWorked = default; + Option enhancedSchemeDataRequestName = default; + Option enhancedSchemeDataTempStartDate = default; + Option enhancedSchemeDataTempWeekEnding = default; + Option enhancedSchemeDataTotalTaxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enhancedSchemeData.customerReference": + enhancedSchemeDataCustomerReference = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.employeeName": + enhancedSchemeDataEmployeeName = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.jobDescription": + enhancedSchemeDataJobDescription = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.regularHoursRate": + enhancedSchemeDataRegularHoursRate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.regularHoursWorked": + enhancedSchemeDataRegularHoursWorked = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.requestName": + enhancedSchemeDataRequestName = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.tempStartDate": + enhancedSchemeDataTempStartDate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.tempWeekEnding": + enhancedSchemeDataTempWeekEnding = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.totalTaxAmount": + enhancedSchemeDataTotalTaxAmount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataTemporaryServices(enhancedSchemeDataCustomerReference, enhancedSchemeDataEmployeeName, enhancedSchemeDataJobDescription, enhancedSchemeDataRegularHoursRate, enhancedSchemeDataRegularHoursWorked, enhancedSchemeDataRequestName, enhancedSchemeDataTempStartDate, enhancedSchemeDataTempWeekEnding, enhancedSchemeDataTotalTaxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataTemporaryServices additionalDataTemporaryServices, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataTemporaryServices, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataTemporaryServices additionalDataTemporaryServices, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataTemporaryServices._EnhancedSchemeDataCustomerReferenceOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataCustomerReference != null) + writer.WriteString("enhancedSchemeData.customerReference", additionalDataTemporaryServices.EnhancedSchemeDataCustomerReference); + + if (additionalDataTemporaryServices._EnhancedSchemeDataEmployeeNameOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataEmployeeName != null) + writer.WriteString("enhancedSchemeData.employeeName", additionalDataTemporaryServices.EnhancedSchemeDataEmployeeName); + + if (additionalDataTemporaryServices._EnhancedSchemeDataJobDescriptionOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataJobDescription != null) + writer.WriteString("enhancedSchemeData.jobDescription", additionalDataTemporaryServices.EnhancedSchemeDataJobDescription); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRegularHoursRateOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursRate != null) + writer.WriteString("enhancedSchemeData.regularHoursRate", additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursRate); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRegularHoursWorkedOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursWorked != null) + writer.WriteString("enhancedSchemeData.regularHoursWorked", additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursWorked); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRequestNameOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRequestName != null) + writer.WriteString("enhancedSchemeData.requestName", additionalDataTemporaryServices.EnhancedSchemeDataRequestName); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTempStartDateOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTempStartDate != null) + writer.WriteString("enhancedSchemeData.tempStartDate", additionalDataTemporaryServices.EnhancedSchemeDataTempStartDate); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTempWeekEndingOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTempWeekEnding != null) + writer.WriteString("enhancedSchemeData.tempWeekEnding", additionalDataTemporaryServices.EnhancedSchemeDataTempWeekEnding); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTotalTaxAmountOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTotalTaxAmount != null) + writer.WriteString("enhancedSchemeData.totalTaxAmount", additionalDataTemporaryServices.EnhancedSchemeDataTotalTaxAmount); + } + } +} diff --git a/Adyen/Checkout/Models/AdditionalDataWallets.cs b/Adyen/Checkout/Models/AdditionalDataWallets.cs new file mode 100644 index 000000000..9c3cdd2a6 --- /dev/null +++ b/Adyen/Checkout/Models/AdditionalDataWallets.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AdditionalDataWallets. + /// + public partial class AdditionalDataWallets : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Android Pay token retrieved from the SDK. + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + /// The Apple Pay token retrieved from the SDK. + /// The Google Pay token retrieved from the SDK. + /// The Samsung Pay token retrieved from the SDK. + /// The Visa Checkout Call ID retrieved from the SDK. + [JsonConstructor] + public AdditionalDataWallets(Option androidpayToken = default, Option masterpassTransactionId = default, Option paymentToken = default, Option paywithgoogleToken = default, Option samsungpayToken = default, Option visacheckoutCallId = default) + { + _AndroidpayTokenOption = androidpayToken; + _MasterpassTransactionIdOption = masterpassTransactionId; + _PaymentTokenOption = paymentToken; + _PaywithgoogleTokenOption = paywithgoogleToken; + _SamsungpayTokenOption = samsungpayToken; + _VisacheckoutCallIdOption = visacheckoutCallId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataWallets() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AndroidpayTokenOption { get; private set; } + + /// + /// The Android Pay token retrieved from the SDK. + /// + /// The Android Pay token retrieved from the SDK. + [JsonPropertyName("androidpay.token")] + public string? AndroidpayToken { get { return this._AndroidpayTokenOption; } set { this._AndroidpayTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MasterpassTransactionIdOption { get; private set; } + + /// + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + /// + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + [JsonPropertyName("masterpass.transactionId")] + public string? MasterpassTransactionId { get { return this._MasterpassTransactionIdOption; } set { this._MasterpassTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentTokenOption { get; private set; } + + /// + /// The Apple Pay token retrieved from the SDK. + /// + /// The Apple Pay token retrieved from the SDK. + [JsonPropertyName("payment.token")] + public string? PaymentToken { get { return this._PaymentTokenOption; } set { this._PaymentTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaywithgoogleTokenOption { get; private set; } + + /// + /// The Google Pay token retrieved from the SDK. + /// + /// The Google Pay token retrieved from the SDK. + [JsonPropertyName("paywithgoogle.token")] + public string? PaywithgoogleToken { get { return this._PaywithgoogleTokenOption; } set { this._PaywithgoogleTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SamsungpayTokenOption { get; private set; } + + /// + /// The Samsung Pay token retrieved from the SDK. + /// + /// The Samsung Pay token retrieved from the SDK. + [JsonPropertyName("samsungpay.token")] + public string? SamsungpayToken { get { return this._SamsungpayTokenOption; } set { this._SamsungpayTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisacheckoutCallIdOption { get; private set; } + + /// + /// The Visa Checkout Call ID retrieved from the SDK. + /// + /// The Visa Checkout Call ID retrieved from the SDK. + [JsonPropertyName("visacheckout.callId")] + public string? VisacheckoutCallId { get { return this._VisacheckoutCallIdOption; } set { this._VisacheckoutCallIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataWallets {\n"); + sb.Append(" AndroidpayToken: ").Append(AndroidpayToken).Append("\n"); + sb.Append(" MasterpassTransactionId: ").Append(MasterpassTransactionId).Append("\n"); + sb.Append(" PaymentToken: ").Append(PaymentToken).Append("\n"); + sb.Append(" PaywithgoogleToken: ").Append(PaywithgoogleToken).Append("\n"); + sb.Append(" SamsungpayToken: ").Append(SamsungpayToken).Append("\n"); + sb.Append(" VisacheckoutCallId: ").Append(VisacheckoutCallId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataWalletsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataWallets Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option androidpayToken = default; + Option masterpassTransactionId = default; + Option paymentToken = default; + Option paywithgoogleToken = default; + Option samsungpayToken = default; + Option visacheckoutCallId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "androidpay.token": + androidpayToken = new Option(utf8JsonReader.GetString()!); + break; + case "masterpass.transactionId": + masterpassTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "payment.token": + paymentToken = new Option(utf8JsonReader.GetString()!); + break; + case "paywithgoogle.token": + paywithgoogleToken = new Option(utf8JsonReader.GetString()!); + break; + case "samsungpay.token": + samsungpayToken = new Option(utf8JsonReader.GetString()!); + break; + case "visacheckout.callId": + visacheckoutCallId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataWallets(androidpayToken, masterpassTransactionId, paymentToken, paywithgoogleToken, samsungpayToken, visacheckoutCallId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataWallets additionalDataWallets, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataWallets, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataWallets additionalDataWallets, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataWallets._AndroidpayTokenOption.IsSet) + if (additionalDataWallets.AndroidpayToken != null) + writer.WriteString("androidpay.token", additionalDataWallets.AndroidpayToken); + + if (additionalDataWallets._MasterpassTransactionIdOption.IsSet) + if (additionalDataWallets.MasterpassTransactionId != null) + writer.WriteString("masterpass.transactionId", additionalDataWallets.MasterpassTransactionId); + + if (additionalDataWallets._PaymentTokenOption.IsSet) + if (additionalDataWallets.PaymentToken != null) + writer.WriteString("payment.token", additionalDataWallets.PaymentToken); + + if (additionalDataWallets._PaywithgoogleTokenOption.IsSet) + if (additionalDataWallets.PaywithgoogleToken != null) + writer.WriteString("paywithgoogle.token", additionalDataWallets.PaywithgoogleToken); + + if (additionalDataWallets._SamsungpayTokenOption.IsSet) + if (additionalDataWallets.SamsungpayToken != null) + writer.WriteString("samsungpay.token", additionalDataWallets.SamsungpayToken); + + if (additionalDataWallets._VisacheckoutCallIdOption.IsSet) + if (additionalDataWallets.VisacheckoutCallId != null) + writer.WriteString("visacheckout.callId", additionalDataWallets.VisacheckoutCallId); + } + } +} diff --git a/Adyen/Checkout/Models/Address.cs b/Adyen/Checkout/Models/Address.cs new file mode 100644 index 000000000..8dcb8e4f2 --- /dev/null +++ b/Adyen/Checkout/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/Checkout/Models/AffirmDetails.cs b/Adyen/Checkout/Models/AffirmDetails.cs new file mode 100644 index 000000000..9f1bef76d --- /dev/null +++ b/Adyen/Checkout/Models/AffirmDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AffirmDetails. + /// + public partial class AffirmDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// **affirm** (default to TypeEnum.Affirm) + [JsonConstructor] + public AffirmDetails(Option checkoutAttemptId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AffirmDetails() + { + } + + partial void OnCreated(); + + /// + /// **affirm** + /// + /// **affirm** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Affirm - affirm + /// + public static readonly TypeEnum Affirm = new("affirm"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "affirm" => TypeEnum.Affirm, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Affirm) + return "affirm"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **affirm** + /// + /// **affirm** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AffirmDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AffirmDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AffirmDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AffirmDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AffirmDetails(checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AffirmDetails affirmDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, affirmDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AffirmDetails affirmDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (affirmDetails._CheckoutAttemptIdOption.IsSet) + if (affirmDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", affirmDetails.CheckoutAttemptId); + + if (affirmDetails._TypeOption.IsSet && affirmDetails.Type != null) + { + string? typeRawValue = AffirmDetails.TypeEnum.ToJsonValue(affirmDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/AfterpayDetails.cs b/Adyen/Checkout/Models/AfterpayDetails.cs new file mode 100644 index 000000000..3bce48a26 --- /dev/null +++ b/Adyen/Checkout/Models/AfterpayDetails.cs @@ -0,0 +1,453 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AfterpayDetails. + /// + public partial class AfterpayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address where to send the invoice. + /// The checkout attempt identifier. + /// The address where the goods should be delivered. + /// Shopper name, date of birth, phone number, and email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **afterpay_default** (default to TypeEnum.AfterpayDefault) + [JsonConstructor] + public AfterpayDetails(Option billingAddress = default, Option checkoutAttemptId = default, Option deliveryAddress = default, Option personalDetails = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + _BillingAddressOption = billingAddress; + _CheckoutAttemptIdOption = checkoutAttemptId; + _DeliveryAddressOption = deliveryAddress; + _PersonalDetailsOption = personalDetails; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AfterpayDetails() + { + } + + partial void OnCreated(); + + /// + /// **afterpay_default** + /// + /// **afterpay_default** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AfterpayDefault - afterpay_default + /// + public static readonly TypeEnum AfterpayDefault = new("afterpay_default"); + + /// + /// TypeEnum.Afterpaytouch - afterpaytouch + /// + public static readonly TypeEnum Afterpaytouch = new("afterpaytouch"); + + /// + /// TypeEnum.AfterpayB2b - afterpay_b2b + /// + public static readonly TypeEnum AfterpayB2b = new("afterpay_b2b"); + + /// + /// TypeEnum.Clearpay - clearpay + /// + public static readonly TypeEnum Clearpay = new("clearpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "afterpay_default" => TypeEnum.AfterpayDefault, + "afterpaytouch" => TypeEnum.Afterpaytouch, + "afterpay_b2b" => TypeEnum.AfterpayB2b, + "clearpay" => TypeEnum.Clearpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AfterpayDefault) + return "afterpay_default"; + + if (value == TypeEnum.Afterpaytouch) + return "afterpaytouch"; + + if (value == TypeEnum.AfterpayB2b) + return "afterpay_b2b"; + + if (value == TypeEnum.Clearpay) + return "clearpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **afterpay_default** + /// + /// **afterpay_default** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// The address where to send the invoice. + /// + /// The address where to send the invoice. + [JsonPropertyName("billingAddress")] + public string? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// The address where the goods should be delivered. + /// + /// The address where the goods should be delivered. + [JsonPropertyName("deliveryAddress")] + public string? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PersonalDetailsOption { get; private set; } + + /// + /// Shopper name, date of birth, phone number, and email address. + /// + /// Shopper name, date of birth, phone number, and email address. + [JsonPropertyName("personalDetails")] + public string? PersonalDetails { get { return this._PersonalDetailsOption; } set { this._PersonalDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AfterpayDetails {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AfterpayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AfterpayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option checkoutAttemptId = default; + Option deliveryAddress = default; + Option personalDetails = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryAddress": + deliveryAddress = new Option(utf8JsonReader.GetString()!); + break; + case "personalDetails": + personalDetails = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AfterpayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AfterpayDetails.", nameof(type)); + + return new AfterpayDetails(billingAddress, checkoutAttemptId, deliveryAddress, personalDetails, recurringDetailReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AfterpayDetails afterpayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, afterpayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AfterpayDetails afterpayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (afterpayDetails._BillingAddressOption.IsSet) + if (afterpayDetails.BillingAddress != null) + writer.WriteString("billingAddress", afterpayDetails.BillingAddress); + + if (afterpayDetails._CheckoutAttemptIdOption.IsSet) + if (afterpayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", afterpayDetails.CheckoutAttemptId); + + if (afterpayDetails._DeliveryAddressOption.IsSet) + if (afterpayDetails.DeliveryAddress != null) + writer.WriteString("deliveryAddress", afterpayDetails.DeliveryAddress); + + if (afterpayDetails._PersonalDetailsOption.IsSet) + if (afterpayDetails.PersonalDetails != null) + writer.WriteString("personalDetails", afterpayDetails.PersonalDetails); + + if (afterpayDetails._RecurringDetailReferenceOption.IsSet) + if (afterpayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", afterpayDetails.RecurringDetailReference); + + if (afterpayDetails._StoredPaymentMethodIdOption.IsSet) + if (afterpayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", afterpayDetails.StoredPaymentMethodId); + + if (afterpayDetails.Type != null) + { + string? typeRawValue = AfterpayDetails.TypeEnum.ToJsonValue(afterpayDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Agency.cs b/Adyen/Checkout/Models/Agency.cs new file mode 100644 index 000000000..94f56823b --- /dev/null +++ b/Adyen/Checkout/Models/Agency.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Agency. + /// + public partial class Agency : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + [JsonConstructor] + public Agency(Option invoiceNumber = default, Option planName = default) + { + _InvoiceNumberOption = invoiceNumber; + _PlanNameOption = planName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Agency() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InvoiceNumberOption { get; private set; } + + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + [JsonPropertyName("invoiceNumber")] + public string? InvoiceNumber { get { return this._InvoiceNumberOption; } set { this._InvoiceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlanNameOption { get; private set; } + + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("planName")] + public string? PlanName { get { return this._PlanNameOption; } set { this._PlanNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Agency {\n"); + sb.Append(" InvoiceNumber: ").Append(InvoiceNumber).Append("\n"); + sb.Append(" PlanName: ").Append(PlanName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AgencyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Agency Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option invoiceNumber = default; + Option planName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "invoiceNumber": + invoiceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "planName": + planName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Agency(invoiceNumber, planName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Agency agency, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, agency, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Agency agency, JsonSerializerOptions jsonSerializerOptions) + { + + if (agency._InvoiceNumberOption.IsSet) + if (agency.InvoiceNumber != null) + writer.WriteString("invoiceNumber", agency.InvoiceNumber); + + if (agency._PlanNameOption.IsSet) + if (agency.PlanName != null) + writer.WriteString("planName", agency.PlanName); + } + } +} diff --git a/Adyen/Checkout/Models/Airline.cs b/Adyen/Checkout/Models/Airline.cs new file mode 100644 index 000000000..30ee10f7a --- /dev/null +++ b/Adyen/Checkout/Models/Airline.cs @@ -0,0 +1,475 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Airline. + /// + public partial class Airline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not start with a space or be all spaces. * Must not be all zeros. + /// agency + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 11 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not start with a space or be all spaces. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// The flight departure date. Time is optional. * Format for date only: `yyyy-MM-dd` * Format for date and time: `yyyy-MM-ddTHH:mm` * Use local time of departure airport. * minLength: 10 characters * maxLength: 16 characters + /// legs + /// passengers + /// ticket + /// travelAgency + [JsonConstructor] + public Airline(string passengerName, Option agency = default, Option boardingFee = default, Option code = default, Option computerizedReservationSystem = default, Option customerReferenceNumber = default, Option designatorCode = default, Option documentType = default, Option flightDate = default, Option?> legs = default, Option?> passengers = default, Option ticket = default, Option travelAgency = default) + { + PassengerName = passengerName; + _AgencyOption = agency; + _BoardingFeeOption = boardingFee; + _CodeOption = code; + _ComputerizedReservationSystemOption = computerizedReservationSystem; + _CustomerReferenceNumberOption = customerReferenceNumber; + _DesignatorCodeOption = designatorCode; + _DocumentTypeOption = documentType; + _FlightDateOption = flightDate; + _LegsOption = legs; + _PassengersOption = passengers; + _TicketOption = ticket; + _TravelAgencyOption = travelAgency; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Airline() + { + } + + partial void OnCreated(); + + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("passengerName")] + public string PassengerName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AgencyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("agency")] + public Agency? Agency { get { return this._AgencyOption; } set { this._AgencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BoardingFeeOption { get; private set; } + + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 11 characters + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 11 characters + [JsonPropertyName("boardingFee")] + public long? BoardingFee { get { return this._BoardingFeeOption; } set { this._BoardingFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ComputerizedReservationSystemOption { get; private set; } + + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + [JsonPropertyName("computerizedReservationSystem")] + public string? ComputerizedReservationSystem { get { return this._ComputerizedReservationSystemOption; } set { this._ComputerizedReservationSystemOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomerReferenceNumberOption { get; private set; } + + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not start with a space or be all spaces. + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not start with a space or be all spaces. + [JsonPropertyName("customerReferenceNumber")] + public string? CustomerReferenceNumber { get { return this._CustomerReferenceNumberOption; } set { this._CustomerReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DesignatorCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. + [JsonPropertyName("designatorCode")] + public string? DesignatorCode { get { return this._DesignatorCodeOption; } set { this._DesignatorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DocumentTypeOption { get; private set; } + + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("documentType")] + public string? DocumentType { get { return this._DocumentTypeOption; } set { this._DocumentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FlightDateOption { get; private set; } + + /// + /// The flight departure date. Time is optional. * Format for date only: `yyyy-MM-dd` * Format for date and time: `yyyy-MM-ddTHH:mm` * Use local time of departure airport. * minLength: 10 characters * maxLength: 16 characters + /// + /// The flight departure date. Time is optional. * Format for date only: `yyyy-MM-dd` * Format for date and time: `yyyy-MM-ddTHH:mm` * Use local time of departure airport. * minLength: 10 characters * maxLength: 16 characters + [JsonPropertyName("flightDate")] + public DateTimeOffset? FlightDate { get { return this._FlightDateOption; } set { this._FlightDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LegsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("legs")] + public List? Legs { get { return this._LegsOption; } set { this._LegsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PassengersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("passengers")] + public List? Passengers { get { return this._PassengersOption; } set { this._PassengersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TicketOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ticket")] + public Ticket? Ticket { get { return this._TicketOption; } set { this._TicketOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelAgencyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("travelAgency")] + public TravelAgency? TravelAgency { get { return this._TravelAgencyOption; } set { this._TravelAgencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Airline {\n"); + sb.Append(" PassengerName: ").Append(PassengerName).Append("\n"); + sb.Append(" Agency: ").Append(Agency).Append("\n"); + sb.Append(" BoardingFee: ").Append(BoardingFee).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" ComputerizedReservationSystem: ").Append(ComputerizedReservationSystem).Append("\n"); + sb.Append(" CustomerReferenceNumber: ").Append(CustomerReferenceNumber).Append("\n"); + sb.Append(" DesignatorCode: ").Append(DesignatorCode).Append("\n"); + sb.Append(" DocumentType: ").Append(DocumentType).Append("\n"); + sb.Append(" FlightDate: ").Append(FlightDate).Append("\n"); + sb.Append(" Legs: ").Append(Legs).Append("\n"); + sb.Append(" Passengers: ").Append(Passengers).Append("\n"); + sb.Append(" Ticket: ").Append(Ticket).Append("\n"); + sb.Append(" TravelAgency: ").Append(TravelAgency).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AirlineJsonConverter : JsonConverter + { + /// + /// The format to use to serialize FlightDate. + /// + public static string FlightDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Airline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option passengerName = default; + Option agency = default; + Option boardingFee = default; + Option code = default; + Option computerizedReservationSystem = default; + Option customerReferenceNumber = default; + Option designatorCode = default; + Option documentType = default; + Option flightDate = default; + Option?> legs = default; + Option?> passengers = default; + Option ticket = default; + Option travelAgency = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "passengerName": + passengerName = new Option(utf8JsonReader.GetString()!); + break; + case "agency": + agency = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "boardingFee": + boardingFee = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "computerizedReservationSystem": + computerizedReservationSystem = new Option(utf8JsonReader.GetString()!); + break; + case "customerReferenceNumber": + customerReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "designatorCode": + designatorCode = new Option(utf8JsonReader.GetString()!); + break; + case "documentType": + documentType = new Option(utf8JsonReader.GetString()!); + break; + case "flightDate": + flightDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "legs": + legs = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "passengers": + passengers = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ticket": + ticket = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "travelAgency": + travelAgency = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!passengerName.IsSet) + throw new ArgumentException("Property is required for class Airline.", nameof(passengerName)); + + return new Airline(passengerName.Value!, agency, boardingFee, code, computerizedReservationSystem, customerReferenceNumber, designatorCode, documentType, flightDate, legs, passengers, ticket, travelAgency); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, airline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + if (airline.PassengerName != null) + writer.WriteString("passengerName", airline.PassengerName); + + if (airline._AgencyOption.IsSet) + { + writer.WritePropertyName("agency"); + JsonSerializer.Serialize(writer, airline.Agency, jsonSerializerOptions); + } + if (airline._BoardingFeeOption.IsSet) + writer.WriteNumber("boardingFee", airline._BoardingFeeOption.Value!.Value); + + if (airline._CodeOption.IsSet) + if (airline.Code != null) + writer.WriteString("code", airline.Code); + + if (airline._ComputerizedReservationSystemOption.IsSet) + if (airline.ComputerizedReservationSystem != null) + writer.WriteString("computerizedReservationSystem", airline.ComputerizedReservationSystem); + + if (airline._CustomerReferenceNumberOption.IsSet) + if (airline.CustomerReferenceNumber != null) + writer.WriteString("customerReferenceNumber", airline.CustomerReferenceNumber); + + if (airline._DesignatorCodeOption.IsSet) + if (airline.DesignatorCode != null) + writer.WriteString("designatorCode", airline.DesignatorCode); + + if (airline._DocumentTypeOption.IsSet) + if (airline.DocumentType != null) + writer.WriteString("documentType", airline.DocumentType); + + if (airline._FlightDateOption.IsSet) + writer.WriteString("flightDate", airline._FlightDateOption.Value!.Value.ToString(FlightDateFormat)); + + if (airline._LegsOption.IsSet) + { + writer.WritePropertyName("legs"); + JsonSerializer.Serialize(writer, airline.Legs, jsonSerializerOptions); + } + if (airline._PassengersOption.IsSet) + { + writer.WritePropertyName("passengers"); + JsonSerializer.Serialize(writer, airline.Passengers, jsonSerializerOptions); + } + if (airline._TicketOption.IsSet) + { + writer.WritePropertyName("ticket"); + JsonSerializer.Serialize(writer, airline.Ticket, jsonSerializerOptions); + } + if (airline._TravelAgencyOption.IsSet) + { + writer.WritePropertyName("travelAgency"); + JsonSerializer.Serialize(writer, airline.TravelAgency, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/AmazonPayDetails.cs b/Adyen/Checkout/Models/AmazonPayDetails.cs new file mode 100644 index 000000000..acec971ed --- /dev/null +++ b/Adyen/Checkout/Models/AmazonPayDetails.cs @@ -0,0 +1,349 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AmazonPayDetails. + /// + public partial class AmazonPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// This is the `amazonPayToken` that you obtained from the [Get Checkout Session](https://amazon-pay-acquirer-guide.s3-eu-west-1.amazonaws.com/v1/amazon-pay-api-v2/checkout-session.html#get-checkout-session) response. This token is used for API only integration specifically. + /// The checkout attempt identifier. + /// The `checkoutSessionId` is used to identify the checkout session at the Amazon Pay side. This field is required only for drop-in and components integration, where it replaces the amazonPayToken. + /// **amazonpay** (default to TypeEnum.Amazonpay) + [JsonConstructor] + public AmazonPayDetails(Option amazonPayToken = default, Option checkoutAttemptId = default, Option checkoutSessionId = default, Option type = default) + { + _AmazonPayTokenOption = amazonPayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _CheckoutSessionIdOption = checkoutSessionId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmazonPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **amazonpay** + /// + /// **amazonpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Amazonpay - amazonpay + /// + public static readonly TypeEnum Amazonpay = new("amazonpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "amazonpay" => TypeEnum.Amazonpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Amazonpay) + return "amazonpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **amazonpay** + /// + /// **amazonpay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmazonPayTokenOption { get; private set; } + + /// + /// This is the `amazonPayToken` that you obtained from the [Get Checkout Session](https://amazon-pay-acquirer-guide.s3-eu-west-1.amazonaws.com/v1/amazon-pay-api-v2/checkout-session.html#get-checkout-session) response. This token is used for API only integration specifically. + /// + /// This is the `amazonPayToken` that you obtained from the [Get Checkout Session](https://amazon-pay-acquirer-guide.s3-eu-west-1.amazonaws.com/v1/amazon-pay-api-v2/checkout-session.html#get-checkout-session) response. This token is used for API only integration specifically. + [JsonPropertyName("amazonPayToken")] + public string? AmazonPayToken { get { return this._AmazonPayTokenOption; } set { this._AmazonPayTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutSessionIdOption { get; private set; } + + /// + /// The `checkoutSessionId` is used to identify the checkout session at the Amazon Pay side. This field is required only for drop-in and components integration, where it replaces the amazonPayToken. + /// + /// The `checkoutSessionId` is used to identify the checkout session at the Amazon Pay side. This field is required only for drop-in and components integration, where it replaces the amazonPayToken. + [JsonPropertyName("checkoutSessionId")] + public string? CheckoutSessionId { get { return this._CheckoutSessionIdOption; } set { this._CheckoutSessionIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmazonPayDetails {\n"); + sb.Append(" AmazonPayToken: ").Append(AmazonPayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" CheckoutSessionId: ").Append(CheckoutSessionId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmazonPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmazonPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amazonPayToken = default; + Option checkoutAttemptId = default; + Option checkoutSessionId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amazonPayToken": + amazonPayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutSessionId": + checkoutSessionId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AmazonPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AmazonPayDetails(amazonPayToken, checkoutAttemptId, checkoutSessionId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmazonPayDetails amazonPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amazonPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmazonPayDetails amazonPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (amazonPayDetails._AmazonPayTokenOption.IsSet) + if (amazonPayDetails.AmazonPayToken != null) + writer.WriteString("amazonPayToken", amazonPayDetails.AmazonPayToken); + + if (amazonPayDetails._CheckoutAttemptIdOption.IsSet) + if (amazonPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", amazonPayDetails.CheckoutAttemptId); + + if (amazonPayDetails._CheckoutSessionIdOption.IsSet) + if (amazonPayDetails.CheckoutSessionId != null) + writer.WriteString("checkoutSessionId", amazonPayDetails.CheckoutSessionId); + + if (amazonPayDetails._TypeOption.IsSet && amazonPayDetails.Type != null) + { + string? typeRawValue = AmazonPayDetails.TypeEnum.ToJsonValue(amazonPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Amount.cs b/Adyen/Checkout/Models/Amount.cs new file mode 100644 index 000000000..8e33010d4 --- /dev/null +++ b/Adyen/Checkout/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Checkout/Models/Amounts.cs b/Adyen/Checkout/Models/Amounts.cs new file mode 100644 index 000000000..585d2f201 --- /dev/null +++ b/Adyen/Checkout/Models/Amounts.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Amounts. + /// + public partial class Amounts : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// The amounts of the donation (in [minor units](https://docs.adyen.com/development-resources/currency-codes/)). + [JsonConstructor] + public Amounts(string currency, List values) + { + Currency = currency; + Values = values; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amounts() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amounts of the donation (in [minor units](https://docs.adyen.com/development-resources/currency-codes/)). + /// + /// The amounts of the donation (in [minor units](https://docs.adyen.com/development-resources/currency-codes/)). + [JsonPropertyName("values")] + public List Values { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amounts {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Values: ").Append(Values).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amounts Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option?> values = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "values": + values = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amounts.", nameof(currency)); + + if (!values.IsSet) + throw new ArgumentException("Property is required for class Amounts.", nameof(values)); + + return new Amounts(currency.Value!, values.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amounts amounts, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amounts, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amounts amounts, JsonSerializerOptions jsonSerializerOptions) + { + + if (amounts.Currency != null) + writer.WriteString("currency", amounts.Currency); + + writer.WritePropertyName("values"); + JsonSerializer.Serialize(writer, amounts.Values, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Checkout/Models/AncvDetails.cs b/Adyen/Checkout/Models/AncvDetails.cs new file mode 100644 index 000000000..fabaa7f62 --- /dev/null +++ b/Adyen/Checkout/Models/AncvDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AncvDetails. + /// + public partial class AncvDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ANCV account identification (email or account number) + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **ancv** + [JsonConstructor] + public AncvDetails(Option beneficiaryId = default, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _BeneficiaryIdOption = beneficiaryId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AncvDetails() + { + } + + partial void OnCreated(); + + /// + /// **ancv** + /// + /// **ancv** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ancv - ancv + /// + public static readonly TypeEnum Ancv = new("ancv"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ancv" => TypeEnum.Ancv, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ancv) + return "ancv"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **ancv** + /// + /// **ancv** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BeneficiaryIdOption { get; private set; } + + /// + /// ANCV account identification (email or account number) + /// + /// ANCV account identification (email or account number) + [JsonPropertyName("beneficiaryId")] + public string? BeneficiaryId { get { return this._BeneficiaryIdOption; } set { this._BeneficiaryIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AncvDetails {\n"); + sb.Append(" BeneficiaryId: ").Append(BeneficiaryId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AncvDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AncvDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option beneficiaryId = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "beneficiaryId": + beneficiaryId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AncvDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AncvDetails(beneficiaryId, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AncvDetails ancvDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ancvDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AncvDetails ancvDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (ancvDetails._BeneficiaryIdOption.IsSet) + if (ancvDetails.BeneficiaryId != null) + writer.WriteString("beneficiaryId", ancvDetails.BeneficiaryId); + + if (ancvDetails._CheckoutAttemptIdOption.IsSet) + if (ancvDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", ancvDetails.CheckoutAttemptId); + + if (ancvDetails._RecurringDetailReferenceOption.IsSet) + if (ancvDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", ancvDetails.RecurringDetailReference); + + if (ancvDetails._StoredPaymentMethodIdOption.IsSet) + if (ancvDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", ancvDetails.StoredPaymentMethodId); + + if (ancvDetails._TypeOption.IsSet && ancvDetails.Type != null) + { + string? typeRawValue = AncvDetails.TypeEnum.ToJsonValue(ancvDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/AndroidPayDetails.cs b/Adyen/Checkout/Models/AndroidPayDetails.cs new file mode 100644 index 000000000..240bec212 --- /dev/null +++ b/Adyen/Checkout/Models/AndroidPayDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AndroidPayDetails. + /// + public partial class AndroidPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// **androidpay** (default to TypeEnum.Androidpay) + [JsonConstructor] + public AndroidPayDetails(Option checkoutAttemptId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **androidpay** + /// + /// **androidpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Androidpay - androidpay + /// + public static readonly TypeEnum Androidpay = new("androidpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "androidpay" => TypeEnum.Androidpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Androidpay) + return "androidpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **androidpay** + /// + /// **androidpay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidPayDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AndroidPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AndroidPayDetails(checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidPayDetails androidPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidPayDetails androidPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidPayDetails._CheckoutAttemptIdOption.IsSet) + if (androidPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", androidPayDetails.CheckoutAttemptId); + + if (androidPayDetails._TypeOption.IsSet && androidPayDetails.Type != null) + { + string? typeRawValue = AndroidPayDetails.TypeEnum.ToJsonValue(androidPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ApplePayDetails.cs b/Adyen/Checkout/Models/ApplePayDetails.cs new file mode 100644 index 000000000..a0482ed31 --- /dev/null +++ b/Adyen/Checkout/Models/ApplePayDetails.cs @@ -0,0 +1,512 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ApplePayDetails. + /// + public partial class ApplePayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **applepay** (default to TypeEnum.Applepay) + [JsonConstructor] + public ApplePayDetails(string applePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + ApplePayToken = applePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplePayDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **applepay** + /// + /// **applepay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Applepay - applepay + /// + public static readonly TypeEnum Applepay = new("applepay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "applepay" => TypeEnum.Applepay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Applepay) + return "applepay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **applepay** + /// + /// **applepay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + [JsonPropertyName("applePayToken")] + public string ApplePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplePayDetails {\n"); + sb.Append(" ApplePayToken: ").Append(ApplePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ApplePayToken (string) maxLength + if (this.ApplePayToken != null && this.ApplePayToken.Length > 10000) + { + yield return new ValidationResult("Invalid value for ApplePayToken, length must be less than 10000.", new [] { "ApplePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplePayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplePayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option applePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "applePayToken": + applePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(ApplePayDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ApplePayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!applePayToken.IsSet) + throw new ArgumentException("Property is required for class ApplePayDetails.", nameof(applePayToken)); + + return new ApplePayDetails(applePayToken.Value!, checkoutAttemptId, fundingSource, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplePayDetails applePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applePayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplePayDetails applePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (applePayDetails.ApplePayToken != null) + writer.WriteString("applePayToken", applePayDetails.ApplePayToken); + + if (applePayDetails._CheckoutAttemptIdOption.IsSet) + if (applePayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", applePayDetails.CheckoutAttemptId); + + if (applePayDetails._FundingSourceOption.IsSet && applePayDetails.FundingSource != null) + { + string? fundingSourceRawValue = ApplePayDetails.FundingSourceEnum.ToJsonValue(applePayDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (applePayDetails._RecurringDetailReferenceOption.IsSet) + if (applePayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", applePayDetails.RecurringDetailReference); + + if (applePayDetails._StoredPaymentMethodIdOption.IsSet) + if (applePayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", applePayDetails.StoredPaymentMethodId); + + if (applePayDetails._TypeOption.IsSet && applePayDetails.Type != null) + { + string? typeRawValue = ApplePayDetails.TypeEnum.ToJsonValue(applePayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ApplePayDonations.cs b/Adyen/Checkout/Models/ApplePayDonations.cs new file mode 100644 index 000000000..2b5aea3c4 --- /dev/null +++ b/Adyen/Checkout/Models/ApplePayDonations.cs @@ -0,0 +1,512 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ApplePayDonations. + /// + public partial class ApplePayDonations : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **applepay** (default to TypeEnum.Applepay) + [JsonConstructor] + public ApplePayDonations(string applePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + ApplePayToken = applePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplePayDonations() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **applepay** + /// + /// **applepay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Applepay - applepay + /// + public static readonly TypeEnum Applepay = new("applepay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "applepay" => TypeEnum.Applepay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Applepay) + return "applepay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **applepay** + /// + /// **applepay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + /// + /// The stringified and base64 encoded `paymentData` you retrieved from the Apple framework. + [JsonPropertyName("applePayToken")] + public string ApplePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplePayDonations {\n"); + sb.Append(" ApplePayToken: ").Append(ApplePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ApplePayToken (string) maxLength + if (this.ApplePayToken != null && this.ApplePayToken.Length > 10000) + { + yield return new ValidationResult("Invalid value for ApplePayToken, length must be less than 10000.", new [] { "ApplePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplePayDonationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplePayDonations Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option applePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "applePayToken": + applePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(ApplePayDonations.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ApplePayDonations.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!applePayToken.IsSet) + throw new ArgumentException("Property is required for class ApplePayDonations.", nameof(applePayToken)); + + return new ApplePayDonations(applePayToken.Value!, checkoutAttemptId, fundingSource, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplePayDonations applePayDonations, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applePayDonations, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplePayDonations applePayDonations, JsonSerializerOptions jsonSerializerOptions) + { + + if (applePayDonations.ApplePayToken != null) + writer.WriteString("applePayToken", applePayDonations.ApplePayToken); + + if (applePayDonations._CheckoutAttemptIdOption.IsSet) + if (applePayDonations.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", applePayDonations.CheckoutAttemptId); + + if (applePayDonations._FundingSourceOption.IsSet && applePayDonations.FundingSource != null) + { + string? fundingSourceRawValue = ApplePayDonations.FundingSourceEnum.ToJsonValue(applePayDonations._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (applePayDonations._RecurringDetailReferenceOption.IsSet) + if (applePayDonations.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", applePayDonations.RecurringDetailReference); + + if (applePayDonations._StoredPaymentMethodIdOption.IsSet) + if (applePayDonations.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", applePayDonations.StoredPaymentMethodId); + + if (applePayDonations._TypeOption.IsSet && applePayDonations.Type != null) + { + string? typeRawValue = ApplePayDonations.TypeEnum.ToJsonValue(applePayDonations._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ApplePaySessionRequest.cs b/Adyen/Checkout/Models/ApplePaySessionRequest.cs new file mode 100644 index 000000000..eb70ddabb --- /dev/null +++ b/Adyen/Checkout/Models/ApplePaySessionRequest.cs @@ -0,0 +1,217 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ApplePaySessionRequest. + /// + public partial class ApplePaySessionRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// This is the name that your shoppers will see in the Apple Pay interface. The value returned as `configuration.merchantName` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + /// The domain name you provided when you added Apple Pay in your Customer Area. This must match the `window.location.hostname` of the web shop. + /// Your merchant identifier registered with Apple Pay. Use the value of the `configuration.merchantId` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + [JsonConstructor] + public ApplePaySessionRequest(string displayName, string domainName, string merchantIdentifier) + { + DisplayName = displayName; + DomainName = domainName; + MerchantIdentifier = merchantIdentifier; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplePaySessionRequest() + { + } + + partial void OnCreated(); + + /// + /// This is the name that your shoppers will see in the Apple Pay interface. The value returned as `configuration.merchantName` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + /// + /// This is the name that your shoppers will see in the Apple Pay interface. The value returned as `configuration.merchantName` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + [JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + /// + /// The domain name you provided when you added Apple Pay in your Customer Area. This must match the `window.location.hostname` of the web shop. + /// + /// The domain name you provided when you added Apple Pay in your Customer Area. This must match the `window.location.hostname` of the web shop. + [JsonPropertyName("domainName")] + public string DomainName { get; set; } + + /// + /// Your merchant identifier registered with Apple Pay. Use the value of the `configuration.merchantId` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + /// + /// Your merchant identifier registered with Apple Pay. Use the value of the `configuration.merchantId` field from the [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. + [JsonPropertyName("merchantIdentifier")] + public string MerchantIdentifier { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplePaySessionRequest {\n"); + sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); + sb.Append(" DomainName: ").Append(DomainName).Append("\n"); + sb.Append(" MerchantIdentifier: ").Append(MerchantIdentifier).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DisplayName (string) maxLength + if (this.DisplayName != null && this.DisplayName.Length > 64) + { + yield return new ValidationResult("Invalid value for DisplayName, length must be less than 64.", new [] { "DisplayName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplePaySessionRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplePaySessionRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option displayName = default; + Option domainName = default; + Option merchantIdentifier = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "displayName": + displayName = new Option(utf8JsonReader.GetString()!); + break; + case "domainName": + domainName = new Option(utf8JsonReader.GetString()!); + break; + case "merchantIdentifier": + merchantIdentifier = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!displayName.IsSet) + throw new ArgumentException("Property is required for class ApplePaySessionRequest.", nameof(displayName)); + + if (!domainName.IsSet) + throw new ArgumentException("Property is required for class ApplePaySessionRequest.", nameof(domainName)); + + if (!merchantIdentifier.IsSet) + throw new ArgumentException("Property is required for class ApplePaySessionRequest.", nameof(merchantIdentifier)); + + return new ApplePaySessionRequest(displayName.Value!, domainName.Value!, merchantIdentifier.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplePaySessionRequest applePaySessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applePaySessionRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplePaySessionRequest applePaySessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (applePaySessionRequest.DisplayName != null) + writer.WriteString("displayName", applePaySessionRequest.DisplayName); + + if (applePaySessionRequest.DomainName != null) + writer.WriteString("domainName", applePaySessionRequest.DomainName); + + if (applePaySessionRequest.MerchantIdentifier != null) + writer.WriteString("merchantIdentifier", applePaySessionRequest.MerchantIdentifier); + } + } +} diff --git a/Adyen/Checkout/Models/ApplePaySessionResponse.cs b/Adyen/Checkout/Models/ApplePaySessionResponse.cs new file mode 100644 index 000000000..fa4084336 --- /dev/null +++ b/Adyen/Checkout/Models/ApplePaySessionResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ApplePaySessionResponse. + /// + public partial class ApplePaySessionResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Base64 encoded data you need to [complete the Apple Pay merchant validation](https://docs.adyen.com/payment-methods/apple-pay/api-only?tab=adyen-certificate-validation_1#complete-apple-pay-session-validation). + [JsonConstructor] + public ApplePaySessionResponse(string data) + { + Data = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplePaySessionResponse() + { + } + + partial void OnCreated(); + + /// + /// Base64 encoded data you need to [complete the Apple Pay merchant validation](https://docs.adyen.com/payment-methods/apple-pay/api-only?tab=adyen-certificate-validation_1#complete-apple-pay-session-validation). + /// + /// Base64 encoded data you need to [complete the Apple Pay merchant validation](https://docs.adyen.com/payment-methods/apple-pay/api-only?tab=adyen-certificate-validation_1#complete-apple-pay-session-validation). + [JsonPropertyName("data")] + public string Data { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplePaySessionResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplePaySessionResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplePaySessionResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class ApplePaySessionResponse.", nameof(data)); + + return new ApplePaySessionResponse(data.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplePaySessionResponse applePaySessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applePaySessionResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplePaySessionResponse applePaySessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (applePaySessionResponse.Data != null) + writer.WriteString("data", applePaySessionResponse.Data); + } + } +} diff --git a/Adyen/Checkout/Models/ApplicationInfo.cs b/Adyen/Checkout/Models/ApplicationInfo.cs new file mode 100644 index 000000000..29e40d3f5 --- /dev/null +++ b/Adyen/Checkout/Models/ApplicationInfo.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ApplicationInfo. + /// + public partial class ApplicationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// adyenLibrary + /// adyenPaymentSource + /// externalPlatform + /// merchantApplication + /// merchantDevice + /// shopperInteractionDevice + [JsonConstructor] + public ApplicationInfo(Option adyenLibrary = default, Option adyenPaymentSource = default, Option externalPlatform = default, Option merchantApplication = default, Option merchantDevice = default, Option shopperInteractionDevice = default) + { + _AdyenLibraryOption = adyenLibrary; + _AdyenPaymentSourceOption = adyenPaymentSource; + _ExternalPlatformOption = externalPlatform; + _MerchantApplicationOption = merchantApplication; + _MerchantDeviceOption = merchantDevice; + _ShopperInteractionDeviceOption = shopperInteractionDevice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplicationInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenLibraryOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("adyenLibrary")] + public CommonField? AdyenLibrary { get { return this._AdyenLibraryOption; } set { this._AdyenLibraryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenPaymentSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("adyenPaymentSource")] + public CommonField? AdyenPaymentSource { get { return this._AdyenPaymentSourceOption; } set { this._AdyenPaymentSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalPlatformOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalPlatform")] + public ExternalPlatform? ExternalPlatform { get { return this._ExternalPlatformOption; } set { this._ExternalPlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantApplicationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantApplication")] + public CommonField? MerchantApplication { get { return this._MerchantApplicationOption; } set { this._MerchantApplicationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantDevice")] + public MerchantDevice? MerchantDevice { get { return this._MerchantDeviceOption; } set { this._MerchantDeviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperInteractionDevice")] + public ShopperInteractionDevice? ShopperInteractionDevice { get { return this._ShopperInteractionDeviceOption; } set { this._ShopperInteractionDeviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplicationInfo {\n"); + sb.Append(" AdyenLibrary: ").Append(AdyenLibrary).Append("\n"); + sb.Append(" AdyenPaymentSource: ").Append(AdyenPaymentSource).Append("\n"); + sb.Append(" ExternalPlatform: ").Append(ExternalPlatform).Append("\n"); + sb.Append(" MerchantApplication: ").Append(MerchantApplication).Append("\n"); + sb.Append(" MerchantDevice: ").Append(MerchantDevice).Append("\n"); + sb.Append(" ShopperInteractionDevice: ").Append(ShopperInteractionDevice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplicationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplicationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option adyenLibrary = default; + Option adyenPaymentSource = default; + Option externalPlatform = default; + Option merchantApplication = default; + Option merchantDevice = default; + Option shopperInteractionDevice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "adyenLibrary": + adyenLibrary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "adyenPaymentSource": + adyenPaymentSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalPlatform": + externalPlatform = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantApplication": + merchantApplication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantDevice": + merchantDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperInteractionDevice": + shopperInteractionDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ApplicationInfo(adyenLibrary, adyenPaymentSource, externalPlatform, merchantApplication, merchantDevice, shopperInteractionDevice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplicationInfo applicationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applicationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplicationInfo applicationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (applicationInfo._AdyenLibraryOption.IsSet) + { + writer.WritePropertyName("adyenLibrary"); + JsonSerializer.Serialize(writer, applicationInfo.AdyenLibrary, jsonSerializerOptions); + } + if (applicationInfo._AdyenPaymentSourceOption.IsSet) + { + writer.WritePropertyName("adyenPaymentSource"); + JsonSerializer.Serialize(writer, applicationInfo.AdyenPaymentSource, jsonSerializerOptions); + } + if (applicationInfo._ExternalPlatformOption.IsSet) + { + writer.WritePropertyName("externalPlatform"); + JsonSerializer.Serialize(writer, applicationInfo.ExternalPlatform, jsonSerializerOptions); + } + if (applicationInfo._MerchantApplicationOption.IsSet) + { + writer.WritePropertyName("merchantApplication"); + JsonSerializer.Serialize(writer, applicationInfo.MerchantApplication, jsonSerializerOptions); + } + if (applicationInfo._MerchantDeviceOption.IsSet) + { + writer.WritePropertyName("merchantDevice"); + JsonSerializer.Serialize(writer, applicationInfo.MerchantDevice, jsonSerializerOptions); + } + if (applicationInfo._ShopperInteractionDeviceOption.IsSet) + { + writer.WritePropertyName("shopperInteractionDevice"); + JsonSerializer.Serialize(writer, applicationInfo.ShopperInteractionDevice, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/AuthenticationData.cs b/Adyen/Checkout/Models/AuthenticationData.cs new file mode 100644 index 000000000..b533ad56e --- /dev/null +++ b/Adyen/Checkout/Models/AuthenticationData.cs @@ -0,0 +1,333 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// AuthenticationData. + /// + public partial class AuthenticationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. (default to false) + /// threeDSRequestData + [JsonConstructor] + public AuthenticationData(Option attemptAuthentication = default, Option authenticationOnly = default, Option threeDSRequestData = default) + { + _AttemptAuthenticationOption = attemptAuthentication; + _AuthenticationOnlyOption = authenticationOnly; + _ThreeDSRequestDataOption = threeDSRequestData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationData() + { + } + + partial void OnCreated(); + + /// + /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined. + /// + /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined. + [JsonConverter(typeof(AttemptAuthenticationEnumJsonConverter))] + public class AttemptAuthenticationEnum : IEnum + { + /// + /// Returns the value of the AttemptAuthenticationEnum. + /// + public string? Value { get; set; } + + /// + /// AttemptAuthenticationEnum.Always - always + /// + public static readonly AttemptAuthenticationEnum Always = new("always"); + + /// + /// AttemptAuthenticationEnum.Never - never + /// + public static readonly AttemptAuthenticationEnum Never = new("never"); + + private AttemptAuthenticationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AttemptAuthenticationEnum?(string? value) => value == null ? null : new AttemptAuthenticationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AttemptAuthenticationEnum? option) => option?.Value; + + public static bool operator ==(AttemptAuthenticationEnum? left, AttemptAuthenticationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AttemptAuthenticationEnum? left, AttemptAuthenticationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AttemptAuthenticationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AttemptAuthenticationEnum? FromStringOrDefault(string value) + { + return value switch { + "always" => AttemptAuthenticationEnum.Always, + "never" => AttemptAuthenticationEnum.Never, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AttemptAuthenticationEnum? value) + { + if (value == null) + return null; + + if (value == AttemptAuthenticationEnum.Always) + return "always"; + + if (value == AttemptAuthenticationEnum.Never) + return "never"; + + return null; + } + + /// + /// JsonConverter for writing AttemptAuthenticationEnum. + /// + public class AttemptAuthenticationEnumJsonConverter : JsonConverter + { + public override AttemptAuthenticationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AttemptAuthenticationEnum.FromStringOrDefault(value) ?? new AttemptAuthenticationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AttemptAuthenticationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AttemptAuthenticationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AttemptAuthenticationOption { get; private set; } + + /// + /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined. + /// + /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined. + [JsonPropertyName("attemptAuthentication")] + public AttemptAuthenticationEnum? AttemptAuthentication { get { return this._AttemptAuthenticationOption; } set { this._AttemptAuthenticationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. + [JsonPropertyName("authenticationOnly")] + public bool? AuthenticationOnly { get { return this._AuthenticationOnlyOption; } set { this._AuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestData")] + public ThreeDSRequestData? ThreeDSRequestData { get { return this._ThreeDSRequestDataOption; } set { this._ThreeDSRequestDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationData {\n"); + sb.Append(" AttemptAuthentication: ").Append(AttemptAuthentication).Append("\n"); + sb.Append(" AuthenticationOnly: ").Append(AuthenticationOnly).Append("\n"); + sb.Append(" ThreeDSRequestData: ").Append(ThreeDSRequestData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option attemptAuthentication = default; + Option authenticationOnly = default; + Option threeDSRequestData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "attemptAuthentication": + string? attemptAuthenticationRawValue = utf8JsonReader.GetString(); + attemptAuthentication = new Option(AuthenticationData.AttemptAuthenticationEnum.FromStringOrDefault(attemptAuthenticationRawValue)); + break; + case "authenticationOnly": + authenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "threeDSRequestData": + threeDSRequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AuthenticationData(attemptAuthentication, authenticationOnly, threeDSRequestData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationData authenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationData authenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationData._AttemptAuthenticationOption.IsSet && authenticationData.AttemptAuthentication != null) + { + string? attemptAuthenticationRawValue = AuthenticationData.AttemptAuthenticationEnum.ToJsonValue(authenticationData._AttemptAuthenticationOption.Value!.Value); + writer.WriteString("attemptAuthentication", attemptAuthenticationRawValue); + } + + if (authenticationData._AuthenticationOnlyOption.IsSet) + writer.WriteBoolean("authenticationOnly", authenticationData._AuthenticationOnlyOption.Value!.Value); + + if (authenticationData._ThreeDSRequestDataOption.IsSet) + { + writer.WritePropertyName("threeDSRequestData"); + JsonSerializer.Serialize(writer, authenticationData.ThreeDSRequestData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/BacsDirectDebitDetails.cs b/Adyen/Checkout/Models/BacsDirectDebitDetails.cs new file mode 100644 index 000000000..c52814811 --- /dev/null +++ b/Adyen/Checkout/Models/BacsDirectDebitDetails.cs @@ -0,0 +1,456 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BacsDirectDebitDetails. + /// + public partial class BacsDirectDebitDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The bank routing number of the account. + /// The checkout attempt identifier. + /// The name of the bank account holder. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// **directdebit_GB** (default to TypeEnum.DirectdebitGB) + [JsonConstructor] + public BacsDirectDebitDetails(Option bankAccountNumber = default, Option bankLocationId = default, Option checkoutAttemptId = default, Option holderName = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option transferInstrumentId = default, Option type = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankLocationIdOption = bankLocationId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _HolderNameOption = holderName; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TransferInstrumentIdOption = transferInstrumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BacsDirectDebitDetails() + { + } + + partial void OnCreated(); + + /// + /// **directdebit_GB** + /// + /// **directdebit_GB** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DirectdebitGB - directdebit_GB + /// + public static readonly TypeEnum DirectdebitGB = new("directdebit_GB"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "directdebit_GB" => TypeEnum.DirectdebitGB, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DirectdebitGB) + return "directdebit_GB"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **directdebit_GB** + /// + /// **directdebit_GB** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The bank routing number of the account. + /// + /// The bank routing number of the account. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the bank account holder. + /// + /// The name of the bank account holder. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BacsDirectDebitDetails {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BacsDirectDebitDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BacsDirectDebitDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankLocationId = default; + Option checkoutAttemptId = default; + Option holderName = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option transferInstrumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BacsDirectDebitDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BacsDirectDebitDetails(bankAccountNumber, bankLocationId, checkoutAttemptId, holderName, recurringDetailReference, storedPaymentMethodId, transferInstrumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BacsDirectDebitDetails bacsDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bacsDirectDebitDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BacsDirectDebitDetails bacsDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (bacsDirectDebitDetails._BankAccountNumberOption.IsSet) + if (bacsDirectDebitDetails.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", bacsDirectDebitDetails.BankAccountNumber); + + if (bacsDirectDebitDetails._BankLocationIdOption.IsSet) + if (bacsDirectDebitDetails.BankLocationId != null) + writer.WriteString("bankLocationId", bacsDirectDebitDetails.BankLocationId); + + if (bacsDirectDebitDetails._CheckoutAttemptIdOption.IsSet) + if (bacsDirectDebitDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", bacsDirectDebitDetails.CheckoutAttemptId); + + if (bacsDirectDebitDetails._HolderNameOption.IsSet) + if (bacsDirectDebitDetails.HolderName != null) + writer.WriteString("holderName", bacsDirectDebitDetails.HolderName); + + if (bacsDirectDebitDetails._RecurringDetailReferenceOption.IsSet) + if (bacsDirectDebitDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", bacsDirectDebitDetails.RecurringDetailReference); + + if (bacsDirectDebitDetails._StoredPaymentMethodIdOption.IsSet) + if (bacsDirectDebitDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", bacsDirectDebitDetails.StoredPaymentMethodId); + + if (bacsDirectDebitDetails._TransferInstrumentIdOption.IsSet) + if (bacsDirectDebitDetails.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", bacsDirectDebitDetails.TransferInstrumentId); + + if (bacsDirectDebitDetails._TypeOption.IsSet && bacsDirectDebitDetails.Type != null) + { + string? typeRawValue = BacsDirectDebitDetails.TypeEnum.ToJsonValue(bacsDirectDebitDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/BalanceCheckRequest.cs b/Adyen/Checkout/Models/BalanceCheckRequest.cs new file mode 100644 index 000000000..e529ac2aa --- /dev/null +++ b/Adyen/Checkout/Models/BalanceCheckRequest.cs @@ -0,0 +1,1511 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BalanceCheckRequest. + /// + public partial class BalanceCheckRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// applicationInfo + /// billingAddress + /// browserInfo + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// dccQuote + /// deliveryAddress + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// installments + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// recurring + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// A session ID used to identify a payment session. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The shopper's social security number. + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public BalanceCheckRequest(Amount amount, string merchantAccount, Dictionary paymentMethod, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option applicationInfo = default, Option billingAddress = default, Option browserInfo = default, Option captureDelayHours = default, Option dateOfBirth = default, Option dccQuote = default, Option deliveryAddress = default, Option deliveryDate = default, Option deviceFingerprint = default, Option fraudOffset = default, Option installments = default, Option?> localizedShopperStatement = default, Option mcc = default, Option merchantOrderReference = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option orderReference = default, Option recurring = default, Option recurringProcessingModel = default, Option reference = default, Option selectedBrand = default, Option selectedRecurringDetailReference = default, Option sessionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option?> splits = default, Option store = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option totalsGroup = default, Option trustedShopper = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _ApplicationInfoOption = applicationInfo; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _CaptureDelayHoursOption = captureDelayHours; + _DateOfBirthOption = dateOfBirth; + _DccQuoteOption = dccQuote; + _DeliveryAddressOption = deliveryAddress; + _DeliveryDateOption = deliveryDate; + _DeviceFingerprintOption = deviceFingerprint; + _FraudOffsetOption = fraudOffset; + _InstallmentsOption = installments; + _LocalizedShopperStatementOption = localizedShopperStatement; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _OrderReferenceOption = orderReference; + _RecurringOption = recurring; + _RecurringProcessingModelOption = recurringProcessingModel; + _ReferenceOption = reference; + _SelectedBrandOption = selectedBrand; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _SessionIdOption = sessionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitsOption = splits; + _StoreOption = store; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TotalsGroupOption = totalsGroup; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceCheckRequest() + { + } + + partial void OnCreated(); + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information. + /// + /// The collection that contains the type of the payment method and its specific information. + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccQuoteOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccQuote")] + public ForexQuote? DccQuote { get { return this._DccQuoteOption; } set { this._DccQuoteOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryDateOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliveryDate")] + public DateTimeOffset? DeliveryDate { get { return this._DeliveryDateOption; } set { this._DeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("installments")] + public Installments? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalizedShopperStatementOption { get; private set; } + + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + [JsonPropertyName("localizedShopperStatement")] + public Dictionary? LocalizedShopperStatement { get { return this._LocalizedShopperStatementOption; } set { this._LocalizedShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderReferenceOption { get; private set; } + + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + [JsonPropertyName("orderReference")] + public string? OrderReference { get { return this._OrderReferenceOption; } set { this._OrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionIdOption { get; private set; } + + /// + /// A session ID used to identify a payment session. + /// + /// A session ID used to identify a payment session. + [JsonPropertyName("sessionId")] + public string? SessionId { get { return this._SessionIdOption; } set { this._SessionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalsGroupOption { get; private set; } + + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + [JsonPropertyName("totalsGroup")] + public string? TotalsGroup { get { return this._TotalsGroupOption; } set { this._TotalsGroupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceCheckRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DccQuote: ").Append(DccQuote).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeliveryDate: ").Append(DeliveryDate).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" LocalizedShopperStatement: ").Append(LocalizedShopperStatement).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" OrderReference: ").Append(OrderReference).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" SessionId: ").Append(SessionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TotalsGroup: ").Append(TotalsGroup).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + // TotalsGroup (string) maxLength + if (this.TotalsGroup != null && this.TotalsGroup.Length > 16) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be less than 16.", new [] { "TotalsGroup" }); + } + + // TotalsGroup (string) minLength + if (this.TotalsGroup != null && this.TotalsGroup.Length < 1) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be greater than 1.", new [] { "TotalsGroup" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceCheckRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliveryDate. + /// + public static string DeliveryDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceCheckRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option?> paymentMethod = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option applicationInfo = default; + Option billingAddress = default; + Option browserInfo = default; + Option captureDelayHours = default; + Option dateOfBirth = default; + Option dccQuote = default; + Option deliveryAddress = default; + Option deliveryDate = default; + Option deviceFingerprint = default; + Option fraudOffset = default; + Option installments = default; + Option?> localizedShopperStatement = default; + Option mcc = default; + Option merchantOrderReference = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option orderReference = default; + Option recurring = default; + Option recurringProcessingModel = default; + Option reference = default; + Option selectedBrand = default; + Option selectedRecurringDetailReference = default; + Option sessionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option?> splits = default; + Option store = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option totalsGroup = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dccQuote": + dccQuote = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryDate": + deliveryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "installments": + installments = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localizedShopperStatement": + localizedShopperStatement = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderReference": + orderReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(BalanceCheckRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "sessionId": + sessionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(BalanceCheckRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "totalsGroup": + totalsGroup = new Option(utf8JsonReader.GetString()!); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class BalanceCheckRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class BalanceCheckRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class BalanceCheckRequest.", nameof(paymentMethod)); + + return new BalanceCheckRequest(amount.Value!, merchantAccount.Value!, paymentMethod.Value!, accountInfo, additionalAmount, additionalData, applicationInfo, billingAddress, browserInfo, captureDelayHours, dateOfBirth, dccQuote, deliveryAddress, deliveryDate, deviceFingerprint, fraudOffset, installments, localizedShopperStatement, mcc, merchantOrderReference, merchantRiskIndicator, metadata, orderReference, recurring, recurringProcessingModel, reference, selectedBrand, selectedRecurringDetailReference, sessionId, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, splits, store, telephoneNumber, threeDS2RequestData, threeDSAuthenticationOnly, totalsGroup, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceCheckRequest balanceCheckRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceCheckRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceCheckRequest balanceCheckRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, balanceCheckRequest.Amount, jsonSerializerOptions); + if (balanceCheckRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", balanceCheckRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, balanceCheckRequest.PaymentMethod, jsonSerializerOptions); + if (balanceCheckRequest._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, balanceCheckRequest.AccountInfo, jsonSerializerOptions); + } + if (balanceCheckRequest._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, balanceCheckRequest.AdditionalAmount, jsonSerializerOptions); + } + if (balanceCheckRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, balanceCheckRequest.AdditionalData, jsonSerializerOptions); + } + if (balanceCheckRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, balanceCheckRequest.ApplicationInfo, jsonSerializerOptions); + } + if (balanceCheckRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, balanceCheckRequest.BillingAddress, jsonSerializerOptions); + } + if (balanceCheckRequest._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, balanceCheckRequest.BrowserInfo, jsonSerializerOptions); + } + if (balanceCheckRequest._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", balanceCheckRequest._CaptureDelayHoursOption.Value!.Value); + + if (balanceCheckRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", balanceCheckRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (balanceCheckRequest._DccQuoteOption.IsSet) + { + writer.WritePropertyName("dccQuote"); + JsonSerializer.Serialize(writer, balanceCheckRequest.DccQuote, jsonSerializerOptions); + } + if (balanceCheckRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, balanceCheckRequest.DeliveryAddress, jsonSerializerOptions); + } + if (balanceCheckRequest._DeliveryDateOption.IsSet) + writer.WriteString("deliveryDate", balanceCheckRequest._DeliveryDateOption.Value!.Value.ToString(DeliveryDateFormat)); + + if (balanceCheckRequest._DeviceFingerprintOption.IsSet) + if (balanceCheckRequest.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", balanceCheckRequest.DeviceFingerprint); + + if (balanceCheckRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", balanceCheckRequest._FraudOffsetOption.Value!.Value); + + if (balanceCheckRequest._InstallmentsOption.IsSet) + { + writer.WritePropertyName("installments"); + JsonSerializer.Serialize(writer, balanceCheckRequest.Installments, jsonSerializerOptions); + } + if (balanceCheckRequest._LocalizedShopperStatementOption.IsSet) + { + writer.WritePropertyName("localizedShopperStatement"); + JsonSerializer.Serialize(writer, balanceCheckRequest.LocalizedShopperStatement, jsonSerializerOptions); + } + if (balanceCheckRequest._MccOption.IsSet) + if (balanceCheckRequest.Mcc != null) + writer.WriteString("mcc", balanceCheckRequest.Mcc); + + if (balanceCheckRequest._MerchantOrderReferenceOption.IsSet) + if (balanceCheckRequest.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", balanceCheckRequest.MerchantOrderReference); + + if (balanceCheckRequest._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, balanceCheckRequest.MerchantRiskIndicator, jsonSerializerOptions); + } + if (balanceCheckRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceCheckRequest.Metadata, jsonSerializerOptions); + } + if (balanceCheckRequest._OrderReferenceOption.IsSet) + if (balanceCheckRequest.OrderReference != null) + writer.WriteString("orderReference", balanceCheckRequest.OrderReference); + + if (balanceCheckRequest._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, balanceCheckRequest.Recurring, jsonSerializerOptions); + } + if (balanceCheckRequest._RecurringProcessingModelOption.IsSet && balanceCheckRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = BalanceCheckRequest.RecurringProcessingModelEnum.ToJsonValue(balanceCheckRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (balanceCheckRequest._ReferenceOption.IsSet) + if (balanceCheckRequest.Reference != null) + writer.WriteString("reference", balanceCheckRequest.Reference); + + if (balanceCheckRequest._SelectedBrandOption.IsSet) + if (balanceCheckRequest.SelectedBrand != null) + writer.WriteString("selectedBrand", balanceCheckRequest.SelectedBrand); + + if (balanceCheckRequest._SelectedRecurringDetailReferenceOption.IsSet) + if (balanceCheckRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", balanceCheckRequest.SelectedRecurringDetailReference); + + if (balanceCheckRequest._SessionIdOption.IsSet) + if (balanceCheckRequest.SessionId != null) + writer.WriteString("sessionId", balanceCheckRequest.SessionId); + + if (balanceCheckRequest._ShopperEmailOption.IsSet) + if (balanceCheckRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", balanceCheckRequest.ShopperEmail); + + if (balanceCheckRequest._ShopperIPOption.IsSet) + if (balanceCheckRequest.ShopperIP != null) + writer.WriteString("shopperIP", balanceCheckRequest.ShopperIP); + + if (balanceCheckRequest._ShopperInteractionOption.IsSet && balanceCheckRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = BalanceCheckRequest.ShopperInteractionEnum.ToJsonValue(balanceCheckRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (balanceCheckRequest._ShopperLocaleOption.IsSet) + if (balanceCheckRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", balanceCheckRequest.ShopperLocale); + + if (balanceCheckRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, balanceCheckRequest.ShopperName, jsonSerializerOptions); + } + if (balanceCheckRequest._ShopperReferenceOption.IsSet) + if (balanceCheckRequest.ShopperReference != null) + writer.WriteString("shopperReference", balanceCheckRequest.ShopperReference); + + if (balanceCheckRequest._ShopperStatementOption.IsSet) + if (balanceCheckRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", balanceCheckRequest.ShopperStatement); + + if (balanceCheckRequest._SocialSecurityNumberOption.IsSet) + if (balanceCheckRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", balanceCheckRequest.SocialSecurityNumber); + + if (balanceCheckRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, balanceCheckRequest.Splits, jsonSerializerOptions); + } + if (balanceCheckRequest._StoreOption.IsSet) + if (balanceCheckRequest.Store != null) + writer.WriteString("store", balanceCheckRequest.Store); + + if (balanceCheckRequest._TelephoneNumberOption.IsSet) + if (balanceCheckRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", balanceCheckRequest.TelephoneNumber); + + if (balanceCheckRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, balanceCheckRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + if (balanceCheckRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", balanceCheckRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (balanceCheckRequest._TotalsGroupOption.IsSet) + if (balanceCheckRequest.TotalsGroup != null) + writer.WriteString("totalsGroup", balanceCheckRequest.TotalsGroup); + + if (balanceCheckRequest._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", balanceCheckRequest._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/BalanceCheckResponse.cs b/Adyen/Checkout/Models/BalanceCheckResponse.cs new file mode 100644 index 000000000..f59138750 --- /dev/null +++ b/Adyen/Checkout/Models/BalanceCheckResponse.cs @@ -0,0 +1,432 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BalanceCheckResponse. + /// + public partial class BalanceCheckResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balance + /// The result of the cancellation request. Possible values: * **Success** – Indicates that the balance check was successful. * **NotEnoughBalance** – Commonly indicates that the card did not have enough balance to pay the amount in the request, or that the currency of the balance on the card did not match the currency of the requested amount. * **Failed** – Indicates that the balance check failed. + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// fraudResult + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// transactionLimit + [JsonConstructor] + public BalanceCheckResponse(Amount balance, ResultCodeEnum resultCode, Option?> additionalData = default, Option fraudResult = default, Option pspReference = default, Option refusalReason = default, Option transactionLimit = default) + { + Balance = balance; + ResultCode = resultCode; + _AdditionalDataOption = additionalData; + _FraudResultOption = fraudResult; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _TransactionLimitOption = transactionLimit; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceCheckResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the cancellation request. Possible values: * **Success** – Indicates that the balance check was successful. * **NotEnoughBalance** – Commonly indicates that the card did not have enough balance to pay the amount in the request, or that the currency of the balance on the card did not match the currency of the requested amount. * **Failed** – Indicates that the balance check failed. + /// + /// The result of the cancellation request. Possible values: * **Success** – Indicates that the balance check was successful. * **NotEnoughBalance** – Commonly indicates that the card did not have enough balance to pay the amount in the request, or that the currency of the balance on the card did not match the currency of the requested amount. * **Failed** – Indicates that the balance check failed. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + /// + /// ResultCodeEnum.Failed - Failed + /// + public static readonly ResultCodeEnum Failed = new("Failed"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + "Failed" => ResultCodeEnum.Failed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + if (value == ResultCodeEnum.Failed) + return "Failed"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the cancellation request. Possible values: * **Success** – Indicates that the balance check was successful. * **NotEnoughBalance** – Commonly indicates that the card did not have enough balance to pay the amount in the request, or that the currency of the balance on the card did not match the currency of the requested amount. * **Failed** – Indicates that the balance check failed. + /// + /// The result of the cancellation request. Possible values: * **Success** – Indicates that the balance check was successful. * **NotEnoughBalance** – Commonly indicates that the card did not have enough balance to pay the amount in the request, or that the currency of the balance on the card did not match the currency of the requested amount. * **Failed** – Indicates that the balance check failed. + [JsonPropertyName("resultCode")] + public ResultCodeEnum ResultCode { get; set; } + + /// + /// . + /// + [JsonPropertyName("balance")] + public Amount Balance { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionLimitOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionLimit")] + public Amount? TransactionLimit { get { return this._TransactionLimitOption; } set { this._TransactionLimitOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceCheckResponse {\n"); + sb.Append(" Balance: ").Append(Balance).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" TransactionLimit: ").Append(TransactionLimit).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceCheckResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceCheckResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balance = default; + Option resultCode = default; + Option?> additionalData = default; + Option fraudResult = default; + Option pspReference = default; + Option refusalReason = default; + Option transactionLimit = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balance": + balance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(BalanceCheckResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "transactionLimit": + transactionLimit = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!balance.IsSet) + throw new ArgumentException("Property is required for class BalanceCheckResponse.", nameof(balance)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class BalanceCheckResponse.", nameof(resultCode)); + + return new BalanceCheckResponse(balance.Value!, resultCode.Value!.Value!, additionalData, fraudResult, pspReference, refusalReason, transactionLimit); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceCheckResponse balanceCheckResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceCheckResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceCheckResponse balanceCheckResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("balance"); + JsonSerializer.Serialize(writer, balanceCheckResponse.Balance, jsonSerializerOptions); + if (balanceCheckResponse.ResultCode != null) + { + string? resultCodeRawValue = BalanceCheckResponse.ResultCodeEnum.ToJsonValue(balanceCheckResponse.ResultCode); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (balanceCheckResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, balanceCheckResponse.AdditionalData, jsonSerializerOptions); + } + if (balanceCheckResponse._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, balanceCheckResponse.FraudResult, jsonSerializerOptions); + } + if (balanceCheckResponse._PspReferenceOption.IsSet) + if (balanceCheckResponse.PspReference != null) + writer.WriteString("pspReference", balanceCheckResponse.PspReference); + + if (balanceCheckResponse._RefusalReasonOption.IsSet) + if (balanceCheckResponse.RefusalReason != null) + writer.WriteString("refusalReason", balanceCheckResponse.RefusalReason); + + if (balanceCheckResponse._TransactionLimitOption.IsSet) + { + writer.WritePropertyName("transactionLimit"); + JsonSerializer.Serialize(writer, balanceCheckResponse.TransactionLimit, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/BillDeskDetails.cs b/Adyen/Checkout/Models/BillDeskDetails.cs new file mode 100644 index 000000000..0ca2276e8 --- /dev/null +++ b/Adyen/Checkout/Models/BillDeskDetails.cs @@ -0,0 +1,323 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BillDeskDetails. + /// + public partial class BillDeskDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The issuer id of the shopper's selected bank. + /// **billdesk** + /// The checkout attempt identifier. + [JsonConstructor] + public BillDeskDetails(string issuer, TypeEnum type, Option checkoutAttemptId = default) + { + Issuer = issuer; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BillDeskDetails() + { + } + + partial void OnCreated(); + + /// + /// **billdesk** + /// + /// **billdesk** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BilldeskOnline - billdesk_online + /// + public static readonly TypeEnum BilldeskOnline = new("billdesk_online"); + + /// + /// TypeEnum.BilldeskWallet - billdesk_wallet + /// + public static readonly TypeEnum BilldeskWallet = new("billdesk_wallet"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "billdesk_online" => TypeEnum.BilldeskOnline, + "billdesk_wallet" => TypeEnum.BilldeskWallet, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BilldeskOnline) + return "billdesk_online"; + + if (value == TypeEnum.BilldeskWallet) + return "billdesk_wallet"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **billdesk** + /// + /// **billdesk** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The issuer id of the shopper's selected bank. + /// + /// The issuer id of the shopper's selected bank. + [JsonPropertyName("issuer")] + public string Issuer { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BillDeskDetails {\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BillDeskDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BillDeskDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issuer = default; + Option type = default; + Option checkoutAttemptId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BillDeskDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!issuer.IsSet) + throw new ArgumentException("Property is required for class BillDeskDetails.", nameof(issuer)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BillDeskDetails.", nameof(type)); + + return new BillDeskDetails(issuer.Value!, type.Value!.Value!, checkoutAttemptId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BillDeskDetails billDeskDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, billDeskDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BillDeskDetails billDeskDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (billDeskDetails.Issuer != null) + writer.WriteString("issuer", billDeskDetails.Issuer); + + if (billDeskDetails.Type != null) + { + string? typeRawValue = BillDeskDetails.TypeEnum.ToJsonValue(billDeskDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (billDeskDetails._CheckoutAttemptIdOption.IsSet) + if (billDeskDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", billDeskDetails.CheckoutAttemptId); + } + } +} diff --git a/Adyen/Checkout/Models/BillingAddress.cs b/Adyen/Checkout/Models/BillingAddress.cs new file mode 100644 index 000000000..9ff293e79 --- /dev/null +++ b/Adyen/Checkout/Models/BillingAddress.cs @@ -0,0 +1,300 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BillingAddress. + /// + public partial class BillingAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public BillingAddress(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BillingAddress() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BillingAddress {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + // StateOrProvince (string) maxLength + if (this.StateOrProvince != null && this.StateOrProvince.Length > 1000) + { + yield return new ValidationResult("Invalid value for StateOrProvince, length must be less than 1000.", new [] { "StateOrProvince" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BillingAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BillingAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class BillingAddress.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class BillingAddress.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class BillingAddress.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class BillingAddress.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class BillingAddress.", nameof(street)); + + return new BillingAddress(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BillingAddress billingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, billingAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BillingAddress billingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (billingAddress.City != null) + writer.WriteString("city", billingAddress.City); + + if (billingAddress.Country != null) + writer.WriteString("country", billingAddress.Country); + + if (billingAddress.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", billingAddress.HouseNumberOrName); + + if (billingAddress.PostalCode != null) + writer.WriteString("postalCode", billingAddress.PostalCode); + + if (billingAddress.Street != null) + writer.WriteString("street", billingAddress.Street); + + if (billingAddress._StateOrProvinceOption.IsSet) + if (billingAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", billingAddress.StateOrProvince); + } + } +} diff --git a/Adyen/Checkout/Models/BlikDetails.cs b/Adyen/Checkout/Models/BlikDetails.cs new file mode 100644 index 000000000..430f208cf --- /dev/null +++ b/Adyen/Checkout/Models/BlikDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BlikDetails. + /// + public partial class BlikDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// BLIK code consisting of 6 digits. + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **blik** + [JsonConstructor] + public BlikDetails(Option blikCode = default, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _BlikCodeOption = blikCode; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BlikDetails() + { + } + + partial void OnCreated(); + + /// + /// **blik** + /// + /// **blik** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Blik - blik + /// + public static readonly TypeEnum Blik = new("blik"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "blik" => TypeEnum.Blik, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Blik) + return "blik"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **blik** + /// + /// **blik** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BlikCodeOption { get; private set; } + + /// + /// BLIK code consisting of 6 digits. + /// + /// BLIK code consisting of 6 digits. + [JsonPropertyName("blikCode")] + public string? BlikCode { get { return this._BlikCodeOption; } set { this._BlikCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BlikDetails {\n"); + sb.Append(" BlikCode: ").Append(BlikCode).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BlikDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BlikDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option blikCode = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "blikCode": + blikCode = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BlikDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BlikDetails(blikCode, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BlikDetails blikDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, blikDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BlikDetails blikDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (blikDetails._BlikCodeOption.IsSet) + if (blikDetails.BlikCode != null) + writer.WriteString("blikCode", blikDetails.BlikCode); + + if (blikDetails._CheckoutAttemptIdOption.IsSet) + if (blikDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", blikDetails.CheckoutAttemptId); + + if (blikDetails._RecurringDetailReferenceOption.IsSet) + if (blikDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", blikDetails.RecurringDetailReference); + + if (blikDetails._StoredPaymentMethodIdOption.IsSet) + if (blikDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", blikDetails.StoredPaymentMethodId); + + if (blikDetails._TypeOption.IsSet && blikDetails.Type != null) + { + string? typeRawValue = BlikDetails.TypeEnum.ToJsonValue(blikDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/BrowserInfo.cs b/Adyen/Checkout/Models/BrowserInfo.cs new file mode 100644 index 000000000..2fd3e142a --- /dev/null +++ b/Adyen/Checkout/Models/BrowserInfo.cs @@ -0,0 +1,330 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// BrowserInfo. + /// + public partial class BrowserInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The accept header value of the shopper's browser. + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + /// Boolean value indicating if the shopper's browser is able to execute Java. + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + /// The total height of the shopper's device screen in pixels. + /// The total width of the shopper's device screen in pixels. + /// Time difference between UTC time and the shopper's browser local time, in minutes. + /// The user agent value of the shopper's browser. + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. (default to true) + [JsonConstructor] + public BrowserInfo(string acceptHeader, int colorDepth, bool javaEnabled, string language, int screenHeight, int screenWidth, int timeZoneOffset, string userAgent, Option javaScriptEnabled = default) + { + AcceptHeader = acceptHeader; + ColorDepth = colorDepth; + JavaEnabled = javaEnabled; + Language = language; + ScreenHeight = screenHeight; + ScreenWidth = screenWidth; + TimeZoneOffset = timeZoneOffset; + UserAgent = userAgent; + _JavaScriptEnabledOption = javaScriptEnabled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BrowserInfo() + { + } + + partial void OnCreated(); + + /// + /// The accept header value of the shopper's browser. + /// + /// The accept header value of the shopper's browser. + [JsonPropertyName("acceptHeader")] + public string AcceptHeader { get; set; } + + /// + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + /// + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + [JsonPropertyName("colorDepth")] + public int ColorDepth { get; set; } + + /// + /// Boolean value indicating if the shopper's browser is able to execute Java. + /// + /// Boolean value indicating if the shopper's browser is able to execute Java. + [JsonPropertyName("javaEnabled")] + public bool JavaEnabled { get; set; } + + /// + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + /// + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + [JsonPropertyName("language")] + public string Language { get; set; } + + /// + /// The total height of the shopper's device screen in pixels. + /// + /// The total height of the shopper's device screen in pixels. + [JsonPropertyName("screenHeight")] + public int ScreenHeight { get; set; } + + /// + /// The total width of the shopper's device screen in pixels. + /// + /// The total width of the shopper's device screen in pixels. + [JsonPropertyName("screenWidth")] + public int ScreenWidth { get; set; } + + /// + /// Time difference between UTC time and the shopper's browser local time, in minutes. + /// + /// Time difference between UTC time and the shopper's browser local time, in minutes. + [JsonPropertyName("timeZoneOffset")] + public int TimeZoneOffset { get; set; } + + /// + /// The user agent value of the shopper's browser. + /// + /// The user agent value of the shopper's browser. + [JsonPropertyName("userAgent")] + public string UserAgent { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JavaScriptEnabledOption { get; private set; } + + /// + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. + /// + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. + [JsonPropertyName("javaScriptEnabled")] + public bool? JavaScriptEnabled { get { return this._JavaScriptEnabledOption; } set { this._JavaScriptEnabledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BrowserInfo {\n"); + sb.Append(" AcceptHeader: ").Append(AcceptHeader).Append("\n"); + sb.Append(" ColorDepth: ").Append(ColorDepth).Append("\n"); + sb.Append(" JavaEnabled: ").Append(JavaEnabled).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" ScreenHeight: ").Append(ScreenHeight).Append("\n"); + sb.Append(" ScreenWidth: ").Append(ScreenWidth).Append("\n"); + sb.Append(" TimeZoneOffset: ").Append(TimeZoneOffset).Append("\n"); + sb.Append(" UserAgent: ").Append(UserAgent).Append("\n"); + sb.Append(" JavaScriptEnabled: ").Append(JavaScriptEnabled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BrowserInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BrowserInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptHeader = default; + Option colorDepth = default; + Option javaEnabled = default; + Option language = default; + Option screenHeight = default; + Option screenWidth = default; + Option timeZoneOffset = default; + Option userAgent = default; + Option javaScriptEnabled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptHeader": + acceptHeader = new Option(utf8JsonReader.GetString()!); + break; + case "colorDepth": + colorDepth = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "javaEnabled": + javaEnabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "screenHeight": + screenHeight = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "screenWidth": + screenWidth = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "timeZoneOffset": + timeZoneOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "userAgent": + userAgent = new Option(utf8JsonReader.GetString()!); + break; + case "javaScriptEnabled": + javaScriptEnabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!acceptHeader.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(acceptHeader)); + + if (!colorDepth.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(colorDepth)); + + if (!javaEnabled.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(javaEnabled)); + + if (!language.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(language)); + + if (!screenHeight.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(screenHeight)); + + if (!screenWidth.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(screenWidth)); + + if (!timeZoneOffset.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(timeZoneOffset)); + + if (!userAgent.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(userAgent)); + + return new BrowserInfo(acceptHeader.Value!, colorDepth.Value!.Value!, javaEnabled.Value!.Value!, language.Value!, screenHeight.Value!.Value!, screenWidth.Value!.Value!, timeZoneOffset.Value!.Value!, userAgent.Value!, javaScriptEnabled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BrowserInfo browserInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, browserInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BrowserInfo browserInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (browserInfo.AcceptHeader != null) + writer.WriteString("acceptHeader", browserInfo.AcceptHeader); + + writer.WriteNumber("colorDepth", browserInfo.ColorDepth); + + writer.WriteBoolean("javaEnabled", browserInfo.JavaEnabled); + + if (browserInfo.Language != null) + writer.WriteString("language", browserInfo.Language); + + writer.WriteNumber("screenHeight", browserInfo.ScreenHeight); + + writer.WriteNumber("screenWidth", browserInfo.ScreenWidth); + + writer.WriteNumber("timeZoneOffset", browserInfo.TimeZoneOffset); + + if (browserInfo.UserAgent != null) + writer.WriteString("userAgent", browserInfo.UserAgent); + + if (browserInfo._JavaScriptEnabledOption.IsSet) + writer.WriteBoolean("javaScriptEnabled", browserInfo._JavaScriptEnabledOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/CancelOrderRequest.cs b/Adyen/Checkout/Models/CancelOrderRequest.cs new file mode 100644 index 000000000..ee273bd38 --- /dev/null +++ b/Adyen/Checkout/Models/CancelOrderRequest.cs @@ -0,0 +1,190 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CancelOrderRequest. + /// + public partial class CancelOrderRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier that orderData belongs to. + /// order + [JsonConstructor] + public CancelOrderRequest(string merchantAccount, EncryptedOrderData order) + { + MerchantAccount = merchantAccount; + Order = order; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CancelOrderRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier that orderData belongs to. + /// + /// The merchant account identifier that orderData belongs to. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("order")] + public EncryptedOrderData Order { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CancelOrderRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Order: ").Append(Order).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CancelOrderRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CancelOrderRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option order = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "order": + order = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CancelOrderRequest.", nameof(merchantAccount)); + + if (!order.IsSet) + throw new ArgumentException("Property is required for class CancelOrderRequest.", nameof(order)); + + return new CancelOrderRequest(merchantAccount.Value!, order.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CancelOrderRequest cancelOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cancelOrderRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CancelOrderRequest cancelOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (cancelOrderRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", cancelOrderRequest.MerchantAccount); + + writer.WritePropertyName("order"); + JsonSerializer.Serialize(writer, cancelOrderRequest.Order, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Checkout/Models/CancelOrderResponse.cs b/Adyen/Checkout/Models/CancelOrderResponse.cs new file mode 100644 index 000000000..545d302eb --- /dev/null +++ b/Adyen/Checkout/Models/CancelOrderResponse.cs @@ -0,0 +1,289 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CancelOrderResponse. + /// + public partial class CancelOrderResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A unique reference of the cancellation request. + /// The result of the cancellation request. Possible values: * **Received** – Indicates the cancellation has successfully been received by Adyen, and will be processed. + [JsonConstructor] + public CancelOrderResponse(string pspReference, ResultCodeEnum resultCode) + { + PspReference = pspReference; + ResultCode = resultCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CancelOrderResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the cancellation request. Possible values: * **Received** – Indicates the cancellation has successfully been received by Adyen, and will be processed. + /// + /// The result of the cancellation request. Possible values: * **Received** – Indicates the cancellation has successfully been received by Adyen, and will be processed. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Received - Received + /// + public static readonly ResultCodeEnum Received = new("Received"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Received" => ResultCodeEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Received) + return "Received"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the cancellation request. Possible values: * **Received** – Indicates the cancellation has successfully been received by Adyen, and will be processed. + /// + /// The result of the cancellation request. Possible values: * **Received** – Indicates the cancellation has successfully been received by Adyen, and will be processed. + [JsonPropertyName("resultCode")] + public ResultCodeEnum ResultCode { get; set; } + + /// + /// A unique reference of the cancellation request. + /// + /// A unique reference of the cancellation request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CancelOrderResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CancelOrderResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CancelOrderResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option resultCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(CancelOrderResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class CancelOrderResponse.", nameof(pspReference)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class CancelOrderResponse.", nameof(resultCode)); + + return new CancelOrderResponse(pspReference.Value!, resultCode.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CancelOrderResponse cancelOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cancelOrderResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CancelOrderResponse cancelOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (cancelOrderResponse.PspReference != null) + writer.WriteString("pspReference", cancelOrderResponse.PspReference); + + if (cancelOrderResponse.ResultCode != null) + { + string? resultCodeRawValue = CancelOrderResponse.ResultCodeEnum.ToJsonValue(cancelOrderResponse.ResultCode); + writer.WriteString("resultCode", resultCodeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/CardBrandDetails.cs b/Adyen/Checkout/Models/CardBrandDetails.cs new file mode 100644 index 000000000..17389644d --- /dev/null +++ b/Adyen/Checkout/Models/CardBrandDetails.cs @@ -0,0 +1,201 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CardBrandDetails. + /// + public partial class CardBrandDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if you support the card brand. + /// The name of the card brand. + [JsonConstructor] + public CardBrandDetails(Option supported = default, Option type = default) + { + _SupportedOption = supported; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardBrandDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SupportedOption { get; private set; } + + /// + /// Indicates if you support the card brand. + /// + /// Indicates if you support the card brand. + [JsonPropertyName("supported")] + public bool? Supported { get { return this._SupportedOption; } set { this._SupportedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The name of the card brand. + /// + /// The name of the card brand. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardBrandDetails {\n"); + sb.Append(" Supported: ").Append(Supported).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardBrandDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardBrandDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option supported = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "supported": + supported = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardBrandDetails(supported, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardBrandDetails cardBrandDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardBrandDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardBrandDetails cardBrandDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardBrandDetails._SupportedOption.IsSet) + writer.WriteBoolean("supported", cardBrandDetails._SupportedOption.Value!.Value); + + if (cardBrandDetails._TypeOption.IsSet) + if (cardBrandDetails.Type != null) + writer.WriteString("type", cardBrandDetails.Type); + } + } +} diff --git a/Adyen/Checkout/Models/CardDetails.cs b/Adyen/Checkout/Models/CardDetails.cs new file mode 100644 index 000000000..e5bcc8c11 --- /dev/null +++ b/Adyen/Checkout/Models/CardDetails.cs @@ -0,0 +1,1130 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CardDetails. + /// + public partial class CardDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// The checkout attempt identifier. + /// cupsecureplusSmscode + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + /// The encrypted card number. + /// The encrypted card expiry month. + /// The encrypted card expiry year. + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// The encrypted card verification code. + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The encoded fastlane data blob + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// The name of the card holder. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + /// An identifier used for the Click to Pay transaction. + /// The SRC reference for the Click to Pay token. + /// The scheme that is being used for Click to Pay. + /// The reference for the Click to Pay token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. (default to TypeEnum.Scheme) + [JsonConstructor] + public CardDetails(Option billingSequenceNumber = default, Option brand = default, Option checkoutAttemptId = default, Option cupsecureplusSmscode = default, Option cvc = default, Option encryptedCard = default, Option encryptedCardNumber = default, Option encryptedExpiryMonth = default, Option encryptedExpiryYear = default, Option encryptedPassword = default, Option encryptedSecurityCode = default, Option expiryMonth = default, Option expiryYear = default, Option fastlaneData = default, Option fundingSource = default, Option holderName = default, Option networkPaymentReference = default, Option number = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option srcCorrelationId = default, Option srcDigitalCardId = default, Option srcScheme = default, Option srcTokenReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + _BillingSequenceNumberOption = billingSequenceNumber; + _BrandOption = brand; + _CheckoutAttemptIdOption = checkoutAttemptId; + _CupsecureplusSmscodeOption = cupsecureplusSmscode; + _CvcOption = cvc; + _EncryptedCardOption = encryptedCard; + _EncryptedCardNumberOption = encryptedCardNumber; + _EncryptedExpiryMonthOption = encryptedExpiryMonth; + _EncryptedExpiryYearOption = encryptedExpiryYear; + _EncryptedPasswordOption = encryptedPassword; + _EncryptedSecurityCodeOption = encryptedSecurityCode; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _FastlaneDataOption = fastlaneData; + _FundingSourceOption = fundingSource; + _HolderNameOption = holderName; + _NetworkPaymentReferenceOption = networkPaymentReference; + _NumberOption = number; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _SrcCorrelationIdOption = srcCorrelationId; + _SrcDigitalCardIdOption = srcDigitalCardId; + _SrcSchemeOption = srcScheme; + _SrcTokenReferenceOption = srcTokenReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Bcmc - bcmc + /// + public static readonly TypeEnum Bcmc = new("bcmc"); + + /// + /// TypeEnum.Scheme - scheme + /// + public static readonly TypeEnum Scheme = new("scheme"); + + /// + /// TypeEnum.NetworkToken - networkToken + /// + public static readonly TypeEnum NetworkToken = new("networkToken"); + + /// + /// TypeEnum.Giftcard - giftcard + /// + public static readonly TypeEnum Giftcard = new("giftcard"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + /// + /// TypeEnum.Clicktopay - clicktopay + /// + public static readonly TypeEnum Clicktopay = new("clicktopay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bcmc" => TypeEnum.Bcmc, + "scheme" => TypeEnum.Scheme, + "networkToken" => TypeEnum.NetworkToken, + "giftcard" => TypeEnum.Giftcard, + "card" => TypeEnum.Card, + "clicktopay" => TypeEnum.Clicktopay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Bcmc) + return "bcmc"; + + if (value == TypeEnum.Scheme) + return "scheme"; + + if (value == TypeEnum.NetworkToken) + return "networkToken"; + + if (value == TypeEnum.Giftcard) + return "giftcard"; + + if (value == TypeEnum.Card) + return "card"; + + if (value == TypeEnum.Clicktopay) + return "clicktopay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupsecureplusSmscodeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cupsecureplus.smscode")] + [Obsolete("")] + public string? CupsecureplusSmscode { get { return this._CupsecureplusSmscodeOption; } set { this._CupsecureplusSmscodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardOption { get; private set; } + + /// + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + /// + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + [JsonPropertyName("encryptedCard")] + public string? EncryptedCard { get { return this._EncryptedCardOption; } set { this._EncryptedCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardNumberOption { get; private set; } + + /// + /// The encrypted card number. + /// + /// The encrypted card number. + [JsonPropertyName("encryptedCardNumber")] + public string? EncryptedCardNumber { get { return this._EncryptedCardNumberOption; } set { this._EncryptedCardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryMonthOption { get; private set; } + + /// + /// The encrypted card expiry month. + /// + /// The encrypted card expiry month. + [JsonPropertyName("encryptedExpiryMonth")] + public string? EncryptedExpiryMonth { get { return this._EncryptedExpiryMonthOption; } set { this._EncryptedExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryYearOption { get; private set; } + + /// + /// The encrypted card expiry year. + /// + /// The encrypted card expiry year. + [JsonPropertyName("encryptedExpiryYear")] + public string? EncryptedExpiryYear { get { return this._EncryptedExpiryYearOption; } set { this._EncryptedExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedPasswordOption { get; private set; } + + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + [JsonPropertyName("encryptedPassword")] + public string? EncryptedPassword { get { return this._EncryptedPasswordOption; } set { this._EncryptedPasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedSecurityCodeOption { get; private set; } + + /// + /// The encrypted card verification code. + /// + /// The encrypted card verification code. + [JsonPropertyName("encryptedSecurityCode")] + public string? EncryptedSecurityCode { get { return this._EncryptedSecurityCodeOption; } set { this._EncryptedSecurityCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FastlaneDataOption { get; private set; } + + /// + /// The encoded fastlane data blob + /// + /// The encoded fastlane data blob + [JsonPropertyName("fastlaneData")] + public string? FastlaneData { get { return this._FastlaneDataOption; } set { this._FastlaneDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the card holder. + /// + /// The name of the card holder. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkPaymentReferenceOption { get; private set; } + + /// + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + [JsonPropertyName("networkPaymentReference")] + public string? NetworkPaymentReference { get { return this._NetworkPaymentReferenceOption; } set { this._NetworkPaymentReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcCorrelationIdOption { get; private set; } + + /// + /// An identifier used for the Click to Pay transaction. + /// + /// An identifier used for the Click to Pay transaction. + [JsonPropertyName("srcCorrelationId")] + public string? SrcCorrelationId { get { return this._SrcCorrelationIdOption; } set { this._SrcCorrelationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcDigitalCardIdOption { get; private set; } + + /// + /// The SRC reference for the Click to Pay token. + /// + /// The SRC reference for the Click to Pay token. + [JsonPropertyName("srcDigitalCardId")] + public string? SrcDigitalCardId { get { return this._SrcDigitalCardIdOption; } set { this._SrcDigitalCardIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcSchemeOption { get; private set; } + + /// + /// The scheme that is being used for Click to Pay. + /// + /// The scheme that is being used for Click to Pay. + [JsonPropertyName("srcScheme")] + public string? SrcScheme { get { return this._SrcSchemeOption; } set { this._SrcSchemeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcTokenReferenceOption { get; private set; } + + /// + /// The reference for the Click to Pay token. + /// + /// The reference for the Click to Pay token. + [JsonPropertyName("srcTokenReference")] + public string? SrcTokenReference { get { return this._SrcTokenReferenceOption; } set { this._SrcTokenReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardDetails {\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" CupsecureplusSmscode: ").Append(CupsecureplusSmscode).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" EncryptedCard: ").Append(EncryptedCard).Append("\n"); + sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); + sb.Append(" EncryptedExpiryMonth: ").Append(EncryptedExpiryMonth).Append("\n"); + sb.Append(" EncryptedExpiryYear: ").Append(EncryptedExpiryYear).Append("\n"); + sb.Append(" EncryptedPassword: ").Append(EncryptedPassword).Append("\n"); + sb.Append(" EncryptedSecurityCode: ").Append(EncryptedSecurityCode).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" FastlaneData: ").Append(FastlaneData).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" NetworkPaymentReference: ").Append(NetworkPaymentReference).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" SrcCorrelationId: ").Append(SrcCorrelationId).Append("\n"); + sb.Append(" SrcDigitalCardId: ").Append(SrcDigitalCardId).Append("\n"); + sb.Append(" SrcScheme: ").Append(SrcScheme).Append("\n"); + sb.Append(" SrcTokenReference: ").Append(SrcTokenReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EncryptedCard (string) maxLength + if (this.EncryptedCard != null && this.EncryptedCard.Length > 40000) + { + yield return new ValidationResult("Invalid value for EncryptedCard, length must be less than 40000.", new [] { "EncryptedCard" }); + } + + // EncryptedCardNumber (string) maxLength + if (this.EncryptedCardNumber != null && this.EncryptedCardNumber.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedCardNumber, length must be less than 15000.", new [] { "EncryptedCardNumber" }); + } + + // EncryptedExpiryMonth (string) maxLength + if (this.EncryptedExpiryMonth != null && this.EncryptedExpiryMonth.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryMonth, length must be less than 15000.", new [] { "EncryptedExpiryMonth" }); + } + + // EncryptedExpiryYear (string) maxLength + if (this.EncryptedExpiryYear != null && this.EncryptedExpiryYear.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryYear, length must be less than 15000.", new [] { "EncryptedExpiryYear" }); + } + + // EncryptedPassword (string) maxLength + if (this.EncryptedPassword != null && this.EncryptedPassword.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedPassword, length must be less than 15000.", new [] { "EncryptedPassword" }); + } + + // EncryptedSecurityCode (string) maxLength + if (this.EncryptedSecurityCode != null && this.EncryptedSecurityCode.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedSecurityCode, length must be less than 15000.", new [] { "EncryptedSecurityCode" }); + } + + // HolderName (string) maxLength + if (this.HolderName != null && this.HolderName.Length > 15000) + { + yield return new ValidationResult("Invalid value for HolderName, length must be less than 15000.", new [] { "HolderName" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingSequenceNumber = default; + Option brand = default; + Option checkoutAttemptId = default; + Option cupsecureplusSmscode = default; + Option cvc = default; + Option encryptedCard = default; + Option encryptedCardNumber = default; + Option encryptedExpiryMonth = default; + Option encryptedExpiryYear = default; + Option encryptedPassword = default; + Option encryptedSecurityCode = default; + Option expiryMonth = default; + Option expiryYear = default; + Option fastlaneData = default; + Option fundingSource = default; + Option holderName = default; + Option networkPaymentReference = default; + Option number = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option srcCorrelationId = default; + Option srcDigitalCardId = default; + Option srcScheme = default; + Option srcTokenReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "cupsecureplus.smscode": + cupsecureplusSmscode = new Option(utf8JsonReader.GetString()!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCard": + encryptedCard = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCardNumber": + encryptedCardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryMonth": + encryptedExpiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryYear": + encryptedExpiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedPassword": + encryptedPassword = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedSecurityCode": + encryptedSecurityCode = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "fastlaneData": + fastlaneData = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(CardDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "networkPaymentReference": + networkPaymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "srcCorrelationId": + srcCorrelationId = new Option(utf8JsonReader.GetString()!); + break; + case "srcDigitalCardId": + srcDigitalCardId = new Option(utf8JsonReader.GetString()!); + break; + case "srcScheme": + srcScheme = new Option(utf8JsonReader.GetString()!); + break; + case "srcTokenReference": + srcTokenReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CardDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CardDetails(billingSequenceNumber, brand, checkoutAttemptId, cupsecureplusSmscode, cvc, encryptedCard, encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, encryptedPassword, encryptedSecurityCode, expiryMonth, expiryYear, fastlaneData, fundingSource, holderName, networkPaymentReference, number, recurringDetailReference, shopperNotificationReference, srcCorrelationId, srcDigitalCardId, srcScheme, srcTokenReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardDetails cardDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardDetails cardDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardDetails._BillingSequenceNumberOption.IsSet) + if (cardDetails.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", cardDetails.BillingSequenceNumber); + + if (cardDetails._BrandOption.IsSet) + if (cardDetails.Brand != null) + writer.WriteString("brand", cardDetails.Brand); + + if (cardDetails._CheckoutAttemptIdOption.IsSet) + if (cardDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", cardDetails.CheckoutAttemptId); + + if (cardDetails._CupsecureplusSmscodeOption.IsSet) + if (cardDetails.CupsecureplusSmscode != null) + writer.WriteString("cupsecureplus.smscode", cardDetails.CupsecureplusSmscode); + + if (cardDetails._CvcOption.IsSet) + if (cardDetails.Cvc != null) + writer.WriteString("cvc", cardDetails.Cvc); + + if (cardDetails._EncryptedCardOption.IsSet) + if (cardDetails.EncryptedCard != null) + writer.WriteString("encryptedCard", cardDetails.EncryptedCard); + + if (cardDetails._EncryptedCardNumberOption.IsSet) + if (cardDetails.EncryptedCardNumber != null) + writer.WriteString("encryptedCardNumber", cardDetails.EncryptedCardNumber); + + if (cardDetails._EncryptedExpiryMonthOption.IsSet) + if (cardDetails.EncryptedExpiryMonth != null) + writer.WriteString("encryptedExpiryMonth", cardDetails.EncryptedExpiryMonth); + + if (cardDetails._EncryptedExpiryYearOption.IsSet) + if (cardDetails.EncryptedExpiryYear != null) + writer.WriteString("encryptedExpiryYear", cardDetails.EncryptedExpiryYear); + + if (cardDetails._EncryptedPasswordOption.IsSet) + if (cardDetails.EncryptedPassword != null) + writer.WriteString("encryptedPassword", cardDetails.EncryptedPassword); + + if (cardDetails._EncryptedSecurityCodeOption.IsSet) + if (cardDetails.EncryptedSecurityCode != null) + writer.WriteString("encryptedSecurityCode", cardDetails.EncryptedSecurityCode); + + if (cardDetails._ExpiryMonthOption.IsSet) + if (cardDetails.ExpiryMonth != null) + writer.WriteString("expiryMonth", cardDetails.ExpiryMonth); + + if (cardDetails._ExpiryYearOption.IsSet) + if (cardDetails.ExpiryYear != null) + writer.WriteString("expiryYear", cardDetails.ExpiryYear); + + if (cardDetails._FastlaneDataOption.IsSet) + if (cardDetails.FastlaneData != null) + writer.WriteString("fastlaneData", cardDetails.FastlaneData); + + if (cardDetails._FundingSourceOption.IsSet && cardDetails.FundingSource != null) + { + string? fundingSourceRawValue = CardDetails.FundingSourceEnum.ToJsonValue(cardDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (cardDetails._HolderNameOption.IsSet) + if (cardDetails.HolderName != null) + writer.WriteString("holderName", cardDetails.HolderName); + + if (cardDetails._NetworkPaymentReferenceOption.IsSet) + if (cardDetails.NetworkPaymentReference != null) + writer.WriteString("networkPaymentReference", cardDetails.NetworkPaymentReference); + + if (cardDetails._NumberOption.IsSet) + if (cardDetails.Number != null) + writer.WriteString("number", cardDetails.Number); + + if (cardDetails._RecurringDetailReferenceOption.IsSet) + if (cardDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", cardDetails.RecurringDetailReference); + + if (cardDetails._ShopperNotificationReferenceOption.IsSet) + if (cardDetails.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", cardDetails.ShopperNotificationReference); + + if (cardDetails._SrcCorrelationIdOption.IsSet) + if (cardDetails.SrcCorrelationId != null) + writer.WriteString("srcCorrelationId", cardDetails.SrcCorrelationId); + + if (cardDetails._SrcDigitalCardIdOption.IsSet) + if (cardDetails.SrcDigitalCardId != null) + writer.WriteString("srcDigitalCardId", cardDetails.SrcDigitalCardId); + + if (cardDetails._SrcSchemeOption.IsSet) + if (cardDetails.SrcScheme != null) + writer.WriteString("srcScheme", cardDetails.SrcScheme); + + if (cardDetails._SrcTokenReferenceOption.IsSet) + if (cardDetails.SrcTokenReference != null) + writer.WriteString("srcTokenReference", cardDetails.SrcTokenReference); + + if (cardDetails._StoredPaymentMethodIdOption.IsSet) + if (cardDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", cardDetails.StoredPaymentMethodId); + + if (cardDetails._ThreeDS2SdkVersionOption.IsSet) + if (cardDetails.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", cardDetails.ThreeDS2SdkVersion); + + if (cardDetails._TypeOption.IsSet && cardDetails.Type != null) + { + string? typeRawValue = CardDetails.TypeEnum.ToJsonValue(cardDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/CardDetailsRequest.cs b/Adyen/Checkout/Models/CardDetailsRequest.cs new file mode 100644 index 000000000..a179e86b0 --- /dev/null +++ b/Adyen/Checkout/Models/CardDetailsRequest.cs @@ -0,0 +1,279 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CardDetailsRequest. + /// + public partial class CardDetailsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// A minimum of the first six digits of the card number. The full card number gives the best result. You must be [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide) to collect raw card data. Alternatively, you can use the `encryptedCardNumber` field. + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// The encrypted card number. + /// The card brands you support. This is the [`brands`](https://docs.adyen.com/api-explorer/Checkout/latest/post/paymentMethods#responses-200-paymentMethods-brands) array from your [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. If not included, our API uses the ones configured for your merchant account and, if provided, the country code. + [JsonConstructor] + public CardDetailsRequest(string merchantAccount, Option cardNumber = default, Option countryCode = default, Option encryptedCardNumber = default, Option?> supportedBrands = default) + { + MerchantAccount = merchantAccount; + _CardNumberOption = cardNumber; + _CountryCodeOption = countryCode; + _EncryptedCardNumberOption = encryptedCardNumber; + _SupportedBrandsOption = supportedBrands; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardDetailsRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardNumberOption { get; private set; } + + /// + /// A minimum of the first six digits of the card number. The full card number gives the best result. You must be [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide) to collect raw card data. Alternatively, you can use the `encryptedCardNumber` field. + /// + /// A minimum of the first six digits of the card number. The full card number gives the best result. You must be [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide) to collect raw card data. Alternatively, you can use the `encryptedCardNumber` field. + [JsonPropertyName("cardNumber")] + public string? CardNumber { get { return this._CardNumberOption; } set { this._CardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardNumberOption { get; private set; } + + /// + /// The encrypted card number. + /// + /// The encrypted card number. + [JsonPropertyName("encryptedCardNumber")] + public string? EncryptedCardNumber { get { return this._EncryptedCardNumberOption; } set { this._EncryptedCardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SupportedBrandsOption { get; private set; } + + /// + /// The card brands you support. This is the [`brands`](https://docs.adyen.com/api-explorer/Checkout/latest/post/paymentMethods#responses-200-paymentMethods-brands) array from your [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. If not included, our API uses the ones configured for your merchant account and, if provided, the country code. + /// + /// The card brands you support. This is the [`brands`](https://docs.adyen.com/api-explorer/Checkout/latest/post/paymentMethods#responses-200-paymentMethods-brands) array from your [`/paymentMethods`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/paymentMethods) response. If not included, our API uses the ones configured for your merchant account and, if provided, the country code. + [JsonPropertyName("supportedBrands")] + public List? SupportedBrands { get { return this._SupportedBrandsOption; } set { this._SupportedBrandsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardDetailsRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); + sb.Append(" SupportedBrands: ").Append(SupportedBrands).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EncryptedCardNumber (string) maxLength + if (this.EncryptedCardNumber != null && this.EncryptedCardNumber.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedCardNumber, length must be less than 15000.", new [] { "EncryptedCardNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardDetailsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardDetailsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option cardNumber = default; + Option countryCode = default; + Option encryptedCardNumber = default; + Option?> supportedBrands = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "cardNumber": + cardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCardNumber": + encryptedCardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "supportedBrands": + supportedBrands = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CardDetailsRequest.", nameof(merchantAccount)); + + return new CardDetailsRequest(merchantAccount.Value!, cardNumber, countryCode, encryptedCardNumber, supportedBrands); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardDetailsRequest cardDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardDetailsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardDetailsRequest cardDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardDetailsRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", cardDetailsRequest.MerchantAccount); + + if (cardDetailsRequest._CardNumberOption.IsSet) + if (cardDetailsRequest.CardNumber != null) + writer.WriteString("cardNumber", cardDetailsRequest.CardNumber); + + if (cardDetailsRequest._CountryCodeOption.IsSet) + if (cardDetailsRequest.CountryCode != null) + writer.WriteString("countryCode", cardDetailsRequest.CountryCode); + + if (cardDetailsRequest._EncryptedCardNumberOption.IsSet) + if (cardDetailsRequest.EncryptedCardNumber != null) + writer.WriteString("encryptedCardNumber", cardDetailsRequest.EncryptedCardNumber); + + if (cardDetailsRequest._SupportedBrandsOption.IsSet) + { + writer.WritePropertyName("supportedBrands"); + JsonSerializer.Serialize(writer, cardDetailsRequest.SupportedBrands, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/CardDetailsResponse.cs b/Adyen/Checkout/Models/CardDetailsResponse.cs new file mode 100644 index 000000000..aa0782bf5 --- /dev/null +++ b/Adyen/Checkout/Models/CardDetailsResponse.cs @@ -0,0 +1,252 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CardDetailsResponse. + /// + public partial class CardDetailsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of brands identified for the card. + /// The funding source of the card, for example **DEBIT**, **CREDIT**, or **PREPAID**. + /// Indicates if this is a commercial card or a consumer card. If **true**, it is a commercial card. If **false**, it is a consumer card. + /// The two-letter country code of the country where the card was issued. + [JsonConstructor] + public CardDetailsResponse(Option?> brands = default, Option fundingSource = default, Option isCardCommercial = default, Option issuingCountryCode = default) + { + _BrandsOption = brands; + _FundingSourceOption = fundingSource; + _IsCardCommercialOption = isCardCommercial; + _IssuingCountryCodeOption = issuingCountryCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardDetailsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BrandsOption { get; private set; } + + /// + /// The list of brands identified for the card. + /// + /// The list of brands identified for the card. + [JsonPropertyName("brands")] + public List? Brands { get { return this._BrandsOption; } set { this._BrandsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source of the card, for example **DEBIT**, **CREDIT**, or **PREPAID**. + /// + /// The funding source of the card, for example **DEBIT**, **CREDIT**, or **PREPAID**. + [JsonPropertyName("fundingSource")] + public string? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IsCardCommercialOption { get; private set; } + + /// + /// Indicates if this is a commercial card or a consumer card. If **true**, it is a commercial card. If **false**, it is a consumer card. + /// + /// Indicates if this is a commercial card or a consumer card. If **true**, it is a commercial card. If **false**, it is a consumer card. + [JsonPropertyName("isCardCommercial")] + public bool? IsCardCommercial { get { return this._IsCardCommercialOption; } set { this._IsCardCommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuingCountryCodeOption { get; private set; } + + /// + /// The two-letter country code of the country where the card was issued. + /// + /// The two-letter country code of the country where the card was issued. + [JsonPropertyName("issuingCountryCode")] + public string? IssuingCountryCode { get { return this._IssuingCountryCodeOption; } set { this._IssuingCountryCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardDetailsResponse {\n"); + sb.Append(" Brands: ").Append(Brands).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" IsCardCommercial: ").Append(IsCardCommercial).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardDetailsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardDetailsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> brands = default; + Option fundingSource = default; + Option isCardCommercial = default; + Option issuingCountryCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brands": + brands = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "isCardCommercial": + isCardCommercial = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardDetailsResponse(brands, fundingSource, isCardCommercial, issuingCountryCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardDetailsResponse cardDetailsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardDetailsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardDetailsResponse cardDetailsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardDetailsResponse._BrandsOption.IsSet) + { + writer.WritePropertyName("brands"); + JsonSerializer.Serialize(writer, cardDetailsResponse.Brands, jsonSerializerOptions); + } + if (cardDetailsResponse._FundingSourceOption.IsSet) + if (cardDetailsResponse.FundingSource != null) + writer.WriteString("fundingSource", cardDetailsResponse.FundingSource); + + if (cardDetailsResponse._IsCardCommercialOption.IsSet) + writer.WriteBoolean("isCardCommercial", cardDetailsResponse._IsCardCommercialOption.Value!.Value); + + if (cardDetailsResponse._IssuingCountryCodeOption.IsSet) + if (cardDetailsResponse.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", cardDetailsResponse.IssuingCountryCode); + } + } +} diff --git a/Adyen/Checkout/Models/CardDonations.cs b/Adyen/Checkout/Models/CardDonations.cs new file mode 100644 index 000000000..b2ce5eaae --- /dev/null +++ b/Adyen/Checkout/Models/CardDonations.cs @@ -0,0 +1,1130 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CardDonations. + /// + public partial class CardDonations : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// The checkout attempt identifier. + /// cupsecureplusSmscode + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + /// The encrypted card number. + /// The encrypted card expiry month. + /// The encrypted card expiry year. + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// The encrypted card verification code. + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The encoded fastlane data blob + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// The name of the card holder. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + /// An identifier used for the Click to Pay transaction. + /// The SRC reference for the Click to Pay token. + /// The scheme that is being used for Click to Pay. + /// The reference for the Click to Pay token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. (default to TypeEnum.Scheme) + [JsonConstructor] + public CardDonations(Option billingSequenceNumber = default, Option brand = default, Option checkoutAttemptId = default, Option cupsecureplusSmscode = default, Option cvc = default, Option encryptedCard = default, Option encryptedCardNumber = default, Option encryptedExpiryMonth = default, Option encryptedExpiryYear = default, Option encryptedPassword = default, Option encryptedSecurityCode = default, Option expiryMonth = default, Option expiryYear = default, Option fastlaneData = default, Option fundingSource = default, Option holderName = default, Option networkPaymentReference = default, Option number = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option srcCorrelationId = default, Option srcDigitalCardId = default, Option srcScheme = default, Option srcTokenReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + _BillingSequenceNumberOption = billingSequenceNumber; + _BrandOption = brand; + _CheckoutAttemptIdOption = checkoutAttemptId; + _CupsecureplusSmscodeOption = cupsecureplusSmscode; + _CvcOption = cvc; + _EncryptedCardOption = encryptedCard; + _EncryptedCardNumberOption = encryptedCardNumber; + _EncryptedExpiryMonthOption = encryptedExpiryMonth; + _EncryptedExpiryYearOption = encryptedExpiryYear; + _EncryptedPasswordOption = encryptedPassword; + _EncryptedSecurityCodeOption = encryptedSecurityCode; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _FastlaneDataOption = fastlaneData; + _FundingSourceOption = fundingSource; + _HolderNameOption = holderName; + _NetworkPaymentReferenceOption = networkPaymentReference; + _NumberOption = number; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _SrcCorrelationIdOption = srcCorrelationId; + _SrcDigitalCardIdOption = srcDigitalCardId; + _SrcSchemeOption = srcScheme; + _SrcTokenReferenceOption = srcTokenReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardDonations() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Bcmc - bcmc + /// + public static readonly TypeEnum Bcmc = new("bcmc"); + + /// + /// TypeEnum.Scheme - scheme + /// + public static readonly TypeEnum Scheme = new("scheme"); + + /// + /// TypeEnum.NetworkToken - networkToken + /// + public static readonly TypeEnum NetworkToken = new("networkToken"); + + /// + /// TypeEnum.Giftcard - giftcard + /// + public static readonly TypeEnum Giftcard = new("giftcard"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + /// + /// TypeEnum.Clicktopay - clicktopay + /// + public static readonly TypeEnum Clicktopay = new("clicktopay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bcmc" => TypeEnum.Bcmc, + "scheme" => TypeEnum.Scheme, + "networkToken" => TypeEnum.NetworkToken, + "giftcard" => TypeEnum.Giftcard, + "card" => TypeEnum.Card, + "clicktopay" => TypeEnum.Clicktopay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Bcmc) + return "bcmc"; + + if (value == TypeEnum.Scheme) + return "scheme"; + + if (value == TypeEnum.NetworkToken) + return "networkToken"; + + if (value == TypeEnum.Giftcard) + return "giftcard"; + + if (value == TypeEnum.Card) + return "card"; + + if (value == TypeEnum.Clicktopay) + return "clicktopay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + /// + /// Default payment method details. Common for scheme payment methods, and for simple payment method details. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupsecureplusSmscodeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cupsecureplus.smscode")] + [Obsolete("")] + public string? CupsecureplusSmscode { get { return this._CupsecureplusSmscodeOption; } set { this._CupsecureplusSmscodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardOption { get; private set; } + + /// + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + /// + /// Only include this for JSON Web Encryption (JWE) implementations. The JWE-encrypted card details. + [JsonPropertyName("encryptedCard")] + public string? EncryptedCard { get { return this._EncryptedCardOption; } set { this._EncryptedCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardNumberOption { get; private set; } + + /// + /// The encrypted card number. + /// + /// The encrypted card number. + [JsonPropertyName("encryptedCardNumber")] + public string? EncryptedCardNumber { get { return this._EncryptedCardNumberOption; } set { this._EncryptedCardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryMonthOption { get; private set; } + + /// + /// The encrypted card expiry month. + /// + /// The encrypted card expiry month. + [JsonPropertyName("encryptedExpiryMonth")] + public string? EncryptedExpiryMonth { get { return this._EncryptedExpiryMonthOption; } set { this._EncryptedExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryYearOption { get; private set; } + + /// + /// The encrypted card expiry year. + /// + /// The encrypted card expiry year. + [JsonPropertyName("encryptedExpiryYear")] + public string? EncryptedExpiryYear { get { return this._EncryptedExpiryYearOption; } set { this._EncryptedExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedPasswordOption { get; private set; } + + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + [JsonPropertyName("encryptedPassword")] + public string? EncryptedPassword { get { return this._EncryptedPasswordOption; } set { this._EncryptedPasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedSecurityCodeOption { get; private set; } + + /// + /// The encrypted card verification code. + /// + /// The encrypted card verification code. + [JsonPropertyName("encryptedSecurityCode")] + public string? EncryptedSecurityCode { get { return this._EncryptedSecurityCodeOption; } set { this._EncryptedSecurityCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FastlaneDataOption { get; private set; } + + /// + /// The encoded fastlane data blob + /// + /// The encoded fastlane data blob + [JsonPropertyName("fastlaneData")] + public string? FastlaneData { get { return this._FastlaneDataOption; } set { this._FastlaneDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the card holder. + /// + /// The name of the card holder. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkPaymentReferenceOption { get; private set; } + + /// + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + [JsonPropertyName("networkPaymentReference")] + public string? NetworkPaymentReference { get { return this._NetworkPaymentReferenceOption; } set { this._NetworkPaymentReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcCorrelationIdOption { get; private set; } + + /// + /// An identifier used for the Click to Pay transaction. + /// + /// An identifier used for the Click to Pay transaction. + [JsonPropertyName("srcCorrelationId")] + public string? SrcCorrelationId { get { return this._SrcCorrelationIdOption; } set { this._SrcCorrelationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcDigitalCardIdOption { get; private set; } + + /// + /// The SRC reference for the Click to Pay token. + /// + /// The SRC reference for the Click to Pay token. + [JsonPropertyName("srcDigitalCardId")] + public string? SrcDigitalCardId { get { return this._SrcDigitalCardIdOption; } set { this._SrcDigitalCardIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcSchemeOption { get; private set; } + + /// + /// The scheme that is being used for Click to Pay. + /// + /// The scheme that is being used for Click to Pay. + [JsonPropertyName("srcScheme")] + public string? SrcScheme { get { return this._SrcSchemeOption; } set { this._SrcSchemeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SrcTokenReferenceOption { get; private set; } + + /// + /// The reference for the Click to Pay token. + /// + /// The reference for the Click to Pay token. + [JsonPropertyName("srcTokenReference")] + public string? SrcTokenReference { get { return this._SrcTokenReferenceOption; } set { this._SrcTokenReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardDonations {\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" CupsecureplusSmscode: ").Append(CupsecureplusSmscode).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" EncryptedCard: ").Append(EncryptedCard).Append("\n"); + sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); + sb.Append(" EncryptedExpiryMonth: ").Append(EncryptedExpiryMonth).Append("\n"); + sb.Append(" EncryptedExpiryYear: ").Append(EncryptedExpiryYear).Append("\n"); + sb.Append(" EncryptedPassword: ").Append(EncryptedPassword).Append("\n"); + sb.Append(" EncryptedSecurityCode: ").Append(EncryptedSecurityCode).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" FastlaneData: ").Append(FastlaneData).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" NetworkPaymentReference: ").Append(NetworkPaymentReference).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" SrcCorrelationId: ").Append(SrcCorrelationId).Append("\n"); + sb.Append(" SrcDigitalCardId: ").Append(SrcDigitalCardId).Append("\n"); + sb.Append(" SrcScheme: ").Append(SrcScheme).Append("\n"); + sb.Append(" SrcTokenReference: ").Append(SrcTokenReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EncryptedCard (string) maxLength + if (this.EncryptedCard != null && this.EncryptedCard.Length > 40000) + { + yield return new ValidationResult("Invalid value for EncryptedCard, length must be less than 40000.", new [] { "EncryptedCard" }); + } + + // EncryptedCardNumber (string) maxLength + if (this.EncryptedCardNumber != null && this.EncryptedCardNumber.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedCardNumber, length must be less than 15000.", new [] { "EncryptedCardNumber" }); + } + + // EncryptedExpiryMonth (string) maxLength + if (this.EncryptedExpiryMonth != null && this.EncryptedExpiryMonth.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryMonth, length must be less than 15000.", new [] { "EncryptedExpiryMonth" }); + } + + // EncryptedExpiryYear (string) maxLength + if (this.EncryptedExpiryYear != null && this.EncryptedExpiryYear.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryYear, length must be less than 15000.", new [] { "EncryptedExpiryYear" }); + } + + // EncryptedPassword (string) maxLength + if (this.EncryptedPassword != null && this.EncryptedPassword.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedPassword, length must be less than 15000.", new [] { "EncryptedPassword" }); + } + + // EncryptedSecurityCode (string) maxLength + if (this.EncryptedSecurityCode != null && this.EncryptedSecurityCode.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedSecurityCode, length must be less than 15000.", new [] { "EncryptedSecurityCode" }); + } + + // HolderName (string) maxLength + if (this.HolderName != null && this.HolderName.Length > 15000) + { + yield return new ValidationResult("Invalid value for HolderName, length must be less than 15000.", new [] { "HolderName" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardDonationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardDonations Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingSequenceNumber = default; + Option brand = default; + Option checkoutAttemptId = default; + Option cupsecureplusSmscode = default; + Option cvc = default; + Option encryptedCard = default; + Option encryptedCardNumber = default; + Option encryptedExpiryMonth = default; + Option encryptedExpiryYear = default; + Option encryptedPassword = default; + Option encryptedSecurityCode = default; + Option expiryMonth = default; + Option expiryYear = default; + Option fastlaneData = default; + Option fundingSource = default; + Option holderName = default; + Option networkPaymentReference = default; + Option number = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option srcCorrelationId = default; + Option srcDigitalCardId = default; + Option srcScheme = default; + Option srcTokenReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "cupsecureplus.smscode": + cupsecureplusSmscode = new Option(utf8JsonReader.GetString()!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCard": + encryptedCard = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCardNumber": + encryptedCardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryMonth": + encryptedExpiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryYear": + encryptedExpiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedPassword": + encryptedPassword = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedSecurityCode": + encryptedSecurityCode = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "fastlaneData": + fastlaneData = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(CardDonations.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "networkPaymentReference": + networkPaymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "srcCorrelationId": + srcCorrelationId = new Option(utf8JsonReader.GetString()!); + break; + case "srcDigitalCardId": + srcDigitalCardId = new Option(utf8JsonReader.GetString()!); + break; + case "srcScheme": + srcScheme = new Option(utf8JsonReader.GetString()!); + break; + case "srcTokenReference": + srcTokenReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CardDonations.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CardDonations(billingSequenceNumber, brand, checkoutAttemptId, cupsecureplusSmscode, cvc, encryptedCard, encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, encryptedPassword, encryptedSecurityCode, expiryMonth, expiryYear, fastlaneData, fundingSource, holderName, networkPaymentReference, number, recurringDetailReference, shopperNotificationReference, srcCorrelationId, srcDigitalCardId, srcScheme, srcTokenReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardDonations cardDonations, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardDonations, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardDonations cardDonations, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardDonations._BillingSequenceNumberOption.IsSet) + if (cardDonations.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", cardDonations.BillingSequenceNumber); + + if (cardDonations._BrandOption.IsSet) + if (cardDonations.Brand != null) + writer.WriteString("brand", cardDonations.Brand); + + if (cardDonations._CheckoutAttemptIdOption.IsSet) + if (cardDonations.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", cardDonations.CheckoutAttemptId); + + if (cardDonations._CupsecureplusSmscodeOption.IsSet) + if (cardDonations.CupsecureplusSmscode != null) + writer.WriteString("cupsecureplus.smscode", cardDonations.CupsecureplusSmscode); + + if (cardDonations._CvcOption.IsSet) + if (cardDonations.Cvc != null) + writer.WriteString("cvc", cardDonations.Cvc); + + if (cardDonations._EncryptedCardOption.IsSet) + if (cardDonations.EncryptedCard != null) + writer.WriteString("encryptedCard", cardDonations.EncryptedCard); + + if (cardDonations._EncryptedCardNumberOption.IsSet) + if (cardDonations.EncryptedCardNumber != null) + writer.WriteString("encryptedCardNumber", cardDonations.EncryptedCardNumber); + + if (cardDonations._EncryptedExpiryMonthOption.IsSet) + if (cardDonations.EncryptedExpiryMonth != null) + writer.WriteString("encryptedExpiryMonth", cardDonations.EncryptedExpiryMonth); + + if (cardDonations._EncryptedExpiryYearOption.IsSet) + if (cardDonations.EncryptedExpiryYear != null) + writer.WriteString("encryptedExpiryYear", cardDonations.EncryptedExpiryYear); + + if (cardDonations._EncryptedPasswordOption.IsSet) + if (cardDonations.EncryptedPassword != null) + writer.WriteString("encryptedPassword", cardDonations.EncryptedPassword); + + if (cardDonations._EncryptedSecurityCodeOption.IsSet) + if (cardDonations.EncryptedSecurityCode != null) + writer.WriteString("encryptedSecurityCode", cardDonations.EncryptedSecurityCode); + + if (cardDonations._ExpiryMonthOption.IsSet) + if (cardDonations.ExpiryMonth != null) + writer.WriteString("expiryMonth", cardDonations.ExpiryMonth); + + if (cardDonations._ExpiryYearOption.IsSet) + if (cardDonations.ExpiryYear != null) + writer.WriteString("expiryYear", cardDonations.ExpiryYear); + + if (cardDonations._FastlaneDataOption.IsSet) + if (cardDonations.FastlaneData != null) + writer.WriteString("fastlaneData", cardDonations.FastlaneData); + + if (cardDonations._FundingSourceOption.IsSet && cardDonations.FundingSource != null) + { + string? fundingSourceRawValue = CardDonations.FundingSourceEnum.ToJsonValue(cardDonations._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (cardDonations._HolderNameOption.IsSet) + if (cardDonations.HolderName != null) + writer.WriteString("holderName", cardDonations.HolderName); + + if (cardDonations._NetworkPaymentReferenceOption.IsSet) + if (cardDonations.NetworkPaymentReference != null) + writer.WriteString("networkPaymentReference", cardDonations.NetworkPaymentReference); + + if (cardDonations._NumberOption.IsSet) + if (cardDonations.Number != null) + writer.WriteString("number", cardDonations.Number); + + if (cardDonations._RecurringDetailReferenceOption.IsSet) + if (cardDonations.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", cardDonations.RecurringDetailReference); + + if (cardDonations._ShopperNotificationReferenceOption.IsSet) + if (cardDonations.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", cardDonations.ShopperNotificationReference); + + if (cardDonations._SrcCorrelationIdOption.IsSet) + if (cardDonations.SrcCorrelationId != null) + writer.WriteString("srcCorrelationId", cardDonations.SrcCorrelationId); + + if (cardDonations._SrcDigitalCardIdOption.IsSet) + if (cardDonations.SrcDigitalCardId != null) + writer.WriteString("srcDigitalCardId", cardDonations.SrcDigitalCardId); + + if (cardDonations._SrcSchemeOption.IsSet) + if (cardDonations.SrcScheme != null) + writer.WriteString("srcScheme", cardDonations.SrcScheme); + + if (cardDonations._SrcTokenReferenceOption.IsSet) + if (cardDonations.SrcTokenReference != null) + writer.WriteString("srcTokenReference", cardDonations.SrcTokenReference); + + if (cardDonations._StoredPaymentMethodIdOption.IsSet) + if (cardDonations.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", cardDonations.StoredPaymentMethodId); + + if (cardDonations._ThreeDS2SdkVersionOption.IsSet) + if (cardDonations.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", cardDonations.ThreeDS2SdkVersion); + + if (cardDonations._TypeOption.IsSet && cardDonations.Type != null) + { + string? typeRawValue = CardDonations.TypeEnum.ToJsonValue(cardDonations._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/CashAppDetails.cs b/Adyen/Checkout/Models/CashAppDetails.cs new file mode 100644 index 000000000..6ee88e82e --- /dev/null +++ b/Adyen/Checkout/Models/CashAppDetails.cs @@ -0,0 +1,506 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CashAppDetails. + /// + public partial class CashAppDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Cash App issued cashtag for recurring payment + /// The checkout attempt identifier. + /// Cash App issued customerId for recurring payment + /// Cash App issued grantId for one time payment + /// Cash App issued onFileGrantId for recurring payment + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Cash App request id + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The payment method subtype. + /// cashapp (default to TypeEnum.Cashapp) + [JsonConstructor] + public CashAppDetails(Option cashtag = default, Option checkoutAttemptId = default, Option customerId = default, Option grantId = default, Option onFileGrantId = default, Option recurringDetailReference = default, Option requestId = default, Option storedPaymentMethodId = default, Option subtype = default, Option type = default) + { + _CashtagOption = cashtag; + _CheckoutAttemptIdOption = checkoutAttemptId; + _CustomerIdOption = customerId; + _GrantIdOption = grantId; + _OnFileGrantIdOption = onFileGrantId; + _RecurringDetailReferenceOption = recurringDetailReference; + _RequestIdOption = requestId; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubtypeOption = subtype; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CashAppDetails() + { + } + + partial void OnCreated(); + + /// + /// cashapp + /// + /// cashapp + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Cashapp - cashapp + /// + public static readonly TypeEnum Cashapp = new("cashapp"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "cashapp" => TypeEnum.Cashapp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Cashapp) + return "cashapp"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// cashapp + /// + /// cashapp + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CashtagOption { get; private set; } + + /// + /// Cash App issued cashtag for recurring payment + /// + /// Cash App issued cashtag for recurring payment + [JsonPropertyName("cashtag")] + public string? Cashtag { get { return this._CashtagOption; } set { this._CashtagOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomerIdOption { get; private set; } + + /// + /// Cash App issued customerId for recurring payment + /// + /// Cash App issued customerId for recurring payment + [JsonPropertyName("customerId")] + public string? CustomerId { get { return this._CustomerIdOption; } set { this._CustomerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GrantIdOption { get; private set; } + + /// + /// Cash App issued grantId for one time payment + /// + /// Cash App issued grantId for one time payment + [JsonPropertyName("grantId")] + public string? GrantId { get { return this._GrantIdOption; } set { this._GrantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OnFileGrantIdOption { get; private set; } + + /// + /// Cash App issued onFileGrantId for recurring payment + /// + /// Cash App issued onFileGrantId for recurring payment + [JsonPropertyName("onFileGrantId")] + public string? OnFileGrantId { get { return this._OnFileGrantIdOption; } set { this._OnFileGrantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// Cash App request id + /// + /// Cash App request id + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// The payment method subtype. + /// + /// The payment method subtype. + [JsonPropertyName("subtype")] + public string? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CashAppDetails {\n"); + sb.Append(" Cashtag: ").Append(Cashtag).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" CustomerId: ").Append(CustomerId).Append("\n"); + sb.Append(" GrantId: ").Append(GrantId).Append("\n"); + sb.Append(" OnFileGrantId: ").Append(OnFileGrantId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CashAppDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CashAppDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cashtag = default; + Option checkoutAttemptId = default; + Option customerId = default; + Option grantId = default; + Option onFileGrantId = default; + Option recurringDetailReference = default; + Option requestId = default; + Option storedPaymentMethodId = default; + Option subtype = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cashtag": + cashtag = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "customerId": + customerId = new Option(utf8JsonReader.GetString()!); + break; + case "grantId": + grantId = new Option(utf8JsonReader.GetString()!); + break; + case "onFileGrantId": + onFileGrantId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + subtype = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CashAppDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CashAppDetails(cashtag, checkoutAttemptId, customerId, grantId, onFileGrantId, recurringDetailReference, requestId, storedPaymentMethodId, subtype, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CashAppDetails cashAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cashAppDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CashAppDetails cashAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (cashAppDetails._CashtagOption.IsSet) + if (cashAppDetails.Cashtag != null) + writer.WriteString("cashtag", cashAppDetails.Cashtag); + + if (cashAppDetails._CheckoutAttemptIdOption.IsSet) + if (cashAppDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", cashAppDetails.CheckoutAttemptId); + + if (cashAppDetails._CustomerIdOption.IsSet) + if (cashAppDetails.CustomerId != null) + writer.WriteString("customerId", cashAppDetails.CustomerId); + + if (cashAppDetails._GrantIdOption.IsSet) + if (cashAppDetails.GrantId != null) + writer.WriteString("grantId", cashAppDetails.GrantId); + + if (cashAppDetails._OnFileGrantIdOption.IsSet) + if (cashAppDetails.OnFileGrantId != null) + writer.WriteString("onFileGrantId", cashAppDetails.OnFileGrantId); + + if (cashAppDetails._RecurringDetailReferenceOption.IsSet) + if (cashAppDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", cashAppDetails.RecurringDetailReference); + + if (cashAppDetails._RequestIdOption.IsSet) + if (cashAppDetails.RequestId != null) + writer.WriteString("requestId", cashAppDetails.RequestId); + + if (cashAppDetails._StoredPaymentMethodIdOption.IsSet) + if (cashAppDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", cashAppDetails.StoredPaymentMethodId); + + if (cashAppDetails._SubtypeOption.IsSet) + if (cashAppDetails.Subtype != null) + writer.WriteString("subtype", cashAppDetails.Subtype); + + if (cashAppDetails._TypeOption.IsSet && cashAppDetails.Type != null) + { + string? typeRawValue = CashAppDetails.TypeEnum.ToJsonValue(cashAppDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/CellulantDetails.cs b/Adyen/Checkout/Models/CellulantDetails.cs new file mode 100644 index 000000000..3dca1fe43 --- /dev/null +++ b/Adyen/Checkout/Models/CellulantDetails.cs @@ -0,0 +1,324 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CellulantDetails. + /// + public partial class CellulantDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The Cellulant issuer. + /// **Cellulant** (default to TypeEnum.Cellulant) + [JsonConstructor] + public CellulantDetails(Option checkoutAttemptId = default, Option issuer = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _IssuerOption = issuer; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CellulantDetails() + { + } + + partial void OnCreated(); + + /// + /// **Cellulant** + /// + /// **Cellulant** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Cellulant - cellulant + /// + public static readonly TypeEnum Cellulant = new("cellulant"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "cellulant" => TypeEnum.Cellulant, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Cellulant) + return "cellulant"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **Cellulant** + /// + /// **Cellulant** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The Cellulant issuer. + /// + /// The Cellulant issuer. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CellulantDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CellulantDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CellulantDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option issuer = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CellulantDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CellulantDetails(checkoutAttemptId, issuer, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CellulantDetails cellulantDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cellulantDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CellulantDetails cellulantDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (cellulantDetails._CheckoutAttemptIdOption.IsSet) + if (cellulantDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", cellulantDetails.CheckoutAttemptId); + + if (cellulantDetails._IssuerOption.IsSet) + if (cellulantDetails.Issuer != null) + writer.WriteString("issuer", cellulantDetails.Issuer); + + if (cellulantDetails._TypeOption.IsSet && cellulantDetails.Type != null) + { + string? typeRawValue = CellulantDetails.TypeEnum.ToJsonValue(cellulantDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutAwaitAction.cs b/Adyen/Checkout/Models/CheckoutAwaitAction.cs new file mode 100644 index 000000000..49c651e22 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutAwaitAction.cs @@ -0,0 +1,344 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutAwaitAction. + /// + public partial class CheckoutAwaitAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **await** + /// Encoded payment data. + /// Specifies the payment method. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutAwaitAction(TypeEnum type, Option paymentData = default, Option paymentMethodType = default, Option url = default) + { + Type = type; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutAwaitAction() + { + } + + partial void OnCreated(); + + /// + /// **await** + /// + /// **await** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Await - await + /// + public static readonly TypeEnum Await = new("await"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "await" => TypeEnum.Await, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Await) + return "await"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **await** + /// + /// **await** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutAwaitAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutAwaitActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutAwaitAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option paymentData = default; + Option paymentMethodType = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutAwaitAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutAwaitAction.", nameof(type)); + + return new CheckoutAwaitAction(type.Value!.Value!, paymentData, paymentMethodType, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutAwaitAction checkoutAwaitAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutAwaitAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutAwaitAction checkoutAwaitAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutAwaitAction.Type != null) + { + string? typeRawValue = CheckoutAwaitAction.TypeEnum.ToJsonValue(checkoutAwaitAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutAwaitAction._PaymentDataOption.IsSet) + if (checkoutAwaitAction.PaymentData != null) + writer.WriteString("paymentData", checkoutAwaitAction.PaymentData); + + if (checkoutAwaitAction._PaymentMethodTypeOption.IsSet) + if (checkoutAwaitAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutAwaitAction.PaymentMethodType); + + if (checkoutAwaitAction._UrlOption.IsSet) + if (checkoutAwaitAction.Url != null) + writer.WriteString("url", checkoutAwaitAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutBankAccount.cs b/Adyen/Checkout/Models/CheckoutBankAccount.cs new file mode 100644 index 000000000..23ccf5fea --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutBankAccount.cs @@ -0,0 +1,553 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutBankAccount. + /// + public partial class CheckoutBankAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of the bank account. + /// The bank account number (without separators). + /// The bank city. + /// The location id of the bank. The field value is `nil` in most cases. + /// The name of the bank. + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// The bank account holder's tax ID. + [JsonConstructor] + public CheckoutBankAccount(Option accountType = default, Option bankAccountNumber = default, Option bankCity = default, Option bankLocationId = default, Option bankName = default, Option bic = default, Option countryCode = default, Option iban = default, Option ownerName = default, Option taxId = default) + { + _AccountTypeOption = accountType; + _BankAccountNumberOption = bankAccountNumber; + _BankCityOption = bankCity; + _BankLocationIdOption = bankLocationId; + _BankNameOption = bankName; + _BicOption = bic; + _CountryCodeOption = countryCode; + _IbanOption = iban; + _OwnerNameOption = ownerName; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutBankAccount() + { + } + + partial void OnCreated(); + + /// + /// The type of the bank account. + /// + /// The type of the bank account. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Balance - balance + /// + public static readonly AccountTypeEnum Balance = new("balance"); + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Deposit - deposit + /// + public static readonly AccountTypeEnum Deposit = new("deposit"); + + /// + /// AccountTypeEnum.General - general + /// + public static readonly AccountTypeEnum General = new("general"); + + /// + /// AccountTypeEnum.Other - other + /// + public static readonly AccountTypeEnum Other = new("other"); + + /// + /// AccountTypeEnum.Payment - payment + /// + public static readonly AccountTypeEnum Payment = new("payment"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balance" => AccountTypeEnum.Balance, + "checking" => AccountTypeEnum.Checking, + "deposit" => AccountTypeEnum.Deposit, + "general" => AccountTypeEnum.General, + "other" => AccountTypeEnum.Other, + "payment" => AccountTypeEnum.Payment, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Balance) + return "balance"; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Deposit) + return "deposit"; + + if (value == AccountTypeEnum.General) + return "general"; + + if (value == AccountTypeEnum.Other) + return "other"; + + if (value == AccountTypeEnum.Payment) + return "payment"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The type of the bank account. + /// + /// The type of the bank account. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCityOption { get; private set; } + + /// + /// The bank city. + /// + /// The bank city. + [JsonPropertyName("bankCity")] + public string? BankCity { get { return this._BankCityOption; } set { this._BankCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The location id of the bank. The field value is `nil` in most cases. + /// + /// The location id of the bank. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankNameOption { get; private set; } + + /// + /// The name of the bank. + /// + /// The name of the bank. + [JsonPropertyName("bankName")] + public string? BankName { get { return this._BankNameOption; } set { this._BankNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The bank account holder's tax ID. + /// + /// The bank account holder's tax ID. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutBankAccount {\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankCity: ").Append(BankCity).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" BankName: ").Append(BankName).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutBankAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutBankAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountType = default; + Option bankAccountNumber = default; + Option bankCity = default; + Option bankLocationId = default; + Option bankName = default; + Option bic = default; + Option countryCode = default; + Option iban = default; + Option ownerName = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(CheckoutBankAccount.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCity": + bankCity = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "bankName": + bankName = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CheckoutBankAccount(accountType, bankAccountNumber, bankCity, bankLocationId, bankName, bic, countryCode, iban, ownerName, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutBankAccount checkoutBankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutBankAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutBankAccount checkoutBankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutBankAccount._AccountTypeOption.IsSet && checkoutBankAccount.AccountType != null) + { + string? accountTypeRawValue = CheckoutBankAccount.AccountTypeEnum.ToJsonValue(checkoutBankAccount._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (checkoutBankAccount._BankAccountNumberOption.IsSet) + if (checkoutBankAccount.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", checkoutBankAccount.BankAccountNumber); + + if (checkoutBankAccount._BankCityOption.IsSet) + if (checkoutBankAccount.BankCity != null) + writer.WriteString("bankCity", checkoutBankAccount.BankCity); + + if (checkoutBankAccount._BankLocationIdOption.IsSet) + if (checkoutBankAccount.BankLocationId != null) + writer.WriteString("bankLocationId", checkoutBankAccount.BankLocationId); + + if (checkoutBankAccount._BankNameOption.IsSet) + if (checkoutBankAccount.BankName != null) + writer.WriteString("bankName", checkoutBankAccount.BankName); + + if (checkoutBankAccount._BicOption.IsSet) + if (checkoutBankAccount.Bic != null) + writer.WriteString("bic", checkoutBankAccount.Bic); + + if (checkoutBankAccount._CountryCodeOption.IsSet) + if (checkoutBankAccount.CountryCode != null) + writer.WriteString("countryCode", checkoutBankAccount.CountryCode); + + if (checkoutBankAccount._IbanOption.IsSet) + if (checkoutBankAccount.Iban != null) + writer.WriteString("iban", checkoutBankAccount.Iban); + + if (checkoutBankAccount._OwnerNameOption.IsSet) + if (checkoutBankAccount.OwnerName != null) + writer.WriteString("ownerName", checkoutBankAccount.OwnerName); + + if (checkoutBankAccount._TaxIdOption.IsSet) + if (checkoutBankAccount.TaxId != null) + writer.WriteString("taxId", checkoutBankAccount.TaxId); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutBankTransferAction.cs b/Adyen/Checkout/Models/CheckoutBankTransferAction.cs new file mode 100644 index 000000000..43dd882ee --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutBankTransferAction.cs @@ -0,0 +1,619 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutBankTransferAction. + /// + public partial class CheckoutBankTransferAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of the action. + /// The account number of the bank transfer. + /// The bank code of the bank transfer. + /// The name of the account holder. + /// The BIC of the IBAN. + /// The branch code of the bank transfer. + /// The url to download payment details with. + /// The IBAN of the bank transfer. + /// Specifies the payment method. + /// The transfer reference. + /// The routing number of the bank transfer. + /// The e-mail of the shopper, included if an e-mail was sent to the shopper. + /// The sort code of the bank transfer. + /// totalAmount + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutBankTransferAction(TypeEnum type, Option accountNumber = default, Option bankCode = default, Option beneficiary = default, Option bic = default, Option branchCode = default, Option downloadUrl = default, Option iban = default, Option paymentMethodType = default, Option reference = default, Option routingNumber = default, Option shopperEmail = default, Option sortCode = default, Option totalAmount = default, Option url = default) + { + Type = type; + _AccountNumberOption = accountNumber; + _BankCodeOption = bankCode; + _BeneficiaryOption = beneficiary; + _BicOption = bic; + _BranchCodeOption = branchCode; + _DownloadUrlOption = downloadUrl; + _IbanOption = iban; + _PaymentMethodTypeOption = paymentMethodType; + _ReferenceOption = reference; + _RoutingNumberOption = routingNumber; + _ShopperEmailOption = shopperEmail; + _SortCodeOption = sortCode; + _TotalAmountOption = totalAmount; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutBankTransferAction() + { + } + + partial void OnCreated(); + + /// + /// The type of the action. + /// + /// The type of the action. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankTransfer" => TypeEnum.BankTransfer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the action. + /// + /// The type of the action. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountNumberOption { get; private set; } + + /// + /// The account number of the bank transfer. + /// + /// The account number of the bank transfer. + [JsonPropertyName("accountNumber")] + public string? AccountNumber { get { return this._AccountNumberOption; } set { this._AccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCodeOption { get; private set; } + + /// + /// The bank code of the bank transfer. + /// + /// The bank code of the bank transfer. + [JsonPropertyName("bankCode")] + public string? BankCode { get { return this._BankCodeOption; } set { this._BankCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BeneficiaryOption { get; private set; } + + /// + /// The name of the account holder. + /// + /// The name of the account holder. + [JsonPropertyName("beneficiary")] + public string? Beneficiary { get { return this._BeneficiaryOption; } set { this._BeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// The BIC of the IBAN. + /// + /// The BIC of the IBAN. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BranchCodeOption { get; private set; } + + /// + /// The branch code of the bank transfer. + /// + /// The branch code of the bank transfer. + [JsonPropertyName("branchCode")] + public string? BranchCode { get { return this._BranchCodeOption; } set { this._BranchCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DownloadUrlOption { get; private set; } + + /// + /// The url to download payment details with. + /// + /// The url to download payment details with. + [JsonPropertyName("downloadUrl")] + public string? DownloadUrl { get { return this._DownloadUrlOption; } set { this._DownloadUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The IBAN of the bank transfer. + /// + /// The IBAN of the bank transfer. + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The transfer reference. + /// + /// The transfer reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RoutingNumberOption { get; private set; } + + /// + /// The routing number of the bank transfer. + /// + /// The routing number of the bank transfer. + [JsonPropertyName("routingNumber")] + public string? RoutingNumber { get { return this._RoutingNumberOption; } set { this._RoutingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The e-mail of the shopper, included if an e-mail was sent to the shopper. + /// + /// The e-mail of the shopper, included if an e-mail was sent to the shopper. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SortCodeOption { get; private set; } + + /// + /// The sort code of the bank transfer. + /// + /// The sort code of the bank transfer. + [JsonPropertyName("sortCode")] + public string? SortCode { get { return this._SortCodeOption; } set { this._SortCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("totalAmount")] + public Amount? TotalAmount { get { return this._TotalAmountOption; } set { this._TotalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutBankTransferAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Beneficiary: ").Append(Beneficiary).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" BranchCode: ").Append(BranchCode).Append("\n"); + sb.Append(" DownloadUrl: ").Append(DownloadUrl).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" TotalAmount: ").Append(TotalAmount).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutBankTransferActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutBankTransferAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option accountNumber = default; + Option bankCode = default; + Option beneficiary = default; + Option bic = default; + Option branchCode = default; + Option downloadUrl = default; + Option iban = default; + Option paymentMethodType = default; + Option reference = default; + Option routingNumber = default; + Option shopperEmail = default; + Option sortCode = default; + Option totalAmount = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutBankTransferAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "beneficiary": + beneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "branchCode": + branchCode = new Option(utf8JsonReader.GetString()!); + break; + case "downloadUrl": + downloadUrl = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "totalAmount": + totalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutBankTransferAction.", nameof(type)); + + return new CheckoutBankTransferAction(type.Value!.Value!, accountNumber, bankCode, beneficiary, bic, branchCode, downloadUrl, iban, paymentMethodType, reference, routingNumber, shopperEmail, sortCode, totalAmount, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutBankTransferAction checkoutBankTransferAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutBankTransferAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutBankTransferAction checkoutBankTransferAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutBankTransferAction.Type != null) + { + string? typeRawValue = CheckoutBankTransferAction.TypeEnum.ToJsonValue(checkoutBankTransferAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutBankTransferAction._AccountNumberOption.IsSet) + if (checkoutBankTransferAction.AccountNumber != null) + writer.WriteString("accountNumber", checkoutBankTransferAction.AccountNumber); + + if (checkoutBankTransferAction._BankCodeOption.IsSet) + if (checkoutBankTransferAction.BankCode != null) + writer.WriteString("bankCode", checkoutBankTransferAction.BankCode); + + if (checkoutBankTransferAction._BeneficiaryOption.IsSet) + if (checkoutBankTransferAction.Beneficiary != null) + writer.WriteString("beneficiary", checkoutBankTransferAction.Beneficiary); + + if (checkoutBankTransferAction._BicOption.IsSet) + if (checkoutBankTransferAction.Bic != null) + writer.WriteString("bic", checkoutBankTransferAction.Bic); + + if (checkoutBankTransferAction._BranchCodeOption.IsSet) + if (checkoutBankTransferAction.BranchCode != null) + writer.WriteString("branchCode", checkoutBankTransferAction.BranchCode); + + if (checkoutBankTransferAction._DownloadUrlOption.IsSet) + if (checkoutBankTransferAction.DownloadUrl != null) + writer.WriteString("downloadUrl", checkoutBankTransferAction.DownloadUrl); + + if (checkoutBankTransferAction._IbanOption.IsSet) + if (checkoutBankTransferAction.Iban != null) + writer.WriteString("iban", checkoutBankTransferAction.Iban); + + if (checkoutBankTransferAction._PaymentMethodTypeOption.IsSet) + if (checkoutBankTransferAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutBankTransferAction.PaymentMethodType); + + if (checkoutBankTransferAction._ReferenceOption.IsSet) + if (checkoutBankTransferAction.Reference != null) + writer.WriteString("reference", checkoutBankTransferAction.Reference); + + if (checkoutBankTransferAction._RoutingNumberOption.IsSet) + if (checkoutBankTransferAction.RoutingNumber != null) + writer.WriteString("routingNumber", checkoutBankTransferAction.RoutingNumber); + + if (checkoutBankTransferAction._ShopperEmailOption.IsSet) + if (checkoutBankTransferAction.ShopperEmail != null) + writer.WriteString("shopperEmail", checkoutBankTransferAction.ShopperEmail); + + if (checkoutBankTransferAction._SortCodeOption.IsSet) + if (checkoutBankTransferAction.SortCode != null) + writer.WriteString("sortCode", checkoutBankTransferAction.SortCode); + + if (checkoutBankTransferAction._TotalAmountOption.IsSet) + { + writer.WritePropertyName("totalAmount"); + JsonSerializer.Serialize(writer, checkoutBankTransferAction.TotalAmount, jsonSerializerOptions); + } + if (checkoutBankTransferAction._UrlOption.IsSet) + if (checkoutBankTransferAction.Url != null) + writer.WriteString("url", checkoutBankTransferAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutDelegatedAuthenticationAction.cs b/Adyen/Checkout/Models/CheckoutDelegatedAuthenticationAction.cs new file mode 100644 index 000000000..ffd5b0b5e --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutDelegatedAuthenticationAction.cs @@ -0,0 +1,394 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutDelegatedAuthenticationAction. + /// + public partial class CheckoutDelegatedAuthenticationAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **delegatedAuthentication** + /// A token needed to authorise a payment. + /// Encoded payment data. + /// Specifies the payment method. + /// A token to pass to the delegatedAuthentication component. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutDelegatedAuthenticationAction(TypeEnum type, Option authorisationToken = default, Option paymentData = default, Option paymentMethodType = default, Option token = default, Option url = default) + { + Type = type; + _AuthorisationTokenOption = authorisationToken; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _TokenOption = token; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutDelegatedAuthenticationAction() + { + } + + partial void OnCreated(); + + /// + /// **delegatedAuthentication** + /// + /// **delegatedAuthentication** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DelegatedAuthentication - delegatedAuthentication + /// + public static readonly TypeEnum DelegatedAuthentication = new("delegatedAuthentication"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "delegatedAuthentication" => TypeEnum.DelegatedAuthentication, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DelegatedAuthentication) + return "delegatedAuthentication"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **delegatedAuthentication** + /// + /// **delegatedAuthentication** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTokenOption { get; private set; } + + /// + /// A token needed to authorise a payment. + /// + /// A token needed to authorise a payment. + [JsonPropertyName("authorisationToken")] + public string? AuthorisationToken { get { return this._AuthorisationTokenOption; } set { this._AuthorisationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenOption { get; private set; } + + /// + /// A token to pass to the delegatedAuthentication component. + /// + /// A token to pass to the delegatedAuthentication component. + [JsonPropertyName("token")] + public string? Token { get { return this._TokenOption; } set { this._TokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutDelegatedAuthenticationAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AuthorisationToken: ").Append(AuthorisationToken).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutDelegatedAuthenticationActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutDelegatedAuthenticationAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option authorisationToken = default; + Option paymentData = default; + Option paymentMethodType = default; + Option token = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutDelegatedAuthenticationAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "authorisationToken": + authorisationToken = new Option(utf8JsonReader.GetString()!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutDelegatedAuthenticationAction.", nameof(type)); + + return new CheckoutDelegatedAuthenticationAction(type.Value!.Value!, authorisationToken, paymentData, paymentMethodType, token, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutDelegatedAuthenticationAction checkoutDelegatedAuthenticationAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutDelegatedAuthenticationAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutDelegatedAuthenticationAction checkoutDelegatedAuthenticationAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutDelegatedAuthenticationAction.Type != null) + { + string? typeRawValue = CheckoutDelegatedAuthenticationAction.TypeEnum.ToJsonValue(checkoutDelegatedAuthenticationAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutDelegatedAuthenticationAction._AuthorisationTokenOption.IsSet) + if (checkoutDelegatedAuthenticationAction.AuthorisationToken != null) + writer.WriteString("authorisationToken", checkoutDelegatedAuthenticationAction.AuthorisationToken); + + if (checkoutDelegatedAuthenticationAction._PaymentDataOption.IsSet) + if (checkoutDelegatedAuthenticationAction.PaymentData != null) + writer.WriteString("paymentData", checkoutDelegatedAuthenticationAction.PaymentData); + + if (checkoutDelegatedAuthenticationAction._PaymentMethodTypeOption.IsSet) + if (checkoutDelegatedAuthenticationAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutDelegatedAuthenticationAction.PaymentMethodType); + + if (checkoutDelegatedAuthenticationAction._TokenOption.IsSet) + if (checkoutDelegatedAuthenticationAction.Token != null) + writer.WriteString("token", checkoutDelegatedAuthenticationAction.Token); + + if (checkoutDelegatedAuthenticationAction._UrlOption.IsSet) + if (checkoutDelegatedAuthenticationAction.Url != null) + writer.WriteString("url", checkoutDelegatedAuthenticationAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutNativeRedirectAction.cs b/Adyen/Checkout/Models/CheckoutNativeRedirectAction.cs new file mode 100644 index 000000000..8c8b8322c --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutNativeRedirectAction.cs @@ -0,0 +1,395 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutNativeRedirectAction. + /// + public partial class CheckoutNativeRedirectAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **nativeRedirect** + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + /// Specifies the HTTP method, for example GET or POST. + /// Native SDK's redirect data containing the direct issuer link and state data that must be submitted to the /v1/nativeRedirect/redirectResult. + /// Specifies the payment method. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutNativeRedirectAction(TypeEnum type, Option?> data = default, Option method = default, Option nativeRedirectData = default, Option paymentMethodType = default, Option url = default) + { + Type = type; + _DataOption = data; + _MethodOption = method; + _NativeRedirectDataOption = nativeRedirectData; + _PaymentMethodTypeOption = paymentMethodType; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutNativeRedirectAction() + { + } + + partial void OnCreated(); + + /// + /// **nativeRedirect** + /// + /// **nativeRedirect** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NativeRedirect - nativeRedirect + /// + public static readonly TypeEnum NativeRedirect = new("nativeRedirect"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nativeRedirect" => TypeEnum.NativeRedirect, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NativeRedirect) + return "nativeRedirect"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **nativeRedirect** + /// + /// **nativeRedirect** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + /// + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + [JsonPropertyName("data")] + public Dictionary? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MethodOption { get; private set; } + + /// + /// Specifies the HTTP method, for example GET or POST. + /// + /// Specifies the HTTP method, for example GET or POST. + [JsonPropertyName("method")] + public string? Method { get { return this._MethodOption; } set { this._MethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NativeRedirectDataOption { get; private set; } + + /// + /// Native SDK's redirect data containing the direct issuer link and state data that must be submitted to the /v1/nativeRedirect/redirectResult. + /// + /// Native SDK's redirect data containing the direct issuer link and state data that must be submitted to the /v1/nativeRedirect/redirectResult. + [JsonPropertyName("nativeRedirectData")] + public string? NativeRedirectData { get { return this._NativeRedirectDataOption; } set { this._NativeRedirectDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutNativeRedirectAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Method: ").Append(Method).Append("\n"); + sb.Append(" NativeRedirectData: ").Append(NativeRedirectData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutNativeRedirectActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutNativeRedirectAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option?> data = default; + Option method = default; + Option nativeRedirectData = default; + Option paymentMethodType = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutNativeRedirectAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "method": + method = new Option(utf8JsonReader.GetString()!); + break; + case "nativeRedirectData": + nativeRedirectData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutNativeRedirectAction.", nameof(type)); + + return new CheckoutNativeRedirectAction(type.Value!.Value!, data, method, nativeRedirectData, paymentMethodType, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutNativeRedirectAction checkoutNativeRedirectAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutNativeRedirectAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutNativeRedirectAction checkoutNativeRedirectAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutNativeRedirectAction.Type != null) + { + string? typeRawValue = CheckoutNativeRedirectAction.TypeEnum.ToJsonValue(checkoutNativeRedirectAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutNativeRedirectAction._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, checkoutNativeRedirectAction.Data, jsonSerializerOptions); + } + if (checkoutNativeRedirectAction._MethodOption.IsSet) + if (checkoutNativeRedirectAction.Method != null) + writer.WriteString("method", checkoutNativeRedirectAction.Method); + + if (checkoutNativeRedirectAction._NativeRedirectDataOption.IsSet) + if (checkoutNativeRedirectAction.NativeRedirectData != null) + writer.WriteString("nativeRedirectData", checkoutNativeRedirectAction.NativeRedirectData); + + if (checkoutNativeRedirectAction._PaymentMethodTypeOption.IsSet) + if (checkoutNativeRedirectAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutNativeRedirectAction.PaymentMethodType); + + if (checkoutNativeRedirectAction._UrlOption.IsSet) + if (checkoutNativeRedirectAction.Url != null) + writer.WriteString("url", checkoutNativeRedirectAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutOrderResponse.cs b/Adyen/Checkout/Models/CheckoutOrderResponse.cs new file mode 100644 index 000000000..2af26a738 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutOrderResponse.cs @@ -0,0 +1,297 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutOrderResponse. + /// + public partial class CheckoutOrderResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `pspReference` that belongs to the order. + /// amount + /// The expiry date for the order. + /// The encrypted order data. + /// The merchant reference for the order. + /// remainingAmount + [JsonConstructor] + public CheckoutOrderResponse(string pspReference, Option amount = default, Option expiresAt = default, Option orderData = default, Option reference = default, Option remainingAmount = default) + { + PspReference = pspReference; + _AmountOption = amount; + _ExpiresAtOption = expiresAt; + _OrderDataOption = orderData; + _ReferenceOption = reference; + _RemainingAmountOption = remainingAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutOrderResponse() + { + } + + partial void OnCreated(); + + /// + /// The `pspReference` that belongs to the order. + /// + /// The `pspReference` that belongs to the order. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The expiry date for the order. + /// + /// The expiry date for the order. + [JsonPropertyName("expiresAt")] + public string? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderDataOption { get; private set; } + + /// + /// The encrypted order data. + /// + /// The encrypted order data. + [JsonPropertyName("orderData")] + public string? OrderData { get { return this._OrderDataOption; } set { this._OrderDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The merchant reference for the order. + /// + /// The merchant reference for the order. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RemainingAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("remainingAmount")] + public Amount? RemainingAmount { get { return this._RemainingAmountOption; } set { this._RemainingAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutOrderResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" OrderData: ").Append(OrderData).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" RemainingAmount: ").Append(RemainingAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutOrderResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutOrderResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option amount = default; + Option expiresAt = default; + Option orderData = default; + Option reference = default; + Option remainingAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(utf8JsonReader.GetString()!); + break; + case "orderData": + orderData = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "remainingAmount": + remainingAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class CheckoutOrderResponse.", nameof(pspReference)); + + return new CheckoutOrderResponse(pspReference.Value!, amount, expiresAt, orderData, reference, remainingAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutOrderResponse checkoutOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutOrderResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutOrderResponse checkoutOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutOrderResponse.PspReference != null) + writer.WriteString("pspReference", checkoutOrderResponse.PspReference); + + if (checkoutOrderResponse._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, checkoutOrderResponse.Amount, jsonSerializerOptions); + } + if (checkoutOrderResponse._ExpiresAtOption.IsSet) + if (checkoutOrderResponse.ExpiresAt != null) + writer.WriteString("expiresAt", checkoutOrderResponse.ExpiresAt); + + if (checkoutOrderResponse._OrderDataOption.IsSet) + if (checkoutOrderResponse.OrderData != null) + writer.WriteString("orderData", checkoutOrderResponse.OrderData); + + if (checkoutOrderResponse._ReferenceOption.IsSet) + if (checkoutOrderResponse.Reference != null) + writer.WriteString("reference", checkoutOrderResponse.Reference); + + if (checkoutOrderResponse._RemainingAmountOption.IsSet) + { + writer.WritePropertyName("remainingAmount"); + JsonSerializer.Serialize(writer, checkoutOrderResponse.RemainingAmount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutPaymentMethod.cs b/Adyen/Checkout/Models/CheckoutPaymentMethod.cs new file mode 100644 index 000000000..a8f61e4fe --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutPaymentMethod.cs @@ -0,0 +1,1527 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// The type and required details of a payment method to use.. + /// + public partial class CheckoutPaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AchDetails achDetails) + { + AchDetails = achDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AffirmDetails affirmDetails) + { + AffirmDetails = affirmDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AfterpayDetails afterpayDetails) + { + AfterpayDetails = afterpayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AmazonPayDetails amazonPayDetails) + { + AmazonPayDetails = amazonPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AncvDetails ancvDetails) + { + AncvDetails = ancvDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(AndroidPayDetails androidPayDetails) + { + AndroidPayDetails = androidPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(ApplePayDetails applePayDetails) + { + ApplePayDetails = applePayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(BacsDirectDebitDetails bacsDirectDebitDetails) + { + BacsDirectDebitDetails = bacsDirectDebitDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(BillDeskDetails billDeskDetails) + { + BillDeskDetails = billDeskDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(BlikDetails blikDetails) + { + BlikDetails = blikDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(CardDetails cardDetails) + { + CardDetails = cardDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(CashAppDetails cashAppDetails) + { + CashAppDetails = cashAppDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(CellulantDetails cellulantDetails) + { + CellulantDetails = cellulantDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(DokuDetails dokuDetails) + { + DokuDetails = dokuDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(DragonpayDetails dragonpayDetails) + { + DragonpayDetails = dragonpayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(EBankingFinlandDetails eBankingFinlandDetails) + { + EBankingFinlandDetails = eBankingFinlandDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(EcontextVoucherDetails econtextVoucherDetails) + { + EcontextVoucherDetails = econtextVoucherDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(EftDetails eftDetails) + { + EftDetails = eftDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(FastlaneDetails fastlaneDetails) + { + FastlaneDetails = fastlaneDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(GenericIssuerPaymentMethodDetails genericIssuerPaymentMethodDetails) + { + GenericIssuerPaymentMethodDetails = genericIssuerPaymentMethodDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(GooglePayDetails googlePayDetails) + { + GooglePayDetails = googlePayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(IdealDetails idealDetails) + { + IdealDetails = idealDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(KlarnaDetails klarnaDetails) + { + KlarnaDetails = klarnaDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(MasterpassDetails masterpassDetails) + { + MasterpassDetails = masterpassDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(MbwayDetails mbwayDetails) + { + MbwayDetails = mbwayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(MobilePayDetails mobilePayDetails) + { + MobilePayDetails = mobilePayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(MolPayDetails molPayDetails) + { + MolPayDetails = molPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(OpenInvoiceDetails openInvoiceDetails) + { + OpenInvoiceDetails = openInvoiceDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayByBankAISDirectDebitDetails payByBankAISDirectDebitDetails) + { + PayByBankAISDirectDebitDetails = payByBankAISDirectDebitDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayByBankDetails payByBankDetails) + { + PayByBankDetails = payByBankDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayPalDetails payPalDetails) + { + PayPalDetails = payPalDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayPayDetails payPayDetails) + { + PayPayDetails = payPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayToDetails payToDetails) + { + PayToDetails = payToDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayUUpiDetails payUUpiDetails) + { + PayUUpiDetails = payUUpiDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PayWithGoogleDetails payWithGoogleDetails) + { + PayWithGoogleDetails = payWithGoogleDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PaymentDetails paymentDetails) + { + PaymentDetails = paymentDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PixDetails pixDetails) + { + PixDetails = pixDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(PseDetails pseDetails) + { + PseDetails = pseDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(RakutenPayDetails rakutenPayDetails) + { + RakutenPayDetails = rakutenPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(RatepayDetails ratepayDetails) + { + RatepayDetails = ratepayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(RivertyDetails rivertyDetails) + { + RivertyDetails = rivertyDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(SamsungPayDetails samsungPayDetails) + { + SamsungPayDetails = samsungPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(SepaDirectDebitDetails sepaDirectDebitDetails) + { + SepaDirectDebitDetails = sepaDirectDebitDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(StoredPaymentMethodDetails storedPaymentMethodDetails) + { + StoredPaymentMethodDetails = storedPaymentMethodDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(TwintDetails twintDetails) + { + TwintDetails = twintDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(UpiCollectDetails upiCollectDetails) + { + UpiCollectDetails = upiCollectDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(UpiIntentDetails upiIntentDetails) + { + UpiIntentDetails = upiIntentDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(UpiQrDetails upiQrDetails) + { + UpiQrDetails = upiQrDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(VippsDetails vippsDetails) + { + VippsDetails = vippsDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(VisaCheckoutDetails visaCheckoutDetails) + { + VisaCheckoutDetails = visaCheckoutDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(WeChatPayDetails weChatPayDetails) + { + WeChatPayDetails = weChatPayDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(WeChatPayMiniProgramDetails weChatPayMiniProgramDetails) + { + WeChatPayMiniProgramDetails = weChatPayMiniProgramDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public CheckoutPaymentMethod(ZipDetails zipDetails) + { + ZipDetails = zipDetails; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AchDetails? AchDetails { get; set; } + + /// + /// .. + /// + public AffirmDetails? AffirmDetails { get; set; } + + /// + /// .. + /// + public AfterpayDetails? AfterpayDetails { get; set; } + + /// + /// .. + /// + public AmazonPayDetails? AmazonPayDetails { get; set; } + + /// + /// .. + /// + public AncvDetails? AncvDetails { get; set; } + + /// + /// .. + /// + public AndroidPayDetails? AndroidPayDetails { get; set; } + + /// + /// .. + /// + public ApplePayDetails? ApplePayDetails { get; set; } + + /// + /// .. + /// + public BacsDirectDebitDetails? BacsDirectDebitDetails { get; set; } + + /// + /// .. + /// + public BillDeskDetails? BillDeskDetails { get; set; } + + /// + /// .. + /// + public BlikDetails? BlikDetails { get; set; } + + /// + /// .. + /// + public CardDetails? CardDetails { get; set; } + + /// + /// .. + /// + public CashAppDetails? CashAppDetails { get; set; } + + /// + /// .. + /// + public CellulantDetails? CellulantDetails { get; set; } + + /// + /// .. + /// + public DokuDetails? DokuDetails { get; set; } + + /// + /// .. + /// + public DragonpayDetails? DragonpayDetails { get; set; } + + /// + /// .. + /// + public EBankingFinlandDetails? EBankingFinlandDetails { get; set; } + + /// + /// .. + /// + public EcontextVoucherDetails? EcontextVoucherDetails { get; set; } + + /// + /// .. + /// + public EftDetails? EftDetails { get; set; } + + /// + /// .. + /// + public FastlaneDetails? FastlaneDetails { get; set; } + + /// + /// .. + /// + public GenericIssuerPaymentMethodDetails? GenericIssuerPaymentMethodDetails { get; set; } + + /// + /// .. + /// + public GooglePayDetails? GooglePayDetails { get; set; } + + /// + /// .. + /// + public IdealDetails? IdealDetails { get; set; } + + /// + /// .. + /// + public KlarnaDetails? KlarnaDetails { get; set; } + + /// + /// .. + /// + public MasterpassDetails? MasterpassDetails { get; set; } + + /// + /// .. + /// + public MbwayDetails? MbwayDetails { get; set; } + + /// + /// .. + /// + public MobilePayDetails? MobilePayDetails { get; set; } + + /// + /// .. + /// + public MolPayDetails? MolPayDetails { get; set; } + + /// + /// .. + /// + public OpenInvoiceDetails? OpenInvoiceDetails { get; set; } + + /// + /// .. + /// + public PayByBankAISDirectDebitDetails? PayByBankAISDirectDebitDetails { get; set; } + + /// + /// .. + /// + public PayByBankDetails? PayByBankDetails { get; set; } + + /// + /// .. + /// + public PayPalDetails? PayPalDetails { get; set; } + + /// + /// .. + /// + public PayPayDetails? PayPayDetails { get; set; } + + /// + /// .. + /// + public PayToDetails? PayToDetails { get; set; } + + /// + /// .. + /// + public PayUUpiDetails? PayUUpiDetails { get; set; } + + /// + /// .. + /// + public PayWithGoogleDetails? PayWithGoogleDetails { get; set; } + + /// + /// .. + /// + public PaymentDetails? PaymentDetails { get; set; } + + /// + /// .. + /// + public PixDetails? PixDetails { get; set; } + + /// + /// .. + /// + public PseDetails? PseDetails { get; set; } + + /// + /// .. + /// + public RakutenPayDetails? RakutenPayDetails { get; set; } + + /// + /// .. + /// + public RatepayDetails? RatepayDetails { get; set; } + + /// + /// .. + /// + public RivertyDetails? RivertyDetails { get; set; } + + /// + /// .. + /// + public SamsungPayDetails? SamsungPayDetails { get; set; } + + /// + /// .. + /// + public SepaDirectDebitDetails? SepaDirectDebitDetails { get; set; } + + /// + /// .. + /// + public StoredPaymentMethodDetails? StoredPaymentMethodDetails { get; set; } + + /// + /// .. + /// + public TwintDetails? TwintDetails { get; set; } + + /// + /// .. + /// + public UpiCollectDetails? UpiCollectDetails { get; set; } + + /// + /// .. + /// + public UpiIntentDetails? UpiIntentDetails { get; set; } + + /// + /// .. + /// + public UpiQrDetails? UpiQrDetails { get; set; } + + /// + /// .. + /// + public VippsDetails? VippsDetails { get; set; } + + /// + /// .. + /// + public VisaCheckoutDetails? VisaCheckoutDetails { get; set; } + + /// + /// .. + /// + public WeChatPayDetails? WeChatPayDetails { get; set; } + + /// + /// .. + /// + public WeChatPayMiniProgramDetails? WeChatPayMiniProgramDetails { get; set; } + + /// + /// .. + /// + public ZipDetails? ZipDetails { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutPaymentMethod {\n"); + if (this.AchDetails != null) + sb.Append(AchDetails.ToString().Replace("\n", "\n ")); + if (this.AffirmDetails != null) + sb.Append(AffirmDetails.ToString().Replace("\n", "\n ")); + if (this.AfterpayDetails != null) + sb.Append(AfterpayDetails.ToString().Replace("\n", "\n ")); + if (this.AmazonPayDetails != null) + sb.Append(AmazonPayDetails.ToString().Replace("\n", "\n ")); + if (this.AncvDetails != null) + sb.Append(AncvDetails.ToString().Replace("\n", "\n ")); + if (this.AndroidPayDetails != null) + sb.Append(AndroidPayDetails.ToString().Replace("\n", "\n ")); + if (this.ApplePayDetails != null) + sb.Append(ApplePayDetails.ToString().Replace("\n", "\n ")); + if (this.BacsDirectDebitDetails != null) + sb.Append(BacsDirectDebitDetails.ToString().Replace("\n", "\n ")); + if (this.BillDeskDetails != null) + sb.Append(BillDeskDetails.ToString().Replace("\n", "\n ")); + if (this.BlikDetails != null) + sb.Append(BlikDetails.ToString().Replace("\n", "\n ")); + if (this.CardDetails != null) + sb.Append(CardDetails.ToString().Replace("\n", "\n ")); + if (this.CashAppDetails != null) + sb.Append(CashAppDetails.ToString().Replace("\n", "\n ")); + if (this.CellulantDetails != null) + sb.Append(CellulantDetails.ToString().Replace("\n", "\n ")); + if (this.DokuDetails != null) + sb.Append(DokuDetails.ToString().Replace("\n", "\n ")); + if (this.DragonpayDetails != null) + sb.Append(DragonpayDetails.ToString().Replace("\n", "\n ")); + if (this.EBankingFinlandDetails != null) + sb.Append(EBankingFinlandDetails.ToString().Replace("\n", "\n ")); + if (this.EcontextVoucherDetails != null) + sb.Append(EcontextVoucherDetails.ToString().Replace("\n", "\n ")); + if (this.EftDetails != null) + sb.Append(EftDetails.ToString().Replace("\n", "\n ")); + if (this.FastlaneDetails != null) + sb.Append(FastlaneDetails.ToString().Replace("\n", "\n ")); + if (this.GenericIssuerPaymentMethodDetails != null) + sb.Append(GenericIssuerPaymentMethodDetails.ToString().Replace("\n", "\n ")); + if (this.GooglePayDetails != null) + sb.Append(GooglePayDetails.ToString().Replace("\n", "\n ")); + if (this.IdealDetails != null) + sb.Append(IdealDetails.ToString().Replace("\n", "\n ")); + if (this.KlarnaDetails != null) + sb.Append(KlarnaDetails.ToString().Replace("\n", "\n ")); + if (this.MasterpassDetails != null) + sb.Append(MasterpassDetails.ToString().Replace("\n", "\n ")); + if (this.MbwayDetails != null) + sb.Append(MbwayDetails.ToString().Replace("\n", "\n ")); + if (this.MobilePayDetails != null) + sb.Append(MobilePayDetails.ToString().Replace("\n", "\n ")); + if (this.MolPayDetails != null) + sb.Append(MolPayDetails.ToString().Replace("\n", "\n ")); + if (this.OpenInvoiceDetails != null) + sb.Append(OpenInvoiceDetails.ToString().Replace("\n", "\n ")); + if (this.PayByBankAISDirectDebitDetails != null) + sb.Append(PayByBankAISDirectDebitDetails.ToString().Replace("\n", "\n ")); + if (this.PayByBankDetails != null) + sb.Append(PayByBankDetails.ToString().Replace("\n", "\n ")); + if (this.PayPalDetails != null) + sb.Append(PayPalDetails.ToString().Replace("\n", "\n ")); + if (this.PayPayDetails != null) + sb.Append(PayPayDetails.ToString().Replace("\n", "\n ")); + if (this.PayToDetails != null) + sb.Append(PayToDetails.ToString().Replace("\n", "\n ")); + if (this.PayUUpiDetails != null) + sb.Append(PayUUpiDetails.ToString().Replace("\n", "\n ")); + if (this.PayWithGoogleDetails != null) + sb.Append(PayWithGoogleDetails.ToString().Replace("\n", "\n ")); + if (this.PaymentDetails != null) + sb.Append(PaymentDetails.ToString().Replace("\n", "\n ")); + if (this.PixDetails != null) + sb.Append(PixDetails.ToString().Replace("\n", "\n ")); + if (this.PseDetails != null) + sb.Append(PseDetails.ToString().Replace("\n", "\n ")); + if (this.RakutenPayDetails != null) + sb.Append(RakutenPayDetails.ToString().Replace("\n", "\n ")); + if (this.RatepayDetails != null) + sb.Append(RatepayDetails.ToString().Replace("\n", "\n ")); + if (this.RivertyDetails != null) + sb.Append(RivertyDetails.ToString().Replace("\n", "\n ")); + if (this.SamsungPayDetails != null) + sb.Append(SamsungPayDetails.ToString().Replace("\n", "\n ")); + if (this.SepaDirectDebitDetails != null) + sb.Append(SepaDirectDebitDetails.ToString().Replace("\n", "\n ")); + if (this.StoredPaymentMethodDetails != null) + sb.Append(StoredPaymentMethodDetails.ToString().Replace("\n", "\n ")); + if (this.TwintDetails != null) + sb.Append(TwintDetails.ToString().Replace("\n", "\n ")); + if (this.UpiCollectDetails != null) + sb.Append(UpiCollectDetails.ToString().Replace("\n", "\n ")); + if (this.UpiIntentDetails != null) + sb.Append(UpiIntentDetails.ToString().Replace("\n", "\n ")); + if (this.UpiQrDetails != null) + sb.Append(UpiQrDetails.ToString().Replace("\n", "\n ")); + if (this.VippsDetails != null) + sb.Append(VippsDetails.ToString().Replace("\n", "\n ")); + if (this.VisaCheckoutDetails != null) + sb.Append(VisaCheckoutDetails.ToString().Replace("\n", "\n ")); + if (this.WeChatPayDetails != null) + sb.Append(WeChatPayDetails.ToString().Replace("\n", "\n ")); + if (this.WeChatPayMiniProgramDetails != null) + sb.Append(WeChatPayMiniProgramDetails.ToString().Replace("\n", "\n ")); + if (this.ZipDetails != null) + sb.Append(ZipDetails.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AchDetails? achDetails = default; + AffirmDetails? affirmDetails = default; + AfterpayDetails? afterpayDetails = default; + AmazonPayDetails? amazonPayDetails = default; + AncvDetails? ancvDetails = default; + AndroidPayDetails? androidPayDetails = default; + ApplePayDetails? applePayDetails = default; + BacsDirectDebitDetails? bacsDirectDebitDetails = default; + BillDeskDetails? billDeskDetails = default; + BlikDetails? blikDetails = default; + CardDetails? cardDetails = default; + CashAppDetails? cashAppDetails = default; + CellulantDetails? cellulantDetails = default; + DokuDetails? dokuDetails = default; + DragonpayDetails? dragonpayDetails = default; + EBankingFinlandDetails? eBankingFinlandDetails = default; + EcontextVoucherDetails? econtextVoucherDetails = default; + EftDetails? eftDetails = default; + FastlaneDetails? fastlaneDetails = default; + GenericIssuerPaymentMethodDetails? genericIssuerPaymentMethodDetails = default; + GooglePayDetails? googlePayDetails = default; + IdealDetails? idealDetails = default; + KlarnaDetails? klarnaDetails = default; + MasterpassDetails? masterpassDetails = default; + MbwayDetails? mbwayDetails = default; + MobilePayDetails? mobilePayDetails = default; + MolPayDetails? molPayDetails = default; + OpenInvoiceDetails? openInvoiceDetails = default; + PayByBankAISDirectDebitDetails? payByBankAISDirectDebitDetails = default; + PayByBankDetails? payByBankDetails = default; + PayPalDetails? payPalDetails = default; + PayPayDetails? payPayDetails = default; + PayToDetails? payToDetails = default; + PayUUpiDetails? payUUpiDetails = default; + PayWithGoogleDetails? payWithGoogleDetails = default; + PaymentDetails? paymentDetails = default; + PixDetails? pixDetails = default; + PseDetails? pseDetails = default; + RakutenPayDetails? rakutenPayDetails = default; + RatepayDetails? ratepayDetails = default; + RivertyDetails? rivertyDetails = default; + SamsungPayDetails? samsungPayDetails = default; + SepaDirectDebitDetails? sepaDirectDebitDetails = default; + StoredPaymentMethodDetails? storedPaymentMethodDetails = default; + TwintDetails? twintDetails = default; + UpiCollectDetails? upiCollectDetails = default; + UpiIntentDetails? upiIntentDetails = default; + UpiQrDetails? upiQrDetails = default; + VippsDetails? vippsDetails = default; + VisaCheckoutDetails? visaCheckoutDetails = default; + WeChatPayDetails? weChatPayDetails = default; + WeChatPayMiniProgramDetails? weChatPayMiniProgramDetails = default; + ZipDetails? zipDetails = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAchDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAchDetails, jsonSerializerOptions, out achDetails); + + Utf8JsonReader utf8JsonReaderAffirmDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAffirmDetails, jsonSerializerOptions, out affirmDetails); + + Utf8JsonReader utf8JsonReaderAfterpayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAfterpayDetails, jsonSerializerOptions, out afterpayDetails); + + Utf8JsonReader utf8JsonReaderAmazonPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAmazonPayDetails, jsonSerializerOptions, out amazonPayDetails); + + Utf8JsonReader utf8JsonReaderAncvDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAncvDetails, jsonSerializerOptions, out ancvDetails); + + Utf8JsonReader utf8JsonReaderAndroidPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAndroidPayDetails, jsonSerializerOptions, out androidPayDetails); + + Utf8JsonReader utf8JsonReaderApplePayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderApplePayDetails, jsonSerializerOptions, out applePayDetails); + + Utf8JsonReader utf8JsonReaderBacsDirectDebitDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBacsDirectDebitDetails, jsonSerializerOptions, out bacsDirectDebitDetails); + + Utf8JsonReader utf8JsonReaderBillDeskDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBillDeskDetails, jsonSerializerOptions, out billDeskDetails); + + Utf8JsonReader utf8JsonReaderBlikDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBlikDetails, jsonSerializerOptions, out blikDetails); + + Utf8JsonReader utf8JsonReaderCardDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCardDetails, jsonSerializerOptions, out cardDetails); + + Utf8JsonReader utf8JsonReaderCashAppDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCashAppDetails, jsonSerializerOptions, out cashAppDetails); + + Utf8JsonReader utf8JsonReaderCellulantDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCellulantDetails, jsonSerializerOptions, out cellulantDetails); + + Utf8JsonReader utf8JsonReaderDokuDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDokuDetails, jsonSerializerOptions, out dokuDetails); + + Utf8JsonReader utf8JsonReaderDragonpayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDragonpayDetails, jsonSerializerOptions, out dragonpayDetails); + + Utf8JsonReader utf8JsonReaderEBankingFinlandDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEBankingFinlandDetails, jsonSerializerOptions, out eBankingFinlandDetails); + + Utf8JsonReader utf8JsonReaderEcontextVoucherDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEcontextVoucherDetails, jsonSerializerOptions, out econtextVoucherDetails); + + Utf8JsonReader utf8JsonReaderEftDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEftDetails, jsonSerializerOptions, out eftDetails); + + Utf8JsonReader utf8JsonReaderFastlaneDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderFastlaneDetails, jsonSerializerOptions, out fastlaneDetails); + + Utf8JsonReader utf8JsonReaderGenericIssuerPaymentMethodDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderGenericIssuerPaymentMethodDetails, jsonSerializerOptions, out genericIssuerPaymentMethodDetails); + + Utf8JsonReader utf8JsonReaderGooglePayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderGooglePayDetails, jsonSerializerOptions, out googlePayDetails); + + Utf8JsonReader utf8JsonReaderIdealDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIdealDetails, jsonSerializerOptions, out idealDetails); + + Utf8JsonReader utf8JsonReaderKlarnaDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderKlarnaDetails, jsonSerializerOptions, out klarnaDetails); + + Utf8JsonReader utf8JsonReaderMasterpassDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMasterpassDetails, jsonSerializerOptions, out masterpassDetails); + + Utf8JsonReader utf8JsonReaderMbwayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMbwayDetails, jsonSerializerOptions, out mbwayDetails); + + Utf8JsonReader utf8JsonReaderMobilePayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMobilePayDetails, jsonSerializerOptions, out mobilePayDetails); + + Utf8JsonReader utf8JsonReaderMolPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMolPayDetails, jsonSerializerOptions, out molPayDetails); + + Utf8JsonReader utf8JsonReaderOpenInvoiceDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderOpenInvoiceDetails, jsonSerializerOptions, out openInvoiceDetails); + + Utf8JsonReader utf8JsonReaderPayByBankAISDirectDebitDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayByBankAISDirectDebitDetails, jsonSerializerOptions, out payByBankAISDirectDebitDetails); + + Utf8JsonReader utf8JsonReaderPayByBankDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayByBankDetails, jsonSerializerOptions, out payByBankDetails); + + Utf8JsonReader utf8JsonReaderPayPalDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayPalDetails, jsonSerializerOptions, out payPalDetails); + + Utf8JsonReader utf8JsonReaderPayPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayPayDetails, jsonSerializerOptions, out payPayDetails); + + Utf8JsonReader utf8JsonReaderPayToDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayToDetails, jsonSerializerOptions, out payToDetails); + + Utf8JsonReader utf8JsonReaderPayUUpiDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayUUpiDetails, jsonSerializerOptions, out payUUpiDetails); + + Utf8JsonReader utf8JsonReaderPayWithGoogleDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayWithGoogleDetails, jsonSerializerOptions, out payWithGoogleDetails); + + Utf8JsonReader utf8JsonReaderPaymentDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPaymentDetails, jsonSerializerOptions, out paymentDetails); + + Utf8JsonReader utf8JsonReaderPixDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPixDetails, jsonSerializerOptions, out pixDetails); + + Utf8JsonReader utf8JsonReaderPseDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPseDetails, jsonSerializerOptions, out pseDetails); + + Utf8JsonReader utf8JsonReaderRakutenPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderRakutenPayDetails, jsonSerializerOptions, out rakutenPayDetails); + + Utf8JsonReader utf8JsonReaderRatepayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderRatepayDetails, jsonSerializerOptions, out ratepayDetails); + + Utf8JsonReader utf8JsonReaderRivertyDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderRivertyDetails, jsonSerializerOptions, out rivertyDetails); + + Utf8JsonReader utf8JsonReaderSamsungPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSamsungPayDetails, jsonSerializerOptions, out samsungPayDetails); + + Utf8JsonReader utf8JsonReaderSepaDirectDebitDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSepaDirectDebitDetails, jsonSerializerOptions, out sepaDirectDebitDetails); + + Utf8JsonReader utf8JsonReaderStoredPaymentMethodDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderStoredPaymentMethodDetails, jsonSerializerOptions, out storedPaymentMethodDetails); + + Utf8JsonReader utf8JsonReaderTwintDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderTwintDetails, jsonSerializerOptions, out twintDetails); + + Utf8JsonReader utf8JsonReaderUpiCollectDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUpiCollectDetails, jsonSerializerOptions, out upiCollectDetails); + + Utf8JsonReader utf8JsonReaderUpiIntentDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUpiIntentDetails, jsonSerializerOptions, out upiIntentDetails); + + Utf8JsonReader utf8JsonReaderUpiQrDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUpiQrDetails, jsonSerializerOptions, out upiQrDetails); + + Utf8JsonReader utf8JsonReaderVippsDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderVippsDetails, jsonSerializerOptions, out vippsDetails); + + Utf8JsonReader utf8JsonReaderVisaCheckoutDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderVisaCheckoutDetails, jsonSerializerOptions, out visaCheckoutDetails); + + Utf8JsonReader utf8JsonReaderWeChatPayDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderWeChatPayDetails, jsonSerializerOptions, out weChatPayDetails); + + Utf8JsonReader utf8JsonReaderWeChatPayMiniProgramDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderWeChatPayMiniProgramDetails, jsonSerializerOptions, out weChatPayMiniProgramDetails); + + Utf8JsonReader utf8JsonReaderZipDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderZipDetails, jsonSerializerOptions, out zipDetails); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (achDetails?.Type != null) + return new CheckoutPaymentMethod(achDetails); + + if (affirmDetails?.Type != null) + return new CheckoutPaymentMethod(affirmDetails); + + if (afterpayDetails?.Type != null) + return new CheckoutPaymentMethod(afterpayDetails); + + if (amazonPayDetails?.Type != null) + return new CheckoutPaymentMethod(amazonPayDetails); + + if (ancvDetails?.Type != null) + return new CheckoutPaymentMethod(ancvDetails); + + if (androidPayDetails?.Type != null) + return new CheckoutPaymentMethod(androidPayDetails); + + if (applePayDetails?.Type != null) + return new CheckoutPaymentMethod(applePayDetails); + + if (bacsDirectDebitDetails?.Type != null) + return new CheckoutPaymentMethod(bacsDirectDebitDetails); + + if (billDeskDetails?.Type != null) + return new CheckoutPaymentMethod(billDeskDetails); + + if (blikDetails?.Type != null) + return new CheckoutPaymentMethod(blikDetails); + + if (cardDetails?.Type != null) + return new CheckoutPaymentMethod(cardDetails); + + if (cashAppDetails?.Type != null) + return new CheckoutPaymentMethod(cashAppDetails); + + if (cellulantDetails?.Type != null) + return new CheckoutPaymentMethod(cellulantDetails); + + if (dokuDetails?.Type != null) + return new CheckoutPaymentMethod(dokuDetails); + + if (dragonpayDetails?.Type != null) + return new CheckoutPaymentMethod(dragonpayDetails); + + if (eBankingFinlandDetails?.Type != null) + return new CheckoutPaymentMethod(eBankingFinlandDetails); + + if (econtextVoucherDetails?.Type != null) + return new CheckoutPaymentMethod(econtextVoucherDetails); + + if (eftDetails?.Type != null) + return new CheckoutPaymentMethod(eftDetails); + + if (fastlaneDetails?.Type != null) + return new CheckoutPaymentMethod(fastlaneDetails); + + if (genericIssuerPaymentMethodDetails?.Type != null) + return new CheckoutPaymentMethod(genericIssuerPaymentMethodDetails); + + if (googlePayDetails?.Type != null) + return new CheckoutPaymentMethod(googlePayDetails); + + if (idealDetails?.Type != null) + return new CheckoutPaymentMethod(idealDetails); + + if (klarnaDetails?.Type != null) + return new CheckoutPaymentMethod(klarnaDetails); + + if (masterpassDetails?.Type != null) + return new CheckoutPaymentMethod(masterpassDetails); + + if (mbwayDetails?.Type != null) + return new CheckoutPaymentMethod(mbwayDetails); + + if (mobilePayDetails?.Type != null) + return new CheckoutPaymentMethod(mobilePayDetails); + + if (molPayDetails?.Type != null) + return new CheckoutPaymentMethod(molPayDetails); + + if (openInvoiceDetails?.Type != null) + return new CheckoutPaymentMethod(openInvoiceDetails); + + if (payByBankAISDirectDebitDetails?.Type != null) + return new CheckoutPaymentMethod(payByBankAISDirectDebitDetails); + + if (payByBankDetails?.Type != null) + return new CheckoutPaymentMethod(payByBankDetails); + + if (payPalDetails?.Type != null) + return new CheckoutPaymentMethod(payPalDetails); + + if (payPayDetails?.Type != null) + return new CheckoutPaymentMethod(payPayDetails); + + if (payToDetails?.Type != null) + return new CheckoutPaymentMethod(payToDetails); + + if (payUUpiDetails?.Type != null) + return new CheckoutPaymentMethod(payUUpiDetails); + + if (payWithGoogleDetails?.Type != null) + return new CheckoutPaymentMethod(payWithGoogleDetails); + + if (paymentDetails?.Type != null) + return new CheckoutPaymentMethod(paymentDetails); + + if (pixDetails?.Type != null) + return new CheckoutPaymentMethod(pixDetails); + + if (pseDetails?.Type != null) + return new CheckoutPaymentMethod(pseDetails); + + if (rakutenPayDetails?.Type != null) + return new CheckoutPaymentMethod(rakutenPayDetails); + + if (ratepayDetails?.Type != null) + return new CheckoutPaymentMethod(ratepayDetails); + + if (rivertyDetails?.Type != null) + return new CheckoutPaymentMethod(rivertyDetails); + + if (samsungPayDetails?.Type != null) + return new CheckoutPaymentMethod(samsungPayDetails); + + if (sepaDirectDebitDetails?.Type != null) + return new CheckoutPaymentMethod(sepaDirectDebitDetails); + + if (storedPaymentMethodDetails?.Type != null) + return new CheckoutPaymentMethod(storedPaymentMethodDetails); + + if (twintDetails?.Type != null) + return new CheckoutPaymentMethod(twintDetails); + + if (upiCollectDetails?.Type != null) + return new CheckoutPaymentMethod(upiCollectDetails); + + if (upiIntentDetails?.Type != null) + return new CheckoutPaymentMethod(upiIntentDetails); + + if (upiQrDetails?.Type != null) + return new CheckoutPaymentMethod(upiQrDetails); + + if (vippsDetails?.Type != null) + return new CheckoutPaymentMethod(vippsDetails); + + if (visaCheckoutDetails?.Type != null) + return new CheckoutPaymentMethod(visaCheckoutDetails); + + if (weChatPayDetails?.Type != null) + return new CheckoutPaymentMethod(weChatPayDetails); + + if (weChatPayMiniProgramDetails?.Type != null) + return new CheckoutPaymentMethod(weChatPayMiniProgramDetails); + + if (zipDetails?.Type != null) + return new CheckoutPaymentMethod(zipDetails); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutPaymentMethod checkoutPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + if (checkoutPaymentMethod.AchDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AchDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.AffirmDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AffirmDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.AfterpayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AfterpayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.AmazonPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AmazonPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.AncvDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AncvDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.AndroidPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.AndroidPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.ApplePayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.ApplePayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.BacsDirectDebitDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.BacsDirectDebitDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.BillDeskDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.BillDeskDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.BlikDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.BlikDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.CardDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.CardDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.CashAppDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.CashAppDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.CellulantDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.CellulantDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.DokuDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.DokuDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.DragonpayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.DragonpayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.EBankingFinlandDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.EBankingFinlandDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.EcontextVoucherDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.EcontextVoucherDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.EftDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.EftDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.FastlaneDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.FastlaneDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.GenericIssuerPaymentMethodDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.GenericIssuerPaymentMethodDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.GooglePayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.GooglePayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.IdealDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.IdealDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.KlarnaDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.KlarnaDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.MasterpassDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.MasterpassDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.MbwayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.MbwayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.MobilePayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.MobilePayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.MolPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.MolPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.OpenInvoiceDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.OpenInvoiceDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayByBankAISDirectDebitDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayByBankAISDirectDebitDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayByBankDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayByBankDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayPalDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayPalDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayToDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayToDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayUUpiDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayUUpiDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PayWithGoogleDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PayWithGoogleDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PaymentDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PaymentDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PixDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PixDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.PseDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.PseDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.RakutenPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.RakutenPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.RatepayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.RatepayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.RivertyDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.RivertyDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.SamsungPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.SamsungPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.SepaDirectDebitDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.SepaDirectDebitDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.StoredPaymentMethodDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.StoredPaymentMethodDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.TwintDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.TwintDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.UpiCollectDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.UpiCollectDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.UpiIntentDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.UpiIntentDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.UpiQrDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.UpiQrDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.VippsDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.VippsDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.VisaCheckoutDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.VisaCheckoutDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.WeChatPayDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.WeChatPayDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.WeChatPayMiniProgramDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.WeChatPayMiniProgramDetails, jsonSerializerOptions); + if (checkoutPaymentMethod.ZipDetails != null) + JsonSerializer.Serialize(writer, checkoutPaymentMethod.ZipDetails, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, checkoutPaymentMethod, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutPaymentMethod checkoutPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutQrCodeAction.cs b/Adyen/Checkout/Models/CheckoutQrCodeAction.cs new file mode 100644 index 000000000..464c22002 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutQrCodeAction.cs @@ -0,0 +1,394 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutQrCodeAction. + /// + public partial class CheckoutQrCodeAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **qrCode** + /// Expiry time of the QR code. + /// Encoded payment data. + /// Specifies the payment method. + /// The contents of the QR code as a UTF8 string. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutQrCodeAction(TypeEnum type, Option expiresAt = default, Option paymentData = default, Option paymentMethodType = default, Option qrCodeData = default, Option url = default) + { + Type = type; + _ExpiresAtOption = expiresAt; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _QrCodeDataOption = qrCodeData; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutQrCodeAction() + { + } + + partial void OnCreated(); + + /// + /// **qrCode** + /// + /// **qrCode** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.QrCode - qrCode + /// + public static readonly TypeEnum QrCode = new("qrCode"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "qrCode" => TypeEnum.QrCode, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.QrCode) + return "qrCode"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **qrCode** + /// + /// **qrCode** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// Expiry time of the QR code. + /// + /// Expiry time of the QR code. + [JsonPropertyName("expiresAt")] + public string? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _QrCodeDataOption { get; private set; } + + /// + /// The contents of the QR code as a UTF8 string. + /// + /// The contents of the QR code as a UTF8 string. + [JsonPropertyName("qrCodeData")] + public string? QrCodeData { get { return this._QrCodeDataOption; } set { this._QrCodeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutQrCodeAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" QrCodeData: ").Append(QrCodeData).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutQrCodeActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutQrCodeAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option expiresAt = default; + Option paymentData = default; + Option paymentMethodType = default; + Option qrCodeData = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutQrCodeAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "expiresAt": + expiresAt = new Option(utf8JsonReader.GetString()!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "qrCodeData": + qrCodeData = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutQrCodeAction.", nameof(type)); + + return new CheckoutQrCodeAction(type.Value!.Value!, expiresAt, paymentData, paymentMethodType, qrCodeData, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutQrCodeAction checkoutQrCodeAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutQrCodeAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutQrCodeAction checkoutQrCodeAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutQrCodeAction.Type != null) + { + string? typeRawValue = CheckoutQrCodeAction.TypeEnum.ToJsonValue(checkoutQrCodeAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutQrCodeAction._ExpiresAtOption.IsSet) + if (checkoutQrCodeAction.ExpiresAt != null) + writer.WriteString("expiresAt", checkoutQrCodeAction.ExpiresAt); + + if (checkoutQrCodeAction._PaymentDataOption.IsSet) + if (checkoutQrCodeAction.PaymentData != null) + writer.WriteString("paymentData", checkoutQrCodeAction.PaymentData); + + if (checkoutQrCodeAction._PaymentMethodTypeOption.IsSet) + if (checkoutQrCodeAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutQrCodeAction.PaymentMethodType); + + if (checkoutQrCodeAction._QrCodeDataOption.IsSet) + if (checkoutQrCodeAction.QrCodeData != null) + writer.WriteString("qrCodeData", checkoutQrCodeAction.QrCodeData); + + if (checkoutQrCodeAction._UrlOption.IsSet) + if (checkoutQrCodeAction.Url != null) + writer.WriteString("url", checkoutQrCodeAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutRedirectAction.cs b/Adyen/Checkout/Models/CheckoutRedirectAction.cs new file mode 100644 index 000000000..25eced08c --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutRedirectAction.cs @@ -0,0 +1,370 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutRedirectAction. + /// + public partial class CheckoutRedirectAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **redirect** + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + /// Specifies the HTTP method, for example GET or POST. + /// Specifies the payment method. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutRedirectAction(TypeEnum type, Option?> data = default, Option method = default, Option paymentMethodType = default, Option url = default) + { + Type = type; + _DataOption = data; + _MethodOption = method; + _PaymentMethodTypeOption = paymentMethodType; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutRedirectAction() + { + } + + partial void OnCreated(); + + /// + /// **redirect** + /// + /// **redirect** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Redirect - redirect + /// + public static readonly TypeEnum Redirect = new("redirect"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "redirect" => TypeEnum.Redirect, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Redirect) + return "redirect"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **redirect** + /// + /// **redirect** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + /// + /// When the redirect URL must be accessed via POST, use this data to post to the redirect URL. + [JsonPropertyName("data")] + public Dictionary? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MethodOption { get; private set; } + + /// + /// Specifies the HTTP method, for example GET or POST. + /// + /// Specifies the HTTP method, for example GET or POST. + [JsonPropertyName("method")] + public string? Method { get { return this._MethodOption; } set { this._MethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutRedirectAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Method: ").Append(Method).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutRedirectActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutRedirectAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option?> data = default; + Option method = default; + Option paymentMethodType = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutRedirectAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "method": + method = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutRedirectAction.", nameof(type)); + + return new CheckoutRedirectAction(type.Value!.Value!, data, method, paymentMethodType, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutRedirectAction checkoutRedirectAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutRedirectAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutRedirectAction checkoutRedirectAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutRedirectAction.Type != null) + { + string? typeRawValue = CheckoutRedirectAction.TypeEnum.ToJsonValue(checkoutRedirectAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutRedirectAction._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, checkoutRedirectAction.Data, jsonSerializerOptions); + } + if (checkoutRedirectAction._MethodOption.IsSet) + if (checkoutRedirectAction.Method != null) + writer.WriteString("method", checkoutRedirectAction.Method); + + if (checkoutRedirectAction._PaymentMethodTypeOption.IsSet) + if (checkoutRedirectAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutRedirectAction.PaymentMethodType); + + if (checkoutRedirectAction._UrlOption.IsSet) + if (checkoutRedirectAction.Url != null) + writer.WriteString("url", checkoutRedirectAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutSDKAction.cs b/Adyen/Checkout/Models/CheckoutSDKAction.cs new file mode 100644 index 000000000..b9dec2bbf --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutSDKAction.cs @@ -0,0 +1,379 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutSDKAction. + /// + public partial class CheckoutSDKAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of the action. + /// Encoded payment data. + /// Specifies the payment method. + /// The data to pass to the SDK. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutSDKAction(TypeEnum type, Option paymentData = default, Option paymentMethodType = default, Option?> sdkData = default, Option url = default) + { + Type = type; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _SdkDataOption = sdkData; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutSDKAction() + { + } + + partial void OnCreated(); + + /// + /// The type of the action. + /// + /// The type of the action. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Sdk - sdk + /// + public static readonly TypeEnum Sdk = new("sdk"); + + /// + /// TypeEnum.WechatpaySDK - wechatpaySDK + /// + public static readonly TypeEnum WechatpaySDK = new("wechatpaySDK"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sdk" => TypeEnum.Sdk, + "wechatpaySDK" => TypeEnum.WechatpaySDK, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Sdk) + return "sdk"; + + if (value == TypeEnum.WechatpaySDK) + return "wechatpaySDK"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the action. + /// + /// The type of the action. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SdkDataOption { get; private set; } + + /// + /// The data to pass to the SDK. + /// + /// The data to pass to the SDK. + [JsonPropertyName("sdkData")] + public Dictionary? SdkData { get { return this._SdkDataOption; } set { this._SdkDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutSDKAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" SdkData: ").Append(SdkData).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutSDKActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutSDKAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option paymentData = default; + Option paymentMethodType = default; + Option?> sdkData = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutSDKAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "sdkData": + sdkData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutSDKAction.", nameof(type)); + + return new CheckoutSDKAction(type.Value!.Value!, paymentData, paymentMethodType, sdkData, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutSDKAction checkoutSDKAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutSDKAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutSDKAction checkoutSDKAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutSDKAction.Type != null) + { + string? typeRawValue = CheckoutSDKAction.TypeEnum.ToJsonValue(checkoutSDKAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutSDKAction._PaymentDataOption.IsSet) + if (checkoutSDKAction.PaymentData != null) + writer.WriteString("paymentData", checkoutSDKAction.PaymentData); + + if (checkoutSDKAction._PaymentMethodTypeOption.IsSet) + if (checkoutSDKAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutSDKAction.PaymentMethodType); + + if (checkoutSDKAction._SdkDataOption.IsSet) + { + writer.WritePropertyName("sdkData"); + JsonSerializer.Serialize(writer, checkoutSDKAction.SdkData, jsonSerializerOptions); + } + if (checkoutSDKAction._UrlOption.IsSet) + if (checkoutSDKAction.Url != null) + writer.WriteString("url", checkoutSDKAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutSessionInstallmentOption.cs b/Adyen/Checkout/Models/CheckoutSessionInstallmentOption.cs new file mode 100644 index 000000000..ad7cc2a0b --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutSessionInstallmentOption.cs @@ -0,0 +1,403 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutSessionInstallmentOption. + /// + public partial class CheckoutSessionInstallmentOption : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving*** **bonus** * **with_interest** * **buynow_paylater** * **nointerest_bonus** * **interest_bonus** * **refund_prctg** * **nointeres_refund_prctg** * **interes_refund_prctg** + /// Preselected number of installments offered for this payment method. + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + [JsonConstructor] + public CheckoutSessionInstallmentOption(Option?> plans = default, Option preselectedValue = default, Option?> values = default) + { + _PlansOption = plans; + _PreselectedValueOption = preselectedValue; + _ValuesOption = values; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutSessionInstallmentOption() + { + } + + partial void OnCreated(); + + /// + /// Defines Plans. + /// + [JsonConverter(typeof(PlansEnumJsonConverter))] + public class PlansEnum : IEnum + { + /// + /// Returns the value of the PlansEnum. + /// + public string? Value { get; set; } + + /// + /// PlansEnum.Bonus - bonus + /// + public static readonly PlansEnum Bonus = new("bonus"); + + /// + /// PlansEnum.BuynowPaylater - buynow_paylater + /// + public static readonly PlansEnum BuynowPaylater = new("buynow_paylater"); + + /// + /// PlansEnum.InteresRefundPrctg - interes_refund_prctg + /// + public static readonly PlansEnum InteresRefundPrctg = new("interes_refund_prctg"); + + /// + /// PlansEnum.InterestBonus - interest_bonus + /// + public static readonly PlansEnum InterestBonus = new("interest_bonus"); + + /// + /// PlansEnum.NointeresRefundPrctg - nointeres_refund_prctg + /// + public static readonly PlansEnum NointeresRefundPrctg = new("nointeres_refund_prctg"); + + /// + /// PlansEnum.NointerestBonus - nointerest_bonus + /// + public static readonly PlansEnum NointerestBonus = new("nointerest_bonus"); + + /// + /// PlansEnum.RefundPrctg - refund_prctg + /// + public static readonly PlansEnum RefundPrctg = new("refund_prctg"); + + /// + /// PlansEnum.Regular - regular + /// + public static readonly PlansEnum Regular = new("regular"); + + /// + /// PlansEnum.Revolving - revolving + /// + public static readonly PlansEnum Revolving = new("revolving"); + + /// + /// PlansEnum.WithInterest - with_interest + /// + public static readonly PlansEnum WithInterest = new("with_interest"); + + private PlansEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlansEnum?(string? value) => value == null ? null : new PlansEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlansEnum? option) => option?.Value; + + public static bool operator ==(PlansEnum? left, PlansEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlansEnum? left, PlansEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlansEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlansEnum? FromStringOrDefault(string value) + { + return value switch { + "bonus" => PlansEnum.Bonus, + "buynow_paylater" => PlansEnum.BuynowPaylater, + "interes_refund_prctg" => PlansEnum.InteresRefundPrctg, + "interest_bonus" => PlansEnum.InterestBonus, + "nointeres_refund_prctg" => PlansEnum.NointeresRefundPrctg, + "nointerest_bonus" => PlansEnum.NointerestBonus, + "refund_prctg" => PlansEnum.RefundPrctg, + "regular" => PlansEnum.Regular, + "revolving" => PlansEnum.Revolving, + "with_interest" => PlansEnum.WithInterest, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlansEnum? value) + { + if (value == null) + return null; + + if (value == PlansEnum.Bonus) + return "bonus"; + + if (value == PlansEnum.BuynowPaylater) + return "buynow_paylater"; + + if (value == PlansEnum.InteresRefundPrctg) + return "interes_refund_prctg"; + + if (value == PlansEnum.InterestBonus) + return "interest_bonus"; + + if (value == PlansEnum.NointeresRefundPrctg) + return "nointeres_refund_prctg"; + + if (value == PlansEnum.NointerestBonus) + return "nointerest_bonus"; + + if (value == PlansEnum.RefundPrctg) + return "refund_prctg"; + + if (value == PlansEnum.Regular) + return "regular"; + + if (value == PlansEnum.Revolving) + return "revolving"; + + if (value == PlansEnum.WithInterest) + return "with_interest"; + + return null; + } + + /// + /// JsonConverter for writing PlansEnum. + /// + public class PlansEnumJsonConverter : JsonConverter + { + public override PlansEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlansEnum.FromStringOrDefault(value) ?? new PlansEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlansEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlansEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PlansOption { get; private set; } + + /// + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving*** **bonus** * **with_interest** * **buynow_paylater** * **nointerest_bonus** * **interest_bonus** * **refund_prctg** * **nointeres_refund_prctg** * **interes_refund_prctg** + /// + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving*** **bonus** * **with_interest** * **buynow_paylater** * **nointerest_bonus** * **interest_bonus** * **refund_prctg** * **nointeres_refund_prctg** * **interes_refund_prctg** + [JsonPropertyName("plans")] + public List? Plans { get { return this._PlansOption; } set { this._PlansOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreselectedValueOption { get; private set; } + + /// + /// Preselected number of installments offered for this payment method. + /// + /// Preselected number of installments offered for this payment method. + [JsonPropertyName("preselectedValue")] + public int? PreselectedValue { get { return this._PreselectedValueOption; } set { this._PreselectedValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValuesOption { get; private set; } + + /// + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + /// + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + [JsonPropertyName("values")] + public List? Values { get { return this._ValuesOption; } set { this._ValuesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutSessionInstallmentOption {\n"); + sb.Append(" Plans: ").Append(Plans).Append("\n"); + sb.Append(" PreselectedValue: ").Append(PreselectedValue).Append("\n"); + sb.Append(" Values: ").Append(Values).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutSessionInstallmentOptionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutSessionInstallmentOption Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> plans = default; + Option preselectedValue = default; + Option?> values = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "plans": + plans = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "preselectedValue": + preselectedValue = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "values": + values = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CheckoutSessionInstallmentOption(plans, preselectedValue, values); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutSessionInstallmentOption checkoutSessionInstallmentOption, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutSessionInstallmentOption, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutSessionInstallmentOption checkoutSessionInstallmentOption, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutSessionInstallmentOption._PlansOption.IsSet) + { + writer.WritePropertyName("plans"); + JsonSerializer.Serialize(writer, checkoutSessionInstallmentOption.Plans, jsonSerializerOptions); + } + if (checkoutSessionInstallmentOption._PreselectedValueOption.IsSet) + writer.WriteNumber("preselectedValue", checkoutSessionInstallmentOption._PreselectedValueOption.Value!.Value); + + if (checkoutSessionInstallmentOption._ValuesOption.IsSet) + { + writer.WritePropertyName("values"); + JsonSerializer.Serialize(writer, checkoutSessionInstallmentOption.Values, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutSessionThreeDS2RequestData.cs b/Adyen/Checkout/Models/CheckoutSessionThreeDS2RequestData.cs new file mode 100644 index 000000000..cb860d362 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutSessionThreeDS2RequestData.cs @@ -0,0 +1,395 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutSessionThreeDS2RequestData. + /// + public partial class CheckoutSessionThreeDS2RequestData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// homePhone + /// mobilePhone + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// workPhone + [JsonConstructor] + public CheckoutSessionThreeDS2RequestData(Option homePhone = default, Option mobilePhone = default, Option threeDSRequestorChallengeInd = default, Option workPhone = default) + { + _HomePhoneOption = homePhone; + _MobilePhoneOption = mobilePhone; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutSessionThreeDS2RequestData() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("homePhone")] + public Phone? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mobilePhone")] + public Phone? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("workPhone")] + public Phone? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutSessionThreeDS2RequestData {\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutSessionThreeDS2RequestDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutSessionThreeDS2RequestData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option homePhone = default; + Option mobilePhone = default; + Option threeDSRequestorChallengeInd = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "homePhone": + homePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mobilePhone": + mobilePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(CheckoutSessionThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "workPhone": + workPhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CheckoutSessionThreeDS2RequestData(homePhone, mobilePhone, threeDSRequestorChallengeInd, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutSessionThreeDS2RequestData checkoutSessionThreeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutSessionThreeDS2RequestData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutSessionThreeDS2RequestData checkoutSessionThreeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutSessionThreeDS2RequestData._HomePhoneOption.IsSet) + { + writer.WritePropertyName("homePhone"); + JsonSerializer.Serialize(writer, checkoutSessionThreeDS2RequestData.HomePhone, jsonSerializerOptions); + } + if (checkoutSessionThreeDS2RequestData._MobilePhoneOption.IsSet) + { + writer.WritePropertyName("mobilePhone"); + JsonSerializer.Serialize(writer, checkoutSessionThreeDS2RequestData.MobilePhone, jsonSerializerOptions); + } + if (checkoutSessionThreeDS2RequestData._ThreeDSRequestorChallengeIndOption.IsSet && checkoutSessionThreeDS2RequestData.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = CheckoutSessionThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(checkoutSessionThreeDS2RequestData._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (checkoutSessionThreeDS2RequestData._WorkPhoneOption.IsSet) + { + writer.WritePropertyName("workPhone"); + JsonSerializer.Serialize(writer, checkoutSessionThreeDS2RequestData.WorkPhone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutThreeDS2Action.cs b/Adyen/Checkout/Models/CheckoutThreeDS2Action.cs new file mode 100644 index 000000000..1211e0954 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutThreeDS2Action.cs @@ -0,0 +1,419 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutThreeDS2Action. + /// + public partial class CheckoutThreeDS2Action : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **threeDS2** + /// A token needed to authorise a payment. + /// Encoded payment data. + /// Specifies the payment method. + /// A subtype of the token. + /// A token to pass to the 3DS2 Component to get the fingerprint. + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutThreeDS2Action(TypeEnum type, Option authorisationToken = default, Option paymentData = default, Option paymentMethodType = default, Option subtype = default, Option token = default, Option url = default) + { + Type = type; + _AuthorisationTokenOption = authorisationToken; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _SubtypeOption = subtype; + _TokenOption = token; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutThreeDS2Action() + { + } + + partial void OnCreated(); + + /// + /// **threeDS2** + /// + /// **threeDS2** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.ThreeDS2 - threeDS2 + /// + public static readonly TypeEnum ThreeDS2 = new("threeDS2"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "threeDS2" => TypeEnum.ThreeDS2, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.ThreeDS2) + return "threeDS2"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **threeDS2** + /// + /// **threeDS2** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTokenOption { get; private set; } + + /// + /// A token needed to authorise a payment. + /// + /// A token needed to authorise a payment. + [JsonPropertyName("authorisationToken")] + public string? AuthorisationToken { get { return this._AuthorisationTokenOption; } set { this._AuthorisationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// A subtype of the token. + /// + /// A subtype of the token. + [JsonPropertyName("subtype")] + public string? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenOption { get; private set; } + + /// + /// A token to pass to the 3DS2 Component to get the fingerprint. + /// + /// A token to pass to the 3DS2 Component to get the fingerprint. + [JsonPropertyName("token")] + public string? Token { get { return this._TokenOption; } set { this._TokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutThreeDS2Action {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AuthorisationToken: ").Append(AuthorisationToken).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutThreeDS2ActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutThreeDS2Action Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option authorisationToken = default; + Option paymentData = default; + Option paymentMethodType = default; + Option subtype = default; + Option token = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutThreeDS2Action.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "authorisationToken": + authorisationToken = new Option(utf8JsonReader.GetString()!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + subtype = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutThreeDS2Action.", nameof(type)); + + return new CheckoutThreeDS2Action(type.Value!.Value!, authorisationToken, paymentData, paymentMethodType, subtype, token, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutThreeDS2Action checkoutThreeDS2Action, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutThreeDS2Action, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutThreeDS2Action checkoutThreeDS2Action, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutThreeDS2Action.Type != null) + { + string? typeRawValue = CheckoutThreeDS2Action.TypeEnum.ToJsonValue(checkoutThreeDS2Action.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutThreeDS2Action._AuthorisationTokenOption.IsSet) + if (checkoutThreeDS2Action.AuthorisationToken != null) + writer.WriteString("authorisationToken", checkoutThreeDS2Action.AuthorisationToken); + + if (checkoutThreeDS2Action._PaymentDataOption.IsSet) + if (checkoutThreeDS2Action.PaymentData != null) + writer.WriteString("paymentData", checkoutThreeDS2Action.PaymentData); + + if (checkoutThreeDS2Action._PaymentMethodTypeOption.IsSet) + if (checkoutThreeDS2Action.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutThreeDS2Action.PaymentMethodType); + + if (checkoutThreeDS2Action._SubtypeOption.IsSet) + if (checkoutThreeDS2Action.Subtype != null) + writer.WriteString("subtype", checkoutThreeDS2Action.Subtype); + + if (checkoutThreeDS2Action._TokenOption.IsSet) + if (checkoutThreeDS2Action.Token != null) + writer.WriteString("token", checkoutThreeDS2Action.Token); + + if (checkoutThreeDS2Action._UrlOption.IsSet) + if (checkoutThreeDS2Action.Url != null) + writer.WriteString("url", checkoutThreeDS2Action.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CheckoutVoucherAction.cs b/Adyen/Checkout/Models/CheckoutVoucherAction.cs new file mode 100644 index 000000000..11f14cae4 --- /dev/null +++ b/Adyen/Checkout/Models/CheckoutVoucherAction.cs @@ -0,0 +1,769 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CheckoutVoucherAction. + /// + public partial class CheckoutVoucherAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// **voucher** + /// The voucher alternative reference code. + /// A collection institution number (store number) for Econtext Pay-Easy ATM. + /// The URL to download the voucher. + /// An entity number of Multibanco. + /// The date time of the voucher expiry. + /// initialAmount + /// The URL to the detailed instructions to make payment using the voucher. + /// The issuer of the voucher. + /// The shopper telephone number (partially masked). + /// The merchant name. + /// The merchant reference. + /// A Base64-encoded token containing all properties of the voucher. For iOS, you can use this to pass a voucher to Apple Wallet. + /// Encoded payment data. + /// Specifies the payment method. + /// The voucher reference code. + /// The shopper email. + /// The shopper name. + /// surcharge + /// totalAmount + /// Specifies the URL to redirect to. + [JsonConstructor] + public CheckoutVoucherAction(TypeEnum type, Option alternativeReference = default, Option collectionInstitutionNumber = default, Option downloadUrl = default, Option entity = default, Option expiresAt = default, Option initialAmount = default, Option instructionsUrl = default, Option issuer = default, Option maskedTelephoneNumber = default, Option merchantName = default, Option merchantReference = default, Option passCreationToken = default, Option paymentData = default, Option paymentMethodType = default, Option reference = default, Option shopperEmail = default, Option shopperName = default, Option surcharge = default, Option totalAmount = default, Option url = default) + { + Type = type; + _AlternativeReferenceOption = alternativeReference; + _CollectionInstitutionNumberOption = collectionInstitutionNumber; + _DownloadUrlOption = downloadUrl; + _EntityOption = entity; + _ExpiresAtOption = expiresAt; + _InitialAmountOption = initialAmount; + _InstructionsUrlOption = instructionsUrl; + _IssuerOption = issuer; + _MaskedTelephoneNumberOption = maskedTelephoneNumber; + _MerchantNameOption = merchantName; + _MerchantReferenceOption = merchantReference; + _PassCreationTokenOption = passCreationToken; + _PaymentDataOption = paymentData; + _PaymentMethodTypeOption = paymentMethodType; + _ReferenceOption = reference; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _SurchargeOption = surcharge; + _TotalAmountOption = totalAmount; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckoutVoucherAction() + { + } + + partial void OnCreated(); + + /// + /// **voucher** + /// + /// **voucher** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Voucher - voucher + /// + public static readonly TypeEnum Voucher = new("voucher"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "voucher" => TypeEnum.Voucher, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Voucher) + return "voucher"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **voucher** + /// + /// **voucher** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AlternativeReferenceOption { get; private set; } + + /// + /// The voucher alternative reference code. + /// + /// The voucher alternative reference code. + [JsonPropertyName("alternativeReference")] + public string? AlternativeReference { get { return this._AlternativeReferenceOption; } set { this._AlternativeReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CollectionInstitutionNumberOption { get; private set; } + + /// + /// A collection institution number (store number) for Econtext Pay-Easy ATM. + /// + /// A collection institution number (store number) for Econtext Pay-Easy ATM. + [JsonPropertyName("collectionInstitutionNumber")] + public string? CollectionInstitutionNumber { get { return this._CollectionInstitutionNumberOption; } set { this._CollectionInstitutionNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DownloadUrlOption { get; private set; } + + /// + /// The URL to download the voucher. + /// + /// The URL to download the voucher. + [JsonPropertyName("downloadUrl")] + public string? DownloadUrl { get { return this._DownloadUrlOption; } set { this._DownloadUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityOption { get; private set; } + + /// + /// An entity number of Multibanco. + /// + /// An entity number of Multibanco. + [JsonPropertyName("entity")] + public string? Entity { get { return this._EntityOption; } set { this._EntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The date time of the voucher expiry. + /// + /// The date time of the voucher expiry. + [JsonPropertyName("expiresAt")] + public string? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InitialAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("initialAmount")] + public Amount? InitialAmount { get { return this._InitialAmountOption; } set { this._InitialAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstructionsUrlOption { get; private set; } + + /// + /// The URL to the detailed instructions to make payment using the voucher. + /// + /// The URL to the detailed instructions to make payment using the voucher. + [JsonPropertyName("instructionsUrl")] + public string? InstructionsUrl { get { return this._InstructionsUrlOption; } set { this._InstructionsUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The issuer of the voucher. + /// + /// The issuer of the voucher. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaskedTelephoneNumberOption { get; private set; } + + /// + /// The shopper telephone number (partially masked). + /// + /// The shopper telephone number (partially masked). + [JsonPropertyName("maskedTelephoneNumber")] + public string? MaskedTelephoneNumber { get { return this._MaskedTelephoneNumberOption; } set { this._MaskedTelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantNameOption { get; private set; } + + /// + /// The merchant name. + /// + /// The merchant name. + [JsonPropertyName("merchantName")] + public string? MerchantName { get { return this._MerchantNameOption; } set { this._MerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The merchant reference. + /// + /// The merchant reference. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PassCreationTokenOption { get; private set; } + + /// + /// A Base64-encoded token containing all properties of the voucher. For iOS, you can use this to pass a voucher to Apple Wallet. + /// + /// A Base64-encoded token containing all properties of the voucher. For iOS, you can use this to pass a voucher to Apple Wallet. + [JsonPropertyName("passCreationToken")] + public string? PassCreationToken { get { return this._PassCreationTokenOption; } set { this._PassCreationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. + /// + /// Encoded payment data. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodTypeOption { get; private set; } + + /// + /// Specifies the payment method. + /// + /// Specifies the payment method. + [JsonPropertyName("paymentMethodType")] + public string? PaymentMethodType { get { return this._PaymentMethodTypeOption; } set { this._PaymentMethodTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The voucher reference code. + /// + /// The voucher reference code. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper email. + /// + /// The shopper email. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// The shopper name. + /// + /// The shopper name. + [JsonPropertyName("shopperName")] + public string? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SurchargeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("surcharge")] + public Amount? Surcharge { get { return this._SurchargeOption; } set { this._SurchargeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("totalAmount")] + public Amount? TotalAmount { get { return this._TotalAmountOption; } set { this._TotalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Specifies the URL to redirect to. + /// + /// Specifies the URL to redirect to. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckoutVoucherAction {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AlternativeReference: ").Append(AlternativeReference).Append("\n"); + sb.Append(" CollectionInstitutionNumber: ").Append(CollectionInstitutionNumber).Append("\n"); + sb.Append(" DownloadUrl: ").Append(DownloadUrl).Append("\n"); + sb.Append(" Entity: ").Append(Entity).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" InitialAmount: ").Append(InitialAmount).Append("\n"); + sb.Append(" InstructionsUrl: ").Append(InstructionsUrl).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" MaskedTelephoneNumber: ").Append(MaskedTelephoneNumber).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" PassCreationToken: ").Append(PassCreationToken).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PaymentMethodType: ").Append(PaymentMethodType).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" TotalAmount: ").Append(TotalAmount).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckoutVoucherActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckoutVoucherAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option alternativeReference = default; + Option collectionInstitutionNumber = default; + Option downloadUrl = default; + Option entity = default; + Option expiresAt = default; + Option initialAmount = default; + Option instructionsUrl = default; + Option issuer = default; + Option maskedTelephoneNumber = default; + Option merchantName = default; + Option merchantReference = default; + Option passCreationToken = default; + Option paymentData = default; + Option paymentMethodType = default; + Option reference = default; + Option shopperEmail = default; + Option shopperName = default; + Option surcharge = default; + Option totalAmount = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CheckoutVoucherAction.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "alternativeReference": + alternativeReference = new Option(utf8JsonReader.GetString()!); + break; + case "collectionInstitutionNumber": + collectionInstitutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "downloadUrl": + downloadUrl = new Option(utf8JsonReader.GetString()!); + break; + case "entity": + entity = new Option(utf8JsonReader.GetString()!); + break; + case "expiresAt": + expiresAt = new Option(utf8JsonReader.GetString()!); + break; + case "initialAmount": + initialAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "instructionsUrl": + instructionsUrl = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "maskedTelephoneNumber": + maskedTelephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "passCreationToken": + passCreationToken = new Option(utf8JsonReader.GetString()!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodType": + paymentMethodType = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(utf8JsonReader.GetString()!); + break; + case "surcharge": + surcharge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "totalAmount": + totalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CheckoutVoucherAction.", nameof(type)); + + return new CheckoutVoucherAction(type.Value!.Value!, alternativeReference, collectionInstitutionNumber, downloadUrl, entity, expiresAt, initialAmount, instructionsUrl, issuer, maskedTelephoneNumber, merchantName, merchantReference, passCreationToken, paymentData, paymentMethodType, reference, shopperEmail, shopperName, surcharge, totalAmount, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckoutVoucherAction checkoutVoucherAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkoutVoucherAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckoutVoucherAction checkoutVoucherAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkoutVoucherAction.Type != null) + { + string? typeRawValue = CheckoutVoucherAction.TypeEnum.ToJsonValue(checkoutVoucherAction.Type); + writer.WriteString("type", typeRawValue); + } + + if (checkoutVoucherAction._AlternativeReferenceOption.IsSet) + if (checkoutVoucherAction.AlternativeReference != null) + writer.WriteString("alternativeReference", checkoutVoucherAction.AlternativeReference); + + if (checkoutVoucherAction._CollectionInstitutionNumberOption.IsSet) + if (checkoutVoucherAction.CollectionInstitutionNumber != null) + writer.WriteString("collectionInstitutionNumber", checkoutVoucherAction.CollectionInstitutionNumber); + + if (checkoutVoucherAction._DownloadUrlOption.IsSet) + if (checkoutVoucherAction.DownloadUrl != null) + writer.WriteString("downloadUrl", checkoutVoucherAction.DownloadUrl); + + if (checkoutVoucherAction._EntityOption.IsSet) + if (checkoutVoucherAction.Entity != null) + writer.WriteString("entity", checkoutVoucherAction.Entity); + + if (checkoutVoucherAction._ExpiresAtOption.IsSet) + if (checkoutVoucherAction.ExpiresAt != null) + writer.WriteString("expiresAt", checkoutVoucherAction.ExpiresAt); + + if (checkoutVoucherAction._InitialAmountOption.IsSet) + { + writer.WritePropertyName("initialAmount"); + JsonSerializer.Serialize(writer, checkoutVoucherAction.InitialAmount, jsonSerializerOptions); + } + if (checkoutVoucherAction._InstructionsUrlOption.IsSet) + if (checkoutVoucherAction.InstructionsUrl != null) + writer.WriteString("instructionsUrl", checkoutVoucherAction.InstructionsUrl); + + if (checkoutVoucherAction._IssuerOption.IsSet) + if (checkoutVoucherAction.Issuer != null) + writer.WriteString("issuer", checkoutVoucherAction.Issuer); + + if (checkoutVoucherAction._MaskedTelephoneNumberOption.IsSet) + if (checkoutVoucherAction.MaskedTelephoneNumber != null) + writer.WriteString("maskedTelephoneNumber", checkoutVoucherAction.MaskedTelephoneNumber); + + if (checkoutVoucherAction._MerchantNameOption.IsSet) + if (checkoutVoucherAction.MerchantName != null) + writer.WriteString("merchantName", checkoutVoucherAction.MerchantName); + + if (checkoutVoucherAction._MerchantReferenceOption.IsSet) + if (checkoutVoucherAction.MerchantReference != null) + writer.WriteString("merchantReference", checkoutVoucherAction.MerchantReference); + + if (checkoutVoucherAction._PassCreationTokenOption.IsSet) + if (checkoutVoucherAction.PassCreationToken != null) + writer.WriteString("passCreationToken", checkoutVoucherAction.PassCreationToken); + + if (checkoutVoucherAction._PaymentDataOption.IsSet) + if (checkoutVoucherAction.PaymentData != null) + writer.WriteString("paymentData", checkoutVoucherAction.PaymentData); + + if (checkoutVoucherAction._PaymentMethodTypeOption.IsSet) + if (checkoutVoucherAction.PaymentMethodType != null) + writer.WriteString("paymentMethodType", checkoutVoucherAction.PaymentMethodType); + + if (checkoutVoucherAction._ReferenceOption.IsSet) + if (checkoutVoucherAction.Reference != null) + writer.WriteString("reference", checkoutVoucherAction.Reference); + + if (checkoutVoucherAction._ShopperEmailOption.IsSet) + if (checkoutVoucherAction.ShopperEmail != null) + writer.WriteString("shopperEmail", checkoutVoucherAction.ShopperEmail); + + if (checkoutVoucherAction._ShopperNameOption.IsSet) + if (checkoutVoucherAction.ShopperName != null) + writer.WriteString("shopperName", checkoutVoucherAction.ShopperName); + + if (checkoutVoucherAction._SurchargeOption.IsSet) + { + writer.WritePropertyName("surcharge"); + JsonSerializer.Serialize(writer, checkoutVoucherAction.Surcharge, jsonSerializerOptions); + } + if (checkoutVoucherAction._TotalAmountOption.IsSet) + { + writer.WritePropertyName("totalAmount"); + JsonSerializer.Serialize(writer, checkoutVoucherAction.TotalAmount, jsonSerializerOptions); + } + if (checkoutVoucherAction._UrlOption.IsSet) + if (checkoutVoucherAction.Url != null) + writer.WriteString("url", checkoutVoucherAction.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CommonField.cs b/Adyen/Checkout/Models/CommonField.cs new file mode 100644 index 000000000..e49de2a00 --- /dev/null +++ b/Adyen/Checkout/Models/CommonField.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CommonField. + /// + public partial class CommonField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name of the field. For example, Name of External Platform. + /// Version of the field. For example, Version of External Platform. + [JsonConstructor] + public CommonField(Option name = default, Option version = default) + { + _NameOption = name; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CommonField() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Name of the field. For example, Name of External Platform. + /// + /// Name of the field. For example, Name of External Platform. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// Version of the field. For example, Version of External Platform. + /// + /// Version of the field. For example, Version of External Platform. + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CommonField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CommonFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CommonField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CommonField(name, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CommonField commonField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, commonField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CommonField commonField, JsonSerializerOptions jsonSerializerOptions) + { + + if (commonField._NameOption.IsSet) + if (commonField.Name != null) + writer.WriteString("name", commonField.Name); + + if (commonField._VersionOption.IsSet) + if (commonField.Version != null) + writer.WriteString("version", commonField.Version); + } + } +} diff --git a/Adyen/Checkout/Models/Company.cs b/Adyen/Checkout/Models/Company.cs new file mode 100644 index 000000000..0e7d828bf --- /dev/null +++ b/Adyen/Checkout/Models/Company.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Company. + /// + public partial class Company : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The company website's home page. + /// The company name. + /// Registration number of the company. + /// Registry location of the company. + /// Tax ID of the company. + /// The company type. + [JsonConstructor] + public Company(Option homepage = default, Option name = default, Option registrationNumber = default, Option registryLocation = default, Option taxId = default, Option type = default) + { + _HomepageOption = homepage; + _NameOption = name; + _RegistrationNumberOption = registrationNumber; + _RegistryLocationOption = registryLocation; + _TaxIdOption = taxId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Company() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomepageOption { get; private set; } + + /// + /// The company website's home page. + /// + /// The company website's home page. + [JsonPropertyName("homepage")] + public string? Homepage { get { return this._HomepageOption; } set { this._HomepageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The company name. + /// + /// The company name. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberOption { get; private set; } + + /// + /// Registration number of the company. + /// + /// Registration number of the company. + [JsonPropertyName("registrationNumber")] + public string? RegistrationNumber { get { return this._RegistrationNumberOption; } set { this._RegistrationNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistryLocationOption { get; private set; } + + /// + /// Registry location of the company. + /// + /// Registry location of the company. + [JsonPropertyName("registryLocation")] + public string? RegistryLocation { get { return this._RegistryLocationOption; } set { this._RegistryLocationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// Tax ID of the company. + /// + /// Tax ID of the company. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The company type. + /// + /// The company type. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Company {\n"); + sb.Append(" Homepage: ").Append(Homepage).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RegistrationNumber: ").Append(RegistrationNumber).Append("\n"); + sb.Append(" RegistryLocation: ").Append(RegistryLocation).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CompanyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Company Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option homepage = default; + Option name = default; + Option registrationNumber = default; + Option registryLocation = default; + Option taxId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "homepage": + homepage = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "registrationNumber": + registrationNumber = new Option(utf8JsonReader.GetString()!); + break; + case "registryLocation": + registryLocation = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Company(homepage, name, registrationNumber, registryLocation, taxId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Company company, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, company, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Company company, JsonSerializerOptions jsonSerializerOptions) + { + + if (company._HomepageOption.IsSet) + if (company.Homepage != null) + writer.WriteString("homepage", company.Homepage); + + if (company._NameOption.IsSet) + if (company.Name != null) + writer.WriteString("name", company.Name); + + if (company._RegistrationNumberOption.IsSet) + if (company.RegistrationNumber != null) + writer.WriteString("registrationNumber", company.RegistrationNumber); + + if (company._RegistryLocationOption.IsSet) + if (company.RegistryLocation != null) + writer.WriteString("registryLocation", company.RegistryLocation); + + if (company._TaxIdOption.IsSet) + if (company.TaxId != null) + writer.WriteString("taxId", company.TaxId); + + if (company._TypeOption.IsSet) + if (company.Type != null) + writer.WriteString("type", company.Type); + } + } +} diff --git a/Adyen/Checkout/Models/CreateCheckoutSessionRequest.cs b/Adyen/Checkout/Models/CreateCheckoutSessionRequest.cs new file mode 100644 index 000000000..5ff1da723 --- /dev/null +++ b/Adyen/Checkout/Models/CreateCheckoutSessionRequest.cs @@ -0,0 +1,2372 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CreateCheckoutSessionRequest. + /// + public partial class CreateCheckoutSessionRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// applicationInfo + /// authenticationData + /// billingAddress + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// company + /// The shopper's two-letter country code. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// deliveryAddress + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + /// fundOrigin + /// fundRecipient + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// mandate + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration (default to ModeEnum.Embedded) + /// mpiData + /// platformChargebackLogic + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// riskData + /// The shopper's email address. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// Set to true to show the payment amount per installment. + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + /// The shopper's social security number. + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false) + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public CreateCheckoutSessionRequest(Amount amount, string merchantAccount, string reference, string returnUrl, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option?> allowedPaymentMethods = default, Option applicationInfo = default, Option authenticationData = default, Option billingAddress = default, Option?> blockedPaymentMethods = default, Option captureDelayHours = default, Option channel = default, Option company = default, Option countryCode = default, Option dateOfBirth = default, Option deliverAt = default, Option deliveryAddress = default, Option enableOneClick = default, Option enablePayOut = default, Option enableRecurring = default, Option expiresAt = default, Option fundOrigin = default, Option fundRecipient = default, Option?> installmentOptions = default, Option?> lineItems = default, Option mandate = default, Option mcc = default, Option merchantOrderReference = default, Option?> metadata = default, Option mode = default, Option mpiData = default, Option platformChargebackLogic = default, Option recurringExpiry = default, Option recurringFrequency = default, Option recurringProcessingModel = default, Option redirectFromIssuerMethod = default, Option redirectToIssuerMethod = default, Option riskData = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option showInstallmentAmount = default, Option showRemovePaymentMethodButton = default, Option socialSecurityNumber = default, Option splitCardFundingSources = default, Option?> splits = default, Option store = default, Option storeFiltrationMode = default, Option storePaymentMethod = default, Option storePaymentMethodMode = default, Option telephoneNumber = default, Option themeId = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option trustedShopper = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + ReturnUrl = returnUrl; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _AllowedPaymentMethodsOption = allowedPaymentMethods; + _ApplicationInfoOption = applicationInfo; + _AuthenticationDataOption = authenticationData; + _BillingAddressOption = billingAddress; + _BlockedPaymentMethodsOption = blockedPaymentMethods; + _CaptureDelayHoursOption = captureDelayHours; + _ChannelOption = channel; + _CompanyOption = company; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _EnableOneClickOption = enableOneClick; + _EnablePayOutOption = enablePayOut; + _EnableRecurringOption = enableRecurring; + _ExpiresAtOption = expiresAt; + _FundOriginOption = fundOrigin; + _FundRecipientOption = fundRecipient; + _InstallmentOptionsOption = installmentOptions; + _LineItemsOption = lineItems; + _MandateOption = mandate; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MetadataOption = metadata; + _ModeOption = mode; + _MpiDataOption = mpiData; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _RecurringProcessingModelOption = recurringProcessingModel; + _RedirectFromIssuerMethodOption = redirectFromIssuerMethod; + _RedirectToIssuerMethodOption = redirectToIssuerMethod; + _RiskDataOption = riskData; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _ShowInstallmentAmountOption = showInstallmentAmount; + _ShowRemovePaymentMethodButtonOption = showRemovePaymentMethodButton; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitCardFundingSourcesOption = splitCardFundingSources; + _SplitsOption = splits; + _StoreOption = store; + _StoreFiltrationModeOption = storeFiltrationMode; + _StorePaymentMethodOption = storePaymentMethod; + _StorePaymentMethodModeOption = storePaymentMethodMode; + _TelephoneNumberOption = telephoneNumber; + _ThemeIdOption = themeId; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCheckoutSessionRequest() + { + } + + partial void OnCreated(); + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + [JsonConverter(typeof(ChannelEnumJsonConverter))] + public class ChannelEnum : IEnum + { + /// + /// Returns the value of the ChannelEnum. + /// + public string? Value { get; set; } + + /// + /// ChannelEnum.IOS - iOS + /// + public static readonly ChannelEnum IOS = new("iOS"); + + /// + /// ChannelEnum.Android - Android + /// + public static readonly ChannelEnum Android = new("Android"); + + /// + /// ChannelEnum.Web - Web + /// + public static readonly ChannelEnum Web = new("Web"); + + private ChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChannelEnum?(string? value) => value == null ? null : new ChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChannelEnum? option) => option?.Value; + + public static bool operator ==(ChannelEnum? left, ChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChannelEnum? left, ChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "iOS" => ChannelEnum.IOS, + "Android" => ChannelEnum.Android, + "Web" => ChannelEnum.Web, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChannelEnum? value) + { + if (value == null) + return null; + + if (value == ChannelEnum.IOS) + return "iOS"; + + if (value == ChannelEnum.Android) + return "Android"; + + if (value == ChannelEnum.Web) + return "Web"; + + return null; + } + + /// + /// JsonConverter for writing ChannelEnum. + /// + public class ChannelEnumJsonConverter : JsonConverter + { + public override ChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChannelEnum.FromStringOrDefault(value) ?? new ChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + [JsonPropertyName("channel")] + public ChannelEnum? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + [JsonConverter(typeof(ModeEnumJsonConverter))] + public class ModeEnum : IEnum + { + /// + /// Returns the value of the ModeEnum. + /// + public string? Value { get; set; } + + /// + /// ModeEnum.Embedded - embedded + /// + public static readonly ModeEnum Embedded = new("embedded"); + + /// + /// ModeEnum.Hosted - hosted + /// + public static readonly ModeEnum Hosted = new("hosted"); + + private ModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ModeEnum?(string? value) => value == null ? null : new ModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ModeEnum? option) => option?.Value; + + public static bool operator ==(ModeEnum? left, ModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ModeEnum? left, ModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ModeEnum? FromStringOrDefault(string value) + { + return value switch { + "embedded" => ModeEnum.Embedded, + "hosted" => ModeEnum.Hosted, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ModeEnum? value) + { + if (value == null) + return null; + + if (value == ModeEnum.Embedded) + return "embedded"; + + if (value == ModeEnum.Hosted) + return "hosted"; + + return null; + } + + /// + /// JsonConverter for writing ModeEnum. + /// + public class ModeEnumJsonConverter : JsonConverter + { + public override ModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ModeEnum.FromStringOrDefault(value) ?? new ModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModeOption { get; private set; } + + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + [JsonPropertyName("mode")] + public ModeEnum? Mode { get { return this._ModeOption; } set { this._ModeOption = new(value); } } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonConverter(typeof(StoreFiltrationModeEnumJsonConverter))] + public class StoreFiltrationModeEnum : IEnum + { + /// + /// Returns the value of the StoreFiltrationModeEnum. + /// + public string? Value { get; set; } + + /// + /// StoreFiltrationModeEnum.Exclusive - exclusive + /// + public static readonly StoreFiltrationModeEnum Exclusive = new("exclusive"); + + /// + /// StoreFiltrationModeEnum.Inclusive - inclusive + /// + public static readonly StoreFiltrationModeEnum Inclusive = new("inclusive"); + + /// + /// StoreFiltrationModeEnum.SkipFilter - skipFilter + /// + public static readonly StoreFiltrationModeEnum SkipFilter = new("skipFilter"); + + private StoreFiltrationModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StoreFiltrationModeEnum?(string? value) => value == null ? null : new StoreFiltrationModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StoreFiltrationModeEnum? option) => option?.Value; + + public static bool operator ==(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StoreFiltrationModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StoreFiltrationModeEnum? FromStringOrDefault(string value) + { + return value switch { + "exclusive" => StoreFiltrationModeEnum.Exclusive, + "inclusive" => StoreFiltrationModeEnum.Inclusive, + "skipFilter" => StoreFiltrationModeEnum.SkipFilter, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StoreFiltrationModeEnum? value) + { + if (value == null) + return null; + + if (value == StoreFiltrationModeEnum.Exclusive) + return "exclusive"; + + if (value == StoreFiltrationModeEnum.Inclusive) + return "inclusive"; + + if (value == StoreFiltrationModeEnum.SkipFilter) + return "skipFilter"; + + return null; + } + + /// + /// JsonConverter for writing StoreFiltrationModeEnum. + /// + public class StoreFiltrationModeEnumJsonConverter : JsonConverter + { + public override StoreFiltrationModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StoreFiltrationModeEnum.FromStringOrDefault(value) ?? new StoreFiltrationModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StoreFiltrationModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StoreFiltrationModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreFiltrationModeOption { get; private set; } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonPropertyName("storeFiltrationMode")] + public StoreFiltrationModeEnum? StoreFiltrationMode { get { return this._StoreFiltrationModeOption; } set { this._StoreFiltrationModeOption = new(value); } } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + [JsonConverter(typeof(StorePaymentMethodModeEnumJsonConverter))] + public class StorePaymentMethodModeEnum : IEnum + { + /// + /// Returns the value of the StorePaymentMethodModeEnum. + /// + public string? Value { get; set; } + + /// + /// StorePaymentMethodModeEnum.AskForConsent - askForConsent + /// + public static readonly StorePaymentMethodModeEnum AskForConsent = new("askForConsent"); + + /// + /// StorePaymentMethodModeEnum.Disabled - disabled + /// + public static readonly StorePaymentMethodModeEnum Disabled = new("disabled"); + + /// + /// StorePaymentMethodModeEnum.Enabled - enabled + /// + public static readonly StorePaymentMethodModeEnum Enabled = new("enabled"); + + private StorePaymentMethodModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StorePaymentMethodModeEnum?(string? value) => value == null ? null : new StorePaymentMethodModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StorePaymentMethodModeEnum? option) => option?.Value; + + public static bool operator ==(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StorePaymentMethodModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StorePaymentMethodModeEnum? FromStringOrDefault(string value) + { + return value switch { + "askForConsent" => StorePaymentMethodModeEnum.AskForConsent, + "disabled" => StorePaymentMethodModeEnum.Disabled, + "enabled" => StorePaymentMethodModeEnum.Enabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StorePaymentMethodModeEnum? value) + { + if (value == null) + return null; + + if (value == StorePaymentMethodModeEnum.AskForConsent) + return "askForConsent"; + + if (value == StorePaymentMethodModeEnum.Disabled) + return "disabled"; + + if (value == StorePaymentMethodModeEnum.Enabled) + return "enabled"; + + return null; + } + + /// + /// JsonConverter for writing StorePaymentMethodModeEnum. + /// + public class StorePaymentMethodModeEnumJsonConverter : JsonConverter + { + public override StorePaymentMethodModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StorePaymentMethodModeEnum.FromStringOrDefault(value) ?? new StorePaymentMethodModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StorePaymentMethodModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StorePaymentMethodModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodModeOption { get; private set; } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + [JsonPropertyName("storePaymentMethodMode")] + public StorePaymentMethodModeEnum? StorePaymentMethodMode { get { return this._StorePaymentMethodModeOption; } set { this._StorePaymentMethodModeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. + /// + /// The reference to uniquely identify a payment. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("returnUrl")] + public string ReturnUrl { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("allowedPaymentMethods")] + public List? AllowedPaymentMethods { get { return this._AllowedPaymentMethodsOption; } set { this._AllowedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationData")] + public AuthenticationData? AuthenticationData { get { return this._AuthenticationDataOption; } set { this._AuthenticationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public BillingAddress? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BlockedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("blockedPaymentMethods")] + public List? BlockedPaymentMethods { get { return this._BlockedPaymentMethodsOption; } set { this._BlockedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("company")] + public Company? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper's two-letter country code. + /// + /// The shopper's two-letter country code. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public DeliveryAddress? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableOneClickOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + [JsonPropertyName("enableOneClick")] + public bool? EnableOneClick { get { return this._EnableOneClickOption; } set { this._EnableOneClickOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnablePayOutOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + [JsonPropertyName("enablePayOut")] + public bool? EnablePayOut { get { return this._EnablePayOutOption; } set { this._EnablePayOutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableRecurringOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + [JsonPropertyName("enableRecurring")] + public bool? EnableRecurring { get { return this._EnableRecurringOption; } set { this._EnableRecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + /// + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + [JsonPropertyName("expiresAt")] + public DateTimeOffset? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundOriginOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundOrigin")] + public FundOrigin? FundOrigin { get { return this._FundOriginOption; } set { this._FundOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundRecipientOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundRecipient")] + public FundRecipient? FundRecipient { get { return this._FundRecipientOption; } set { this._FundRecipientOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InstallmentOptionsOption { get; private set; } + + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + [JsonPropertyName("installmentOptions")] + public Dictionary? InstallmentOptions { get { return this._InstallmentOptionsOption; } set { this._InstallmentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mandate")] + public Mandate? Mandate { get { return this._MandateOption; } set { this._MandateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectFromIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + [JsonPropertyName("redirectFromIssuerMethod")] + public string? RedirectFromIssuerMethod { get { return this._RedirectFromIssuerMethodOption; } set { this._RedirectFromIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectToIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + [JsonPropertyName("redirectToIssuerMethod")] + public string? RedirectToIssuerMethod { get { return this._RedirectToIssuerMethodOption; } set { this._RedirectToIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskData")] + public RiskData? RiskData { get { return this._RiskDataOption; } set { this._RiskDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public ShopperName? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowInstallmentAmountOption { get; private set; } + + /// + /// Set to true to show the payment amount per installment. + /// + /// Set to true to show the payment amount per installment. + [JsonPropertyName("showInstallmentAmount")] + public bool? ShowInstallmentAmount { get { return this._ShowInstallmentAmountOption; } set { this._ShowInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowRemovePaymentMethodButtonOption { get; private set; } + + /// + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + /// + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + [JsonPropertyName("showRemovePaymentMethodButton")] + public bool? ShowRemovePaymentMethodButton { get { return this._ShowRemovePaymentMethodButtonOption; } set { this._ShowRemovePaymentMethodButtonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitCardFundingSourcesOption { get; private set; } + + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + [JsonPropertyName("splitCardFundingSources")] + public bool? SplitCardFundingSources { get { return this._SplitCardFundingSourcesOption; } set { this._SplitCardFundingSourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + [JsonPropertyName("storePaymentMethod")] + public bool? StorePaymentMethod { get { return this._StorePaymentMethodOption; } set { this._StorePaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThemeIdOption { get; private set; } + + /// + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + /// + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + [JsonPropertyName("themeId")] + public string? ThemeId { get { return this._ThemeIdOption; } set { this._ThemeIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public CheckoutSessionThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCheckoutSessionRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" AuthenticationData: ").Append(AuthenticationData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" EnableOneClick: ").Append(EnableOneClick).Append("\n"); + sb.Append(" EnablePayOut: ").Append(EnablePayOut).Append("\n"); + sb.Append(" EnableRecurring: ").Append(EnableRecurring).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" FundOrigin: ").Append(FundOrigin).Append("\n"); + sb.Append(" FundRecipient: ").Append(FundRecipient).Append("\n"); + sb.Append(" InstallmentOptions: ").Append(InstallmentOptions).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" Mandate: ").Append(Mandate).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" Mode: ").Append(Mode).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RedirectFromIssuerMethod: ").Append(RedirectFromIssuerMethod).Append("\n"); + sb.Append(" RedirectToIssuerMethod: ").Append(RedirectToIssuerMethod).Append("\n"); + sb.Append(" RiskData: ").Append(RiskData).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" ShowInstallmentAmount: ").Append(ShowInstallmentAmount).Append("\n"); + sb.Append(" ShowRemovePaymentMethodButton: ").Append(ShowRemovePaymentMethodButton).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StoreFiltrationMode: ").Append(StoreFiltrationMode).Append("\n"); + sb.Append(" StorePaymentMethod: ").Append(StorePaymentMethod).Append("\n"); + sb.Append(" StorePaymentMethodMode: ").Append(StorePaymentMethodMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThemeId: ").Append(ThemeId).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCheckoutSessionRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCheckoutSessionRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option returnUrl = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option?> allowedPaymentMethods = default; + Option applicationInfo = default; + Option authenticationData = default; + Option billingAddress = default; + Option?> blockedPaymentMethods = default; + Option captureDelayHours = default; + Option channel = default; + Option company = default; + Option countryCode = default; + Option dateOfBirth = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option enableOneClick = default; + Option enablePayOut = default; + Option enableRecurring = default; + Option expiresAt = default; + Option fundOrigin = default; + Option fundRecipient = default; + Option?> installmentOptions = default; + Option?> lineItems = default; + Option mandate = default; + Option mcc = default; + Option merchantOrderReference = default; + Option?> metadata = default; + Option mode = default; + Option mpiData = default; + Option platformChargebackLogic = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option recurringProcessingModel = default; + Option redirectFromIssuerMethod = default; + Option redirectToIssuerMethod = default; + Option riskData = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option showInstallmentAmount = default; + Option showRemovePaymentMethodButton = default; + Option socialSecurityNumber = default; + Option splitCardFundingSources = default; + Option?> splits = default; + Option store = default; + Option storeFiltrationMode = default; + Option storePaymentMethod = default; + Option storePaymentMethodMode = default; + Option telephoneNumber = default; + Option themeId = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedPaymentMethods": + allowedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationData": + authenticationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "blockedPaymentMethods": + blockedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "channel": + string? channelRawValue = utf8JsonReader.GetString(); + channel = new Option(CreateCheckoutSessionRequest.ChannelEnum.FromStringOrDefault(channelRawValue)); + break; + case "company": + company = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enableOneClick": + enableOneClick = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enablePayOut": + enablePayOut = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enableRecurring": + enableRecurring = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "fundOrigin": + fundOrigin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundRecipient": + fundRecipient = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "installmentOptions": + installmentOptions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mandate": + mandate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mode": + string? modeRawValue = utf8JsonReader.GetString(); + mode = new Option(CreateCheckoutSessionRequest.ModeEnum.FromStringOrDefault(modeRawValue)); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(CreateCheckoutSessionRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "redirectFromIssuerMethod": + redirectFromIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "redirectToIssuerMethod": + redirectToIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "riskData": + riskData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(CreateCheckoutSessionRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "showInstallmentAmount": + showInstallmentAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "showRemovePaymentMethodButton": + showRemovePaymentMethodButton = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splitCardFundingSources": + splitCardFundingSources = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storeFiltrationMode": + string? storeFiltrationModeRawValue = utf8JsonReader.GetString(); + storeFiltrationMode = new Option(CreateCheckoutSessionRequest.StoreFiltrationModeEnum.FromStringOrDefault(storeFiltrationModeRawValue)); + break; + case "storePaymentMethod": + storePaymentMethod = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "storePaymentMethodMode": + string? storePaymentMethodModeRawValue = utf8JsonReader.GetString(); + storePaymentMethodMode = new Option(CreateCheckoutSessionRequest.StorePaymentMethodModeEnum.FromStringOrDefault(storePaymentMethodModeRawValue)); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "themeId": + themeId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionRequest.", nameof(reference)); + + if (!returnUrl.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionRequest.", nameof(returnUrl)); + + return new CreateCheckoutSessionRequest(amount.Value!, merchantAccount.Value!, reference.Value!, returnUrl.Value!, accountInfo, additionalAmount, additionalData, allowedPaymentMethods, applicationInfo, authenticationData, billingAddress, blockedPaymentMethods, captureDelayHours, channel, company, countryCode, dateOfBirth, deliverAt, deliveryAddress, enableOneClick, enablePayOut, enableRecurring, expiresAt, fundOrigin, fundRecipient, installmentOptions, lineItems, mandate, mcc, merchantOrderReference, metadata, mode, mpiData, platformChargebackLogic, recurringExpiry, recurringFrequency, recurringProcessingModel, redirectFromIssuerMethod, redirectToIssuerMethod, riskData, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, showInstallmentAmount, showRemovePaymentMethodButton, socialSecurityNumber, splitCardFundingSources, splits, store, storeFiltrationMode, storePaymentMethod, storePaymentMethodMode, telephoneNumber, themeId, threeDS2RequestData, threeDSAuthenticationOnly, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCheckoutSessionRequest createCheckoutSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCheckoutSessionRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCheckoutSessionRequest createCheckoutSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.Amount, jsonSerializerOptions); + if (createCheckoutSessionRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", createCheckoutSessionRequest.MerchantAccount); + + if (createCheckoutSessionRequest.Reference != null) + writer.WriteString("reference", createCheckoutSessionRequest.Reference); + + if (createCheckoutSessionRequest.ReturnUrl != null) + writer.WriteString("returnUrl", createCheckoutSessionRequest.ReturnUrl); + + if (createCheckoutSessionRequest._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.AccountInfo, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.AdditionalAmount, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.AdditionalData, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._AllowedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("allowedPaymentMethods"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.AllowedPaymentMethods, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.ApplicationInfo, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._AuthenticationDataOption.IsSet) + { + writer.WritePropertyName("authenticationData"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.AuthenticationData, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.BillingAddress, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._BlockedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("blockedPaymentMethods"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.BlockedPaymentMethods, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", createCheckoutSessionRequest._CaptureDelayHoursOption.Value!.Value); + + if (createCheckoutSessionRequest._ChannelOption.IsSet && createCheckoutSessionRequest.Channel != null) + { + string? channelRawValue = CreateCheckoutSessionRequest.ChannelEnum.ToJsonValue(createCheckoutSessionRequest._ChannelOption.Value!.Value); + writer.WriteString("channel", channelRawValue); + } + + if (createCheckoutSessionRequest._CompanyOption.IsSet) + { + writer.WritePropertyName("company"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.Company, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._CountryCodeOption.IsSet) + if (createCheckoutSessionRequest.CountryCode != null) + writer.WriteString("countryCode", createCheckoutSessionRequest.CountryCode); + + if (createCheckoutSessionRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", createCheckoutSessionRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (createCheckoutSessionRequest._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", createCheckoutSessionRequest._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (createCheckoutSessionRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.DeliveryAddress, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._EnableOneClickOption.IsSet) + writer.WriteBoolean("enableOneClick", createCheckoutSessionRequest._EnableOneClickOption.Value!.Value); + + if (createCheckoutSessionRequest._EnablePayOutOption.IsSet) + writer.WriteBoolean("enablePayOut", createCheckoutSessionRequest._EnablePayOutOption.Value!.Value); + + if (createCheckoutSessionRequest._EnableRecurringOption.IsSet) + writer.WriteBoolean("enableRecurring", createCheckoutSessionRequest._EnableRecurringOption.Value!.Value); + + if (createCheckoutSessionRequest._ExpiresAtOption.IsSet) + writer.WriteString("expiresAt", createCheckoutSessionRequest._ExpiresAtOption.Value!.Value.ToString(ExpiresAtFormat)); + + if (createCheckoutSessionRequest._FundOriginOption.IsSet) + { + writer.WritePropertyName("fundOrigin"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.FundOrigin, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._FundRecipientOption.IsSet) + { + writer.WritePropertyName("fundRecipient"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.FundRecipient, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._InstallmentOptionsOption.IsSet) + { + writer.WritePropertyName("installmentOptions"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.InstallmentOptions, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.LineItems, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._MandateOption.IsSet) + { + writer.WritePropertyName("mandate"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.Mandate, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._MccOption.IsSet) + if (createCheckoutSessionRequest.Mcc != null) + writer.WriteString("mcc", createCheckoutSessionRequest.Mcc); + + if (createCheckoutSessionRequest._MerchantOrderReferenceOption.IsSet) + if (createCheckoutSessionRequest.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", createCheckoutSessionRequest.MerchantOrderReference); + + if (createCheckoutSessionRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.Metadata, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._ModeOption.IsSet && createCheckoutSessionRequest.Mode != null) + { + string? modeRawValue = CreateCheckoutSessionRequest.ModeEnum.ToJsonValue(createCheckoutSessionRequest._ModeOption.Value!.Value); + writer.WriteString("mode", modeRawValue); + } + + if (createCheckoutSessionRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.MpiData, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._RecurringExpiryOption.IsSet) + if (createCheckoutSessionRequest.RecurringExpiry != null) + writer.WriteString("recurringExpiry", createCheckoutSessionRequest.RecurringExpiry); + + if (createCheckoutSessionRequest._RecurringFrequencyOption.IsSet) + if (createCheckoutSessionRequest.RecurringFrequency != null) + writer.WriteString("recurringFrequency", createCheckoutSessionRequest.RecurringFrequency); + + if (createCheckoutSessionRequest._RecurringProcessingModelOption.IsSet && createCheckoutSessionRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = CreateCheckoutSessionRequest.RecurringProcessingModelEnum.ToJsonValue(createCheckoutSessionRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (createCheckoutSessionRequest._RedirectFromIssuerMethodOption.IsSet) + if (createCheckoutSessionRequest.RedirectFromIssuerMethod != null) + writer.WriteString("redirectFromIssuerMethod", createCheckoutSessionRequest.RedirectFromIssuerMethod); + + if (createCheckoutSessionRequest._RedirectToIssuerMethodOption.IsSet) + if (createCheckoutSessionRequest.RedirectToIssuerMethod != null) + writer.WriteString("redirectToIssuerMethod", createCheckoutSessionRequest.RedirectToIssuerMethod); + + if (createCheckoutSessionRequest._RiskDataOption.IsSet) + { + writer.WritePropertyName("riskData"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.RiskData, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._ShopperEmailOption.IsSet) + if (createCheckoutSessionRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", createCheckoutSessionRequest.ShopperEmail); + + if (createCheckoutSessionRequest._ShopperIPOption.IsSet) + if (createCheckoutSessionRequest.ShopperIP != null) + writer.WriteString("shopperIP", createCheckoutSessionRequest.ShopperIP); + + if (createCheckoutSessionRequest._ShopperInteractionOption.IsSet && createCheckoutSessionRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = CreateCheckoutSessionRequest.ShopperInteractionEnum.ToJsonValue(createCheckoutSessionRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (createCheckoutSessionRequest._ShopperLocaleOption.IsSet) + if (createCheckoutSessionRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", createCheckoutSessionRequest.ShopperLocale); + + if (createCheckoutSessionRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.ShopperName, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._ShopperReferenceOption.IsSet) + if (createCheckoutSessionRequest.ShopperReference != null) + writer.WriteString("shopperReference", createCheckoutSessionRequest.ShopperReference); + + if (createCheckoutSessionRequest._ShopperStatementOption.IsSet) + if (createCheckoutSessionRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", createCheckoutSessionRequest.ShopperStatement); + + if (createCheckoutSessionRequest._ShowInstallmentAmountOption.IsSet) + writer.WriteBoolean("showInstallmentAmount", createCheckoutSessionRequest._ShowInstallmentAmountOption.Value!.Value); + + if (createCheckoutSessionRequest._ShowRemovePaymentMethodButtonOption.IsSet) + writer.WriteBoolean("showRemovePaymentMethodButton", createCheckoutSessionRequest._ShowRemovePaymentMethodButtonOption.Value!.Value); + + if (createCheckoutSessionRequest._SocialSecurityNumberOption.IsSet) + if (createCheckoutSessionRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", createCheckoutSessionRequest.SocialSecurityNumber); + + if (createCheckoutSessionRequest._SplitCardFundingSourcesOption.IsSet) + writer.WriteBoolean("splitCardFundingSources", createCheckoutSessionRequest._SplitCardFundingSourcesOption.Value!.Value); + + if (createCheckoutSessionRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.Splits, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._StoreOption.IsSet) + if (createCheckoutSessionRequest.Store != null) + writer.WriteString("store", createCheckoutSessionRequest.Store); + + if (createCheckoutSessionRequest._StoreFiltrationModeOption.IsSet && createCheckoutSessionRequest.StoreFiltrationMode != null) + { + string? storeFiltrationModeRawValue = CreateCheckoutSessionRequest.StoreFiltrationModeEnum.ToJsonValue(createCheckoutSessionRequest._StoreFiltrationModeOption.Value!.Value); + writer.WriteString("storeFiltrationMode", storeFiltrationModeRawValue); + } + + if (createCheckoutSessionRequest._StorePaymentMethodOption.IsSet) + writer.WriteBoolean("storePaymentMethod", createCheckoutSessionRequest._StorePaymentMethodOption.Value!.Value); + + if (createCheckoutSessionRequest._StorePaymentMethodModeOption.IsSet && createCheckoutSessionRequest.StorePaymentMethodMode != null) + { + string? storePaymentMethodModeRawValue = CreateCheckoutSessionRequest.StorePaymentMethodModeEnum.ToJsonValue(createCheckoutSessionRequest._StorePaymentMethodModeOption.Value!.Value); + writer.WriteString("storePaymentMethodMode", storePaymentMethodModeRawValue); + } + + if (createCheckoutSessionRequest._TelephoneNumberOption.IsSet) + if (createCheckoutSessionRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", createCheckoutSessionRequest.TelephoneNumber); + + if (createCheckoutSessionRequest._ThemeIdOption.IsSet) + if (createCheckoutSessionRequest.ThemeId != null) + writer.WriteString("themeId", createCheckoutSessionRequest.ThemeId); + + if (createCheckoutSessionRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, createCheckoutSessionRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + if (createCheckoutSessionRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", createCheckoutSessionRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (createCheckoutSessionRequest._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", createCheckoutSessionRequest._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/CreateCheckoutSessionResponse.cs b/Adyen/Checkout/Models/CreateCheckoutSessionResponse.cs new file mode 100644 index 000000000..bfd180699 --- /dev/null +++ b/Adyen/Checkout/Models/CreateCheckoutSessionResponse.cs @@ -0,0 +1,2437 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CreateCheckoutSessionResponse. + /// + public partial class CreateCheckoutSessionResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + /// A unique identifier of the session. + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// applicationInfo + /// authenticationData + /// billingAddress + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// company + /// The shopper's two-letter country code. + /// The shopper's date of birth in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// deliveryAddress + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// fundOrigin + /// fundRecipient + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// mandate + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration (default to ModeEnum.Embedded) + /// mpiData + /// platformChargebackLogic + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// riskData + /// The payment session data you need to pass to your front end. + /// The shopper's email address. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// Set to true to show the payment amount per installment. + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + /// The shopper's social security number. + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false) + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// Set to true if the payment should be routed to a trusted MID. + /// The URL for the Hosted Checkout page. Redirect the shopper to this URL so they can make the payment. + [JsonConstructor] + public CreateCheckoutSessionResponse(Amount amount, DateTimeOffset expiresAt, string id, string merchantAccount, string reference, string returnUrl, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option?> allowedPaymentMethods = default, Option applicationInfo = default, Option authenticationData = default, Option billingAddress = default, Option?> blockedPaymentMethods = default, Option captureDelayHours = default, Option channel = default, Option company = default, Option countryCode = default, Option dateOfBirth = default, Option deliverAt = default, Option deliveryAddress = default, Option enableOneClick = default, Option enablePayOut = default, Option enableRecurring = default, Option fundOrigin = default, Option fundRecipient = default, Option?> installmentOptions = default, Option?> lineItems = default, Option mandate = default, Option mcc = default, Option merchantOrderReference = default, Option?> metadata = default, Option mode = default, Option mpiData = default, Option platformChargebackLogic = default, Option recurringExpiry = default, Option recurringFrequency = default, Option recurringProcessingModel = default, Option redirectFromIssuerMethod = default, Option redirectToIssuerMethod = default, Option riskData = default, Option sessionData = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option showInstallmentAmount = default, Option showRemovePaymentMethodButton = default, Option socialSecurityNumber = default, Option splitCardFundingSources = default, Option?> splits = default, Option store = default, Option storeFiltrationMode = default, Option storePaymentMethod = default, Option storePaymentMethodMode = default, Option telephoneNumber = default, Option themeId = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option trustedShopper = default, Option url = default) + { + Amount = amount; + ExpiresAt = expiresAt; + Id = id; + MerchantAccount = merchantAccount; + Reference = reference; + ReturnUrl = returnUrl; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _AllowedPaymentMethodsOption = allowedPaymentMethods; + _ApplicationInfoOption = applicationInfo; + _AuthenticationDataOption = authenticationData; + _BillingAddressOption = billingAddress; + _BlockedPaymentMethodsOption = blockedPaymentMethods; + _CaptureDelayHoursOption = captureDelayHours; + _ChannelOption = channel; + _CompanyOption = company; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _EnableOneClickOption = enableOneClick; + _EnablePayOutOption = enablePayOut; + _EnableRecurringOption = enableRecurring; + _FundOriginOption = fundOrigin; + _FundRecipientOption = fundRecipient; + _InstallmentOptionsOption = installmentOptions; + _LineItemsOption = lineItems; + _MandateOption = mandate; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MetadataOption = metadata; + _ModeOption = mode; + _MpiDataOption = mpiData; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _RecurringProcessingModelOption = recurringProcessingModel; + _RedirectFromIssuerMethodOption = redirectFromIssuerMethod; + _RedirectToIssuerMethodOption = redirectToIssuerMethod; + _RiskDataOption = riskData; + _SessionDataOption = sessionData; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _ShowInstallmentAmountOption = showInstallmentAmount; + _ShowRemovePaymentMethodButtonOption = showRemovePaymentMethodButton; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitCardFundingSourcesOption = splitCardFundingSources; + _SplitsOption = splits; + _StoreOption = store; + _StoreFiltrationModeOption = storeFiltrationMode; + _StorePaymentMethodOption = storePaymentMethod; + _StorePaymentMethodModeOption = storePaymentMethodMode; + _TelephoneNumberOption = telephoneNumber; + _ThemeIdOption = themeId; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TrustedShopperOption = trustedShopper; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCheckoutSessionResponse() + { + } + + partial void OnCreated(); + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + [JsonConverter(typeof(ChannelEnumJsonConverter))] + public class ChannelEnum : IEnum + { + /// + /// Returns the value of the ChannelEnum. + /// + public string? Value { get; set; } + + /// + /// ChannelEnum.IOS - iOS + /// + public static readonly ChannelEnum IOS = new("iOS"); + + /// + /// ChannelEnum.Android - Android + /// + public static readonly ChannelEnum Android = new("Android"); + + /// + /// ChannelEnum.Web - Web + /// + public static readonly ChannelEnum Web = new("Web"); + + private ChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChannelEnum?(string? value) => value == null ? null : new ChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChannelEnum? option) => option?.Value; + + public static bool operator ==(ChannelEnum? left, ChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChannelEnum? left, ChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "iOS" => ChannelEnum.IOS, + "Android" => ChannelEnum.Android, + "Web" => ChannelEnum.Web, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChannelEnum? value) + { + if (value == null) + return null; + + if (value == ChannelEnum.IOS) + return "iOS"; + + if (value == ChannelEnum.Android) + return "Android"; + + if (value == ChannelEnum.Web) + return "Web"; + + return null; + } + + /// + /// JsonConverter for writing ChannelEnum. + /// + public class ChannelEnumJsonConverter : JsonConverter + { + public override ChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChannelEnum.FromStringOrDefault(value) ?? new ChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * **iOS** * **Android** * **Web** + [JsonPropertyName("channel")] + public ChannelEnum? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + [JsonConverter(typeof(ModeEnumJsonConverter))] + public class ModeEnum : IEnum + { + /// + /// Returns the value of the ModeEnum. + /// + public string? Value { get; set; } + + /// + /// ModeEnum.Embedded - embedded + /// + public static readonly ModeEnum Embedded = new("embedded"); + + /// + /// ModeEnum.Hosted - hosted + /// + public static readonly ModeEnum Hosted = new("hosted"); + + private ModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ModeEnum?(string? value) => value == null ? null : new ModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ModeEnum? option) => option?.Value; + + public static bool operator ==(ModeEnum? left, ModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ModeEnum? left, ModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ModeEnum? FromStringOrDefault(string value) + { + return value switch { + "embedded" => ModeEnum.Embedded, + "hosted" => ModeEnum.Hosted, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ModeEnum? value) + { + if (value == null) + return null; + + if (value == ModeEnum.Embedded) + return "embedded"; + + if (value == ModeEnum.Hosted) + return "hosted"; + + return null; + } + + /// + /// JsonConverter for writing ModeEnum. + /// + public class ModeEnumJsonConverter : JsonConverter + { + public override ModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ModeEnum.FromStringOrDefault(value) ?? new ModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModeOption { get; private set; } + + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + /// + /// Indicates the type of front end integration. Possible values: * **embedded** (default): Drop-in or Components integration * **hosted**: Hosted Checkout integration + [JsonPropertyName("mode")] + public ModeEnum? Mode { get { return this._ModeOption; } set { this._ModeOption = new(value); } } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonConverter(typeof(StoreFiltrationModeEnumJsonConverter))] + public class StoreFiltrationModeEnum : IEnum + { + /// + /// Returns the value of the StoreFiltrationModeEnum. + /// + public string? Value { get; set; } + + /// + /// StoreFiltrationModeEnum.Exclusive - exclusive + /// + public static readonly StoreFiltrationModeEnum Exclusive = new("exclusive"); + + /// + /// StoreFiltrationModeEnum.Inclusive - inclusive + /// + public static readonly StoreFiltrationModeEnum Inclusive = new("inclusive"); + + /// + /// StoreFiltrationModeEnum.SkipFilter - skipFilter + /// + public static readonly StoreFiltrationModeEnum SkipFilter = new("skipFilter"); + + private StoreFiltrationModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StoreFiltrationModeEnum?(string? value) => value == null ? null : new StoreFiltrationModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StoreFiltrationModeEnum? option) => option?.Value; + + public static bool operator ==(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StoreFiltrationModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StoreFiltrationModeEnum? FromStringOrDefault(string value) + { + return value switch { + "exclusive" => StoreFiltrationModeEnum.Exclusive, + "inclusive" => StoreFiltrationModeEnum.Inclusive, + "skipFilter" => StoreFiltrationModeEnum.SkipFilter, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StoreFiltrationModeEnum? value) + { + if (value == null) + return null; + + if (value == StoreFiltrationModeEnum.Exclusive) + return "exclusive"; + + if (value == StoreFiltrationModeEnum.Inclusive) + return "inclusive"; + + if (value == StoreFiltrationModeEnum.SkipFilter) + return "skipFilter"; + + return null; + } + + /// + /// JsonConverter for writing StoreFiltrationModeEnum. + /// + public class StoreFiltrationModeEnumJsonConverter : JsonConverter + { + public override StoreFiltrationModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StoreFiltrationModeEnum.FromStringOrDefault(value) ?? new StoreFiltrationModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StoreFiltrationModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StoreFiltrationModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreFiltrationModeOption { get; private set; } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonPropertyName("storeFiltrationMode")] + public StoreFiltrationModeEnum? StoreFiltrationMode { get { return this._StoreFiltrationModeOption; } set { this._StoreFiltrationModeOption = new(value); } } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + [JsonConverter(typeof(StorePaymentMethodModeEnumJsonConverter))] + public class StorePaymentMethodModeEnum : IEnum + { + /// + /// Returns the value of the StorePaymentMethodModeEnum. + /// + public string? Value { get; set; } + + /// + /// StorePaymentMethodModeEnum.AskForConsent - askForConsent + /// + public static readonly StorePaymentMethodModeEnum AskForConsent = new("askForConsent"); + + /// + /// StorePaymentMethodModeEnum.Disabled - disabled + /// + public static readonly StorePaymentMethodModeEnum Disabled = new("disabled"); + + /// + /// StorePaymentMethodModeEnum.Enabled - enabled + /// + public static readonly StorePaymentMethodModeEnum Enabled = new("enabled"); + + private StorePaymentMethodModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StorePaymentMethodModeEnum?(string? value) => value == null ? null : new StorePaymentMethodModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StorePaymentMethodModeEnum? option) => option?.Value; + + public static bool operator ==(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StorePaymentMethodModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StorePaymentMethodModeEnum? FromStringOrDefault(string value) + { + return value switch { + "askForConsent" => StorePaymentMethodModeEnum.AskForConsent, + "disabled" => StorePaymentMethodModeEnum.Disabled, + "enabled" => StorePaymentMethodModeEnum.Enabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StorePaymentMethodModeEnum? value) + { + if (value == null) + return null; + + if (value == StorePaymentMethodModeEnum.AskForConsent) + return "askForConsent"; + + if (value == StorePaymentMethodModeEnum.Disabled) + return "disabled"; + + if (value == StorePaymentMethodModeEnum.Enabled) + return "enabled"; + + return null; + } + + /// + /// JsonConverter for writing StorePaymentMethodModeEnum. + /// + public class StorePaymentMethodModeEnumJsonConverter : JsonConverter + { + public override StorePaymentMethodModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StorePaymentMethodModeEnum.FromStringOrDefault(value) ?? new StorePaymentMethodModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StorePaymentMethodModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StorePaymentMethodModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodModeOption { get; private set; } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. + [JsonPropertyName("storePaymentMethodMode")] + public StorePaymentMethodModeEnum? StorePaymentMethodMode { get { return this._StorePaymentMethodModeOption; } set { this._StorePaymentMethodModeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + /// + /// The date the session expires in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. When not specified, the expiry date is set to 1 hour after session creation. You cannot set the session expiry to more than 24 hours after session creation. + [JsonPropertyName("expiresAt")] + public DateTimeOffset ExpiresAt { get; set; } + + /// + /// A unique identifier of the session. + /// + /// A unique identifier of the session. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. + /// + /// The reference to uniquely identify a payment. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("returnUrl")] + public string ReturnUrl { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("allowedPaymentMethods")] + public List? AllowedPaymentMethods { get { return this._AllowedPaymentMethodsOption; } set { this._AllowedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationData")] + public AuthenticationData? AuthenticationData { get { return this._AuthenticationDataOption; } set { this._AuthenticationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public BillingAddress? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BlockedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("blockedPaymentMethods")] + public List? BlockedPaymentMethods { get { return this._BlockedPaymentMethodsOption; } set { this._BlockedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("company")] + public Company? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper's two-letter country code. + /// + /// The shopper's two-letter country code. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + /// + /// The shopper's date of birth in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + [JsonPropertyName("dateOfBirth")] + public DateTimeOffset? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public DeliveryAddress? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableOneClickOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + [JsonPropertyName("enableOneClick")] + public bool? EnableOneClick { get { return this._EnableOneClickOption; } set { this._EnableOneClickOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnablePayOutOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + [JsonPropertyName("enablePayOut")] + public bool? EnablePayOut { get { return this._EnablePayOutOption; } set { this._EnablePayOutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableRecurringOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + [JsonPropertyName("enableRecurring")] + public bool? EnableRecurring { get { return this._EnableRecurringOption; } set { this._EnableRecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundOriginOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundOrigin")] + public FundOrigin? FundOrigin { get { return this._FundOriginOption; } set { this._FundOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundRecipientOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundRecipient")] + public FundRecipient? FundRecipient { get { return this._FundRecipientOption; } set { this._FundRecipientOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InstallmentOptionsOption { get; private set; } + + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + [JsonPropertyName("installmentOptions")] + public Dictionary? InstallmentOptions { get { return this._InstallmentOptionsOption; } set { this._InstallmentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mandate")] + public Mandate? Mandate { get { return this._MandateOption; } set { this._MandateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectFromIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + [JsonPropertyName("redirectFromIssuerMethod")] + public string? RedirectFromIssuerMethod { get { return this._RedirectFromIssuerMethodOption; } set { this._RedirectFromIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectToIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + [JsonPropertyName("redirectToIssuerMethod")] + public string? RedirectToIssuerMethod { get { return this._RedirectToIssuerMethodOption; } set { this._RedirectToIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskData")] + public RiskData? RiskData { get { return this._RiskDataOption; } set { this._RiskDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionDataOption { get; private set; } + + /// + /// The payment session data you need to pass to your front end. + /// + /// The payment session data you need to pass to your front end. + [JsonPropertyName("sessionData")] + public string? SessionData { get { return this._SessionDataOption; } set { this._SessionDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public ShopperName? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowInstallmentAmountOption { get; private set; } + + /// + /// Set to true to show the payment amount per installment. + /// + /// Set to true to show the payment amount per installment. + [JsonPropertyName("showInstallmentAmount")] + public bool? ShowInstallmentAmount { get { return this._ShowInstallmentAmountOption; } set { this._ShowInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowRemovePaymentMethodButtonOption { get; private set; } + + /// + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + /// + /// Set to **true** to show a button that lets the shopper remove a stored payment method. + [JsonPropertyName("showRemovePaymentMethodButton")] + public bool? ShowRemovePaymentMethodButton { get { return this._ShowRemovePaymentMethodButtonOption; } set { this._ShowRemovePaymentMethodButtonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitCardFundingSourcesOption { get; private set; } + + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + [JsonPropertyName("splitCardFundingSources")] + public bool? SplitCardFundingSources { get { return this._SplitCardFundingSourcesOption; } set { this._SplitCardFundingSourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + [JsonPropertyName("storePaymentMethod")] + public bool? StorePaymentMethod { get { return this._StorePaymentMethodOption; } set { this._StorePaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThemeIdOption { get; private set; } + + /// + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + /// + /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area. + [JsonPropertyName("themeId")] + public string? ThemeId { get { return this._ThemeIdOption; } set { this._ThemeIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public CheckoutSessionThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// The URL for the Hosted Checkout page. Redirect the shopper to this URL so they can make the payment. + /// + /// The URL for the Hosted Checkout page. Redirect the shopper to this URL so they can make the payment. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCheckoutSessionResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" AuthenticationData: ").Append(AuthenticationData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" EnableOneClick: ").Append(EnableOneClick).Append("\n"); + sb.Append(" EnablePayOut: ").Append(EnablePayOut).Append("\n"); + sb.Append(" EnableRecurring: ").Append(EnableRecurring).Append("\n"); + sb.Append(" FundOrigin: ").Append(FundOrigin).Append("\n"); + sb.Append(" FundRecipient: ").Append(FundRecipient).Append("\n"); + sb.Append(" InstallmentOptions: ").Append(InstallmentOptions).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" Mandate: ").Append(Mandate).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" Mode: ").Append(Mode).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RedirectFromIssuerMethod: ").Append(RedirectFromIssuerMethod).Append("\n"); + sb.Append(" RedirectToIssuerMethod: ").Append(RedirectToIssuerMethod).Append("\n"); + sb.Append(" RiskData: ").Append(RiskData).Append("\n"); + sb.Append(" SessionData: ").Append(SessionData).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" ShowInstallmentAmount: ").Append(ShowInstallmentAmount).Append("\n"); + sb.Append(" ShowRemovePaymentMethodButton: ").Append(ShowRemovePaymentMethodButton).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StoreFiltrationMode: ").Append(StoreFiltrationMode).Append("\n"); + sb.Append(" StorePaymentMethod: ").Append(StorePaymentMethod).Append("\n"); + sb.Append(" StorePaymentMethodMode: ").Append(StorePaymentMethodMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThemeId: ").Append(ThemeId).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCheckoutSessionResponseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCheckoutSessionResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option expiresAt = default; + Option id = default; + Option merchantAccount = default; + Option reference = default; + Option returnUrl = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option?> allowedPaymentMethods = default; + Option applicationInfo = default; + Option authenticationData = default; + Option billingAddress = default; + Option?> blockedPaymentMethods = default; + Option captureDelayHours = default; + Option channel = default; + Option company = default; + Option countryCode = default; + Option dateOfBirth = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option enableOneClick = default; + Option enablePayOut = default; + Option enableRecurring = default; + Option fundOrigin = default; + Option fundRecipient = default; + Option?> installmentOptions = default; + Option?> lineItems = default; + Option mandate = default; + Option mcc = default; + Option merchantOrderReference = default; + Option?> metadata = default; + Option mode = default; + Option mpiData = default; + Option platformChargebackLogic = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option recurringProcessingModel = default; + Option redirectFromIssuerMethod = default; + Option redirectToIssuerMethod = default; + Option riskData = default; + Option sessionData = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option showInstallmentAmount = default; + Option showRemovePaymentMethodButton = default; + Option socialSecurityNumber = default; + Option splitCardFundingSources = default; + Option?> splits = default; + Option store = default; + Option storeFiltrationMode = default; + Option storePaymentMethod = default; + Option storePaymentMethodMode = default; + Option telephoneNumber = default; + Option themeId = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option trustedShopper = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedPaymentMethods": + allowedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationData": + authenticationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "blockedPaymentMethods": + blockedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "channel": + string? channelRawValue = utf8JsonReader.GetString(); + channel = new Option(CreateCheckoutSessionResponse.ChannelEnum.FromStringOrDefault(channelRawValue)); + break; + case "company": + company = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enableOneClick": + enableOneClick = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enablePayOut": + enablePayOut = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enableRecurring": + enableRecurring = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "fundOrigin": + fundOrigin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundRecipient": + fundRecipient = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "installmentOptions": + installmentOptions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mandate": + mandate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mode": + string? modeRawValue = utf8JsonReader.GetString(); + mode = new Option(CreateCheckoutSessionResponse.ModeEnum.FromStringOrDefault(modeRawValue)); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(CreateCheckoutSessionResponse.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "redirectFromIssuerMethod": + redirectFromIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "redirectToIssuerMethod": + redirectToIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "riskData": + riskData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sessionData": + sessionData = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(CreateCheckoutSessionResponse.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "showInstallmentAmount": + showInstallmentAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "showRemovePaymentMethodButton": + showRemovePaymentMethodButton = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splitCardFundingSources": + splitCardFundingSources = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storeFiltrationMode": + string? storeFiltrationModeRawValue = utf8JsonReader.GetString(); + storeFiltrationMode = new Option(CreateCheckoutSessionResponse.StoreFiltrationModeEnum.FromStringOrDefault(storeFiltrationModeRawValue)); + break; + case "storePaymentMethod": + storePaymentMethod = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "storePaymentMethodMode": + string? storePaymentMethodModeRawValue = utf8JsonReader.GetString(); + storePaymentMethodMode = new Option(CreateCheckoutSessionResponse.StorePaymentMethodModeEnum.FromStringOrDefault(storePaymentMethodModeRawValue)); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "themeId": + themeId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(amount)); + + if (!expiresAt.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(expiresAt)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(id)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(reference)); + + if (!returnUrl.IsSet) + throw new ArgumentException("Property is required for class CreateCheckoutSessionResponse.", nameof(returnUrl)); + + return new CreateCheckoutSessionResponse(amount.Value!, expiresAt.Value!.Value!, id.Value!, merchantAccount.Value!, reference.Value!, returnUrl.Value!, accountInfo, additionalAmount, additionalData, allowedPaymentMethods, applicationInfo, authenticationData, billingAddress, blockedPaymentMethods, captureDelayHours, channel, company, countryCode, dateOfBirth, deliverAt, deliveryAddress, enableOneClick, enablePayOut, enableRecurring, fundOrigin, fundRecipient, installmentOptions, lineItems, mandate, mcc, merchantOrderReference, metadata, mode, mpiData, platformChargebackLogic, recurringExpiry, recurringFrequency, recurringProcessingModel, redirectFromIssuerMethod, redirectToIssuerMethod, riskData, sessionData, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, showInstallmentAmount, showRemovePaymentMethodButton, socialSecurityNumber, splitCardFundingSources, splits, store, storeFiltrationMode, storePaymentMethod, storePaymentMethodMode, telephoneNumber, themeId, threeDS2RequestData, threeDSAuthenticationOnly, trustedShopper, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCheckoutSessionResponse createCheckoutSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCheckoutSessionResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCheckoutSessionResponse createCheckoutSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.Amount, jsonSerializerOptions); + writer.WriteString("expiresAt", createCheckoutSessionResponse.ExpiresAt.ToString(ExpiresAtFormat)); + + if (createCheckoutSessionResponse.Id != null) + writer.WriteString("id", createCheckoutSessionResponse.Id); + + if (createCheckoutSessionResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", createCheckoutSessionResponse.MerchantAccount); + + if (createCheckoutSessionResponse.Reference != null) + writer.WriteString("reference", createCheckoutSessionResponse.Reference); + + if (createCheckoutSessionResponse.ReturnUrl != null) + writer.WriteString("returnUrl", createCheckoutSessionResponse.ReturnUrl); + + if (createCheckoutSessionResponse._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.AccountInfo, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.AdditionalAmount, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.AdditionalData, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._AllowedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("allowedPaymentMethods"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.AllowedPaymentMethods, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.ApplicationInfo, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._AuthenticationDataOption.IsSet) + { + writer.WritePropertyName("authenticationData"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.AuthenticationData, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.BillingAddress, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._BlockedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("blockedPaymentMethods"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.BlockedPaymentMethods, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", createCheckoutSessionResponse._CaptureDelayHoursOption.Value!.Value); + + if (createCheckoutSessionResponse._ChannelOption.IsSet && createCheckoutSessionResponse.Channel != null) + { + string? channelRawValue = CreateCheckoutSessionResponse.ChannelEnum.ToJsonValue(createCheckoutSessionResponse._ChannelOption.Value!.Value); + writer.WriteString("channel", channelRawValue); + } + + if (createCheckoutSessionResponse._CompanyOption.IsSet) + { + writer.WritePropertyName("company"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.Company, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._CountryCodeOption.IsSet) + if (createCheckoutSessionResponse.CountryCode != null) + writer.WriteString("countryCode", createCheckoutSessionResponse.CountryCode); + + if (createCheckoutSessionResponse._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", createCheckoutSessionResponse._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (createCheckoutSessionResponse._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", createCheckoutSessionResponse._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (createCheckoutSessionResponse._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.DeliveryAddress, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._EnableOneClickOption.IsSet) + writer.WriteBoolean("enableOneClick", createCheckoutSessionResponse._EnableOneClickOption.Value!.Value); + + if (createCheckoutSessionResponse._EnablePayOutOption.IsSet) + writer.WriteBoolean("enablePayOut", createCheckoutSessionResponse._EnablePayOutOption.Value!.Value); + + if (createCheckoutSessionResponse._EnableRecurringOption.IsSet) + writer.WriteBoolean("enableRecurring", createCheckoutSessionResponse._EnableRecurringOption.Value!.Value); + + if (createCheckoutSessionResponse._FundOriginOption.IsSet) + { + writer.WritePropertyName("fundOrigin"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.FundOrigin, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._FundRecipientOption.IsSet) + { + writer.WritePropertyName("fundRecipient"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.FundRecipient, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._InstallmentOptionsOption.IsSet) + { + writer.WritePropertyName("installmentOptions"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.InstallmentOptions, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.LineItems, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._MandateOption.IsSet) + { + writer.WritePropertyName("mandate"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.Mandate, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._MccOption.IsSet) + if (createCheckoutSessionResponse.Mcc != null) + writer.WriteString("mcc", createCheckoutSessionResponse.Mcc); + + if (createCheckoutSessionResponse._MerchantOrderReferenceOption.IsSet) + if (createCheckoutSessionResponse.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", createCheckoutSessionResponse.MerchantOrderReference); + + if (createCheckoutSessionResponse._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.Metadata, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._ModeOption.IsSet && createCheckoutSessionResponse.Mode != null) + { + string? modeRawValue = CreateCheckoutSessionResponse.ModeEnum.ToJsonValue(createCheckoutSessionResponse._ModeOption.Value!.Value); + writer.WriteString("mode", modeRawValue); + } + + if (createCheckoutSessionResponse._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.MpiData, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.PlatformChargebackLogic, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._RecurringExpiryOption.IsSet) + if (createCheckoutSessionResponse.RecurringExpiry != null) + writer.WriteString("recurringExpiry", createCheckoutSessionResponse.RecurringExpiry); + + if (createCheckoutSessionResponse._RecurringFrequencyOption.IsSet) + if (createCheckoutSessionResponse.RecurringFrequency != null) + writer.WriteString("recurringFrequency", createCheckoutSessionResponse.RecurringFrequency); + + if (createCheckoutSessionResponse._RecurringProcessingModelOption.IsSet && createCheckoutSessionResponse.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = CreateCheckoutSessionResponse.RecurringProcessingModelEnum.ToJsonValue(createCheckoutSessionResponse._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (createCheckoutSessionResponse._RedirectFromIssuerMethodOption.IsSet) + if (createCheckoutSessionResponse.RedirectFromIssuerMethod != null) + writer.WriteString("redirectFromIssuerMethod", createCheckoutSessionResponse.RedirectFromIssuerMethod); + + if (createCheckoutSessionResponse._RedirectToIssuerMethodOption.IsSet) + if (createCheckoutSessionResponse.RedirectToIssuerMethod != null) + writer.WriteString("redirectToIssuerMethod", createCheckoutSessionResponse.RedirectToIssuerMethod); + + if (createCheckoutSessionResponse._RiskDataOption.IsSet) + { + writer.WritePropertyName("riskData"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.RiskData, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._SessionDataOption.IsSet) + if (createCheckoutSessionResponse.SessionData != null) + writer.WriteString("sessionData", createCheckoutSessionResponse.SessionData); + + if (createCheckoutSessionResponse._ShopperEmailOption.IsSet) + if (createCheckoutSessionResponse.ShopperEmail != null) + writer.WriteString("shopperEmail", createCheckoutSessionResponse.ShopperEmail); + + if (createCheckoutSessionResponse._ShopperIPOption.IsSet) + if (createCheckoutSessionResponse.ShopperIP != null) + writer.WriteString("shopperIP", createCheckoutSessionResponse.ShopperIP); + + if (createCheckoutSessionResponse._ShopperInteractionOption.IsSet && createCheckoutSessionResponse.ShopperInteraction != null) + { + string? shopperInteractionRawValue = CreateCheckoutSessionResponse.ShopperInteractionEnum.ToJsonValue(createCheckoutSessionResponse._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (createCheckoutSessionResponse._ShopperLocaleOption.IsSet) + if (createCheckoutSessionResponse.ShopperLocale != null) + writer.WriteString("shopperLocale", createCheckoutSessionResponse.ShopperLocale); + + if (createCheckoutSessionResponse._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.ShopperName, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._ShopperReferenceOption.IsSet) + if (createCheckoutSessionResponse.ShopperReference != null) + writer.WriteString("shopperReference", createCheckoutSessionResponse.ShopperReference); + + if (createCheckoutSessionResponse._ShopperStatementOption.IsSet) + if (createCheckoutSessionResponse.ShopperStatement != null) + writer.WriteString("shopperStatement", createCheckoutSessionResponse.ShopperStatement); + + if (createCheckoutSessionResponse._ShowInstallmentAmountOption.IsSet) + writer.WriteBoolean("showInstallmentAmount", createCheckoutSessionResponse._ShowInstallmentAmountOption.Value!.Value); + + if (createCheckoutSessionResponse._ShowRemovePaymentMethodButtonOption.IsSet) + writer.WriteBoolean("showRemovePaymentMethodButton", createCheckoutSessionResponse._ShowRemovePaymentMethodButtonOption.Value!.Value); + + if (createCheckoutSessionResponse._SocialSecurityNumberOption.IsSet) + if (createCheckoutSessionResponse.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", createCheckoutSessionResponse.SocialSecurityNumber); + + if (createCheckoutSessionResponse._SplitCardFundingSourcesOption.IsSet) + writer.WriteBoolean("splitCardFundingSources", createCheckoutSessionResponse._SplitCardFundingSourcesOption.Value!.Value); + + if (createCheckoutSessionResponse._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.Splits, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._StoreOption.IsSet) + if (createCheckoutSessionResponse.Store != null) + writer.WriteString("store", createCheckoutSessionResponse.Store); + + if (createCheckoutSessionResponse._StoreFiltrationModeOption.IsSet && createCheckoutSessionResponse.StoreFiltrationMode != null) + { + string? storeFiltrationModeRawValue = CreateCheckoutSessionResponse.StoreFiltrationModeEnum.ToJsonValue(createCheckoutSessionResponse._StoreFiltrationModeOption.Value!.Value); + writer.WriteString("storeFiltrationMode", storeFiltrationModeRawValue); + } + + if (createCheckoutSessionResponse._StorePaymentMethodOption.IsSet) + writer.WriteBoolean("storePaymentMethod", createCheckoutSessionResponse._StorePaymentMethodOption.Value!.Value); + + if (createCheckoutSessionResponse._StorePaymentMethodModeOption.IsSet && createCheckoutSessionResponse.StorePaymentMethodMode != null) + { + string? storePaymentMethodModeRawValue = CreateCheckoutSessionResponse.StorePaymentMethodModeEnum.ToJsonValue(createCheckoutSessionResponse._StorePaymentMethodModeOption.Value!.Value); + writer.WriteString("storePaymentMethodMode", storePaymentMethodModeRawValue); + } + + if (createCheckoutSessionResponse._TelephoneNumberOption.IsSet) + if (createCheckoutSessionResponse.TelephoneNumber != null) + writer.WriteString("telephoneNumber", createCheckoutSessionResponse.TelephoneNumber); + + if (createCheckoutSessionResponse._ThemeIdOption.IsSet) + if (createCheckoutSessionResponse.ThemeId != null) + writer.WriteString("themeId", createCheckoutSessionResponse.ThemeId); + + if (createCheckoutSessionResponse._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, createCheckoutSessionResponse.ThreeDS2RequestData, jsonSerializerOptions); + } + if (createCheckoutSessionResponse._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", createCheckoutSessionResponse._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (createCheckoutSessionResponse._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", createCheckoutSessionResponse._TrustedShopperOption.Value!.Value); + + if (createCheckoutSessionResponse._UrlOption.IsSet) + if (createCheckoutSessionResponse.Url != null) + writer.WriteString("url", createCheckoutSessionResponse.Url); + } + } +} diff --git a/Adyen/Checkout/Models/CreateOrderRequest.cs b/Adyen/Checkout/Models/CreateOrderRequest.cs new file mode 100644 index 000000000..4a65ef332 --- /dev/null +++ b/Adyen/Checkout/Models/CreateOrderRequest.cs @@ -0,0 +1,234 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CreateOrderRequest. + /// + public partial class CreateOrderRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the order. + /// A custom reference identifying the order. + /// The date when the order should expire. If not provided, the default expiry duration is 1 day. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonConstructor] + public CreateOrderRequest(Amount amount, string merchantAccount, string reference, Option expiresAt = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + _ExpiresAtOption = expiresAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateOrderRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the order. + /// + /// The merchant account identifier, with which you want to process the order. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// A custom reference identifying the order. + /// + /// A custom reference identifying the order. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The date when the order should expire. If not provided, the default expiry duration is 1 day. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date when the order should expire. If not provided, the default expiry duration is 1 day. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("expiresAt")] + public string? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateOrderRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateOrderRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateOrderRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option expiresAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "expiresAt": + expiresAt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CreateOrderRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CreateOrderRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class CreateOrderRequest.", nameof(reference)); + + return new CreateOrderRequest(amount.Value!, merchantAccount.Value!, reference.Value!, expiresAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateOrderRequest createOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createOrderRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateOrderRequest createOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, createOrderRequest.Amount, jsonSerializerOptions); + if (createOrderRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", createOrderRequest.MerchantAccount); + + if (createOrderRequest.Reference != null) + writer.WriteString("reference", createOrderRequest.Reference); + + if (createOrderRequest._ExpiresAtOption.IsSet) + if (createOrderRequest.ExpiresAt != null) + writer.WriteString("expiresAt", createOrderRequest.ExpiresAt); + } + } +} diff --git a/Adyen/Checkout/Models/CreateOrderResponse.cs b/Adyen/Checkout/Models/CreateOrderResponse.cs new file mode 100644 index 000000000..7915df430 --- /dev/null +++ b/Adyen/Checkout/Models/CreateOrderResponse.cs @@ -0,0 +1,471 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// CreateOrderResponse. + /// + public partial class CreateOrderResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The date that the order will expire. + /// The encrypted data that will be used by merchant for adding payments to the order. + /// remainingAmount + /// The result of the order creation request. The value is always **Success**. + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// fraudResult + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// The reference provided by merchant for creating the order. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonConstructor] + public CreateOrderResponse(Amount amount, string expiresAt, string orderData, Amount remainingAmount, ResultCodeEnum resultCode, Option?> additionalData = default, Option fraudResult = default, Option pspReference = default, Option reference = default, Option refusalReason = default) + { + Amount = amount; + ExpiresAt = expiresAt; + OrderData = orderData; + RemainingAmount = remainingAmount; + ResultCode = resultCode; + _AdditionalDataOption = additionalData; + _FraudResultOption = fraudResult; + _PspReferenceOption = pspReference; + _ReferenceOption = reference; + _RefusalReasonOption = refusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateOrderResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the order creation request. The value is always **Success**. + /// + /// The result of the order creation request. The value is always **Success**. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the order creation request. The value is always **Success**. + /// + /// The result of the order creation request. The value is always **Success**. + [JsonPropertyName("resultCode")] + public ResultCodeEnum ResultCode { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The date that the order will expire. + /// + /// The date that the order will expire. + [JsonPropertyName("expiresAt")] + public string ExpiresAt { get; set; } + + /// + /// The encrypted data that will be used by merchant for adding payments to the order. + /// + /// The encrypted data that will be used by merchant for adding payments to the order. + [JsonPropertyName("orderData")] + public string OrderData { get; set; } + + /// + /// . + /// + [JsonPropertyName("remainingAmount")] + public Amount RemainingAmount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference provided by merchant for creating the order. + /// + /// The reference provided by merchant for creating the order. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateOrderResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" OrderData: ").Append(OrderData).Append("\n"); + sb.Append(" RemainingAmount: ").Append(RemainingAmount).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateOrderResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateOrderResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option expiresAt = default; + Option orderData = default; + Option remainingAmount = default; + Option resultCode = default; + Option?> additionalData = default; + Option fraudResult = default; + Option pspReference = default; + Option reference = default; + Option refusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(utf8JsonReader.GetString()!); + break; + case "orderData": + orderData = new Option(utf8JsonReader.GetString()!); + break; + case "remainingAmount": + remainingAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(CreateOrderResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class CreateOrderResponse.", nameof(amount)); + + if (!expiresAt.IsSet) + throw new ArgumentException("Property is required for class CreateOrderResponse.", nameof(expiresAt)); + + if (!orderData.IsSet) + throw new ArgumentException("Property is required for class CreateOrderResponse.", nameof(orderData)); + + if (!remainingAmount.IsSet) + throw new ArgumentException("Property is required for class CreateOrderResponse.", nameof(remainingAmount)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class CreateOrderResponse.", nameof(resultCode)); + + return new CreateOrderResponse(amount.Value!, expiresAt.Value!, orderData.Value!, remainingAmount.Value!, resultCode.Value!.Value!, additionalData, fraudResult, pspReference, reference, refusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateOrderResponse createOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createOrderResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateOrderResponse createOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, createOrderResponse.Amount, jsonSerializerOptions); + if (createOrderResponse.ExpiresAt != null) + writer.WriteString("expiresAt", createOrderResponse.ExpiresAt); + + if (createOrderResponse.OrderData != null) + writer.WriteString("orderData", createOrderResponse.OrderData); + + writer.WritePropertyName("remainingAmount"); + JsonSerializer.Serialize(writer, createOrderResponse.RemainingAmount, jsonSerializerOptions); + if (createOrderResponse.ResultCode != null) + { + string? resultCodeRawValue = CreateOrderResponse.ResultCodeEnum.ToJsonValue(createOrderResponse.ResultCode); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (createOrderResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, createOrderResponse.AdditionalData, jsonSerializerOptions); + } + if (createOrderResponse._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, createOrderResponse.FraudResult, jsonSerializerOptions); + } + if (createOrderResponse._PspReferenceOption.IsSet) + if (createOrderResponse.PspReference != null) + writer.WriteString("pspReference", createOrderResponse.PspReference); + + if (createOrderResponse._ReferenceOption.IsSet) + if (createOrderResponse.Reference != null) + writer.WriteString("reference", createOrderResponse.Reference); + + if (createOrderResponse._RefusalReasonOption.IsSet) + if (createOrderResponse.RefusalReason != null) + writer.WriteString("refusalReason", createOrderResponse.RefusalReason); + } + } +} diff --git a/Adyen/Checkout/Models/DefaultErrorResponseEntity.cs b/Adyen/Checkout/Models/DefaultErrorResponseEntity.cs new file mode 100644 index 000000000..201320e4c --- /dev/null +++ b/Adyen/Checkout/Models/DefaultErrorResponseEntity.cs @@ -0,0 +1,352 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Standardized error response following RFC-7807 format. + /// + public partial class DefaultErrorResponseEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// Unique business error code. + /// A URI that identifies the specific occurrence of the problem if applicable. + /// Array of fields with validation errors when applicable. + /// The unique reference for the request. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonConstructor] + public DefaultErrorResponseEntity(Option detail = default, Option errorCode = default, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option status = default, Option title = default, Option type = default) + { + _DetailOption = detail; + _ErrorCodeOption = errorCode; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _StatusOption = status; + _TitleOption = title; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefaultErrorResponseEntity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailOption { get; private set; } + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string? Detail { get { return this._DetailOption; } set { this._DetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// Unique business error code. + /// + /// Unique business error code. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Array of fields with validation errors when applicable. + /// + /// Array of fields with validation errors when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// The unique reference for the request. + /// + /// The unique reference for the request. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefaultErrorResponseEntity {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefaultErrorResponseEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefaultErrorResponseEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option status = default; + Option title = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DefaultErrorResponseEntity(detail, errorCode, instance, invalidFields, requestId, status, title, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defaultErrorResponseEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (defaultErrorResponseEntity._DetailOption.IsSet) + if (defaultErrorResponseEntity.Detail != null) + writer.WriteString("detail", defaultErrorResponseEntity.Detail); + + if (defaultErrorResponseEntity._ErrorCodeOption.IsSet) + if (defaultErrorResponseEntity.ErrorCode != null) + writer.WriteString("errorCode", defaultErrorResponseEntity.ErrorCode); + + if (defaultErrorResponseEntity._InstanceOption.IsSet) + if (defaultErrorResponseEntity.Instance != null) + writer.WriteString("instance", defaultErrorResponseEntity.Instance); + + if (defaultErrorResponseEntity._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, defaultErrorResponseEntity.InvalidFields, jsonSerializerOptions); + } + if (defaultErrorResponseEntity._RequestIdOption.IsSet) + if (defaultErrorResponseEntity.RequestId != null) + writer.WriteString("requestId", defaultErrorResponseEntity.RequestId); + + if (defaultErrorResponseEntity._StatusOption.IsSet) + writer.WriteNumber("status", defaultErrorResponseEntity._StatusOption.Value!.Value); + + if (defaultErrorResponseEntity._TitleOption.IsSet) + if (defaultErrorResponseEntity.Title != null) + writer.WriteString("title", defaultErrorResponseEntity.Title); + + if (defaultErrorResponseEntity._TypeOption.IsSet) + if (defaultErrorResponseEntity.Type != null) + writer.WriteString("type", defaultErrorResponseEntity.Type); + } + } +} diff --git a/Adyen/Checkout/Models/DeliveryAddress.cs b/Adyen/Checkout/Models/DeliveryAddress.cs new file mode 100644 index 000000000..e033cddd0 --- /dev/null +++ b/Adyen/Checkout/Models/DeliveryAddress.cs @@ -0,0 +1,348 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DeliveryAddress. + /// + public partial class DeliveryAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// firstName + /// lastName + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public DeliveryAddress(string city, string country, string houseNumberOrName, string postalCode, string street, Option firstName = default, Option lastName = default, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _FirstNameOption = firstName; + _LastNameOption = lastName; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryAddress() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryAddress {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + // StateOrProvince (string) maxLength + if (this.StateOrProvince != null && this.StateOrProvince.Length > 1000) + { + yield return new ValidationResult("Invalid value for StateOrProvince, length must be less than 1000.", new [] { "StateOrProvince" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option firstName = default; + Option lastName = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(street)); + + return new DeliveryAddress(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, firstName, lastName, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (deliveryAddress.City != null) + writer.WriteString("city", deliveryAddress.City); + + if (deliveryAddress.Country != null) + writer.WriteString("country", deliveryAddress.Country); + + if (deliveryAddress.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", deliveryAddress.HouseNumberOrName); + + if (deliveryAddress.PostalCode != null) + writer.WriteString("postalCode", deliveryAddress.PostalCode); + + if (deliveryAddress.Street != null) + writer.WriteString("street", deliveryAddress.Street); + + if (deliveryAddress._FirstNameOption.IsSet) + if (deliveryAddress.FirstName != null) + writer.WriteString("firstName", deliveryAddress.FirstName); + + if (deliveryAddress._LastNameOption.IsSet) + if (deliveryAddress.LastName != null) + writer.WriteString("lastName", deliveryAddress.LastName); + + if (deliveryAddress._StateOrProvinceOption.IsSet) + if (deliveryAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", deliveryAddress.StateOrProvince); + } + } +} diff --git a/Adyen/Checkout/Models/DeliveryMethod.cs b/Adyen/Checkout/Models/DeliveryMethod.cs new file mode 100644 index 000000000..11bd12e86 --- /dev/null +++ b/Adyen/Checkout/Models/DeliveryMethod.cs @@ -0,0 +1,373 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DeliveryMethod. + /// + public partial class DeliveryMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The name of the delivery method as shown to the shopper. + /// The reference of the delivery method. + /// If you display the PayPal lightbox with delivery methods, set to **true** for the delivery method that is selected. Only one delivery method can be selected at a time. + /// The type of the delivery method. + [JsonConstructor] + public DeliveryMethod(Option amount = default, Option description = default, Option reference = default, Option selected = default, Option type = default) + { + _AmountOption = amount; + _DescriptionOption = description; + _ReferenceOption = reference; + _SelectedOption = selected; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryMethod() + { + } + + partial void OnCreated(); + + /// + /// The type of the delivery method. + /// + /// The type of the delivery method. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Shipping - Shipping + /// + public static readonly TypeEnum Shipping = new("Shipping"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "Shipping" => TypeEnum.Shipping, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Shipping) + return "Shipping"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the delivery method. + /// + /// The type of the delivery method. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The name of the delivery method as shown to the shopper. + /// + /// The name of the delivery method as shown to the shopper. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference of the delivery method. + /// + /// The reference of the delivery method. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedOption { get; private set; } + + /// + /// If you display the PayPal lightbox with delivery methods, set to **true** for the delivery method that is selected. Only one delivery method can be selected at a time. + /// + /// If you display the PayPal lightbox with delivery methods, set to **true** for the delivery method that is selected. Only one delivery method can be selected at a time. + [JsonPropertyName("selected")] + public bool? Selected { get { return this._SelectedOption; } set { this._SelectedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryMethod {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Selected: ").Append(Selected).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option description = default; + Option reference = default; + Option selected = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "selected": + selected = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DeliveryMethod.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new DeliveryMethod(amount, description, reference, selected, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryMethod deliveryMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryMethod deliveryMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (deliveryMethod._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, deliveryMethod.Amount, jsonSerializerOptions); + } + if (deliveryMethod._DescriptionOption.IsSet) + if (deliveryMethod.Description != null) + writer.WriteString("description", deliveryMethod.Description); + + if (deliveryMethod._ReferenceOption.IsSet) + if (deliveryMethod.Reference != null) + writer.WriteString("reference", deliveryMethod.Reference); + + if (deliveryMethod._SelectedOption.IsSet) + writer.WriteBoolean("selected", deliveryMethod._SelectedOption.Value!.Value); + + if (deliveryMethod._TypeOption.IsSet && deliveryMethod.Type != null) + { + string? typeRawValue = DeliveryMethod.TypeEnum.ToJsonValue(deliveryMethod._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/DetailsRequestAuthenticationData.cs b/Adyen/Checkout/Models/DetailsRequestAuthenticationData.cs new file mode 100644 index 000000000..fc0f9715e --- /dev/null +++ b/Adyen/Checkout/Models/DetailsRequestAuthenticationData.cs @@ -0,0 +1,176 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DetailsRequestAuthenticationData. + /// + public partial class DetailsRequestAuthenticationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + [JsonConstructor] + public DetailsRequestAuthenticationData(Option authenticationOnly = default) + { + _AuthenticationOnlyOption = authenticationOnly; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DetailsRequestAuthenticationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("authenticationOnly")] + public bool? AuthenticationOnly { get { return this._AuthenticationOnlyOption; } set { this._AuthenticationOnlyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DetailsRequestAuthenticationData {\n"); + sb.Append(" AuthenticationOnly: ").Append(AuthenticationOnly).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DetailsRequestAuthenticationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DetailsRequestAuthenticationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationOnly = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationOnly": + authenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new DetailsRequestAuthenticationData(authenticationOnly); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DetailsRequestAuthenticationData detailsRequestAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, detailsRequestAuthenticationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DetailsRequestAuthenticationData detailsRequestAuthenticationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (detailsRequestAuthenticationData._AuthenticationOnlyOption.IsSet) + writer.WriteBoolean("authenticationOnly", detailsRequestAuthenticationData._AuthenticationOnlyOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/DeviceRenderOptions.cs b/Adyen/Checkout/Models/DeviceRenderOptions.cs new file mode 100644 index 000000000..bca54f0b5 --- /dev/null +++ b/Adyen/Checkout/Models/DeviceRenderOptions.cs @@ -0,0 +1,448 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DeviceRenderOptions. + /// + public partial class DeviceRenderOptions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Supported SDK interface types. Allowed values: * native * html * both (default to SdkInterfaceEnum.Both) + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + [JsonConstructor] + public DeviceRenderOptions(Option sdkInterface = default, Option?> sdkUiType = default) + { + _SdkInterfaceOption = sdkInterface; + _SdkUiTypeOption = sdkUiType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeviceRenderOptions() + { + } + + partial void OnCreated(); + + /// + /// Supported SDK interface types. Allowed values: * native * html * both + /// + /// Supported SDK interface types. Allowed values: * native * html * both + [JsonConverter(typeof(SdkInterfaceEnumJsonConverter))] + public class SdkInterfaceEnum : IEnum + { + /// + /// Returns the value of the SdkInterfaceEnum. + /// + public string? Value { get; set; } + + /// + /// SdkInterfaceEnum.Native - native + /// + public static readonly SdkInterfaceEnum Native = new("native"); + + /// + /// SdkInterfaceEnum.Html - html + /// + public static readonly SdkInterfaceEnum Html = new("html"); + + /// + /// SdkInterfaceEnum.Both - both + /// + public static readonly SdkInterfaceEnum Both = new("both"); + + private SdkInterfaceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SdkInterfaceEnum?(string? value) => value == null ? null : new SdkInterfaceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SdkInterfaceEnum? option) => option?.Value; + + public static bool operator ==(SdkInterfaceEnum? left, SdkInterfaceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SdkInterfaceEnum? left, SdkInterfaceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SdkInterfaceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SdkInterfaceEnum? FromStringOrDefault(string value) + { + return value switch { + "native" => SdkInterfaceEnum.Native, + "html" => SdkInterfaceEnum.Html, + "both" => SdkInterfaceEnum.Both, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SdkInterfaceEnum? value) + { + if (value == null) + return null; + + if (value == SdkInterfaceEnum.Native) + return "native"; + + if (value == SdkInterfaceEnum.Html) + return "html"; + + if (value == SdkInterfaceEnum.Both) + return "both"; + + return null; + } + + /// + /// JsonConverter for writing SdkInterfaceEnum. + /// + public class SdkInterfaceEnumJsonConverter : JsonConverter + { + public override SdkInterfaceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SdkInterfaceEnum.FromStringOrDefault(value) ?? new SdkInterfaceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SdkInterfaceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SdkInterfaceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInterfaceOption { get; private set; } + + /// + /// Supported SDK interface types. Allowed values: * native * html * both + /// + /// Supported SDK interface types. Allowed values: * native * html * both + [JsonPropertyName("sdkInterface")] + public SdkInterfaceEnum? SdkInterface { get { return this._SdkInterfaceOption; } set { this._SdkInterfaceOption = new(value); } } + + /// + /// Defines SdkUiType. + /// + [JsonConverter(typeof(SdkUiTypeEnumJsonConverter))] + public class SdkUiTypeEnum : IEnum + { + /// + /// Returns the value of the SdkUiTypeEnum. + /// + public string? Value { get; set; } + + /// + /// SdkUiTypeEnum.MultiSelect - multiSelect + /// + public static readonly SdkUiTypeEnum MultiSelect = new("multiSelect"); + + /// + /// SdkUiTypeEnum.OtherHtml - otherHtml + /// + public static readonly SdkUiTypeEnum OtherHtml = new("otherHtml"); + + /// + /// SdkUiTypeEnum.OutOfBand - outOfBand + /// + public static readonly SdkUiTypeEnum OutOfBand = new("outOfBand"); + + /// + /// SdkUiTypeEnum.SingleSelect - singleSelect + /// + public static readonly SdkUiTypeEnum SingleSelect = new("singleSelect"); + + /// + /// SdkUiTypeEnum.Text - text + /// + public static readonly SdkUiTypeEnum Text = new("text"); + + private SdkUiTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SdkUiTypeEnum?(string? value) => value == null ? null : new SdkUiTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SdkUiTypeEnum? option) => option?.Value; + + public static bool operator ==(SdkUiTypeEnum? left, SdkUiTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SdkUiTypeEnum? left, SdkUiTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SdkUiTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SdkUiTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "multiSelect" => SdkUiTypeEnum.MultiSelect, + "otherHtml" => SdkUiTypeEnum.OtherHtml, + "outOfBand" => SdkUiTypeEnum.OutOfBand, + "singleSelect" => SdkUiTypeEnum.SingleSelect, + "text" => SdkUiTypeEnum.Text, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SdkUiTypeEnum? value) + { + if (value == null) + return null; + + if (value == SdkUiTypeEnum.MultiSelect) + return "multiSelect"; + + if (value == SdkUiTypeEnum.OtherHtml) + return "otherHtml"; + + if (value == SdkUiTypeEnum.OutOfBand) + return "outOfBand"; + + if (value == SdkUiTypeEnum.SingleSelect) + return "singleSelect"; + + if (value == SdkUiTypeEnum.Text) + return "text"; + + return null; + } + + /// + /// JsonConverter for writing SdkUiTypeEnum. + /// + public class SdkUiTypeEnumJsonConverter : JsonConverter + { + public override SdkUiTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SdkUiTypeEnum.FromStringOrDefault(value) ?? new SdkUiTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SdkUiTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SdkUiTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SdkUiTypeOption { get; private set; } + + /// + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + /// + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + [JsonPropertyName("sdkUiType")] + public List? SdkUiType { get { return this._SdkUiTypeOption; } set { this._SdkUiTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeviceRenderOptions {\n"); + sb.Append(" SdkInterface: ").Append(SdkInterface).Append("\n"); + sb.Append(" SdkUiType: ").Append(SdkUiType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeviceRenderOptionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeviceRenderOptions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkInterface = default; + Option?> sdkUiType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkInterface": + string? sdkInterfaceRawValue = utf8JsonReader.GetString(); + sdkInterface = new Option(DeviceRenderOptions.SdkInterfaceEnum.FromStringOrDefault(sdkInterfaceRawValue)); + break; + case "sdkUiType": + sdkUiType = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new DeviceRenderOptions(sdkInterface, sdkUiType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeviceRenderOptions deviceRenderOptions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deviceRenderOptions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeviceRenderOptions deviceRenderOptions, JsonSerializerOptions jsonSerializerOptions) + { + + if (deviceRenderOptions._SdkInterfaceOption.IsSet && deviceRenderOptions.SdkInterface != null) + { + string? sdkInterfaceRawValue = DeviceRenderOptions.SdkInterfaceEnum.ToJsonValue(deviceRenderOptions._SdkInterfaceOption.Value!.Value); + writer.WriteString("sdkInterface", sdkInterfaceRawValue); + } + + if (deviceRenderOptions._SdkUiTypeOption.IsSet) + { + writer.WritePropertyName("sdkUiType"); + JsonSerializer.Serialize(writer, deviceRenderOptions.SdkUiType, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/DokuDetails.cs b/Adyen/Checkout/Models/DokuDetails.cs new file mode 100644 index 000000000..12cb32301 --- /dev/null +++ b/Adyen/Checkout/Models/DokuDetails.cs @@ -0,0 +1,444 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DokuDetails. + /// + public partial class DokuDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The shopper's first name. + /// The shopper's last name. + /// The shopper's email. + /// **doku** + /// The checkout attempt identifier. + [JsonConstructor] + public DokuDetails(string firstName, string lastName, string shopperEmail, TypeEnum type, Option checkoutAttemptId = default) + { + FirstName = firstName; + LastName = lastName; + ShopperEmail = shopperEmail; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DokuDetails() + { + } + + partial void OnCreated(); + + /// + /// **doku** + /// + /// **doku** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DokuMandiriVa - doku_mandiri_va + /// + public static readonly TypeEnum DokuMandiriVa = new("doku_mandiri_va"); + + /// + /// TypeEnum.DokuCimbVa - doku_cimb_va + /// + public static readonly TypeEnum DokuCimbVa = new("doku_cimb_va"); + + /// + /// TypeEnum.DokuDanamonVa - doku_danamon_va + /// + public static readonly TypeEnum DokuDanamonVa = new("doku_danamon_va"); + + /// + /// TypeEnum.DokuBniVa - doku_bni_va + /// + public static readonly TypeEnum DokuBniVa = new("doku_bni_va"); + + /// + /// TypeEnum.DokuPermataLiteAtm - doku_permata_lite_atm + /// + public static readonly TypeEnum DokuPermataLiteAtm = new("doku_permata_lite_atm"); + + /// + /// TypeEnum.DokuBriVa - doku_bri_va + /// + public static readonly TypeEnum DokuBriVa = new("doku_bri_va"); + + /// + /// TypeEnum.DokuBcaVa - doku_bca_va + /// + public static readonly TypeEnum DokuBcaVa = new("doku_bca_va"); + + /// + /// TypeEnum.DokuAlfamart - doku_alfamart + /// + public static readonly TypeEnum DokuAlfamart = new("doku_alfamart"); + + /// + /// TypeEnum.DokuIndomaret - doku_indomaret + /// + public static readonly TypeEnum DokuIndomaret = new("doku_indomaret"); + + /// + /// TypeEnum.DokuWallet - doku_wallet + /// + public static readonly TypeEnum DokuWallet = new("doku_wallet"); + + /// + /// TypeEnum.DokuOvo - doku_ovo + /// + public static readonly TypeEnum DokuOvo = new("doku_ovo"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "doku_mandiri_va" => TypeEnum.DokuMandiriVa, + "doku_cimb_va" => TypeEnum.DokuCimbVa, + "doku_danamon_va" => TypeEnum.DokuDanamonVa, + "doku_bni_va" => TypeEnum.DokuBniVa, + "doku_permata_lite_atm" => TypeEnum.DokuPermataLiteAtm, + "doku_bri_va" => TypeEnum.DokuBriVa, + "doku_bca_va" => TypeEnum.DokuBcaVa, + "doku_alfamart" => TypeEnum.DokuAlfamart, + "doku_indomaret" => TypeEnum.DokuIndomaret, + "doku_wallet" => TypeEnum.DokuWallet, + "doku_ovo" => TypeEnum.DokuOvo, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DokuMandiriVa) + return "doku_mandiri_va"; + + if (value == TypeEnum.DokuCimbVa) + return "doku_cimb_va"; + + if (value == TypeEnum.DokuDanamonVa) + return "doku_danamon_va"; + + if (value == TypeEnum.DokuBniVa) + return "doku_bni_va"; + + if (value == TypeEnum.DokuPermataLiteAtm) + return "doku_permata_lite_atm"; + + if (value == TypeEnum.DokuBriVa) + return "doku_bri_va"; + + if (value == TypeEnum.DokuBcaVa) + return "doku_bca_va"; + + if (value == TypeEnum.DokuAlfamart) + return "doku_alfamart"; + + if (value == TypeEnum.DokuIndomaret) + return "doku_indomaret"; + + if (value == TypeEnum.DokuWallet) + return "doku_wallet"; + + if (value == TypeEnum.DokuOvo) + return "doku_ovo"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **doku** + /// + /// **doku** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The shopper's first name. + /// + /// The shopper's first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The shopper's last name. + /// + /// The shopper's last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// The shopper's email. + /// + /// The shopper's email. + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DokuDetails {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DokuDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DokuDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + Option shopperEmail = default; + Option type = default; + Option checkoutAttemptId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DokuDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class DokuDetails.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class DokuDetails.", nameof(lastName)); + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class DokuDetails.", nameof(shopperEmail)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DokuDetails.", nameof(type)); + + return new DokuDetails(firstName.Value!, lastName.Value!, shopperEmail.Value!, type.Value!.Value!, checkoutAttemptId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DokuDetails dokuDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dokuDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DokuDetails dokuDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (dokuDetails.FirstName != null) + writer.WriteString("firstName", dokuDetails.FirstName); + + if (dokuDetails.LastName != null) + writer.WriteString("lastName", dokuDetails.LastName); + + if (dokuDetails.ShopperEmail != null) + writer.WriteString("shopperEmail", dokuDetails.ShopperEmail); + + if (dokuDetails.Type != null) + { + string? typeRawValue = DokuDetails.TypeEnum.ToJsonValue(dokuDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (dokuDetails._CheckoutAttemptIdOption.IsSet) + if (dokuDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", dokuDetails.CheckoutAttemptId); + } + } +} diff --git a/Adyen/Checkout/Models/Donation.cs b/Adyen/Checkout/Models/Donation.cs new file mode 100644 index 000000000..c493fa60f --- /dev/null +++ b/Adyen/Checkout/Models/Donation.cs @@ -0,0 +1,262 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Donation. + /// + public partial class Donation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donations amounts that the shopper can select from. + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donation amounts that the shopper can select from. + /// The maximum amount a transaction can be rounded up to make a donation. This field is only present when `donationType` is **roundup**. + /// The fixed donation amounts in [minor units](https://docs.adyen.com/development-resources/currency-codes//#minor-units). This field is only present when `donationType` is **fixedAmounts**. + [JsonConstructor] + public Donation(string currency, string donationType, string type, Option maxRoundupAmount = default, Option?> values = default) + { + Currency = currency; + DonationType = donationType; + Type = type; + _MaxRoundupAmountOption = maxRoundupAmount; + _ValuesOption = values; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Donation() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donations amounts that the shopper can select from. + /// + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donations amounts that the shopper can select from. + [JsonPropertyName("donationType")] + public string DonationType { get; set; } + + /// + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donation amounts that the shopper can select from. + /// + /// The [type of donation](https://docs.adyen.com/online-payments/donations/#donation-types). Possible values: * **roundup**: a donation where the original transaction amount is rounded up as a donation. * **fixedAmounts**: a donation where you show fixed donation amounts that the shopper can select from. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxRoundupAmountOption { get; private set; } + + /// + /// The maximum amount a transaction can be rounded up to make a donation. This field is only present when `donationType` is **roundup**. + /// + /// The maximum amount a transaction can be rounded up to make a donation. This field is only present when `donationType` is **roundup**. + [JsonPropertyName("maxRoundupAmount")] + public long? MaxRoundupAmount { get { return this._MaxRoundupAmountOption; } set { this._MaxRoundupAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValuesOption { get; private set; } + + /// + /// The fixed donation amounts in [minor units](https://docs.adyen.com/development-resources/currency-codes//#minor-units). This field is only present when `donationType` is **fixedAmounts**. + /// + /// The fixed donation amounts in [minor units](https://docs.adyen.com/development-resources/currency-codes//#minor-units). This field is only present when `donationType` is **fixedAmounts**. + [JsonPropertyName("values")] + public List? Values { get { return this._ValuesOption; } set { this._ValuesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Donation {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" DonationType: ").Append(DonationType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" MaxRoundupAmount: ").Append(MaxRoundupAmount).Append("\n"); + sb.Append(" Values: ").Append(Values).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Donation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option donationType = default; + Option type = default; + Option maxRoundupAmount = default; + Option?> values = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "donationType": + donationType = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "maxRoundupAmount": + maxRoundupAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "values": + values = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Donation.", nameof(currency)); + + if (!donationType.IsSet) + throw new ArgumentException("Property is required for class Donation.", nameof(donationType)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Donation.", nameof(type)); + + return new Donation(currency.Value!, donationType.Value!, type.Value!, maxRoundupAmount, values); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Donation donation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Donation donation, JsonSerializerOptions jsonSerializerOptions) + { + + if (donation.Currency != null) + writer.WriteString("currency", donation.Currency); + + if (donation.DonationType != null) + writer.WriteString("donationType", donation.DonationType); + + if (donation.Type != null) + writer.WriteString("type", donation.Type); + + if (donation._MaxRoundupAmountOption.IsSet) + writer.WriteNumber("maxRoundupAmount", donation._MaxRoundupAmountOption.Value!.Value); + + if (donation._ValuesOption.IsSet) + { + writer.WritePropertyName("values"); + JsonSerializer.Serialize(writer, donation.Values, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/DonationCampaign.cs b/Adyen/Checkout/Models/DonationCampaign.cs new file mode 100644 index 000000000..1831554da --- /dev/null +++ b/Adyen/Checkout/Models/DonationCampaign.cs @@ -0,0 +1,427 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DonationCampaign. + /// + public partial class DonationCampaign : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amounts + /// The URL for the banner of the nonprofit or campaign. + /// The name of the donation campaign.. + /// The cause of the nonprofit. + /// donation + /// The unique campaign ID of the donation campaign. + /// The URL for the logo of the nonprofit. + /// The description of the nonprofit. + /// The name of the nonprofit organization that receives the donation. + /// The website URL of the nonprofit. + /// The URL of the terms and conditions page of the nonprofit and the campaign. + [JsonConstructor] + public DonationCampaign(Option amounts = default, Option bannerUrl = default, Option campaignName = default, Option causeName = default, Option donation = default, Option id = default, Option logoUrl = default, Option nonprofitDescription = default, Option nonprofitName = default, Option nonprofitUrl = default, Option termsAndConditionsUrl = default) + { + _AmountsOption = amounts; + _BannerUrlOption = bannerUrl; + _CampaignNameOption = campaignName; + _CauseNameOption = causeName; + _DonationOption = donation; + _IdOption = id; + _LogoUrlOption = logoUrl; + _NonprofitDescriptionOption = nonprofitDescription; + _NonprofitNameOption = nonprofitName; + _NonprofitUrlOption = nonprofitUrl; + _TermsAndConditionsUrlOption = termsAndConditionsUrl; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationCampaign() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amounts")] + public Amounts? Amounts { get { return this._AmountsOption; } set { this._AmountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BannerUrlOption { get; private set; } + + /// + /// The URL for the banner of the nonprofit or campaign. + /// + /// The URL for the banner of the nonprofit or campaign. + [JsonPropertyName("bannerUrl")] + public string? BannerUrl { get { return this._BannerUrlOption; } set { this._BannerUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CampaignNameOption { get; private set; } + + /// + /// The name of the donation campaign.. + /// + /// The name of the donation campaign.. + [JsonPropertyName("campaignName")] + public string? CampaignName { get { return this._CampaignNameOption; } set { this._CampaignNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CauseNameOption { get; private set; } + + /// + /// The cause of the nonprofit. + /// + /// The cause of the nonprofit. + [JsonPropertyName("causeName")] + public string? CauseName { get { return this._CauseNameOption; } set { this._CauseNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("donation")] + public Donation? Donation { get { return this._DonationOption; } set { this._DonationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique campaign ID of the donation campaign. + /// + /// The unique campaign ID of the donation campaign. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LogoUrlOption { get; private set; } + + /// + /// The URL for the logo of the nonprofit. + /// + /// The URL for the logo of the nonprofit. + [JsonPropertyName("logoUrl")] + public string? LogoUrl { get { return this._LogoUrlOption; } set { this._LogoUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NonprofitDescriptionOption { get; private set; } + + /// + /// The description of the nonprofit. + /// + /// The description of the nonprofit. + [JsonPropertyName("nonprofitDescription")] + public string? NonprofitDescription { get { return this._NonprofitDescriptionOption; } set { this._NonprofitDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NonprofitNameOption { get; private set; } + + /// + /// The name of the nonprofit organization that receives the donation. + /// + /// The name of the nonprofit organization that receives the donation. + [JsonPropertyName("nonprofitName")] + public string? NonprofitName { get { return this._NonprofitNameOption; } set { this._NonprofitNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NonprofitUrlOption { get; private set; } + + /// + /// The website URL of the nonprofit. + /// + /// The website URL of the nonprofit. + [JsonPropertyName("nonprofitUrl")] + public string? NonprofitUrl { get { return this._NonprofitUrlOption; } set { this._NonprofitUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsAndConditionsUrlOption { get; private set; } + + /// + /// The URL of the terms and conditions page of the nonprofit and the campaign. + /// + /// The URL of the terms and conditions page of the nonprofit and the campaign. + [JsonPropertyName("termsAndConditionsUrl")] + public string? TermsAndConditionsUrl { get { return this._TermsAndConditionsUrlOption; } set { this._TermsAndConditionsUrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationCampaign {\n"); + sb.Append(" Amounts: ").Append(Amounts).Append("\n"); + sb.Append(" BannerUrl: ").Append(BannerUrl).Append("\n"); + sb.Append(" CampaignName: ").Append(CampaignName).Append("\n"); + sb.Append(" CauseName: ").Append(CauseName).Append("\n"); + sb.Append(" Donation: ").Append(Donation).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LogoUrl: ").Append(LogoUrl).Append("\n"); + sb.Append(" NonprofitDescription: ").Append(NonprofitDescription).Append("\n"); + sb.Append(" NonprofitName: ").Append(NonprofitName).Append("\n"); + sb.Append(" NonprofitUrl: ").Append(NonprofitUrl).Append("\n"); + sb.Append(" TermsAndConditionsUrl: ").Append(TermsAndConditionsUrl).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationCampaignJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationCampaign Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amounts = default; + Option bannerUrl = default; + Option campaignName = default; + Option causeName = default; + Option donation = default; + Option id = default; + Option logoUrl = default; + Option nonprofitDescription = default; + Option nonprofitName = default; + Option nonprofitUrl = default; + Option termsAndConditionsUrl = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amounts": + amounts = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bannerUrl": + bannerUrl = new Option(utf8JsonReader.GetString()!); + break; + case "campaignName": + campaignName = new Option(utf8JsonReader.GetString()!); + break; + case "causeName": + causeName = new Option(utf8JsonReader.GetString()!); + break; + case "donation": + donation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "logoUrl": + logoUrl = new Option(utf8JsonReader.GetString()!); + break; + case "nonprofitDescription": + nonprofitDescription = new Option(utf8JsonReader.GetString()!); + break; + case "nonprofitName": + nonprofitName = new Option(utf8JsonReader.GetString()!); + break; + case "nonprofitUrl": + nonprofitUrl = new Option(utf8JsonReader.GetString()!); + break; + case "termsAndConditionsUrl": + termsAndConditionsUrl = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DonationCampaign(amounts, bannerUrl, campaignName, causeName, donation, id, logoUrl, nonprofitDescription, nonprofitName, nonprofitUrl, termsAndConditionsUrl); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationCampaign donationCampaign, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationCampaign, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationCampaign donationCampaign, JsonSerializerOptions jsonSerializerOptions) + { + + if (donationCampaign._AmountsOption.IsSet) + { + writer.WritePropertyName("amounts"); + JsonSerializer.Serialize(writer, donationCampaign.Amounts, jsonSerializerOptions); + } + if (donationCampaign._BannerUrlOption.IsSet) + if (donationCampaign.BannerUrl != null) + writer.WriteString("bannerUrl", donationCampaign.BannerUrl); + + if (donationCampaign._CampaignNameOption.IsSet) + if (donationCampaign.CampaignName != null) + writer.WriteString("campaignName", donationCampaign.CampaignName); + + if (donationCampaign._CauseNameOption.IsSet) + if (donationCampaign.CauseName != null) + writer.WriteString("causeName", donationCampaign.CauseName); + + if (donationCampaign._DonationOption.IsSet) + { + writer.WritePropertyName("donation"); + JsonSerializer.Serialize(writer, donationCampaign.Donation, jsonSerializerOptions); + } + if (donationCampaign._IdOption.IsSet) + if (donationCampaign.Id != null) + writer.WriteString("id", donationCampaign.Id); + + if (donationCampaign._LogoUrlOption.IsSet) + if (donationCampaign.LogoUrl != null) + writer.WriteString("logoUrl", donationCampaign.LogoUrl); + + if (donationCampaign._NonprofitDescriptionOption.IsSet) + if (donationCampaign.NonprofitDescription != null) + writer.WriteString("nonprofitDescription", donationCampaign.NonprofitDescription); + + if (donationCampaign._NonprofitNameOption.IsSet) + if (donationCampaign.NonprofitName != null) + writer.WriteString("nonprofitName", donationCampaign.NonprofitName); + + if (donationCampaign._NonprofitUrlOption.IsSet) + if (donationCampaign.NonprofitUrl != null) + writer.WriteString("nonprofitUrl", donationCampaign.NonprofitUrl); + + if (donationCampaign._TermsAndConditionsUrlOption.IsSet) + if (donationCampaign.TermsAndConditionsUrl != null) + writer.WriteString("termsAndConditionsUrl", donationCampaign.TermsAndConditionsUrl); + } + } +} diff --git a/Adyen/Checkout/Models/DonationCampaignsRequest.cs b/Adyen/Checkout/Models/DonationCampaignsRequest.cs new file mode 100644 index 000000000..e7a473667 --- /dev/null +++ b/Adyen/Checkout/Models/DonationCampaignsRequest.cs @@ -0,0 +1,216 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DonationCampaignsRequest. + /// + public partial class DonationCampaignsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// Your merchant account identifier. + /// Locale on the shopper interaction device. + [JsonConstructor] + public DonationCampaignsRequest(string currency, string merchantAccount, Option locale = default) + { + Currency = currency; + MerchantAccount = merchantAccount; + _LocaleOption = locale; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationCampaignsRequest() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes/). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// Your merchant account identifier. + /// + /// Your merchant account identifier. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LocaleOption { get; private set; } + + /// + /// Locale on the shopper interaction device. + /// + /// Locale on the shopper interaction device. + [JsonPropertyName("locale")] + public string? Locale { get { return this._LocaleOption; } set { this._LocaleOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationCampaignsRequest {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Locale: ").Append(Locale).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationCampaignsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationCampaignsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option merchantAccount = default; + Option locale = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "locale": + locale = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class DonationCampaignsRequest.", nameof(currency)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class DonationCampaignsRequest.", nameof(merchantAccount)); + + return new DonationCampaignsRequest(currency.Value!, merchantAccount.Value!, locale); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationCampaignsRequest donationCampaignsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationCampaignsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationCampaignsRequest donationCampaignsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (donationCampaignsRequest.Currency != null) + writer.WriteString("currency", donationCampaignsRequest.Currency); + + if (donationCampaignsRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", donationCampaignsRequest.MerchantAccount); + + if (donationCampaignsRequest._LocaleOption.IsSet) + if (donationCampaignsRequest.Locale != null) + writer.WriteString("locale", donationCampaignsRequest.Locale); + } + } +} diff --git a/Adyen/Checkout/Models/DonationCampaignsResponse.cs b/Adyen/Checkout/Models/DonationCampaignsResponse.cs new file mode 100644 index 000000000..ec89496d3 --- /dev/null +++ b/Adyen/Checkout/Models/DonationCampaignsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DonationCampaignsResponse. + /// + public partial class DonationCampaignsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of active donation campaigns for your merchant account. + [JsonConstructor] + public DonationCampaignsResponse(Option?> donationCampaigns = default) + { + _DonationCampaignsOption = donationCampaigns; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationCampaignsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DonationCampaignsOption { get; private set; } + + /// + /// List of active donation campaigns for your merchant account. + /// + /// List of active donation campaigns for your merchant account. + [JsonPropertyName("donationCampaigns")] + public List? DonationCampaigns { get { return this._DonationCampaignsOption; } set { this._DonationCampaignsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationCampaignsResponse {\n"); + sb.Append(" DonationCampaigns: ").Append(DonationCampaigns).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationCampaignsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationCampaignsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> donationCampaigns = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "donationCampaigns": + donationCampaigns = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new DonationCampaignsResponse(donationCampaigns); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationCampaignsResponse donationCampaignsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationCampaignsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationCampaignsResponse donationCampaignsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (donationCampaignsResponse._DonationCampaignsOption.IsSet) + { + writer.WritePropertyName("donationCampaigns"); + JsonSerializer.Serialize(writer, donationCampaignsResponse.DonationCampaigns, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/DonationPaymentMethod.cs b/Adyen/Checkout/Models/DonationPaymentMethod.cs new file mode 100644 index 000000000..79e92c971 --- /dev/null +++ b/Adyen/Checkout/Models/DonationPaymentMethod.cs @@ -0,0 +1,279 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// The type and required details of a payment method to use. When `donationToken` is provided, the payment method is derived from the token and this field becomes optional. If you are [PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide), and make donations using raw card details, you must explicitly provide the payment method details.. + /// + public partial class DonationPaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public DonationPaymentMethod(ApplePayDonations applePayDonations) + { + ApplePayDonations = applePayDonations; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DonationPaymentMethod(CardDonations cardDonations) + { + CardDonations = cardDonations; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DonationPaymentMethod(GooglePayDonations googlePayDonations) + { + GooglePayDonations = googlePayDonations; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DonationPaymentMethod(IdealDonations idealDonations) + { + IdealDonations = idealDonations; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DonationPaymentMethod(PayWithGoogleDonations payWithGoogleDonations) + { + PayWithGoogleDonations = payWithGoogleDonations; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public ApplePayDonations? ApplePayDonations { get; set; } + + /// + /// .. + /// + public CardDonations? CardDonations { get; set; } + + /// + /// .. + /// + public GooglePayDonations? GooglePayDonations { get; set; } + + /// + /// .. + /// + public IdealDonations? IdealDonations { get; set; } + + /// + /// .. + /// + public PayWithGoogleDonations? PayWithGoogleDonations { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationPaymentMethod {\n"); + if (this.ApplePayDonations != null) + sb.Append(ApplePayDonations.ToString().Replace("\n", "\n ")); + if (this.CardDonations != null) + sb.Append(CardDonations.ToString().Replace("\n", "\n ")); + if (this.GooglePayDonations != null) + sb.Append(GooglePayDonations.ToString().Replace("\n", "\n ")); + if (this.IdealDonations != null) + sb.Append(IdealDonations.ToString().Replace("\n", "\n ")); + if (this.PayWithGoogleDonations != null) + sb.Append(PayWithGoogleDonations.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ApplePayDonations? applePayDonations = default; + CardDonations? cardDonations = default; + GooglePayDonations? googlePayDonations = default; + IdealDonations? idealDonations = default; + PayWithGoogleDonations? payWithGoogleDonations = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderApplePayDonations = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderApplePayDonations, jsonSerializerOptions, out applePayDonations); + + Utf8JsonReader utf8JsonReaderCardDonations = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCardDonations, jsonSerializerOptions, out cardDonations); + + Utf8JsonReader utf8JsonReaderGooglePayDonations = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderGooglePayDonations, jsonSerializerOptions, out googlePayDonations); + + Utf8JsonReader utf8JsonReaderIdealDonations = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIdealDonations, jsonSerializerOptions, out idealDonations); + + Utf8JsonReader utf8JsonReaderPayWithGoogleDonations = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPayWithGoogleDonations, jsonSerializerOptions, out payWithGoogleDonations); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (applePayDonations?.Type != null) + return new DonationPaymentMethod(applePayDonations); + + if (cardDonations?.Type != null) + return new DonationPaymentMethod(cardDonations); + + if (googlePayDonations?.Type != null) + return new DonationPaymentMethod(googlePayDonations); + + if (idealDonations?.Type != null) + return new DonationPaymentMethod(idealDonations); + + if (payWithGoogleDonations?.Type != null) + return new DonationPaymentMethod(payWithGoogleDonations); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationPaymentMethod donationPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + if (donationPaymentMethod.ApplePayDonations != null) + JsonSerializer.Serialize(writer, donationPaymentMethod.ApplePayDonations, jsonSerializerOptions); + if (donationPaymentMethod.CardDonations != null) + JsonSerializer.Serialize(writer, donationPaymentMethod.CardDonations, jsonSerializerOptions); + if (donationPaymentMethod.GooglePayDonations != null) + JsonSerializer.Serialize(writer, donationPaymentMethod.GooglePayDonations, jsonSerializerOptions); + if (donationPaymentMethod.IdealDonations != null) + JsonSerializer.Serialize(writer, donationPaymentMethod.IdealDonations, jsonSerializerOptions); + if (donationPaymentMethod.PayWithGoogleDonations != null) + JsonSerializer.Serialize(writer, donationPaymentMethod.PayWithGoogleDonations, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, donationPaymentMethod, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationPaymentMethod donationPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Checkout/Models/DonationPaymentRequest.cs b/Adyen/Checkout/Models/DonationPaymentRequest.cs new file mode 100644 index 000000000..dc80e7b87 --- /dev/null +++ b/Adyen/Checkout/Models/DonationPaymentRequest.cs @@ -0,0 +1,1587 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DonationPaymentRequest. + /// + public partial class DonationPaymentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// accountInfo + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// applicationInfo + /// authenticationData + /// billingAddress + /// browserInfo + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// deliveryAddress + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// Donation account to which the transaction is credited. + /// The donation campaign ID received in the `/donationCampaigns` call. + /// PSP reference of the transaction from which the donation token is generated. Required when `donationToken` is provided. + /// Donation token received in the `/payments` call. + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// mpiData + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + /// paymentMethod + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// The shopper's social security number. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + [JsonConstructor] + public DonationPaymentRequest(Amount amount, string merchantAccount, string reference, string returnUrl, Option accountInfo = default, Option?> additionalData = default, Option applicationInfo = default, Option authenticationData = default, Option billingAddress = default, Option browserInfo = default, Option channel = default, Option checkoutAttemptId = default, Option conversionId = default, Option countryCode = default, Option dateOfBirth = default, Option deliverAt = default, Option deliveryAddress = default, Option deviceFingerprint = default, Option donationAccount = default, Option donationCampaignId = default, Option donationOriginalPspReference = default, Option donationToken = default, Option?> lineItems = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option mpiData = default, Option origin = default, Option paymentMethod = default, Option recurringProcessingModel = default, Option redirectFromIssuerMethod = default, Option redirectToIssuerMethod = default, Option sessionValidity = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option socialSecurityNumber = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + ReturnUrl = returnUrl; + _AccountInfoOption = accountInfo; + _AdditionalDataOption = additionalData; + _ApplicationInfoOption = applicationInfo; + _AuthenticationDataOption = authenticationData; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _ChannelOption = channel; + _CheckoutAttemptIdOption = checkoutAttemptId; + _ConversionIdOption = conversionId; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _DeviceFingerprintOption = deviceFingerprint; + _DonationAccountOption = donationAccount; + _DonationCampaignIdOption = donationCampaignId; + _DonationOriginalPspReferenceOption = donationOriginalPspReference; + _DonationTokenOption = donationToken; + _LineItemsOption = lineItems; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _MpiDataOption = mpiData; + _OriginOption = origin; + _PaymentMethodOption = paymentMethod; + _RecurringProcessingModelOption = recurringProcessingModel; + _RedirectFromIssuerMethodOption = redirectFromIssuerMethod; + _RedirectToIssuerMethodOption = redirectToIssuerMethod; + _SessionValidityOption = sessionValidity; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _SocialSecurityNumberOption = socialSecurityNumber; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationPaymentRequest() + { + } + + partial void OnCreated(); + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + [JsonConverter(typeof(ChannelEnumJsonConverter))] + public class ChannelEnum : IEnum + { + /// + /// Returns the value of the ChannelEnum. + /// + public string? Value { get; set; } + + /// + /// ChannelEnum.IOS - iOS + /// + public static readonly ChannelEnum IOS = new("iOS"); + + /// + /// ChannelEnum.Android - Android + /// + public static readonly ChannelEnum Android = new("Android"); + + /// + /// ChannelEnum.Web - Web + /// + public static readonly ChannelEnum Web = new("Web"); + + private ChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChannelEnum?(string? value) => value == null ? null : new ChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChannelEnum? option) => option?.Value; + + public static bool operator ==(ChannelEnum? left, ChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChannelEnum? left, ChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "iOS" => ChannelEnum.IOS, + "Android" => ChannelEnum.Android, + "Web" => ChannelEnum.Web, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChannelEnum? value) + { + if (value == null) + return null; + + if (value == ChannelEnum.IOS) + return "iOS"; + + if (value == ChannelEnum.Android) + return "Android"; + + if (value == ChannelEnum.Web) + return "Web"; + + return null; + } + + /// + /// JsonConverter for writing ChannelEnum. + /// + public class ChannelEnumJsonConverter : JsonConverter + { + public override ChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChannelEnum.FromStringOrDefault(value) ?? new ChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + [JsonPropertyName("channel")] + public ChannelEnum? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("returnUrl")] + public string ReturnUrl { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationData")] + public AuthenticationData? AuthenticationData { get { return this._AuthenticationDataOption; } set { this._AuthenticationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public BillingAddress? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConversionIdOption { get; private set; } + + /// + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + [JsonPropertyName("conversionId")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `checkoutAttemptId` instead")] + public string? ConversionId { get { return this._ConversionIdOption; } set { this._ConversionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateTimeOffset? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public DeliveryAddress? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationAccountOption { get; private set; } + + /// + /// Donation account to which the transaction is credited. + /// + /// Donation account to which the transaction is credited. + [JsonPropertyName("donationAccount")] + public string? DonationAccount { get { return this._DonationAccountOption; } set { this._DonationAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationCampaignIdOption { get; private set; } + + /// + /// The donation campaign ID received in the `/donationCampaigns` call. + /// + /// The donation campaign ID received in the `/donationCampaigns` call. + [JsonPropertyName("donationCampaignId")] + public string? DonationCampaignId { get { return this._DonationCampaignIdOption; } set { this._DonationCampaignIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationOriginalPspReferenceOption { get; private set; } + + /// + /// PSP reference of the transaction from which the donation token is generated. Required when `donationToken` is provided. + /// + /// PSP reference of the transaction from which the donation token is generated. Required when `donationToken` is provided. + [JsonPropertyName("donationOriginalPspReference")] + public string? DonationOriginalPspReference { get { return this._DonationOriginalPspReferenceOption; } set { this._DonationOriginalPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationTokenOption { get; private set; } + + /// + /// Donation token received in the `/payments` call. + /// + /// Donation token received in the `/payments` call. + [JsonPropertyName("donationToken")] + public string? DonationToken { get { return this._DonationTokenOption; } set { this._DonationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginOption { get; private set; } + + /// + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + /// + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + [JsonPropertyName("origin")] + public string? Origin { get { return this._OriginOption; } set { this._OriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public DonationPaymentMethod? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectFromIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + [JsonPropertyName("redirectFromIssuerMethod")] + public string? RedirectFromIssuerMethod { get { return this._RedirectFromIssuerMethodOption; } set { this._RedirectFromIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectToIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + [JsonPropertyName("redirectToIssuerMethod")] + public string? RedirectToIssuerMethod { get { return this._RedirectToIssuerMethodOption; } set { this._RedirectToIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionValidityOption { get; private set; } + + /// + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + /// + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + [JsonPropertyName("sessionValidity")] + public string? SessionValidity { get { return this._SessionValidityOption; } set { this._SessionValidityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public ShopperName? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestFields? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationPaymentRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" AuthenticationData: ").Append(AuthenticationData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" ConversionId: ").Append(ConversionId).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" DonationAccount: ").Append(DonationAccount).Append("\n"); + sb.Append(" DonationCampaignId: ").Append(DonationCampaignId).Append("\n"); + sb.Append(" DonationOriginalPspReference: ").Append(DonationOriginalPspReference).Append("\n"); + sb.Append(" DonationToken: ").Append(DonationToken).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" Origin: ").Append(Origin).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RedirectFromIssuerMethod: ").Append(RedirectFromIssuerMethod).Append("\n"); + sb.Append(" RedirectToIssuerMethod: ").Append(RedirectToIssuerMethod).Append("\n"); + sb.Append(" SessionValidity: ").Append(SessionValidity).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // CountryCode (string) maxLength + if (this.CountryCode != null && this.CountryCode.Length > 100) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be less than 100.", new [] { "CountryCode" }); + } + + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Origin (string) maxLength + if (this.Origin != null && this.Origin.Length > 80) + { + yield return new ValidationResult("Invalid value for Origin, length must be less than 80.", new [] { "Origin" }); + } + + // ShopperIP (string) maxLength + if (this.ShopperIP != null && this.ShopperIP.Length > 1000) + { + yield return new ValidationResult("Invalid value for ShopperIP, length must be less than 1000.", new [] { "ShopperIP" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationPaymentRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationPaymentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option returnUrl = default; + Option accountInfo = default; + Option?> additionalData = default; + Option applicationInfo = default; + Option authenticationData = default; + Option billingAddress = default; + Option browserInfo = default; + Option channel = default; + Option checkoutAttemptId = default; + Option conversionId = default; + Option countryCode = default; + Option dateOfBirth = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option deviceFingerprint = default; + Option donationAccount = default; + Option donationCampaignId = default; + Option donationOriginalPspReference = default; + Option donationToken = default; + Option?> lineItems = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option mpiData = default; + Option origin = default; + Option paymentMethod = default; + Option recurringProcessingModel = default; + Option redirectFromIssuerMethod = default; + Option redirectToIssuerMethod = default; + Option sessionValidity = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option socialSecurityNumber = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationData": + authenticationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "channel": + string? channelRawValue = utf8JsonReader.GetString(); + channel = new Option(DonationPaymentRequest.ChannelEnum.FromStringOrDefault(channelRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "conversionId": + conversionId = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "donationAccount": + donationAccount = new Option(utf8JsonReader.GetString()!); + break; + case "donationCampaignId": + donationCampaignId = new Option(utf8JsonReader.GetString()!); + break; + case "donationOriginalPspReference": + donationOriginalPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "donationToken": + donationToken = new Option(utf8JsonReader.GetString()!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "origin": + origin = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(DonationPaymentRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "redirectFromIssuerMethod": + redirectFromIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "redirectToIssuerMethod": + redirectToIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "sessionValidity": + sessionValidity = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(DonationPaymentRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class DonationPaymentRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class DonationPaymentRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class DonationPaymentRequest.", nameof(reference)); + + if (!returnUrl.IsSet) + throw new ArgumentException("Property is required for class DonationPaymentRequest.", nameof(returnUrl)); + + return new DonationPaymentRequest(amount.Value!, merchantAccount.Value!, reference.Value!, returnUrl.Value!, accountInfo, additionalData, applicationInfo, authenticationData, billingAddress, browserInfo, channel, checkoutAttemptId, conversionId, countryCode, dateOfBirth, deliverAt, deliveryAddress, deviceFingerprint, donationAccount, donationCampaignId, donationOriginalPspReference, donationToken, lineItems, merchantRiskIndicator, metadata, mpiData, origin, paymentMethod, recurringProcessingModel, redirectFromIssuerMethod, redirectToIssuerMethod, sessionValidity, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, socialSecurityNumber, telephoneNumber, threeDS2RequestData, threeDSAuthenticationOnly); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationPaymentRequest donationPaymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationPaymentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationPaymentRequest donationPaymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, donationPaymentRequest.Amount, jsonSerializerOptions); + if (donationPaymentRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", donationPaymentRequest.MerchantAccount); + + if (donationPaymentRequest.Reference != null) + writer.WriteString("reference", donationPaymentRequest.Reference); + + if (donationPaymentRequest.ReturnUrl != null) + writer.WriteString("returnUrl", donationPaymentRequest.ReturnUrl); + + if (donationPaymentRequest._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, donationPaymentRequest.AccountInfo, jsonSerializerOptions); + } + if (donationPaymentRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, donationPaymentRequest.AdditionalData, jsonSerializerOptions); + } + if (donationPaymentRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, donationPaymentRequest.ApplicationInfo, jsonSerializerOptions); + } + if (donationPaymentRequest._AuthenticationDataOption.IsSet) + { + writer.WritePropertyName("authenticationData"); + JsonSerializer.Serialize(writer, donationPaymentRequest.AuthenticationData, jsonSerializerOptions); + } + if (donationPaymentRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, donationPaymentRequest.BillingAddress, jsonSerializerOptions); + } + if (donationPaymentRequest._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, donationPaymentRequest.BrowserInfo, jsonSerializerOptions); + } + if (donationPaymentRequest._ChannelOption.IsSet && donationPaymentRequest.Channel != null) + { + string? channelRawValue = DonationPaymentRequest.ChannelEnum.ToJsonValue(donationPaymentRequest._ChannelOption.Value!.Value); + writer.WriteString("channel", channelRawValue); + } + + if (donationPaymentRequest._CheckoutAttemptIdOption.IsSet) + if (donationPaymentRequest.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", donationPaymentRequest.CheckoutAttemptId); + + if (donationPaymentRequest._ConversionIdOption.IsSet) + if (donationPaymentRequest.ConversionId != null) + writer.WriteString("conversionId", donationPaymentRequest.ConversionId); + + if (donationPaymentRequest._CountryCodeOption.IsSet) + if (donationPaymentRequest.CountryCode != null) + writer.WriteString("countryCode", donationPaymentRequest.CountryCode); + + if (donationPaymentRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", donationPaymentRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (donationPaymentRequest._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", donationPaymentRequest._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (donationPaymentRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, donationPaymentRequest.DeliveryAddress, jsonSerializerOptions); + } + if (donationPaymentRequest._DeviceFingerprintOption.IsSet) + if (donationPaymentRequest.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", donationPaymentRequest.DeviceFingerprint); + + if (donationPaymentRequest._DonationAccountOption.IsSet) + if (donationPaymentRequest.DonationAccount != null) + writer.WriteString("donationAccount", donationPaymentRequest.DonationAccount); + + if (donationPaymentRequest._DonationCampaignIdOption.IsSet) + if (donationPaymentRequest.DonationCampaignId != null) + writer.WriteString("donationCampaignId", donationPaymentRequest.DonationCampaignId); + + if (donationPaymentRequest._DonationOriginalPspReferenceOption.IsSet) + if (donationPaymentRequest.DonationOriginalPspReference != null) + writer.WriteString("donationOriginalPspReference", donationPaymentRequest.DonationOriginalPspReference); + + if (donationPaymentRequest._DonationTokenOption.IsSet) + if (donationPaymentRequest.DonationToken != null) + writer.WriteString("donationToken", donationPaymentRequest.DonationToken); + + if (donationPaymentRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, donationPaymentRequest.LineItems, jsonSerializerOptions); + } + if (donationPaymentRequest._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, donationPaymentRequest.MerchantRiskIndicator, jsonSerializerOptions); + } + if (donationPaymentRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, donationPaymentRequest.Metadata, jsonSerializerOptions); + } + if (donationPaymentRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, donationPaymentRequest.MpiData, jsonSerializerOptions); + } + if (donationPaymentRequest._OriginOption.IsSet) + if (donationPaymentRequest.Origin != null) + writer.WriteString("origin", donationPaymentRequest.Origin); + + if (donationPaymentRequest._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, donationPaymentRequest.PaymentMethod, jsonSerializerOptions); + } + if (donationPaymentRequest._RecurringProcessingModelOption.IsSet && donationPaymentRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = DonationPaymentRequest.RecurringProcessingModelEnum.ToJsonValue(donationPaymentRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (donationPaymentRequest._RedirectFromIssuerMethodOption.IsSet) + if (donationPaymentRequest.RedirectFromIssuerMethod != null) + writer.WriteString("redirectFromIssuerMethod", donationPaymentRequest.RedirectFromIssuerMethod); + + if (donationPaymentRequest._RedirectToIssuerMethodOption.IsSet) + if (donationPaymentRequest.RedirectToIssuerMethod != null) + writer.WriteString("redirectToIssuerMethod", donationPaymentRequest.RedirectToIssuerMethod); + + if (donationPaymentRequest._SessionValidityOption.IsSet) + if (donationPaymentRequest.SessionValidity != null) + writer.WriteString("sessionValidity", donationPaymentRequest.SessionValidity); + + if (donationPaymentRequest._ShopperEmailOption.IsSet) + if (donationPaymentRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", donationPaymentRequest.ShopperEmail); + + if (donationPaymentRequest._ShopperIPOption.IsSet) + if (donationPaymentRequest.ShopperIP != null) + writer.WriteString("shopperIP", donationPaymentRequest.ShopperIP); + + if (donationPaymentRequest._ShopperInteractionOption.IsSet && donationPaymentRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = DonationPaymentRequest.ShopperInteractionEnum.ToJsonValue(donationPaymentRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (donationPaymentRequest._ShopperLocaleOption.IsSet) + if (donationPaymentRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", donationPaymentRequest.ShopperLocale); + + if (donationPaymentRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, donationPaymentRequest.ShopperName, jsonSerializerOptions); + } + if (donationPaymentRequest._ShopperReferenceOption.IsSet) + if (donationPaymentRequest.ShopperReference != null) + writer.WriteString("shopperReference", donationPaymentRequest.ShopperReference); + + if (donationPaymentRequest._SocialSecurityNumberOption.IsSet) + if (donationPaymentRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", donationPaymentRequest.SocialSecurityNumber); + + if (donationPaymentRequest._TelephoneNumberOption.IsSet) + if (donationPaymentRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", donationPaymentRequest.TelephoneNumber); + + if (donationPaymentRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, donationPaymentRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + if (donationPaymentRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", donationPaymentRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/DonationPaymentResponse.cs b/Adyen/Checkout/Models/DonationPaymentResponse.cs new file mode 100644 index 000000000..abf765794 --- /dev/null +++ b/Adyen/Checkout/Models/DonationPaymentResponse.cs @@ -0,0 +1,442 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DonationPaymentResponse. + /// + public partial class DonationPaymentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The Adyen account name of your charity. We will provide you with this account name once your chosen charity has been [onboarded](https://docs.adyen.com/online-payments/donations#onboarding). + /// Your unique resource identifier. + /// The merchant account identifier, with which you want to process the transaction. + /// payment + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The status of the donation transaction. Possible values: * **completed** * **pending** * **refused** + [JsonConstructor] + public DonationPaymentResponse(Option amount = default, Option donationAccount = default, Option id = default, Option merchantAccount = default, Option payment = default, Option reference = default, Option status = default) + { + _AmountOption = amount; + _DonationAccountOption = donationAccount; + _IdOption = id; + _MerchantAccountOption = merchantAccount; + _PaymentOption = payment; + _ReferenceOption = reference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationPaymentResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of the donation transaction. Possible values: * **completed** * **pending** * **refused** + /// + /// The status of the donation transaction. Possible values: * **completed** * **pending** * **refused** + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Completed - completed + /// + public static readonly StatusEnum Completed = new("completed"); + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "completed" => StatusEnum.Completed, + "pending" => StatusEnum.Pending, + "refused" => StatusEnum.Refused, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Completed) + return "completed"; + + if (value == StatusEnum.Pending) + return "pending"; + + if (value == StatusEnum.Refused) + return "refused"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the donation transaction. Possible values: * **completed** * **pending** * **refused** + /// + /// The status of the donation transaction. Possible values: * **completed** * **pending** * **refused** + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationAccountOption { get; private set; } + + /// + /// The Adyen account name of your charity. We will provide you with this account name once your chosen charity has been [onboarded](https://docs.adyen.com/online-payments/donations#onboarding). + /// + /// The Adyen account name of your charity. We will provide you with this account name once your chosen charity has been [onboarded](https://docs.adyen.com/online-payments/donations#onboarding). + [JsonPropertyName("donationAccount")] + public string? DonationAccount { get { return this._DonationAccountOption; } set { this._DonationAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Your unique resource identifier. + /// + /// Your unique resource identifier. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payment")] + public PaymentResponse? Payment { get { return this._PaymentOption; } set { this._PaymentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationPaymentResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" DonationAccount: ").Append(DonationAccount).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Payment: ").Append(Payment).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationPaymentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationPaymentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option donationAccount = default; + Option id = default; + Option merchantAccount = default; + Option payment = default; + Option reference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "donationAccount": + donationAccount = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "payment": + payment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(DonationPaymentResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new DonationPaymentResponse(amount, donationAccount, id, merchantAccount, payment, reference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationPaymentResponse donationPaymentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationPaymentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationPaymentResponse donationPaymentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (donationPaymentResponse._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, donationPaymentResponse.Amount, jsonSerializerOptions); + } + if (donationPaymentResponse._DonationAccountOption.IsSet) + if (donationPaymentResponse.DonationAccount != null) + writer.WriteString("donationAccount", donationPaymentResponse.DonationAccount); + + if (donationPaymentResponse._IdOption.IsSet) + if (donationPaymentResponse.Id != null) + writer.WriteString("id", donationPaymentResponse.Id); + + if (donationPaymentResponse._MerchantAccountOption.IsSet) + if (donationPaymentResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", donationPaymentResponse.MerchantAccount); + + if (donationPaymentResponse._PaymentOption.IsSet) + { + writer.WritePropertyName("payment"); + JsonSerializer.Serialize(writer, donationPaymentResponse.Payment, jsonSerializerOptions); + } + if (donationPaymentResponse._ReferenceOption.IsSet) + if (donationPaymentResponse.Reference != null) + writer.WriteString("reference", donationPaymentResponse.Reference); + + if (donationPaymentResponse._StatusOption.IsSet && donationPaymentResponse.Status != null) + { + string? statusRawValue = DonationPaymentResponse.StatusEnum.ToJsonValue(donationPaymentResponse._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/DragonpayDetails.cs b/Adyen/Checkout/Models/DragonpayDetails.cs new file mode 100644 index 000000000..0245a1afe --- /dev/null +++ b/Adyen/Checkout/Models/DragonpayDetails.cs @@ -0,0 +1,366 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// DragonpayDetails. + /// + public partial class DragonpayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Dragonpay issuer value of the shopper's selected bank. Set this to an **id** of a Dragonpay issuer to preselect it. + /// **dragonpay** + /// The checkout attempt identifier. + /// The shopper’s email address. + [JsonConstructor] + public DragonpayDetails(string issuer, TypeEnum type, Option checkoutAttemptId = default, Option shopperEmail = default) + { + Issuer = issuer; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + _ShopperEmailOption = shopperEmail; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DragonpayDetails() + { + } + + partial void OnCreated(); + + /// + /// **dragonpay** + /// + /// **dragonpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DragonpayEbanking - dragonpay_ebanking + /// + public static readonly TypeEnum DragonpayEbanking = new("dragonpay_ebanking"); + + /// + /// TypeEnum.DragonpayOtcBanking - dragonpay_otc_banking + /// + public static readonly TypeEnum DragonpayOtcBanking = new("dragonpay_otc_banking"); + + /// + /// TypeEnum.DragonpayOtcNonBanking - dragonpay_otc_non_banking + /// + public static readonly TypeEnum DragonpayOtcNonBanking = new("dragonpay_otc_non_banking"); + + /// + /// TypeEnum.DragonpayOtcPhilippines - dragonpay_otc_philippines + /// + public static readonly TypeEnum DragonpayOtcPhilippines = new("dragonpay_otc_philippines"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dragonpay_ebanking" => TypeEnum.DragonpayEbanking, + "dragonpay_otc_banking" => TypeEnum.DragonpayOtcBanking, + "dragonpay_otc_non_banking" => TypeEnum.DragonpayOtcNonBanking, + "dragonpay_otc_philippines" => TypeEnum.DragonpayOtcPhilippines, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DragonpayEbanking) + return "dragonpay_ebanking"; + + if (value == TypeEnum.DragonpayOtcBanking) + return "dragonpay_otc_banking"; + + if (value == TypeEnum.DragonpayOtcNonBanking) + return "dragonpay_otc_non_banking"; + + if (value == TypeEnum.DragonpayOtcPhilippines) + return "dragonpay_otc_philippines"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **dragonpay** + /// + /// **dragonpay** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The Dragonpay issuer value of the shopper's selected bank. Set this to an **id** of a Dragonpay issuer to preselect it. + /// + /// The Dragonpay issuer value of the shopper's selected bank. Set this to an **id** of a Dragonpay issuer to preselect it. + [JsonPropertyName("issuer")] + public string Issuer { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper’s email address. + /// + /// The shopper’s email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DragonpayDetails {\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DragonpayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DragonpayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issuer = default; + Option type = default; + Option checkoutAttemptId = default; + Option shopperEmail = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DragonpayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!issuer.IsSet) + throw new ArgumentException("Property is required for class DragonpayDetails.", nameof(issuer)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DragonpayDetails.", nameof(type)); + + return new DragonpayDetails(issuer.Value!, type.Value!.Value!, checkoutAttemptId, shopperEmail); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DragonpayDetails dragonpayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dragonpayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DragonpayDetails dragonpayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (dragonpayDetails.Issuer != null) + writer.WriteString("issuer", dragonpayDetails.Issuer); + + if (dragonpayDetails.Type != null) + { + string? typeRawValue = DragonpayDetails.TypeEnum.ToJsonValue(dragonpayDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (dragonpayDetails._CheckoutAttemptIdOption.IsSet) + if (dragonpayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", dragonpayDetails.CheckoutAttemptId); + + if (dragonpayDetails._ShopperEmailOption.IsSet) + if (dragonpayDetails.ShopperEmail != null) + writer.WriteString("shopperEmail", dragonpayDetails.ShopperEmail); + } + } +} diff --git a/Adyen/Checkout/Models/EBankingFinlandDetails.cs b/Adyen/Checkout/Models/EBankingFinlandDetails.cs new file mode 100644 index 000000000..32207aff9 --- /dev/null +++ b/Adyen/Checkout/Models/EBankingFinlandDetails.cs @@ -0,0 +1,319 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// EBankingFinlandDetails. + /// + public partial class EBankingFinlandDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The Ebanking Finland issuer value of the shopper's selected bank. + /// **ebanking_FI** (default to TypeEnum.EbankingFI) + [JsonConstructor] + public EBankingFinlandDetails(Option checkoutAttemptId = default, Option issuer = default, TypeEnum type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _IssuerOption = issuer; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EBankingFinlandDetails() + { + } + + partial void OnCreated(); + + /// + /// **ebanking_FI** + /// + /// **ebanking_FI** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.EbankingFI - ebanking_FI + /// + public static readonly TypeEnum EbankingFI = new("ebanking_FI"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ebanking_FI" => TypeEnum.EbankingFI, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.EbankingFI) + return "ebanking_FI"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ebanking_FI** + /// + /// **ebanking_FI** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The Ebanking Finland issuer value of the shopper's selected bank. + /// + /// The Ebanking Finland issuer value of the shopper's selected bank. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EBankingFinlandDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EBankingFinlandDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EBankingFinlandDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option issuer = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(EBankingFinlandDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class EBankingFinlandDetails.", nameof(type)); + + return new EBankingFinlandDetails(checkoutAttemptId, issuer, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EBankingFinlandDetails eBankingFinlandDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, eBankingFinlandDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EBankingFinlandDetails eBankingFinlandDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (eBankingFinlandDetails._CheckoutAttemptIdOption.IsSet) + if (eBankingFinlandDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", eBankingFinlandDetails.CheckoutAttemptId); + + if (eBankingFinlandDetails._IssuerOption.IsSet) + if (eBankingFinlandDetails.Issuer != null) + writer.WriteString("issuer", eBankingFinlandDetails.Issuer); + + if (eBankingFinlandDetails.Type != null) + { + string? typeRawValue = EBankingFinlandDetails.TypeEnum.ToJsonValue(eBankingFinlandDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/EcontextVoucherDetails.cs b/Adyen/Checkout/Models/EcontextVoucherDetails.cs new file mode 100644 index 000000000..7fcbd6d85 --- /dev/null +++ b/Adyen/Checkout/Models/EcontextVoucherDetails.cs @@ -0,0 +1,410 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// EcontextVoucherDetails. + /// + public partial class EcontextVoucherDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The shopper's first name. + /// The shopper's last name. + /// The shopper's email. + /// The shopper's contact number. It must have an international number format, for example **+31 20 779 1846**. Formats like **+31 (0)20 779 1846** or **0031 20 779 1846** are not accepted. + /// **econtextvoucher** + /// The checkout attempt identifier. + [JsonConstructor] + public EcontextVoucherDetails(string firstName, string lastName, string shopperEmail, string telephoneNumber, TypeEnum type, Option checkoutAttemptId = default) + { + FirstName = firstName; + LastName = lastName; + ShopperEmail = shopperEmail; + TelephoneNumber = telephoneNumber; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EcontextVoucherDetails() + { + } + + partial void OnCreated(); + + /// + /// **econtextvoucher** + /// + /// **econtextvoucher** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.EcontextSevenEleven - econtext_seven_eleven + /// + public static readonly TypeEnum EcontextSevenEleven = new("econtext_seven_eleven"); + + /// + /// TypeEnum.EcontextOnline - econtext_online + /// + public static readonly TypeEnum EcontextOnline = new("econtext_online"); + + /// + /// TypeEnum.Econtext - econtext + /// + public static readonly TypeEnum Econtext = new("econtext"); + + /// + /// TypeEnum.EcontextStores - econtext_stores + /// + public static readonly TypeEnum EcontextStores = new("econtext_stores"); + + /// + /// TypeEnum.EcontextAtm - econtext_atm + /// + public static readonly TypeEnum EcontextAtm = new("econtext_atm"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "econtext_seven_eleven" => TypeEnum.EcontextSevenEleven, + "econtext_online" => TypeEnum.EcontextOnline, + "econtext" => TypeEnum.Econtext, + "econtext_stores" => TypeEnum.EcontextStores, + "econtext_atm" => TypeEnum.EcontextAtm, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.EcontextSevenEleven) + return "econtext_seven_eleven"; + + if (value == TypeEnum.EcontextOnline) + return "econtext_online"; + + if (value == TypeEnum.Econtext) + return "econtext"; + + if (value == TypeEnum.EcontextStores) + return "econtext_stores"; + + if (value == TypeEnum.EcontextAtm) + return "econtext_atm"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **econtextvoucher** + /// + /// **econtextvoucher** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The shopper's first name. + /// + /// The shopper's first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The shopper's last name. + /// + /// The shopper's last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// The shopper's email. + /// + /// The shopper's email. + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// The shopper's contact number. It must have an international number format, for example **+31 20 779 1846**. Formats like **+31 (0)20 779 1846** or **0031 20 779 1846** are not accepted. + /// + /// The shopper's contact number. It must have an international number format, for example **+31 20 779 1846**. Formats like **+31 (0)20 779 1846** or **0031 20 779 1846** are not accepted. + [JsonPropertyName("telephoneNumber")] + public string TelephoneNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EcontextVoucherDetails {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EcontextVoucherDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EcontextVoucherDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + Option shopperEmail = default; + Option telephoneNumber = default; + Option type = default; + Option checkoutAttemptId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(EcontextVoucherDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class EcontextVoucherDetails.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class EcontextVoucherDetails.", nameof(lastName)); + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class EcontextVoucherDetails.", nameof(shopperEmail)); + + if (!telephoneNumber.IsSet) + throw new ArgumentException("Property is required for class EcontextVoucherDetails.", nameof(telephoneNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class EcontextVoucherDetails.", nameof(type)); + + return new EcontextVoucherDetails(firstName.Value!, lastName.Value!, shopperEmail.Value!, telephoneNumber.Value!, type.Value!.Value!, checkoutAttemptId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EcontextVoucherDetails econtextVoucherDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, econtextVoucherDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EcontextVoucherDetails econtextVoucherDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (econtextVoucherDetails.FirstName != null) + writer.WriteString("firstName", econtextVoucherDetails.FirstName); + + if (econtextVoucherDetails.LastName != null) + writer.WriteString("lastName", econtextVoucherDetails.LastName); + + if (econtextVoucherDetails.ShopperEmail != null) + writer.WriteString("shopperEmail", econtextVoucherDetails.ShopperEmail); + + if (econtextVoucherDetails.TelephoneNumber != null) + writer.WriteString("telephoneNumber", econtextVoucherDetails.TelephoneNumber); + + if (econtextVoucherDetails.Type != null) + { + string? typeRawValue = EcontextVoucherDetails.TypeEnum.ToJsonValue(econtextVoucherDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (econtextVoucherDetails._CheckoutAttemptIdOption.IsSet) + if (econtextVoucherDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", econtextVoucherDetails.CheckoutAttemptId); + } + } +} diff --git a/Adyen/Checkout/Models/EftDetails.cs b/Adyen/Checkout/Models/EftDetails.cs new file mode 100644 index 000000000..f91ffe623 --- /dev/null +++ b/Adyen/Checkout/Models/EftDetails.cs @@ -0,0 +1,456 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// EftDetails. + /// + public partial class EftDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The financial institution code. + /// The bank routing number of the account. + /// The checkout attempt identifier. + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **eft** (default to TypeEnum.EftDirectdebitCA) + [JsonConstructor] + public EftDetails(Option bankAccountNumber = default, Option bankCode = default, Option bankLocationId = default, Option checkoutAttemptId = default, Option ownerName = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankCodeOption = bankCode; + _BankLocationIdOption = bankLocationId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _OwnerNameOption = ownerName; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EftDetails() + { + } + + partial void OnCreated(); + + /// + /// **eft** + /// + /// **eft** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.EftDirectdebitCA - eft_directdebit_CA + /// + public static readonly TypeEnum EftDirectdebitCA = new("eft_directdebit_CA"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "eft_directdebit_CA" => TypeEnum.EftDirectdebitCA, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.EftDirectdebitCA) + return "eft_directdebit_CA"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **eft** + /// + /// **eft** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCodeOption { get; private set; } + + /// + /// The financial institution code. + /// + /// The financial institution code. + [JsonPropertyName("bankCode")] + public string? BankCode { get { return this._BankCodeOption; } set { this._BankCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The bank routing number of the account. + /// + /// The bank routing number of the account. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EftDetails {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EftDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EftDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankCode = default; + Option bankLocationId = default; + Option checkoutAttemptId = default; + Option ownerName = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(EftDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new EftDetails(bankAccountNumber, bankCode, bankLocationId, checkoutAttemptId, ownerName, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EftDetails eftDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, eftDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EftDetails eftDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (eftDetails._BankAccountNumberOption.IsSet) + if (eftDetails.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", eftDetails.BankAccountNumber); + + if (eftDetails._BankCodeOption.IsSet) + if (eftDetails.BankCode != null) + writer.WriteString("bankCode", eftDetails.BankCode); + + if (eftDetails._BankLocationIdOption.IsSet) + if (eftDetails.BankLocationId != null) + writer.WriteString("bankLocationId", eftDetails.BankLocationId); + + if (eftDetails._CheckoutAttemptIdOption.IsSet) + if (eftDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", eftDetails.CheckoutAttemptId); + + if (eftDetails._OwnerNameOption.IsSet) + if (eftDetails.OwnerName != null) + writer.WriteString("ownerName", eftDetails.OwnerName); + + if (eftDetails._RecurringDetailReferenceOption.IsSet) + if (eftDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", eftDetails.RecurringDetailReference); + + if (eftDetails._StoredPaymentMethodIdOption.IsSet) + if (eftDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", eftDetails.StoredPaymentMethodId); + + if (eftDetails._TypeOption.IsSet && eftDetails.Type != null) + { + string? typeRawValue = EftDetails.TypeEnum.ToJsonValue(eftDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/EncryptedOrderData.cs b/Adyen/Checkout/Models/EncryptedOrderData.cs new file mode 100644 index 000000000..f6b8ee1eb --- /dev/null +++ b/Adyen/Checkout/Models/EncryptedOrderData.cs @@ -0,0 +1,197 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// EncryptedOrderData. + /// + public partial class EncryptedOrderData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The encrypted order data. + /// The `pspReference` that belongs to the order. + [JsonConstructor] + public EncryptedOrderData(string orderData, string pspReference) + { + OrderData = orderData; + PspReference = pspReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EncryptedOrderData() + { + } + + partial void OnCreated(); + + /// + /// The encrypted order data. + /// + /// The encrypted order data. + [JsonPropertyName("orderData")] + public string OrderData { get; set; } + + /// + /// The `pspReference` that belongs to the order. + /// + /// The `pspReference` that belongs to the order. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EncryptedOrderData {\n"); + sb.Append(" OrderData: ").Append(OrderData).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // OrderData (string) maxLength + if (this.OrderData != null && this.OrderData.Length > 5000) + { + yield return new ValidationResult("Invalid value for OrderData, length must be less than 5000.", new [] { "OrderData" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EncryptedOrderDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EncryptedOrderData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option orderData = default; + Option pspReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "orderData": + orderData = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!orderData.IsSet) + throw new ArgumentException("Property is required for class EncryptedOrderData.", nameof(orderData)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class EncryptedOrderData.", nameof(pspReference)); + + return new EncryptedOrderData(orderData.Value!, pspReference.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EncryptedOrderData encryptedOrderData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, encryptedOrderData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EncryptedOrderData encryptedOrderData, JsonSerializerOptions jsonSerializerOptions) + { + + if (encryptedOrderData.OrderData != null) + writer.WriteString("orderData", encryptedOrderData.OrderData); + + if (encryptedOrderData.PspReference != null) + writer.WriteString("pspReference", encryptedOrderData.PspReference); + } + } +} diff --git a/Adyen/Checkout/Models/EnhancedSchemeData.cs b/Adyen/Checkout/Models/EnhancedSchemeData.cs new file mode 100644 index 000000000..e873c6275 --- /dev/null +++ b/Adyen/Checkout/Models/EnhancedSchemeData.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// EnhancedSchemeData. + /// + public partial class EnhancedSchemeData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// airline + [JsonConstructor] + public EnhancedSchemeData(Option airline = default) + { + _AirlineOption = airline; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EnhancedSchemeData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("airline")] + public Airline? Airline { get { return this._AirlineOption; } set { this._AirlineOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EnhancedSchemeData {\n"); + sb.Append(" Airline: ").Append(Airline).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EnhancedSchemeDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EnhancedSchemeData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option airline = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "airline": + airline = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new EnhancedSchemeData(airline); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EnhancedSchemeData enhancedSchemeData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, enhancedSchemeData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EnhancedSchemeData enhancedSchemeData, JsonSerializerOptions jsonSerializerOptions) + { + + if (enhancedSchemeData._AirlineOption.IsSet) + { + writer.WritePropertyName("airline"); + JsonSerializer.Serialize(writer, enhancedSchemeData.Airline, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/ExternalPlatform.cs b/Adyen/Checkout/Models/ExternalPlatform.cs new file mode 100644 index 000000000..16dccf98b --- /dev/null +++ b/Adyen/Checkout/Models/ExternalPlatform.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ExternalPlatform. + /// + public partial class ExternalPlatform : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// External platform integrator. + /// Name of the field. For example, Name of External Platform. + /// Version of the field. For example, Version of External Platform. + [JsonConstructor] + public ExternalPlatform(Option integrator = default, Option name = default, Option version = default) + { + _IntegratorOption = integrator; + _NameOption = name; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExternalPlatform() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IntegratorOption { get; private set; } + + /// + /// External platform integrator. + /// + /// External platform integrator. + [JsonPropertyName("integrator")] + public string? Integrator { get { return this._IntegratorOption; } set { this._IntegratorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Name of the field. For example, Name of External Platform. + /// + /// Name of the field. For example, Name of External Platform. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// Version of the field. For example, Version of External Platform. + /// + /// Version of the field. For example, Version of External Platform. + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExternalPlatform {\n"); + sb.Append(" Integrator: ").Append(Integrator).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExternalPlatformJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExternalPlatform Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option integrator = default; + Option name = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "integrator": + integrator = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExternalPlatform(integrator, name, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExternalPlatform externalPlatform, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, externalPlatform, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExternalPlatform externalPlatform, JsonSerializerOptions jsonSerializerOptions) + { + + if (externalPlatform._IntegratorOption.IsSet) + if (externalPlatform.Integrator != null) + writer.WriteString("integrator", externalPlatform.Integrator); + + if (externalPlatform._NameOption.IsSet) + if (externalPlatform.Name != null) + writer.WriteString("name", externalPlatform.Name); + + if (externalPlatform._VersionOption.IsSet) + if (externalPlatform.Version != null) + writer.WriteString("version", externalPlatform.Version); + } + } +} diff --git a/Adyen/Checkout/Models/FastlaneDetails.cs b/Adyen/Checkout/Models/FastlaneDetails.cs new file mode 100644 index 000000000..a82089bc8 --- /dev/null +++ b/Adyen/Checkout/Models/FastlaneDetails.cs @@ -0,0 +1,371 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// FastlaneDetails. + /// + public partial class FastlaneDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The encoded fastlane data blob + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **fastlane** (default to TypeEnum.Fastlane) + [JsonConstructor] + public FastlaneDetails(string fastlaneData, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + FastlaneData = fastlaneData; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FastlaneDetails() + { + } + + partial void OnCreated(); + + /// + /// **fastlane** + /// + /// **fastlane** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Fastlane - fastlane + /// + public static readonly TypeEnum Fastlane = new("fastlane"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "fastlane" => TypeEnum.Fastlane, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Fastlane) + return "fastlane"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **fastlane** + /// + /// **fastlane** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The encoded fastlane data blob + /// + /// The encoded fastlane data blob + [JsonPropertyName("fastlaneData")] + public string FastlaneData { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FastlaneDetails {\n"); + sb.Append(" FastlaneData: ").Append(FastlaneData).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FastlaneDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FastlaneDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option fastlaneData = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "fastlaneData": + fastlaneData = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(FastlaneDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!fastlaneData.IsSet) + throw new ArgumentException("Property is required for class FastlaneDetails.", nameof(fastlaneData)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class FastlaneDetails.", nameof(type)); + + return new FastlaneDetails(fastlaneData.Value!, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FastlaneDetails fastlaneDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fastlaneDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FastlaneDetails fastlaneDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (fastlaneDetails.FastlaneData != null) + writer.WriteString("fastlaneData", fastlaneDetails.FastlaneData); + + if (fastlaneDetails._CheckoutAttemptIdOption.IsSet) + if (fastlaneDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", fastlaneDetails.CheckoutAttemptId); + + if (fastlaneDetails._RecurringDetailReferenceOption.IsSet) + if (fastlaneDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", fastlaneDetails.RecurringDetailReference); + + if (fastlaneDetails._StoredPaymentMethodIdOption.IsSet) + if (fastlaneDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", fastlaneDetails.StoredPaymentMethodId); + + if (fastlaneDetails.Type != null) + { + string? typeRawValue = FastlaneDetails.TypeEnum.ToJsonValue(fastlaneDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ForexQuote.cs b/Adyen/Checkout/Models/ForexQuote.cs new file mode 100644 index 000000000..cee043e29 --- /dev/null +++ b/Adyen/Checkout/Models/ForexQuote.cs @@ -0,0 +1,444 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ForexQuote. + /// + public partial class ForexQuote : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The base points. + /// The date until which the forex quote is valid. + /// The account name. + /// The account type. + /// baseAmount + /// buy + /// interbank + /// The reference assigned to the forex quote request. + /// sell + /// The signature to validate the integrity. + /// The source of the forex quote. + /// The type of forex. + [JsonConstructor] + public ForexQuote(int basePoints, DateTimeOffset validTill, Option account = default, Option accountType = default, Option baseAmount = default, Option buy = default, Option interbank = default, Option reference = default, Option sell = default, Option signature = default, Option source = default, Option type = default) + { + BasePoints = basePoints; + ValidTill = validTill; + _AccountOption = account; + _AccountTypeOption = accountType; + _BaseAmountOption = baseAmount; + _BuyOption = buy; + _InterbankOption = interbank; + _ReferenceOption = reference; + _SellOption = sell; + _SignatureOption = signature; + _SourceOption = source; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ForexQuote() + { + } + + partial void OnCreated(); + + /// + /// The base points. + /// + /// The base points. + [JsonPropertyName("basePoints")] + public int BasePoints { get; set; } + + /// + /// The date until which the forex quote is valid. + /// + /// The date until which the forex quote is valid. + [JsonPropertyName("validTill")] + public DateTimeOffset ValidTill { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountOption { get; private set; } + + /// + /// The account name. + /// + /// The account name. + [JsonPropertyName("account")] + public string? Account { get { return this._AccountOption; } set { this._AccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The account type. + /// + /// The account type. + [JsonPropertyName("accountType")] + public string? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BaseAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("baseAmount")] + public Amount? BaseAmount { get { return this._BaseAmountOption; } set { this._BaseAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BuyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("buy")] + public Amount? Buy { get { return this._BuyOption; } set { this._BuyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InterbankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interbank")] + public Amount? Interbank { get { return this._InterbankOption; } set { this._InterbankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference assigned to the forex quote request. + /// + /// The reference assigned to the forex quote request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SellOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sell")] + public Amount? Sell { get { return this._SellOption; } set { this._SellOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SignatureOption { get; private set; } + + /// + /// The signature to validate the integrity. + /// + /// The signature to validate the integrity. + [JsonPropertyName("signature")] + public string? Signature { get { return this._SignatureOption; } set { this._SignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceOption { get; private set; } + + /// + /// The source of the forex quote. + /// + /// The source of the forex quote. + [JsonPropertyName("source")] + public string? Source { get { return this._SourceOption; } set { this._SourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of forex. + /// + /// The type of forex. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ForexQuote {\n"); + sb.Append(" BasePoints: ").Append(BasePoints).Append("\n"); + sb.Append(" ValidTill: ").Append(ValidTill).Append("\n"); + sb.Append(" Account: ").Append(Account).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BaseAmount: ").Append(BaseAmount).Append("\n"); + sb.Append(" Buy: ").Append(Buy).Append("\n"); + sb.Append(" Interbank: ").Append(Interbank).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Sell: ").Append(Sell).Append("\n"); + sb.Append(" Signature: ").Append(Signature).Append("\n"); + sb.Append(" Source: ").Append(Source).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ForexQuoteJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ValidTill. + /// + public static string ValidTillFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ForexQuote Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option basePoints = default; + Option validTill = default; + Option account = default; + Option accountType = default; + Option baseAmount = default; + Option buy = default; + Option interbank = default; + Option reference = default; + Option sell = default; + Option signature = default; + Option source = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "basePoints": + basePoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "validTill": + validTill = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "account": + account = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + accountType = new Option(utf8JsonReader.GetString()!); + break; + case "baseAmount": + baseAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "buy": + buy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interbank": + interbank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "sell": + sell = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signature": + signature = new Option(utf8JsonReader.GetString()!); + break; + case "source": + source = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!basePoints.IsSet) + throw new ArgumentException("Property is required for class ForexQuote.", nameof(basePoints)); + + if (!validTill.IsSet) + throw new ArgumentException("Property is required for class ForexQuote.", nameof(validTill)); + + return new ForexQuote(basePoints.Value!.Value!, validTill.Value!.Value!, account, accountType, baseAmount, buy, interbank, reference, sell, signature, source, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ForexQuote forexQuote, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, forexQuote, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ForexQuote forexQuote, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("basePoints", forexQuote.BasePoints); + + writer.WriteString("validTill", forexQuote.ValidTill.ToString(ValidTillFormat)); + + if (forexQuote._AccountOption.IsSet) + if (forexQuote.Account != null) + writer.WriteString("account", forexQuote.Account); + + if (forexQuote._AccountTypeOption.IsSet) + if (forexQuote.AccountType != null) + writer.WriteString("accountType", forexQuote.AccountType); + + if (forexQuote._BaseAmountOption.IsSet) + { + writer.WritePropertyName("baseAmount"); + JsonSerializer.Serialize(writer, forexQuote.BaseAmount, jsonSerializerOptions); + } + if (forexQuote._BuyOption.IsSet) + { + writer.WritePropertyName("buy"); + JsonSerializer.Serialize(writer, forexQuote.Buy, jsonSerializerOptions); + } + if (forexQuote._InterbankOption.IsSet) + { + writer.WritePropertyName("interbank"); + JsonSerializer.Serialize(writer, forexQuote.Interbank, jsonSerializerOptions); + } + if (forexQuote._ReferenceOption.IsSet) + if (forexQuote.Reference != null) + writer.WriteString("reference", forexQuote.Reference); + + if (forexQuote._SellOption.IsSet) + { + writer.WritePropertyName("sell"); + JsonSerializer.Serialize(writer, forexQuote.Sell, jsonSerializerOptions); + } + if (forexQuote._SignatureOption.IsSet) + if (forexQuote.Signature != null) + writer.WriteString("signature", forexQuote.Signature); + + if (forexQuote._SourceOption.IsSet) + if (forexQuote.Source != null) + writer.WriteString("source", forexQuote.Source); + + if (forexQuote._TypeOption.IsSet) + if (forexQuote.Type != null) + writer.WriteString("type", forexQuote.Type); + } + } +} diff --git a/Adyen/Checkout/Models/FraudCheckResult.cs b/Adyen/Checkout/Models/FraudCheckResult.cs new file mode 100644 index 000000000..7b1aed1c6 --- /dev/null +++ b/Adyen/Checkout/Models/FraudCheckResult.cs @@ -0,0 +1,209 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// FraudCheckResult. + /// + public partial class FraudCheckResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The fraud score generated by the risk check. + /// The ID of the risk check. + /// The name of the risk check. + [JsonConstructor] + public FraudCheckResult(int accountScore, int checkId, string name) + { + AccountScore = accountScore; + CheckId = checkId; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudCheckResult() + { + } + + partial void OnCreated(); + + /// + /// The fraud score generated by the risk check. + /// + /// The fraud score generated by the risk check. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// The ID of the risk check. + /// + /// The ID of the risk check. + [JsonPropertyName("checkId")] + public int CheckId { get; set; } + + /// + /// The name of the risk check. + /// + /// The name of the risk check. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudCheckResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" CheckId: ").Append(CheckId).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudCheckResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option checkId = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "checkId": + checkId = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(accountScore)); + + if (!checkId.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(checkId)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(name)); + + return new FraudCheckResult(accountScore.Value!.Value!, checkId.Value!.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudCheckResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudCheckResult.AccountScore); + + writer.WriteNumber("checkId", fraudCheckResult.CheckId); + + if (fraudCheckResult.Name != null) + writer.WriteString("name", fraudCheckResult.Name); + } + } +} diff --git a/Adyen/Checkout/Models/FraudResult.cs b/Adyen/Checkout/Models/FraudResult.cs new file mode 100644 index 000000000..5fee2758f --- /dev/null +++ b/Adyen/Checkout/Models/FraudResult.cs @@ -0,0 +1,197 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// FraudResult. + /// + public partial class FraudResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The total fraud score generated by the risk checks. + /// The result of the individual risk checks. + [JsonConstructor] + public FraudResult(int accountScore, Option?> results = default) + { + AccountScore = accountScore; + _ResultsOption = results; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudResult() + { + } + + partial void OnCreated(); + + /// + /// The total fraud score generated by the risk checks. + /// + /// The total fraud score generated by the risk checks. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ResultsOption { get; private set; } + + /// + /// The result of the individual risk checks. + /// + /// The result of the individual risk checks. + [JsonPropertyName("results")] + public List? Results { get { return this._ResultsOption; } set { this._ResultsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" Results: ").Append(Results).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option?> results = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "results": + results = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudResult.", nameof(accountScore)); + + return new FraudResult(accountScore.Value!.Value!, results); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudResult.AccountScore); + + if (fraudResult._ResultsOption.IsSet) + { + writer.WritePropertyName("results"); + JsonSerializer.Serialize(writer, fraudResult.Results, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/FundOrigin.cs b/Adyen/Checkout/Models/FundOrigin.cs new file mode 100644 index 000000000..0a82d354e --- /dev/null +++ b/Adyen/Checkout/Models/FundOrigin.cs @@ -0,0 +1,277 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// FundOrigin. + /// + public partial class FundOrigin : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// billingAddress + /// The email address of the person funding the money. + /// shopperName + /// The phone number of the person funding the money. + /// The unique identifier of the wallet where the funds are coming from. + [JsonConstructor] + public FundOrigin(Option billingAddress = default, Option shopperEmail = default, Option shopperName = default, Option telephoneNumber = default, Option walletIdentifier = default) + { + _BillingAddressOption = billingAddress; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _TelephoneNumberOption = telephoneNumber; + _WalletIdentifierOption = walletIdentifier; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FundOrigin() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The email address of the person funding the money. + /// + /// The email address of the person funding the money. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The phone number of the person funding the money. + /// + /// The phone number of the person funding the money. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletIdentifierOption { get; private set; } + + /// + /// The unique identifier of the wallet where the funds are coming from. + /// + /// The unique identifier of the wallet where the funds are coming from. + [JsonPropertyName("walletIdentifier")] + public string? WalletIdentifier { get { return this._WalletIdentifierOption; } set { this._WalletIdentifierOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FundOrigin {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" WalletIdentifier: ").Append(WalletIdentifier).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FundOriginJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FundOrigin Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option shopperEmail = default; + Option shopperName = default; + Option telephoneNumber = default; + Option walletIdentifier = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "walletIdentifier": + walletIdentifier = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new FundOrigin(billingAddress, shopperEmail, shopperName, telephoneNumber, walletIdentifier); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FundOrigin fundOrigin, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fundOrigin, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FundOrigin fundOrigin, JsonSerializerOptions jsonSerializerOptions) + { + + if (fundOrigin._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, fundOrigin.BillingAddress, jsonSerializerOptions); + } + if (fundOrigin._ShopperEmailOption.IsSet) + if (fundOrigin.ShopperEmail != null) + writer.WriteString("shopperEmail", fundOrigin.ShopperEmail); + + if (fundOrigin._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, fundOrigin.ShopperName, jsonSerializerOptions); + } + if (fundOrigin._TelephoneNumberOption.IsSet) + if (fundOrigin.TelephoneNumber != null) + writer.WriteString("telephoneNumber", fundOrigin.TelephoneNumber); + + if (fundOrigin._WalletIdentifierOption.IsSet) + if (fundOrigin.WalletIdentifier != null) + writer.WriteString("walletIdentifier", fundOrigin.WalletIdentifier); + } + } +} diff --git a/Adyen/Checkout/Models/FundRecipient.cs b/Adyen/Checkout/Models/FundRecipient.cs new file mode 100644 index 000000000..d07c7aee6 --- /dev/null +++ b/Adyen/Checkout/Models/FundRecipient.cs @@ -0,0 +1,603 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// FundRecipient. + /// + public partial class FundRecipient : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The IBAN of the bank account where the funds are being transferred to. + /// billingAddress + /// paymentMethod + /// The email address of the shopper. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// subMerchant + /// The telephone number of the shopper. + /// The unique identifier for the wallet the funds are being transferred to. You can use the shopper reference or any other identifier. + /// The tax identifier of the person receiving the funds. + /// The purpose of a digital wallet transaction. + [JsonConstructor] + public FundRecipient(Option iBAN = default, Option billingAddress = default, Option paymentMethod = default, Option shopperEmail = default, Option shopperName = default, Option shopperReference = default, Option storedPaymentMethodId = default, Option subMerchant = default, Option telephoneNumber = default, Option walletIdentifier = default, Option walletOwnerTaxId = default, Option walletPurpose = default) + { + _IBANOption = iBAN; + _BillingAddressOption = billingAddress; + _PaymentMethodOption = paymentMethod; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubMerchantOption = subMerchant; + _TelephoneNumberOption = telephoneNumber; + _WalletIdentifierOption = walletIdentifier; + _WalletOwnerTaxIdOption = walletOwnerTaxId; + _WalletPurposeOption = walletPurpose; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FundRecipient() + { + } + + partial void OnCreated(); + + /// + /// The purpose of a digital wallet transaction. + /// + /// The purpose of a digital wallet transaction. + [JsonConverter(typeof(WalletPurposeEnumJsonConverter))] + public class WalletPurposeEnum : IEnum + { + /// + /// Returns the value of the WalletPurposeEnum. + /// + public string? Value { get; set; } + + /// + /// WalletPurposeEnum.IdentifiedBoleto - identifiedBoleto + /// + public static readonly WalletPurposeEnum IdentifiedBoleto = new("identifiedBoleto"); + + /// + /// WalletPurposeEnum.TransferDifferentWallet - transferDifferentWallet + /// + public static readonly WalletPurposeEnum TransferDifferentWallet = new("transferDifferentWallet"); + + /// + /// WalletPurposeEnum.TransferOwnWallet - transferOwnWallet + /// + public static readonly WalletPurposeEnum TransferOwnWallet = new("transferOwnWallet"); + + /// + /// WalletPurposeEnum.TransferSameWallet - transferSameWallet + /// + public static readonly WalletPurposeEnum TransferSameWallet = new("transferSameWallet"); + + /// + /// WalletPurposeEnum.UnidentifiedBoleto - unidentifiedBoleto + /// + public static readonly WalletPurposeEnum UnidentifiedBoleto = new("unidentifiedBoleto"); + + private WalletPurposeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator WalletPurposeEnum?(string? value) => value == null ? null : new WalletPurposeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(WalletPurposeEnum? option) => option?.Value; + + public static bool operator ==(WalletPurposeEnum? left, WalletPurposeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(WalletPurposeEnum? left, WalletPurposeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is WalletPurposeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static WalletPurposeEnum? FromStringOrDefault(string value) + { + return value switch { + "identifiedBoleto" => WalletPurposeEnum.IdentifiedBoleto, + "transferDifferentWallet" => WalletPurposeEnum.TransferDifferentWallet, + "transferOwnWallet" => WalletPurposeEnum.TransferOwnWallet, + "transferSameWallet" => WalletPurposeEnum.TransferSameWallet, + "unidentifiedBoleto" => WalletPurposeEnum.UnidentifiedBoleto, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(WalletPurposeEnum? value) + { + if (value == null) + return null; + + if (value == WalletPurposeEnum.IdentifiedBoleto) + return "identifiedBoleto"; + + if (value == WalletPurposeEnum.TransferDifferentWallet) + return "transferDifferentWallet"; + + if (value == WalletPurposeEnum.TransferOwnWallet) + return "transferOwnWallet"; + + if (value == WalletPurposeEnum.TransferSameWallet) + return "transferSameWallet"; + + if (value == WalletPurposeEnum.UnidentifiedBoleto) + return "unidentifiedBoleto"; + + return null; + } + + /// + /// JsonConverter for writing WalletPurposeEnum. + /// + public class WalletPurposeEnumJsonConverter : JsonConverter + { + public override WalletPurposeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : WalletPurposeEnum.FromStringOrDefault(value) ?? new WalletPurposeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, WalletPurposeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(WalletPurposeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletPurposeOption { get; private set; } + + /// + /// The purpose of a digital wallet transaction. + /// + /// The purpose of a digital wallet transaction. + [JsonPropertyName("walletPurpose")] + public WalletPurposeEnum? WalletPurpose { get { return this._WalletPurposeOption; } set { this._WalletPurposeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IBANOption { get; private set; } + + /// + /// The IBAN of the bank account where the funds are being transferred to. + /// + /// The IBAN of the bank account where the funds are being transferred to. + [JsonPropertyName("IBAN")] + public string? IBAN { get { return this._IBANOption; } set { this._IBANOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public CardDetails? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The email address of the shopper. + /// + /// The email address of the shopper. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchant")] + public SubMerchant? SubMerchant { get { return this._SubMerchantOption; } set { this._SubMerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The telephone number of the shopper. + /// + /// The telephone number of the shopper. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletIdentifierOption { get; private set; } + + /// + /// The unique identifier for the wallet the funds are being transferred to. You can use the shopper reference or any other identifier. + /// + /// The unique identifier for the wallet the funds are being transferred to. You can use the shopper reference or any other identifier. + [JsonPropertyName("walletIdentifier")] + public string? WalletIdentifier { get { return this._WalletIdentifierOption; } set { this._WalletIdentifierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletOwnerTaxIdOption { get; private set; } + + /// + /// The tax identifier of the person receiving the funds. + /// + /// The tax identifier of the person receiving the funds. + [JsonPropertyName("walletOwnerTaxId")] + public string? WalletOwnerTaxId { get { return this._WalletOwnerTaxIdOption; } set { this._WalletOwnerTaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FundRecipient {\n"); + sb.Append(" IBAN: ").Append(IBAN).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" SubMerchant: ").Append(SubMerchant).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" WalletIdentifier: ").Append(WalletIdentifier).Append("\n"); + sb.Append(" WalletOwnerTaxId: ").Append(WalletOwnerTaxId).Append("\n"); + sb.Append(" WalletPurpose: ").Append(WalletPurpose).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FundRecipientJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FundRecipient Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iBAN = default; + Option billingAddress = default; + Option paymentMethod = default; + Option shopperEmail = default; + Option shopperName = default; + Option shopperReference = default; + Option storedPaymentMethodId = default; + Option subMerchant = default; + Option telephoneNumber = default; + Option walletIdentifier = default; + Option walletOwnerTaxId = default; + Option walletPurpose = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "IBAN": + iBAN = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant": + subMerchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "walletIdentifier": + walletIdentifier = new Option(utf8JsonReader.GetString()!); + break; + case "walletOwnerTaxId": + walletOwnerTaxId = new Option(utf8JsonReader.GetString()!); + break; + case "walletPurpose": + string? walletPurposeRawValue = utf8JsonReader.GetString(); + walletPurpose = new Option(FundRecipient.WalletPurposeEnum.FromStringOrDefault(walletPurposeRawValue)); + break; + default: + break; + } + } + } + + + return new FundRecipient(iBAN, billingAddress, paymentMethod, shopperEmail, shopperName, shopperReference, storedPaymentMethodId, subMerchant, telephoneNumber, walletIdentifier, walletOwnerTaxId, walletPurpose); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FundRecipient fundRecipient, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fundRecipient, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FundRecipient fundRecipient, JsonSerializerOptions jsonSerializerOptions) + { + + if (fundRecipient._IBANOption.IsSet) + if (fundRecipient.IBAN != null) + writer.WriteString("IBAN", fundRecipient.IBAN); + + if (fundRecipient._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, fundRecipient.BillingAddress, jsonSerializerOptions); + } + if (fundRecipient._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, fundRecipient.PaymentMethod, jsonSerializerOptions); + } + if (fundRecipient._ShopperEmailOption.IsSet) + if (fundRecipient.ShopperEmail != null) + writer.WriteString("shopperEmail", fundRecipient.ShopperEmail); + + if (fundRecipient._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, fundRecipient.ShopperName, jsonSerializerOptions); + } + if (fundRecipient._ShopperReferenceOption.IsSet) + if (fundRecipient.ShopperReference != null) + writer.WriteString("shopperReference", fundRecipient.ShopperReference); + + if (fundRecipient._StoredPaymentMethodIdOption.IsSet) + if (fundRecipient.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", fundRecipient.StoredPaymentMethodId); + + if (fundRecipient._SubMerchantOption.IsSet) + { + writer.WritePropertyName("subMerchant"); + JsonSerializer.Serialize(writer, fundRecipient.SubMerchant, jsonSerializerOptions); + } + if (fundRecipient._TelephoneNumberOption.IsSet) + if (fundRecipient.TelephoneNumber != null) + writer.WriteString("telephoneNumber", fundRecipient.TelephoneNumber); + + if (fundRecipient._WalletIdentifierOption.IsSet) + if (fundRecipient.WalletIdentifier != null) + writer.WriteString("walletIdentifier", fundRecipient.WalletIdentifier); + + if (fundRecipient._WalletOwnerTaxIdOption.IsSet) + if (fundRecipient.WalletOwnerTaxId != null) + writer.WriteString("walletOwnerTaxId", fundRecipient.WalletOwnerTaxId); + + if (fundRecipient._WalletPurposeOption.IsSet && fundRecipient.WalletPurpose != null) + { + string? walletPurposeRawValue = FundRecipient.WalletPurposeEnum.ToJsonValue(fundRecipient._WalletPurposeOption.Value!.Value); + writer.WriteString("walletPurpose", walletPurposeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/GenericIssuerPaymentMethodDetails.cs b/Adyen/Checkout/Models/GenericIssuerPaymentMethodDetails.cs new file mode 100644 index 000000000..ae2622f80 --- /dev/null +++ b/Adyen/Checkout/Models/GenericIssuerPaymentMethodDetails.cs @@ -0,0 +1,407 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// GenericIssuerPaymentMethodDetails. + /// + public partial class GenericIssuerPaymentMethodDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The issuer id of the shopper's selected bank. + /// **genericissuer** + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonConstructor] + public GenericIssuerPaymentMethodDetails(string issuer, TypeEnum type, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default) + { + Issuer = issuer; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GenericIssuerPaymentMethodDetails() + { + } + + partial void OnCreated(); + + /// + /// **genericissuer** + /// + /// **genericissuer** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.OnlineBankingPL - onlineBanking_PL + /// + public static readonly TypeEnum OnlineBankingPL = new("onlineBanking_PL"); + + /// + /// TypeEnum.Eps - eps + /// + public static readonly TypeEnum Eps = new("eps"); + + /// + /// TypeEnum.OnlineBankingSK - onlineBanking_SK + /// + public static readonly TypeEnum OnlineBankingSK = new("onlineBanking_SK"); + + /// + /// TypeEnum.OnlineBankingCZ - onlineBanking_CZ + /// + public static readonly TypeEnum OnlineBankingCZ = new("onlineBanking_CZ"); + + /// + /// TypeEnum.OnlinebankingIN - onlinebanking_IN + /// + public static readonly TypeEnum OnlinebankingIN = new("onlinebanking_IN"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "onlineBanking_PL" => TypeEnum.OnlineBankingPL, + "eps" => TypeEnum.Eps, + "onlineBanking_SK" => TypeEnum.OnlineBankingSK, + "onlineBanking_CZ" => TypeEnum.OnlineBankingCZ, + "onlinebanking_IN" => TypeEnum.OnlinebankingIN, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.OnlineBankingPL) + return "onlineBanking_PL"; + + if (value == TypeEnum.Eps) + return "eps"; + + if (value == TypeEnum.OnlineBankingSK) + return "onlineBanking_SK"; + + if (value == TypeEnum.OnlineBankingCZ) + return "onlineBanking_CZ"; + + if (value == TypeEnum.OnlinebankingIN) + return "onlinebanking_IN"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **genericissuer** + /// + /// **genericissuer** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The issuer id of the shopper's selected bank. + /// + /// The issuer id of the shopper's selected bank. + [JsonPropertyName("issuer")] + public string Issuer { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GenericIssuerPaymentMethodDetails {\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GenericIssuerPaymentMethodDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GenericIssuerPaymentMethodDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issuer = default; + Option type = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(GenericIssuerPaymentMethodDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!issuer.IsSet) + throw new ArgumentException("Property is required for class GenericIssuerPaymentMethodDetails.", nameof(issuer)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class GenericIssuerPaymentMethodDetails.", nameof(type)); + + return new GenericIssuerPaymentMethodDetails(issuer.Value!, type.Value!.Value!, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GenericIssuerPaymentMethodDetails genericIssuerPaymentMethodDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, genericIssuerPaymentMethodDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GenericIssuerPaymentMethodDetails genericIssuerPaymentMethodDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (genericIssuerPaymentMethodDetails.Issuer != null) + writer.WriteString("issuer", genericIssuerPaymentMethodDetails.Issuer); + + if (genericIssuerPaymentMethodDetails.Type != null) + { + string? typeRawValue = GenericIssuerPaymentMethodDetails.TypeEnum.ToJsonValue(genericIssuerPaymentMethodDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (genericIssuerPaymentMethodDetails._CheckoutAttemptIdOption.IsSet) + if (genericIssuerPaymentMethodDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", genericIssuerPaymentMethodDetails.CheckoutAttemptId); + + if (genericIssuerPaymentMethodDetails._RecurringDetailReferenceOption.IsSet) + if (genericIssuerPaymentMethodDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", genericIssuerPaymentMethodDetails.RecurringDetailReference); + + if (genericIssuerPaymentMethodDetails._StoredPaymentMethodIdOption.IsSet) + if (genericIssuerPaymentMethodDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", genericIssuerPaymentMethodDetails.StoredPaymentMethodId); + } + } +} diff --git a/Adyen/Checkout/Models/GooglePayDetails.cs b/Adyen/Checkout/Models/GooglePayDetails.cs new file mode 100644 index 000000000..71b2afb29 --- /dev/null +++ b/Adyen/Checkout/Models/GooglePayDetails.cs @@ -0,0 +1,568 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// GooglePayDetails. + /// + public partial class GooglePayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// The selected payment card network. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// **googlepay**, **paywithgoogle** (default to TypeEnum.Googlepay) + [JsonConstructor] + public GooglePayDetails(string googlePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option googlePayCardNetwork = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + GooglePayToken = googlePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _GooglePayCardNetworkOption = googlePayCardNetwork; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GooglePayDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **googlepay**, **paywithgoogle** + /// + /// **googlepay**, **paywithgoogle** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Googlepay - googlepay + /// + public static readonly TypeEnum Googlepay = new("googlepay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "googlepay" => TypeEnum.Googlepay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Googlepay) + return "googlepay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **googlepay**, **paywithgoogle** + /// + /// **googlepay**, **paywithgoogle** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + [JsonPropertyName("googlePayToken")] + public string GooglePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GooglePayCardNetworkOption { get; private set; } + + /// + /// The selected payment card network. + /// + /// The selected payment card network. + [JsonPropertyName("googlePayCardNetwork")] + public string? GooglePayCardNetwork { get { return this._GooglePayCardNetworkOption; } set { this._GooglePayCardNetworkOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GooglePayDetails {\n"); + sb.Append(" GooglePayToken: ").Append(GooglePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" GooglePayCardNetwork: ").Append(GooglePayCardNetwork).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // GooglePayToken (string) maxLength + if (this.GooglePayToken != null && this.GooglePayToken.Length > 10000) + { + yield return new ValidationResult("Invalid value for GooglePayToken, length must be less than 10000.", new [] { "GooglePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GooglePayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GooglePayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option googlePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option googlePayCardNetwork = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "googlePayToken": + googlePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(GooglePayDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "googlePayCardNetwork": + googlePayCardNetwork = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(GooglePayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!googlePayToken.IsSet) + throw new ArgumentException("Property is required for class GooglePayDetails.", nameof(googlePayToken)); + + return new GooglePayDetails(googlePayToken.Value!, checkoutAttemptId, fundingSource, googlePayCardNetwork, recurringDetailReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GooglePayDetails googlePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, googlePayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GooglePayDetails googlePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (googlePayDetails.GooglePayToken != null) + writer.WriteString("googlePayToken", googlePayDetails.GooglePayToken); + + if (googlePayDetails._CheckoutAttemptIdOption.IsSet) + if (googlePayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", googlePayDetails.CheckoutAttemptId); + + if (googlePayDetails._FundingSourceOption.IsSet && googlePayDetails.FundingSource != null) + { + string? fundingSourceRawValue = GooglePayDetails.FundingSourceEnum.ToJsonValue(googlePayDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (googlePayDetails._GooglePayCardNetworkOption.IsSet) + if (googlePayDetails.GooglePayCardNetwork != null) + writer.WriteString("googlePayCardNetwork", googlePayDetails.GooglePayCardNetwork); + + if (googlePayDetails._RecurringDetailReferenceOption.IsSet) + if (googlePayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", googlePayDetails.RecurringDetailReference); + + if (googlePayDetails._StoredPaymentMethodIdOption.IsSet) + if (googlePayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", googlePayDetails.StoredPaymentMethodId); + + if (googlePayDetails._ThreeDS2SdkVersionOption.IsSet) + if (googlePayDetails.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", googlePayDetails.ThreeDS2SdkVersion); + + if (googlePayDetails._TypeOption.IsSet && googlePayDetails.Type != null) + { + string? typeRawValue = GooglePayDetails.TypeEnum.ToJsonValue(googlePayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/GooglePayDonations.cs b/Adyen/Checkout/Models/GooglePayDonations.cs new file mode 100644 index 000000000..b2a807ad4 --- /dev/null +++ b/Adyen/Checkout/Models/GooglePayDonations.cs @@ -0,0 +1,568 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// GooglePayDonations. + /// + public partial class GooglePayDonations : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// The selected payment card network. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// **googlepay**, **paywithgoogle** (default to TypeEnum.Googlepay) + [JsonConstructor] + public GooglePayDonations(string googlePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option googlePayCardNetwork = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + GooglePayToken = googlePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _GooglePayCardNetworkOption = googlePayCardNetwork; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GooglePayDonations() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **googlepay**, **paywithgoogle** + /// + /// **googlepay**, **paywithgoogle** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Googlepay - googlepay + /// + public static readonly TypeEnum Googlepay = new("googlepay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "googlepay" => TypeEnum.Googlepay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Googlepay) + return "googlepay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **googlepay**, **paywithgoogle** + /// + /// **googlepay**, **paywithgoogle** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + [JsonPropertyName("googlePayToken")] + public string GooglePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GooglePayCardNetworkOption { get; private set; } + + /// + /// The selected payment card network. + /// + /// The selected payment card network. + [JsonPropertyName("googlePayCardNetwork")] + public string? GooglePayCardNetwork { get { return this._GooglePayCardNetworkOption; } set { this._GooglePayCardNetworkOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GooglePayDonations {\n"); + sb.Append(" GooglePayToken: ").Append(GooglePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" GooglePayCardNetwork: ").Append(GooglePayCardNetwork).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // GooglePayToken (string) maxLength + if (this.GooglePayToken != null && this.GooglePayToken.Length > 10000) + { + yield return new ValidationResult("Invalid value for GooglePayToken, length must be less than 10000.", new [] { "GooglePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GooglePayDonationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GooglePayDonations Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option googlePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option googlePayCardNetwork = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "googlePayToken": + googlePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(GooglePayDonations.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "googlePayCardNetwork": + googlePayCardNetwork = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(GooglePayDonations.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!googlePayToken.IsSet) + throw new ArgumentException("Property is required for class GooglePayDonations.", nameof(googlePayToken)); + + return new GooglePayDonations(googlePayToken.Value!, checkoutAttemptId, fundingSource, googlePayCardNetwork, recurringDetailReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GooglePayDonations googlePayDonations, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, googlePayDonations, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GooglePayDonations googlePayDonations, JsonSerializerOptions jsonSerializerOptions) + { + + if (googlePayDonations.GooglePayToken != null) + writer.WriteString("googlePayToken", googlePayDonations.GooglePayToken); + + if (googlePayDonations._CheckoutAttemptIdOption.IsSet) + if (googlePayDonations.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", googlePayDonations.CheckoutAttemptId); + + if (googlePayDonations._FundingSourceOption.IsSet && googlePayDonations.FundingSource != null) + { + string? fundingSourceRawValue = GooglePayDonations.FundingSourceEnum.ToJsonValue(googlePayDonations._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (googlePayDonations._GooglePayCardNetworkOption.IsSet) + if (googlePayDonations.GooglePayCardNetwork != null) + writer.WriteString("googlePayCardNetwork", googlePayDonations.GooglePayCardNetwork); + + if (googlePayDonations._RecurringDetailReferenceOption.IsSet) + if (googlePayDonations.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", googlePayDonations.RecurringDetailReference); + + if (googlePayDonations._StoredPaymentMethodIdOption.IsSet) + if (googlePayDonations.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", googlePayDonations.StoredPaymentMethodId); + + if (googlePayDonations._ThreeDS2SdkVersionOption.IsSet) + if (googlePayDonations.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", googlePayDonations.ThreeDS2SdkVersion); + + if (googlePayDonations._TypeOption.IsSet && googlePayDonations.Type != null) + { + string? typeRawValue = GooglePayDonations.TypeEnum.ToJsonValue(googlePayDonations._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/IdealDetails.cs b/Adyen/Checkout/Models/IdealDetails.cs new file mode 100644 index 000000000..aaaa2a66a --- /dev/null +++ b/Adyen/Checkout/Models/IdealDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// IdealDetails. + /// + public partial class IdealDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **ideal** (default to TypeEnum.Ideal) + [JsonConstructor] + public IdealDetails(Option checkoutAttemptId = default, Option issuer = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _IssuerOption = issuer; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IdealDetails() + { + } + + partial void OnCreated(); + + /// + /// **ideal** + /// + /// **ideal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ideal - ideal + /// + public static readonly TypeEnum Ideal = new("ideal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ideal" => TypeEnum.Ideal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ideal) + return "ideal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **ideal** + /// + /// **ideal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + /// + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IdealDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IdealDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IdealDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option issuer = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IdealDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new IdealDetails(checkoutAttemptId, issuer, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IdealDetails idealDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, idealDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IdealDetails idealDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (idealDetails._CheckoutAttemptIdOption.IsSet) + if (idealDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", idealDetails.CheckoutAttemptId); + + if (idealDetails._IssuerOption.IsSet) + if (idealDetails.Issuer != null) + writer.WriteString("issuer", idealDetails.Issuer); + + if (idealDetails._RecurringDetailReferenceOption.IsSet) + if (idealDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", idealDetails.RecurringDetailReference); + + if (idealDetails._StoredPaymentMethodIdOption.IsSet) + if (idealDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", idealDetails.StoredPaymentMethodId); + + if (idealDetails._TypeOption.IsSet && idealDetails.Type != null) + { + string? typeRawValue = IdealDetails.TypeEnum.ToJsonValue(idealDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/IdealDonations.cs b/Adyen/Checkout/Models/IdealDonations.cs new file mode 100644 index 000000000..bde54f6f0 --- /dev/null +++ b/Adyen/Checkout/Models/IdealDonations.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// IdealDonations. + /// + public partial class IdealDonations : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **ideal** (default to TypeEnum.Ideal) + [JsonConstructor] + public IdealDonations(Option checkoutAttemptId = default, Option issuer = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _IssuerOption = issuer; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IdealDonations() + { + } + + partial void OnCreated(); + + /// + /// **ideal** + /// + /// **ideal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ideal - ideal + /// + public static readonly TypeEnum Ideal = new("ideal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ideal" => TypeEnum.Ideal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ideal) + return "ideal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **ideal** + /// + /// **ideal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + /// + /// The iDEAL issuer value of the shopper's selected bank. Set this to an **id** of an iDEAL issuer to preselect it. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IdealDonations {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IdealDonationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IdealDonations Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option issuer = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IdealDonations.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new IdealDonations(checkoutAttemptId, issuer, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IdealDonations idealDonations, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, idealDonations, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IdealDonations idealDonations, JsonSerializerOptions jsonSerializerOptions) + { + + if (idealDonations._CheckoutAttemptIdOption.IsSet) + if (idealDonations.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", idealDonations.CheckoutAttemptId); + + if (idealDonations._IssuerOption.IsSet) + if (idealDonations.Issuer != null) + writer.WriteString("issuer", idealDonations.Issuer); + + if (idealDonations._RecurringDetailReferenceOption.IsSet) + if (idealDonations.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", idealDonations.RecurringDetailReference); + + if (idealDonations._StoredPaymentMethodIdOption.IsSet) + if (idealDonations.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", idealDonations.StoredPaymentMethodId); + + if (idealDonations._TypeOption.IsSet && idealDonations.Type != null) + { + string? typeRawValue = IdealDonations.TypeEnum.ToJsonValue(idealDonations._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/InputDetail.cs b/Adyen/Checkout/Models/InputDetail.cs new file mode 100644 index 000000000..3b7973641 --- /dev/null +++ b/Adyen/Checkout/Models/InputDetail.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// InputDetail. + /// + public partial class InputDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Configuration parameters for the required input. + /// Input details can also be provided recursively. + /// Input details can also be provided recursively (deprecated). + /// In case of a select, the URL from which to query the items. + /// In case of a select, the items to choose from. + /// The value to provide in the result. + /// True if this input value is optional. + /// The type of the required input. + /// The value can be pre-filled, if available. + [JsonConstructor] + public InputDetail(Option?> configuration = default, Option?> details = default, Option?> inputDetails = default, Option itemSearchUrl = default, Option?> items = default, Option key = default, Option optional = default, Option type = default, Option value = default) + { + _ConfigurationOption = configuration; + _DetailsOption = details; + _InputDetailsOption = inputDetails; + _ItemSearchUrlOption = itemSearchUrl; + _ItemsOption = items; + _KeyOption = key; + _OptionalOption = optional; + _TypeOption = type; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InputDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConfigurationOption { get; private set; } + + /// + /// Configuration parameters for the required input. + /// + /// Configuration parameters for the required input. + [JsonPropertyName("configuration")] + public Dictionary? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DetailsOption { get; private set; } + + /// + /// Input details can also be provided recursively. + /// + /// Input details can also be provided recursively. + [JsonPropertyName("details")] + public List? Details { get { return this._DetailsOption; } set { this._DetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InputDetailsOption { get; private set; } + + /// + /// Input details can also be provided recursively (deprecated). + /// + /// Input details can also be provided recursively (deprecated). + [JsonPropertyName("inputDetails")] + [Obsolete("")] + public List? InputDetails { get { return this._InputDetailsOption; } set { this._InputDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ItemSearchUrlOption { get; private set; } + + /// + /// In case of a select, the URL from which to query the items. + /// + /// In case of a select, the URL from which to query the items. + [JsonPropertyName("itemSearchUrl")] + public string? ItemSearchUrl { get { return this._ItemSearchUrlOption; } set { this._ItemSearchUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsOption { get; private set; } + + /// + /// In case of a select, the items to choose from. + /// + /// In case of a select, the items to choose from. + [JsonPropertyName("items")] + public List? Items { get { return this._ItemsOption; } set { this._ItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KeyOption { get; private set; } + + /// + /// The value to provide in the result. + /// + /// The value to provide in the result. + [JsonPropertyName("key")] + public string? Key { get { return this._KeyOption; } set { this._KeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OptionalOption { get; private set; } + + /// + /// True if this input value is optional. + /// + /// True if this input value is optional. + [JsonPropertyName("optional")] + public bool? Optional { get { return this._OptionalOption; } set { this._OptionalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the required input. + /// + /// The type of the required input. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The value can be pre-filled, if available. + /// + /// The value can be pre-filled, if available. + [JsonPropertyName("value")] + public string? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InputDetail {\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" Details: ").Append(Details).Append("\n"); + sb.Append(" InputDetails: ").Append(InputDetails).Append("\n"); + sb.Append(" ItemSearchUrl: ").Append(ItemSearchUrl).Append("\n"); + sb.Append(" Items: ").Append(Items).Append("\n"); + sb.Append(" Key: ").Append(Key).Append("\n"); + sb.Append(" Optional: ").Append(Optional).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InputDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InputDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> configuration = default; + Option?> details = default; + Option?> inputDetails = default; + Option itemSearchUrl = default; + Option?> items = default; + Option key = default; + Option optional = default; + Option type = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "configuration": + configuration = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "details": + details = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "inputDetails": + inputDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "itemSearchUrl": + itemSearchUrl = new Option(utf8JsonReader.GetString()!); + break; + case "items": + items = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "key": + key = new Option(utf8JsonReader.GetString()!); + break; + case "optional": + optional = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new InputDetail(configuration, details, inputDetails, itemSearchUrl, items, key, optional, type, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InputDetail inputDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, inputDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InputDetail inputDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (inputDetail._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, inputDetail.Configuration, jsonSerializerOptions); + } + if (inputDetail._DetailsOption.IsSet) + { + writer.WritePropertyName("details"); + JsonSerializer.Serialize(writer, inputDetail.Details, jsonSerializerOptions); + } + if (inputDetail._InputDetailsOption.IsSet) + { + writer.WritePropertyName("inputDetails"); + JsonSerializer.Serialize(writer, inputDetail.InputDetails, jsonSerializerOptions); + } + if (inputDetail._ItemSearchUrlOption.IsSet) + if (inputDetail.ItemSearchUrl != null) + writer.WriteString("itemSearchUrl", inputDetail.ItemSearchUrl); + + if (inputDetail._ItemsOption.IsSet) + { + writer.WritePropertyName("items"); + JsonSerializer.Serialize(writer, inputDetail.Items, jsonSerializerOptions); + } + if (inputDetail._KeyOption.IsSet) + if (inputDetail.Key != null) + writer.WriteString("key", inputDetail.Key); + + if (inputDetail._OptionalOption.IsSet) + writer.WriteBoolean("optional", inputDetail._OptionalOption.Value!.Value); + + if (inputDetail._TypeOption.IsSet) + if (inputDetail.Type != null) + writer.WriteString("type", inputDetail.Type); + + if (inputDetail._ValueOption.IsSet) + if (inputDetail.Value != null) + writer.WriteString("value", inputDetail.Value); + } + } +} diff --git a/Adyen/Checkout/Models/InstallmentOption.cs b/Adyen/Checkout/Models/InstallmentOption.cs new file mode 100644 index 000000000..9763d96fa --- /dev/null +++ b/Adyen/Checkout/Models/InstallmentOption.cs @@ -0,0 +1,427 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// InstallmentOption. + /// + public partial class InstallmentOption : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The maximum number of installments offered for this payment method. + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving** + /// Preselected number of installments offered for this payment method. + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + [JsonConstructor] + public InstallmentOption(Option maxValue = default, Option?> plans = default, Option preselectedValue = default, Option?> values = default) + { + _MaxValueOption = maxValue; + _PlansOption = plans; + _PreselectedValueOption = preselectedValue; + _ValuesOption = values; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InstallmentOption() + { + } + + partial void OnCreated(); + + /// + /// Defines Plans. + /// + [JsonConverter(typeof(PlansEnumJsonConverter))] + public class PlansEnum : IEnum + { + /// + /// Returns the value of the PlansEnum. + /// + public string? Value { get; set; } + + /// + /// PlansEnum.Bonus - bonus + /// + public static readonly PlansEnum Bonus = new("bonus"); + + /// + /// PlansEnum.BuynowPaylater - buynow_paylater + /// + public static readonly PlansEnum BuynowPaylater = new("buynow_paylater"); + + /// + /// PlansEnum.InteresRefundPrctg - interes_refund_prctg + /// + public static readonly PlansEnum InteresRefundPrctg = new("interes_refund_prctg"); + + /// + /// PlansEnum.InterestBonus - interest_bonus + /// + public static readonly PlansEnum InterestBonus = new("interest_bonus"); + + /// + /// PlansEnum.NointeresRefundPrctg - nointeres_refund_prctg + /// + public static readonly PlansEnum NointeresRefundPrctg = new("nointeres_refund_prctg"); + + /// + /// PlansEnum.NointerestBonus - nointerest_bonus + /// + public static readonly PlansEnum NointerestBonus = new("nointerest_bonus"); + + /// + /// PlansEnum.RefundPrctg - refund_prctg + /// + public static readonly PlansEnum RefundPrctg = new("refund_prctg"); + + /// + /// PlansEnum.Regular - regular + /// + public static readonly PlansEnum Regular = new("regular"); + + /// + /// PlansEnum.Revolving - revolving + /// + public static readonly PlansEnum Revolving = new("revolving"); + + /// + /// PlansEnum.WithInterest - with_interest + /// + public static readonly PlansEnum WithInterest = new("with_interest"); + + private PlansEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlansEnum?(string? value) => value == null ? null : new PlansEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlansEnum? option) => option?.Value; + + public static bool operator ==(PlansEnum? left, PlansEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlansEnum? left, PlansEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlansEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlansEnum? FromStringOrDefault(string value) + { + return value switch { + "bonus" => PlansEnum.Bonus, + "buynow_paylater" => PlansEnum.BuynowPaylater, + "interes_refund_prctg" => PlansEnum.InteresRefundPrctg, + "interest_bonus" => PlansEnum.InterestBonus, + "nointeres_refund_prctg" => PlansEnum.NointeresRefundPrctg, + "nointerest_bonus" => PlansEnum.NointerestBonus, + "refund_prctg" => PlansEnum.RefundPrctg, + "regular" => PlansEnum.Regular, + "revolving" => PlansEnum.Revolving, + "with_interest" => PlansEnum.WithInterest, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlansEnum? value) + { + if (value == null) + return null; + + if (value == PlansEnum.Bonus) + return "bonus"; + + if (value == PlansEnum.BuynowPaylater) + return "buynow_paylater"; + + if (value == PlansEnum.InteresRefundPrctg) + return "interes_refund_prctg"; + + if (value == PlansEnum.InterestBonus) + return "interest_bonus"; + + if (value == PlansEnum.NointeresRefundPrctg) + return "nointeres_refund_prctg"; + + if (value == PlansEnum.NointerestBonus) + return "nointerest_bonus"; + + if (value == PlansEnum.RefundPrctg) + return "refund_prctg"; + + if (value == PlansEnum.Regular) + return "regular"; + + if (value == PlansEnum.Revolving) + return "revolving"; + + if (value == PlansEnum.WithInterest) + return "with_interest"; + + return null; + } + + /// + /// JsonConverter for writing PlansEnum. + /// + public class PlansEnumJsonConverter : JsonConverter + { + public override PlansEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlansEnum.FromStringOrDefault(value) ?? new PlansEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlansEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlansEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxValueOption { get; private set; } + + /// + /// The maximum number of installments offered for this payment method. + /// + /// The maximum number of installments offered for this payment method. + [JsonPropertyName("maxValue")] + public int? MaxValue { get { return this._MaxValueOption; } set { this._MaxValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PlansOption { get; private set; } + + /// + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving** + /// + /// Defines the type of installment plan. If not set, defaults to **regular**. Possible values: * **regular** * **revolving** + [JsonPropertyName("plans")] + public List? Plans { get { return this._PlansOption; } set { this._PlansOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreselectedValueOption { get; private set; } + + /// + /// Preselected number of installments offered for this payment method. + /// + /// Preselected number of installments offered for this payment method. + [JsonPropertyName("preselectedValue")] + public int? PreselectedValue { get { return this._PreselectedValueOption; } set { this._PreselectedValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValuesOption { get; private set; } + + /// + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + /// + /// An array of the number of installments that the shopper can choose from. For example, **[2,3,5]**. This cannot be specified simultaneously with `maxValue`. + [JsonPropertyName("values")] + public List? Values { get { return this._ValuesOption; } set { this._ValuesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InstallmentOption {\n"); + sb.Append(" MaxValue: ").Append(MaxValue).Append("\n"); + sb.Append(" Plans: ").Append(Plans).Append("\n"); + sb.Append(" PreselectedValue: ").Append(PreselectedValue).Append("\n"); + sb.Append(" Values: ").Append(Values).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InstallmentOptionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InstallmentOption Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option maxValue = default; + Option?> plans = default; + Option preselectedValue = default; + Option?> values = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "maxValue": + maxValue = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "plans": + plans = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "preselectedValue": + preselectedValue = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "values": + values = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new InstallmentOption(maxValue, plans, preselectedValue, values); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InstallmentOption installmentOption, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, installmentOption, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InstallmentOption installmentOption, JsonSerializerOptions jsonSerializerOptions) + { + + if (installmentOption._MaxValueOption.IsSet) + writer.WriteNumber("maxValue", installmentOption._MaxValueOption.Value!.Value); + + if (installmentOption._PlansOption.IsSet) + { + writer.WritePropertyName("plans"); + JsonSerializer.Serialize(writer, installmentOption.Plans, jsonSerializerOptions); + } + if (installmentOption._PreselectedValueOption.IsSet) + writer.WriteNumber("preselectedValue", installmentOption._PreselectedValueOption.Value!.Value); + + if (installmentOption._ValuesOption.IsSet) + { + writer.WritePropertyName("values"); + JsonSerializer.Serialize(writer, installmentOption.Values, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/Installments.cs b/Adyen/Checkout/Models/Installments.cs new file mode 100644 index 000000000..564e48ba8 --- /dev/null +++ b/Adyen/Checkout/Models/Installments.cs @@ -0,0 +1,397 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Installments. + /// + public partial class Installments : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonConstructor] + public Installments(int value, Option extra = default, Option plan = default) + { + Value = value; + _ExtraOption = extra; + _PlanOption = plan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Installments() + { + } + + partial void OnCreated(); + + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonConverter(typeof(PlanEnumJsonConverter))] + public class PlanEnum : IEnum + { + /// + /// Returns the value of the PlanEnum. + /// + public string? Value { get; set; } + + /// + /// PlanEnum.Bonus - bonus + /// + public static readonly PlanEnum Bonus = new("bonus"); + + /// + /// PlanEnum.BuynowPaylater - buynow_paylater + /// + public static readonly PlanEnum BuynowPaylater = new("buynow_paylater"); + + /// + /// PlanEnum.InteresRefundPrctg - interes_refund_prctg + /// + public static readonly PlanEnum InteresRefundPrctg = new("interes_refund_prctg"); + + /// + /// PlanEnum.InterestBonus - interest_bonus + /// + public static readonly PlanEnum InterestBonus = new("interest_bonus"); + + /// + /// PlanEnum.NointeresRefundPrctg - nointeres_refund_prctg + /// + public static readonly PlanEnum NointeresRefundPrctg = new("nointeres_refund_prctg"); + + /// + /// PlanEnum.NointerestBonus - nointerest_bonus + /// + public static readonly PlanEnum NointerestBonus = new("nointerest_bonus"); + + /// + /// PlanEnum.RefundPrctg - refund_prctg + /// + public static readonly PlanEnum RefundPrctg = new("refund_prctg"); + + /// + /// PlanEnum.Regular - regular + /// + public static readonly PlanEnum Regular = new("regular"); + + /// + /// PlanEnum.Revolving - revolving + /// + public static readonly PlanEnum Revolving = new("revolving"); + + /// + /// PlanEnum.WithInterest - with_interest + /// + public static readonly PlanEnum WithInterest = new("with_interest"); + + private PlanEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlanEnum?(string? value) => value == null ? null : new PlanEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlanEnum? option) => option?.Value; + + public static bool operator ==(PlanEnum? left, PlanEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlanEnum? left, PlanEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlanEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlanEnum? FromStringOrDefault(string value) + { + return value switch { + "bonus" => PlanEnum.Bonus, + "buynow_paylater" => PlanEnum.BuynowPaylater, + "interes_refund_prctg" => PlanEnum.InteresRefundPrctg, + "interest_bonus" => PlanEnum.InterestBonus, + "nointeres_refund_prctg" => PlanEnum.NointeresRefundPrctg, + "nointerest_bonus" => PlanEnum.NointerestBonus, + "refund_prctg" => PlanEnum.RefundPrctg, + "regular" => PlanEnum.Regular, + "revolving" => PlanEnum.Revolving, + "with_interest" => PlanEnum.WithInterest, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlanEnum? value) + { + if (value == null) + return null; + + if (value == PlanEnum.Bonus) + return "bonus"; + + if (value == PlanEnum.BuynowPaylater) + return "buynow_paylater"; + + if (value == PlanEnum.InteresRefundPrctg) + return "interes_refund_prctg"; + + if (value == PlanEnum.InterestBonus) + return "interest_bonus"; + + if (value == PlanEnum.NointeresRefundPrctg) + return "nointeres_refund_prctg"; + + if (value == PlanEnum.NointerestBonus) + return "nointerest_bonus"; + + if (value == PlanEnum.RefundPrctg) + return "refund_prctg"; + + if (value == PlanEnum.Regular) + return "regular"; + + if (value == PlanEnum.Revolving) + return "revolving"; + + if (value == PlanEnum.WithInterest) + return "with_interest"; + + return null; + } + + /// + /// JsonConverter for writing PlanEnum. + /// + public class PlanEnumJsonConverter : JsonConverter + { + public override PlanEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlanEnum.FromStringOrDefault(value) ?? new PlanEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlanEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlanEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlanOption { get; private set; } + + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonPropertyName("plan")] + public PlanEnum? Plan { get { return this._PlanOption; } set { this._PlanOption = new(value); } } + + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + [JsonPropertyName("value")] + public int Value { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraOption { get; private set; } + + /// + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + /// + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + [JsonPropertyName("extra")] + public int? Extra { get { return this._ExtraOption; } set { this._ExtraOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Installments {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Extra: ").Append(Extra).Append("\n"); + sb.Append(" Plan: ").Append(Plan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InstallmentsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Installments Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option value = default; + Option extra = default; + Option plan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "extra": + extra = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "plan": + string? planRawValue = utf8JsonReader.GetString(); + plan = new Option(Installments.PlanEnum.FromStringOrDefault(planRawValue)); + break; + default: + break; + } + } + } + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Installments.", nameof(value)); + + return new Installments(value.Value!.Value!, extra, plan); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Installments installments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, installments, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Installments installments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("value", installments.Value); + + if (installments._ExtraOption.IsSet) + writer.WriteNumber("extra", installments._ExtraOption.Value!.Value); + + if (installments._PlanOption.IsSet && installments.Plan != null) + { + string? planRawValue = Installments.PlanEnum.ToJsonValue(installments._PlanOption.Value!.Value); + writer.WriteString("plan", planRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/InvalidField.cs b/Adyen/Checkout/Models/InvalidField.cs new file mode 100644 index 000000000..954878ebe --- /dev/null +++ b/Adyen/Checkout/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The field that has an invalid value. + /// The invalid value. + /// Description of the validation error. + [JsonConstructor] + public InvalidField(string name, string value, string message) + { + Name = name; + Value = value; + Message = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option value = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + return new InvalidField(name.Value!, value.Value!, message.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + } + } +} diff --git a/Adyen/Checkout/Models/Item.cs b/Adyen/Checkout/Models/Item.cs new file mode 100644 index 000000000..cdab7cf2b --- /dev/null +++ b/Adyen/Checkout/Models/Item.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Item. + /// + public partial class Item : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value to provide in the result. + /// The display name. + [JsonConstructor] + public Item(Option id = default, Option name = default) + { + _IdOption = id; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Item() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The value to provide in the result. + /// + /// The value to provide in the result. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The display name. + /// + /// The display name. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Item {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ItemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Item Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Item(id, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Item item, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, item, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Item item, JsonSerializerOptions jsonSerializerOptions) + { + + if (item._IdOption.IsSet) + if (item.Id != null) + writer.WriteString("id", item.Id); + + if (item._NameOption.IsSet) + if (item.Name != null) + writer.WriteString("name", item.Name); + } + } +} diff --git a/Adyen/Checkout/Models/KlarnaDetails.cs b/Adyen/Checkout/Models/KlarnaDetails.cs new file mode 100644 index 000000000..0a9ec4888 --- /dev/null +++ b/Adyen/Checkout/Models/KlarnaDetails.cs @@ -0,0 +1,505 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// KlarnaDetails. + /// + public partial class KlarnaDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address where to send the invoice. + /// The checkout attempt identifier. + /// The address where the goods should be delivered. + /// Shopper name, date of birth, phone number, and email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The type of flow to initiate. + /// **klarna** (default to TypeEnum.Klarna) + [JsonConstructor] + public KlarnaDetails(Option billingAddress = default, Option checkoutAttemptId = default, Option deliveryAddress = default, Option personalDetails = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option subtype = default, TypeEnum type = default) + { + _BillingAddressOption = billingAddress; + _CheckoutAttemptIdOption = checkoutAttemptId; + _DeliveryAddressOption = deliveryAddress; + _PersonalDetailsOption = personalDetails; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubtypeOption = subtype; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public KlarnaDetails() + { + } + + partial void OnCreated(); + + /// + /// **klarna** + /// + /// **klarna** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Klarna - klarna + /// + public static readonly TypeEnum Klarna = new("klarna"); + + /// + /// TypeEnum.Klarnapayments - klarnapayments + /// + public static readonly TypeEnum Klarnapayments = new("klarnapayments"); + + /// + /// TypeEnum.KlarnapaymentsAccount - klarnapayments_account + /// + public static readonly TypeEnum KlarnapaymentsAccount = new("klarnapayments_account"); + + /// + /// TypeEnum.KlarnapaymentsB2b - klarnapayments_b2b + /// + public static readonly TypeEnum KlarnapaymentsB2b = new("klarnapayments_b2b"); + + /// + /// TypeEnum.KlarnaPaynow - klarna_paynow + /// + public static readonly TypeEnum KlarnaPaynow = new("klarna_paynow"); + + /// + /// TypeEnum.KlarnaAccount - klarna_account + /// + public static readonly TypeEnum KlarnaAccount = new("klarna_account"); + + /// + /// TypeEnum.KlarnaB2b - klarna_b2b + /// + public static readonly TypeEnum KlarnaB2b = new("klarna_b2b"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "klarna" => TypeEnum.Klarna, + "klarnapayments" => TypeEnum.Klarnapayments, + "klarnapayments_account" => TypeEnum.KlarnapaymentsAccount, + "klarnapayments_b2b" => TypeEnum.KlarnapaymentsB2b, + "klarna_paynow" => TypeEnum.KlarnaPaynow, + "klarna_account" => TypeEnum.KlarnaAccount, + "klarna_b2b" => TypeEnum.KlarnaB2b, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Klarna) + return "klarna"; + + if (value == TypeEnum.Klarnapayments) + return "klarnapayments"; + + if (value == TypeEnum.KlarnapaymentsAccount) + return "klarnapayments_account"; + + if (value == TypeEnum.KlarnapaymentsB2b) + return "klarnapayments_b2b"; + + if (value == TypeEnum.KlarnaPaynow) + return "klarna_paynow"; + + if (value == TypeEnum.KlarnaAccount) + return "klarna_account"; + + if (value == TypeEnum.KlarnaB2b) + return "klarna_b2b"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **klarna** + /// + /// **klarna** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// The address where to send the invoice. + /// + /// The address where to send the invoice. + [JsonPropertyName("billingAddress")] + public string? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// The address where the goods should be delivered. + /// + /// The address where the goods should be delivered. + [JsonPropertyName("deliveryAddress")] + public string? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PersonalDetailsOption { get; private set; } + + /// + /// Shopper name, date of birth, phone number, and email address. + /// + /// Shopper name, date of birth, phone number, and email address. + [JsonPropertyName("personalDetails")] + public string? PersonalDetails { get { return this._PersonalDetailsOption; } set { this._PersonalDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// The type of flow to initiate. + /// + /// The type of flow to initiate. + [JsonPropertyName("subtype")] + public string? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class KlarnaDetails {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class KlarnaDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override KlarnaDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option checkoutAttemptId = default; + Option deliveryAddress = default; + Option personalDetails = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option subtype = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryAddress": + deliveryAddress = new Option(utf8JsonReader.GetString()!); + break; + case "personalDetails": + personalDetails = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + subtype = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(KlarnaDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class KlarnaDetails.", nameof(type)); + + return new KlarnaDetails(billingAddress, checkoutAttemptId, deliveryAddress, personalDetails, recurringDetailReference, storedPaymentMethodId, subtype, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, KlarnaDetails klarnaDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, klarnaDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, KlarnaDetails klarnaDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (klarnaDetails._BillingAddressOption.IsSet) + if (klarnaDetails.BillingAddress != null) + writer.WriteString("billingAddress", klarnaDetails.BillingAddress); + + if (klarnaDetails._CheckoutAttemptIdOption.IsSet) + if (klarnaDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", klarnaDetails.CheckoutAttemptId); + + if (klarnaDetails._DeliveryAddressOption.IsSet) + if (klarnaDetails.DeliveryAddress != null) + writer.WriteString("deliveryAddress", klarnaDetails.DeliveryAddress); + + if (klarnaDetails._PersonalDetailsOption.IsSet) + if (klarnaDetails.PersonalDetails != null) + writer.WriteString("personalDetails", klarnaDetails.PersonalDetails); + + if (klarnaDetails._RecurringDetailReferenceOption.IsSet) + if (klarnaDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", klarnaDetails.RecurringDetailReference); + + if (klarnaDetails._StoredPaymentMethodIdOption.IsSet) + if (klarnaDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", klarnaDetails.StoredPaymentMethodId); + + if (klarnaDetails._SubtypeOption.IsSet) + if (klarnaDetails.Subtype != null) + writer.WriteString("subtype", klarnaDetails.Subtype); + + if (klarnaDetails.Type != null) + { + string? typeRawValue = KlarnaDetails.TypeEnum.ToJsonValue(klarnaDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Leg.cs b/Adyen/Checkout/Models/Leg.cs new file mode 100644 index 000000000..eeba5318d --- /dev/null +++ b/Adyen/Checkout/Models/Leg.cs @@ -0,0 +1,380 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Leg. + /// + public partial class Leg : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not start with a space or be all spaces. * Must not be all zeros. + /// Date and time of travel in format `yyyy-MM-ddTHH:mm`. * Use local time of departure airport. * minLength: 16 characters * maxLength: 16 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 11 * Must not be all zeros. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + [JsonConstructor] + public Leg(Option carrierCode = default, Option classOfTravel = default, Option dateOfTravel = default, Option departureAirportCode = default, Option departureTax = default, Option destinationAirportCode = default, Option fareBasisCode = default, Option flightNumber = default, Option stopOverCode = default) + { + _CarrierCodeOption = carrierCode; + _ClassOfTravelOption = classOfTravel; + _DateOfTravelOption = dateOfTravel; + _DepartureAirportCodeOption = departureAirportCode; + _DepartureTaxOption = departureTax; + _DestinationAirportCodeOption = destinationAirportCode; + _FareBasisCodeOption = fareBasisCode; + _FlightNumberOption = flightNumber; + _StopOverCodeOption = stopOverCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Leg() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("carrierCode")] + public string? CarrierCode { get { return this._CarrierCodeOption; } set { this._CarrierCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClassOfTravelOption { get; private set; } + + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("classOfTravel")] + public string? ClassOfTravel { get { return this._ClassOfTravelOption; } set { this._ClassOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfTravelOption { get; private set; } + + /// + /// Date and time of travel in format `yyyy-MM-ddTHH:mm`. * Use local time of departure airport. * minLength: 16 characters * maxLength: 16 characters + /// + /// Date and time of travel in format `yyyy-MM-ddTHH:mm`. * Use local time of departure airport. * minLength: 16 characters * maxLength: 16 characters + [JsonPropertyName("dateOfTravel")] + public DateTimeOffset? DateOfTravel { get { return this._DateOfTravelOption; } set { this._DateOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureAirportCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("departureAirportCode")] + public string? DepartureAirportCode { get { return this._DepartureAirportCodeOption; } set { this._DepartureAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureTaxOption { get; private set; } + + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 11 * Must not be all zeros. + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 11 * Must not be all zeros. + [JsonPropertyName("departureTax")] + public long? DepartureTax { get { return this._DepartureTaxOption; } set { this._DepartureTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DestinationAirportCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("destinationAirportCode")] + public string? DestinationAirportCode { get { return this._DestinationAirportCodeOption; } set { this._DestinationAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FareBasisCodeOption { get; private set; } + + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("fareBasisCode")] + public string? FareBasisCode { get { return this._FareBasisCodeOption; } set { this._FareBasisCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FlightNumberOption { get; private set; } + + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("flightNumber")] + public string? FlightNumber { get { return this._FlightNumberOption; } set { this._FlightNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StopOverCodeOption { get; private set; } + + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + [JsonPropertyName("stopOverCode")] + public string? StopOverCode { get { return this._StopOverCodeOption; } set { this._StopOverCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Leg {\n"); + sb.Append(" CarrierCode: ").Append(CarrierCode).Append("\n"); + sb.Append(" ClassOfTravel: ").Append(ClassOfTravel).Append("\n"); + sb.Append(" DateOfTravel: ").Append(DateOfTravel).Append("\n"); + sb.Append(" DepartureAirportCode: ").Append(DepartureAirportCode).Append("\n"); + sb.Append(" DepartureTax: ").Append(DepartureTax).Append("\n"); + sb.Append(" DestinationAirportCode: ").Append(DestinationAirportCode).Append("\n"); + sb.Append(" FareBasisCode: ").Append(FareBasisCode).Append("\n"); + sb.Append(" FlightNumber: ").Append(FlightNumber).Append("\n"); + sb.Append(" StopOverCode: ").Append(StopOverCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfTravel. + /// + public static string DateOfTravelFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Leg Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option carrierCode = default; + Option classOfTravel = default; + Option dateOfTravel = default; + Option departureAirportCode = default; + Option departureTax = default; + Option destinationAirportCode = default; + Option fareBasisCode = default; + Option flightNumber = default; + Option stopOverCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "carrierCode": + carrierCode = new Option(utf8JsonReader.GetString()!); + break; + case "classOfTravel": + classOfTravel = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfTravel": + dateOfTravel = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "departureAirportCode": + departureAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "departureTax": + departureTax = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "destinationAirportCode": + destinationAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "fareBasisCode": + fareBasisCode = new Option(utf8JsonReader.GetString()!); + break; + case "flightNumber": + flightNumber = new Option(utf8JsonReader.GetString()!); + break; + case "stopOverCode": + stopOverCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Leg(carrierCode, classOfTravel, dateOfTravel, departureAirportCode, departureTax, destinationAirportCode, fareBasisCode, flightNumber, stopOverCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, leg, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + if (leg._CarrierCodeOption.IsSet) + if (leg.CarrierCode != null) + writer.WriteString("carrierCode", leg.CarrierCode); + + if (leg._ClassOfTravelOption.IsSet) + if (leg.ClassOfTravel != null) + writer.WriteString("classOfTravel", leg.ClassOfTravel); + + if (leg._DateOfTravelOption.IsSet) + writer.WriteString("dateOfTravel", leg._DateOfTravelOption.Value!.Value.ToString(DateOfTravelFormat)); + + if (leg._DepartureAirportCodeOption.IsSet) + if (leg.DepartureAirportCode != null) + writer.WriteString("departureAirportCode", leg.DepartureAirportCode); + + if (leg._DepartureTaxOption.IsSet) + writer.WriteNumber("departureTax", leg._DepartureTaxOption.Value!.Value); + + if (leg._DestinationAirportCodeOption.IsSet) + if (leg.DestinationAirportCode != null) + writer.WriteString("destinationAirportCode", leg.DestinationAirportCode); + + if (leg._FareBasisCodeOption.IsSet) + if (leg.FareBasisCode != null) + writer.WriteString("fareBasisCode", leg.FareBasisCode); + + if (leg._FlightNumberOption.IsSet) + if (leg.FlightNumber != null) + writer.WriteString("flightNumber", leg.FlightNumber); + + if (leg._StopOverCodeOption.IsSet) + if (leg.StopOverCode != null) + writer.WriteString("stopOverCode", leg.StopOverCode); + } + } +} diff --git a/Adyen/Checkout/Models/LineItem.cs b/Adyen/Checkout/Models/LineItem.cs new file mode 100644 index 000000000..967fcacca --- /dev/null +++ b/Adyen/Checkout/Models/LineItem.cs @@ -0,0 +1,603 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// LineItem. + /// + public partial class LineItem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Item amount excluding the tax, in minor units. + /// Item amount including the tax, in minor units. + /// Brand of the item. + /// Color of the item. + /// Description of the line item. + /// ID of the line item. + /// Link to the picture of the purchased item. + /// Item category, used by the payment methods PayPal and Ratepay. + /// Manufacturer of the item. + /// Marketplace seller id. + /// Link to the purchased item. + /// Number of items. + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// Size of the item. + /// Stock keeping unit. + /// Tax amount, in minor units. + /// Tax percentage, in minor units. + /// Universal Product Code. + [JsonConstructor] + public LineItem(Option amountExcludingTax = default, Option amountIncludingTax = default, Option brand = default, Option color = default, Option description = default, Option id = default, Option imageUrl = default, Option itemCategory = default, Option manufacturer = default, Option marketplaceSellerId = default, Option productUrl = default, Option quantity = default, Option receiverEmail = default, Option size = default, Option sku = default, Option taxAmount = default, Option taxPercentage = default, Option upc = default) + { + _AmountExcludingTaxOption = amountExcludingTax; + _AmountIncludingTaxOption = amountIncludingTax; + _BrandOption = brand; + _ColorOption = color; + _DescriptionOption = description; + _IdOption = id; + _ImageUrlOption = imageUrl; + _ItemCategoryOption = itemCategory; + _ManufacturerOption = manufacturer; + _MarketplaceSellerIdOption = marketplaceSellerId; + _ProductUrlOption = productUrl; + _QuantityOption = quantity; + _ReceiverEmailOption = receiverEmail; + _SizeOption = size; + _SkuOption = sku; + _TaxAmountOption = taxAmount; + _TaxPercentageOption = taxPercentage; + _UpcOption = upc; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LineItem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountExcludingTaxOption { get; private set; } + + /// + /// Item amount excluding the tax, in minor units. + /// + /// Item amount excluding the tax, in minor units. + [JsonPropertyName("amountExcludingTax")] + public long? AmountExcludingTax { get { return this._AmountExcludingTaxOption; } set { this._AmountExcludingTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountIncludingTaxOption { get; private set; } + + /// + /// Item amount including the tax, in minor units. + /// + /// Item amount including the tax, in minor units. + [JsonPropertyName("amountIncludingTax")] + public long? AmountIncludingTax { get { return this._AmountIncludingTaxOption; } set { this._AmountIncludingTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Brand of the item. + /// + /// Brand of the item. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ColorOption { get; private set; } + + /// + /// Color of the item. + /// + /// Color of the item. + [JsonPropertyName("color")] + public string? Color { get { return this._ColorOption; } set { this._ColorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the line item. + /// + /// Description of the line item. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// ID of the line item. + /// + /// ID of the line item. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ImageUrlOption { get; private set; } + + /// + /// Link to the picture of the purchased item. + /// + /// Link to the picture of the purchased item. + [JsonPropertyName("imageUrl")] + public string? ImageUrl { get { return this._ImageUrlOption; } set { this._ImageUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ItemCategoryOption { get; private set; } + + /// + /// Item category, used by the payment methods PayPal and Ratepay. + /// + /// Item category, used by the payment methods PayPal and Ratepay. + [JsonPropertyName("itemCategory")] + public string? ItemCategory { get { return this._ItemCategoryOption; } set { this._ItemCategoryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ManufacturerOption { get; private set; } + + /// + /// Manufacturer of the item. + /// + /// Manufacturer of the item. + [JsonPropertyName("manufacturer")] + public string? Manufacturer { get { return this._ManufacturerOption; } set { this._ManufacturerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MarketplaceSellerIdOption { get; private set; } + + /// + /// Marketplace seller id. + /// + /// Marketplace seller id. + [JsonPropertyName("marketplaceSellerId")] + public string? MarketplaceSellerId { get { return this._MarketplaceSellerIdOption; } set { this._MarketplaceSellerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProductUrlOption { get; private set; } + + /// + /// Link to the purchased item. + /// + /// Link to the purchased item. + [JsonPropertyName("productUrl")] + public string? ProductUrl { get { return this._ProductUrlOption; } set { this._ProductUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _QuantityOption { get; private set; } + + /// + /// Number of items. + /// + /// Number of items. + [JsonPropertyName("quantity")] + public long? Quantity { get { return this._QuantityOption; } set { this._QuantityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiverEmailOption { get; private set; } + + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + [JsonPropertyName("receiverEmail")] + public string? ReceiverEmail { get { return this._ReceiverEmailOption; } set { this._ReceiverEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SizeOption { get; private set; } + + /// + /// Size of the item. + /// + /// Size of the item. + [JsonPropertyName("size")] + public string? Size { get { return this._SizeOption; } set { this._SizeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SkuOption { get; private set; } + + /// + /// Stock keeping unit. + /// + /// Stock keeping unit. + [JsonPropertyName("sku")] + public string? Sku { get { return this._SkuOption; } set { this._SkuOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxAmountOption { get; private set; } + + /// + /// Tax amount, in minor units. + /// + /// Tax amount, in minor units. + [JsonPropertyName("taxAmount")] + public long? TaxAmount { get { return this._TaxAmountOption; } set { this._TaxAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxPercentageOption { get; private set; } + + /// + /// Tax percentage, in minor units. + /// + /// Tax percentage, in minor units. + [JsonPropertyName("taxPercentage")] + public long? TaxPercentage { get { return this._TaxPercentageOption; } set { this._TaxPercentageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpcOption { get; private set; } + + /// + /// Universal Product Code. + /// + /// Universal Product Code. + [JsonPropertyName("upc")] + public string? Upc { get { return this._UpcOption; } set { this._UpcOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LineItem {\n"); + sb.Append(" AmountExcludingTax: ").Append(AmountExcludingTax).Append("\n"); + sb.Append(" AmountIncludingTax: ").Append(AmountIncludingTax).Append("\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n"); + sb.Append(" ItemCategory: ").Append(ItemCategory).Append("\n"); + sb.Append(" Manufacturer: ").Append(Manufacturer).Append("\n"); + sb.Append(" MarketplaceSellerId: ").Append(MarketplaceSellerId).Append("\n"); + sb.Append(" ProductUrl: ").Append(ProductUrl).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ReceiverEmail: ").Append(ReceiverEmail).Append("\n"); + sb.Append(" Size: ").Append(Size).Append("\n"); + sb.Append(" Sku: ").Append(Sku).Append("\n"); + sb.Append(" TaxAmount: ").Append(TaxAmount).Append("\n"); + sb.Append(" TaxPercentage: ").Append(TaxPercentage).Append("\n"); + sb.Append(" Upc: ").Append(Upc).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 10000) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 10000.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LineItemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LineItem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amountExcludingTax = default; + Option amountIncludingTax = default; + Option brand = default; + Option color = default; + Option description = default; + Option id = default; + Option imageUrl = default; + Option itemCategory = default; + Option manufacturer = default; + Option marketplaceSellerId = default; + Option productUrl = default; + Option quantity = default; + Option receiverEmail = default; + Option size = default; + Option sku = default; + Option taxAmount = default; + Option taxPercentage = default; + Option upc = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amountExcludingTax": + amountExcludingTax = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "amountIncludingTax": + amountIncludingTax = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "color": + color = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "imageUrl": + imageUrl = new Option(utf8JsonReader.GetString()!); + break; + case "itemCategory": + itemCategory = new Option(utf8JsonReader.GetString()!); + break; + case "manufacturer": + manufacturer = new Option(utf8JsonReader.GetString()!); + break; + case "marketplaceSellerId": + marketplaceSellerId = new Option(utf8JsonReader.GetString()!); + break; + case "productUrl": + productUrl = new Option(utf8JsonReader.GetString()!); + break; + case "quantity": + quantity = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "receiverEmail": + receiverEmail = new Option(utf8JsonReader.GetString()!); + break; + case "size": + size = new Option(utf8JsonReader.GetString()!); + break; + case "sku": + sku = new Option(utf8JsonReader.GetString()!); + break; + case "taxAmount": + taxAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "taxPercentage": + taxPercentage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "upc": + upc = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new LineItem(amountExcludingTax, amountIncludingTax, brand, color, description, id, imageUrl, itemCategory, manufacturer, marketplaceSellerId, productUrl, quantity, receiverEmail, size, sku, taxAmount, taxPercentage, upc); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LineItem lineItem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, lineItem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LineItem lineItem, JsonSerializerOptions jsonSerializerOptions) + { + + if (lineItem._AmountExcludingTaxOption.IsSet) + writer.WriteNumber("amountExcludingTax", lineItem._AmountExcludingTaxOption.Value!.Value); + + if (lineItem._AmountIncludingTaxOption.IsSet) + writer.WriteNumber("amountIncludingTax", lineItem._AmountIncludingTaxOption.Value!.Value); + + if (lineItem._BrandOption.IsSet) + if (lineItem.Brand != null) + writer.WriteString("brand", lineItem.Brand); + + if (lineItem._ColorOption.IsSet) + if (lineItem.Color != null) + writer.WriteString("color", lineItem.Color); + + if (lineItem._DescriptionOption.IsSet) + if (lineItem.Description != null) + writer.WriteString("description", lineItem.Description); + + if (lineItem._IdOption.IsSet) + if (lineItem.Id != null) + writer.WriteString("id", lineItem.Id); + + if (lineItem._ImageUrlOption.IsSet) + if (lineItem.ImageUrl != null) + writer.WriteString("imageUrl", lineItem.ImageUrl); + + if (lineItem._ItemCategoryOption.IsSet) + if (lineItem.ItemCategory != null) + writer.WriteString("itemCategory", lineItem.ItemCategory); + + if (lineItem._ManufacturerOption.IsSet) + if (lineItem.Manufacturer != null) + writer.WriteString("manufacturer", lineItem.Manufacturer); + + if (lineItem._MarketplaceSellerIdOption.IsSet) + if (lineItem.MarketplaceSellerId != null) + writer.WriteString("marketplaceSellerId", lineItem.MarketplaceSellerId); + + if (lineItem._ProductUrlOption.IsSet) + if (lineItem.ProductUrl != null) + writer.WriteString("productUrl", lineItem.ProductUrl); + + if (lineItem._QuantityOption.IsSet) + writer.WriteNumber("quantity", lineItem._QuantityOption.Value!.Value); + + if (lineItem._ReceiverEmailOption.IsSet) + if (lineItem.ReceiverEmail != null) + writer.WriteString("receiverEmail", lineItem.ReceiverEmail); + + if (lineItem._SizeOption.IsSet) + if (lineItem.Size != null) + writer.WriteString("size", lineItem.Size); + + if (lineItem._SkuOption.IsSet) + if (lineItem.Sku != null) + writer.WriteString("sku", lineItem.Sku); + + if (lineItem._TaxAmountOption.IsSet) + writer.WriteNumber("taxAmount", lineItem._TaxAmountOption.Value!.Value); + + if (lineItem._TaxPercentageOption.IsSet) + writer.WriteNumber("taxPercentage", lineItem._TaxPercentageOption.Value!.Value); + + if (lineItem._UpcOption.IsSet) + if (lineItem.Upc != null) + writer.WriteString("upc", lineItem.Upc); + } + } +} diff --git a/Adyen/Checkout/Models/ListStoredPaymentMethodsResponse.cs b/Adyen/Checkout/Models/ListStoredPaymentMethodsResponse.cs new file mode 100644 index 000000000..eb9307b4e --- /dev/null +++ b/Adyen/Checkout/Models/ListStoredPaymentMethodsResponse.cs @@ -0,0 +1,229 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ListStoredPaymentMethodsResponse. + /// + public partial class ListStoredPaymentMethodsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your merchant account. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// List of all stored payment methods. + [JsonConstructor] + public ListStoredPaymentMethodsResponse(Option merchantAccount = default, Option shopperReference = default, Option?> storedPaymentMethods = default) + { + _MerchantAccountOption = merchantAccount; + _ShopperReferenceOption = shopperReference; + _StoredPaymentMethodsOption = storedPaymentMethods; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListStoredPaymentMethodsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// Your merchant account. + /// + /// Your merchant account. + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _StoredPaymentMethodsOption { get; private set; } + + /// + /// List of all stored payment methods. + /// + /// List of all stored payment methods. + [JsonPropertyName("storedPaymentMethods")] + public List? StoredPaymentMethods { get { return this._StoredPaymentMethodsOption; } set { this._StoredPaymentMethodsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListStoredPaymentMethodsResponse {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" StoredPaymentMethods: ").Append(StoredPaymentMethods).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListStoredPaymentMethodsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListStoredPaymentMethodsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option shopperReference = default; + Option?> storedPaymentMethods = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethods": + storedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ListStoredPaymentMethodsResponse(merchantAccount, shopperReference, storedPaymentMethods); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListStoredPaymentMethodsResponse listStoredPaymentMethodsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listStoredPaymentMethodsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListStoredPaymentMethodsResponse listStoredPaymentMethodsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (listStoredPaymentMethodsResponse._MerchantAccountOption.IsSet) + if (listStoredPaymentMethodsResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", listStoredPaymentMethodsResponse.MerchantAccount); + + if (listStoredPaymentMethodsResponse._ShopperReferenceOption.IsSet) + if (listStoredPaymentMethodsResponse.ShopperReference != null) + writer.WriteString("shopperReference", listStoredPaymentMethodsResponse.ShopperReference); + + if (listStoredPaymentMethodsResponse._StoredPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("storedPaymentMethods"); + JsonSerializer.Serialize(writer, listStoredPaymentMethodsResponse.StoredPaymentMethods, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/Mandate.cs b/Adyen/Checkout/Models/Mandate.cs new file mode 100644 index 000000000..fe8db427e --- /dev/null +++ b/Adyen/Checkout/Models/Mandate.cs @@ -0,0 +1,743 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Mandate. + /// + public partial class Mandate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The billing amount (in minor units) of the recurring transactions. + /// End date of the billing plan, in YYYY-MM-DD format. + /// The frequency with which a shopper should be charged. Possible values: **adhoc**, **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + /// The number of transactions that can be performed within the given frequency. + /// The message shown by UPI to the shopper on the approval screen. + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + [JsonConstructor] + public Mandate(string amount, string endsAt, FrequencyEnum frequency, Option amountRule = default, Option billingAttemptsRule = default, Option billingDay = default, Option count = default, Option remarks = default, Option startsAt = default) + { + Amount = amount; + EndsAt = endsAt; + Frequency = frequency; + _AmountRuleOption = amountRule; + _BillingAttemptsRuleOption = billingAttemptsRule; + _BillingDayOption = billingDay; + _CountOption = count; + _RemarksOption = remarks; + _StartsAtOption = startsAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Mandate() + { + } + + partial void OnCreated(); + + /// + /// The frequency with which a shopper should be charged. Possible values: **adhoc**, **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// + /// The frequency with which a shopper should be charged. Possible values: **adhoc**, **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + [JsonConverter(typeof(FrequencyEnumJsonConverter))] + public class FrequencyEnum : IEnum + { + /// + /// Returns the value of the FrequencyEnum. + /// + public string? Value { get; set; } + + /// + /// FrequencyEnum.Adhoc - adhoc + /// + public static readonly FrequencyEnum Adhoc = new("adhoc"); + + /// + /// FrequencyEnum.Daily - daily + /// + public static readonly FrequencyEnum Daily = new("daily"); + + /// + /// FrequencyEnum.Weekly - weekly + /// + public static readonly FrequencyEnum Weekly = new("weekly"); + + /// + /// FrequencyEnum.BiWeekly - biWeekly + /// + public static readonly FrequencyEnum BiWeekly = new("biWeekly"); + + /// + /// FrequencyEnum.Monthly - monthly + /// + public static readonly FrequencyEnum Monthly = new("monthly"); + + /// + /// FrequencyEnum.Quarterly - quarterly + /// + public static readonly FrequencyEnum Quarterly = new("quarterly"); + + /// + /// FrequencyEnum.HalfYearly - halfYearly + /// + public static readonly FrequencyEnum HalfYearly = new("halfYearly"); + + /// + /// FrequencyEnum.Yearly - yearly + /// + public static readonly FrequencyEnum Yearly = new("yearly"); + + private FrequencyEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FrequencyEnum?(string? value) => value == null ? null : new FrequencyEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FrequencyEnum? option) => option?.Value; + + public static bool operator ==(FrequencyEnum? left, FrequencyEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FrequencyEnum? left, FrequencyEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FrequencyEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FrequencyEnum? FromStringOrDefault(string value) + { + return value switch { + "adhoc" => FrequencyEnum.Adhoc, + "daily" => FrequencyEnum.Daily, + "weekly" => FrequencyEnum.Weekly, + "biWeekly" => FrequencyEnum.BiWeekly, + "monthly" => FrequencyEnum.Monthly, + "quarterly" => FrequencyEnum.Quarterly, + "halfYearly" => FrequencyEnum.HalfYearly, + "yearly" => FrequencyEnum.Yearly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FrequencyEnum? value) + { + if (value == null) + return null; + + if (value == FrequencyEnum.Adhoc) + return "adhoc"; + + if (value == FrequencyEnum.Daily) + return "daily"; + + if (value == FrequencyEnum.Weekly) + return "weekly"; + + if (value == FrequencyEnum.BiWeekly) + return "biWeekly"; + + if (value == FrequencyEnum.Monthly) + return "monthly"; + + if (value == FrequencyEnum.Quarterly) + return "quarterly"; + + if (value == FrequencyEnum.HalfYearly) + return "halfYearly"; + + if (value == FrequencyEnum.Yearly) + return "yearly"; + + return null; + } + + /// + /// JsonConverter for writing FrequencyEnum. + /// + public class FrequencyEnumJsonConverter : JsonConverter + { + public override FrequencyEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FrequencyEnum.FromStringOrDefault(value) ?? new FrequencyEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FrequencyEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FrequencyEnum.ToJsonValue(value)); + } + } + } + + /// + /// The frequency with which a shopper should be charged. Possible values: **adhoc**, **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// + /// The frequency with which a shopper should be charged. Possible values: **adhoc**, **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + [JsonPropertyName("frequency")] + public FrequencyEnum Frequency { get; set; } + + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + [JsonConverter(typeof(AmountRuleEnumJsonConverter))] + public class AmountRuleEnum : IEnum + { + /// + /// Returns the value of the AmountRuleEnum. + /// + public string? Value { get; set; } + + /// + /// AmountRuleEnum.Max - max + /// + public static readonly AmountRuleEnum Max = new("max"); + + /// + /// AmountRuleEnum.Exact - exact + /// + public static readonly AmountRuleEnum Exact = new("exact"); + + private AmountRuleEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AmountRuleEnum?(string? value) => value == null ? null : new AmountRuleEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AmountRuleEnum? option) => option?.Value; + + public static bool operator ==(AmountRuleEnum? left, AmountRuleEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AmountRuleEnum? left, AmountRuleEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AmountRuleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AmountRuleEnum? FromStringOrDefault(string value) + { + return value switch { + "max" => AmountRuleEnum.Max, + "exact" => AmountRuleEnum.Exact, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AmountRuleEnum? value) + { + if (value == null) + return null; + + if (value == AmountRuleEnum.Max) + return "max"; + + if (value == AmountRuleEnum.Exact) + return "exact"; + + return null; + } + + /// + /// JsonConverter for writing AmountRuleEnum. + /// + public class AmountRuleEnumJsonConverter : JsonConverter + { + public override AmountRuleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AmountRuleEnum.FromStringOrDefault(value) ?? new AmountRuleEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AmountRuleEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AmountRuleEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountRuleOption { get; private set; } + + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + [JsonPropertyName("amountRule")] + public AmountRuleEnum? AmountRule { get { return this._AmountRuleOption; } set { this._AmountRuleOption = new(value); } } + + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + [JsonConverter(typeof(BillingAttemptsRuleEnumJsonConverter))] + public class BillingAttemptsRuleEnum : IEnum + { + /// + /// Returns the value of the BillingAttemptsRuleEnum. + /// + public string? Value { get; set; } + + /// + /// BillingAttemptsRuleEnum.On - on + /// + public static readonly BillingAttemptsRuleEnum On = new("on"); + + /// + /// BillingAttemptsRuleEnum.Before - before + /// + public static readonly BillingAttemptsRuleEnum Before = new("before"); + + /// + /// BillingAttemptsRuleEnum.After - after + /// + public static readonly BillingAttemptsRuleEnum After = new("after"); + + private BillingAttemptsRuleEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BillingAttemptsRuleEnum?(string? value) => value == null ? null : new BillingAttemptsRuleEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BillingAttemptsRuleEnum? option) => option?.Value; + + public static bool operator ==(BillingAttemptsRuleEnum? left, BillingAttemptsRuleEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BillingAttemptsRuleEnum? left, BillingAttemptsRuleEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BillingAttemptsRuleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BillingAttemptsRuleEnum? FromStringOrDefault(string value) + { + return value switch { + "on" => BillingAttemptsRuleEnum.On, + "before" => BillingAttemptsRuleEnum.Before, + "after" => BillingAttemptsRuleEnum.After, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BillingAttemptsRuleEnum? value) + { + if (value == null) + return null; + + if (value == BillingAttemptsRuleEnum.On) + return "on"; + + if (value == BillingAttemptsRuleEnum.Before) + return "before"; + + if (value == BillingAttemptsRuleEnum.After) + return "after"; + + return null; + } + + /// + /// JsonConverter for writing BillingAttemptsRuleEnum. + /// + public class BillingAttemptsRuleEnumJsonConverter : JsonConverter + { + public override BillingAttemptsRuleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BillingAttemptsRuleEnum.FromStringOrDefault(value) ?? new BillingAttemptsRuleEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BillingAttemptsRuleEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BillingAttemptsRuleEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAttemptsRuleOption { get; private set; } + + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + [JsonPropertyName("billingAttemptsRule")] + public BillingAttemptsRuleEnum? BillingAttemptsRule { get { return this._BillingAttemptsRuleOption; } set { this._BillingAttemptsRuleOption = new(value); } } + + /// + /// The billing amount (in minor units) of the recurring transactions. + /// + /// The billing amount (in minor units) of the recurring transactions. + [JsonPropertyName("amount")] + public string Amount { get; set; } + + /// + /// End date of the billing plan, in YYYY-MM-DD format. + /// + /// End date of the billing plan, in YYYY-MM-DD format. + [JsonPropertyName("endsAt")] + public string EndsAt { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingDayOption { get; private set; } + + /// + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + /// + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + [JsonPropertyName("billingDay")] + public string? BillingDay { get { return this._BillingDayOption; } set { this._BillingDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountOption { get; private set; } + + /// + /// The number of transactions that can be performed within the given frequency. + /// + /// The number of transactions that can be performed within the given frequency. + [JsonPropertyName("count")] + public string? Count { get { return this._CountOption; } set { this._CountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RemarksOption { get; private set; } + + /// + /// The message shown by UPI to the shopper on the approval screen. + /// + /// The message shown by UPI to the shopper on the approval screen. + [JsonPropertyName("remarks")] + public string? Remarks { get { return this._RemarksOption; } set { this._RemarksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartsAtOption { get; private set; } + + /// + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + /// + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + [JsonPropertyName("startsAt")] + public string? StartsAt { get { return this._StartsAtOption; } set { this._StartsAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Mandate {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); + sb.Append(" Frequency: ").Append(Frequency).Append("\n"); + sb.Append(" AmountRule: ").Append(AmountRule).Append("\n"); + sb.Append(" BillingAttemptsRule: ").Append(BillingAttemptsRule).Append("\n"); + sb.Append(" BillingDay: ").Append(BillingDay).Append("\n"); + sb.Append(" Count: ").Append(Count).Append("\n"); + sb.Append(" Remarks: ").Append(Remarks).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MandateJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Mandate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option endsAt = default; + Option frequency = default; + Option amountRule = default; + Option billingAttemptsRule = default; + Option billingDay = default; + Option count = default; + Option remarks = default; + Option startsAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(utf8JsonReader.GetString()!); + break; + case "endsAt": + endsAt = new Option(utf8JsonReader.GetString()!); + break; + case "frequency": + string? frequencyRawValue = utf8JsonReader.GetString(); + frequency = new Option(Mandate.FrequencyEnum.FromStringOrDefault(frequencyRawValue)); + break; + case "amountRule": + string? amountRuleRawValue = utf8JsonReader.GetString(); + amountRule = new Option(Mandate.AmountRuleEnum.FromStringOrDefault(amountRuleRawValue)); + break; + case "billingAttemptsRule": + string? billingAttemptsRuleRawValue = utf8JsonReader.GetString(); + billingAttemptsRule = new Option(Mandate.BillingAttemptsRuleEnum.FromStringOrDefault(billingAttemptsRuleRawValue)); + break; + case "billingDay": + billingDay = new Option(utf8JsonReader.GetString()!); + break; + case "count": + count = new Option(utf8JsonReader.GetString()!); + break; + case "remarks": + remarks = new Option(utf8JsonReader.GetString()!); + break; + case "startsAt": + startsAt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(amount)); + + if (!endsAt.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(endsAt)); + + if (!frequency.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(frequency)); + + return new Mandate(amount.Value!, endsAt.Value!, frequency.Value!.Value!, amountRule, billingAttemptsRule, billingDay, count, remarks, startsAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Mandate mandate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mandate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Mandate mandate, JsonSerializerOptions jsonSerializerOptions) + { + + if (mandate.Amount != null) + writer.WriteString("amount", mandate.Amount); + + if (mandate.EndsAt != null) + writer.WriteString("endsAt", mandate.EndsAt); + + if (mandate.Frequency != null) + { + string? frequencyRawValue = Mandate.FrequencyEnum.ToJsonValue(mandate.Frequency); + writer.WriteString("frequency", frequencyRawValue); + } + + if (mandate._AmountRuleOption.IsSet && mandate.AmountRule != null) + { + string? amountRuleRawValue = Mandate.AmountRuleEnum.ToJsonValue(mandate._AmountRuleOption.Value!.Value); + writer.WriteString("amountRule", amountRuleRawValue); + } + + if (mandate._BillingAttemptsRuleOption.IsSet && mandate.BillingAttemptsRule != null) + { + string? billingAttemptsRuleRawValue = Mandate.BillingAttemptsRuleEnum.ToJsonValue(mandate._BillingAttemptsRuleOption.Value!.Value); + writer.WriteString("billingAttemptsRule", billingAttemptsRuleRawValue); + } + + if (mandate._BillingDayOption.IsSet) + if (mandate.BillingDay != null) + writer.WriteString("billingDay", mandate.BillingDay); + + if (mandate._CountOption.IsSet) + if (mandate.Count != null) + writer.WriteString("count", mandate.Count); + + if (mandate._RemarksOption.IsSet) + if (mandate.Remarks != null) + writer.WriteString("remarks", mandate.Remarks); + + if (mandate._StartsAtOption.IsSet) + if (mandate.StartsAt != null) + writer.WriteString("startsAt", mandate.StartsAt); + } + } +} diff --git a/Adyen/Checkout/Models/MasterpassDetails.cs b/Adyen/Checkout/Models/MasterpassDetails.cs new file mode 100644 index 000000000..bcb1028bc --- /dev/null +++ b/Adyen/Checkout/Models/MasterpassDetails.cs @@ -0,0 +1,449 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MasterpassDetails. + /// + public partial class MasterpassDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Masterpass transaction ID. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// **masterpass** (default to TypeEnum.Masterpass) + [JsonConstructor] + public MasterpassDetails(string masterpassTransactionId, Option checkoutAttemptId = default, Option fundingSource = default, Option type = default) + { + MasterpassTransactionId = masterpassTransactionId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MasterpassDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **masterpass** + /// + /// **masterpass** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Masterpass - masterpass + /// + public static readonly TypeEnum Masterpass = new("masterpass"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "masterpass" => TypeEnum.Masterpass, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Masterpass) + return "masterpass"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **masterpass** + /// + /// **masterpass** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The Masterpass transaction ID. + /// + /// The Masterpass transaction ID. + [JsonPropertyName("masterpassTransactionId")] + public string MasterpassTransactionId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MasterpassDetails {\n"); + sb.Append(" MasterpassTransactionId: ").Append(MasterpassTransactionId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MasterpassDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MasterpassDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option masterpassTransactionId = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "masterpassTransactionId": + masterpassTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(MasterpassDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MasterpassDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!masterpassTransactionId.IsSet) + throw new ArgumentException("Property is required for class MasterpassDetails.", nameof(masterpassTransactionId)); + + return new MasterpassDetails(masterpassTransactionId.Value!, checkoutAttemptId, fundingSource, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MasterpassDetails masterpassDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, masterpassDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MasterpassDetails masterpassDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (masterpassDetails.MasterpassTransactionId != null) + writer.WriteString("masterpassTransactionId", masterpassDetails.MasterpassTransactionId); + + if (masterpassDetails._CheckoutAttemptIdOption.IsSet) + if (masterpassDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", masterpassDetails.CheckoutAttemptId); + + if (masterpassDetails._FundingSourceOption.IsSet && masterpassDetails.FundingSource != null) + { + string? fundingSourceRawValue = MasterpassDetails.FundingSourceEnum.ToJsonValue(masterpassDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (masterpassDetails._TypeOption.IsSet && masterpassDetails.Type != null) + { + string? typeRawValue = MasterpassDetails.TypeEnum.ToJsonValue(masterpassDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/MbwayDetails.cs b/Adyen/Checkout/Models/MbwayDetails.cs new file mode 100644 index 000000000..0284d287d --- /dev/null +++ b/Adyen/Checkout/Models/MbwayDetails.cs @@ -0,0 +1,336 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MbwayDetails. + /// + public partial class MbwayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shopperEmail + /// telephoneNumber + /// The checkout attempt identifier. + /// **mbway** (default to TypeEnum.Mbway) + [JsonConstructor] + public MbwayDetails(string shopperEmail, string telephoneNumber, Option checkoutAttemptId = default, Option type = default) + { + ShopperEmail = shopperEmail; + TelephoneNumber = telephoneNumber; + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MbwayDetails() + { + } + + partial void OnCreated(); + + /// + /// **mbway** + /// + /// **mbway** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Mbway - mbway + /// + public static readonly TypeEnum Mbway = new("mbway"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "mbway" => TypeEnum.Mbway, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Mbway) + return "mbway"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **mbway** + /// + /// **mbway** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// . + /// + [JsonPropertyName("telephoneNumber")] + public string TelephoneNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MbwayDetails {\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MbwayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MbwayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option shopperEmail = default; + Option telephoneNumber = default; + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MbwayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class MbwayDetails.", nameof(shopperEmail)); + + if (!telephoneNumber.IsSet) + throw new ArgumentException("Property is required for class MbwayDetails.", nameof(telephoneNumber)); + + return new MbwayDetails(shopperEmail.Value!, telephoneNumber.Value!, checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MbwayDetails mbwayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mbwayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MbwayDetails mbwayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (mbwayDetails.ShopperEmail != null) + writer.WriteString("shopperEmail", mbwayDetails.ShopperEmail); + + if (mbwayDetails.TelephoneNumber != null) + writer.WriteString("telephoneNumber", mbwayDetails.TelephoneNumber); + + if (mbwayDetails._CheckoutAttemptIdOption.IsSet) + if (mbwayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", mbwayDetails.CheckoutAttemptId); + + if (mbwayDetails._TypeOption.IsSet && mbwayDetails.Type != null) + { + string? typeRawValue = MbwayDetails.TypeEnum.ToJsonValue(mbwayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/MerchantDevice.cs b/Adyen/Checkout/Models/MerchantDevice.cs new file mode 100644 index 000000000..44349a059 --- /dev/null +++ b/Adyen/Checkout/Models/MerchantDevice.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MerchantDevice. + /// + public partial class MerchantDevice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Operating system running on the merchant device. + /// Version of the operating system on the merchant device. + /// Merchant device reference. + [JsonConstructor] + public MerchantDevice(Option os = default, Option osVersion = default, Option reference = default) + { + _OsOption = os; + _OsVersionOption = osVersion; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantDevice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsOption { get; private set; } + + /// + /// Operating system running on the merchant device. + /// + /// Operating system running on the merchant device. + [JsonPropertyName("os")] + public string? Os { get { return this._OsOption; } set { this._OsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsVersionOption { get; private set; } + + /// + /// Version of the operating system on the merchant device. + /// + /// Version of the operating system on the merchant device. + [JsonPropertyName("osVersion")] + public string? OsVersion { get { return this._OsVersionOption; } set { this._OsVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Merchant device reference. + /// + /// Merchant device reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantDevice {\n"); + sb.Append(" Os: ").Append(Os).Append("\n"); + sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantDeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantDevice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option os = default; + Option osVersion = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "os": + os = new Option(utf8JsonReader.GetString()!); + break; + case "osVersion": + osVersion = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantDevice(os, osVersion, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantDevice merchantDevice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantDevice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantDevice merchantDevice, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantDevice._OsOption.IsSet) + if (merchantDevice.Os != null) + writer.WriteString("os", merchantDevice.Os); + + if (merchantDevice._OsVersionOption.IsSet) + if (merchantDevice.OsVersion != null) + writer.WriteString("osVersion", merchantDevice.OsVersion); + + if (merchantDevice._ReferenceOption.IsSet) + if (merchantDevice.Reference != null) + writer.WriteString("reference", merchantDevice.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/MerchantRiskIndicator.cs b/Adyen/Checkout/Models/MerchantRiskIndicator.cs new file mode 100644 index 000000000..7158d869d --- /dev/null +++ b/Adyen/Checkout/Models/MerchantRiskIndicator.cs @@ -0,0 +1,784 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MerchantRiskIndicator. + /// + public partial class MerchantRiskIndicator : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Whether the chosen delivery address is identical to the billing address. + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// The delivery email address (for digital goods). + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// giftCardAmount + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + /// For pre-order purchases, the expected date this product will be available to the shopper. + /// Indicator for whether this transaction is for pre-ordering a product. + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + /// Indicator for whether the shopper has already purchased the same items in the past. + /// Indicates whether the cardholder is reordering previously purchased merchandise. + /// Indicates shipping method chosen for the transaction. + [JsonConstructor] + public MerchantRiskIndicator(Option addressMatch = default, Option deliveryAddressIndicator = default, Option deliveryEmail = default, Option deliveryEmailAddress = default, Option deliveryTimeframe = default, Option giftCardAmount = default, Option giftCardCount = default, Option giftCardCurr = default, Option preOrderDate = default, Option preOrderPurchase = default, Option preOrderPurchaseInd = default, Option reorderItems = default, Option reorderItemsInd = default, Option shipIndicator = default) + { + _AddressMatchOption = addressMatch; + _DeliveryAddressIndicatorOption = deliveryAddressIndicator; + _DeliveryEmailOption = deliveryEmail; + _DeliveryEmailAddressOption = deliveryEmailAddress; + _DeliveryTimeframeOption = deliveryTimeframe; + _GiftCardAmountOption = giftCardAmount; + _GiftCardCountOption = giftCardCount; + _GiftCardCurrOption = giftCardCurr; + _PreOrderDateOption = preOrderDate; + _PreOrderPurchaseOption = preOrderPurchase; + _PreOrderPurchaseIndOption = preOrderPurchaseInd; + _ReorderItemsOption = reorderItems; + _ReorderItemsIndOption = reorderItemsInd; + _ShipIndicatorOption = shipIndicator; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantRiskIndicator() + { + } + + partial void OnCreated(); + + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + [JsonConverter(typeof(DeliveryAddressIndicatorEnumJsonConverter))] + public class DeliveryAddressIndicatorEnum : IEnum + { + /// + /// Returns the value of the DeliveryAddressIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryAddressIndicatorEnum.ShipToBillingAddress - shipToBillingAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToBillingAddress = new("shipToBillingAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToVerifiedAddress - shipToVerifiedAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToVerifiedAddress = new("shipToVerifiedAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToNewAddress - shipToNewAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToNewAddress = new("shipToNewAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToStore - shipToStore + /// + public static readonly DeliveryAddressIndicatorEnum ShipToStore = new("shipToStore"); + + /// + /// DeliveryAddressIndicatorEnum.DigitalGoods - digitalGoods + /// + public static readonly DeliveryAddressIndicatorEnum DigitalGoods = new("digitalGoods"); + + /// + /// DeliveryAddressIndicatorEnum.GoodsNotShipped - goodsNotShipped + /// + public static readonly DeliveryAddressIndicatorEnum GoodsNotShipped = new("goodsNotShipped"); + + /// + /// DeliveryAddressIndicatorEnum.Other - other + /// + public static readonly DeliveryAddressIndicatorEnum Other = new("other"); + + private DeliveryAddressIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryAddressIndicatorEnum?(string? value) => value == null ? null : new DeliveryAddressIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryAddressIndicatorEnum? option) => option?.Value; + + public static bool operator ==(DeliveryAddressIndicatorEnum? left, DeliveryAddressIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryAddressIndicatorEnum? left, DeliveryAddressIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryAddressIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryAddressIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "shipToBillingAddress" => DeliveryAddressIndicatorEnum.ShipToBillingAddress, + "shipToVerifiedAddress" => DeliveryAddressIndicatorEnum.ShipToVerifiedAddress, + "shipToNewAddress" => DeliveryAddressIndicatorEnum.ShipToNewAddress, + "shipToStore" => DeliveryAddressIndicatorEnum.ShipToStore, + "digitalGoods" => DeliveryAddressIndicatorEnum.DigitalGoods, + "goodsNotShipped" => DeliveryAddressIndicatorEnum.GoodsNotShipped, + "other" => DeliveryAddressIndicatorEnum.Other, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryAddressIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryAddressIndicatorEnum.ShipToBillingAddress) + return "shipToBillingAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToVerifiedAddress) + return "shipToVerifiedAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToNewAddress) + return "shipToNewAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToStore) + return "shipToStore"; + + if (value == DeliveryAddressIndicatorEnum.DigitalGoods) + return "digitalGoods"; + + if (value == DeliveryAddressIndicatorEnum.GoodsNotShipped) + return "goodsNotShipped"; + + if (value == DeliveryAddressIndicatorEnum.Other) + return "other"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryAddressIndicatorEnum. + /// + public class DeliveryAddressIndicatorEnumJsonConverter : JsonConverter + { + public override DeliveryAddressIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryAddressIndicatorEnum.FromStringOrDefault(value) ?? new DeliveryAddressIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryAddressIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryAddressIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressIndicatorOption { get; private set; } + + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + [JsonPropertyName("deliveryAddressIndicator")] + public DeliveryAddressIndicatorEnum? DeliveryAddressIndicator { get { return this._DeliveryAddressIndicatorOption; } set { this._DeliveryAddressIndicatorOption = new(value); } } + + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + [JsonConverter(typeof(DeliveryTimeframeEnumJsonConverter))] + public class DeliveryTimeframeEnum : IEnum + { + /// + /// Returns the value of the DeliveryTimeframeEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryTimeframeEnum.ElectronicDelivery - electronicDelivery + /// + public static readonly DeliveryTimeframeEnum ElectronicDelivery = new("electronicDelivery"); + + /// + /// DeliveryTimeframeEnum.SameDayShipping - sameDayShipping + /// + public static readonly DeliveryTimeframeEnum SameDayShipping = new("sameDayShipping"); + + /// + /// DeliveryTimeframeEnum.OvernightShipping - overnightShipping + /// + public static readonly DeliveryTimeframeEnum OvernightShipping = new("overnightShipping"); + + /// + /// DeliveryTimeframeEnum.TwoOrMoreDaysShipping - twoOrMoreDaysShipping + /// + public static readonly DeliveryTimeframeEnum TwoOrMoreDaysShipping = new("twoOrMoreDaysShipping"); + + private DeliveryTimeframeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryTimeframeEnum?(string? value) => value == null ? null : new DeliveryTimeframeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryTimeframeEnum? option) => option?.Value; + + public static bool operator ==(DeliveryTimeframeEnum? left, DeliveryTimeframeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryTimeframeEnum? left, DeliveryTimeframeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryTimeframeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryTimeframeEnum? FromStringOrDefault(string value) + { + return value switch { + "electronicDelivery" => DeliveryTimeframeEnum.ElectronicDelivery, + "sameDayShipping" => DeliveryTimeframeEnum.SameDayShipping, + "overnightShipping" => DeliveryTimeframeEnum.OvernightShipping, + "twoOrMoreDaysShipping" => DeliveryTimeframeEnum.TwoOrMoreDaysShipping, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryTimeframeEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryTimeframeEnum.ElectronicDelivery) + return "electronicDelivery"; + + if (value == DeliveryTimeframeEnum.SameDayShipping) + return "sameDayShipping"; + + if (value == DeliveryTimeframeEnum.OvernightShipping) + return "overnightShipping"; + + if (value == DeliveryTimeframeEnum.TwoOrMoreDaysShipping) + return "twoOrMoreDaysShipping"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryTimeframeEnum. + /// + public class DeliveryTimeframeEnumJsonConverter : JsonConverter + { + public override DeliveryTimeframeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryTimeframeEnum.FromStringOrDefault(value) ?? new DeliveryTimeframeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryTimeframeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryTimeframeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryTimeframeOption { get; private set; } + + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + [JsonPropertyName("deliveryTimeframe")] + public DeliveryTimeframeEnum? DeliveryTimeframe { get { return this._DeliveryTimeframeOption; } set { this._DeliveryTimeframeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressMatchOption { get; private set; } + + /// + /// Whether the chosen delivery address is identical to the billing address. + /// + /// Whether the chosen delivery address is identical to the billing address. + [JsonPropertyName("addressMatch")] + public bool? AddressMatch { get { return this._AddressMatchOption; } set { this._AddressMatchOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryEmailOption { get; private set; } + + /// + /// The delivery email address (for digital goods). + /// + /// The delivery email address (for digital goods). + [JsonPropertyName("deliveryEmail")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `deliveryEmailAddress` instead.")] + public string? DeliveryEmail { get { return this._DeliveryEmailOption; } set { this._DeliveryEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryEmailAddressOption { get; private set; } + + /// + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + /// + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + [JsonPropertyName("deliveryEmailAddress")] + public string? DeliveryEmailAddress { get { return this._DeliveryEmailAddressOption; } set { this._DeliveryEmailAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("giftCardAmount")] + public Amount? GiftCardAmount { get { return this._GiftCardAmountOption; } set { this._GiftCardAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardCountOption { get; private set; } + + /// + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + /// + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + [JsonPropertyName("giftCardCount")] + public int? GiftCardCount { get { return this._GiftCardCountOption; } set { this._GiftCardCountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardCurrOption { get; private set; } + + /// + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + /// + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + [JsonPropertyName("giftCardCurr")] + public string? GiftCardCurr { get { return this._GiftCardCurrOption; } set { this._GiftCardCurrOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderDateOption { get; private set; } + + /// + /// For pre-order purchases, the expected date this product will be available to the shopper. + /// + /// For pre-order purchases, the expected date this product will be available to the shopper. + [JsonPropertyName("preOrderDate")] + public DateTimeOffset? PreOrderDate { get { return this._PreOrderDateOption; } set { this._PreOrderDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderPurchaseOption { get; private set; } + + /// + /// Indicator for whether this transaction is for pre-ordering a product. + /// + /// Indicator for whether this transaction is for pre-ordering a product. + [JsonPropertyName("preOrderPurchase")] + public bool? PreOrderPurchase { get { return this._PreOrderPurchaseOption; } set { this._PreOrderPurchaseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderPurchaseIndOption { get; private set; } + + /// + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + /// + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + [JsonPropertyName("preOrderPurchaseInd")] + public string? PreOrderPurchaseInd { get { return this._PreOrderPurchaseIndOption; } set { this._PreOrderPurchaseIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReorderItemsOption { get; private set; } + + /// + /// Indicator for whether the shopper has already purchased the same items in the past. + /// + /// Indicator for whether the shopper has already purchased the same items in the past. + [JsonPropertyName("reorderItems")] + public bool? ReorderItems { get { return this._ReorderItemsOption; } set { this._ReorderItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReorderItemsIndOption { get; private set; } + + /// + /// Indicates whether the cardholder is reordering previously purchased merchandise. + /// + /// Indicates whether the cardholder is reordering previously purchased merchandise. + [JsonPropertyName("reorderItemsInd")] + public string? ReorderItemsInd { get { return this._ReorderItemsIndOption; } set { this._ReorderItemsIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipIndicatorOption { get; private set; } + + /// + /// Indicates shipping method chosen for the transaction. + /// + /// Indicates shipping method chosen for the transaction. + [JsonPropertyName("shipIndicator")] + public string? ShipIndicator { get { return this._ShipIndicatorOption; } set { this._ShipIndicatorOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantRiskIndicator {\n"); + sb.Append(" AddressMatch: ").Append(AddressMatch).Append("\n"); + sb.Append(" DeliveryAddressIndicator: ").Append(DeliveryAddressIndicator).Append("\n"); + sb.Append(" DeliveryEmail: ").Append(DeliveryEmail).Append("\n"); + sb.Append(" DeliveryEmailAddress: ").Append(DeliveryEmailAddress).Append("\n"); + sb.Append(" DeliveryTimeframe: ").Append(DeliveryTimeframe).Append("\n"); + sb.Append(" GiftCardAmount: ").Append(GiftCardAmount).Append("\n"); + sb.Append(" GiftCardCount: ").Append(GiftCardCount).Append("\n"); + sb.Append(" GiftCardCurr: ").Append(GiftCardCurr).Append("\n"); + sb.Append(" PreOrderDate: ").Append(PreOrderDate).Append("\n"); + sb.Append(" PreOrderPurchase: ").Append(PreOrderPurchase).Append("\n"); + sb.Append(" PreOrderPurchaseInd: ").Append(PreOrderPurchaseInd).Append("\n"); + sb.Append(" ReorderItems: ").Append(ReorderItems).Append("\n"); + sb.Append(" ReorderItemsInd: ").Append(ReorderItemsInd).Append("\n"); + sb.Append(" ShipIndicator: ").Append(ShipIndicator).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeliveryEmailAddress (string) maxLength + if (this.DeliveryEmailAddress != null && this.DeliveryEmailAddress.Length > 254) + { + yield return new ValidationResult("Invalid value for DeliveryEmailAddress, length must be less than 254.", new [] { "DeliveryEmailAddress" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantRiskIndicatorJsonConverter : JsonConverter + { + /// + /// The format to use to serialize PreOrderDate. + /// + public static string PreOrderDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantRiskIndicator Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option addressMatch = default; + Option deliveryAddressIndicator = default; + Option deliveryEmail = default; + Option deliveryEmailAddress = default; + Option deliveryTimeframe = default; + Option giftCardAmount = default; + Option giftCardCount = default; + Option giftCardCurr = default; + Option preOrderDate = default; + Option preOrderPurchase = default; + Option preOrderPurchaseInd = default; + Option reorderItems = default; + Option reorderItemsInd = default; + Option shipIndicator = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "addressMatch": + addressMatch = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "deliveryAddressIndicator": + string? deliveryAddressIndicatorRawValue = utf8JsonReader.GetString(); + deliveryAddressIndicator = new Option(MerchantRiskIndicator.DeliveryAddressIndicatorEnum.FromStringOrDefault(deliveryAddressIndicatorRawValue)); + break; + case "deliveryEmail": + deliveryEmail = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryEmailAddress": + deliveryEmailAddress = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryTimeframe": + string? deliveryTimeframeRawValue = utf8JsonReader.GetString(); + deliveryTimeframe = new Option(MerchantRiskIndicator.DeliveryTimeframeEnum.FromStringOrDefault(deliveryTimeframeRawValue)); + break; + case "giftCardAmount": + giftCardAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "giftCardCount": + giftCardCount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "giftCardCurr": + giftCardCurr = new Option(utf8JsonReader.GetString()!); + break; + case "preOrderDate": + preOrderDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "preOrderPurchase": + preOrderPurchase = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "preOrderPurchaseInd": + preOrderPurchaseInd = new Option(utf8JsonReader.GetString()!); + break; + case "reorderItems": + reorderItems = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "reorderItemsInd": + reorderItemsInd = new Option(utf8JsonReader.GetString()!); + break; + case "shipIndicator": + shipIndicator = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantRiskIndicator(addressMatch, deliveryAddressIndicator, deliveryEmail, deliveryEmailAddress, deliveryTimeframe, giftCardAmount, giftCardCount, giftCardCurr, preOrderDate, preOrderPurchase, preOrderPurchaseInd, reorderItems, reorderItemsInd, shipIndicator); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantRiskIndicator merchantRiskIndicator, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantRiskIndicator, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantRiskIndicator merchantRiskIndicator, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantRiskIndicator._AddressMatchOption.IsSet) + writer.WriteBoolean("addressMatch", merchantRiskIndicator._AddressMatchOption.Value!.Value); + + if (merchantRiskIndicator._DeliveryAddressIndicatorOption.IsSet && merchantRiskIndicator.DeliveryAddressIndicator != null) + { + string? deliveryAddressIndicatorRawValue = MerchantRiskIndicator.DeliveryAddressIndicatorEnum.ToJsonValue(merchantRiskIndicator._DeliveryAddressIndicatorOption.Value!.Value); + writer.WriteString("deliveryAddressIndicator", deliveryAddressIndicatorRawValue); + } + + if (merchantRiskIndicator._DeliveryEmailOption.IsSet) + if (merchantRiskIndicator.DeliveryEmail != null) + writer.WriteString("deliveryEmail", merchantRiskIndicator.DeliveryEmail); + + if (merchantRiskIndicator._DeliveryEmailAddressOption.IsSet) + if (merchantRiskIndicator.DeliveryEmailAddress != null) + writer.WriteString("deliveryEmailAddress", merchantRiskIndicator.DeliveryEmailAddress); + + if (merchantRiskIndicator._DeliveryTimeframeOption.IsSet && merchantRiskIndicator.DeliveryTimeframe != null) + { + string? deliveryTimeframeRawValue = MerchantRiskIndicator.DeliveryTimeframeEnum.ToJsonValue(merchantRiskIndicator._DeliveryTimeframeOption.Value!.Value); + writer.WriteString("deliveryTimeframe", deliveryTimeframeRawValue); + } + + if (merchantRiskIndicator._GiftCardAmountOption.IsSet) + { + writer.WritePropertyName("giftCardAmount"); + JsonSerializer.Serialize(writer, merchantRiskIndicator.GiftCardAmount, jsonSerializerOptions); + } + if (merchantRiskIndicator._GiftCardCountOption.IsSet) + writer.WriteNumber("giftCardCount", merchantRiskIndicator._GiftCardCountOption.Value!.Value); + + if (merchantRiskIndicator._GiftCardCurrOption.IsSet) + if (merchantRiskIndicator.GiftCardCurr != null) + writer.WriteString("giftCardCurr", merchantRiskIndicator.GiftCardCurr); + + if (merchantRiskIndicator._PreOrderDateOption.IsSet) + writer.WriteString("preOrderDate", merchantRiskIndicator._PreOrderDateOption.Value!.Value.ToString(PreOrderDateFormat)); + + if (merchantRiskIndicator._PreOrderPurchaseOption.IsSet) + writer.WriteBoolean("preOrderPurchase", merchantRiskIndicator._PreOrderPurchaseOption.Value!.Value); + + if (merchantRiskIndicator._PreOrderPurchaseIndOption.IsSet) + if (merchantRiskIndicator.PreOrderPurchaseInd != null) + writer.WriteString("preOrderPurchaseInd", merchantRiskIndicator.PreOrderPurchaseInd); + + if (merchantRiskIndicator._ReorderItemsOption.IsSet) + writer.WriteBoolean("reorderItems", merchantRiskIndicator._ReorderItemsOption.Value!.Value); + + if (merchantRiskIndicator._ReorderItemsIndOption.IsSet) + if (merchantRiskIndicator.ReorderItemsInd != null) + writer.WriteString("reorderItemsInd", merchantRiskIndicator.ReorderItemsInd); + + if (merchantRiskIndicator._ShipIndicatorOption.IsSet) + if (merchantRiskIndicator.ShipIndicator != null) + writer.WriteString("shipIndicator", merchantRiskIndicator.ShipIndicator); + } + } +} diff --git a/Adyen/Checkout/Models/MobilePayDetails.cs b/Adyen/Checkout/Models/MobilePayDetails.cs new file mode 100644 index 000000000..2c4246a2b --- /dev/null +++ b/Adyen/Checkout/Models/MobilePayDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MobilePayDetails. + /// + public partial class MobilePayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// **mobilepay** (default to TypeEnum.Mobilepay) + [JsonConstructor] + public MobilePayDetails(Option checkoutAttemptId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MobilePayDetails() + { + } + + partial void OnCreated(); + + /// + /// **mobilepay** + /// + /// **mobilepay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Mobilepay - mobilepay + /// + public static readonly TypeEnum Mobilepay = new("mobilepay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "mobilepay" => TypeEnum.Mobilepay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Mobilepay) + return "mobilepay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **mobilepay** + /// + /// **mobilepay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MobilePayDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MobilePayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MobilePayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MobilePayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new MobilePayDetails(checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MobilePayDetails mobilePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mobilePayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MobilePayDetails mobilePayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (mobilePayDetails._CheckoutAttemptIdOption.IsSet) + if (mobilePayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", mobilePayDetails.CheckoutAttemptId); + + if (mobilePayDetails._TypeOption.IsSet && mobilePayDetails.Type != null) + { + string? typeRawValue = MobilePayDetails.TypeEnum.ToJsonValue(mobilePayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/MolPayDetails.cs b/Adyen/Checkout/Models/MolPayDetails.cs new file mode 100644 index 000000000..6e55ec5d0 --- /dev/null +++ b/Adyen/Checkout/Models/MolPayDetails.cs @@ -0,0 +1,323 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// MolPayDetails. + /// + public partial class MolPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The shopper's bank. Specify this with the issuer value that corresponds to this bank. + /// **molpay** + /// The checkout attempt identifier. + [JsonConstructor] + public MolPayDetails(string issuer, TypeEnum type, Option checkoutAttemptId = default) + { + Issuer = issuer; + Type = type; + _CheckoutAttemptIdOption = checkoutAttemptId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MolPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **molpay** + /// + /// **molpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.MolpayEbankingFpxMY - molpay_ebanking_fpx_MY + /// + public static readonly TypeEnum MolpayEbankingFpxMY = new("molpay_ebanking_fpx_MY"); + + /// + /// TypeEnum.MolpayEbankingTH - molpay_ebanking_TH + /// + public static readonly TypeEnum MolpayEbankingTH = new("molpay_ebanking_TH"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "molpay_ebanking_fpx_MY" => TypeEnum.MolpayEbankingFpxMY, + "molpay_ebanking_TH" => TypeEnum.MolpayEbankingTH, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.MolpayEbankingFpxMY) + return "molpay_ebanking_fpx_MY"; + + if (value == TypeEnum.MolpayEbankingTH) + return "molpay_ebanking_TH"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **molpay** + /// + /// **molpay** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The shopper's bank. Specify this with the issuer value that corresponds to this bank. + /// + /// The shopper's bank. Specify this with the issuer value that corresponds to this bank. + [JsonPropertyName("issuer")] + public string Issuer { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MolPayDetails {\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MolPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MolPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issuer = default; + Option type = default; + Option checkoutAttemptId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MolPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!issuer.IsSet) + throw new ArgumentException("Property is required for class MolPayDetails.", nameof(issuer)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MolPayDetails.", nameof(type)); + + return new MolPayDetails(issuer.Value!, type.Value!.Value!, checkoutAttemptId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MolPayDetails molPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, molPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MolPayDetails molPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (molPayDetails.Issuer != null) + writer.WriteString("issuer", molPayDetails.Issuer); + + if (molPayDetails.Type != null) + { + string? typeRawValue = MolPayDetails.TypeEnum.ToJsonValue(molPayDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (molPayDetails._CheckoutAttemptIdOption.IsSet) + if (molPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", molPayDetails.CheckoutAttemptId); + } + } +} diff --git a/Adyen/Checkout/Models/Name.cs b/Adyen/Checkout/Models/Name.cs new file mode 100644 index 000000000..5db823986 --- /dev/null +++ b/Adyen/Checkout/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/Checkout/Models/OpenInvoiceDetails.cs b/Adyen/Checkout/Models/OpenInvoiceDetails.cs new file mode 100644 index 000000000..a526b1774 --- /dev/null +++ b/Adyen/Checkout/Models/OpenInvoiceDetails.cs @@ -0,0 +1,449 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// OpenInvoiceDetails. + /// + public partial class OpenInvoiceDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address where to send the invoice. + /// The checkout attempt identifier. + /// The address where the goods should be delivered. + /// Shopper name, date of birth, phone number, and email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **openinvoice** (default to TypeEnum.Openinvoice) + [JsonConstructor] + public OpenInvoiceDetails(Option billingAddress = default, Option checkoutAttemptId = default, Option deliveryAddress = default, Option personalDetails = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _BillingAddressOption = billingAddress; + _CheckoutAttemptIdOption = checkoutAttemptId; + _DeliveryAddressOption = deliveryAddress; + _PersonalDetailsOption = personalDetails; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OpenInvoiceDetails() + { + } + + partial void OnCreated(); + + /// + /// **openinvoice** + /// + /// **openinvoice** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Openinvoice - openinvoice + /// + public static readonly TypeEnum Openinvoice = new("openinvoice"); + + /// + /// TypeEnum.AfterpayDirectdebit - afterpay_directdebit + /// + public static readonly TypeEnum AfterpayDirectdebit = new("afterpay_directdebit"); + + /// + /// TypeEnum.AtomePos - atome_pos + /// + public static readonly TypeEnum AtomePos = new("atome_pos"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "openinvoice" => TypeEnum.Openinvoice, + "afterpay_directdebit" => TypeEnum.AfterpayDirectdebit, + "atome_pos" => TypeEnum.AtomePos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Openinvoice) + return "openinvoice"; + + if (value == TypeEnum.AfterpayDirectdebit) + return "afterpay_directdebit"; + + if (value == TypeEnum.AtomePos) + return "atome_pos"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **openinvoice** + /// + /// **openinvoice** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// The address where to send the invoice. + /// + /// The address where to send the invoice. + [JsonPropertyName("billingAddress")] + public string? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// The address where the goods should be delivered. + /// + /// The address where the goods should be delivered. + [JsonPropertyName("deliveryAddress")] + public string? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PersonalDetailsOption { get; private set; } + + /// + /// Shopper name, date of birth, phone number, and email address. + /// + /// Shopper name, date of birth, phone number, and email address. + [JsonPropertyName("personalDetails")] + public string? PersonalDetails { get { return this._PersonalDetailsOption; } set { this._PersonalDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OpenInvoiceDetails {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OpenInvoiceDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OpenInvoiceDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option checkoutAttemptId = default; + Option deliveryAddress = default; + Option personalDetails = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryAddress": + deliveryAddress = new Option(utf8JsonReader.GetString()!); + break; + case "personalDetails": + personalDetails = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(OpenInvoiceDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new OpenInvoiceDetails(billingAddress, checkoutAttemptId, deliveryAddress, personalDetails, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OpenInvoiceDetails openInvoiceDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, openInvoiceDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OpenInvoiceDetails openInvoiceDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (openInvoiceDetails._BillingAddressOption.IsSet) + if (openInvoiceDetails.BillingAddress != null) + writer.WriteString("billingAddress", openInvoiceDetails.BillingAddress); + + if (openInvoiceDetails._CheckoutAttemptIdOption.IsSet) + if (openInvoiceDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", openInvoiceDetails.CheckoutAttemptId); + + if (openInvoiceDetails._DeliveryAddressOption.IsSet) + if (openInvoiceDetails.DeliveryAddress != null) + writer.WriteString("deliveryAddress", openInvoiceDetails.DeliveryAddress); + + if (openInvoiceDetails._PersonalDetailsOption.IsSet) + if (openInvoiceDetails.PersonalDetails != null) + writer.WriteString("personalDetails", openInvoiceDetails.PersonalDetails); + + if (openInvoiceDetails._RecurringDetailReferenceOption.IsSet) + if (openInvoiceDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", openInvoiceDetails.RecurringDetailReference); + + if (openInvoiceDetails._StoredPaymentMethodIdOption.IsSet) + if (openInvoiceDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", openInvoiceDetails.StoredPaymentMethodId); + + if (openInvoiceDetails._TypeOption.IsSet && openInvoiceDetails.Type != null) + { + string? typeRawValue = OpenInvoiceDetails.TypeEnum.ToJsonValue(openInvoiceDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Passenger.cs b/Adyen/Checkout/Models/Passenger.cs new file mode 100644 index 000000000..9ef759008 --- /dev/null +++ b/Adyen/Checkout/Models/Passenger.cs @@ -0,0 +1,281 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Passenger. + /// + public partial class Passenger : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The passenger's date of birth. * Format `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + [JsonConstructor] + public Passenger(Option dateOfBirth = default, Option firstName = default, Option lastName = default, Option phoneNumber = default, Option travellerType = default) + { + _DateOfBirthOption = dateOfBirth; + _FirstNameOption = firstName; + _LastNameOption = lastName; + _PhoneNumberOption = phoneNumber; + _TravellerTypeOption = travellerType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Passenger() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The passenger's date of birth. * Format `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// + /// The passenger's date of birth. * Format `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravellerTypeOption { get; private set; } + + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + [JsonPropertyName("travellerType")] + public string? TravellerType { get { return this._TravellerTypeOption; } set { this._TravellerTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Passenger {\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" TravellerType: ").Append(TravellerType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PassengerJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Passenger Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dateOfBirth = default; + Option firstName = default; + Option lastName = default; + Option phoneNumber = default; + Option travellerType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "travellerType": + travellerType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Passenger(dateOfBirth, firstName, lastName, phoneNumber, travellerType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Passenger passenger, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, passenger, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Passenger passenger, JsonSerializerOptions jsonSerializerOptions) + { + + if (passenger._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", passenger._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (passenger._FirstNameOption.IsSet) + if (passenger.FirstName != null) + writer.WriteString("firstName", passenger.FirstName); + + if (passenger._LastNameOption.IsSet) + if (passenger.LastName != null) + writer.WriteString("lastName", passenger.LastName); + + if (passenger._PhoneNumberOption.IsSet) + if (passenger.PhoneNumber != null) + writer.WriteString("phoneNumber", passenger.PhoneNumber); + + if (passenger._TravellerTypeOption.IsSet) + if (passenger.TravellerType != null) + writer.WriteString("travellerType", passenger.TravellerType); + } + } +} diff --git a/Adyen/Checkout/Models/PayByBankAISDirectDebitDetails.cs b/Adyen/Checkout/Models/PayByBankAISDirectDebitDetails.cs new file mode 100644 index 000000000..62dd8559a --- /dev/null +++ b/Adyen/Checkout/Models/PayByBankAISDirectDebitDetails.cs @@ -0,0 +1,351 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayByBankAISDirectDebitDetails. + /// + public partial class PayByBankAISDirectDebitDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **paybybank_AIS_DD** (default to TypeEnum.PaybybankAISDD) + [JsonConstructor] + public PayByBankAISDirectDebitDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayByBankAISDirectDebitDetails() + { + } + + partial void OnCreated(); + + /// + /// **paybybank_AIS_DD** + /// + /// **paybybank_AIS_DD** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaybybankAISDD - paybybank_AIS_DD + /// + public static readonly TypeEnum PaybybankAISDD = new("paybybank_AIS_DD"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paybybank_AIS_DD" => TypeEnum.PaybybankAISDD, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaybybankAISDD) + return "paybybank_AIS_DD"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **paybybank_AIS_DD** + /// + /// **paybybank_AIS_DD** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayByBankAISDirectDebitDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayByBankAISDirectDebitDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayByBankAISDirectDebitDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayByBankAISDirectDebitDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PayByBankAISDirectDebitDetails.", nameof(type)); + + return new PayByBankAISDirectDebitDetails(checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayByBankAISDirectDebitDetails payByBankAISDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payByBankAISDirectDebitDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayByBankAISDirectDebitDetails payByBankAISDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payByBankAISDirectDebitDetails._CheckoutAttemptIdOption.IsSet) + if (payByBankAISDirectDebitDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payByBankAISDirectDebitDetails.CheckoutAttemptId); + + if (payByBankAISDirectDebitDetails._RecurringDetailReferenceOption.IsSet) + if (payByBankAISDirectDebitDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payByBankAISDirectDebitDetails.RecurringDetailReference); + + if (payByBankAISDirectDebitDetails._StoredPaymentMethodIdOption.IsSet) + if (payByBankAISDirectDebitDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payByBankAISDirectDebitDetails.StoredPaymentMethodId); + + if (payByBankAISDirectDebitDetails.Type != null) + { + string? typeRawValue = PayByBankAISDirectDebitDetails.TypeEnum.ToJsonValue(payByBankAISDirectDebitDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayByBankDetails.cs b/Adyen/Checkout/Models/PayByBankDetails.cs new file mode 100644 index 000000000..4461cab44 --- /dev/null +++ b/Adyen/Checkout/Models/PayByBankDetails.cs @@ -0,0 +1,319 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayByBankDetails. + /// + public partial class PayByBankDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The PayByBank issuer value of the shopper's selected bank. + /// **paybybank** (default to TypeEnum.Paybybank) + [JsonConstructor] + public PayByBankDetails(Option checkoutAttemptId = default, Option issuer = default, TypeEnum type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _IssuerOption = issuer; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayByBankDetails() + { + } + + partial void OnCreated(); + + /// + /// **paybybank** + /// + /// **paybybank** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Paybybank - paybybank + /// + public static readonly TypeEnum Paybybank = new("paybybank"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paybybank" => TypeEnum.Paybybank, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Paybybank) + return "paybybank"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **paybybank** + /// + /// **paybybank** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerOption { get; private set; } + + /// + /// The PayByBank issuer value of the shopper's selected bank. + /// + /// The PayByBank issuer value of the shopper's selected bank. + [JsonPropertyName("issuer")] + public string? Issuer { get { return this._IssuerOption; } set { this._IssuerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayByBankDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Issuer: ").Append(Issuer).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayByBankDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayByBankDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option issuer = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "issuer": + issuer = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayByBankDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PayByBankDetails.", nameof(type)); + + return new PayByBankDetails(checkoutAttemptId, issuer, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayByBankDetails payByBankDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payByBankDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayByBankDetails payByBankDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payByBankDetails._CheckoutAttemptIdOption.IsSet) + if (payByBankDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payByBankDetails.CheckoutAttemptId); + + if (payByBankDetails._IssuerOption.IsSet) + if (payByBankDetails.Issuer != null) + writer.WriteString("issuer", payByBankDetails.Issuer); + + if (payByBankDetails.Type != null) + { + string? typeRawValue = PayByBankDetails.TypeEnum.ToJsonValue(payByBankDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayPalDetails.cs b/Adyen/Checkout/Models/PayPalDetails.cs new file mode 100644 index 000000000..f0cd29f14 --- /dev/null +++ b/Adyen/Checkout/Models/PayPalDetails.cs @@ -0,0 +1,591 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayPalDetails. + /// + public partial class PayPalDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The unique ID associated with the order. + /// IMMEDIATE_PAYMENT_REQUIRED or UNRESTRICTED + /// The unique ID associated with the payer. + /// PAYPAL or PAYPAL_CREDIT + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The type of flow to initiate. + /// **paypal** (default to TypeEnum.Paypal) + [JsonConstructor] + public PayPalDetails(Option checkoutAttemptId = default, Option orderID = default, Option payeePreferred = default, Option payerID = default, Option payerSelected = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option subtype = default, TypeEnum type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _OrderIDOption = orderID; + _PayeePreferredOption = payeePreferred; + _PayerIDOption = payerID; + _PayerSelectedOption = payerSelected; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubtypeOption = subtype; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayPalDetails() + { + } + + partial void OnCreated(); + + /// + /// The type of flow to initiate. + /// + /// The type of flow to initiate. + [JsonConverter(typeof(SubtypeEnumJsonConverter))] + public class SubtypeEnum : IEnum + { + /// + /// Returns the value of the SubtypeEnum. + /// + public string? Value { get; set; } + + /// + /// SubtypeEnum.Express - express + /// + public static readonly SubtypeEnum Express = new("express"); + + /// + /// SubtypeEnum.Redirect - redirect + /// + public static readonly SubtypeEnum Redirect = new("redirect"); + + /// + /// SubtypeEnum.Sdk - sdk + /// + public static readonly SubtypeEnum Sdk = new("sdk"); + + private SubtypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SubtypeEnum?(string? value) => value == null ? null : new SubtypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SubtypeEnum? option) => option?.Value; + + public static bool operator ==(SubtypeEnum? left, SubtypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SubtypeEnum? left, SubtypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SubtypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SubtypeEnum? FromStringOrDefault(string value) + { + return value switch { + "express" => SubtypeEnum.Express, + "redirect" => SubtypeEnum.Redirect, + "sdk" => SubtypeEnum.Sdk, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SubtypeEnum? value) + { + if (value == null) + return null; + + if (value == SubtypeEnum.Express) + return "express"; + + if (value == SubtypeEnum.Redirect) + return "redirect"; + + if (value == SubtypeEnum.Sdk) + return "sdk"; + + return null; + } + + /// + /// JsonConverter for writing SubtypeEnum. + /// + public class SubtypeEnumJsonConverter : JsonConverter + { + public override SubtypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SubtypeEnum.FromStringOrDefault(value) ?? new SubtypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SubtypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SubtypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// The type of flow to initiate. + /// + /// The type of flow to initiate. + [JsonPropertyName("subtype")] + public SubtypeEnum? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// **paypal** + /// + /// **paypal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Paypal - paypal + /// + public static readonly TypeEnum Paypal = new("paypal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paypal" => TypeEnum.Paypal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Paypal) + return "paypal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **paypal** + /// + /// **paypal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderIDOption { get; private set; } + + /// + /// The unique ID associated with the order. + /// + /// The unique ID associated with the order. + [JsonPropertyName("orderID")] + public string? OrderID { get { return this._OrderIDOption; } set { this._OrderIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayeePreferredOption { get; private set; } + + /// + /// IMMEDIATE_PAYMENT_REQUIRED or UNRESTRICTED + /// + /// IMMEDIATE_PAYMENT_REQUIRED or UNRESTRICTED + [JsonPropertyName("payeePreferred")] + public string? PayeePreferred { get { return this._PayeePreferredOption; } set { this._PayeePreferredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayerIDOption { get; private set; } + + /// + /// The unique ID associated with the payer. + /// + /// The unique ID associated with the payer. + [JsonPropertyName("payerID")] + public string? PayerID { get { return this._PayerIDOption; } set { this._PayerIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayerSelectedOption { get; private set; } + + /// + /// PAYPAL or PAYPAL_CREDIT + /// + /// PAYPAL or PAYPAL_CREDIT + [JsonPropertyName("payerSelected")] + public string? PayerSelected { get { return this._PayerSelectedOption; } set { this._PayerSelectedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayPalDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" OrderID: ").Append(OrderID).Append("\n"); + sb.Append(" PayeePreferred: ").Append(PayeePreferred).Append("\n"); + sb.Append(" PayerID: ").Append(PayerID).Append("\n"); + sb.Append(" PayerSelected: ").Append(PayerSelected).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayPalDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayPalDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option orderID = default; + Option payeePreferred = default; + Option payerID = default; + Option payerSelected = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option subtype = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "orderID": + orderID = new Option(utf8JsonReader.GetString()!); + break; + case "payeePreferred": + payeePreferred = new Option(utf8JsonReader.GetString()!); + break; + case "payerID": + payerID = new Option(utf8JsonReader.GetString()!); + break; + case "payerSelected": + payerSelected = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + string? subtypeRawValue = utf8JsonReader.GetString(); + subtype = new Option(PayPalDetails.SubtypeEnum.FromStringOrDefault(subtypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayPalDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PayPalDetails.", nameof(type)); + + return new PayPalDetails(checkoutAttemptId, orderID, payeePreferred, payerID, payerSelected, recurringDetailReference, storedPaymentMethodId, subtype, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayPalDetails payPalDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payPalDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayPalDetails payPalDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payPalDetails._CheckoutAttemptIdOption.IsSet) + if (payPalDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payPalDetails.CheckoutAttemptId); + + if (payPalDetails._OrderIDOption.IsSet) + if (payPalDetails.OrderID != null) + writer.WriteString("orderID", payPalDetails.OrderID); + + if (payPalDetails._PayeePreferredOption.IsSet) + if (payPalDetails.PayeePreferred != null) + writer.WriteString("payeePreferred", payPalDetails.PayeePreferred); + + if (payPalDetails._PayerIDOption.IsSet) + if (payPalDetails.PayerID != null) + writer.WriteString("payerID", payPalDetails.PayerID); + + if (payPalDetails._PayerSelectedOption.IsSet) + if (payPalDetails.PayerSelected != null) + writer.WriteString("payerSelected", payPalDetails.PayerSelected); + + if (payPalDetails._RecurringDetailReferenceOption.IsSet) + if (payPalDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payPalDetails.RecurringDetailReference); + + if (payPalDetails._StoredPaymentMethodIdOption.IsSet) + if (payPalDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payPalDetails.StoredPaymentMethodId); + + if (payPalDetails._SubtypeOption.IsSet && payPalDetails.Subtype != null) + { + string? subtypeRawValue = PayPalDetails.SubtypeEnum.ToJsonValue(payPalDetails._SubtypeOption.Value!.Value); + writer.WriteString("subtype", subtypeRawValue); + } + + if (payPalDetails.Type != null) + { + string? typeRawValue = PayPalDetails.TypeEnum.ToJsonValue(payPalDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayPayDetails.cs b/Adyen/Checkout/Models/PayPayDetails.cs new file mode 100644 index 000000000..90d7399d5 --- /dev/null +++ b/Adyen/Checkout/Models/PayPayDetails.cs @@ -0,0 +1,356 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayPayDetails. + /// + public partial class PayPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **paypay** (default to TypeEnum.Paypay) + [JsonConstructor] + public PayPayDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **paypay** + /// + /// **paypay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Paypay - paypay + /// + public static readonly TypeEnum Paypay = new("paypay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paypay" => TypeEnum.Paypay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Paypay) + return "paypay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **paypay** + /// + /// **paypay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayPayDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PayPayDetails(checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayPayDetails payPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayPayDetails payPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payPayDetails._CheckoutAttemptIdOption.IsSet) + if (payPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payPayDetails.CheckoutAttemptId); + + if (payPayDetails._RecurringDetailReferenceOption.IsSet) + if (payPayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payPayDetails.RecurringDetailReference); + + if (payPayDetails._StoredPaymentMethodIdOption.IsSet) + if (payPayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payPayDetails.StoredPaymentMethodId); + + if (payPayDetails._TypeOption.IsSet && payPayDetails.Type != null) + { + string? typeRawValue = PayPayDetails.TypeEnum.ToJsonValue(payPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayToDetails.cs b/Adyen/Checkout/Models/PayToDetails.cs new file mode 100644 index 000000000..e9e5672b1 --- /dev/null +++ b/Adyen/Checkout/Models/PayToDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayToDetails. + /// + public partial class PayToDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The shopper's banking details or payId reference, used to complete payment. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **payto** (default to TypeEnum.Payto) + [JsonConstructor] + public PayToDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option shopperAccountIdentifier = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperAccountIdentifierOption = shopperAccountIdentifier; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayToDetails() + { + } + + partial void OnCreated(); + + /// + /// **payto** + /// + /// **payto** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Payto - payto + /// + public static readonly TypeEnum Payto = new("payto"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "payto" => TypeEnum.Payto, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Payto) + return "payto"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **payto** + /// + /// **payto** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperAccountIdentifierOption { get; private set; } + + /// + /// The shopper's banking details or payId reference, used to complete payment. + /// + /// The shopper's banking details or payId reference, used to complete payment. + [JsonPropertyName("shopperAccountIdentifier")] + public string? ShopperAccountIdentifier { get { return this._ShopperAccountIdentifierOption; } set { this._ShopperAccountIdentifierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayToDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperAccountIdentifier: ").Append(ShopperAccountIdentifier).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayToDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayToDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option shopperAccountIdentifier = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperAccountIdentifier": + shopperAccountIdentifier = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayToDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PayToDetails(checkoutAttemptId, recurringDetailReference, shopperAccountIdentifier, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayToDetails payToDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payToDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayToDetails payToDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payToDetails._CheckoutAttemptIdOption.IsSet) + if (payToDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payToDetails.CheckoutAttemptId); + + if (payToDetails._RecurringDetailReferenceOption.IsSet) + if (payToDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payToDetails.RecurringDetailReference); + + if (payToDetails._ShopperAccountIdentifierOption.IsSet) + if (payToDetails.ShopperAccountIdentifier != null) + writer.WriteString("shopperAccountIdentifier", payToDetails.ShopperAccountIdentifier); + + if (payToDetails._StoredPaymentMethodIdOption.IsSet) + if (payToDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payToDetails.StoredPaymentMethodId); + + if (payToDetails._TypeOption.IsSet && payToDetails.Type != null) + { + string? typeRawValue = PayToDetails.TypeEnum.ToJsonValue(payToDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayToPaymentMethod.cs b/Adyen/Checkout/Models/PayToPaymentMethod.cs new file mode 100644 index 000000000..ec52aecfc --- /dev/null +++ b/Adyen/Checkout/Models/PayToPaymentMethod.cs @@ -0,0 +1,170 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayToPaymentMethod. + /// + public partial class PayToPaymentMethod : ShopperIdPaymentMethod, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// shopperReference + [JsonConstructor] + public PayToPaymentMethod(Option shopperReference = default) : base() + { + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayToPaymentMethod {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class PayToPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayToPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PayToPaymentMethod.", nameof(type)); + + return new PayToPaymentMethod(shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayToPaymentMethod payToPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payToPaymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayToPaymentMethod payToPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (payToPaymentMethod.Type != null) + writer.WriteString("type", payToPaymentMethod.Type); + + if (payToPaymentMethod._ShopperReferenceOption.IsSet) + if (payToPaymentMethod.ShopperReference != null) + writer.WriteString("shopperReference", payToPaymentMethod.ShopperReference); + } + } +} diff --git a/Adyen/Checkout/Models/PayUUpiDetails.cs b/Adyen/Checkout/Models/PayUUpiDetails.cs new file mode 100644 index 000000000..b455b2116 --- /dev/null +++ b/Adyen/Checkout/Models/PayUUpiDetails.cs @@ -0,0 +1,401 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayUUpiDetails. + /// + public partial class PayUUpiDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **payu_IN_upi** (default to TypeEnum.PayuINUpi) + /// The virtual payment address for UPI. + [JsonConstructor] + public PayUUpiDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option storedPaymentMethodId = default, TypeEnum type = default, Option virtualPaymentAddress = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + _VirtualPaymentAddressOption = virtualPaymentAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayUUpiDetails() + { + } + + partial void OnCreated(); + + /// + /// **payu_IN_upi** + /// + /// **payu_IN_upi** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PayuINUpi - payu_IN_upi + /// + public static readonly TypeEnum PayuINUpi = new("payu_IN_upi"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "payu_IN_upi" => TypeEnum.PayuINUpi, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PayuINUpi) + return "payu_IN_upi"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **payu_IN_upi** + /// + /// **payu_IN_upi** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VirtualPaymentAddressOption { get; private set; } + + /// + /// The virtual payment address for UPI. + /// + /// The virtual payment address for UPI. + [JsonPropertyName("virtualPaymentAddress")] + public string? VirtualPaymentAddress { get { return this._VirtualPaymentAddressOption; } set { this._VirtualPaymentAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayUUpiDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" VirtualPaymentAddress: ").Append(VirtualPaymentAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayUUpiDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayUUpiDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option storedPaymentMethodId = default; + Option type = default; + Option virtualPaymentAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayUUpiDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "virtualPaymentAddress": + virtualPaymentAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PayUUpiDetails.", nameof(type)); + + return new PayUUpiDetails(checkoutAttemptId, recurringDetailReference, shopperNotificationReference, storedPaymentMethodId, type.Value!.Value!, virtualPaymentAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayUUpiDetails payUUpiDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payUUpiDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayUUpiDetails payUUpiDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payUUpiDetails._CheckoutAttemptIdOption.IsSet) + if (payUUpiDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payUUpiDetails.CheckoutAttemptId); + + if (payUUpiDetails._RecurringDetailReferenceOption.IsSet) + if (payUUpiDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payUUpiDetails.RecurringDetailReference); + + if (payUUpiDetails._ShopperNotificationReferenceOption.IsSet) + if (payUUpiDetails.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", payUUpiDetails.ShopperNotificationReference); + + if (payUUpiDetails._StoredPaymentMethodIdOption.IsSet) + if (payUUpiDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payUUpiDetails.StoredPaymentMethodId); + + if (payUUpiDetails.Type != null) + { + string? typeRawValue = PayUUpiDetails.TypeEnum.ToJsonValue(payUUpiDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (payUUpiDetails._VirtualPaymentAddressOption.IsSet) + if (payUUpiDetails.VirtualPaymentAddress != null) + writer.WriteString("virtualPaymentAddress", payUUpiDetails.VirtualPaymentAddress); + } + } +} diff --git a/Adyen/Checkout/Models/PayWithGoogleDetails.cs b/Adyen/Checkout/Models/PayWithGoogleDetails.cs new file mode 100644 index 000000000..e762ae4d6 --- /dev/null +++ b/Adyen/Checkout/Models/PayWithGoogleDetails.cs @@ -0,0 +1,543 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayWithGoogleDetails. + /// + public partial class PayWithGoogleDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// **paywithgoogle** (default to TypeEnum.Paywithgoogle) + [JsonConstructor] + public PayWithGoogleDetails(string googlePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + GooglePayToken = googlePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayWithGoogleDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **paywithgoogle** + /// + /// **paywithgoogle** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Paywithgoogle - paywithgoogle + /// + public static readonly TypeEnum Paywithgoogle = new("paywithgoogle"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paywithgoogle" => TypeEnum.Paywithgoogle, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Paywithgoogle) + return "paywithgoogle"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **paywithgoogle** + /// + /// **paywithgoogle** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + [JsonPropertyName("googlePayToken")] + public string GooglePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayWithGoogleDetails {\n"); + sb.Append(" GooglePayToken: ").Append(GooglePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // GooglePayToken (string) maxLength + if (this.GooglePayToken != null && this.GooglePayToken.Length > 5000) + { + yield return new ValidationResult("Invalid value for GooglePayToken, length must be less than 5000.", new [] { "GooglePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayWithGoogleDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayWithGoogleDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option googlePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "googlePayToken": + googlePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(PayWithGoogleDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayWithGoogleDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!googlePayToken.IsSet) + throw new ArgumentException("Property is required for class PayWithGoogleDetails.", nameof(googlePayToken)); + + return new PayWithGoogleDetails(googlePayToken.Value!, checkoutAttemptId, fundingSource, recurringDetailReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayWithGoogleDetails payWithGoogleDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payWithGoogleDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayWithGoogleDetails payWithGoogleDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (payWithGoogleDetails.GooglePayToken != null) + writer.WriteString("googlePayToken", payWithGoogleDetails.GooglePayToken); + + if (payWithGoogleDetails._CheckoutAttemptIdOption.IsSet) + if (payWithGoogleDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payWithGoogleDetails.CheckoutAttemptId); + + if (payWithGoogleDetails._FundingSourceOption.IsSet && payWithGoogleDetails.FundingSource != null) + { + string? fundingSourceRawValue = PayWithGoogleDetails.FundingSourceEnum.ToJsonValue(payWithGoogleDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (payWithGoogleDetails._RecurringDetailReferenceOption.IsSet) + if (payWithGoogleDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payWithGoogleDetails.RecurringDetailReference); + + if (payWithGoogleDetails._StoredPaymentMethodIdOption.IsSet) + if (payWithGoogleDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payWithGoogleDetails.StoredPaymentMethodId); + + if (payWithGoogleDetails._ThreeDS2SdkVersionOption.IsSet) + if (payWithGoogleDetails.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", payWithGoogleDetails.ThreeDS2SdkVersion); + + if (payWithGoogleDetails._TypeOption.IsSet && payWithGoogleDetails.Type != null) + { + string? typeRawValue = PayWithGoogleDetails.TypeEnum.ToJsonValue(payWithGoogleDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PayWithGoogleDonations.cs b/Adyen/Checkout/Models/PayWithGoogleDonations.cs new file mode 100644 index 000000000..f08dd6f0f --- /dev/null +++ b/Adyen/Checkout/Models/PayWithGoogleDonations.cs @@ -0,0 +1,543 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PayWithGoogleDonations. + /// + public partial class PayWithGoogleDonations : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// **paywithgoogle** (default to TypeEnum.Paywithgoogle) + [JsonConstructor] + public PayWithGoogleDonations(string googlePayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option threeDS2SdkVersion = default, Option type = default) + { + GooglePayToken = googlePayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _ThreeDS2SdkVersionOption = threeDS2SdkVersion; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayWithGoogleDonations() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **paywithgoogle** + /// + /// **paywithgoogle** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Paywithgoogle - paywithgoogle + /// + public static readonly TypeEnum Paywithgoogle = new("paywithgoogle"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paywithgoogle" => TypeEnum.Paywithgoogle, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Paywithgoogle) + return "paywithgoogle"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **paywithgoogle** + /// + /// **paywithgoogle** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + /// + /// The `token` that you obtained from the [Google Pay API](https://developers.google.com/pay/api/web/reference/response-objects#PaymentData) `PaymentData` response. + [JsonPropertyName("googlePayToken")] + public string GooglePayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2SdkVersionOption { get; private set; } + + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + /// + /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK. + [JsonPropertyName("threeDS2SdkVersion")] + public string? ThreeDS2SdkVersion { get { return this._ThreeDS2SdkVersionOption; } set { this._ThreeDS2SdkVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayWithGoogleDonations {\n"); + sb.Append(" GooglePayToken: ").Append(GooglePayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" ThreeDS2SdkVersion: ").Append(ThreeDS2SdkVersion).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // GooglePayToken (string) maxLength + if (this.GooglePayToken != null && this.GooglePayToken.Length > 5000) + { + yield return new ValidationResult("Invalid value for GooglePayToken, length must be less than 5000.", new [] { "GooglePayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + // ThreeDS2SdkVersion (string) maxLength + if (this.ThreeDS2SdkVersion != null && this.ThreeDS2SdkVersion.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDS2SdkVersion, length must be less than 12.", new [] { "ThreeDS2SdkVersion" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayWithGoogleDonationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayWithGoogleDonations Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option googlePayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option threeDS2SdkVersion = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "googlePayToken": + googlePayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(PayWithGoogleDonations.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2SdkVersion": + threeDS2SdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PayWithGoogleDonations.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!googlePayToken.IsSet) + throw new ArgumentException("Property is required for class PayWithGoogleDonations.", nameof(googlePayToken)); + + return new PayWithGoogleDonations(googlePayToken.Value!, checkoutAttemptId, fundingSource, recurringDetailReference, storedPaymentMethodId, threeDS2SdkVersion, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayWithGoogleDonations payWithGoogleDonations, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payWithGoogleDonations, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayWithGoogleDonations payWithGoogleDonations, JsonSerializerOptions jsonSerializerOptions) + { + + if (payWithGoogleDonations.GooglePayToken != null) + writer.WriteString("googlePayToken", payWithGoogleDonations.GooglePayToken); + + if (payWithGoogleDonations._CheckoutAttemptIdOption.IsSet) + if (payWithGoogleDonations.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", payWithGoogleDonations.CheckoutAttemptId); + + if (payWithGoogleDonations._FundingSourceOption.IsSet && payWithGoogleDonations.FundingSource != null) + { + string? fundingSourceRawValue = PayWithGoogleDonations.FundingSourceEnum.ToJsonValue(payWithGoogleDonations._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (payWithGoogleDonations._RecurringDetailReferenceOption.IsSet) + if (payWithGoogleDonations.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", payWithGoogleDonations.RecurringDetailReference); + + if (payWithGoogleDonations._StoredPaymentMethodIdOption.IsSet) + if (payWithGoogleDonations.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", payWithGoogleDonations.StoredPaymentMethodId); + + if (payWithGoogleDonations._ThreeDS2SdkVersionOption.IsSet) + if (payWithGoogleDonations.ThreeDS2SdkVersion != null) + writer.WriteString("threeDS2SdkVersion", payWithGoogleDonations.ThreeDS2SdkVersion); + + if (payWithGoogleDonations._TypeOption.IsSet && payWithGoogleDonations.Type != null) + { + string? typeRawValue = PayWithGoogleDonations.TypeEnum.ToJsonValue(payWithGoogleDonations._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Payment.cs b/Adyen/Checkout/Models/Payment.cs new file mode 100644 index 000000000..c6a87ff85 --- /dev/null +++ b/Adyen/Checkout/Models/Payment.cs @@ -0,0 +1,349 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Payment. + /// + public partial class Payment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// paymentMethod + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request. + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + [JsonConstructor] + public Payment(Option amount = default, Option paymentMethod = default, Option pspReference = default, Option resultCode = default) + { + _AmountOption = amount; + _PaymentMethodOption = paymentMethod; + _PspReferenceOption = pspReference; + _ResultCodeOption = resultCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Payment() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Authorised - Authorised + /// + public static readonly ResultCodeEnum Authorised = new("Authorised"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Authorised" => ResultCodeEnum.Authorised, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Authorised) + return "Authorised"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public ResponsePaymentMethod? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Payment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Payment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option paymentMethod = default; + Option pspReference = default; + Option resultCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(Payment.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + default: + break; + } + } + } + + + return new Payment(amount, paymentMethod, pspReference, resultCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Payment payment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Payment payment, JsonSerializerOptions jsonSerializerOptions) + { + + if (payment._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, payment.Amount, jsonSerializerOptions); + } + if (payment._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, payment.PaymentMethod, jsonSerializerOptions); + } + if (payment._PspReferenceOption.IsSet) + if (payment.PspReference != null) + writer.WriteString("pspReference", payment.PspReference); + + if (payment._ResultCodeOption.IsSet && payment.ResultCode != null) + { + string? resultCodeRawValue = Payment.ResultCodeEnum.ToJsonValue(payment._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentAmountUpdateRequest.cs b/Adyen/Checkout/Models/PaymentAmountUpdateRequest.cs new file mode 100644 index 000000000..894eeaa21 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentAmountUpdateRequest.cs @@ -0,0 +1,457 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentAmountUpdateRequest. + /// + public partial class PaymentAmountUpdateRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// applicationInfo + /// enhancedSchemeData + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// Your reference for the amount update request. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + [JsonConstructor] + public PaymentAmountUpdateRequest(Amount amount, string merchantAccount, Option applicationInfo = default, Option enhancedSchemeData = default, Option industryUsage = default, Option?> lineItems = default, Option reference = default, Option?> splits = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + _ApplicationInfoOption = applicationInfo; + _EnhancedSchemeDataOption = enhancedSchemeData; + _IndustryUsageOption = industryUsage; + _LineItemsOption = lineItems; + _ReferenceOption = reference; + _SplitsOption = splits; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentAmountUpdateRequest() + { + } + + partial void OnCreated(); + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonConverter(typeof(IndustryUsageEnumJsonConverter))] + public class IndustryUsageEnum : IEnum + { + /// + /// Returns the value of the IndustryUsageEnum. + /// + public string? Value { get; set; } + + /// + /// IndustryUsageEnum.DelayedCharge - delayedCharge + /// + public static readonly IndustryUsageEnum DelayedCharge = new("delayedCharge"); + + /// + /// IndustryUsageEnum.Installment - installment + /// + public static readonly IndustryUsageEnum Installment = new("installment"); + + /// + /// IndustryUsageEnum.NoShow - noShow + /// + public static readonly IndustryUsageEnum NoShow = new("noShow"); + + private IndustryUsageEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IndustryUsageEnum?(string? value) => value == null ? null : new IndustryUsageEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IndustryUsageEnum? option) => option?.Value; + + public static bool operator ==(IndustryUsageEnum? left, IndustryUsageEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IndustryUsageEnum? left, IndustryUsageEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IndustryUsageEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IndustryUsageEnum? FromStringOrDefault(string value) + { + return value switch { + "delayedCharge" => IndustryUsageEnum.DelayedCharge, + "installment" => IndustryUsageEnum.Installment, + "noShow" => IndustryUsageEnum.NoShow, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IndustryUsageEnum? value) + { + if (value == null) + return null; + + if (value == IndustryUsageEnum.DelayedCharge) + return "delayedCharge"; + + if (value == IndustryUsageEnum.Installment) + return "installment"; + + if (value == IndustryUsageEnum.NoShow) + return "noShow"; + + return null; + } + + /// + /// JsonConverter for writing IndustryUsageEnum. + /// + public class IndustryUsageEnumJsonConverter : JsonConverter + { + public override IndustryUsageEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IndustryUsageEnum.FromStringOrDefault(value) ?? new IndustryUsageEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IndustryUsageEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IndustryUsageEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryUsageOption { get; private set; } + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonPropertyName("industryUsage")] + public IndustryUsageEnum? IndustryUsage { get { return this._IndustryUsageOption; } set { this._IndustryUsageOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the amount update request. Maximum length: 80 characters. + /// + /// Your reference for the amount update request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentAmountUpdateRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentAmountUpdateRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentAmountUpdateRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option applicationInfo = default; + Option enhancedSchemeData = default; + Option industryUsage = default; + Option?> lineItems = default; + Option reference = default; + Option?> splits = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "industryUsage": + string? industryUsageRawValue = utf8JsonReader.GetString(); + industryUsage = new Option(PaymentAmountUpdateRequest.IndustryUsageEnum.FromStringOrDefault(industryUsageRawValue)); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateRequest.", nameof(merchantAccount)); + + return new PaymentAmountUpdateRequest(amount.Value!, merchantAccount.Value!, applicationInfo, enhancedSchemeData, industryUsage, lineItems, reference, splits); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentAmountUpdateRequest paymentAmountUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentAmountUpdateRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentAmountUpdateRequest paymentAmountUpdateRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentAmountUpdateRequest.Amount, jsonSerializerOptions); + if (paymentAmountUpdateRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentAmountUpdateRequest.MerchantAccount); + + if (paymentAmountUpdateRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentAmountUpdateRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentAmountUpdateRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentAmountUpdateRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentAmountUpdateRequest._IndustryUsageOption.IsSet && paymentAmountUpdateRequest.IndustryUsage != null) + { + string? industryUsageRawValue = PaymentAmountUpdateRequest.IndustryUsageEnum.ToJsonValue(paymentAmountUpdateRequest._IndustryUsageOption.Value!.Value); + writer.WriteString("industryUsage", industryUsageRawValue); + } + + if (paymentAmountUpdateRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentAmountUpdateRequest.LineItems, jsonSerializerOptions); + } + if (paymentAmountUpdateRequest._ReferenceOption.IsSet) + if (paymentAmountUpdateRequest.Reference != null) + writer.WriteString("reference", paymentAmountUpdateRequest.Reference); + + if (paymentAmountUpdateRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentAmountUpdateRequest.Splits, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentAmountUpdateResponse.cs b/Adyen/Checkout/Models/PaymentAmountUpdateResponse.cs new file mode 100644 index 000000000..14054bdf1 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentAmountUpdateResponse.cs @@ -0,0 +1,560 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentAmountUpdateResponse. + /// + public partial class PaymentAmountUpdateResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to update. + /// Adyen's 16-character reference associated with the amount update request. + /// Your reference for the amount update request. Maximum length: 80 characters. + /// The status of your request. This will always have the value **received**. + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + [JsonConstructor] + public PaymentAmountUpdateResponse(Amount amount, string merchantAccount, string paymentPspReference, string pspReference, string reference, StatusEnum status, Option industryUsage = default, Option?> lineItems = default, Option?> splits = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentPspReference = paymentPspReference; + PspReference = pspReference; + Reference = reference; + Status = status; + _IndustryUsageOption = industryUsage; + _LineItemsOption = lineItems; + _SplitsOption = splits; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentAmountUpdateResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonConverter(typeof(IndustryUsageEnumJsonConverter))] + public class IndustryUsageEnum : IEnum + { + /// + /// Returns the value of the IndustryUsageEnum. + /// + public string? Value { get; set; } + + /// + /// IndustryUsageEnum.DelayedCharge - delayedCharge + /// + public static readonly IndustryUsageEnum DelayedCharge = new("delayedCharge"); + + /// + /// IndustryUsageEnum.Installment - installment + /// + public static readonly IndustryUsageEnum Installment = new("installment"); + + /// + /// IndustryUsageEnum.NoShow - noShow + /// + public static readonly IndustryUsageEnum NoShow = new("noShow"); + + private IndustryUsageEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IndustryUsageEnum?(string? value) => value == null ? null : new IndustryUsageEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IndustryUsageEnum? option) => option?.Value; + + public static bool operator ==(IndustryUsageEnum? left, IndustryUsageEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IndustryUsageEnum? left, IndustryUsageEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IndustryUsageEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IndustryUsageEnum? FromStringOrDefault(string value) + { + return value switch { + "delayedCharge" => IndustryUsageEnum.DelayedCharge, + "installment" => IndustryUsageEnum.Installment, + "noShow" => IndustryUsageEnum.NoShow, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IndustryUsageEnum? value) + { + if (value == null) + return null; + + if (value == IndustryUsageEnum.DelayedCharge) + return "delayedCharge"; + + if (value == IndustryUsageEnum.Installment) + return "installment"; + + if (value == IndustryUsageEnum.NoShow) + return "noShow"; + + return null; + } + + /// + /// JsonConverter for writing IndustryUsageEnum. + /// + public class IndustryUsageEnumJsonConverter : JsonConverter + { + public override IndustryUsageEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IndustryUsageEnum.FromStringOrDefault(value) ?? new IndustryUsageEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IndustryUsageEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IndustryUsageEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryUsageOption { get; private set; } + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonPropertyName("industryUsage")] + public IndustryUsageEnum? IndustryUsage { get { return this._IndustryUsageOption; } set { this._IndustryUsageOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to update. + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to update. + [JsonPropertyName("paymentPspReference")] + public string PaymentPspReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the amount update request. + /// + /// Adyen's 16-character reference associated with the amount update request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// Your reference for the amount update request. Maximum length: 80 characters. + /// + /// Your reference for the amount update request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentAmountUpdateResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentPspReference: ").Append(PaymentPspReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentAmountUpdateResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentAmountUpdateResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option paymentPspReference = default; + Option pspReference = default; + Option reference = default; + Option status = default; + Option industryUsage = default; + Option?> lineItems = default; + Option?> splits = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentPspReference": + paymentPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentAmountUpdateResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "industryUsage": + string? industryUsageRawValue = utf8JsonReader.GetString(); + industryUsage = new Option(PaymentAmountUpdateResponse.IndustryUsageEnum.FromStringOrDefault(industryUsageRawValue)); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(merchantAccount)); + + if (!paymentPspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(paymentPspReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(pspReference)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(reference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentAmountUpdateResponse.", nameof(status)); + + return new PaymentAmountUpdateResponse(amount.Value!, merchantAccount.Value!, paymentPspReference.Value!, pspReference.Value!, reference.Value!, status.Value!.Value!, industryUsage, lineItems, splits); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentAmountUpdateResponse paymentAmountUpdateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentAmountUpdateResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentAmountUpdateResponse paymentAmountUpdateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentAmountUpdateResponse.Amount, jsonSerializerOptions); + if (paymentAmountUpdateResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentAmountUpdateResponse.MerchantAccount); + + if (paymentAmountUpdateResponse.PaymentPspReference != null) + writer.WriteString("paymentPspReference", paymentAmountUpdateResponse.PaymentPspReference); + + if (paymentAmountUpdateResponse.PspReference != null) + writer.WriteString("pspReference", paymentAmountUpdateResponse.PspReference); + + if (paymentAmountUpdateResponse.Reference != null) + writer.WriteString("reference", paymentAmountUpdateResponse.Reference); + + if (paymentAmountUpdateResponse.Status != null) + { + string? statusRawValue = PaymentAmountUpdateResponse.StatusEnum.ToJsonValue(paymentAmountUpdateResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentAmountUpdateResponse._IndustryUsageOption.IsSet && paymentAmountUpdateResponse.IndustryUsage != null) + { + string? industryUsageRawValue = PaymentAmountUpdateResponse.IndustryUsageEnum.ToJsonValue(paymentAmountUpdateResponse._IndustryUsageOption.Value!.Value); + writer.WriteString("industryUsage", industryUsageRawValue); + } + + if (paymentAmountUpdateResponse._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentAmountUpdateResponse.LineItems, jsonSerializerOptions); + } + if (paymentAmountUpdateResponse._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentAmountUpdateResponse.Splits, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentCancelRequest.cs b/Adyen/Checkout/Models/PaymentCancelRequest.cs new file mode 100644 index 000000000..81103644a --- /dev/null +++ b/Adyen/Checkout/Models/PaymentCancelRequest.cs @@ -0,0 +1,246 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentCancelRequest. + /// + public partial class PaymentCancelRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// applicationInfo + /// enhancedSchemeData + /// Your reference for the cancel request. Maximum length: 80 characters. + [JsonConstructor] + public PaymentCancelRequest(string merchantAccount, Option applicationInfo = default, Option enhancedSchemeData = default, Option reference = default) + { + MerchantAccount = merchantAccount; + _ApplicationInfoOption = applicationInfo; + _EnhancedSchemeDataOption = enhancedSchemeData; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentCancelRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the cancel request. Maximum length: 80 characters. + /// + /// Your reference for the cancel request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentCancelRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentCancelRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentCancelRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option applicationInfo = default; + Option enhancedSchemeData = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentCancelRequest.", nameof(merchantAccount)); + + return new PaymentCancelRequest(merchantAccount.Value!, applicationInfo, enhancedSchemeData, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentCancelRequest paymentCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentCancelRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentCancelRequest paymentCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentCancelRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentCancelRequest.MerchantAccount); + + if (paymentCancelRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentCancelRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentCancelRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentCancelRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentCancelRequest._ReferenceOption.IsSet) + if (paymentCancelRequest.Reference != null) + writer.WriteString("reference", paymentCancelRequest.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentCancelResponse.cs b/Adyen/Checkout/Models/PaymentCancelResponse.cs new file mode 100644 index 000000000..47715f03c --- /dev/null +++ b/Adyen/Checkout/Models/PaymentCancelResponse.cs @@ -0,0 +1,354 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentCancelResponse. + /// + public partial class PaymentCancelResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to cancel. + /// Adyen's 16-character reference associated with the cancel request. + /// The status of your request. This will always have the value **received**. + /// Your reference for the cancel request. + [JsonConstructor] + public PaymentCancelResponse(string merchantAccount, string paymentPspReference, string pspReference, StatusEnum status, Option reference = default) + { + MerchantAccount = merchantAccount; + PaymentPspReference = paymentPspReference; + PspReference = pspReference; + Status = status; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentCancelResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to cancel. + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to cancel. + [JsonPropertyName("paymentPspReference")] + public string PaymentPspReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the cancel request. + /// + /// Adyen's 16-character reference associated with the cancel request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the cancel request. + /// + /// Your reference for the cancel request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentCancelResponse {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentPspReference: ").Append(PaymentPspReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentCancelResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentCancelResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentPspReference = default; + Option pspReference = default; + Option status = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentPspReference": + paymentPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentCancelResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentCancelResponse.", nameof(merchantAccount)); + + if (!paymentPspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentCancelResponse.", nameof(paymentPspReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentCancelResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentCancelResponse.", nameof(status)); + + return new PaymentCancelResponse(merchantAccount.Value!, paymentPspReference.Value!, pspReference.Value!, status.Value!.Value!, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentCancelResponse paymentCancelResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentCancelResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentCancelResponse paymentCancelResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentCancelResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentCancelResponse.MerchantAccount); + + if (paymentCancelResponse.PaymentPspReference != null) + writer.WriteString("paymentPspReference", paymentCancelResponse.PaymentPspReference); + + if (paymentCancelResponse.PspReference != null) + writer.WriteString("pspReference", paymentCancelResponse.PspReference); + + if (paymentCancelResponse.Status != null) + { + string? statusRawValue = PaymentCancelResponse.StatusEnum.ToJsonValue(paymentCancelResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentCancelResponse._ReferenceOption.IsSet) + if (paymentCancelResponse.Reference != null) + writer.WriteString("reference", paymentCancelResponse.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentCaptureRequest.cs b/Adyen/Checkout/Models/PaymentCaptureRequest.cs new file mode 100644 index 000000000..abc9a3626 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentCaptureRequest.cs @@ -0,0 +1,368 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentCaptureRequest. + /// + public partial class PaymentCaptureRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// applicationInfo + /// enhancedSchemeData + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// platformChargebackLogic + /// Your reference for the capture request. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// A List of sub-merchants. + [JsonConstructor] + public PaymentCaptureRequest(Amount amount, string merchantAccount, Option applicationInfo = default, Option enhancedSchemeData = default, Option?> lineItems = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option?> subMerchants = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + _ApplicationInfoOption = applicationInfo; + _EnhancedSchemeDataOption = enhancedSchemeData; + _LineItemsOption = lineItems; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _SubMerchantsOption = subMerchants; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentCaptureRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the capture request. Maximum length: 80 characters. + /// + /// Your reference for the capture request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubMerchantsOption { get; private set; } + + /// + /// A List of sub-merchants. + /// + /// A List of sub-merchants. + [JsonPropertyName("subMerchants")] + public List? SubMerchants { get { return this._SubMerchantsOption; } set { this._SubMerchantsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentCaptureRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" SubMerchants: ").Append(SubMerchants).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentCaptureRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentCaptureRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option applicationInfo = default; + Option enhancedSchemeData = default; + Option?> lineItems = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option?> subMerchants = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subMerchants": + subMerchants = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureRequest.", nameof(merchantAccount)); + + return new PaymentCaptureRequest(amount.Value!, merchantAccount.Value!, applicationInfo, enhancedSchemeData, lineItems, platformChargebackLogic, reference, splits, subMerchants); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentCaptureRequest paymentCaptureRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentCaptureRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentCaptureRequest paymentCaptureRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.Amount, jsonSerializerOptions); + if (paymentCaptureRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentCaptureRequest.MerchantAccount); + + if (paymentCaptureRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentCaptureRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentCaptureRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.LineItems, jsonSerializerOptions); + } + if (paymentCaptureRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentCaptureRequest._ReferenceOption.IsSet) + if (paymentCaptureRequest.Reference != null) + writer.WriteString("reference", paymentCaptureRequest.Reference); + + if (paymentCaptureRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.Splits, jsonSerializerOptions); + } + if (paymentCaptureRequest._SubMerchantsOption.IsSet) + { + writer.WritePropertyName("subMerchants"); + JsonSerializer.Serialize(writer, paymentCaptureRequest.SubMerchants, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentCaptureResponse.cs b/Adyen/Checkout/Models/PaymentCaptureResponse.cs new file mode 100644 index 000000000..e9d358199 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentCaptureResponse.cs @@ -0,0 +1,476 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentCaptureResponse. + /// + public partial class PaymentCaptureResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to capture. + /// Adyen's 16-character reference associated with the capture request. + /// The status of your request. This will always have the value **received**. + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// platformChargebackLogic + /// Your reference for the capture request. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// List of sub-merchants. + [JsonConstructor] + public PaymentCaptureResponse(Amount amount, string merchantAccount, string paymentPspReference, string pspReference, StatusEnum status, Option?> lineItems = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option?> subMerchants = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentPspReference = paymentPspReference; + PspReference = pspReference; + Status = status; + _LineItemsOption = lineItems; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _SubMerchantsOption = subMerchants; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentCaptureResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to capture. + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to capture. + [JsonPropertyName("paymentPspReference")] + public string PaymentPspReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the capture request. + /// + /// Adyen's 16-character reference associated with the capture request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the capture request. + /// + /// Your reference for the capture request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubMerchantsOption { get; private set; } + + /// + /// List of sub-merchants. + /// + /// List of sub-merchants. + [JsonPropertyName("subMerchants")] + public List? SubMerchants { get { return this._SubMerchantsOption; } set { this._SubMerchantsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentCaptureResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentPspReference: ").Append(PaymentPspReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" SubMerchants: ").Append(SubMerchants).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentCaptureResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentCaptureResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option paymentPspReference = default; + Option pspReference = default; + Option status = default; + Option?> lineItems = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option?> subMerchants = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentPspReference": + paymentPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentCaptureResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subMerchants": + subMerchants = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureResponse.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureResponse.", nameof(merchantAccount)); + + if (!paymentPspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureResponse.", nameof(paymentPspReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentCaptureResponse.", nameof(status)); + + return new PaymentCaptureResponse(amount.Value!, merchantAccount.Value!, paymentPspReference.Value!, pspReference.Value!, status.Value!.Value!, lineItems, platformChargebackLogic, reference, splits, subMerchants); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentCaptureResponse paymentCaptureResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentCaptureResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentCaptureResponse paymentCaptureResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentCaptureResponse.Amount, jsonSerializerOptions); + if (paymentCaptureResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentCaptureResponse.MerchantAccount); + + if (paymentCaptureResponse.PaymentPspReference != null) + writer.WriteString("paymentPspReference", paymentCaptureResponse.PaymentPspReference); + + if (paymentCaptureResponse.PspReference != null) + writer.WriteString("pspReference", paymentCaptureResponse.PspReference); + + if (paymentCaptureResponse.Status != null) + { + string? statusRawValue = PaymentCaptureResponse.StatusEnum.ToJsonValue(paymentCaptureResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentCaptureResponse._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentCaptureResponse.LineItems, jsonSerializerOptions); + } + if (paymentCaptureResponse._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentCaptureResponse.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentCaptureResponse._ReferenceOption.IsSet) + if (paymentCaptureResponse.Reference != null) + writer.WriteString("reference", paymentCaptureResponse.Reference); + + if (paymentCaptureResponse._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentCaptureResponse.Splits, jsonSerializerOptions); + } + if (paymentCaptureResponse._SubMerchantsOption.IsSet) + { + writer.WritePropertyName("subMerchants"); + JsonSerializer.Serialize(writer, paymentCaptureResponse.SubMerchants, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentCompletionDetails.cs b/Adyen/Checkout/Models/PaymentCompletionDetails.cs new file mode 100644 index 000000000..2e4d4cbaf --- /dev/null +++ b/Adyen/Checkout/Models/PaymentCompletionDetails.cs @@ -0,0 +1,705 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentCompletionDetails. + /// + public partial class PaymentCompletionDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A payment session identifier returned by the card issuer. + /// (3D) Payment Authentication Request data for the card issuer. + /// (3D) Payment Authentication Response data by the card issuer. + /// authorizationToken + /// PayPal-generated token for recurring payments. + /// The SMS verification code collected from the shopper. + /// PayPal-generated third party access token. + /// A random number sent to the mobile phone number of the shopper to verify the payment. + /// PayPal-assigned ID for the order. + /// PayPal-assigned ID for the payer (shopper). + /// Payload appended to the `returnURL` as a result of the redirect. + /// PayPal-generated ID for the payment. + /// Value passed from the WeChat MiniProgram `wx.requestPayment` **complete** callback. Possible values: any value starting with `requestPayment:`. + /// The result of the redirect as appended to the `returnURL`. + /// Value you received from the WeChat Pay SDK. + /// The query string as appended to the `returnURL` when using direct issuer links . + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameters: `transStatus`, `authorisationToken`. + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `transStatus`. + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `threeDSCompInd`. + /// PayPalv2-generated token for recurring payments. + [JsonConstructor] + public PaymentCompletionDetails(Option mD = default, Option paReq = default, Option paRes = default, Option authorizationToken = default, Option billingToken = default, Option cupsecureplusSmscode = default, Option facilitatorAccessToken = default, Option oneTimePasscode = default, Option orderID = default, Option payerID = default, Option payload = default, Option paymentID = default, Option paymentStatus = default, Option redirectResult = default, Option resultCode = default, Option returnUrlQueryString = default, Option threeDSResult = default, Option threeds2ChallengeResult = default, Option threeds2Fingerprint = default, Option vaultToken = default) + { + _MDOption = mD; + _PaReqOption = paReq; + _PaResOption = paRes; + _AuthorizationTokenOption = authorizationToken; + _BillingTokenOption = billingToken; + _CupsecureplusSmscodeOption = cupsecureplusSmscode; + _FacilitatorAccessTokenOption = facilitatorAccessToken; + _OneTimePasscodeOption = oneTimePasscode; + _OrderIDOption = orderID; + _PayerIDOption = payerID; + _PayloadOption = payload; + _PaymentIDOption = paymentID; + _PaymentStatusOption = paymentStatus; + _RedirectResultOption = redirectResult; + _ResultCodeOption = resultCode; + _ReturnUrlQueryStringOption = returnUrlQueryString; + _ThreeDSResultOption = threeDSResult; + _Threeds2ChallengeResultOption = threeds2ChallengeResult; + _Threeds2FingerprintOption = threeds2Fingerprint; + _VaultTokenOption = vaultToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentCompletionDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MDOption { get; private set; } + + /// + /// A payment session identifier returned by the card issuer. + /// + /// A payment session identifier returned by the card issuer. + [JsonPropertyName("MD")] + public string? MD { get { return this._MDOption; } set { this._MDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaReqOption { get; private set; } + + /// + /// (3D) Payment Authentication Request data for the card issuer. + /// + /// (3D) Payment Authentication Request data for the card issuer. + [JsonPropertyName("PaReq")] + public string? PaReq { get { return this._PaReqOption; } set { this._PaReqOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaResOption { get; private set; } + + /// + /// (3D) Payment Authentication Response data by the card issuer. + /// + /// (3D) Payment Authentication Response data by the card issuer. + [JsonPropertyName("PaRes")] + public string? PaRes { get { return this._PaResOption; } set { this._PaResOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorizationTokenOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authorization_token")] + public string? AuthorizationToken { get { return this._AuthorizationTokenOption; } set { this._AuthorizationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingTokenOption { get; private set; } + + /// + /// PayPal-generated token for recurring payments. + /// + /// PayPal-generated token for recurring payments. + [JsonPropertyName("billingToken")] + public string? BillingToken { get { return this._BillingTokenOption; } set { this._BillingTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupsecureplusSmscodeOption { get; private set; } + + /// + /// The SMS verification code collected from the shopper. + /// + /// The SMS verification code collected from the shopper. + [JsonPropertyName("cupsecureplus.smscode")] + public string? CupsecureplusSmscode { get { return this._CupsecureplusSmscodeOption; } set { this._CupsecureplusSmscodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FacilitatorAccessTokenOption { get; private set; } + + /// + /// PayPal-generated third party access token. + /// + /// PayPal-generated third party access token. + [JsonPropertyName("facilitatorAccessToken")] + public string? FacilitatorAccessToken { get { return this._FacilitatorAccessTokenOption; } set { this._FacilitatorAccessTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OneTimePasscodeOption { get; private set; } + + /// + /// A random number sent to the mobile phone number of the shopper to verify the payment. + /// + /// A random number sent to the mobile phone number of the shopper to verify the payment. + [JsonPropertyName("oneTimePasscode")] + public string? OneTimePasscode { get { return this._OneTimePasscodeOption; } set { this._OneTimePasscodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderIDOption { get; private set; } + + /// + /// PayPal-assigned ID for the order. + /// + /// PayPal-assigned ID for the order. + [JsonPropertyName("orderID")] + public string? OrderID { get { return this._OrderIDOption; } set { this._OrderIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayerIDOption { get; private set; } + + /// + /// PayPal-assigned ID for the payer (shopper). + /// + /// PayPal-assigned ID for the payer (shopper). + [JsonPropertyName("payerID")] + public string? PayerID { get { return this._PayerIDOption; } set { this._PayerIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayloadOption { get; private set; } + + /// + /// Payload appended to the `returnURL` as a result of the redirect. + /// + /// Payload appended to the `returnURL` as a result of the redirect. + [JsonPropertyName("payload")] + public string? Payload { get { return this._PayloadOption; } set { this._PayloadOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentIDOption { get; private set; } + + /// + /// PayPal-generated ID for the payment. + /// + /// PayPal-generated ID for the payment. + [JsonPropertyName("paymentID")] + public string? PaymentID { get { return this._PaymentIDOption; } set { this._PaymentIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentStatusOption { get; private set; } + + /// + /// Value passed from the WeChat MiniProgram `wx.requestPayment` **complete** callback. Possible values: any value starting with `requestPayment:`. + /// + /// Value passed from the WeChat MiniProgram `wx.requestPayment` **complete** callback. Possible values: any value starting with `requestPayment:`. + [JsonPropertyName("paymentStatus")] + public string? PaymentStatus { get { return this._PaymentStatusOption; } set { this._PaymentStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectResultOption { get; private set; } + + /// + /// The result of the redirect as appended to the `returnURL`. + /// + /// The result of the redirect as appended to the `returnURL`. + [JsonPropertyName("redirectResult")] + public string? RedirectResult { get { return this._RedirectResultOption; } set { this._RedirectResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// Value you received from the WeChat Pay SDK. + /// + /// Value you received from the WeChat Pay SDK. + [JsonPropertyName("resultCode")] + public string? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReturnUrlQueryStringOption { get; private set; } + + /// + /// The query string as appended to the `returnURL` when using direct issuer links . + /// + /// The query string as appended to the `returnURL` when using direct issuer links . + [JsonPropertyName("returnUrlQueryString")] + public string? ReturnUrlQueryString { get { return this._ReturnUrlQueryStringOption; } set { this._ReturnUrlQueryStringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSResultOption { get; private set; } + + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameters: `transStatus`, `authorisationToken`. + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameters: `transStatus`, `authorisationToken`. + [JsonPropertyName("threeDSResult")] + public string? ThreeDSResult { get { return this._ThreeDSResultOption; } set { this._ThreeDSResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Threeds2ChallengeResultOption { get; private set; } + + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `transStatus`. + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `transStatus`. + [JsonPropertyName("threeds2.challengeResult")] + public string? Threeds2ChallengeResult { get { return this._Threeds2ChallengeResultOption; } set { this._Threeds2ChallengeResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Threeds2FingerprintOption { get; private set; } + + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `threeDSCompInd`. + /// + /// Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `threeDSCompInd`. + [JsonPropertyName("threeds2.fingerprint")] + public string? Threeds2Fingerprint { get { return this._Threeds2FingerprintOption; } set { this._Threeds2FingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VaultTokenOption { get; private set; } + + /// + /// PayPalv2-generated token for recurring payments. + /// + /// PayPalv2-generated token for recurring payments. + [JsonPropertyName("vaultToken")] + public string? VaultToken { get { return this._VaultTokenOption; } set { this._VaultTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentCompletionDetails {\n"); + sb.Append(" MD: ").Append(MD).Append("\n"); + sb.Append(" PaReq: ").Append(PaReq).Append("\n"); + sb.Append(" PaRes: ").Append(PaRes).Append("\n"); + sb.Append(" AuthorizationToken: ").Append(AuthorizationToken).Append("\n"); + sb.Append(" BillingToken: ").Append(BillingToken).Append("\n"); + sb.Append(" CupsecureplusSmscode: ").Append(CupsecureplusSmscode).Append("\n"); + sb.Append(" FacilitatorAccessToken: ").Append(FacilitatorAccessToken).Append("\n"); + sb.Append(" OneTimePasscode: ").Append(OneTimePasscode).Append("\n"); + sb.Append(" OrderID: ").Append(OrderID).Append("\n"); + sb.Append(" PayerID: ").Append(PayerID).Append("\n"); + sb.Append(" Payload: ").Append(Payload).Append("\n"); + sb.Append(" PaymentID: ").Append(PaymentID).Append("\n"); + sb.Append(" PaymentStatus: ").Append(PaymentStatus).Append("\n"); + sb.Append(" RedirectResult: ").Append(RedirectResult).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ReturnUrlQueryString: ").Append(ReturnUrlQueryString).Append("\n"); + sb.Append(" ThreeDSResult: ").Append(ThreeDSResult).Append("\n"); + sb.Append(" Threeds2ChallengeResult: ").Append(Threeds2ChallengeResult).Append("\n"); + sb.Append(" Threeds2Fingerprint: ").Append(Threeds2Fingerprint).Append("\n"); + sb.Append(" VaultToken: ").Append(VaultToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MD (string) maxLength + if (this.MD != null && this.MD.Length > 20000) + { + yield return new ValidationResult("Invalid value for MD, length must be less than 20000.", new [] { "MD" }); + } + + // PaReq (string) maxLength + if (this.PaReq != null && this.PaReq.Length > 20000) + { + yield return new ValidationResult("Invalid value for PaReq, length must be less than 20000.", new [] { "PaReq" }); + } + + // PaRes (string) maxLength + if (this.PaRes != null && this.PaRes.Length > 20000) + { + yield return new ValidationResult("Invalid value for PaRes, length must be less than 20000.", new [] { "PaRes" }); + } + + // Payload (string) maxLength + if (this.Payload != null && this.Payload.Length > 20000) + { + yield return new ValidationResult("Invalid value for Payload, length must be less than 20000.", new [] { "Payload" }); + } + + // RedirectResult (string) maxLength + if (this.RedirectResult != null && this.RedirectResult.Length > 20000) + { + yield return new ValidationResult("Invalid value for RedirectResult, length must be less than 20000.", new [] { "RedirectResult" }); + } + + // ReturnUrlQueryString (string) maxLength + if (this.ReturnUrlQueryString != null && this.ReturnUrlQueryString.Length > 20000) + { + yield return new ValidationResult("Invalid value for ReturnUrlQueryString, length must be less than 20000.", new [] { "ReturnUrlQueryString" }); + } + + // ThreeDSResult (string) maxLength + if (this.ThreeDSResult != null && this.ThreeDSResult.Length > 50000) + { + yield return new ValidationResult("Invalid value for ThreeDSResult, length must be less than 50000.", new [] { "ThreeDSResult" }); + } + + // Threeds2ChallengeResult (string) maxLength + if (this.Threeds2ChallengeResult != null && this.Threeds2ChallengeResult.Length > 50000) + { + yield return new ValidationResult("Invalid value for Threeds2ChallengeResult, length must be less than 50000.", new [] { "Threeds2ChallengeResult" }); + } + + // Threeds2Fingerprint (string) maxLength + if (this.Threeds2Fingerprint != null && this.Threeds2Fingerprint.Length > 100000) + { + yield return new ValidationResult("Invalid value for Threeds2Fingerprint, length must be less than 100000.", new [] { "Threeds2Fingerprint" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentCompletionDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentCompletionDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option mD = default; + Option paReq = default; + Option paRes = default; + Option authorizationToken = default; + Option billingToken = default; + Option cupsecureplusSmscode = default; + Option facilitatorAccessToken = default; + Option oneTimePasscode = default; + Option orderID = default; + Option payerID = default; + Option payload = default; + Option paymentID = default; + Option paymentStatus = default; + Option redirectResult = default; + Option resultCode = default; + Option returnUrlQueryString = default; + Option threeDSResult = default; + Option threeds2ChallengeResult = default; + Option threeds2Fingerprint = default; + Option vaultToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "MD": + mD = new Option(utf8JsonReader.GetString()!); + break; + case "PaReq": + paReq = new Option(utf8JsonReader.GetString()!); + break; + case "PaRes": + paRes = new Option(utf8JsonReader.GetString()!); + break; + case "authorization_token": + authorizationToken = new Option(utf8JsonReader.GetString()!); + break; + case "billingToken": + billingToken = new Option(utf8JsonReader.GetString()!); + break; + case "cupsecureplus.smscode": + cupsecureplusSmscode = new Option(utf8JsonReader.GetString()!); + break; + case "facilitatorAccessToken": + facilitatorAccessToken = new Option(utf8JsonReader.GetString()!); + break; + case "oneTimePasscode": + oneTimePasscode = new Option(utf8JsonReader.GetString()!); + break; + case "orderID": + orderID = new Option(utf8JsonReader.GetString()!); + break; + case "payerID": + payerID = new Option(utf8JsonReader.GetString()!); + break; + case "payload": + payload = new Option(utf8JsonReader.GetString()!); + break; + case "paymentID": + paymentID = new Option(utf8JsonReader.GetString()!); + break; + case "paymentStatus": + paymentStatus = new Option(utf8JsonReader.GetString()!); + break; + case "redirectResult": + redirectResult = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + case "returnUrlQueryString": + returnUrlQueryString = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSResult": + threeDSResult = new Option(utf8JsonReader.GetString()!); + break; + case "threeds2.challengeResult": + threeds2ChallengeResult = new Option(utf8JsonReader.GetString()!); + break; + case "threeds2.fingerprint": + threeds2Fingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "vaultToken": + vaultToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentCompletionDetails(mD, paReq, paRes, authorizationToken, billingToken, cupsecureplusSmscode, facilitatorAccessToken, oneTimePasscode, orderID, payerID, payload, paymentID, paymentStatus, redirectResult, resultCode, returnUrlQueryString, threeDSResult, threeds2ChallengeResult, threeds2Fingerprint, vaultToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentCompletionDetails paymentCompletionDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentCompletionDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentCompletionDetails paymentCompletionDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentCompletionDetails._MDOption.IsSet) + if (paymentCompletionDetails.MD != null) + writer.WriteString("MD", paymentCompletionDetails.MD); + + if (paymentCompletionDetails._PaReqOption.IsSet) + if (paymentCompletionDetails.PaReq != null) + writer.WriteString("PaReq", paymentCompletionDetails.PaReq); + + if (paymentCompletionDetails._PaResOption.IsSet) + if (paymentCompletionDetails.PaRes != null) + writer.WriteString("PaRes", paymentCompletionDetails.PaRes); + + if (paymentCompletionDetails._AuthorizationTokenOption.IsSet) + if (paymentCompletionDetails.AuthorizationToken != null) + writer.WriteString("authorization_token", paymentCompletionDetails.AuthorizationToken); + + if (paymentCompletionDetails._BillingTokenOption.IsSet) + if (paymentCompletionDetails.BillingToken != null) + writer.WriteString("billingToken", paymentCompletionDetails.BillingToken); + + if (paymentCompletionDetails._CupsecureplusSmscodeOption.IsSet) + if (paymentCompletionDetails.CupsecureplusSmscode != null) + writer.WriteString("cupsecureplus.smscode", paymentCompletionDetails.CupsecureplusSmscode); + + if (paymentCompletionDetails._FacilitatorAccessTokenOption.IsSet) + if (paymentCompletionDetails.FacilitatorAccessToken != null) + writer.WriteString("facilitatorAccessToken", paymentCompletionDetails.FacilitatorAccessToken); + + if (paymentCompletionDetails._OneTimePasscodeOption.IsSet) + if (paymentCompletionDetails.OneTimePasscode != null) + writer.WriteString("oneTimePasscode", paymentCompletionDetails.OneTimePasscode); + + if (paymentCompletionDetails._OrderIDOption.IsSet) + if (paymentCompletionDetails.OrderID != null) + writer.WriteString("orderID", paymentCompletionDetails.OrderID); + + if (paymentCompletionDetails._PayerIDOption.IsSet) + if (paymentCompletionDetails.PayerID != null) + writer.WriteString("payerID", paymentCompletionDetails.PayerID); + + if (paymentCompletionDetails._PayloadOption.IsSet) + if (paymentCompletionDetails.Payload != null) + writer.WriteString("payload", paymentCompletionDetails.Payload); + + if (paymentCompletionDetails._PaymentIDOption.IsSet) + if (paymentCompletionDetails.PaymentID != null) + writer.WriteString("paymentID", paymentCompletionDetails.PaymentID); + + if (paymentCompletionDetails._PaymentStatusOption.IsSet) + if (paymentCompletionDetails.PaymentStatus != null) + writer.WriteString("paymentStatus", paymentCompletionDetails.PaymentStatus); + + if (paymentCompletionDetails._RedirectResultOption.IsSet) + if (paymentCompletionDetails.RedirectResult != null) + writer.WriteString("redirectResult", paymentCompletionDetails.RedirectResult); + + if (paymentCompletionDetails._ResultCodeOption.IsSet) + if (paymentCompletionDetails.ResultCode != null) + writer.WriteString("resultCode", paymentCompletionDetails.ResultCode); + + if (paymentCompletionDetails._ReturnUrlQueryStringOption.IsSet) + if (paymentCompletionDetails.ReturnUrlQueryString != null) + writer.WriteString("returnUrlQueryString", paymentCompletionDetails.ReturnUrlQueryString); + + if (paymentCompletionDetails._ThreeDSResultOption.IsSet) + if (paymentCompletionDetails.ThreeDSResult != null) + writer.WriteString("threeDSResult", paymentCompletionDetails.ThreeDSResult); + + if (paymentCompletionDetails._Threeds2ChallengeResultOption.IsSet) + if (paymentCompletionDetails.Threeds2ChallengeResult != null) + writer.WriteString("threeds2.challengeResult", paymentCompletionDetails.Threeds2ChallengeResult); + + if (paymentCompletionDetails._Threeds2FingerprintOption.IsSet) + if (paymentCompletionDetails.Threeds2Fingerprint != null) + writer.WriteString("threeds2.fingerprint", paymentCompletionDetails.Threeds2Fingerprint); + + if (paymentCompletionDetails._VaultTokenOption.IsSet) + if (paymentCompletionDetails.VaultToken != null) + writer.WriteString("vaultToken", paymentCompletionDetails.VaultToken); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentDetails.cs b/Adyen/Checkout/Models/PaymentDetails.cs new file mode 100644 index 000000000..75f1d90c7 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentDetails.cs @@ -0,0 +1,1091 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentDetails. + /// + public partial class PaymentDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// The payment method type. + [JsonConstructor] + public PaymentDetails(Option checkoutAttemptId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentDetails() + { + } + + partial void OnCreated(); + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Alipay - alipay + /// + public static readonly TypeEnum Alipay = new("alipay"); + + /// + /// TypeEnum.Multibanco - multibanco + /// + public static readonly TypeEnum Multibanco = new("multibanco"); + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + /// + /// TypeEnum.BankTransferIBAN - bankTransfer_IBAN + /// + public static readonly TypeEnum BankTransferIBAN = new("bankTransfer_IBAN"); + + /// + /// TypeEnum.Paybright - paybright + /// + public static readonly TypeEnum Paybright = new("paybright"); + + /// + /// TypeEnum.Paynow - paynow + /// + public static readonly TypeEnum Paynow = new("paynow"); + + /// + /// TypeEnum.AffirmPos - affirm_pos + /// + public static readonly TypeEnum AffirmPos = new("affirm_pos"); + + /// + /// TypeEnum.Iris - iris + /// + public static readonly TypeEnum Iris = new("iris"); + + /// + /// TypeEnum.Trustly - trustly + /// + public static readonly TypeEnum Trustly = new("trustly"); + + /// + /// TypeEnum.Trustlyvector - trustlyvector + /// + public static readonly TypeEnum Trustlyvector = new("trustlyvector"); + + /// + /// TypeEnum.Oney - oney + /// + public static readonly TypeEnum Oney = new("oney"); + + /// + /// TypeEnum.Facilypay - facilypay + /// + public static readonly TypeEnum Facilypay = new("facilypay"); + + /// + /// TypeEnum.Facilypay3x - facilypay_3x + /// + public static readonly TypeEnum Facilypay3x = new("facilypay_3x"); + + /// + /// TypeEnum.Facilypay4x - facilypay_4x + /// + public static readonly TypeEnum Facilypay4x = new("facilypay_4x"); + + /// + /// TypeEnum.Facilypay6x - facilypay_6x + /// + public static readonly TypeEnum Facilypay6x = new("facilypay_6x"); + + /// + /// TypeEnum.Facilypay10x - facilypay_10x + /// + public static readonly TypeEnum Facilypay10x = new("facilypay_10x"); + + /// + /// TypeEnum.Facilypay12x - facilypay_12x + /// + public static readonly TypeEnum Facilypay12x = new("facilypay_12x"); + + /// + /// TypeEnum.Unionpay - unionpay + /// + public static readonly TypeEnum Unionpay = new("unionpay"); + + /// + /// TypeEnum.KcpBanktransfer - kcp_banktransfer + /// + public static readonly TypeEnum KcpBanktransfer = new("kcp_banktransfer"); + + /// + /// TypeEnum.KcpPayco - kcp_payco + /// + public static readonly TypeEnum KcpPayco = new("kcp_payco"); + + /// + /// TypeEnum.KcpCreditcard - kcp_creditcard + /// + public static readonly TypeEnum KcpCreditcard = new("kcp_creditcard"); + + /// + /// TypeEnum.WechatpaySDK - wechatpaySDK + /// + public static readonly TypeEnum WechatpaySDK = new("wechatpaySDK"); + + /// + /// TypeEnum.WechatpayQR - wechatpayQR + /// + public static readonly TypeEnum WechatpayQR = new("wechatpayQR"); + + /// + /// TypeEnum.WechatpayWeb - wechatpayWeb + /// + public static readonly TypeEnum WechatpayWeb = new("wechatpayWeb"); + + /// + /// TypeEnum.MolpayBoost - molpay_boost + /// + public static readonly TypeEnum MolpayBoost = new("molpay_boost"); + + /// + /// TypeEnum.WalletIN - wallet_IN + /// + public static readonly TypeEnum WalletIN = new("wallet_IN"); + + /// + /// TypeEnum.PayuINCashcard - payu_IN_cashcard + /// + public static readonly TypeEnum PayuINCashcard = new("payu_IN_cashcard"); + + /// + /// TypeEnum.PayuINNb - payu_IN_nb + /// + public static readonly TypeEnum PayuINNb = new("payu_IN_nb"); + + /// + /// TypeEnum.Paytm - paytm + /// + public static readonly TypeEnum Paytm = new("paytm"); + + /// + /// TypeEnum.MolpayEbankingVN - molpay_ebanking_VN + /// + public static readonly TypeEnum MolpayEbankingVN = new("molpay_ebanking_VN"); + + /// + /// TypeEnum.MolpayEbankingMY - molpay_ebanking_MY + /// + public static readonly TypeEnum MolpayEbankingMY = new("molpay_ebanking_MY"); + + /// + /// TypeEnum.MolpayEbankingDirectMY - molpay_ebanking_direct_MY + /// + public static readonly TypeEnum MolpayEbankingDirectMY = new("molpay_ebanking_direct_MY"); + + /// + /// TypeEnum.Swish - swish + /// + public static readonly TypeEnum Swish = new("swish"); + + /// + /// TypeEnum.Bizum - bizum + /// + public static readonly TypeEnum Bizum = new("bizum"); + + /// + /// TypeEnum.Walley - walley + /// + public static readonly TypeEnum Walley = new("walley"); + + /// + /// TypeEnum.WalleyB2b - walley_b2b + /// + public static readonly TypeEnum WalleyB2b = new("walley_b2b"); + + /// + /// TypeEnum.Alma - alma + /// + public static readonly TypeEnum Alma = new("alma"); + + /// + /// TypeEnum.Paypo - paypo + /// + public static readonly TypeEnum Paypo = new("paypo"); + + /// + /// TypeEnum.Scalapay - scalapay + /// + public static readonly TypeEnum Scalapay = new("scalapay"); + + /// + /// TypeEnum.Scalapay3x - scalapay_3x + /// + public static readonly TypeEnum Scalapay3x = new("scalapay_3x"); + + /// + /// TypeEnum.Scalapay4x - scalapay_4x + /// + public static readonly TypeEnum Scalapay4x = new("scalapay_4x"); + + /// + /// TypeEnum.MolpayFpx - molpay_fpx + /// + public static readonly TypeEnum MolpayFpx = new("molpay_fpx"); + + /// + /// TypeEnum.Payme - payme + /// + public static readonly TypeEnum Payme = new("payme"); + + /// + /// TypeEnum.PaymePos - payme_pos + /// + public static readonly TypeEnum PaymePos = new("payme_pos"); + + /// + /// TypeEnum.Konbini - konbini + /// + public static readonly TypeEnum Konbini = new("konbini"); + + /// + /// TypeEnum.DirectEbanking - directEbanking + /// + public static readonly TypeEnum DirectEbanking = new("directEbanking"); + + /// + /// TypeEnum.Boletobancario - boletobancario + /// + public static readonly TypeEnum Boletobancario = new("boletobancario"); + + /// + /// TypeEnum.Neteller - neteller + /// + public static readonly TypeEnum Neteller = new("neteller"); + + /// + /// TypeEnum.Cashticket - cashticket + /// + public static readonly TypeEnum Cashticket = new("cashticket"); + + /// + /// TypeEnum.Ikano - ikano + /// + public static readonly TypeEnum Ikano = new("ikano"); + + /// + /// TypeEnum.Karenmillen - karenmillen + /// + public static readonly TypeEnum Karenmillen = new("karenmillen"); + + /// + /// TypeEnum.Oasis - oasis + /// + public static readonly TypeEnum Oasis = new("oasis"); + + /// + /// TypeEnum.Warehouse - warehouse + /// + public static readonly TypeEnum Warehouse = new("warehouse"); + + /// + /// TypeEnum.PrimeiropayBoleto - primeiropay_boleto + /// + public static readonly TypeEnum PrimeiropayBoleto = new("primeiropay_boleto"); + + /// + /// TypeEnum.Mada - mada + /// + public static readonly TypeEnum Mada = new("mada"); + + /// + /// TypeEnum.Benefit - benefit + /// + public static readonly TypeEnum Benefit = new("benefit"); + + /// + /// TypeEnum.Knet - knet + /// + public static readonly TypeEnum Knet = new("knet"); + + /// + /// TypeEnum.Omannet - omannet + /// + public static readonly TypeEnum Omannet = new("omannet"); + + /// + /// TypeEnum.GopayWallet - gopay_wallet + /// + public static readonly TypeEnum GopayWallet = new("gopay_wallet"); + + /// + /// TypeEnum.KcpNaverpay - kcp_naverpay + /// + public static readonly TypeEnum KcpNaverpay = new("kcp_naverpay"); + + /// + /// TypeEnum.Fawry - fawry + /// + public static readonly TypeEnum Fawry = new("fawry"); + + /// + /// TypeEnum.Atome - atome + /// + public static readonly TypeEnum Atome = new("atome"); + + /// + /// TypeEnum.Moneybookers - moneybookers + /// + public static readonly TypeEnum Moneybookers = new("moneybookers"); + + /// + /// TypeEnum.Naps - naps + /// + public static readonly TypeEnum Naps = new("naps"); + + /// + /// TypeEnum.Nordea - nordea + /// + public static readonly TypeEnum Nordea = new("nordea"); + + /// + /// TypeEnum.BoletobancarioBradesco - boletobancario_bradesco + /// + public static readonly TypeEnum BoletobancarioBradesco = new("boletobancario_bradesco"); + + /// + /// TypeEnum.BoletobancarioItau - boletobancario_itau + /// + public static readonly TypeEnum BoletobancarioItau = new("boletobancario_itau"); + + /// + /// TypeEnum.BoletobancarioSantander - boletobancario_santander + /// + public static readonly TypeEnum BoletobancarioSantander = new("boletobancario_santander"); + + /// + /// TypeEnum.BoletobancarioBancodobrasil - boletobancario_bancodobrasil + /// + public static readonly TypeEnum BoletobancarioBancodobrasil = new("boletobancario_bancodobrasil"); + + /// + /// TypeEnum.BoletobancarioHsbc - boletobancario_hsbc + /// + public static readonly TypeEnum BoletobancarioHsbc = new("boletobancario_hsbc"); + + /// + /// TypeEnum.MolpayMaybank2u - molpay_maybank2u + /// + public static readonly TypeEnum MolpayMaybank2u = new("molpay_maybank2u"); + + /// + /// TypeEnum.MolpayCimb - molpay_cimb + /// + public static readonly TypeEnum MolpayCimb = new("molpay_cimb"); + + /// + /// TypeEnum.MolpayRhb - molpay_rhb + /// + public static readonly TypeEnum MolpayRhb = new("molpay_rhb"); + + /// + /// TypeEnum.MolpayAmb - molpay_amb + /// + public static readonly TypeEnum MolpayAmb = new("molpay_amb"); + + /// + /// TypeEnum.MolpayHlb - molpay_hlb + /// + public static readonly TypeEnum MolpayHlb = new("molpay_hlb"); + + /// + /// TypeEnum.MolpayAffinEpg - molpay_affin_epg + /// + public static readonly TypeEnum MolpayAffinEpg = new("molpay_affin_epg"); + + /// + /// TypeEnum.MolpayBankislam - molpay_bankislam + /// + public static readonly TypeEnum MolpayBankislam = new("molpay_bankislam"); + + /// + /// TypeEnum.MolpayPublicbank - molpay_publicbank + /// + public static readonly TypeEnum MolpayPublicbank = new("molpay_publicbank"); + + /// + /// TypeEnum.FpxAgrobank - fpx_agrobank + /// + public static readonly TypeEnum FpxAgrobank = new("fpx_agrobank"); + + /// + /// TypeEnum.Touchngo - touchngo + /// + public static readonly TypeEnum Touchngo = new("touchngo"); + + /// + /// TypeEnum.Maybank2uMae - maybank2u_mae + /// + public static readonly TypeEnum Maybank2uMae = new("maybank2u_mae"); + + /// + /// TypeEnum.Duitnow - duitnow + /// + public static readonly TypeEnum Duitnow = new("duitnow"); + + /// + /// TypeEnum.Promptpay - promptpay + /// + public static readonly TypeEnum Promptpay = new("promptpay"); + + /// + /// TypeEnum.TwintPos - twint_pos + /// + public static readonly TypeEnum TwintPos = new("twint_pos"); + + /// + /// TypeEnum.AlipayHk - alipay_hk + /// + public static readonly TypeEnum AlipayHk = new("alipay_hk"); + + /// + /// TypeEnum.AlipayHkWeb - alipay_hk_web + /// + public static readonly TypeEnum AlipayHkWeb = new("alipay_hk_web"); + + /// + /// TypeEnum.AlipayHkWap - alipay_hk_wap + /// + public static readonly TypeEnum AlipayHkWap = new("alipay_hk_wap"); + + /// + /// TypeEnum.AlipayWap - alipay_wap + /// + public static readonly TypeEnum AlipayWap = new("alipay_wap"); + + /// + /// TypeEnum.Balanceplatform - balanceplatform + /// + public static readonly TypeEnum Balanceplatform = new("balanceplatform"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "alipay" => TypeEnum.Alipay, + "multibanco" => TypeEnum.Multibanco, + "bankTransfer" => TypeEnum.BankTransfer, + "bankTransfer_IBAN" => TypeEnum.BankTransferIBAN, + "paybright" => TypeEnum.Paybright, + "paynow" => TypeEnum.Paynow, + "affirm_pos" => TypeEnum.AffirmPos, + "iris" => TypeEnum.Iris, + "trustly" => TypeEnum.Trustly, + "trustlyvector" => TypeEnum.Trustlyvector, + "oney" => TypeEnum.Oney, + "facilypay" => TypeEnum.Facilypay, + "facilypay_3x" => TypeEnum.Facilypay3x, + "facilypay_4x" => TypeEnum.Facilypay4x, + "facilypay_6x" => TypeEnum.Facilypay6x, + "facilypay_10x" => TypeEnum.Facilypay10x, + "facilypay_12x" => TypeEnum.Facilypay12x, + "unionpay" => TypeEnum.Unionpay, + "kcp_banktransfer" => TypeEnum.KcpBanktransfer, + "kcp_payco" => TypeEnum.KcpPayco, + "kcp_creditcard" => TypeEnum.KcpCreditcard, + "wechatpaySDK" => TypeEnum.WechatpaySDK, + "wechatpayQR" => TypeEnum.WechatpayQR, + "wechatpayWeb" => TypeEnum.WechatpayWeb, + "molpay_boost" => TypeEnum.MolpayBoost, + "wallet_IN" => TypeEnum.WalletIN, + "payu_IN_cashcard" => TypeEnum.PayuINCashcard, + "payu_IN_nb" => TypeEnum.PayuINNb, + "paytm" => TypeEnum.Paytm, + "molpay_ebanking_VN" => TypeEnum.MolpayEbankingVN, + "molpay_ebanking_MY" => TypeEnum.MolpayEbankingMY, + "molpay_ebanking_direct_MY" => TypeEnum.MolpayEbankingDirectMY, + "swish" => TypeEnum.Swish, + "bizum" => TypeEnum.Bizum, + "walley" => TypeEnum.Walley, + "walley_b2b" => TypeEnum.WalleyB2b, + "alma" => TypeEnum.Alma, + "paypo" => TypeEnum.Paypo, + "scalapay" => TypeEnum.Scalapay, + "scalapay_3x" => TypeEnum.Scalapay3x, + "scalapay_4x" => TypeEnum.Scalapay4x, + "molpay_fpx" => TypeEnum.MolpayFpx, + "payme" => TypeEnum.Payme, + "payme_pos" => TypeEnum.PaymePos, + "konbini" => TypeEnum.Konbini, + "directEbanking" => TypeEnum.DirectEbanking, + "boletobancario" => TypeEnum.Boletobancario, + "neteller" => TypeEnum.Neteller, + "cashticket" => TypeEnum.Cashticket, + "ikano" => TypeEnum.Ikano, + "karenmillen" => TypeEnum.Karenmillen, + "oasis" => TypeEnum.Oasis, + "warehouse" => TypeEnum.Warehouse, + "primeiropay_boleto" => TypeEnum.PrimeiropayBoleto, + "mada" => TypeEnum.Mada, + "benefit" => TypeEnum.Benefit, + "knet" => TypeEnum.Knet, + "omannet" => TypeEnum.Omannet, + "gopay_wallet" => TypeEnum.GopayWallet, + "kcp_naverpay" => TypeEnum.KcpNaverpay, + "fawry" => TypeEnum.Fawry, + "atome" => TypeEnum.Atome, + "moneybookers" => TypeEnum.Moneybookers, + "naps" => TypeEnum.Naps, + "nordea" => TypeEnum.Nordea, + "boletobancario_bradesco" => TypeEnum.BoletobancarioBradesco, + "boletobancario_itau" => TypeEnum.BoletobancarioItau, + "boletobancario_santander" => TypeEnum.BoletobancarioSantander, + "boletobancario_bancodobrasil" => TypeEnum.BoletobancarioBancodobrasil, + "boletobancario_hsbc" => TypeEnum.BoletobancarioHsbc, + "molpay_maybank2u" => TypeEnum.MolpayMaybank2u, + "molpay_cimb" => TypeEnum.MolpayCimb, + "molpay_rhb" => TypeEnum.MolpayRhb, + "molpay_amb" => TypeEnum.MolpayAmb, + "molpay_hlb" => TypeEnum.MolpayHlb, + "molpay_affin_epg" => TypeEnum.MolpayAffinEpg, + "molpay_bankislam" => TypeEnum.MolpayBankislam, + "molpay_publicbank" => TypeEnum.MolpayPublicbank, + "fpx_agrobank" => TypeEnum.FpxAgrobank, + "touchngo" => TypeEnum.Touchngo, + "maybank2u_mae" => TypeEnum.Maybank2uMae, + "duitnow" => TypeEnum.Duitnow, + "promptpay" => TypeEnum.Promptpay, + "twint_pos" => TypeEnum.TwintPos, + "alipay_hk" => TypeEnum.AlipayHk, + "alipay_hk_web" => TypeEnum.AlipayHkWeb, + "alipay_hk_wap" => TypeEnum.AlipayHkWap, + "alipay_wap" => TypeEnum.AlipayWap, + "balanceplatform" => TypeEnum.Balanceplatform, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Alipay) + return "alipay"; + + if (value == TypeEnum.Multibanco) + return "multibanco"; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == TypeEnum.BankTransferIBAN) + return "bankTransfer_IBAN"; + + if (value == TypeEnum.Paybright) + return "paybright"; + + if (value == TypeEnum.Paynow) + return "paynow"; + + if (value == TypeEnum.AffirmPos) + return "affirm_pos"; + + if (value == TypeEnum.Iris) + return "iris"; + + if (value == TypeEnum.Trustly) + return "trustly"; + + if (value == TypeEnum.Trustlyvector) + return "trustlyvector"; + + if (value == TypeEnum.Oney) + return "oney"; + + if (value == TypeEnum.Facilypay) + return "facilypay"; + + if (value == TypeEnum.Facilypay3x) + return "facilypay_3x"; + + if (value == TypeEnum.Facilypay4x) + return "facilypay_4x"; + + if (value == TypeEnum.Facilypay6x) + return "facilypay_6x"; + + if (value == TypeEnum.Facilypay10x) + return "facilypay_10x"; + + if (value == TypeEnum.Facilypay12x) + return "facilypay_12x"; + + if (value == TypeEnum.Unionpay) + return "unionpay"; + + if (value == TypeEnum.KcpBanktransfer) + return "kcp_banktransfer"; + + if (value == TypeEnum.KcpPayco) + return "kcp_payco"; + + if (value == TypeEnum.KcpCreditcard) + return "kcp_creditcard"; + + if (value == TypeEnum.WechatpaySDK) + return "wechatpaySDK"; + + if (value == TypeEnum.WechatpayQR) + return "wechatpayQR"; + + if (value == TypeEnum.WechatpayWeb) + return "wechatpayWeb"; + + if (value == TypeEnum.MolpayBoost) + return "molpay_boost"; + + if (value == TypeEnum.WalletIN) + return "wallet_IN"; + + if (value == TypeEnum.PayuINCashcard) + return "payu_IN_cashcard"; + + if (value == TypeEnum.PayuINNb) + return "payu_IN_nb"; + + if (value == TypeEnum.Paytm) + return "paytm"; + + if (value == TypeEnum.MolpayEbankingVN) + return "molpay_ebanking_VN"; + + if (value == TypeEnum.MolpayEbankingMY) + return "molpay_ebanking_MY"; + + if (value == TypeEnum.MolpayEbankingDirectMY) + return "molpay_ebanking_direct_MY"; + + if (value == TypeEnum.Swish) + return "swish"; + + if (value == TypeEnum.Bizum) + return "bizum"; + + if (value == TypeEnum.Walley) + return "walley"; + + if (value == TypeEnum.WalleyB2b) + return "walley_b2b"; + + if (value == TypeEnum.Alma) + return "alma"; + + if (value == TypeEnum.Paypo) + return "paypo"; + + if (value == TypeEnum.Scalapay) + return "scalapay"; + + if (value == TypeEnum.Scalapay3x) + return "scalapay_3x"; + + if (value == TypeEnum.Scalapay4x) + return "scalapay_4x"; + + if (value == TypeEnum.MolpayFpx) + return "molpay_fpx"; + + if (value == TypeEnum.Payme) + return "payme"; + + if (value == TypeEnum.PaymePos) + return "payme_pos"; + + if (value == TypeEnum.Konbini) + return "konbini"; + + if (value == TypeEnum.DirectEbanking) + return "directEbanking"; + + if (value == TypeEnum.Boletobancario) + return "boletobancario"; + + if (value == TypeEnum.Neteller) + return "neteller"; + + if (value == TypeEnum.Cashticket) + return "cashticket"; + + if (value == TypeEnum.Ikano) + return "ikano"; + + if (value == TypeEnum.Karenmillen) + return "karenmillen"; + + if (value == TypeEnum.Oasis) + return "oasis"; + + if (value == TypeEnum.Warehouse) + return "warehouse"; + + if (value == TypeEnum.PrimeiropayBoleto) + return "primeiropay_boleto"; + + if (value == TypeEnum.Mada) + return "mada"; + + if (value == TypeEnum.Benefit) + return "benefit"; + + if (value == TypeEnum.Knet) + return "knet"; + + if (value == TypeEnum.Omannet) + return "omannet"; + + if (value == TypeEnum.GopayWallet) + return "gopay_wallet"; + + if (value == TypeEnum.KcpNaverpay) + return "kcp_naverpay"; + + if (value == TypeEnum.Fawry) + return "fawry"; + + if (value == TypeEnum.Atome) + return "atome"; + + if (value == TypeEnum.Moneybookers) + return "moneybookers"; + + if (value == TypeEnum.Naps) + return "naps"; + + if (value == TypeEnum.Nordea) + return "nordea"; + + if (value == TypeEnum.BoletobancarioBradesco) + return "boletobancario_bradesco"; + + if (value == TypeEnum.BoletobancarioItau) + return "boletobancario_itau"; + + if (value == TypeEnum.BoletobancarioSantander) + return "boletobancario_santander"; + + if (value == TypeEnum.BoletobancarioBancodobrasil) + return "boletobancario_bancodobrasil"; + + if (value == TypeEnum.BoletobancarioHsbc) + return "boletobancario_hsbc"; + + if (value == TypeEnum.MolpayMaybank2u) + return "molpay_maybank2u"; + + if (value == TypeEnum.MolpayCimb) + return "molpay_cimb"; + + if (value == TypeEnum.MolpayRhb) + return "molpay_rhb"; + + if (value == TypeEnum.MolpayAmb) + return "molpay_amb"; + + if (value == TypeEnum.MolpayHlb) + return "molpay_hlb"; + + if (value == TypeEnum.MolpayAffinEpg) + return "molpay_affin_epg"; + + if (value == TypeEnum.MolpayBankislam) + return "molpay_bankislam"; + + if (value == TypeEnum.MolpayPublicbank) + return "molpay_publicbank"; + + if (value == TypeEnum.FpxAgrobank) + return "fpx_agrobank"; + + if (value == TypeEnum.Touchngo) + return "touchngo"; + + if (value == TypeEnum.Maybank2uMae) + return "maybank2u_mae"; + + if (value == TypeEnum.Duitnow) + return "duitnow"; + + if (value == TypeEnum.Promptpay) + return "promptpay"; + + if (value == TypeEnum.TwintPos) + return "twint_pos"; + + if (value == TypeEnum.AlipayHk) + return "alipay_hk"; + + if (value == TypeEnum.AlipayHkWeb) + return "alipay_hk_web"; + + if (value == TypeEnum.AlipayHkWap) + return "alipay_hk_wap"; + + if (value == TypeEnum.AlipayWap) + return "alipay_wap"; + + if (value == TypeEnum.Balanceplatform) + return "balanceplatform"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PaymentDetails(checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentDetails paymentDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentDetails paymentDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentDetails._CheckoutAttemptIdOption.IsSet) + if (paymentDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", paymentDetails.CheckoutAttemptId); + + if (paymentDetails._TypeOption.IsSet && paymentDetails.Type != null) + { + string? typeRawValue = PaymentDetails.TypeEnum.ToJsonValue(paymentDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentDetailsRequest.cs b/Adyen/Checkout/Models/PaymentDetailsRequest.cs new file mode 100644 index 000000000..6810956e0 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentDetailsRequest.cs @@ -0,0 +1,250 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentDetailsRequest. + /// + public partial class PaymentDetailsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// details + /// authenticationData + /// Encoded payment data. For [authorizing a payment after using 3D Secure 2 Authentication-only](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only/#authorise-the-payment-with-adyen): If you received `resultCode`: **AuthenticationNotRequired** in the `/payments` response, use the `threeDSPaymentData` from the same response. If you received `resultCode`: **AuthenticationFinished** in the `/payments` response, use the `action.paymentData` from the same response. + /// Change the `authenticationOnly` indicator originally set in the `/payments` request. Only needs to be set if you want to modify the value set previously. + [JsonConstructor] + public PaymentDetailsRequest(PaymentCompletionDetails details, Option authenticationData = default, Option paymentData = default, Option threeDSAuthenticationOnly = default) + { + Details = details; + _AuthenticationDataOption = authenticationData; + _PaymentDataOption = paymentData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentDetailsRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("details")] + public PaymentCompletionDetails Details { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationData")] + public DetailsRequestAuthenticationData? AuthenticationData { get { return this._AuthenticationDataOption; } set { this._AuthenticationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// Encoded payment data. For [authorizing a payment after using 3D Secure 2 Authentication-only](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only/#authorise-the-payment-with-adyen): If you received `resultCode`: **AuthenticationNotRequired** in the `/payments` response, use the `threeDSPaymentData` from the same response. If you received `resultCode`: **AuthenticationFinished** in the `/payments` response, use the `action.paymentData` from the same response. + /// + /// Encoded payment data. For [authorizing a payment after using 3D Secure 2 Authentication-only](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only/#authorise-the-payment-with-adyen): If you received `resultCode`: **AuthenticationNotRequired** in the `/payments` response, use the `threeDSPaymentData` from the same response. If you received `resultCode`: **AuthenticationFinished** in the `/payments` response, use the `action.paymentData` from the same response. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Change the `authenticationOnly` indicator originally set in the `/payments` request. Only needs to be set if you want to modify the value set previously. + /// + /// Change the `authenticationOnly` indicator originally set in the `/payments` request. Only needs to be set if you want to modify the value set previously. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentDetailsRequest {\n"); + sb.Append(" Details: ").Append(Details).Append("\n"); + sb.Append(" AuthenticationData: ").Append(AuthenticationData).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // PaymentData (string) maxLength + if (this.PaymentData != null && this.PaymentData.Length > 200000) + { + yield return new ValidationResult("Invalid value for PaymentData, length must be less than 200000.", new [] { "PaymentData" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentDetailsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentDetailsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option details = default; + Option authenticationData = default; + Option paymentData = default; + Option threeDSAuthenticationOnly = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "details": + details = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationData": + authenticationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!details.IsSet) + throw new ArgumentException("Property is required for class PaymentDetailsRequest.", nameof(details)); + + return new PaymentDetailsRequest(details.Value!, authenticationData, paymentData, threeDSAuthenticationOnly); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentDetailsRequest paymentDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentDetailsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentDetailsRequest paymentDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("details"); + JsonSerializer.Serialize(writer, paymentDetailsRequest.Details, jsonSerializerOptions); + if (paymentDetailsRequest._AuthenticationDataOption.IsSet) + { + writer.WritePropertyName("authenticationData"); + JsonSerializer.Serialize(writer, paymentDetailsRequest.AuthenticationData, jsonSerializerOptions); + } + if (paymentDetailsRequest._PaymentDataOption.IsSet) + if (paymentDetailsRequest.PaymentData != null) + writer.WriteString("paymentData", paymentDetailsRequest.PaymentData); + + if (paymentDetailsRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", paymentDetailsRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentDetailsResponse.cs b/Adyen/Checkout/Models/PaymentDetailsResponse.cs new file mode 100644 index 000000000..a7794bdae --- /dev/null +++ b/Adyen/Checkout/Models/PaymentDetailsResponse.cs @@ -0,0 +1,792 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentDetailsResponse. + /// + public partial class PaymentDetailsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// action + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// amount + /// Donation Token containing payment details for Adyen Giving. + /// fraudResult + /// The reference used during the /payments request. + /// order + /// paymentMethod + /// paymentValidations + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// The shopperLocale. + /// threeDS2ResponseData + /// threeDS2Result + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + [JsonConstructor] + public PaymentDetailsResponse(Option action = default, Option?> additionalData = default, Option amount = default, Option donationToken = default, Option fraudResult = default, Option merchantReference = default, Option order = default, Option paymentMethod = default, Option paymentValidations = default, Option pspReference = default, Option refusalReason = default, Option refusalReasonCode = default, Option resultCode = default, Option shopperLocale = default, Option threeDS2ResponseData = default, Option threeDS2Result = default, Option threeDSPaymentData = default) + { + _ActionOption = action; + _AdditionalDataOption = additionalData; + _AmountOption = amount; + _DonationTokenOption = donationToken; + _FraudResultOption = fraudResult; + _MerchantReferenceOption = merchantReference; + _OrderOption = order; + _PaymentMethodOption = paymentMethod; + _PaymentValidationsOption = paymentValidations; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _RefusalReasonCodeOption = refusalReasonCode; + _ResultCodeOption = resultCode; + _ShopperLocaleOption = shopperLocale; + _ThreeDS2ResponseDataOption = threeDS2ResponseData; + _ThreeDS2ResultOption = threeDS2Result; + _ThreeDSPaymentDataOption = threeDSPaymentData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentDetailsResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.AuthenticationFinished - AuthenticationFinished + /// + public static readonly ResultCodeEnum AuthenticationFinished = new("AuthenticationFinished"); + + /// + /// ResultCodeEnum.AuthenticationNotRequired - AuthenticationNotRequired + /// + public static readonly ResultCodeEnum AuthenticationNotRequired = new("AuthenticationNotRequired"); + + /// + /// ResultCodeEnum.Authorised - Authorised + /// + public static readonly ResultCodeEnum Authorised = new("Authorised"); + + /// + /// ResultCodeEnum.Cancelled - Cancelled + /// + public static readonly ResultCodeEnum Cancelled = new("Cancelled"); + + /// + /// ResultCodeEnum.ChallengeShopper - ChallengeShopper + /// + public static readonly ResultCodeEnum ChallengeShopper = new("ChallengeShopper"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.IdentifyShopper - IdentifyShopper + /// + public static readonly ResultCodeEnum IdentifyShopper = new("IdentifyShopper"); + + /// + /// ResultCodeEnum.PartiallyAuthorised - PartiallyAuthorised + /// + public static readonly ResultCodeEnum PartiallyAuthorised = new("PartiallyAuthorised"); + + /// + /// ResultCodeEnum.Pending - Pending + /// + public static readonly ResultCodeEnum Pending = new("Pending"); + + /// + /// ResultCodeEnum.PresentToShopper - PresentToShopper + /// + public static readonly ResultCodeEnum PresentToShopper = new("PresentToShopper"); + + /// + /// ResultCodeEnum.Received - Received + /// + public static readonly ResultCodeEnum Received = new("Received"); + + /// + /// ResultCodeEnum.RedirectShopper - RedirectShopper + /// + public static readonly ResultCodeEnum RedirectShopper = new("RedirectShopper"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "AuthenticationFinished" => ResultCodeEnum.AuthenticationFinished, + "AuthenticationNotRequired" => ResultCodeEnum.AuthenticationNotRequired, + "Authorised" => ResultCodeEnum.Authorised, + "Cancelled" => ResultCodeEnum.Cancelled, + "ChallengeShopper" => ResultCodeEnum.ChallengeShopper, + "Error" => ResultCodeEnum.Error, + "IdentifyShopper" => ResultCodeEnum.IdentifyShopper, + "PartiallyAuthorised" => ResultCodeEnum.PartiallyAuthorised, + "Pending" => ResultCodeEnum.Pending, + "PresentToShopper" => ResultCodeEnum.PresentToShopper, + "Received" => ResultCodeEnum.Received, + "RedirectShopper" => ResultCodeEnum.RedirectShopper, + "Refused" => ResultCodeEnum.Refused, + "Success" => ResultCodeEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.AuthenticationFinished) + return "AuthenticationFinished"; + + if (value == ResultCodeEnum.AuthenticationNotRequired) + return "AuthenticationNotRequired"; + + if (value == ResultCodeEnum.Authorised) + return "Authorised"; + + if (value == ResultCodeEnum.Cancelled) + return "Cancelled"; + + if (value == ResultCodeEnum.ChallengeShopper) + return "ChallengeShopper"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.IdentifyShopper) + return "IdentifyShopper"; + + if (value == ResultCodeEnum.PartiallyAuthorised) + return "PartiallyAuthorised"; + + if (value == ResultCodeEnum.Pending) + return "Pending"; + + if (value == ResultCodeEnum.PresentToShopper) + return "PresentToShopper"; + + if (value == ResultCodeEnum.Received) + return "Received"; + + if (value == ResultCodeEnum.RedirectShopper) + return "RedirectShopper"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Success) + return "Success"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("action")] + public CheckoutThreeDS2Action? Action { get { return this._ActionOption; } set { this._ActionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationTokenOption { get; private set; } + + /// + /// Donation Token containing payment details for Adyen Giving. + /// + /// Donation Token containing payment details for Adyen Giving. + [JsonPropertyName("donationToken")] + public string? DonationToken { get { return this._DonationTokenOption; } set { this._DonationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The reference used during the /payments request. + /// + /// The reference used during the /payments request. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("order")] + public CheckoutOrderResponse? Order { get { return this._OrderOption; } set { this._OrderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public ResponsePaymentMethod? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentValidationsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentValidations")] + public PaymentValidationsResponse? PaymentValidations { get { return this._PaymentValidationsOption; } set { this._PaymentValidationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonCodeOption { get; private set; } + + /// + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReasonCode")] + public string? RefusalReasonCode { get { return this._RefusalReasonCodeOption; } set { this._RefusalReasonCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The shopperLocale. + /// + /// The shopperLocale. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResponseDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2ResponseData")] + public ThreeDS2ResponseData? ThreeDS2ResponseData { get { return this._ThreeDS2ResponseDataOption; } set { this._ThreeDS2ResponseDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2Result")] + public ThreeDS2Result? ThreeDS2Result { get { return this._ThreeDS2ResultOption; } set { this._ThreeDS2ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSPaymentDataOption { get; private set; } + + /// + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + /// + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + [JsonPropertyName("threeDSPaymentData")] + public string? ThreeDSPaymentData { get { return this._ThreeDSPaymentDataOption; } set { this._ThreeDSPaymentDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentDetailsResponse {\n"); + sb.Append(" Action: ").Append(Action).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" DonationToken: ").Append(DonationToken).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" Order: ").Append(Order).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PaymentValidations: ").Append(PaymentValidations).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" RefusalReasonCode: ").Append(RefusalReasonCode).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ThreeDS2ResponseData: ").Append(ThreeDS2ResponseData).Append("\n"); + sb.Append(" ThreeDS2Result: ").Append(ThreeDS2Result).Append("\n"); + sb.Append(" ThreeDSPaymentData: ").Append(ThreeDSPaymentData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentDetailsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentDetailsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option action = default; + Option?> additionalData = default; + Option amount = default; + Option donationToken = default; + Option fraudResult = default; + Option merchantReference = default; + Option order = default; + Option paymentMethod = default; + Option paymentValidations = default; + Option pspReference = default; + Option refusalReason = default; + Option refusalReasonCode = default; + Option resultCode = default; + Option shopperLocale = default; + Option threeDS2ResponseData = default; + Option threeDS2Result = default; + Option threeDSPaymentData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "action": + action = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "donationToken": + donationToken = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "order": + order = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentValidations": + paymentValidations = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReasonCode": + refusalReasonCode = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(PaymentDetailsResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2ResponseData": + threeDS2ResponseData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2Result": + threeDS2Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSPaymentData": + threeDSPaymentData = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentDetailsResponse(action, additionalData, amount, donationToken, fraudResult, merchantReference, order, paymentMethod, paymentValidations, pspReference, refusalReason, refusalReasonCode, resultCode, shopperLocale, threeDS2ResponseData, threeDS2Result, threeDSPaymentData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentDetailsResponse paymentDetailsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentDetailsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentDetailsResponse paymentDetailsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentDetailsResponse._ActionOption.IsSet) + { + writer.WritePropertyName("action"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.Action, jsonSerializerOptions); + } + if (paymentDetailsResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.AdditionalData, jsonSerializerOptions); + } + if (paymentDetailsResponse._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.Amount, jsonSerializerOptions); + } + if (paymentDetailsResponse._DonationTokenOption.IsSet) + if (paymentDetailsResponse.DonationToken != null) + writer.WriteString("donationToken", paymentDetailsResponse.DonationToken); + + if (paymentDetailsResponse._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.FraudResult, jsonSerializerOptions); + } + if (paymentDetailsResponse._MerchantReferenceOption.IsSet) + if (paymentDetailsResponse.MerchantReference != null) + writer.WriteString("merchantReference", paymentDetailsResponse.MerchantReference); + + if (paymentDetailsResponse._OrderOption.IsSet) + { + writer.WritePropertyName("order"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.Order, jsonSerializerOptions); + } + if (paymentDetailsResponse._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.PaymentMethod, jsonSerializerOptions); + } + if (paymentDetailsResponse._PaymentValidationsOption.IsSet) + { + writer.WritePropertyName("paymentValidations"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.PaymentValidations, jsonSerializerOptions); + } + if (paymentDetailsResponse._PspReferenceOption.IsSet) + if (paymentDetailsResponse.PspReference != null) + writer.WriteString("pspReference", paymentDetailsResponse.PspReference); + + if (paymentDetailsResponse._RefusalReasonOption.IsSet) + if (paymentDetailsResponse.RefusalReason != null) + writer.WriteString("refusalReason", paymentDetailsResponse.RefusalReason); + + if (paymentDetailsResponse._RefusalReasonCodeOption.IsSet) + if (paymentDetailsResponse.RefusalReasonCode != null) + writer.WriteString("refusalReasonCode", paymentDetailsResponse.RefusalReasonCode); + + if (paymentDetailsResponse._ResultCodeOption.IsSet && paymentDetailsResponse.ResultCode != null) + { + string? resultCodeRawValue = PaymentDetailsResponse.ResultCodeEnum.ToJsonValue(paymentDetailsResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (paymentDetailsResponse._ShopperLocaleOption.IsSet) + if (paymentDetailsResponse.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentDetailsResponse.ShopperLocale); + + if (paymentDetailsResponse._ThreeDS2ResponseDataOption.IsSet) + { + writer.WritePropertyName("threeDS2ResponseData"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.ThreeDS2ResponseData, jsonSerializerOptions); + } + if (paymentDetailsResponse._ThreeDS2ResultOption.IsSet) + { + writer.WritePropertyName("threeDS2Result"); + JsonSerializer.Serialize(writer, paymentDetailsResponse.ThreeDS2Result, jsonSerializerOptions); + } + if (paymentDetailsResponse._ThreeDSPaymentDataOption.IsSet) + if (paymentDetailsResponse.ThreeDSPaymentData != null) + writer.WriteString("threeDSPaymentData", paymentDetailsResponse.ThreeDSPaymentData); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentLinkRequest.cs b/Adyen/Checkout/Models/PaymentLinkRequest.cs new file mode 100644 index 000000000..ce26f7b12 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentLinkRequest.cs @@ -0,0 +1,1624 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentLinkRequest. + /// + public partial class PaymentLinkRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier for which the payment link is created. + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// applicationInfo + /// billingAddress + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The shopper's two-letter country code. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// deliveryAddress + /// A short description visible on the payment page. Maximum length: 280 characters. + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + /// fundOrigin + /// fundRecipient + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + /// platformChargebackLogic + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + /// riskData + /// The shopper's email address. + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + /// shopperName + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. (default to true) + /// The shopper's social security number. + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false) + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// The physical store, for which this payment is processed. + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + /// threeDS2RequestData + [JsonConstructor] + public PaymentLinkRequest(Amount amount, string merchantAccount, string reference, Option?> allowedPaymentMethods = default, Option applicationInfo = default, Option billingAddress = default, Option?> blockedPaymentMethods = default, Option captureDelayHours = default, Option countryCode = default, Option dateOfBirth = default, Option deliverAt = default, Option deliveryAddress = default, Option description = default, Option expiresAt = default, Option fundOrigin = default, Option fundRecipient = default, Option?> installmentOptions = default, Option?> lineItems = default, Option manualCapture = default, Option mcc = default, Option merchantOrderReference = default, Option?> metadata = default, Option platformChargebackLogic = default, Option recurringProcessingModel = default, Option?> requiredShopperFields = default, Option returnUrl = default, Option reusable = default, Option riskData = default, Option shopperEmail = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option showRemovePaymentMethodButton = default, Option socialSecurityNumber = default, Option splitCardFundingSources = default, Option?> splits = default, Option store = default, Option storePaymentMethodMode = default, Option telephoneNumber = default, Option themeId = default, Option threeDS2RequestData = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + _AllowedPaymentMethodsOption = allowedPaymentMethods; + _ApplicationInfoOption = applicationInfo; + _BillingAddressOption = billingAddress; + _BlockedPaymentMethodsOption = blockedPaymentMethods; + _CaptureDelayHoursOption = captureDelayHours; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _DescriptionOption = description; + _ExpiresAtOption = expiresAt; + _FundOriginOption = fundOrigin; + _FundRecipientOption = fundRecipient; + _InstallmentOptionsOption = installmentOptions; + _LineItemsOption = lineItems; + _ManualCaptureOption = manualCapture; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MetadataOption = metadata; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringProcessingModelOption = recurringProcessingModel; + _RequiredShopperFieldsOption = requiredShopperFields; + _ReturnUrlOption = returnUrl; + _ReusableOption = reusable; + _RiskDataOption = riskData; + _ShopperEmailOption = shopperEmail; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _ShowRemovePaymentMethodButtonOption = showRemovePaymentMethodButton; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitCardFundingSourcesOption = splitCardFundingSources; + _SplitsOption = splits; + _StoreOption = store; + _StorePaymentMethodModeOption = storePaymentMethodMode; + _TelephoneNumberOption = telephoneNumber; + _ThemeIdOption = themeId; + _ThreeDS2RequestDataOption = threeDS2RequestData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentLinkRequest() + { + } + + partial void OnCreated(); + + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Defines RequiredShopperFields. + /// + [JsonConverter(typeof(RequiredShopperFieldsEnumJsonConverter))] + public class RequiredShopperFieldsEnum : IEnum + { + /// + /// Returns the value of the RequiredShopperFieldsEnum. + /// + public string? Value { get; set; } + + /// + /// RequiredShopperFieldsEnum.BillingAddress - billingAddress + /// + public static readonly RequiredShopperFieldsEnum BillingAddress = new("billingAddress"); + + /// + /// RequiredShopperFieldsEnum.DeliveryAddress - deliveryAddress + /// + public static readonly RequiredShopperFieldsEnum DeliveryAddress = new("deliveryAddress"); + + /// + /// RequiredShopperFieldsEnum.ShopperEmail - shopperEmail + /// + public static readonly RequiredShopperFieldsEnum ShopperEmail = new("shopperEmail"); + + /// + /// RequiredShopperFieldsEnum.ShopperName - shopperName + /// + public static readonly RequiredShopperFieldsEnum ShopperName = new("shopperName"); + + /// + /// RequiredShopperFieldsEnum.TelephoneNumber - telephoneNumber + /// + public static readonly RequiredShopperFieldsEnum TelephoneNumber = new("telephoneNumber"); + + private RequiredShopperFieldsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequiredShopperFieldsEnum?(string? value) => value == null ? null : new RequiredShopperFieldsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequiredShopperFieldsEnum? option) => option?.Value; + + public static bool operator ==(RequiredShopperFieldsEnum? left, RequiredShopperFieldsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequiredShopperFieldsEnum? left, RequiredShopperFieldsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequiredShopperFieldsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequiredShopperFieldsEnum? FromStringOrDefault(string value) + { + return value switch { + "billingAddress" => RequiredShopperFieldsEnum.BillingAddress, + "deliveryAddress" => RequiredShopperFieldsEnum.DeliveryAddress, + "shopperEmail" => RequiredShopperFieldsEnum.ShopperEmail, + "shopperName" => RequiredShopperFieldsEnum.ShopperName, + "telephoneNumber" => RequiredShopperFieldsEnum.TelephoneNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequiredShopperFieldsEnum? value) + { + if (value == null) + return null; + + if (value == RequiredShopperFieldsEnum.BillingAddress) + return "billingAddress"; + + if (value == RequiredShopperFieldsEnum.DeliveryAddress) + return "deliveryAddress"; + + if (value == RequiredShopperFieldsEnum.ShopperEmail) + return "shopperEmail"; + + if (value == RequiredShopperFieldsEnum.ShopperName) + return "shopperName"; + + if (value == RequiredShopperFieldsEnum.TelephoneNumber) + return "telephoneNumber"; + + return null; + } + + /// + /// JsonConverter for writing RequiredShopperFieldsEnum. + /// + public class RequiredShopperFieldsEnumJsonConverter : JsonConverter + { + public override RequiredShopperFieldsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequiredShopperFieldsEnum.FromStringOrDefault(value) ?? new RequiredShopperFieldsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequiredShopperFieldsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequiredShopperFieldsEnum.ToJsonValue(value)); + } + } + } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + [JsonConverter(typeof(StorePaymentMethodModeEnumJsonConverter))] + public class StorePaymentMethodModeEnum : IEnum + { + /// + /// Returns the value of the StorePaymentMethodModeEnum. + /// + public string? Value { get; set; } + + /// + /// StorePaymentMethodModeEnum.AskForConsent - askForConsent + /// + public static readonly StorePaymentMethodModeEnum AskForConsent = new("askForConsent"); + + /// + /// StorePaymentMethodModeEnum.Disabled - disabled + /// + public static readonly StorePaymentMethodModeEnum Disabled = new("disabled"); + + /// + /// StorePaymentMethodModeEnum.Enabled - enabled + /// + public static readonly StorePaymentMethodModeEnum Enabled = new("enabled"); + + private StorePaymentMethodModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StorePaymentMethodModeEnum?(string? value) => value == null ? null : new StorePaymentMethodModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StorePaymentMethodModeEnum? option) => option?.Value; + + public static bool operator ==(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StorePaymentMethodModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StorePaymentMethodModeEnum? FromStringOrDefault(string value) + { + return value switch { + "askForConsent" => StorePaymentMethodModeEnum.AskForConsent, + "disabled" => StorePaymentMethodModeEnum.Disabled, + "enabled" => StorePaymentMethodModeEnum.Enabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StorePaymentMethodModeEnum? value) + { + if (value == null) + return null; + + if (value == StorePaymentMethodModeEnum.AskForConsent) + return "askForConsent"; + + if (value == StorePaymentMethodModeEnum.Disabled) + return "disabled"; + + if (value == StorePaymentMethodModeEnum.Enabled) + return "enabled"; + + return null; + } + + /// + /// JsonConverter for writing StorePaymentMethodModeEnum. + /// + public class StorePaymentMethodModeEnumJsonConverter : JsonConverter + { + public override StorePaymentMethodModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StorePaymentMethodModeEnum.FromStringOrDefault(value) ?? new StorePaymentMethodModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StorePaymentMethodModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StorePaymentMethodModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodModeOption { get; private set; } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + [JsonPropertyName("storePaymentMethodMode")] + public StorePaymentMethodModeEnum? StorePaymentMethodMode { get { return this._StorePaymentMethodModeOption; } set { this._StorePaymentMethodModeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier for which the payment link is created. + /// + /// The merchant account identifier for which the payment link is created. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + /// + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("allowedPaymentMethods")] + public List? AllowedPaymentMethods { get { return this._AllowedPaymentMethodsOption; } set { this._AllowedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BlockedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("blockedPaymentMethods")] + public List? BlockedPaymentMethods { get { return this._BlockedPaymentMethodsOption; } set { this._BlockedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper's two-letter country code. + /// + /// The shopper's two-letter country code. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A short description visible on the payment page. Maximum length: 280 characters. + /// + /// A short description visible on the payment page. Maximum length: 280 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + /// + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + [JsonPropertyName("expiresAt")] + public DateTimeOffset? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundOriginOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundOrigin")] + public FundOrigin? FundOrigin { get { return this._FundOriginOption; } set { this._FundOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundRecipientOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundRecipient")] + public FundRecipient? FundRecipient { get { return this._FundRecipientOption; } set { this._FundRecipientOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InstallmentOptionsOption { get; private set; } + + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + [JsonPropertyName("installmentOptions")] + public Dictionary? InstallmentOptions { get { return this._InstallmentOptionsOption; } set { this._InstallmentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ManualCaptureOption { get; private set; } + + /// + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + /// + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + [JsonPropertyName("manualCapture")] + public bool? ManualCapture { get { return this._ManualCaptureOption; } set { this._ManualCaptureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RequiredShopperFieldsOption { get; private set; } + + /// + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + /// + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + [JsonPropertyName("requiredShopperFields")] + public List? RequiredShopperFields { get { return this._RequiredShopperFieldsOption; } set { this._RequiredShopperFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReturnUrlOption { get; private set; } + + /// + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + /// + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + [JsonPropertyName("returnUrl")] + public string? ReturnUrl { get { return this._ReturnUrlOption; } set { this._ReturnUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReusableOption { get; private set; } + + /// + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + /// + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + [JsonPropertyName("reusable")] + public bool? Reusable { get { return this._ReusableOption; } set { this._ReusableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskData")] + public RiskData? RiskData { get { return this._RiskDataOption; } set { this._RiskDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + /// + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowRemovePaymentMethodButtonOption { get; private set; } + + /// + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. + /// + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. + [JsonPropertyName("showRemovePaymentMethodButton")] + public bool? ShowRemovePaymentMethodButton { get { return this._ShowRemovePaymentMethodButtonOption; } set { this._ShowRemovePaymentMethodButtonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitCardFundingSourcesOption { get; private set; } + + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + [JsonPropertyName("splitCardFundingSources")] + public bool? SplitCardFundingSources { get { return this._SplitCardFundingSourcesOption; } set { this._SplitCardFundingSourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThemeIdOption { get; private set; } + + /// + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + /// + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + [JsonPropertyName("themeId")] + public string? ThemeId { get { return this._ThemeIdOption; } set { this._ThemeIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public CheckoutSessionThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentLinkRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" FundOrigin: ").Append(FundOrigin).Append("\n"); + sb.Append(" FundRecipient: ").Append(FundRecipient).Append("\n"); + sb.Append(" InstallmentOptions: ").Append(InstallmentOptions).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" ManualCapture: ").Append(ManualCapture).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RequiredShopperFields: ").Append(RequiredShopperFields).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" Reusable: ").Append(Reusable).Append("\n"); + sb.Append(" RiskData: ").Append(RiskData).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" ShowRemovePaymentMethodButton: ").Append(ShowRemovePaymentMethodButton).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StorePaymentMethodMode: ").Append(StorePaymentMethodMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThemeId: ").Append(ThemeId).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CountryCode (string) maxLength + if (this.CountryCode != null && this.CountryCode.Length > 100) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be less than 100.", new [] { "CountryCode" }); + } + + // Mcc (string) maxLength + if (this.Mcc != null && this.Mcc.Length > 16) + { + yield return new ValidationResult("Invalid value for Mcc, length must be less than 16.", new [] { "Mcc" }); + } + + // MerchantOrderReference (string) maxLength + if (this.MerchantOrderReference != null && this.MerchantOrderReference.Length > 1000) + { + yield return new ValidationResult("Invalid value for MerchantOrderReference, length must be less than 1000.", new [] { "MerchantOrderReference" }); + } + + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // ShopperEmail (string) maxLength + if (this.ShopperEmail != null && this.ShopperEmail.Length > 500) + { + yield return new ValidationResult("Invalid value for ShopperEmail, length must be less than 500.", new [] { "ShopperEmail" }); + } + + // ShopperLocale (string) maxLength + if (this.ShopperLocale != null && this.ShopperLocale.Length > 32) + { + yield return new ValidationResult("Invalid value for ShopperLocale, length must be less than 32.", new [] { "ShopperLocale" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + // ShopperStatement (string) maxLength + if (this.ShopperStatement != null && this.ShopperStatement.Length > 10000) + { + yield return new ValidationResult("Invalid value for ShopperStatement, length must be less than 10000.", new [] { "ShopperStatement" }); + } + + // SocialSecurityNumber (string) maxLength + if (this.SocialSecurityNumber != null && this.SocialSecurityNumber.Length > 32) + { + yield return new ValidationResult("Invalid value for SocialSecurityNumber, length must be less than 32.", new [] { "SocialSecurityNumber" }); + } + + // TelephoneNumber (string) maxLength + if (this.TelephoneNumber != null && this.TelephoneNumber.Length > 32) + { + yield return new ValidationResult("Invalid value for TelephoneNumber, length must be less than 32.", new [] { "TelephoneNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentLinkRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentLinkRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option?> allowedPaymentMethods = default; + Option applicationInfo = default; + Option billingAddress = default; + Option?> blockedPaymentMethods = default; + Option captureDelayHours = default; + Option countryCode = default; + Option dateOfBirth = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option description = default; + Option expiresAt = default; + Option fundOrigin = default; + Option fundRecipient = default; + Option?> installmentOptions = default; + Option?> lineItems = default; + Option manualCapture = default; + Option mcc = default; + Option merchantOrderReference = default; + Option?> metadata = default; + Option platformChargebackLogic = default; + Option recurringProcessingModel = default; + Option?> requiredShopperFields = default; + Option returnUrl = default; + Option reusable = default; + Option riskData = default; + Option shopperEmail = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option showRemovePaymentMethodButton = default; + Option socialSecurityNumber = default; + Option splitCardFundingSources = default; + Option?> splits = default; + Option store = default; + Option storePaymentMethodMode = default; + Option telephoneNumber = default; + Option themeId = default; + Option threeDS2RequestData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "allowedPaymentMethods": + allowedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "blockedPaymentMethods": + blockedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "fundOrigin": + fundOrigin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundRecipient": + fundRecipient = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "installmentOptions": + installmentOptions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "manualCapture": + manualCapture = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentLinkRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "requiredShopperFields": + requiredShopperFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "reusable": + reusable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "riskData": + riskData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "showRemovePaymentMethodButton": + showRemovePaymentMethodButton = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splitCardFundingSources": + splitCardFundingSources = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storePaymentMethodMode": + string? storePaymentMethodModeRawValue = utf8JsonReader.GetString(); + storePaymentMethodMode = new Option(PaymentLinkRequest.StorePaymentMethodModeEnum.FromStringOrDefault(storePaymentMethodModeRawValue)); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "themeId": + themeId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkRequest.", nameof(reference)); + + return new PaymentLinkRequest(amount.Value!, merchantAccount.Value!, reference.Value!, allowedPaymentMethods, applicationInfo, billingAddress, blockedPaymentMethods, captureDelayHours, countryCode, dateOfBirth, deliverAt, deliveryAddress, description, expiresAt, fundOrigin, fundRecipient, installmentOptions, lineItems, manualCapture, mcc, merchantOrderReference, metadata, platformChargebackLogic, recurringProcessingModel, requiredShopperFields, returnUrl, reusable, riskData, shopperEmail, shopperLocale, shopperName, shopperReference, shopperStatement, showRemovePaymentMethodButton, socialSecurityNumber, splitCardFundingSources, splits, store, storePaymentMethodMode, telephoneNumber, themeId, threeDS2RequestData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentLinkRequest paymentLinkRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentLinkRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentLinkRequest paymentLinkRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentLinkRequest.Amount, jsonSerializerOptions); + if (paymentLinkRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentLinkRequest.MerchantAccount); + + if (paymentLinkRequest.Reference != null) + writer.WriteString("reference", paymentLinkRequest.Reference); + + if (paymentLinkRequest._AllowedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("allowedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentLinkRequest.AllowedPaymentMethods, jsonSerializerOptions); + } + if (paymentLinkRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentLinkRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentLinkRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentLinkRequest.BillingAddress, jsonSerializerOptions); + } + if (paymentLinkRequest._BlockedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("blockedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentLinkRequest.BlockedPaymentMethods, jsonSerializerOptions); + } + if (paymentLinkRequest._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentLinkRequest._CaptureDelayHoursOption.Value!.Value); + + if (paymentLinkRequest._CountryCodeOption.IsSet) + if (paymentLinkRequest.CountryCode != null) + writer.WriteString("countryCode", paymentLinkRequest.CountryCode); + + if (paymentLinkRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentLinkRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentLinkRequest._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", paymentLinkRequest._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (paymentLinkRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentLinkRequest.DeliveryAddress, jsonSerializerOptions); + } + if (paymentLinkRequest._DescriptionOption.IsSet) + if (paymentLinkRequest.Description != null) + writer.WriteString("description", paymentLinkRequest.Description); + + if (paymentLinkRequest._ExpiresAtOption.IsSet) + writer.WriteString("expiresAt", paymentLinkRequest._ExpiresAtOption.Value!.Value.ToString(ExpiresAtFormat)); + + if (paymentLinkRequest._FundOriginOption.IsSet) + { + writer.WritePropertyName("fundOrigin"); + JsonSerializer.Serialize(writer, paymentLinkRequest.FundOrigin, jsonSerializerOptions); + } + if (paymentLinkRequest._FundRecipientOption.IsSet) + { + writer.WritePropertyName("fundRecipient"); + JsonSerializer.Serialize(writer, paymentLinkRequest.FundRecipient, jsonSerializerOptions); + } + if (paymentLinkRequest._InstallmentOptionsOption.IsSet) + { + writer.WritePropertyName("installmentOptions"); + JsonSerializer.Serialize(writer, paymentLinkRequest.InstallmentOptions, jsonSerializerOptions); + } + if (paymentLinkRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentLinkRequest.LineItems, jsonSerializerOptions); + } + if (paymentLinkRequest._ManualCaptureOption.IsSet) + writer.WriteBoolean("manualCapture", paymentLinkRequest._ManualCaptureOption.Value!.Value); + + if (paymentLinkRequest._MccOption.IsSet) + if (paymentLinkRequest.Mcc != null) + writer.WriteString("mcc", paymentLinkRequest.Mcc); + + if (paymentLinkRequest._MerchantOrderReferenceOption.IsSet) + if (paymentLinkRequest.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentLinkRequest.MerchantOrderReference); + + if (paymentLinkRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentLinkRequest.Metadata, jsonSerializerOptions); + } + if (paymentLinkRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentLinkRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentLinkRequest._RecurringProcessingModelOption.IsSet && paymentLinkRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentLinkRequest.RecurringProcessingModelEnum.ToJsonValue(paymentLinkRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentLinkRequest._RequiredShopperFieldsOption.IsSet) + { + writer.WritePropertyName("requiredShopperFields"); + JsonSerializer.Serialize(writer, paymentLinkRequest.RequiredShopperFields, jsonSerializerOptions); + } + if (paymentLinkRequest._ReturnUrlOption.IsSet) + if (paymentLinkRequest.ReturnUrl != null) + writer.WriteString("returnUrl", paymentLinkRequest.ReturnUrl); + + if (paymentLinkRequest._ReusableOption.IsSet) + writer.WriteBoolean("reusable", paymentLinkRequest._ReusableOption.Value!.Value); + + if (paymentLinkRequest._RiskDataOption.IsSet) + { + writer.WritePropertyName("riskData"); + JsonSerializer.Serialize(writer, paymentLinkRequest.RiskData, jsonSerializerOptions); + } + if (paymentLinkRequest._ShopperEmailOption.IsSet) + if (paymentLinkRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentLinkRequest.ShopperEmail); + + if (paymentLinkRequest._ShopperLocaleOption.IsSet) + if (paymentLinkRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentLinkRequest.ShopperLocale); + + if (paymentLinkRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentLinkRequest.ShopperName, jsonSerializerOptions); + } + if (paymentLinkRequest._ShopperReferenceOption.IsSet) + if (paymentLinkRequest.ShopperReference != null) + writer.WriteString("shopperReference", paymentLinkRequest.ShopperReference); + + if (paymentLinkRequest._ShopperStatementOption.IsSet) + if (paymentLinkRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentLinkRequest.ShopperStatement); + + if (paymentLinkRequest._ShowRemovePaymentMethodButtonOption.IsSet) + writer.WriteBoolean("showRemovePaymentMethodButton", paymentLinkRequest._ShowRemovePaymentMethodButtonOption.Value!.Value); + + if (paymentLinkRequest._SocialSecurityNumberOption.IsSet) + if (paymentLinkRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentLinkRequest.SocialSecurityNumber); + + if (paymentLinkRequest._SplitCardFundingSourcesOption.IsSet) + writer.WriteBoolean("splitCardFundingSources", paymentLinkRequest._SplitCardFundingSourcesOption.Value!.Value); + + if (paymentLinkRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentLinkRequest.Splits, jsonSerializerOptions); + } + if (paymentLinkRequest._StoreOption.IsSet) + if (paymentLinkRequest.Store != null) + writer.WriteString("store", paymentLinkRequest.Store); + + if (paymentLinkRequest._StorePaymentMethodModeOption.IsSet && paymentLinkRequest.StorePaymentMethodMode != null) + { + string? storePaymentMethodModeRawValue = PaymentLinkRequest.StorePaymentMethodModeEnum.ToJsonValue(paymentLinkRequest._StorePaymentMethodModeOption.Value!.Value); + writer.WriteString("storePaymentMethodMode", storePaymentMethodModeRawValue); + } + + if (paymentLinkRequest._TelephoneNumberOption.IsSet) + if (paymentLinkRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentLinkRequest.TelephoneNumber); + + if (paymentLinkRequest._ThemeIdOption.IsSet) + if (paymentLinkRequest.ThemeId != null) + writer.WriteString("themeId", paymentLinkRequest.ThemeId); + + if (paymentLinkRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentLinkRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentLinkResponse.cs b/Adyen/Checkout/Models/PaymentLinkResponse.cs new file mode 100644 index 000000000..62ad7c272 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentLinkResponse.cs @@ -0,0 +1,1846 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentLinkResponse. + /// + public partial class PaymentLinkResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// A unique identifier of the payment link. + /// The merchant account identifier for which the payment link is created. + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. + /// The URL at which the shopper can complete the payment. + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// applicationInfo + /// billingAddress + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The shopper's two-letter country code. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// deliveryAddress + /// A short description visible on the payment page. Maximum length: 280 characters. + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + /// fundOrigin + /// fundRecipient + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + /// platformChargebackLogic + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + /// riskData + /// The shopper's email address. + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + /// shopperName + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. (default to true) + /// The shopper's social security number. + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false) + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// The physical store, for which this payment is processed. + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + /// threeDS2RequestData + /// The date when the payment link status was updated. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonConstructor] + public PaymentLinkResponse(Amount amount, string id, string merchantAccount, string reference, StatusEnum status, string url, Option?> allowedPaymentMethods = default, Option applicationInfo = default, Option billingAddress = default, Option?> blockedPaymentMethods = default, Option captureDelayHours = default, Option countryCode = default, Option dateOfBirth = default, Option deliverAt = default, Option deliveryAddress = default, Option description = default, Option expiresAt = default, Option fundOrigin = default, Option fundRecipient = default, Option?> installmentOptions = default, Option?> lineItems = default, Option manualCapture = default, Option mcc = default, Option merchantOrderReference = default, Option?> metadata = default, Option platformChargebackLogic = default, Option recurringProcessingModel = default, Option?> requiredShopperFields = default, Option returnUrl = default, Option reusable = default, Option riskData = default, Option shopperEmail = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option showRemovePaymentMethodButton = default, Option socialSecurityNumber = default, Option splitCardFundingSources = default, Option?> splits = default, Option store = default, Option storePaymentMethodMode = default, Option telephoneNumber = default, Option themeId = default, Option threeDS2RequestData = default, Option updatedAt = default) + { + Amount = amount; + Id = id; + MerchantAccount = merchantAccount; + Reference = reference; + Status = status; + Url = url; + _AllowedPaymentMethodsOption = allowedPaymentMethods; + _ApplicationInfoOption = applicationInfo; + _BillingAddressOption = billingAddress; + _BlockedPaymentMethodsOption = blockedPaymentMethods; + _CaptureDelayHoursOption = captureDelayHours; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _DescriptionOption = description; + _ExpiresAtOption = expiresAt; + _FundOriginOption = fundOrigin; + _FundRecipientOption = fundRecipient; + _InstallmentOptionsOption = installmentOptions; + _LineItemsOption = lineItems; + _ManualCaptureOption = manualCapture; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MetadataOption = metadata; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringProcessingModelOption = recurringProcessingModel; + _RequiredShopperFieldsOption = requiredShopperFields; + _ReturnUrlOption = returnUrl; + _ReusableOption = reusable; + _RiskDataOption = riskData; + _ShopperEmailOption = shopperEmail; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _ShowRemovePaymentMethodButtonOption = showRemovePaymentMethodButton; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitCardFundingSourcesOption = splitCardFundingSources; + _SplitsOption = splits; + _StoreOption = store; + _StorePaymentMethodModeOption = storePaymentMethodMode; + _TelephoneNumberOption = telephoneNumber; + _ThemeIdOption = themeId; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _UpdatedAtOption = updatedAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentLinkResponse() + { + } + + partial void OnCreated(); + + /// + /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. + /// + /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Completed - completed + /// + public static readonly StatusEnum Completed = new("completed"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Paid - paid + /// + public static readonly StatusEnum Paid = new("paid"); + + /// + /// StatusEnum.PaymentPending - paymentPending + /// + public static readonly StatusEnum PaymentPending = new("paymentPending"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "completed" => StatusEnum.Completed, + "expired" => StatusEnum.Expired, + "paid" => StatusEnum.Paid, + "paymentPending" => StatusEnum.PaymentPending, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Completed) + return "completed"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Paid) + return "paid"; + + if (value == StatusEnum.PaymentPending) + return "paymentPending"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. + /// + /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when `storePaymentMethodMode` is set to **askForConsent** or **enabled**. Possible values: * **Subscription** – A transaction for a fixed or variable amount, which follows a fixed schedule. * **CardOnFile** – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * **UnscheduledCardOnFile** – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or has variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Defines RequiredShopperFields. + /// + [JsonConverter(typeof(RequiredShopperFieldsEnumJsonConverter))] + public class RequiredShopperFieldsEnum : IEnum + { + /// + /// Returns the value of the RequiredShopperFieldsEnum. + /// + public string? Value { get; set; } + + /// + /// RequiredShopperFieldsEnum.BillingAddress - billingAddress + /// + public static readonly RequiredShopperFieldsEnum BillingAddress = new("billingAddress"); + + /// + /// RequiredShopperFieldsEnum.DeliveryAddress - deliveryAddress + /// + public static readonly RequiredShopperFieldsEnum DeliveryAddress = new("deliveryAddress"); + + /// + /// RequiredShopperFieldsEnum.ShopperEmail - shopperEmail + /// + public static readonly RequiredShopperFieldsEnum ShopperEmail = new("shopperEmail"); + + /// + /// RequiredShopperFieldsEnum.ShopperName - shopperName + /// + public static readonly RequiredShopperFieldsEnum ShopperName = new("shopperName"); + + /// + /// RequiredShopperFieldsEnum.TelephoneNumber - telephoneNumber + /// + public static readonly RequiredShopperFieldsEnum TelephoneNumber = new("telephoneNumber"); + + private RequiredShopperFieldsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequiredShopperFieldsEnum?(string? value) => value == null ? null : new RequiredShopperFieldsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequiredShopperFieldsEnum? option) => option?.Value; + + public static bool operator ==(RequiredShopperFieldsEnum? left, RequiredShopperFieldsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequiredShopperFieldsEnum? left, RequiredShopperFieldsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequiredShopperFieldsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequiredShopperFieldsEnum? FromStringOrDefault(string value) + { + return value switch { + "billingAddress" => RequiredShopperFieldsEnum.BillingAddress, + "deliveryAddress" => RequiredShopperFieldsEnum.DeliveryAddress, + "shopperEmail" => RequiredShopperFieldsEnum.ShopperEmail, + "shopperName" => RequiredShopperFieldsEnum.ShopperName, + "telephoneNumber" => RequiredShopperFieldsEnum.TelephoneNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequiredShopperFieldsEnum? value) + { + if (value == null) + return null; + + if (value == RequiredShopperFieldsEnum.BillingAddress) + return "billingAddress"; + + if (value == RequiredShopperFieldsEnum.DeliveryAddress) + return "deliveryAddress"; + + if (value == RequiredShopperFieldsEnum.ShopperEmail) + return "shopperEmail"; + + if (value == RequiredShopperFieldsEnum.ShopperName) + return "shopperName"; + + if (value == RequiredShopperFieldsEnum.TelephoneNumber) + return "telephoneNumber"; + + return null; + } + + /// + /// JsonConverter for writing RequiredShopperFieldsEnum. + /// + public class RequiredShopperFieldsEnumJsonConverter : JsonConverter + { + public override RequiredShopperFieldsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequiredShopperFieldsEnum.FromStringOrDefault(value) ?? new RequiredShopperFieldsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequiredShopperFieldsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequiredShopperFieldsEnum.ToJsonValue(value)); + } + } + } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + [JsonConverter(typeof(StorePaymentMethodModeEnumJsonConverter))] + public class StorePaymentMethodModeEnum : IEnum + { + /// + /// Returns the value of the StorePaymentMethodModeEnum. + /// + public string? Value { get; set; } + + /// + /// StorePaymentMethodModeEnum.AskForConsent - askForConsent + /// + public static readonly StorePaymentMethodModeEnum AskForConsent = new("askForConsent"); + + /// + /// StorePaymentMethodModeEnum.Disabled - disabled + /// + public static readonly StorePaymentMethodModeEnum Disabled = new("disabled"); + + /// + /// StorePaymentMethodModeEnum.Enabled - enabled + /// + public static readonly StorePaymentMethodModeEnum Enabled = new("enabled"); + + private StorePaymentMethodModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StorePaymentMethodModeEnum?(string? value) => value == null ? null : new StorePaymentMethodModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StorePaymentMethodModeEnum? option) => option?.Value; + + public static bool operator ==(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StorePaymentMethodModeEnum? left, StorePaymentMethodModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StorePaymentMethodModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StorePaymentMethodModeEnum? FromStringOrDefault(string value) + { + return value switch { + "askForConsent" => StorePaymentMethodModeEnum.AskForConsent, + "disabled" => StorePaymentMethodModeEnum.Disabled, + "enabled" => StorePaymentMethodModeEnum.Enabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StorePaymentMethodModeEnum? value) + { + if (value == null) + return null; + + if (value == StorePaymentMethodModeEnum.AskForConsent) + return "askForConsent"; + + if (value == StorePaymentMethodModeEnum.Disabled) + return "disabled"; + + if (value == StorePaymentMethodModeEnum.Enabled) + return "enabled"; + + return null; + } + + /// + /// JsonConverter for writing StorePaymentMethodModeEnum. + /// + public class StorePaymentMethodModeEnumJsonConverter : JsonConverter + { + public override StorePaymentMethodModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StorePaymentMethodModeEnum.FromStringOrDefault(value) ?? new StorePaymentMethodModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StorePaymentMethodModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StorePaymentMethodModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodModeOption { get; private set; } + + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + /// + /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter. + [JsonPropertyName("storePaymentMethodMode")] + public StorePaymentMethodModeEnum? StorePaymentMethodMode { get { return this._StorePaymentMethodModeOption; } set { this._StorePaymentMethodModeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// A unique identifier of the payment link. + /// + /// A unique identifier of the payment link. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// The merchant account identifier for which the payment link is created. + /// + /// The merchant account identifier for which the payment link is created. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + /// + /// A reference that is used to uniquely identify the payment in future communications about the payment status. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The URL at which the shopper can complete the payment. + /// + /// The URL at which the shopper can complete the payment. + [JsonPropertyName("url")] + public string Url { get; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("allowedPaymentMethods")] + public List? AllowedPaymentMethods { get { return this._AllowedPaymentMethodsOption; } set { this._AllowedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BlockedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("blockedPaymentMethods")] + public List? BlockedPaymentMethods { get { return this._BlockedPaymentMethodsOption; } set { this._BlockedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper's two-letter country code. + /// + /// The shopper's two-letter country code. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the purchased goods should be delivered. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A short description visible on the payment page. Maximum length: 280 characters. + /// + /// A short description visible on the payment page. Maximum length: 280 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiresAtOption { get; private set; } + + /// + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + /// + /// The date when the payment link expires. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format with time zone offset: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. The maximum expiry date is 70 days after the payment link is created. If not provided, the payment link expires 24 hours after it was created. + [JsonPropertyName("expiresAt")] + public DateTimeOffset? ExpiresAt { get { return this._ExpiresAtOption; } set { this._ExpiresAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundOriginOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundOrigin")] + public FundOrigin? FundOrigin { get { return this._FundOriginOption; } set { this._FundOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundRecipientOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundRecipient")] + public FundRecipient? FundRecipient { get { return this._FundRecipientOption; } set { this._FundRecipientOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InstallmentOptionsOption { get; private set; } + + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + /// + /// A set of key-value pairs that specifies the installment options available per payment method. The key must be a payment method name in lowercase. For example, **card** to specify installment options for all cards, or **visa** or **mc**. The value must be an object containing the installment options. + [JsonPropertyName("installmentOptions")] + public Dictionary? InstallmentOptions { get { return this._InstallmentOptionsOption; } set { this._InstallmentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ManualCaptureOption { get; private set; } + + /// + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + /// + /// Indicates if the payment must be [captured manually](https://docs.adyen.com/online-payments/capture). + [JsonPropertyName("manualCapture")] + public bool? ManualCapture { get { return this._ManualCaptureOption; } set { this._ManualCaptureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (for example, order auth-rate). The reference should be unique per billing cycle. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limitations: * Maximum 20 key-value pairs per request. Otherwise, error \"177\" occurs: \"Metadata size exceeds limit\" * Maximum 20 characters per key. Otherwise, error \"178\" occurs: \"Metadata key size exceeds limit\" * A key cannot have the name `checkout.linkId`. Any value that you provide with this key is going to be replaced by the real payment link ID. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RequiredShopperFieldsOption { get; private set; } + + /// + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + /// + /// List of fields that the shopper has to provide on the payment page before completing the payment. For more information, refer to [Provide shopper information](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#shopper-information). Possible values: * **billingAddress** – The address where to send the invoice. * **deliveryAddress** – The address where the purchased goods should be delivered. * **shopperEmail** – The shopper's email address. * **shopperName** – The shopper's full name. * **telephoneNumber** – The shopper's phone number. + [JsonPropertyName("requiredShopperFields")] + public List? RequiredShopperFields { get { return this._RequiredShopperFieldsOption; } set { this._RequiredShopperFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReturnUrlOption { get; private set; } + + /// + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + /// + /// Website URL used for redirection after payment is completed. If provided, a **Continue** button will be shown on the payment page. If shoppers select the button, they are redirected to the specified URL. + [JsonPropertyName("returnUrl")] + public string? ReturnUrl { get { return this._ReturnUrlOption; } set { this._ReturnUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReusableOption { get; private set; } + + /// + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + /// + /// Indicates whether the payment link can be reused for multiple payments. If not provided, this defaults to **false** which means the link can be used for one successful payment only. + [JsonPropertyName("reusable")] + public bool? Reusable { get { return this._ReusableOption; } set { this._ReusableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskData")] + public RiskData? RiskData { get { return this._RiskDataOption; } set { this._RiskDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + /// + /// The language to be used in the payment page, specified by a combination of a language and country code. For example, `en-US`. For a list of shopper locales that Pay by Link supports, refer to [Language and localization](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#language). + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowRemovePaymentMethodButtonOption { get; private set; } + + /// + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. + /// + /// Set to **false** to hide the button that lets the shopper remove a stored payment method. + [JsonPropertyName("showRemovePaymentMethodButton")] + public bool? ShowRemovePaymentMethodButton { get { return this._ShowRemovePaymentMethodButtonOption; } set { this._ShowRemovePaymentMethodButtonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitCardFundingSourcesOption { get; private set; } + + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + [JsonPropertyName("splitCardFundingSources")] + public bool? SplitCardFundingSources { get { return this._SplitCardFundingSourcesOption; } set { this._SplitCardFundingSourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThemeIdOption { get; private set; } + + /// + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + /// + /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area. + [JsonPropertyName("themeId")] + public string? ThemeId { get { return this._ThemeIdOption; } set { this._ThemeIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public CheckoutSessionThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdatedAtOption { get; private set; } + + /// + /// The date when the payment link status was updated. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + /// + /// The date when the payment link status was updated. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("updatedAt")] + public DateTimeOffset? UpdatedAt { get { return this._UpdatedAtOption; } set { this._UpdatedAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentLinkResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" FundOrigin: ").Append(FundOrigin).Append("\n"); + sb.Append(" FundRecipient: ").Append(FundRecipient).Append("\n"); + sb.Append(" InstallmentOptions: ").Append(InstallmentOptions).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" ManualCapture: ").Append(ManualCapture).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RequiredShopperFields: ").Append(RequiredShopperFields).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" Reusable: ").Append(Reusable).Append("\n"); + sb.Append(" RiskData: ").Append(RiskData).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" ShowRemovePaymentMethodButton: ").Append(ShowRemovePaymentMethodButton).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StorePaymentMethodMode: ").Append(StorePaymentMethodMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThemeId: ").Append(ThemeId).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CountryCode (string) maxLength + if (this.CountryCode != null && this.CountryCode.Length > 100) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be less than 100.", new [] { "CountryCode" }); + } + + // Mcc (string) maxLength + if (this.Mcc != null && this.Mcc.Length > 16) + { + yield return new ValidationResult("Invalid value for Mcc, length must be less than 16.", new [] { "Mcc" }); + } + + // MerchantOrderReference (string) maxLength + if (this.MerchantOrderReference != null && this.MerchantOrderReference.Length > 1000) + { + yield return new ValidationResult("Invalid value for MerchantOrderReference, length must be less than 1000.", new [] { "MerchantOrderReference" }); + } + + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // ShopperEmail (string) maxLength + if (this.ShopperEmail != null && this.ShopperEmail.Length > 500) + { + yield return new ValidationResult("Invalid value for ShopperEmail, length must be less than 500.", new [] { "ShopperEmail" }); + } + + // ShopperLocale (string) maxLength + if (this.ShopperLocale != null && this.ShopperLocale.Length > 32) + { + yield return new ValidationResult("Invalid value for ShopperLocale, length must be less than 32.", new [] { "ShopperLocale" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + // ShopperStatement (string) maxLength + if (this.ShopperStatement != null && this.ShopperStatement.Length > 10000) + { + yield return new ValidationResult("Invalid value for ShopperStatement, length must be less than 10000.", new [] { "ShopperStatement" }); + } + + // SocialSecurityNumber (string) maxLength + if (this.SocialSecurityNumber != null && this.SocialSecurityNumber.Length > 32) + { + yield return new ValidationResult("Invalid value for SocialSecurityNumber, length must be less than 32.", new [] { "SocialSecurityNumber" }); + } + + // TelephoneNumber (string) maxLength + if (this.TelephoneNumber != null && this.TelephoneNumber.Length > 32) + { + yield return new ValidationResult("Invalid value for TelephoneNumber, length must be less than 32.", new [] { "TelephoneNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentLinkResponseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdatedAt. + /// + public static string UpdatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentLinkResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option id = default; + Option merchantAccount = default; + Option reference = default; + Option status = default; + Option url = default; + Option?> allowedPaymentMethods = default; + Option applicationInfo = default; + Option billingAddress = default; + Option?> blockedPaymentMethods = default; + Option captureDelayHours = default; + Option countryCode = default; + Option dateOfBirth = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option description = default; + Option expiresAt = default; + Option fundOrigin = default; + Option fundRecipient = default; + Option?> installmentOptions = default; + Option?> lineItems = default; + Option manualCapture = default; + Option mcc = default; + Option merchantOrderReference = default; + Option?> metadata = default; + Option platformChargebackLogic = default; + Option recurringProcessingModel = default; + Option?> requiredShopperFields = default; + Option returnUrl = default; + Option reusable = default; + Option riskData = default; + Option shopperEmail = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option showRemovePaymentMethodButton = default; + Option socialSecurityNumber = default; + Option splitCardFundingSources = default; + Option?> splits = default; + Option store = default; + Option storePaymentMethodMode = default; + Option telephoneNumber = default; + Option themeId = default; + Option threeDS2RequestData = default; + Option updatedAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentLinkResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "allowedPaymentMethods": + allowedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "blockedPaymentMethods": + blockedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "fundOrigin": + fundOrigin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundRecipient": + fundRecipient = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "installmentOptions": + installmentOptions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "manualCapture": + manualCapture = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentLinkResponse.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "requiredShopperFields": + requiredShopperFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "reusable": + reusable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "riskData": + riskData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "showRemovePaymentMethodButton": + showRemovePaymentMethodButton = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splitCardFundingSources": + splitCardFundingSources = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storePaymentMethodMode": + string? storePaymentMethodModeRawValue = utf8JsonReader.GetString(); + storePaymentMethodMode = new Option(PaymentLinkResponse.StorePaymentMethodModeEnum.FromStringOrDefault(storePaymentMethodModeRawValue)); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "themeId": + themeId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "updatedAt": + updatedAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(amount)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(id)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(reference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(status)); + + if (!url.IsSet) + throw new ArgumentException("Property is required for class PaymentLinkResponse.", nameof(url)); + + return new PaymentLinkResponse(amount.Value!, id.Value!, merchantAccount.Value!, reference.Value!, status.Value!.Value!, url.Value!, allowedPaymentMethods, applicationInfo, billingAddress, blockedPaymentMethods, captureDelayHours, countryCode, dateOfBirth, deliverAt, deliveryAddress, description, expiresAt, fundOrigin, fundRecipient, installmentOptions, lineItems, manualCapture, mcc, merchantOrderReference, metadata, platformChargebackLogic, recurringProcessingModel, requiredShopperFields, returnUrl, reusable, riskData, shopperEmail, shopperLocale, shopperName, shopperReference, shopperStatement, showRemovePaymentMethodButton, socialSecurityNumber, splitCardFundingSources, splits, store, storePaymentMethodMode, telephoneNumber, themeId, threeDS2RequestData, updatedAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentLinkResponse paymentLinkResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentLinkResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentLinkResponse paymentLinkResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentLinkResponse.Amount, jsonSerializerOptions); + if (paymentLinkResponse.Id != null) + writer.WriteString("id", paymentLinkResponse.Id); + + if (paymentLinkResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentLinkResponse.MerchantAccount); + + if (paymentLinkResponse.Reference != null) + writer.WriteString("reference", paymentLinkResponse.Reference); + + if (paymentLinkResponse.Status != null) + { + string? statusRawValue = PaymentLinkResponse.StatusEnum.ToJsonValue(paymentLinkResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentLinkResponse.Url != null) + writer.WriteString("url", paymentLinkResponse.Url); + + if (paymentLinkResponse._AllowedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("allowedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentLinkResponse.AllowedPaymentMethods, jsonSerializerOptions); + } + if (paymentLinkResponse._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentLinkResponse.ApplicationInfo, jsonSerializerOptions); + } + if (paymentLinkResponse._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentLinkResponse.BillingAddress, jsonSerializerOptions); + } + if (paymentLinkResponse._BlockedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("blockedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentLinkResponse.BlockedPaymentMethods, jsonSerializerOptions); + } + if (paymentLinkResponse._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentLinkResponse._CaptureDelayHoursOption.Value!.Value); + + if (paymentLinkResponse._CountryCodeOption.IsSet) + if (paymentLinkResponse.CountryCode != null) + writer.WriteString("countryCode", paymentLinkResponse.CountryCode); + + if (paymentLinkResponse._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentLinkResponse._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentLinkResponse._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", paymentLinkResponse._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (paymentLinkResponse._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentLinkResponse.DeliveryAddress, jsonSerializerOptions); + } + if (paymentLinkResponse._DescriptionOption.IsSet) + if (paymentLinkResponse.Description != null) + writer.WriteString("description", paymentLinkResponse.Description); + + if (paymentLinkResponse._ExpiresAtOption.IsSet) + writer.WriteString("expiresAt", paymentLinkResponse._ExpiresAtOption.Value!.Value.ToString(ExpiresAtFormat)); + + if (paymentLinkResponse._FundOriginOption.IsSet) + { + writer.WritePropertyName("fundOrigin"); + JsonSerializer.Serialize(writer, paymentLinkResponse.FundOrigin, jsonSerializerOptions); + } + if (paymentLinkResponse._FundRecipientOption.IsSet) + { + writer.WritePropertyName("fundRecipient"); + JsonSerializer.Serialize(writer, paymentLinkResponse.FundRecipient, jsonSerializerOptions); + } + if (paymentLinkResponse._InstallmentOptionsOption.IsSet) + { + writer.WritePropertyName("installmentOptions"); + JsonSerializer.Serialize(writer, paymentLinkResponse.InstallmentOptions, jsonSerializerOptions); + } + if (paymentLinkResponse._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentLinkResponse.LineItems, jsonSerializerOptions); + } + if (paymentLinkResponse._ManualCaptureOption.IsSet) + writer.WriteBoolean("manualCapture", paymentLinkResponse._ManualCaptureOption.Value!.Value); + + if (paymentLinkResponse._MccOption.IsSet) + if (paymentLinkResponse.Mcc != null) + writer.WriteString("mcc", paymentLinkResponse.Mcc); + + if (paymentLinkResponse._MerchantOrderReferenceOption.IsSet) + if (paymentLinkResponse.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentLinkResponse.MerchantOrderReference); + + if (paymentLinkResponse._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentLinkResponse.Metadata, jsonSerializerOptions); + } + if (paymentLinkResponse._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentLinkResponse.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentLinkResponse._RecurringProcessingModelOption.IsSet && paymentLinkResponse.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentLinkResponse.RecurringProcessingModelEnum.ToJsonValue(paymentLinkResponse._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentLinkResponse._RequiredShopperFieldsOption.IsSet) + { + writer.WritePropertyName("requiredShopperFields"); + JsonSerializer.Serialize(writer, paymentLinkResponse.RequiredShopperFields, jsonSerializerOptions); + } + if (paymentLinkResponse._ReturnUrlOption.IsSet) + if (paymentLinkResponse.ReturnUrl != null) + writer.WriteString("returnUrl", paymentLinkResponse.ReturnUrl); + + if (paymentLinkResponse._ReusableOption.IsSet) + writer.WriteBoolean("reusable", paymentLinkResponse._ReusableOption.Value!.Value); + + if (paymentLinkResponse._RiskDataOption.IsSet) + { + writer.WritePropertyName("riskData"); + JsonSerializer.Serialize(writer, paymentLinkResponse.RiskData, jsonSerializerOptions); + } + if (paymentLinkResponse._ShopperEmailOption.IsSet) + if (paymentLinkResponse.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentLinkResponse.ShopperEmail); + + if (paymentLinkResponse._ShopperLocaleOption.IsSet) + if (paymentLinkResponse.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentLinkResponse.ShopperLocale); + + if (paymentLinkResponse._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentLinkResponse.ShopperName, jsonSerializerOptions); + } + if (paymentLinkResponse._ShopperReferenceOption.IsSet) + if (paymentLinkResponse.ShopperReference != null) + writer.WriteString("shopperReference", paymentLinkResponse.ShopperReference); + + if (paymentLinkResponse._ShopperStatementOption.IsSet) + if (paymentLinkResponse.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentLinkResponse.ShopperStatement); + + if (paymentLinkResponse._ShowRemovePaymentMethodButtonOption.IsSet) + writer.WriteBoolean("showRemovePaymentMethodButton", paymentLinkResponse._ShowRemovePaymentMethodButtonOption.Value!.Value); + + if (paymentLinkResponse._SocialSecurityNumberOption.IsSet) + if (paymentLinkResponse.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentLinkResponse.SocialSecurityNumber); + + if (paymentLinkResponse._SplitCardFundingSourcesOption.IsSet) + writer.WriteBoolean("splitCardFundingSources", paymentLinkResponse._SplitCardFundingSourcesOption.Value!.Value); + + if (paymentLinkResponse._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentLinkResponse.Splits, jsonSerializerOptions); + } + if (paymentLinkResponse._StoreOption.IsSet) + if (paymentLinkResponse.Store != null) + writer.WriteString("store", paymentLinkResponse.Store); + + if (paymentLinkResponse._StorePaymentMethodModeOption.IsSet && paymentLinkResponse.StorePaymentMethodMode != null) + { + string? storePaymentMethodModeRawValue = PaymentLinkResponse.StorePaymentMethodModeEnum.ToJsonValue(paymentLinkResponse._StorePaymentMethodModeOption.Value!.Value); + writer.WriteString("storePaymentMethodMode", storePaymentMethodModeRawValue); + } + + if (paymentLinkResponse._TelephoneNumberOption.IsSet) + if (paymentLinkResponse.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentLinkResponse.TelephoneNumber); + + if (paymentLinkResponse._ThemeIdOption.IsSet) + if (paymentLinkResponse.ThemeId != null) + writer.WriteString("themeId", paymentLinkResponse.ThemeId); + + if (paymentLinkResponse._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentLinkResponse.ThreeDS2RequestData, jsonSerializerOptions); + } + if (paymentLinkResponse._UpdatedAtOption.IsSet) + writer.WriteString("updatedAt", paymentLinkResponse._UpdatedAtOption.Value!.Value.ToString(UpdatedAtFormat)); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethod.cs b/Adyen/Checkout/Models/PaymentMethod.cs new file mode 100644 index 000000000..5ae8676d0 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethod.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethod. + /// + public partial class PaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A list of apps for this payment method. + /// Brand for the selected gift card. For example: plastix, hmclub. + /// List of possible brands. For example: visa, mc. + /// The configuration of the payment method. + /// The funding source of the payment method. + /// group + /// All input details to be provided to complete the payment with this payment method. + /// A list of issuers for this payment method. + /// The displayable name of this payment method. + /// Indicates whether this payment method should be promoted or not. + /// The unique payment method code. + [JsonConstructor] + public PaymentMethod(Option?> apps = default, Option brand = default, Option?> brands = default, Option?> configuration = default, Option fundingSource = default, Option group = default, Option?> inputDetails = default, Option?> issuers = default, Option name = default, Option promoted = default, Option type = default) + { + _AppsOption = apps; + _BrandOption = brand; + _BrandsOption = brands; + _ConfigurationOption = configuration; + _FundingSourceOption = fundingSource; + _GroupOption = group; + _InputDetailsOption = inputDetails; + _IssuersOption = issuers; + _NameOption = name; + _PromotedOption = promoted; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethod() + { + } + + partial void OnCreated(); + + /// + /// The funding source of the payment method. + /// + /// The funding source of the payment method. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source of the payment method. + /// + /// The funding source of the payment method. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AppsOption { get; private set; } + + /// + /// A list of apps for this payment method. + /// + /// A list of apps for this payment method. + [JsonPropertyName("apps")] + public List? Apps { get { return this._AppsOption; } set { this._AppsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Brand for the selected gift card. For example: plastix, hmclub. + /// + /// Brand for the selected gift card. For example: plastix, hmclub. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BrandsOption { get; private set; } + + /// + /// List of possible brands. For example: visa, mc. + /// + /// List of possible brands. For example: visa, mc. + [JsonPropertyName("brands")] + public List? Brands { get { return this._BrandsOption; } set { this._BrandsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConfigurationOption { get; private set; } + + /// + /// The configuration of the payment method. + /// + /// The configuration of the payment method. + [JsonPropertyName("configuration")] + public Dictionary? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GroupOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("group")] + public PaymentMethodGroup? Group { get { return this._GroupOption; } set { this._GroupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InputDetailsOption { get; private set; } + + /// + /// All input details to be provided to complete the payment with this payment method. + /// + /// All input details to be provided to complete the payment with this payment method. + [JsonPropertyName("inputDetails")] + [Obsolete("")] + public List? InputDetails { get { return this._InputDetailsOption; } set { this._InputDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IssuersOption { get; private set; } + + /// + /// A list of issuers for this payment method. + /// + /// A list of issuers for this payment method. + [JsonPropertyName("issuers")] + public List? Issuers { get { return this._IssuersOption; } set { this._IssuersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The displayable name of this payment method. + /// + /// The displayable name of this payment method. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PromotedOption { get; private set; } + + /// + /// Indicates whether this payment method should be promoted or not. + /// + /// Indicates whether this payment method should be promoted or not. + [JsonPropertyName("promoted")] + public bool? Promoted { get { return this._PromotedOption; } set { this._PromotedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The unique payment method code. + /// + /// The unique payment method code. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethod {\n"); + sb.Append(" Apps: ").Append(Apps).Append("\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" Brands: ").Append(Brands).Append("\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Group: ").Append(Group).Append("\n"); + sb.Append(" InputDetails: ").Append(InputDetails).Append("\n"); + sb.Append(" Issuers: ").Append(Issuers).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Promoted: ").Append(Promoted).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> apps = default; + Option brand = default; + Option?> brands = default; + Option?> configuration = default; + Option fundingSource = default; + Option group = default; + Option?> inputDetails = default; + Option?> issuers = default; + Option name = default; + Option promoted = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "apps": + apps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "brands": + brands = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "configuration": + configuration = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(PaymentMethod.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "group": + group = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "inputDetails": + inputDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "issuers": + issuers = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "promoted": + promoted = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentMethod(apps, brand, brands, configuration, fundingSource, group, inputDetails, issuers, name, promoted, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethod paymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethod paymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethod._AppsOption.IsSet) + { + writer.WritePropertyName("apps"); + JsonSerializer.Serialize(writer, paymentMethod.Apps, jsonSerializerOptions); + } + if (paymentMethod._BrandOption.IsSet) + if (paymentMethod.Brand != null) + writer.WriteString("brand", paymentMethod.Brand); + + if (paymentMethod._BrandsOption.IsSet) + { + writer.WritePropertyName("brands"); + JsonSerializer.Serialize(writer, paymentMethod.Brands, jsonSerializerOptions); + } + if (paymentMethod._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, paymentMethod.Configuration, jsonSerializerOptions); + } + if (paymentMethod._FundingSourceOption.IsSet && paymentMethod.FundingSource != null) + { + string? fundingSourceRawValue = PaymentMethod.FundingSourceEnum.ToJsonValue(paymentMethod._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (paymentMethod._GroupOption.IsSet) + { + writer.WritePropertyName("group"); + JsonSerializer.Serialize(writer, paymentMethod.Group, jsonSerializerOptions); + } + if (paymentMethod._InputDetailsOption.IsSet) + { + writer.WritePropertyName("inputDetails"); + JsonSerializer.Serialize(writer, paymentMethod.InputDetails, jsonSerializerOptions); + } + if (paymentMethod._IssuersOption.IsSet) + { + writer.WritePropertyName("issuers"); + JsonSerializer.Serialize(writer, paymentMethod.Issuers, jsonSerializerOptions); + } + if (paymentMethod._NameOption.IsSet) + if (paymentMethod.Name != null) + writer.WriteString("name", paymentMethod.Name); + + if (paymentMethod._PromotedOption.IsSet) + writer.WriteBoolean("promoted", paymentMethod._PromotedOption.Value!.Value); + + if (paymentMethod._TypeOption.IsSet) + if (paymentMethod.Type != null) + writer.WriteString("type", paymentMethod.Type); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodGroup.cs b/Adyen/Checkout/Models/PaymentMethodGroup.cs new file mode 100644 index 000000000..247356466 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodGroup.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodGroup. + /// + public partial class PaymentMethodGroup : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the group. + /// Echo data to be used if the payment method is displayed as part of this group. + /// The unique code of the group. + [JsonConstructor] + public PaymentMethodGroup(Option name = default, Option paymentMethodData = default, Option type = default) + { + _NameOption = name; + _PaymentMethodDataOption = paymentMethodData; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodGroup() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the group. + /// + /// The name of the group. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodDataOption { get; private set; } + + /// + /// Echo data to be used if the payment method is displayed as part of this group. + /// + /// Echo data to be used if the payment method is displayed as part of this group. + [JsonPropertyName("paymentMethodData")] + public string? PaymentMethodData { get { return this._PaymentMethodDataOption; } set { this._PaymentMethodDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The unique code of the group. + /// + /// The unique code of the group. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodGroup {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PaymentMethodData: ").Append(PaymentMethodData).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodGroupJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodGroup Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option paymentMethodData = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodData": + paymentMethodData = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentMethodGroup(name, paymentMethodData, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodGroup paymentMethodGroup, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodGroup, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodGroup paymentMethodGroup, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodGroup._NameOption.IsSet) + if (paymentMethodGroup.Name != null) + writer.WriteString("name", paymentMethodGroup.Name); + + if (paymentMethodGroup._PaymentMethodDataOption.IsSet) + if (paymentMethodGroup.PaymentMethodData != null) + writer.WriteString("paymentMethodData", paymentMethodGroup.PaymentMethodData); + + if (paymentMethodGroup._TypeOption.IsSet) + if (paymentMethodGroup.Type != null) + writer.WriteString("type", paymentMethodGroup.Type); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodIssuer.cs b/Adyen/Checkout/Models/PaymentMethodIssuer.cs new file mode 100644 index 000000000..83f9e6f7c --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodIssuer.cs @@ -0,0 +1,215 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodIssuer. + /// + public partial class PaymentMethodIssuer : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of this issuer, to submit in requests to /payments. + /// A localized name of the issuer. + /// A boolean value indicating whether this issuer is unavailable. Can be `true` whenever the issuer is offline. (default to false) + [JsonConstructor] + public PaymentMethodIssuer(string id, string name, Option disabled = default) + { + Id = id; + Name = name; + _DisabledOption = disabled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodIssuer() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of this issuer, to submit in requests to /payments. + /// + /// The unique identifier of this issuer, to submit in requests to /payments. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// A localized name of the issuer. + /// + /// A localized name of the issuer. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisabledOption { get; private set; } + + /// + /// A boolean value indicating whether this issuer is unavailable. Can be `true` whenever the issuer is offline. + /// + /// A boolean value indicating whether this issuer is unavailable. Can be `true` whenever the issuer is offline. + [JsonPropertyName("disabled")] + public bool? Disabled { get { return this._DisabledOption; } set { this._DisabledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodIssuer {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Disabled: ").Append(Disabled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodIssuerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodIssuer Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option disabled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "disabled": + disabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodIssuer.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodIssuer.", nameof(name)); + + return new PaymentMethodIssuer(id.Value!, name.Value!, disabled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodIssuer paymentMethodIssuer, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodIssuer, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodIssuer paymentMethodIssuer, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodIssuer.Id != null) + writer.WriteString("id", paymentMethodIssuer.Id); + + if (paymentMethodIssuer.Name != null) + writer.WriteString("name", paymentMethodIssuer.Name); + + if (paymentMethodIssuer._DisabledOption.IsSet) + writer.WriteBoolean("disabled", paymentMethodIssuer._DisabledOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodToStore.cs b/Adyen/Checkout/Models/PaymentMethodToStore.cs new file mode 100644 index 000000000..0b112dfc1 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodToStore.cs @@ -0,0 +1,482 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodToStore. + /// + public partial class PaymentMethodToStore : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The encrypted card. + /// The encrypted card number. + /// The encrypted card expiry month. + /// The encrypted card expiry year. + /// The encrypted card verification code. + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// The name of the card holder. + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// Set to **scheme**. + [JsonConstructor] + public PaymentMethodToStore(Option brand = default, Option cvc = default, Option encryptedCard = default, Option encryptedCardNumber = default, Option encryptedExpiryMonth = default, Option encryptedExpiryYear = default, Option encryptedSecurityCode = default, Option expiryMonth = default, Option expiryYear = default, Option holderName = default, Option number = default, Option type = default) + { + _BrandOption = brand; + _CvcOption = cvc; + _EncryptedCardOption = encryptedCard; + _EncryptedCardNumberOption = encryptedCardNumber; + _EncryptedExpiryMonthOption = encryptedExpiryMonth; + _EncryptedExpiryYearOption = encryptedExpiryYear; + _EncryptedSecurityCodeOption = encryptedSecurityCode; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _HolderNameOption = holderName; + _NumberOption = number; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodToStore() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + /// + /// Secondary brand of the card. For example: **plastix**, **hmclub**. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card verification code. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardOption { get; private set; } + + /// + /// The encrypted card. + /// + /// The encrypted card. + [JsonPropertyName("encryptedCard")] + public string? EncryptedCard { get { return this._EncryptedCardOption; } set { this._EncryptedCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedCardNumberOption { get; private set; } + + /// + /// The encrypted card number. + /// + /// The encrypted card number. + [JsonPropertyName("encryptedCardNumber")] + public string? EncryptedCardNumber { get { return this._EncryptedCardNumberOption; } set { this._EncryptedCardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryMonthOption { get; private set; } + + /// + /// The encrypted card expiry month. + /// + /// The encrypted card expiry month. + [JsonPropertyName("encryptedExpiryMonth")] + public string? EncryptedExpiryMonth { get { return this._EncryptedExpiryMonthOption; } set { this._EncryptedExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedExpiryYearOption { get; private set; } + + /// + /// The encrypted card expiry year. + /// + /// The encrypted card expiry year. + [JsonPropertyName("encryptedExpiryYear")] + public string? EncryptedExpiryYear { get { return this._EncryptedExpiryYearOption; } set { this._EncryptedExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedSecurityCodeOption { get; private set; } + + /// + /// The encrypted card verification code. + /// + /// The encrypted card verification code. + [JsonPropertyName("encryptedSecurityCode")] + public string? EncryptedSecurityCode { get { return this._EncryptedSecurityCodeOption; } set { this._EncryptedSecurityCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the card holder. + /// + /// The name of the card holder. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + /// + /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide). + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Set to **scheme**. + /// + /// Set to **scheme**. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodToStore {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" EncryptedCard: ").Append(EncryptedCard).Append("\n"); + sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); + sb.Append(" EncryptedExpiryMonth: ").Append(EncryptedExpiryMonth).Append("\n"); + sb.Append(" EncryptedExpiryYear: ").Append(EncryptedExpiryYear).Append("\n"); + sb.Append(" EncryptedSecurityCode: ").Append(EncryptedSecurityCode).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // EncryptedCard (string) maxLength + if (this.EncryptedCard != null && this.EncryptedCard.Length > 40000) + { + yield return new ValidationResult("Invalid value for EncryptedCard, length must be less than 40000.", new [] { "EncryptedCard" }); + } + + // EncryptedCardNumber (string) maxLength + if (this.EncryptedCardNumber != null && this.EncryptedCardNumber.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedCardNumber, length must be less than 15000.", new [] { "EncryptedCardNumber" }); + } + + // EncryptedExpiryMonth (string) maxLength + if (this.EncryptedExpiryMonth != null && this.EncryptedExpiryMonth.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryMonth, length must be less than 15000.", new [] { "EncryptedExpiryMonth" }); + } + + // EncryptedExpiryYear (string) maxLength + if (this.EncryptedExpiryYear != null && this.EncryptedExpiryYear.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedExpiryYear, length must be less than 15000.", new [] { "EncryptedExpiryYear" }); + } + + // EncryptedSecurityCode (string) maxLength + if (this.EncryptedSecurityCode != null && this.EncryptedSecurityCode.Length > 15000) + { + yield return new ValidationResult("Invalid value for EncryptedSecurityCode, length must be less than 15000.", new [] { "EncryptedSecurityCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodToStoreJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodToStore Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option cvc = default; + Option encryptedCard = default; + Option encryptedCardNumber = default; + Option encryptedExpiryMonth = default; + Option encryptedExpiryYear = default; + Option encryptedSecurityCode = default; + Option expiryMonth = default; + Option expiryYear = default; + Option holderName = default; + Option number = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCard": + encryptedCard = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedCardNumber": + encryptedCardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryMonth": + encryptedExpiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedExpiryYear": + encryptedExpiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "encryptedSecurityCode": + encryptedSecurityCode = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentMethodToStore(brand, cvc, encryptedCard, encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, encryptedSecurityCode, expiryMonth, expiryYear, holderName, number, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodToStore paymentMethodToStore, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodToStore, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodToStore paymentMethodToStore, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodToStore._BrandOption.IsSet) + if (paymentMethodToStore.Brand != null) + writer.WriteString("brand", paymentMethodToStore.Brand); + + if (paymentMethodToStore._CvcOption.IsSet) + if (paymentMethodToStore.Cvc != null) + writer.WriteString("cvc", paymentMethodToStore.Cvc); + + if (paymentMethodToStore._EncryptedCardOption.IsSet) + if (paymentMethodToStore.EncryptedCard != null) + writer.WriteString("encryptedCard", paymentMethodToStore.EncryptedCard); + + if (paymentMethodToStore._EncryptedCardNumberOption.IsSet) + if (paymentMethodToStore.EncryptedCardNumber != null) + writer.WriteString("encryptedCardNumber", paymentMethodToStore.EncryptedCardNumber); + + if (paymentMethodToStore._EncryptedExpiryMonthOption.IsSet) + if (paymentMethodToStore.EncryptedExpiryMonth != null) + writer.WriteString("encryptedExpiryMonth", paymentMethodToStore.EncryptedExpiryMonth); + + if (paymentMethodToStore._EncryptedExpiryYearOption.IsSet) + if (paymentMethodToStore.EncryptedExpiryYear != null) + writer.WriteString("encryptedExpiryYear", paymentMethodToStore.EncryptedExpiryYear); + + if (paymentMethodToStore._EncryptedSecurityCodeOption.IsSet) + if (paymentMethodToStore.EncryptedSecurityCode != null) + writer.WriteString("encryptedSecurityCode", paymentMethodToStore.EncryptedSecurityCode); + + if (paymentMethodToStore._ExpiryMonthOption.IsSet) + if (paymentMethodToStore.ExpiryMonth != null) + writer.WriteString("expiryMonth", paymentMethodToStore.ExpiryMonth); + + if (paymentMethodToStore._ExpiryYearOption.IsSet) + if (paymentMethodToStore.ExpiryYear != null) + writer.WriteString("expiryYear", paymentMethodToStore.ExpiryYear); + + if (paymentMethodToStore._HolderNameOption.IsSet) + if (paymentMethodToStore.HolderName != null) + writer.WriteString("holderName", paymentMethodToStore.HolderName); + + if (paymentMethodToStore._NumberOption.IsSet) + if (paymentMethodToStore.Number != null) + writer.WriteString("number", paymentMethodToStore.Number); + + if (paymentMethodToStore._TypeOption.IsSet) + if (paymentMethodToStore.Type != null) + writer.WriteString("type", paymentMethodToStore.Type); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodUPIApps.cs b/Adyen/Checkout/Models/PaymentMethodUPIApps.cs new file mode 100644 index 000000000..4a6ef5df3 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodUPIApps.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodUPIApps. + /// + public partial class PaymentMethodUPIApps : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of this app, to submit in requests to /payments. + /// A localized name of the app. + [JsonConstructor] + public PaymentMethodUPIApps(string id, string name) + { + Id = id; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodUPIApps() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of this app, to submit in requests to /payments. + /// + /// The unique identifier of this app, to submit in requests to /payments. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// A localized name of the app. + /// + /// A localized name of the app. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodUPIApps {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodUPIAppsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodUPIApps Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodUPIApps.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodUPIApps.", nameof(name)); + + return new PaymentMethodUPIApps(id.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodUPIApps paymentMethodUPIApps, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodUPIApps, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodUPIApps paymentMethodUPIApps, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodUPIApps.Id != null) + writer.WriteString("id", paymentMethodUPIApps.Id); + + if (paymentMethodUPIApps.Name != null) + writer.WriteString("name", paymentMethodUPIApps.Name); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodsRequest.cs b/Adyen/Checkout/Models/PaymentMethodsRequest.cs new file mode 100644 index 000000000..afe5db88f --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodsRequest.cs @@ -0,0 +1,846 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodsRequest. + /// + public partial class PaymentMethodsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// amount + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// browserInfo + /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web + /// The shopper's country code. + /// order + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false) + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonConstructor] + public PaymentMethodsRequest(string merchantAccount, Option?> additionalData = default, Option?> allowedPaymentMethods = default, Option amount = default, Option?> blockedPaymentMethods = default, Option browserInfo = default, Option channel = default, Option countryCode = default, Option order = default, Option shopperConversionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperLocale = default, Option shopperReference = default, Option splitCardFundingSources = default, Option store = default, Option storeFiltrationMode = default, Option telephoneNumber = default) + { + MerchantAccount = merchantAccount; + _AdditionalDataOption = additionalData; + _AllowedPaymentMethodsOption = allowedPaymentMethods; + _AmountOption = amount; + _BlockedPaymentMethodsOption = blockedPaymentMethods; + _BrowserInfoOption = browserInfo; + _ChannelOption = channel; + _CountryCodeOption = countryCode; + _OrderOption = order; + _ShopperConversionIdOption = shopperConversionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperLocaleOption = shopperLocale; + _ShopperReferenceOption = shopperReference; + _SplitCardFundingSourcesOption = splitCardFundingSources; + _StoreOption = store; + _StoreFiltrationModeOption = storeFiltrationMode; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodsRequest() + { + } + + partial void OnCreated(); + + /// + /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web + [JsonConverter(typeof(ChannelEnumJsonConverter))] + public class ChannelEnum : IEnum + { + /// + /// Returns the value of the ChannelEnum. + /// + public string? Value { get; set; } + + /// + /// ChannelEnum.IOS - iOS + /// + public static readonly ChannelEnum IOS = new("iOS"); + + /// + /// ChannelEnum.Android - Android + /// + public static readonly ChannelEnum Android = new("Android"); + + /// + /// ChannelEnum.Web - Web + /// + public static readonly ChannelEnum Web = new("Web"); + + private ChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChannelEnum?(string? value) => value == null ? null : new ChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChannelEnum? option) => option?.Value; + + public static bool operator ==(ChannelEnum? left, ChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChannelEnum? left, ChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "iOS" => ChannelEnum.IOS, + "Android" => ChannelEnum.Android, + "Web" => ChannelEnum.Web, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChannelEnum? value) + { + if (value == null) + return null; + + if (value == ChannelEnum.IOS) + return "iOS"; + + if (value == ChannelEnum.Android) + return "Android"; + + if (value == ChannelEnum.Web) + return "Web"; + + return null; + } + + /// + /// JsonConverter for writing ChannelEnum. + /// + public class ChannelEnumJsonConverter : JsonConverter + { + public override ChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChannelEnum.FromStringOrDefault(value) ?? new ChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web + [JsonPropertyName("channel")] + public ChannelEnum? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonConverter(typeof(StoreFiltrationModeEnumJsonConverter))] + public class StoreFiltrationModeEnum : IEnum + { + /// + /// Returns the value of the StoreFiltrationModeEnum. + /// + public string? Value { get; set; } + + /// + /// StoreFiltrationModeEnum.Exclusive - exclusive + /// + public static readonly StoreFiltrationModeEnum Exclusive = new("exclusive"); + + /// + /// StoreFiltrationModeEnum.Inclusive - inclusive + /// + public static readonly StoreFiltrationModeEnum Inclusive = new("inclusive"); + + /// + /// StoreFiltrationModeEnum.SkipFilter - skipFilter + /// + public static readonly StoreFiltrationModeEnum SkipFilter = new("skipFilter"); + + private StoreFiltrationModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StoreFiltrationModeEnum?(string? value) => value == null ? null : new StoreFiltrationModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StoreFiltrationModeEnum? option) => option?.Value; + + public static bool operator ==(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StoreFiltrationModeEnum? left, StoreFiltrationModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StoreFiltrationModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StoreFiltrationModeEnum? FromStringOrDefault(string value) + { + return value switch { + "exclusive" => StoreFiltrationModeEnum.Exclusive, + "inclusive" => StoreFiltrationModeEnum.Inclusive, + "skipFilter" => StoreFiltrationModeEnum.SkipFilter, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StoreFiltrationModeEnum? value) + { + if (value == null) + return null; + + if (value == StoreFiltrationModeEnum.Exclusive) + return "exclusive"; + + if (value == StoreFiltrationModeEnum.Inclusive) + return "inclusive"; + + if (value == StoreFiltrationModeEnum.SkipFilter) + return "skipFilter"; + + return null; + } + + /// + /// JsonConverter for writing StoreFiltrationModeEnum. + /// + public class StoreFiltrationModeEnumJsonConverter : JsonConverter + { + public override StoreFiltrationModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StoreFiltrationModeEnum.FromStringOrDefault(value) ?? new StoreFiltrationModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StoreFiltrationModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StoreFiltrationModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreFiltrationModeOption { get; private set; } + + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + /// + /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned. + [JsonPropertyName("storeFiltrationMode")] + public StoreFiltrationModeEnum? StoreFiltrationMode { get { return this._StoreFiltrationModeOption; } set { this._StoreFiltrationModeOption = new(value); } } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("allowedPaymentMethods")] + public List? AllowedPaymentMethods { get { return this._AllowedPaymentMethodsOption; } set { this._AllowedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BlockedPaymentMethodsOption { get; private set; } + + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + /// + /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]` + [JsonPropertyName("blockedPaymentMethods")] + public List? BlockedPaymentMethods { get { return this._BlockedPaymentMethodsOption; } set { this._BlockedPaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper's country code. + /// + /// The shopper's country code. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("order")] + public EncryptedOrderData? Order { get { return this._OrderOption; } set { this._OrderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperConversionIdOption { get; private set; } + + /// + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + /// + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + [JsonPropertyName("shopperConversionId")] + public string? ShopperConversionId { get { return this._ShopperConversionIdOption; } set { this._ShopperConversionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitCardFundingSourcesOption { get; private set; } + + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + /// + /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. + [JsonPropertyName("splitCardFundingSources")] + public bool? SplitCardFundingSources { get { return this._SplitCardFundingSourcesOption; } set { this._SplitCardFundingSourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodsRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" Order: ").Append(Order).Append("\n"); + sb.Append(" ShopperConversionId: ").Append(ShopperConversionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StoreFiltrationMode: ").Append(StoreFiltrationMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ShopperConversionId (string) maxLength + if (this.ShopperConversionId != null && this.ShopperConversionId.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperConversionId, length must be less than 256.", new [] { "ShopperConversionId" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> additionalData = default; + Option?> allowedPaymentMethods = default; + Option amount = default; + Option?> blockedPaymentMethods = default; + Option browserInfo = default; + Option channel = default; + Option countryCode = default; + Option order = default; + Option shopperConversionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperLocale = default; + Option shopperReference = default; + Option splitCardFundingSources = default; + Option store = default; + Option storeFiltrationMode = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedPaymentMethods": + allowedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "blockedPaymentMethods": + blockedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "channel": + string? channelRawValue = utf8JsonReader.GetString(); + channel = new Option(PaymentMethodsRequest.ChannelEnum.FromStringOrDefault(channelRawValue)); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "order": + order = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperConversionId": + shopperConversionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "splitCardFundingSources": + splitCardFundingSources = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storeFiltrationMode": + string? storeFiltrationModeRawValue = utf8JsonReader.GetString(); + storeFiltrationMode = new Option(PaymentMethodsRequest.StoreFiltrationModeEnum.FromStringOrDefault(storeFiltrationModeRawValue)); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodsRequest.", nameof(merchantAccount)); + + return new PaymentMethodsRequest(merchantAccount.Value!, additionalData, allowedPaymentMethods, amount, blockedPaymentMethods, browserInfo, channel, countryCode, order, shopperConversionId, shopperEmail, shopperIP, shopperLocale, shopperReference, splitCardFundingSources, store, storeFiltrationMode, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodsRequest paymentMethodsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodsRequest paymentMethodsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodsRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentMethodsRequest.MerchantAccount); + + if (paymentMethodsRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.AdditionalData, jsonSerializerOptions); + } + if (paymentMethodsRequest._AllowedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("allowedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.AllowedPaymentMethods, jsonSerializerOptions); + } + if (paymentMethodsRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.Amount, jsonSerializerOptions); + } + if (paymentMethodsRequest._BlockedPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("blockedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.BlockedPaymentMethods, jsonSerializerOptions); + } + if (paymentMethodsRequest._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.BrowserInfo, jsonSerializerOptions); + } + if (paymentMethodsRequest._ChannelOption.IsSet && paymentMethodsRequest.Channel != null) + { + string? channelRawValue = PaymentMethodsRequest.ChannelEnum.ToJsonValue(paymentMethodsRequest._ChannelOption.Value!.Value); + writer.WriteString("channel", channelRawValue); + } + + if (paymentMethodsRequest._CountryCodeOption.IsSet) + if (paymentMethodsRequest.CountryCode != null) + writer.WriteString("countryCode", paymentMethodsRequest.CountryCode); + + if (paymentMethodsRequest._OrderOption.IsSet) + { + writer.WritePropertyName("order"); + JsonSerializer.Serialize(writer, paymentMethodsRequest.Order, jsonSerializerOptions); + } + if (paymentMethodsRequest._ShopperConversionIdOption.IsSet) + if (paymentMethodsRequest.ShopperConversionId != null) + writer.WriteString("shopperConversionId", paymentMethodsRequest.ShopperConversionId); + + if (paymentMethodsRequest._ShopperEmailOption.IsSet) + if (paymentMethodsRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentMethodsRequest.ShopperEmail); + + if (paymentMethodsRequest._ShopperIPOption.IsSet) + if (paymentMethodsRequest.ShopperIP != null) + writer.WriteString("shopperIP", paymentMethodsRequest.ShopperIP); + + if (paymentMethodsRequest._ShopperLocaleOption.IsSet) + if (paymentMethodsRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentMethodsRequest.ShopperLocale); + + if (paymentMethodsRequest._ShopperReferenceOption.IsSet) + if (paymentMethodsRequest.ShopperReference != null) + writer.WriteString("shopperReference", paymentMethodsRequest.ShopperReference); + + if (paymentMethodsRequest._SplitCardFundingSourcesOption.IsSet) + writer.WriteBoolean("splitCardFundingSources", paymentMethodsRequest._SplitCardFundingSourcesOption.Value!.Value); + + if (paymentMethodsRequest._StoreOption.IsSet) + if (paymentMethodsRequest.Store != null) + writer.WriteString("store", paymentMethodsRequest.Store); + + if (paymentMethodsRequest._StoreFiltrationModeOption.IsSet && paymentMethodsRequest.StoreFiltrationMode != null) + { + string? storeFiltrationModeRawValue = PaymentMethodsRequest.StoreFiltrationModeEnum.ToJsonValue(paymentMethodsRequest._StoreFiltrationModeOption.Value!.Value); + writer.WriteString("storeFiltrationMode", storeFiltrationModeRawValue); + } + + if (paymentMethodsRequest._TelephoneNumberOption.IsSet) + if (paymentMethodsRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentMethodsRequest.TelephoneNumber); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentMethodsResponse.cs b/Adyen/Checkout/Models/PaymentMethodsResponse.cs new file mode 100644 index 000000000..36a305e5d --- /dev/null +++ b/Adyen/Checkout/Models/PaymentMethodsResponse.cs @@ -0,0 +1,205 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentMethodsResponse. + /// + public partial class PaymentMethodsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Detailed list of payment methods required to generate payment forms. + /// List of all stored payment methods. + [JsonConstructor] + public PaymentMethodsResponse(Option?> paymentMethods = default, Option?> storedPaymentMethods = default) + { + _PaymentMethodsOption = paymentMethods; + _StoredPaymentMethodsOption = storedPaymentMethods; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PaymentMethodsOption { get; private set; } + + /// + /// Detailed list of payment methods required to generate payment forms. + /// + /// Detailed list of payment methods required to generate payment forms. + [JsonPropertyName("paymentMethods")] + public List? PaymentMethods { get { return this._PaymentMethodsOption; } set { this._PaymentMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _StoredPaymentMethodsOption { get; private set; } + + /// + /// List of all stored payment methods. + /// + /// List of all stored payment methods. + [JsonPropertyName("storedPaymentMethods")] + public List? StoredPaymentMethods { get { return this._StoredPaymentMethodsOption; } set { this._StoredPaymentMethodsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodsResponse {\n"); + sb.Append(" PaymentMethods: ").Append(PaymentMethods).Append("\n"); + sb.Append(" StoredPaymentMethods: ").Append(StoredPaymentMethods).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> paymentMethods = default; + Option?> storedPaymentMethods = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "paymentMethods": + paymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storedPaymentMethods": + storedPaymentMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PaymentMethodsResponse(paymentMethods, storedPaymentMethods); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodsResponse paymentMethodsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodsResponse paymentMethodsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodsResponse._PaymentMethodsOption.IsSet) + { + writer.WritePropertyName("paymentMethods"); + JsonSerializer.Serialize(writer, paymentMethodsResponse.PaymentMethods, jsonSerializerOptions); + } + if (paymentMethodsResponse._StoredPaymentMethodsOption.IsSet) + { + writer.WritePropertyName("storedPaymentMethods"); + JsonSerializer.Serialize(writer, paymentMethodsResponse.StoredPaymentMethods, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentRefundRequest.cs b/Adyen/Checkout/Models/PaymentRefundRequest.cs new file mode 100644 index 000000000..aeb84906a --- /dev/null +++ b/Adyen/Checkout/Models/PaymentRefundRequest.cs @@ -0,0 +1,524 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentRefundRequest. + /// + public partial class PaymentRefundRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// applicationInfo + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + /// enhancedSchemeData + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** + /// Your reference for the refund request. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + [JsonConstructor] + public PaymentRefundRequest(Amount amount, string merchantAccount, Option applicationInfo = default, Option capturePspReference = default, Option enhancedSchemeData = default, Option?> lineItems = default, Option merchantRefundReason = default, Option reference = default, Option?> splits = default, Option store = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + _ApplicationInfoOption = applicationInfo; + _CapturePspReferenceOption = capturePspReference; + _EnhancedSchemeDataOption = enhancedSchemeData; + _LineItemsOption = lineItems; + _MerchantRefundReasonOption = merchantRefundReason; + _ReferenceOption = reference; + _SplitsOption = splits; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRefundRequest() + { + } + + partial void OnCreated(); + + /// + /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** + /// + /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** + [JsonConverter(typeof(MerchantRefundReasonEnumJsonConverter))] + public class MerchantRefundReasonEnum : IEnum + { + /// + /// Returns the value of the MerchantRefundReasonEnum. + /// + public string? Value { get; set; } + + /// + /// MerchantRefundReasonEnum.FRAUD - FRAUD + /// + public static readonly MerchantRefundReasonEnum FRAUD = new("FRAUD"); + + /// + /// MerchantRefundReasonEnum.CUSTOMERREQUEST - CUSTOMER REQUEST + /// + public static readonly MerchantRefundReasonEnum CUSTOMERREQUEST = new("CUSTOMER REQUEST"); + + /// + /// MerchantRefundReasonEnum.RETURN - RETURN + /// + public static readonly MerchantRefundReasonEnum RETURN = new("RETURN"); + + /// + /// MerchantRefundReasonEnum.DUPLICATE - DUPLICATE + /// + public static readonly MerchantRefundReasonEnum DUPLICATE = new("DUPLICATE"); + + /// + /// MerchantRefundReasonEnum.OTHER - OTHER + /// + public static readonly MerchantRefundReasonEnum OTHER = new("OTHER"); + + private MerchantRefundReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator MerchantRefundReasonEnum?(string? value) => value == null ? null : new MerchantRefundReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(MerchantRefundReasonEnum? option) => option?.Value; + + public static bool operator ==(MerchantRefundReasonEnum? left, MerchantRefundReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(MerchantRefundReasonEnum? left, MerchantRefundReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is MerchantRefundReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static MerchantRefundReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "FRAUD" => MerchantRefundReasonEnum.FRAUD, + "CUSTOMER REQUEST" => MerchantRefundReasonEnum.CUSTOMERREQUEST, + "RETURN" => MerchantRefundReasonEnum.RETURN, + "DUPLICATE" => MerchantRefundReasonEnum.DUPLICATE, + "OTHER" => MerchantRefundReasonEnum.OTHER, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(MerchantRefundReasonEnum? value) + { + if (value == null) + return null; + + if (value == MerchantRefundReasonEnum.FRAUD) + return "FRAUD"; + + if (value == MerchantRefundReasonEnum.CUSTOMERREQUEST) + return "CUSTOMER REQUEST"; + + if (value == MerchantRefundReasonEnum.RETURN) + return "RETURN"; + + if (value == MerchantRefundReasonEnum.DUPLICATE) + return "DUPLICATE"; + + if (value == MerchantRefundReasonEnum.OTHER) + return "OTHER"; + + return null; + } + + /// + /// JsonConverter for writing MerchantRefundReasonEnum. + /// + public class MerchantRefundReasonEnumJsonConverter : JsonConverter + { + public override MerchantRefundReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : MerchantRefundReasonEnum.FromStringOrDefault(value) ?? new MerchantRefundReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, MerchantRefundReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(MerchantRefundReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRefundReasonOption { get; private set; } + + /// + /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** + /// + /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** + [JsonPropertyName("merchantRefundReason")] + public MerchantRefundReasonEnum? MerchantRefundReason { get { return this._MerchantRefundReasonOption; } set { this._MerchantRefundReasonOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CapturePspReferenceOption { get; private set; } + + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + [JsonPropertyName("capturePspReference")] + public string? CapturePspReference { get { return this._CapturePspReferenceOption; } set { this._CapturePspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the refund request. Maximum length: 80 characters. + /// + /// Your reference for the refund request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + /// + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRefundRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" CapturePspReference: ").Append(CapturePspReference).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" MerchantRefundReason: ").Append(MerchantRefundReason).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRefundRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRefundRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option applicationInfo = default; + Option capturePspReference = default; + Option enhancedSchemeData = default; + Option?> lineItems = default; + Option merchantRefundReason = default; + Option reference = default; + Option?> splits = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "capturePspReference": + capturePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantRefundReason": + string? merchantRefundReasonRawValue = utf8JsonReader.GetString(); + merchantRefundReason = new Option(PaymentRefundRequest.MerchantRefundReasonEnum.FromStringOrDefault(merchantRefundReasonRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundRequest.", nameof(merchantAccount)); + + return new PaymentRefundRequest(amount.Value!, merchantAccount.Value!, applicationInfo, capturePspReference, enhancedSchemeData, lineItems, merchantRefundReason, reference, splits, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRefundRequest paymentRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRefundRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRefundRequest paymentRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRefundRequest.Amount, jsonSerializerOptions); + if (paymentRefundRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRefundRequest.MerchantAccount); + + if (paymentRefundRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentRefundRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentRefundRequest._CapturePspReferenceOption.IsSet) + if (paymentRefundRequest.CapturePspReference != null) + writer.WriteString("capturePspReference", paymentRefundRequest.CapturePspReference); + + if (paymentRefundRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentRefundRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentRefundRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentRefundRequest.LineItems, jsonSerializerOptions); + } + var merchantRefundReasonRawValue = PaymentRefundRequest.MerchantRefundReasonEnum.ToJsonValue(paymentRefundRequest._MerchantRefundReasonOption.Value!.Value); + if (merchantRefundReasonRawValue != null) + writer.WriteString("merchantRefundReason", merchantRefundReasonRawValue); + else + writer.WriteNull("merchantRefundReason"); + + if (paymentRefundRequest._ReferenceOption.IsSet) + if (paymentRefundRequest.Reference != null) + writer.WriteString("reference", paymentRefundRequest.Reference); + + if (paymentRefundRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRefundRequest.Splits, jsonSerializerOptions); + } + if (paymentRefundRequest._StoreOption.IsSet) + if (paymentRefundRequest.Store != null) + writer.WriteString("store", paymentRefundRequest.Store); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentRefundResponse.cs b/Adyen/Checkout/Models/PaymentRefundResponse.cs new file mode 100644 index 000000000..7009d6b1c --- /dev/null +++ b/Adyen/Checkout/Models/PaymentRefundResponse.cs @@ -0,0 +1,632 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentRefundResponse. + /// + public partial class PaymentRefundResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account that is used to process the payment. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to refund. + /// Adyen's 16-character reference associated with the refund request. + /// The status of your request. This will always have the value **received**. + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// Your reason for the refund request. + /// Your reference for the refund request. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + [JsonConstructor] + public PaymentRefundResponse(Amount amount, string merchantAccount, string paymentPspReference, string pspReference, StatusEnum status, Option capturePspReference = default, Option?> lineItems = default, Option merchantRefundReason = default, Option reference = default, Option?> splits = default, Option store = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentPspReference = paymentPspReference; + PspReference = pspReference; + Status = status; + _CapturePspReferenceOption = capturePspReference; + _LineItemsOption = lineItems; + _MerchantRefundReasonOption = merchantRefundReason; + _ReferenceOption = reference; + _SplitsOption = splits; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRefundResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Your reason for the refund request. + /// + /// Your reason for the refund request. + [JsonConverter(typeof(MerchantRefundReasonEnumJsonConverter))] + public class MerchantRefundReasonEnum : IEnum + { + /// + /// Returns the value of the MerchantRefundReasonEnum. + /// + public string? Value { get; set; } + + /// + /// MerchantRefundReasonEnum.FRAUD - FRAUD + /// + public static readonly MerchantRefundReasonEnum FRAUD = new("FRAUD"); + + /// + /// MerchantRefundReasonEnum.CUSTOMERREQUEST - CUSTOMER REQUEST + /// + public static readonly MerchantRefundReasonEnum CUSTOMERREQUEST = new("CUSTOMER REQUEST"); + + /// + /// MerchantRefundReasonEnum.RETURN - RETURN + /// + public static readonly MerchantRefundReasonEnum RETURN = new("RETURN"); + + /// + /// MerchantRefundReasonEnum.DUPLICATE - DUPLICATE + /// + public static readonly MerchantRefundReasonEnum DUPLICATE = new("DUPLICATE"); + + /// + /// MerchantRefundReasonEnum.OTHER - OTHER + /// + public static readonly MerchantRefundReasonEnum OTHER = new("OTHER"); + + private MerchantRefundReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator MerchantRefundReasonEnum?(string? value) => value == null ? null : new MerchantRefundReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(MerchantRefundReasonEnum? option) => option?.Value; + + public static bool operator ==(MerchantRefundReasonEnum? left, MerchantRefundReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(MerchantRefundReasonEnum? left, MerchantRefundReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is MerchantRefundReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static MerchantRefundReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "FRAUD" => MerchantRefundReasonEnum.FRAUD, + "CUSTOMER REQUEST" => MerchantRefundReasonEnum.CUSTOMERREQUEST, + "RETURN" => MerchantRefundReasonEnum.RETURN, + "DUPLICATE" => MerchantRefundReasonEnum.DUPLICATE, + "OTHER" => MerchantRefundReasonEnum.OTHER, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(MerchantRefundReasonEnum? value) + { + if (value == null) + return null; + + if (value == MerchantRefundReasonEnum.FRAUD) + return "FRAUD"; + + if (value == MerchantRefundReasonEnum.CUSTOMERREQUEST) + return "CUSTOMER REQUEST"; + + if (value == MerchantRefundReasonEnum.RETURN) + return "RETURN"; + + if (value == MerchantRefundReasonEnum.DUPLICATE) + return "DUPLICATE"; + + if (value == MerchantRefundReasonEnum.OTHER) + return "OTHER"; + + return null; + } + + /// + /// JsonConverter for writing MerchantRefundReasonEnum. + /// + public class MerchantRefundReasonEnumJsonConverter : JsonConverter + { + public override MerchantRefundReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : MerchantRefundReasonEnum.FromStringOrDefault(value) ?? new MerchantRefundReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, MerchantRefundReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(MerchantRefundReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRefundReasonOption { get; private set; } + + /// + /// Your reason for the refund request. + /// + /// Your reason for the refund request. + [JsonPropertyName("merchantRefundReason")] + public MerchantRefundReasonEnum? MerchantRefundReason { get { return this._MerchantRefundReasonOption; } set { this._MerchantRefundReasonOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to refund. + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to refund. + [JsonPropertyName("paymentPspReference")] + public string PaymentPspReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the refund request. + /// + /// Adyen's 16-character reference associated with the refund request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CapturePspReferenceOption { get; private set; } + + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the specific capture to refund. + [JsonPropertyName("capturePspReference")] + public string? CapturePspReference { get { return this._CapturePspReferenceOption; } set { this._CapturePspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + /// + /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the refund request. + /// + /// Your reference for the refund request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + /// + /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRefundResponse {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentPspReference: ").Append(PaymentPspReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" CapturePspReference: ").Append(CapturePspReference).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" MerchantRefundReason: ").Append(MerchantRefundReason).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRefundResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRefundResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option paymentPspReference = default; + Option pspReference = default; + Option status = default; + Option capturePspReference = default; + Option?> lineItems = default; + Option merchantRefundReason = default; + Option reference = default; + Option?> splits = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentPspReference": + paymentPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentRefundResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "capturePspReference": + capturePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantRefundReason": + string? merchantRefundReasonRawValue = utf8JsonReader.GetString(); + merchantRefundReason = new Option(PaymentRefundResponse.MerchantRefundReasonEnum.FromStringOrDefault(merchantRefundReasonRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundResponse.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundResponse.", nameof(merchantAccount)); + + if (!paymentPspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundResponse.", nameof(paymentPspReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentRefundResponse.", nameof(status)); + + return new PaymentRefundResponse(amount.Value!, merchantAccount.Value!, paymentPspReference.Value!, pspReference.Value!, status.Value!.Value!, capturePspReference, lineItems, merchantRefundReason, reference, splits, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRefundResponse paymentRefundResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRefundResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRefundResponse paymentRefundResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRefundResponse.Amount, jsonSerializerOptions); + if (paymentRefundResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRefundResponse.MerchantAccount); + + if (paymentRefundResponse.PaymentPspReference != null) + writer.WriteString("paymentPspReference", paymentRefundResponse.PaymentPspReference); + + if (paymentRefundResponse.PspReference != null) + writer.WriteString("pspReference", paymentRefundResponse.PspReference); + + if (paymentRefundResponse.Status != null) + { + string? statusRawValue = PaymentRefundResponse.StatusEnum.ToJsonValue(paymentRefundResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentRefundResponse._CapturePspReferenceOption.IsSet) + if (paymentRefundResponse.CapturePspReference != null) + writer.WriteString("capturePspReference", paymentRefundResponse.CapturePspReference); + + if (paymentRefundResponse._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentRefundResponse.LineItems, jsonSerializerOptions); + } + var merchantRefundReasonRawValue = PaymentRefundResponse.MerchantRefundReasonEnum.ToJsonValue(paymentRefundResponse._MerchantRefundReasonOption.Value!.Value); + if (merchantRefundReasonRawValue != null) + writer.WriteString("merchantRefundReason", merchantRefundReasonRawValue); + else + writer.WriteNull("merchantRefundReason"); + + if (paymentRefundResponse._ReferenceOption.IsSet) + if (paymentRefundResponse.Reference != null) + writer.WriteString("reference", paymentRefundResponse.Reference); + + if (paymentRefundResponse._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRefundResponse.Splits, jsonSerializerOptions); + } + if (paymentRefundResponse._StoreOption.IsSet) + if (paymentRefundResponse.Store != null) + writer.WriteString("store", paymentRefundResponse.Store); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentRequest.cs b/Adyen/Checkout/Models/PaymentRequest.cs new file mode 100644 index 000000000..e7262f56b --- /dev/null +++ b/Adyen/Checkout/Models/PaymentRequest.cs @@ -0,0 +1,2613 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentRequest. + /// + public partial class PaymentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// paymentMethod + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// applicationInfo + /// authenticationData + /// bankAccount + /// billingAddress + /// browserInfo + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// company + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// dccQuote + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// deliveryAddress + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// enhancedSchemeData + /// The type of the entity the payment is processed for. + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// fundOrigin + /// fundRecipient + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// installments + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana character set for Visa and Mastercard payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, capital letters, numbers and special characters. * Half-width or full-width characters. + /// mandate + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// mpiData + /// order + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + /// platformChargebackLogic + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// riskData + /// Base64-encoded JSON object containing SDK related parameters required by the SDK to function optimally. Clients must not add unrelated or sensitive personal information. + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The shopper's social security number. + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// This field contains additional information on the submerchant, who is onboarded to an acquirer through a payment facilitator or aggregator + /// surcharge + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. (default to false) + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public PaymentRequest(Amount amount, string merchantAccount, CheckoutPaymentMethod paymentMethod, string reference, string returnUrl, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option applicationInfo = default, Option authenticationData = default, Option bankAccount = default, Option billingAddress = default, Option browserInfo = default, Option captureDelayHours = default, Option channel = default, Option checkoutAttemptId = default, Option company = default, Option conversionId = default, Option countryCode = default, Option dateOfBirth = default, Option dccQuote = default, Option deliverAt = default, Option deliveryAddress = default, Option deliveryDate = default, Option deviceFingerprint = default, Option enableOneClick = default, Option enablePayOut = default, Option enableRecurring = default, Option enhancedSchemeData = default, Option entityType = default, Option fraudOffset = default, Option fundOrigin = default, Option fundRecipient = default, Option industryUsage = default, Option installments = default, Option?> lineItems = default, Option?> localizedShopperStatement = default, Option mandate = default, Option mcc = default, Option merchantOrderReference = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option mpiData = default, Option order = default, Option orderReference = default, Option origin = default, Option platformChargebackLogic = default, Option recurringExpiry = default, Option recurringFrequency = default, Option recurringProcessingModel = default, Option redirectFromIssuerMethod = default, Option redirectToIssuerMethod = default, Option riskData = default, Option sdkData = default, Option sessionValidity = default, Option shopperConversionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option?> splits = default, Option store = default, Option storePaymentMethod = default, Option?> subMerchants = default, Option surcharge = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option trustedShopper = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + ReturnUrl = returnUrl; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _ApplicationInfoOption = applicationInfo; + _AuthenticationDataOption = authenticationData; + _BankAccountOption = bankAccount; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _CaptureDelayHoursOption = captureDelayHours; + _ChannelOption = channel; + _CheckoutAttemptIdOption = checkoutAttemptId; + _CompanyOption = company; + _ConversionIdOption = conversionId; + _CountryCodeOption = countryCode; + _DateOfBirthOption = dateOfBirth; + _DccQuoteOption = dccQuote; + _DeliverAtOption = deliverAt; + _DeliveryAddressOption = deliveryAddress; + _DeliveryDateOption = deliveryDate; + _DeviceFingerprintOption = deviceFingerprint; + _EnableOneClickOption = enableOneClick; + _EnablePayOutOption = enablePayOut; + _EnableRecurringOption = enableRecurring; + _EnhancedSchemeDataOption = enhancedSchemeData; + _EntityTypeOption = entityType; + _FraudOffsetOption = fraudOffset; + _FundOriginOption = fundOrigin; + _FundRecipientOption = fundRecipient; + _IndustryUsageOption = industryUsage; + _InstallmentsOption = installments; + _LineItemsOption = lineItems; + _LocalizedShopperStatementOption = localizedShopperStatement; + _MandateOption = mandate; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _MpiDataOption = mpiData; + _OrderOption = order; + _OrderReferenceOption = orderReference; + _OriginOption = origin; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _RecurringProcessingModelOption = recurringProcessingModel; + _RedirectFromIssuerMethodOption = redirectFromIssuerMethod; + _RedirectToIssuerMethodOption = redirectToIssuerMethod; + _RiskDataOption = riskData; + _SdkDataOption = sdkData; + _SessionValidityOption = sessionValidity; + _ShopperConversionIdOption = shopperConversionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitsOption = splits; + _StoreOption = store; + _StorePaymentMethodOption = storePaymentMethod; + _SubMerchantsOption = subMerchants; + _SurchargeOption = surcharge; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRequest() + { + } + + partial void OnCreated(); + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + [JsonConverter(typeof(ChannelEnumJsonConverter))] + public class ChannelEnum : IEnum + { + /// + /// Returns the value of the ChannelEnum. + /// + public string? Value { get; set; } + + /// + /// ChannelEnum.IOS - iOS + /// + public static readonly ChannelEnum IOS = new("iOS"); + + /// + /// ChannelEnum.Android - Android + /// + public static readonly ChannelEnum Android = new("Android"); + + /// + /// ChannelEnum.Web - Web + /// + public static readonly ChannelEnum Web = new("Web"); + + private ChannelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChannelEnum?(string? value) => value == null ? null : new ChannelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChannelEnum? option) => option?.Value; + + public static bool operator ==(ChannelEnum? left, ChannelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChannelEnum? left, ChannelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChannelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChannelEnum? FromStringOrDefault(string value) + { + return value switch { + "iOS" => ChannelEnum.IOS, + "Android" => ChannelEnum.Android, + "Web" => ChannelEnum.Web, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChannelEnum? value) + { + if (value == null) + return null; + + if (value == ChannelEnum.IOS) + return "iOS"; + + if (value == ChannelEnum.Android) + return "Android"; + + if (value == ChannelEnum.Web) + return "Web"; + + return null; + } + + /// + /// JsonConverter for writing ChannelEnum. + /// + public class ChannelEnumJsonConverter : JsonConverter + { + public override ChannelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChannelEnum.FromStringOrDefault(value) ?? new ChannelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChannelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChannelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + /// + /// The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we will try to infer it from the `sdkVersion` or `token`. Possible values: * iOS * Android * Web + [JsonPropertyName("channel")] + public ChannelEnum? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// The type of the entity the payment is processed for. + /// + /// The type of the entity the payment is processed for. + [JsonConverter(typeof(EntityTypeEnumJsonConverter))] + public class EntityTypeEnum : IEnum + { + /// + /// Returns the value of the EntityTypeEnum. + /// + public string? Value { get; set; } + + /// + /// EntityTypeEnum.NaturalPerson - NaturalPerson + /// + public static readonly EntityTypeEnum NaturalPerson = new("NaturalPerson"); + + /// + /// EntityTypeEnum.CompanyName - CompanyName + /// + public static readonly EntityTypeEnum CompanyName = new("CompanyName"); + + private EntityTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EntityTypeEnum?(string? value) => value == null ? null : new EntityTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EntityTypeEnum? option) => option?.Value; + + public static bool operator ==(EntityTypeEnum? left, EntityTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EntityTypeEnum? left, EntityTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EntityTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EntityTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "NaturalPerson" => EntityTypeEnum.NaturalPerson, + "CompanyName" => EntityTypeEnum.CompanyName, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EntityTypeEnum? value) + { + if (value == null) + return null; + + if (value == EntityTypeEnum.NaturalPerson) + return "NaturalPerson"; + + if (value == EntityTypeEnum.CompanyName) + return "CompanyName"; + + return null; + } + + /// + /// JsonConverter for writing EntityTypeEnum. + /// + public class EntityTypeEnumJsonConverter : JsonConverter + { + public override EntityTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EntityTypeEnum.FromStringOrDefault(value) ?? new EntityTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EntityTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EntityTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityTypeOption { get; private set; } + + /// + /// The type of the entity the payment is processed for. + /// + /// The type of the entity the payment is processed for. + [JsonPropertyName("entityType")] + public EntityTypeEnum? EntityType { get { return this._EntityTypeOption; } set { this._EntityTypeOption = new(value); } } + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonConverter(typeof(IndustryUsageEnumJsonConverter))] + public class IndustryUsageEnum : IEnum + { + /// + /// Returns the value of the IndustryUsageEnum. + /// + public string? Value { get; set; } + + /// + /// IndustryUsageEnum.DelayedCharge - delayedCharge + /// + public static readonly IndustryUsageEnum DelayedCharge = new("delayedCharge"); + + /// + /// IndustryUsageEnum.Installment - installment + /// + public static readonly IndustryUsageEnum Installment = new("installment"); + + /// + /// IndustryUsageEnum.NoShow - noShow + /// + public static readonly IndustryUsageEnum NoShow = new("noShow"); + + private IndustryUsageEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IndustryUsageEnum?(string? value) => value == null ? null : new IndustryUsageEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IndustryUsageEnum? option) => option?.Value; + + public static bool operator ==(IndustryUsageEnum? left, IndustryUsageEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IndustryUsageEnum? left, IndustryUsageEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IndustryUsageEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IndustryUsageEnum? FromStringOrDefault(string value) + { + return value switch { + "delayedCharge" => IndustryUsageEnum.DelayedCharge, + "installment" => IndustryUsageEnum.Installment, + "noShow" => IndustryUsageEnum.NoShow, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IndustryUsageEnum? value) + { + if (value == null) + return null; + + if (value == IndustryUsageEnum.DelayedCharge) + return "delayedCharge"; + + if (value == IndustryUsageEnum.Installment) + return "installment"; + + if (value == IndustryUsageEnum.NoShow) + return "noShow"; + + return null; + } + + /// + /// JsonConverter for writing IndustryUsageEnum. + /// + public class IndustryUsageEnumJsonConverter : JsonConverter + { + public override IndustryUsageEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IndustryUsageEnum.FromStringOrDefault(value) ?? new IndustryUsageEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IndustryUsageEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IndustryUsageEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryUsageOption { get; private set; } + + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + /// + /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment** + [JsonPropertyName("industryUsage")] + public IndustryUsageEnum? IndustryUsage { get { return this._IndustryUsageOption; } set { this._IndustryUsageOption = new(value); } } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public CheckoutPaymentMethod PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + /// + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("returnUrl")] + public string ReturnUrl { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationData")] + public AuthenticationData? AuthenticationData { get { return this._AuthenticationDataOption; } set { this._AuthenticationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public CheckoutBankAccount? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public BillingAddress? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// + /// Checkout attempt ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("company")] + public Company? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConversionIdOption { get; private set; } + + /// + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + /// + /// Conversion ID that corresponds to the Id generated by the client SDK for tracking user payment journey. + [JsonPropertyName("conversionId")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `checkoutAttemptId` instead")] + public string? ConversionId { get { return this._ConversionIdOption; } set { this._ConversionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + /// + /// The shopper country. Format: [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) Example: NL or DE + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateTimeOffset? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccQuoteOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccQuote")] + public ForexQuote? DccQuote { get { return this._DccQuoteOption; } set { this._DccQuoteOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliverAtOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliverAt")] + public DateTimeOffset? DeliverAt { get { return this._DeliverAtOption; } set { this._DeliverAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public DeliveryAddress? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryDateOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliveryDate")] + [Obsolete("Deprecated since Adyen Checkout API v70. Use `deliverAt` instead.")] + public DateTimeOffset? DeliveryDate { get { return this._DeliveryDateOption; } set { this._DeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableOneClickOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + /// + /// When true and `shopperReference` is provided, the shopper will be asked if the payment details should be stored for future [one-click payments](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#one-click-payments-definition). + [JsonPropertyName("enableOneClick")] + public bool? EnableOneClick { get { return this._EnableOneClickOption; } set { this._EnableOneClickOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnablePayOutOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + /// + /// When true and `shopperReference` is provided, the payment details will be tokenized for payouts. + [JsonPropertyName("enablePayOut")] + public bool? EnablePayOut { get { return this._EnablePayOutOption; } set { this._EnablePayOutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableRecurringOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + /// + /// When true and `shopperReference` is provided, the payment details will be stored for [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types) where the shopper is not present, such as subscription or automatic top-up payments. + [JsonPropertyName("enableRecurring")] + public bool? EnableRecurring { get { return this._EnableRecurringOption; } set { this._EnableRecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundOriginOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundOrigin")] + public FundOrigin? FundOrigin { get { return this._FundOriginOption; } set { this._FundOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundRecipientOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundRecipient")] + public FundRecipient? FundRecipient { get { return this._FundRecipientOption; } set { this._FundRecipientOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("installments")] + public Installments? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LineItemsOption { get; private set; } + + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + /// + /// Price and product information about the purchased items, to be included on the invoice sent to the shopper. > This field is required for 3x 4x Oney, Affirm, Afterpay, Clearpay, Klarna, Ratepay, and Riverty. + [JsonPropertyName("lineItems")] + public List? LineItems { get { return this._LineItemsOption; } set { this._LineItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalizedShopperStatementOption { get; private set; } + + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana character set for Visa and Mastercard payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, capital letters, numbers and special characters. * Half-width or full-width characters. + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana character set for Visa and Mastercard payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, capital letters, numbers and special characters. * Half-width or full-width characters. + [JsonPropertyName("localizedShopperStatement")] + public Dictionary? LocalizedShopperStatement { get { return this._LocalizedShopperStatementOption; } set { this._LocalizedShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mandate")] + public Mandate? Mandate { get { return this._MandateOption; } set { this._MandateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("order")] + public EncryptedOrderData? Order { get { return this._OrderOption; } set { this._OrderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderReferenceOption { get; private set; } + + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + [JsonPropertyName("orderReference")] + public string? OrderReference { get { return this._OrderReferenceOption; } set { this._OrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginOption { get; private set; } + + /// + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + /// + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. + [JsonPropertyName("origin")] + public string? Origin { get { return this._OriginOption; } set { this._OriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectFromIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting back from the issuer. + [JsonPropertyName("redirectFromIssuerMethod")] + public string? RedirectFromIssuerMethod { get { return this._RedirectFromIssuerMethodOption; } set { this._RedirectFromIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectToIssuerMethodOption { get; private set; } + + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + /// + /// Specifies the redirect method (GET or POST) when redirecting to the issuer. + [JsonPropertyName("redirectToIssuerMethod")] + public string? RedirectToIssuerMethod { get { return this._RedirectToIssuerMethodOption; } set { this._RedirectToIssuerMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskData")] + public RiskData? RiskData { get { return this._RiskDataOption; } set { this._RiskDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkDataOption { get; private set; } + + /// + /// Base64-encoded JSON object containing SDK related parameters required by the SDK to function optimally. Clients must not add unrelated or sensitive personal information. + /// + /// Base64-encoded JSON object containing SDK related parameters required by the SDK to function optimally. Clients must not add unrelated or sensitive personal information. + [JsonPropertyName("sdkData")] + public string? SdkData { get { return this._SdkDataOption; } set { this._SdkDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionValidityOption { get; private set; } + + /// + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + /// + /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00 + [JsonPropertyName("sessionValidity")] + public string? SessionValidity { get { return this._SessionValidityOption; } set { this._SessionValidityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperConversionIdOption { get; private set; } + + /// + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + /// + /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates. + [JsonPropertyName("shopperConversionId")] + public string? ShopperConversionId { get { return this._ShopperConversionIdOption; } set { this._ShopperConversionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public ShopperName? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + /// + /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StorePaymentMethodOption { get; private set; } + + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + /// + /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types). + [JsonPropertyName("storePaymentMethod")] + public bool? StorePaymentMethod { get { return this._StorePaymentMethodOption; } set { this._StorePaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubMerchantsOption { get; private set; } + + /// + /// This field contains additional information on the submerchant, who is onboarded to an acquirer through a payment facilitator or aggregator + /// + /// This field contains additional information on the submerchant, who is onboarded to an acquirer through a payment facilitator or aggregator + [JsonPropertyName("subMerchants")] + public List? SubMerchants { get { return this._SubMerchantsOption; } set { this._SubMerchantsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SurchargeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("surcharge")] + public Surcharge? Surcharge { get { return this._SurchargeOption; } set { this._SurchargeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestFields? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" AuthenticationData: ").Append(AuthenticationData).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" ConversionId: ").Append(ConversionId).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DccQuote: ").Append(DccQuote).Append("\n"); + sb.Append(" DeliverAt: ").Append(DeliverAt).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeliveryDate: ").Append(DeliveryDate).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" EnableOneClick: ").Append(EnableOneClick).Append("\n"); + sb.Append(" EnablePayOut: ").Append(EnablePayOut).Append("\n"); + sb.Append(" EnableRecurring: ").Append(EnableRecurring).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" FundOrigin: ").Append(FundOrigin).Append("\n"); + sb.Append(" FundRecipient: ").Append(FundRecipient).Append("\n"); + sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" LineItems: ").Append(LineItems).Append("\n"); + sb.Append(" LocalizedShopperStatement: ").Append(LocalizedShopperStatement).Append("\n"); + sb.Append(" Mandate: ").Append(Mandate).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" Order: ").Append(Order).Append("\n"); + sb.Append(" OrderReference: ").Append(OrderReference).Append("\n"); + sb.Append(" Origin: ").Append(Origin).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" RedirectFromIssuerMethod: ").Append(RedirectFromIssuerMethod).Append("\n"); + sb.Append(" RedirectToIssuerMethod: ").Append(RedirectToIssuerMethod).Append("\n"); + sb.Append(" RiskData: ").Append(RiskData).Append("\n"); + sb.Append(" SdkData: ").Append(SdkData).Append("\n"); + sb.Append(" SessionValidity: ").Append(SessionValidity).Append("\n"); + sb.Append(" ShopperConversionId: ").Append(ShopperConversionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" StorePaymentMethod: ").Append(StorePaymentMethod).Append("\n"); + sb.Append(" SubMerchants: ").Append(SubMerchants).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + + // CheckoutAttemptId (string) maxLength + if (this.CheckoutAttemptId != null && this.CheckoutAttemptId.Length > 256) + { + yield return new ValidationResult("Invalid value for CheckoutAttemptId, length must be less than 256.", new [] { "CheckoutAttemptId" }); + } + + // CountryCode (string) maxLength + if (this.CountryCode != null && this.CountryCode.Length > 100) + { + yield return new ValidationResult("Invalid value for CountryCode, length must be less than 100.", new [] { "CountryCode" }); + } + + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // MerchantOrderReference (string) maxLength + if (this.MerchantOrderReference != null && this.MerchantOrderReference.Length > 1000) + { + yield return new ValidationResult("Invalid value for MerchantOrderReference, length must be less than 1000.", new [] { "MerchantOrderReference" }); + } + + // Origin (string) maxLength + if (this.Origin != null && this.Origin.Length > 80) + { + yield return new ValidationResult("Invalid value for Origin, length must be less than 80.", new [] { "Origin" }); + } + + // ShopperConversionId (string) maxLength + if (this.ShopperConversionId != null && this.ShopperConversionId.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperConversionId, length must be less than 256.", new [] { "ShopperConversionId" }); + } + + // ShopperIP (string) maxLength + if (this.ShopperIP != null && this.ShopperIP.Length > 1000) + { + yield return new ValidationResult("Invalid value for ShopperIP, length must be less than 1000.", new [] { "ShopperIP" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + // ShopperStatement (string) maxLength + if (this.ShopperStatement != null && this.ShopperStatement.Length > 10000) + { + yield return new ValidationResult("Invalid value for ShopperStatement, length must be less than 10000.", new [] { "ShopperStatement" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 64) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 64.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliverAt. + /// + public static string DeliverAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliveryDate. + /// + public static string DeliveryDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option paymentMethod = default; + Option reference = default; + Option returnUrl = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option applicationInfo = default; + Option authenticationData = default; + Option bankAccount = default; + Option billingAddress = default; + Option browserInfo = default; + Option captureDelayHours = default; + Option channel = default; + Option checkoutAttemptId = default; + Option company = default; + Option conversionId = default; + Option countryCode = default; + Option dateOfBirth = default; + Option dccQuote = default; + Option deliverAt = default; + Option deliveryAddress = default; + Option deliveryDate = default; + Option deviceFingerprint = default; + Option enableOneClick = default; + Option enablePayOut = default; + Option enableRecurring = default; + Option enhancedSchemeData = default; + Option entityType = default; + Option fraudOffset = default; + Option fundOrigin = default; + Option fundRecipient = default; + Option industryUsage = default; + Option installments = default; + Option?> lineItems = default; + Option?> localizedShopperStatement = default; + Option mandate = default; + Option mcc = default; + Option merchantOrderReference = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option mpiData = default; + Option order = default; + Option orderReference = default; + Option origin = default; + Option platformChargebackLogic = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option recurringProcessingModel = default; + Option redirectFromIssuerMethod = default; + Option redirectToIssuerMethod = default; + Option riskData = default; + Option sdkData = default; + Option sessionValidity = default; + Option shopperConversionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option?> splits = default; + Option store = default; + Option storePaymentMethod = default; + Option?> subMerchants = default; + Option surcharge = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "returnUrl": + returnUrl = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationData": + authenticationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "channel": + string? channelRawValue = utf8JsonReader.GetString(); + channel = new Option(PaymentRequest.ChannelEnum.FromStringOrDefault(channelRawValue)); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "company": + company = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "conversionId": + conversionId = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dccQuote": + dccQuote = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliverAt": + deliverAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryDate": + deliveryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "enableOneClick": + enableOneClick = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enablePayOut": + enablePayOut = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enableRecurring": + enableRecurring = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + entityType = new Option(PaymentRequest.EntityTypeEnum.FromStringOrDefault(entityTypeRawValue)); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "fundOrigin": + fundOrigin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundRecipient": + fundRecipient = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "industryUsage": + string? industryUsageRawValue = utf8JsonReader.GetString(); + industryUsage = new Option(PaymentRequest.IndustryUsageEnum.FromStringOrDefault(industryUsageRawValue)); + break; + case "installments": + installments = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lineItems": + lineItems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localizedShopperStatement": + localizedShopperStatement = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mandate": + mandate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "order": + order = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderReference": + orderReference = new Option(utf8JsonReader.GetString()!); + break; + case "origin": + origin = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "redirectFromIssuerMethod": + redirectFromIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "redirectToIssuerMethod": + redirectToIssuerMethod = new Option(utf8JsonReader.GetString()!); + break; + case "riskData": + riskData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sdkData": + sdkData = new Option(utf8JsonReader.GetString()!); + break; + case "sessionValidity": + sessionValidity = new Option(utf8JsonReader.GetString()!); + break; + case "shopperConversionId": + shopperConversionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PaymentRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "storePaymentMethod": + storePaymentMethod = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "subMerchants": + subMerchants = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "surcharge": + surcharge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(reference)); + + if (!returnUrl.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(returnUrl)); + + return new PaymentRequest(amount.Value!, merchantAccount.Value!, paymentMethod.Value!, reference.Value!, returnUrl.Value!, accountInfo, additionalAmount, additionalData, applicationInfo, authenticationData, bankAccount, billingAddress, browserInfo, captureDelayHours, channel, checkoutAttemptId, company, conversionId, countryCode, dateOfBirth, dccQuote, deliverAt, deliveryAddress, deliveryDate, deviceFingerprint, enableOneClick, enablePayOut, enableRecurring, enhancedSchemeData, entityType, fraudOffset, fundOrigin, fundRecipient, industryUsage, installments, lineItems, localizedShopperStatement, mandate, mcc, merchantOrderReference, merchantRiskIndicator, metadata, mpiData, order, orderReference, origin, platformChargebackLogic, recurringExpiry, recurringFrequency, recurringProcessingModel, redirectFromIssuerMethod, redirectToIssuerMethod, riskData, sdkData, sessionValidity, shopperConversionId, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, splits, store, storePaymentMethod, subMerchants, surcharge, telephoneNumber, threeDS2RequestData, threeDSAuthenticationOnly, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRequest paymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRequest paymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRequest.Amount, jsonSerializerOptions); + if (paymentRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, paymentRequest.PaymentMethod, jsonSerializerOptions); + if (paymentRequest.Reference != null) + writer.WriteString("reference", paymentRequest.Reference); + + if (paymentRequest.ReturnUrl != null) + writer.WriteString("returnUrl", paymentRequest.ReturnUrl); + + if (paymentRequest._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, paymentRequest.AccountInfo, jsonSerializerOptions); + } + if (paymentRequest._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, paymentRequest.AdditionalAmount, jsonSerializerOptions); + } + if (paymentRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentRequest.AdditionalData, jsonSerializerOptions); + } + if (paymentRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentRequest._AuthenticationDataOption.IsSet) + { + writer.WritePropertyName("authenticationData"); + JsonSerializer.Serialize(writer, paymentRequest.AuthenticationData, jsonSerializerOptions); + } + if (paymentRequest._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, paymentRequest.BankAccount, jsonSerializerOptions); + } + if (paymentRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentRequest.BillingAddress, jsonSerializerOptions); + } + if (paymentRequest._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, paymentRequest.BrowserInfo, jsonSerializerOptions); + } + if (paymentRequest._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentRequest._CaptureDelayHoursOption.Value!.Value); + + if (paymentRequest._ChannelOption.IsSet && paymentRequest.Channel != null) + { + string? channelRawValue = PaymentRequest.ChannelEnum.ToJsonValue(paymentRequest._ChannelOption.Value!.Value); + writer.WriteString("channel", channelRawValue); + } + + if (paymentRequest._CheckoutAttemptIdOption.IsSet) + if (paymentRequest.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", paymentRequest.CheckoutAttemptId); + + if (paymentRequest._CompanyOption.IsSet) + { + writer.WritePropertyName("company"); + JsonSerializer.Serialize(writer, paymentRequest.Company, jsonSerializerOptions); + } + if (paymentRequest._ConversionIdOption.IsSet) + if (paymentRequest.ConversionId != null) + writer.WriteString("conversionId", paymentRequest.ConversionId); + + if (paymentRequest._CountryCodeOption.IsSet) + if (paymentRequest.CountryCode != null) + writer.WriteString("countryCode", paymentRequest.CountryCode); + + if (paymentRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentRequest._DccQuoteOption.IsSet) + { + writer.WritePropertyName("dccQuote"); + JsonSerializer.Serialize(writer, paymentRequest.DccQuote, jsonSerializerOptions); + } + if (paymentRequest._DeliverAtOption.IsSet) + writer.WriteString("deliverAt", paymentRequest._DeliverAtOption.Value!.Value.ToString(DeliverAtFormat)); + + if (paymentRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentRequest.DeliveryAddress, jsonSerializerOptions); + } + if (paymentRequest._DeliveryDateOption.IsSet) + writer.WriteString("deliveryDate", paymentRequest._DeliveryDateOption.Value!.Value.ToString(DeliveryDateFormat)); + + if (paymentRequest._DeviceFingerprintOption.IsSet) + if (paymentRequest.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", paymentRequest.DeviceFingerprint); + + if (paymentRequest._EnableOneClickOption.IsSet) + writer.WriteBoolean("enableOneClick", paymentRequest._EnableOneClickOption.Value!.Value); + + if (paymentRequest._EnablePayOutOption.IsSet) + writer.WriteBoolean("enablePayOut", paymentRequest._EnablePayOutOption.Value!.Value); + + if (paymentRequest._EnableRecurringOption.IsSet) + writer.WriteBoolean("enableRecurring", paymentRequest._EnableRecurringOption.Value!.Value); + + if (paymentRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentRequest._EntityTypeOption.IsSet && paymentRequest.EntityType != null) + { + string? entityTypeRawValue = PaymentRequest.EntityTypeEnum.ToJsonValue(paymentRequest._EntityTypeOption.Value!.Value); + writer.WriteString("entityType", entityTypeRawValue); + } + + if (paymentRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", paymentRequest._FraudOffsetOption.Value!.Value); + + if (paymentRequest._FundOriginOption.IsSet) + { + writer.WritePropertyName("fundOrigin"); + JsonSerializer.Serialize(writer, paymentRequest.FundOrigin, jsonSerializerOptions); + } + if (paymentRequest._FundRecipientOption.IsSet) + { + writer.WritePropertyName("fundRecipient"); + JsonSerializer.Serialize(writer, paymentRequest.FundRecipient, jsonSerializerOptions); + } + if (paymentRequest._IndustryUsageOption.IsSet && paymentRequest.IndustryUsage != null) + { + string? industryUsageRawValue = PaymentRequest.IndustryUsageEnum.ToJsonValue(paymentRequest._IndustryUsageOption.Value!.Value); + writer.WriteString("industryUsage", industryUsageRawValue); + } + + if (paymentRequest._InstallmentsOption.IsSet) + { + writer.WritePropertyName("installments"); + JsonSerializer.Serialize(writer, paymentRequest.Installments, jsonSerializerOptions); + } + if (paymentRequest._LineItemsOption.IsSet) + { + writer.WritePropertyName("lineItems"); + JsonSerializer.Serialize(writer, paymentRequest.LineItems, jsonSerializerOptions); + } + if (paymentRequest._LocalizedShopperStatementOption.IsSet) + { + writer.WritePropertyName("localizedShopperStatement"); + JsonSerializer.Serialize(writer, paymentRequest.LocalizedShopperStatement, jsonSerializerOptions); + } + if (paymentRequest._MandateOption.IsSet) + { + writer.WritePropertyName("mandate"); + JsonSerializer.Serialize(writer, paymentRequest.Mandate, jsonSerializerOptions); + } + if (paymentRequest._MccOption.IsSet) + if (paymentRequest.Mcc != null) + writer.WriteString("mcc", paymentRequest.Mcc); + + if (paymentRequest._MerchantOrderReferenceOption.IsSet) + if (paymentRequest.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentRequest.MerchantOrderReference); + + if (paymentRequest._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, paymentRequest.MerchantRiskIndicator, jsonSerializerOptions); + } + if (paymentRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentRequest.Metadata, jsonSerializerOptions); + } + if (paymentRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, paymentRequest.MpiData, jsonSerializerOptions); + } + if (paymentRequest._OrderOption.IsSet) + { + writer.WritePropertyName("order"); + JsonSerializer.Serialize(writer, paymentRequest.Order, jsonSerializerOptions); + } + if (paymentRequest._OrderReferenceOption.IsSet) + if (paymentRequest.OrderReference != null) + writer.WriteString("orderReference", paymentRequest.OrderReference); + + if (paymentRequest._OriginOption.IsSet) + if (paymentRequest.Origin != null) + writer.WriteString("origin", paymentRequest.Origin); + + if (paymentRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentRequest._RecurringExpiryOption.IsSet) + if (paymentRequest.RecurringExpiry != null) + writer.WriteString("recurringExpiry", paymentRequest.RecurringExpiry); + + if (paymentRequest._RecurringFrequencyOption.IsSet) + if (paymentRequest.RecurringFrequency != null) + writer.WriteString("recurringFrequency", paymentRequest.RecurringFrequency); + + if (paymentRequest._RecurringProcessingModelOption.IsSet && paymentRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentRequest.RecurringProcessingModelEnum.ToJsonValue(paymentRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentRequest._RedirectFromIssuerMethodOption.IsSet) + if (paymentRequest.RedirectFromIssuerMethod != null) + writer.WriteString("redirectFromIssuerMethod", paymentRequest.RedirectFromIssuerMethod); + + if (paymentRequest._RedirectToIssuerMethodOption.IsSet) + if (paymentRequest.RedirectToIssuerMethod != null) + writer.WriteString("redirectToIssuerMethod", paymentRequest.RedirectToIssuerMethod); + + if (paymentRequest._RiskDataOption.IsSet) + { + writer.WritePropertyName("riskData"); + JsonSerializer.Serialize(writer, paymentRequest.RiskData, jsonSerializerOptions); + } + if (paymentRequest._SdkDataOption.IsSet) + if (paymentRequest.SdkData != null) + writer.WriteString("sdkData", paymentRequest.SdkData); + + if (paymentRequest._SessionValidityOption.IsSet) + if (paymentRequest.SessionValidity != null) + writer.WriteString("sessionValidity", paymentRequest.SessionValidity); + + if (paymentRequest._ShopperConversionIdOption.IsSet) + if (paymentRequest.ShopperConversionId != null) + writer.WriteString("shopperConversionId", paymentRequest.ShopperConversionId); + + if (paymentRequest._ShopperEmailOption.IsSet) + if (paymentRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentRequest.ShopperEmail); + + if (paymentRequest._ShopperIPOption.IsSet) + if (paymentRequest.ShopperIP != null) + writer.WriteString("shopperIP", paymentRequest.ShopperIP); + + if (paymentRequest._ShopperInteractionOption.IsSet && paymentRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PaymentRequest.ShopperInteractionEnum.ToJsonValue(paymentRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (paymentRequest._ShopperLocaleOption.IsSet) + if (paymentRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentRequest.ShopperLocale); + + if (paymentRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentRequest.ShopperName, jsonSerializerOptions); + } + if (paymentRequest._ShopperReferenceOption.IsSet) + if (paymentRequest.ShopperReference != null) + writer.WriteString("shopperReference", paymentRequest.ShopperReference); + + if (paymentRequest._ShopperStatementOption.IsSet) + if (paymentRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentRequest.ShopperStatement); + + if (paymentRequest._SocialSecurityNumberOption.IsSet) + if (paymentRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentRequest.SocialSecurityNumber); + + if (paymentRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRequest.Splits, jsonSerializerOptions); + } + if (paymentRequest._StoreOption.IsSet) + if (paymentRequest.Store != null) + writer.WriteString("store", paymentRequest.Store); + + if (paymentRequest._StorePaymentMethodOption.IsSet) + writer.WriteBoolean("storePaymentMethod", paymentRequest._StorePaymentMethodOption.Value!.Value); + + if (paymentRequest._SubMerchantsOption.IsSet) + { + writer.WritePropertyName("subMerchants"); + JsonSerializer.Serialize(writer, paymentRequest.SubMerchants, jsonSerializerOptions); + } + if (paymentRequest._SurchargeOption.IsSet) + { + writer.WritePropertyName("surcharge"); + JsonSerializer.Serialize(writer, paymentRequest.Surcharge, jsonSerializerOptions); + } + if (paymentRequest._TelephoneNumberOption.IsSet) + if (paymentRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentRequest.TelephoneNumber); + + if (paymentRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + if (paymentRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", paymentRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (paymentRequest._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", paymentRequest._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentResponse.cs b/Adyen/Checkout/Models/PaymentResponse.cs new file mode 100644 index 000000000..d27e1a319 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentResponse.cs @@ -0,0 +1,767 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentResponse. + /// + public partial class PaymentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// action + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// amount + /// Donation Token containing payment details for Adyen Giving. + /// fraudResult + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// order + /// paymentMethod + /// paymentValidations + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. > For payment methods that require a redirect or additional action, you will get this value in the `/payments/details` response. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// threeDS2ResponseData + /// threeDS2Result + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + [JsonConstructor] + public PaymentResponse(Option action = default, Option?> additionalData = default, Option amount = default, Option donationToken = default, Option fraudResult = default, Option merchantReference = default, Option order = default, Option paymentMethod = default, Option paymentValidations = default, Option pspReference = default, Option refusalReason = default, Option refusalReasonCode = default, Option resultCode = default, Option threeDS2ResponseData = default, Option threeDS2Result = default, Option threeDSPaymentData = default) + { + _ActionOption = action; + _AdditionalDataOption = additionalData; + _AmountOption = amount; + _DonationTokenOption = donationToken; + _FraudResultOption = fraudResult; + _MerchantReferenceOption = merchantReference; + _OrderOption = order; + _PaymentMethodOption = paymentMethod; + _PaymentValidationsOption = paymentValidations; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _RefusalReasonCodeOption = refusalReasonCode; + _ResultCodeOption = resultCode; + _ThreeDS2ResponseDataOption = threeDS2ResponseData; + _ThreeDS2ResultOption = threeDS2Result; + _ThreeDSPaymentDataOption = threeDSPaymentData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.AuthenticationFinished - AuthenticationFinished + /// + public static readonly ResultCodeEnum AuthenticationFinished = new("AuthenticationFinished"); + + /// + /// ResultCodeEnum.AuthenticationNotRequired - AuthenticationNotRequired + /// + public static readonly ResultCodeEnum AuthenticationNotRequired = new("AuthenticationNotRequired"); + + /// + /// ResultCodeEnum.Authorised - Authorised + /// + public static readonly ResultCodeEnum Authorised = new("Authorised"); + + /// + /// ResultCodeEnum.Cancelled - Cancelled + /// + public static readonly ResultCodeEnum Cancelled = new("Cancelled"); + + /// + /// ResultCodeEnum.ChallengeShopper - ChallengeShopper + /// + public static readonly ResultCodeEnum ChallengeShopper = new("ChallengeShopper"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.IdentifyShopper - IdentifyShopper + /// + public static readonly ResultCodeEnum IdentifyShopper = new("IdentifyShopper"); + + /// + /// ResultCodeEnum.PartiallyAuthorised - PartiallyAuthorised + /// + public static readonly ResultCodeEnum PartiallyAuthorised = new("PartiallyAuthorised"); + + /// + /// ResultCodeEnum.Pending - Pending + /// + public static readonly ResultCodeEnum Pending = new("Pending"); + + /// + /// ResultCodeEnum.PresentToShopper - PresentToShopper + /// + public static readonly ResultCodeEnum PresentToShopper = new("PresentToShopper"); + + /// + /// ResultCodeEnum.Received - Received + /// + public static readonly ResultCodeEnum Received = new("Received"); + + /// + /// ResultCodeEnum.RedirectShopper - RedirectShopper + /// + public static readonly ResultCodeEnum RedirectShopper = new("RedirectShopper"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "AuthenticationFinished" => ResultCodeEnum.AuthenticationFinished, + "AuthenticationNotRequired" => ResultCodeEnum.AuthenticationNotRequired, + "Authorised" => ResultCodeEnum.Authorised, + "Cancelled" => ResultCodeEnum.Cancelled, + "ChallengeShopper" => ResultCodeEnum.ChallengeShopper, + "Error" => ResultCodeEnum.Error, + "IdentifyShopper" => ResultCodeEnum.IdentifyShopper, + "PartiallyAuthorised" => ResultCodeEnum.PartiallyAuthorised, + "Pending" => ResultCodeEnum.Pending, + "PresentToShopper" => ResultCodeEnum.PresentToShopper, + "Received" => ResultCodeEnum.Received, + "RedirectShopper" => ResultCodeEnum.RedirectShopper, + "Refused" => ResultCodeEnum.Refused, + "Success" => ResultCodeEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.AuthenticationFinished) + return "AuthenticationFinished"; + + if (value == ResultCodeEnum.AuthenticationNotRequired) + return "AuthenticationNotRequired"; + + if (value == ResultCodeEnum.Authorised) + return "Authorised"; + + if (value == ResultCodeEnum.Cancelled) + return "Cancelled"; + + if (value == ResultCodeEnum.ChallengeShopper) + return "ChallengeShopper"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.IdentifyShopper) + return "IdentifyShopper"; + + if (value == ResultCodeEnum.PartiallyAuthorised) + return "PartiallyAuthorised"; + + if (value == ResultCodeEnum.Pending) + return "Pending"; + + if (value == ResultCodeEnum.PresentToShopper) + return "PresentToShopper"; + + if (value == ResultCodeEnum.Received) + return "Received"; + + if (value == ResultCodeEnum.RedirectShopper) + return "RedirectShopper"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Success) + return "Success"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("action")] + public PaymentResponseAction? Action { get { return this._ActionOption; } set { this._ActionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DonationTokenOption { get; private set; } + + /// + /// Donation Token containing payment details for Adyen Giving. + /// + /// Donation Token containing payment details for Adyen Giving. + [JsonPropertyName("donationToken")] + public string? DonationToken { get { return this._DonationTokenOption; } set { this._DonationTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("order")] + public CheckoutOrderResponse? Order { get { return this._OrderOption; } set { this._OrderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public ResponsePaymentMethod? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentValidationsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentValidations")] + public PaymentValidationsResponse? PaymentValidations { get { return this._PaymentValidationsOption; } set { this._PaymentValidationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. > For payment methods that require a redirect or additional action, you will get this value in the `/payments/details` response. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. > For payment methods that require a redirect or additional action, you will get this value in the `/payments/details` response. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonCodeOption { get; private set; } + + /// + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// Code that specifies the refusal reason. For more information, see [Authorisation refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReasonCode")] + public string? RefusalReasonCode { get { return this._RefusalReasonCodeOption; } set { this._RefusalReasonCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResponseDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2ResponseData")] + public ThreeDS2ResponseData? ThreeDS2ResponseData { get { return this._ThreeDS2ResponseDataOption; } set { this._ThreeDS2ResponseDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2Result")] + public ThreeDS2Result? ThreeDS2Result { get { return this._ThreeDS2ResultOption; } set { this._ThreeDS2ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSPaymentDataOption { get; private set; } + + /// + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + /// + /// When non-empty, contains a value that you must submit to the `/payments/details` endpoint as `paymentData`. + [JsonPropertyName("threeDSPaymentData")] + public string? ThreeDSPaymentData { get { return this._ThreeDSPaymentDataOption; } set { this._ThreeDSPaymentDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentResponse {\n"); + sb.Append(" Action: ").Append(Action).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" DonationToken: ").Append(DonationToken).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" Order: ").Append(Order).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PaymentValidations: ").Append(PaymentValidations).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" RefusalReasonCode: ").Append(RefusalReasonCode).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThreeDS2ResponseData: ").Append(ThreeDS2ResponseData).Append("\n"); + sb.Append(" ThreeDS2Result: ").Append(ThreeDS2Result).Append("\n"); + sb.Append(" ThreeDSPaymentData: ").Append(ThreeDSPaymentData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option action = default; + Option?> additionalData = default; + Option amount = default; + Option donationToken = default; + Option fraudResult = default; + Option merchantReference = default; + Option order = default; + Option paymentMethod = default; + Option paymentValidations = default; + Option pspReference = default; + Option refusalReason = default; + Option refusalReasonCode = default; + Option resultCode = default; + Option threeDS2ResponseData = default; + Option threeDS2Result = default; + Option threeDSPaymentData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "action": + action = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "donationToken": + donationToken = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "order": + order = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentValidations": + paymentValidations = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReasonCode": + refusalReasonCode = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(PaymentResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "threeDS2ResponseData": + threeDS2ResponseData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2Result": + threeDS2Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSPaymentData": + threeDSPaymentData = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentResponse(action, additionalData, amount, donationToken, fraudResult, merchantReference, order, paymentMethod, paymentValidations, pspReference, refusalReason, refusalReasonCode, resultCode, threeDS2ResponseData, threeDS2Result, threeDSPaymentData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentResponse paymentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentResponse paymentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentResponse._ActionOption.IsSet) + { + writer.WritePropertyName("action"); + JsonSerializer.Serialize(writer, paymentResponse.Action, jsonSerializerOptions); + } + if (paymentResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentResponse.AdditionalData, jsonSerializerOptions); + } + if (paymentResponse._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentResponse.Amount, jsonSerializerOptions); + } + if (paymentResponse._DonationTokenOption.IsSet) + if (paymentResponse.DonationToken != null) + writer.WriteString("donationToken", paymentResponse.DonationToken); + + if (paymentResponse._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, paymentResponse.FraudResult, jsonSerializerOptions); + } + if (paymentResponse._MerchantReferenceOption.IsSet) + if (paymentResponse.MerchantReference != null) + writer.WriteString("merchantReference", paymentResponse.MerchantReference); + + if (paymentResponse._OrderOption.IsSet) + { + writer.WritePropertyName("order"); + JsonSerializer.Serialize(writer, paymentResponse.Order, jsonSerializerOptions); + } + if (paymentResponse._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, paymentResponse.PaymentMethod, jsonSerializerOptions); + } + if (paymentResponse._PaymentValidationsOption.IsSet) + { + writer.WritePropertyName("paymentValidations"); + JsonSerializer.Serialize(writer, paymentResponse.PaymentValidations, jsonSerializerOptions); + } + if (paymentResponse._PspReferenceOption.IsSet) + if (paymentResponse.PspReference != null) + writer.WriteString("pspReference", paymentResponse.PspReference); + + if (paymentResponse._RefusalReasonOption.IsSet) + if (paymentResponse.RefusalReason != null) + writer.WriteString("refusalReason", paymentResponse.RefusalReason); + + if (paymentResponse._RefusalReasonCodeOption.IsSet) + if (paymentResponse.RefusalReasonCode != null) + writer.WriteString("refusalReasonCode", paymentResponse.RefusalReasonCode); + + if (paymentResponse._ResultCodeOption.IsSet && paymentResponse.ResultCode != null) + { + string? resultCodeRawValue = PaymentResponse.ResultCodeEnum.ToJsonValue(paymentResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (paymentResponse._ThreeDS2ResponseDataOption.IsSet) + { + writer.WritePropertyName("threeDS2ResponseData"); + JsonSerializer.Serialize(writer, paymentResponse.ThreeDS2ResponseData, jsonSerializerOptions); + } + if (paymentResponse._ThreeDS2ResultOption.IsSet) + { + writer.WritePropertyName("threeDS2Result"); + JsonSerializer.Serialize(writer, paymentResponse.ThreeDS2Result, jsonSerializerOptions); + } + if (paymentResponse._ThreeDSPaymentDataOption.IsSet) + if (paymentResponse.ThreeDSPaymentData != null) + writer.WriteString("threeDSPaymentData", paymentResponse.ThreeDSPaymentData); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentResponseAction.cs b/Adyen/Checkout/Models/PaymentResponseAction.cs new file mode 100644 index 000000000..b8e88bf5e --- /dev/null +++ b/Adyen/Checkout/Models/PaymentResponseAction.cs @@ -0,0 +1,383 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Action to be taken for completing the payment.. + /// + public partial class PaymentResponseAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutAwaitAction checkoutAwaitAction) + { + CheckoutAwaitAction = checkoutAwaitAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutBankTransferAction checkoutBankTransferAction) + { + CheckoutBankTransferAction = checkoutBankTransferAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutDelegatedAuthenticationAction checkoutDelegatedAuthenticationAction) + { + CheckoutDelegatedAuthenticationAction = checkoutDelegatedAuthenticationAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutNativeRedirectAction checkoutNativeRedirectAction) + { + CheckoutNativeRedirectAction = checkoutNativeRedirectAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutQrCodeAction checkoutQrCodeAction) + { + CheckoutQrCodeAction = checkoutQrCodeAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutRedirectAction checkoutRedirectAction) + { + CheckoutRedirectAction = checkoutRedirectAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutSDKAction checkoutSDKAction) + { + CheckoutSDKAction = checkoutSDKAction; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutThreeDS2Action checkoutThreeDS2Action) + { + CheckoutThreeDS2Action = checkoutThreeDS2Action; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentResponseAction(CheckoutVoucherAction checkoutVoucherAction) + { + CheckoutVoucherAction = checkoutVoucherAction; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public CheckoutAwaitAction? CheckoutAwaitAction { get; set; } + + /// + /// .. + /// + public CheckoutBankTransferAction? CheckoutBankTransferAction { get; set; } + + /// + /// .. + /// + public CheckoutDelegatedAuthenticationAction? CheckoutDelegatedAuthenticationAction { get; set; } + + /// + /// .. + /// + public CheckoutNativeRedirectAction? CheckoutNativeRedirectAction { get; set; } + + /// + /// .. + /// + public CheckoutQrCodeAction? CheckoutQrCodeAction { get; set; } + + /// + /// .. + /// + public CheckoutRedirectAction? CheckoutRedirectAction { get; set; } + + /// + /// .. + /// + public CheckoutSDKAction? CheckoutSDKAction { get; set; } + + /// + /// .. + /// + public CheckoutThreeDS2Action? CheckoutThreeDS2Action { get; set; } + + /// + /// .. + /// + public CheckoutVoucherAction? CheckoutVoucherAction { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentResponseAction {\n"); + if (this.CheckoutAwaitAction != null) + sb.Append(CheckoutAwaitAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutBankTransferAction != null) + sb.Append(CheckoutBankTransferAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutDelegatedAuthenticationAction != null) + sb.Append(CheckoutDelegatedAuthenticationAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutNativeRedirectAction != null) + sb.Append(CheckoutNativeRedirectAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutQrCodeAction != null) + sb.Append(CheckoutQrCodeAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutRedirectAction != null) + sb.Append(CheckoutRedirectAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutSDKAction != null) + sb.Append(CheckoutSDKAction.ToString().Replace("\n", "\n ")); + if (this.CheckoutThreeDS2Action != null) + sb.Append(CheckoutThreeDS2Action.ToString().Replace("\n", "\n ")); + if (this.CheckoutVoucherAction != null) + sb.Append(CheckoutVoucherAction.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentResponseActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentResponseAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + CheckoutAwaitAction? checkoutAwaitAction = default; + CheckoutBankTransferAction? checkoutBankTransferAction = default; + CheckoutDelegatedAuthenticationAction? checkoutDelegatedAuthenticationAction = default; + CheckoutNativeRedirectAction? checkoutNativeRedirectAction = default; + CheckoutQrCodeAction? checkoutQrCodeAction = default; + CheckoutRedirectAction? checkoutRedirectAction = default; + CheckoutSDKAction? checkoutSDKAction = default; + CheckoutThreeDS2Action? checkoutThreeDS2Action = default; + CheckoutVoucherAction? checkoutVoucherAction = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderCheckoutAwaitAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutAwaitAction, jsonSerializerOptions, out checkoutAwaitAction); + + Utf8JsonReader utf8JsonReaderCheckoutBankTransferAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutBankTransferAction, jsonSerializerOptions, out checkoutBankTransferAction); + + Utf8JsonReader utf8JsonReaderCheckoutDelegatedAuthenticationAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutDelegatedAuthenticationAction, jsonSerializerOptions, out checkoutDelegatedAuthenticationAction); + + Utf8JsonReader utf8JsonReaderCheckoutNativeRedirectAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutNativeRedirectAction, jsonSerializerOptions, out checkoutNativeRedirectAction); + + Utf8JsonReader utf8JsonReaderCheckoutQrCodeAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutQrCodeAction, jsonSerializerOptions, out checkoutQrCodeAction); + + Utf8JsonReader utf8JsonReaderCheckoutRedirectAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutRedirectAction, jsonSerializerOptions, out checkoutRedirectAction); + + Utf8JsonReader utf8JsonReaderCheckoutSDKAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutSDKAction, jsonSerializerOptions, out checkoutSDKAction); + + Utf8JsonReader utf8JsonReaderCheckoutThreeDS2Action = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutThreeDS2Action, jsonSerializerOptions, out checkoutThreeDS2Action); + + Utf8JsonReader utf8JsonReaderCheckoutVoucherAction = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCheckoutVoucherAction, jsonSerializerOptions, out checkoutVoucherAction); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (checkoutAwaitAction?.Type != null) + return new PaymentResponseAction(checkoutAwaitAction); + + if (checkoutBankTransferAction?.Type != null) + return new PaymentResponseAction(checkoutBankTransferAction); + + if (checkoutDelegatedAuthenticationAction?.Type != null) + return new PaymentResponseAction(checkoutDelegatedAuthenticationAction); + + if (checkoutNativeRedirectAction?.Type != null) + return new PaymentResponseAction(checkoutNativeRedirectAction); + + if (checkoutQrCodeAction?.Type != null) + return new PaymentResponseAction(checkoutQrCodeAction); + + if (checkoutRedirectAction?.Type != null) + return new PaymentResponseAction(checkoutRedirectAction); + + if (checkoutSDKAction?.Type != null) + return new PaymentResponseAction(checkoutSDKAction); + + if (checkoutThreeDS2Action?.Type != null) + return new PaymentResponseAction(checkoutThreeDS2Action); + + if (checkoutVoucherAction?.Type != null) + return new PaymentResponseAction(checkoutVoucherAction); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentResponseAction paymentResponseAction, JsonSerializerOptions jsonSerializerOptions) + { + if (paymentResponseAction.CheckoutAwaitAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutAwaitAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutBankTransferAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutBankTransferAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutDelegatedAuthenticationAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutDelegatedAuthenticationAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutNativeRedirectAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutNativeRedirectAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutQrCodeAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutQrCodeAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutRedirectAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutRedirectAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutSDKAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutSDKAction, jsonSerializerOptions); + if (paymentResponseAction.CheckoutThreeDS2Action != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutThreeDS2Action, jsonSerializerOptions); + if (paymentResponseAction.CheckoutVoucherAction != null) + JsonSerializer.Serialize(writer, paymentResponseAction.CheckoutVoucherAction, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, paymentResponseAction, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentResponseAction paymentResponseAction, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Checkout/Models/PaymentReversalRequest.cs b/Adyen/Checkout/Models/PaymentReversalRequest.cs new file mode 100644 index 000000000..07299e043 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentReversalRequest.cs @@ -0,0 +1,246 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentReversalRequest. + /// + public partial class PaymentReversalRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// applicationInfo + /// enhancedSchemeData + /// Your reference for the reversal request. Maximum length: 80 characters. + [JsonConstructor] + public PaymentReversalRequest(string merchantAccount, Option applicationInfo = default, Option enhancedSchemeData = default, Option reference = default) + { + MerchantAccount = merchantAccount; + _ApplicationInfoOption = applicationInfo; + _EnhancedSchemeDataOption = enhancedSchemeData; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentReversalRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the reversal request. Maximum length: 80 characters. + /// + /// Your reference for the reversal request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentReversalRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentReversalRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentReversalRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option applicationInfo = default; + Option enhancedSchemeData = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentReversalRequest.", nameof(merchantAccount)); + + return new PaymentReversalRequest(merchantAccount.Value!, applicationInfo, enhancedSchemeData, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentReversalRequest paymentReversalRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentReversalRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentReversalRequest paymentReversalRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentReversalRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentReversalRequest.MerchantAccount); + + if (paymentReversalRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentReversalRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentReversalRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, paymentReversalRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (paymentReversalRequest._ReferenceOption.IsSet) + if (paymentReversalRequest.Reference != null) + writer.WriteString("reference", paymentReversalRequest.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentReversalResponse.cs b/Adyen/Checkout/Models/PaymentReversalResponse.cs new file mode 100644 index 000000000..eb2c24b9a --- /dev/null +++ b/Adyen/Checkout/Models/PaymentReversalResponse.cs @@ -0,0 +1,354 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentReversalResponse. + /// + public partial class PaymentReversalResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to reverse. + /// Adyen's 16-character reference associated with the reversal request. + /// The status of your request. This will always have the value **received**. + /// Your reference for the reversal request. + [JsonConstructor] + public PaymentReversalResponse(string merchantAccount, string paymentPspReference, string pspReference, StatusEnum status, Option reference = default) + { + MerchantAccount = merchantAccount; + PaymentPspReference = paymentPspReference; + PspReference = pspReference; + Status = status; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentReversalResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to reverse. + /// + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment to reverse. + [JsonPropertyName("paymentPspReference")] + public string PaymentPspReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the reversal request. + /// + /// Adyen's 16-character reference associated with the reversal request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the reversal request. + /// + /// Your reference for the reversal request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentReversalResponse {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentPspReference: ").Append(PaymentPspReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentReversalResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentReversalResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentPspReference = default; + Option pspReference = default; + Option status = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentPspReference": + paymentPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentReversalResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentReversalResponse.", nameof(merchantAccount)); + + if (!paymentPspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentReversalResponse.", nameof(paymentPspReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class PaymentReversalResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentReversalResponse.", nameof(status)); + + return new PaymentReversalResponse(merchantAccount.Value!, paymentPspReference.Value!, pspReference.Value!, status.Value!.Value!, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentReversalResponse paymentReversalResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentReversalResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentReversalResponse paymentReversalResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentReversalResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentReversalResponse.MerchantAccount); + + if (paymentReversalResponse.PaymentPspReference != null) + writer.WriteString("paymentPspReference", paymentReversalResponse.PaymentPspReference); + + if (paymentReversalResponse.PspReference != null) + writer.WriteString("pspReference", paymentReversalResponse.PspReference); + + if (paymentReversalResponse.Status != null) + { + string? statusRawValue = PaymentReversalResponse.StatusEnum.ToJsonValue(paymentReversalResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (paymentReversalResponse._ReferenceOption.IsSet) + if (paymentReversalResponse.Reference != null) + writer.WriteString("reference", paymentReversalResponse.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentValidationsNameResponse.cs b/Adyen/Checkout/Models/PaymentValidationsNameResponse.cs new file mode 100644 index 000000000..25ce43bb0 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentValidationsNameResponse.cs @@ -0,0 +1,342 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentValidationsNameResponse. + /// + public partial class PaymentValidationsNameResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// rawResponse + /// result + /// Name Validation status result + [JsonConstructor] + public PaymentValidationsNameResponse(Option rawResponse = default, Option result = default, Option status = default) + { + _RawResponseOption = rawResponse; + _ResultOption = result; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentValidationsNameResponse() + { + } + + partial void OnCreated(); + + /// + /// Name Validation status result + /// + /// Name Validation status result + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.NotPerformed - notPerformed + /// + public static readonly StatusEnum NotPerformed = new("notPerformed"); + + /// + /// StatusEnum.NotSupported - notSupported + /// + public static readonly StatusEnum NotSupported = new("notSupported"); + + /// + /// StatusEnum.Performed - performed + /// + public static readonly StatusEnum Performed = new("performed"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "notPerformed" => StatusEnum.NotPerformed, + "notSupported" => StatusEnum.NotSupported, + "performed" => StatusEnum.Performed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.NotPerformed) + return "notPerformed"; + + if (value == StatusEnum.NotSupported) + return "notSupported"; + + if (value == StatusEnum.Performed) + return "performed"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// Name Validation status result + /// + /// Name Validation status result + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RawResponseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("rawResponse")] + public PaymentValidationsNameResultRawResponse? RawResponse { get { return this._RawResponseOption; } set { this._RawResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("result")] + public PaymentValidationsNameResultResponse? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentValidationsNameResponse {\n"); + sb.Append(" RawResponse: ").Append(RawResponse).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentValidationsNameResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentValidationsNameResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option rawResponse = default; + Option result = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "rawResponse": + rawResponse = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "result": + result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentValidationsNameResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new PaymentValidationsNameResponse(rawResponse, result, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentValidationsNameResponse paymentValidationsNameResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentValidationsNameResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentValidationsNameResponse paymentValidationsNameResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentValidationsNameResponse._RawResponseOption.IsSet) + { + writer.WritePropertyName("rawResponse"); + JsonSerializer.Serialize(writer, paymentValidationsNameResponse.RawResponse, jsonSerializerOptions); + } + if (paymentValidationsNameResponse._ResultOption.IsSet) + { + writer.WritePropertyName("result"); + JsonSerializer.Serialize(writer, paymentValidationsNameResponse.Result, jsonSerializerOptions); + } + if (paymentValidationsNameResponse._StatusOption.IsSet && paymentValidationsNameResponse.Status != null) + { + string? statusRawValue = PaymentValidationsNameResponse.StatusEnum.ToJsonValue(paymentValidationsNameResponse._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaymentValidationsNameResultRawResponse.cs b/Adyen/Checkout/Models/PaymentValidationsNameResultRawResponse.cs new file mode 100644 index 000000000..bea1b6996 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentValidationsNameResultRawResponse.cs @@ -0,0 +1,277 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentValidationsNameResultRawResponse. + /// + public partial class PaymentValidationsNameResultRawResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name Validation Raw firstName Result + /// Name Validation Raw fullName Result + /// Name Validation Raw lastName Result + /// Name Validation Raw middleName Result + /// Name Validation Raw status result + [JsonConstructor] + public PaymentValidationsNameResultRawResponse(Option firstName = default, Option fullName = default, Option lastName = default, Option middleName = default, Option status = default) + { + _FirstNameOption = firstName; + _FullNameOption = fullName; + _LastNameOption = lastName; + _MiddleNameOption = middleName; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentValidationsNameResultRawResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// Name Validation Raw firstName Result + /// + /// Name Validation Raw firstName Result + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullNameOption { get; private set; } + + /// + /// Name Validation Raw fullName Result + /// + /// Name Validation Raw fullName Result + [JsonPropertyName("fullName")] + public string? FullName { get { return this._FullNameOption; } set { this._FullNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// Name Validation Raw lastName Result + /// + /// Name Validation Raw lastName Result + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MiddleNameOption { get; private set; } + + /// + /// Name Validation Raw middleName Result + /// + /// Name Validation Raw middleName Result + [JsonPropertyName("middleName")] + public string? MiddleName { get { return this._MiddleNameOption; } set { this._MiddleNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// Name Validation Raw status result + /// + /// Name Validation Raw status result + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentValidationsNameResultRawResponse {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" FullName: ").Append(FullName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentValidationsNameResultRawResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentValidationsNameResultRawResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option fullName = default; + Option lastName = default; + Option middleName = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "fullName": + fullName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "middleName": + middleName = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentValidationsNameResultRawResponse(firstName, fullName, lastName, middleName, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentValidationsNameResultRawResponse paymentValidationsNameResultRawResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentValidationsNameResultRawResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentValidationsNameResultRawResponse paymentValidationsNameResultRawResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentValidationsNameResultRawResponse._FirstNameOption.IsSet) + if (paymentValidationsNameResultRawResponse.FirstName != null) + writer.WriteString("firstName", paymentValidationsNameResultRawResponse.FirstName); + + if (paymentValidationsNameResultRawResponse._FullNameOption.IsSet) + if (paymentValidationsNameResultRawResponse.FullName != null) + writer.WriteString("fullName", paymentValidationsNameResultRawResponse.FullName); + + if (paymentValidationsNameResultRawResponse._LastNameOption.IsSet) + if (paymentValidationsNameResultRawResponse.LastName != null) + writer.WriteString("lastName", paymentValidationsNameResultRawResponse.LastName); + + if (paymentValidationsNameResultRawResponse._MiddleNameOption.IsSet) + if (paymentValidationsNameResultRawResponse.MiddleName != null) + writer.WriteString("middleName", paymentValidationsNameResultRawResponse.MiddleName); + + if (paymentValidationsNameResultRawResponse._StatusOption.IsSet) + if (paymentValidationsNameResultRawResponse.Status != null) + writer.WriteString("status", paymentValidationsNameResultRawResponse.Status); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentValidationsNameResultResponse.cs b/Adyen/Checkout/Models/PaymentValidationsNameResultResponse.cs new file mode 100644 index 000000000..5893fea4a --- /dev/null +++ b/Adyen/Checkout/Models/PaymentValidationsNameResultResponse.cs @@ -0,0 +1,252 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentValidationsNameResultResponse. + /// + public partial class PaymentValidationsNameResultResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name Validation firstName result + /// Name Validation fullName result + /// Name Validation lastName result + /// Name Validation middleName result + [JsonConstructor] + public PaymentValidationsNameResultResponse(Option firstName = default, Option fullName = default, Option lastName = default, Option middleName = default) + { + _FirstNameOption = firstName; + _FullNameOption = fullName; + _LastNameOption = lastName; + _MiddleNameOption = middleName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentValidationsNameResultResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// Name Validation firstName result + /// + /// Name Validation firstName result + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullNameOption { get; private set; } + + /// + /// Name Validation fullName result + /// + /// Name Validation fullName result + [JsonPropertyName("fullName")] + public string? FullName { get { return this._FullNameOption; } set { this._FullNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// Name Validation lastName result + /// + /// Name Validation lastName result + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MiddleNameOption { get; private set; } + + /// + /// Name Validation middleName result + /// + /// Name Validation middleName result + [JsonPropertyName("middleName")] + public string? MiddleName { get { return this._MiddleNameOption; } set { this._MiddleNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentValidationsNameResultResponse {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" FullName: ").Append(FullName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentValidationsNameResultResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentValidationsNameResultResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option fullName = default; + Option lastName = default; + Option middleName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "fullName": + fullName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "middleName": + middleName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentValidationsNameResultResponse(firstName, fullName, lastName, middleName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentValidationsNameResultResponse paymentValidationsNameResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentValidationsNameResultResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentValidationsNameResultResponse paymentValidationsNameResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentValidationsNameResultResponse._FirstNameOption.IsSet) + if (paymentValidationsNameResultResponse.FirstName != null) + writer.WriteString("firstName", paymentValidationsNameResultResponse.FirstName); + + if (paymentValidationsNameResultResponse._FullNameOption.IsSet) + if (paymentValidationsNameResultResponse.FullName != null) + writer.WriteString("fullName", paymentValidationsNameResultResponse.FullName); + + if (paymentValidationsNameResultResponse._LastNameOption.IsSet) + if (paymentValidationsNameResultResponse.LastName != null) + writer.WriteString("lastName", paymentValidationsNameResultResponse.LastName); + + if (paymentValidationsNameResultResponse._MiddleNameOption.IsSet) + if (paymentValidationsNameResultResponse.MiddleName != null) + writer.WriteString("middleName", paymentValidationsNameResultResponse.MiddleName); + } + } +} diff --git a/Adyen/Checkout/Models/PaymentValidationsResponse.cs b/Adyen/Checkout/Models/PaymentValidationsResponse.cs new file mode 100644 index 000000000..8305bd867 --- /dev/null +++ b/Adyen/Checkout/Models/PaymentValidationsResponse.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaymentValidationsResponse. + /// + public partial class PaymentValidationsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + [JsonConstructor] + public PaymentValidationsResponse(Option name = default) + { + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentValidationsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public PaymentValidationsNameResponse? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentValidationsResponse {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentValidationsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentValidationsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PaymentValidationsResponse(name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentValidationsResponse paymentValidationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentValidationsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentValidationsResponse paymentValidationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentValidationsResponse._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, paymentValidationsResponse.Name, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaypalUpdateOrderRequest.cs b/Adyen/Checkout/Models/PaypalUpdateOrderRequest.cs new file mode 100644 index 000000000..0dbedbeca --- /dev/null +++ b/Adyen/Checkout/Models/PaypalUpdateOrderRequest.cs @@ -0,0 +1,304 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaypalUpdateOrderRequest. + /// + public partial class PaypalUpdateOrderRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The list of new delivery methods and the cost of each. + /// The `paymentData` from the client side. This value changes every time you make a `/paypal/updateOrder` request. + /// The original `pspReference` from the `/payments` response. + /// The original `sessionId` from the `/sessions` response. + /// taxTotal + [JsonConstructor] + public PaypalUpdateOrderRequest(Option amount = default, Option?> deliveryMethods = default, Option paymentData = default, Option pspReference = default, Option sessionId = default, Option taxTotal = default) + { + _AmountOption = amount; + _DeliveryMethodsOption = deliveryMethods; + _PaymentDataOption = paymentData; + _PspReferenceOption = pspReference; + _SessionIdOption = sessionId; + _TaxTotalOption = taxTotal; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaypalUpdateOrderRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DeliveryMethodsOption { get; private set; } + + /// + /// The list of new delivery methods and the cost of each. + /// + /// The list of new delivery methods and the cost of each. + [JsonPropertyName("deliveryMethods")] + public List? DeliveryMethods { get { return this._DeliveryMethodsOption; } set { this._DeliveryMethodsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentDataOption { get; private set; } + + /// + /// The `paymentData` from the client side. This value changes every time you make a `/paypal/updateOrder` request. + /// + /// The `paymentData` from the client side. This value changes every time you make a `/paypal/updateOrder` request. + [JsonPropertyName("paymentData")] + public string? PaymentData { get { return this._PaymentDataOption; } set { this._PaymentDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The original `pspReference` from the `/payments` response. + /// + /// The original `pspReference` from the `/payments` response. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionIdOption { get; private set; } + + /// + /// The original `sessionId` from the `/sessions` response. + /// + /// The original `sessionId` from the `/sessions` response. + [JsonPropertyName("sessionId")] + public string? SessionId { get { return this._SessionIdOption; } set { this._SessionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxTotalOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("taxTotal")] + public TaxTotal? TaxTotal { get { return this._TaxTotalOption; } set { this._TaxTotalOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaypalUpdateOrderRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" DeliveryMethods: ").Append(DeliveryMethods).Append("\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" SessionId: ").Append(SessionId).Append("\n"); + sb.Append(" TaxTotal: ").Append(TaxTotal).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaypalUpdateOrderRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaypalUpdateOrderRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option?> deliveryMethods = default; + Option paymentData = default; + Option pspReference = default; + Option sessionId = default; + Option taxTotal = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryMethods": + deliveryMethods = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "sessionId": + sessionId = new Option(utf8JsonReader.GetString()!); + break; + case "taxTotal": + taxTotal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PaypalUpdateOrderRequest(amount, deliveryMethods, paymentData, pspReference, sessionId, taxTotal); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaypalUpdateOrderRequest paypalUpdateOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paypalUpdateOrderRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaypalUpdateOrderRequest paypalUpdateOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (paypalUpdateOrderRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paypalUpdateOrderRequest.Amount, jsonSerializerOptions); + } + if (paypalUpdateOrderRequest._DeliveryMethodsOption.IsSet) + { + writer.WritePropertyName("deliveryMethods"); + JsonSerializer.Serialize(writer, paypalUpdateOrderRequest.DeliveryMethods, jsonSerializerOptions); + } + if (paypalUpdateOrderRequest._PaymentDataOption.IsSet) + if (paypalUpdateOrderRequest.PaymentData != null) + writer.WriteString("paymentData", paypalUpdateOrderRequest.PaymentData); + + if (paypalUpdateOrderRequest._PspReferenceOption.IsSet) + if (paypalUpdateOrderRequest.PspReference != null) + writer.WriteString("pspReference", paypalUpdateOrderRequest.PspReference); + + if (paypalUpdateOrderRequest._SessionIdOption.IsSet) + if (paypalUpdateOrderRequest.SessionId != null) + writer.WriteString("sessionId", paypalUpdateOrderRequest.SessionId); + + if (paypalUpdateOrderRequest._TaxTotalOption.IsSet) + { + writer.WritePropertyName("taxTotal"); + JsonSerializer.Serialize(writer, paypalUpdateOrderRequest.TaxTotal, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/PaypalUpdateOrderResponse.cs b/Adyen/Checkout/Models/PaypalUpdateOrderResponse.cs new file mode 100644 index 000000000..c99e04d41 --- /dev/null +++ b/Adyen/Checkout/Models/PaypalUpdateOrderResponse.cs @@ -0,0 +1,298 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PaypalUpdateOrderResponse. + /// + public partial class PaypalUpdateOrderResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The updated paymentData. + /// The status of the request. This indicates whether the order was successfully updated with PayPal. + [JsonConstructor] + public PaypalUpdateOrderResponse(string paymentData, StatusEnum status) + { + PaymentData = paymentData; + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaypalUpdateOrderResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of the request. This indicates whether the order was successfully updated with PayPal. + /// + /// The status of the request. This indicates whether the order was successfully updated with PayPal. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Success - success + /// + public static readonly StatusEnum Success = new("success"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "error" => StatusEnum.Error, + "success" => StatusEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Success) + return "success"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the request. This indicates whether the order was successfully updated with PayPal. + /// + /// The status of the request. This indicates whether the order was successfully updated with PayPal. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The updated paymentData. + /// + /// The updated paymentData. + [JsonPropertyName("paymentData")] + public string PaymentData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaypalUpdateOrderResponse {\n"); + sb.Append(" PaymentData: ").Append(PaymentData).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaypalUpdateOrderResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaypalUpdateOrderResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option paymentData = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "paymentData": + paymentData = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaypalUpdateOrderResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!paymentData.IsSet) + throw new ArgumentException("Property is required for class PaypalUpdateOrderResponse.", nameof(paymentData)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaypalUpdateOrderResponse.", nameof(status)); + + return new PaypalUpdateOrderResponse(paymentData.Value!, status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaypalUpdateOrderResponse paypalUpdateOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paypalUpdateOrderResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaypalUpdateOrderResponse paypalUpdateOrderResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paypalUpdateOrderResponse.PaymentData != null) + writer.WriteString("paymentData", paypalUpdateOrderResponse.PaymentData); + + if (paypalUpdateOrderResponse.Status != null) + { + string? statusRawValue = PaypalUpdateOrderResponse.StatusEnum.ToJsonValue(paypalUpdateOrderResponse.Status); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Phone.cs b/Adyen/Checkout/Models/Phone.cs new file mode 100644 index 000000000..e9254006c --- /dev/null +++ b/Adyen/Checkout/Models/Phone.cs @@ -0,0 +1,220 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Phone. + /// + public partial class Phone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Country code. Length: 1–3 digits. + /// Subscriber number. Length: 4-15 digits. + [JsonConstructor] + public Phone(Option cc = default, Option subscriber = default) + { + _CcOption = cc; + _SubscriberOption = subscriber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Phone() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CcOption { get; private set; } + + /// + /// Country code. Length: 1–3 digits. + /// + /// Country code. Length: 1–3 digits. + [JsonPropertyName("cc")] + public string? Cc { get { return this._CcOption; } set { this._CcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubscriberOption { get; private set; } + + /// + /// Subscriber number. Length: 4-15 digits. + /// + /// Subscriber number. Length: 4-15 digits. + [JsonPropertyName("subscriber")] + public string? Subscriber { get { return this._SubscriberOption; } set { this._SubscriberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Phone {\n"); + sb.Append(" Cc: ").Append(Cc).Append("\n"); + sb.Append(" Subscriber: ").Append(Subscriber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Cc (string) maxLength + if (this.Cc != null && this.Cc.Length > 3) + { + yield return new ValidationResult("Invalid value for Cc, length must be less than 3.", new [] { "Cc" }); + } + + // Cc (string) minLength + if (this.Cc != null && this.Cc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cc, length must be greater than 1.", new [] { "Cc" }); + } + + // Subscriber (string) maxLength + if (this.Subscriber != null && this.Subscriber.Length > 15) + { + yield return new ValidationResult("Invalid value for Subscriber, length must be less than 15.", new [] { "Subscriber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Phone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cc = default; + Option subscriber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cc": + cc = new Option(utf8JsonReader.GetString()!); + break; + case "subscriber": + subscriber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Phone(cc, subscriber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + if (phone._CcOption.IsSet) + if (phone.Cc != null) + writer.WriteString("cc", phone.Cc); + + if (phone._SubscriberOption.IsSet) + if (phone.Subscriber != null) + writer.WriteString("subscriber", phone.Subscriber); + } + } +} diff --git a/Adyen/Checkout/Models/PixDetails.cs b/Adyen/Checkout/Models/PixDetails.cs new file mode 100644 index 000000000..bd8007ebd --- /dev/null +++ b/Adyen/Checkout/Models/PixDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PixDetails. + /// + public partial class PixDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// pixRecurring + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The payment method type. + [JsonConstructor] + public PixDetails(Option checkoutAttemptId = default, Option pixRecurring = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _PixRecurringOption = pixRecurring; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PixDetails() + { + } + + partial void OnCreated(); + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Pix - pix + /// + public static readonly TypeEnum Pix = new("pix"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pix" => TypeEnum.Pix, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Pix) + return "pix"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PixRecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pixRecurring")] + public PixRecurring? PixRecurring { get { return this._PixRecurringOption; } set { this._PixRecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PixDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" PixRecurring: ").Append(PixRecurring).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PixDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PixDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option pixRecurring = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "pixRecurring": + pixRecurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PixDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PixDetails(checkoutAttemptId, pixRecurring, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PixDetails pixDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pixDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PixDetails pixDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (pixDetails._CheckoutAttemptIdOption.IsSet) + if (pixDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", pixDetails.CheckoutAttemptId); + + if (pixDetails._PixRecurringOption.IsSet) + { + writer.WritePropertyName("pixRecurring"); + JsonSerializer.Serialize(writer, pixDetails.PixRecurring, jsonSerializerOptions); + } + if (pixDetails._RecurringDetailReferenceOption.IsSet) + if (pixDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", pixDetails.RecurringDetailReference); + + if (pixDetails._StoredPaymentMethodIdOption.IsSet) + if (pixDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", pixDetails.StoredPaymentMethodId); + + if (pixDetails._TypeOption.IsSet && pixDetails.Type != null) + { + string? typeRawValue = PixDetails.TypeEnum.ToJsonValue(pixDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/PixRecurring.cs b/Adyen/Checkout/Models/PixRecurring.cs new file mode 100644 index 000000000..f74885d0d --- /dev/null +++ b/Adyen/Checkout/Models/PixRecurring.cs @@ -0,0 +1,533 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PixRecurring. + /// + public partial class PixRecurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date on which the shopper's payment method will be charged, in YYYY-MM-DD format. + /// Flag used to define whether liquidation can happen only on business days + /// End date of the billing plan, in YYYY-MM-DD format. The end date must align with the frequency and the start date of the billing plan. If left blank, the subscription will continue indefinitely unless it is cancelled by the shopper. + /// The frequency at which the shopper will be charged. + /// minAmount + /// The pspReference for the failed recurring payment. Find this in AUTHORISATION webhook you received after the billing date. + /// recurringAmount + /// The text that that will be shown on the shopper's bank statement for the recurring payments. We recommend to add a descriptive text about the subscription to let your shoppers recognize your recurring payments. Maximum length: 35 characters. + /// When set to true, you can retry for failed recurring payments. The default value is true. + /// Start date of the billing plan, in YYYY-MM-DD format. The default value is the transaction date. + [JsonConstructor] + public PixRecurring(Option billingDate = default, Option businessDayOnly = default, Option endsAt = default, Option frequency = default, Option minAmount = default, Option originalPspReference = default, Option recurringAmount = default, Option recurringStatement = default, Option retryPolicy = default, Option startsAt = default) + { + _BillingDateOption = billingDate; + _BusinessDayOnlyOption = businessDayOnly; + _EndsAtOption = endsAt; + _FrequencyOption = frequency; + _MinAmountOption = minAmount; + _OriginalPspReferenceOption = originalPspReference; + _RecurringAmountOption = recurringAmount; + _RecurringStatementOption = recurringStatement; + _RetryPolicyOption = retryPolicy; + _StartsAtOption = startsAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PixRecurring() + { + } + + partial void OnCreated(); + + /// + /// The frequency at which the shopper will be charged. + /// + /// The frequency at which the shopper will be charged. + [JsonConverter(typeof(FrequencyEnumJsonConverter))] + public class FrequencyEnum : IEnum + { + /// + /// Returns the value of the FrequencyEnum. + /// + public string? Value { get; set; } + + /// + /// FrequencyEnum.Weekly - weekly + /// + public static readonly FrequencyEnum Weekly = new("weekly"); + + /// + /// FrequencyEnum.Monthly - monthly + /// + public static readonly FrequencyEnum Monthly = new("monthly"); + + /// + /// FrequencyEnum.Quarterly - quarterly + /// + public static readonly FrequencyEnum Quarterly = new("quarterly"); + + /// + /// FrequencyEnum.HalfYearly - half-yearly + /// + public static readonly FrequencyEnum HalfYearly = new("half-yearly"); + + /// + /// FrequencyEnum.Yearly - yearly + /// + public static readonly FrequencyEnum Yearly = new("yearly"); + + private FrequencyEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FrequencyEnum?(string? value) => value == null ? null : new FrequencyEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FrequencyEnum? option) => option?.Value; + + public static bool operator ==(FrequencyEnum? left, FrequencyEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FrequencyEnum? left, FrequencyEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FrequencyEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FrequencyEnum? FromStringOrDefault(string value) + { + return value switch { + "weekly" => FrequencyEnum.Weekly, + "monthly" => FrequencyEnum.Monthly, + "quarterly" => FrequencyEnum.Quarterly, + "half-yearly" => FrequencyEnum.HalfYearly, + "yearly" => FrequencyEnum.Yearly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FrequencyEnum? value) + { + if (value == null) + return null; + + if (value == FrequencyEnum.Weekly) + return "weekly"; + + if (value == FrequencyEnum.Monthly) + return "monthly"; + + if (value == FrequencyEnum.Quarterly) + return "quarterly"; + + if (value == FrequencyEnum.HalfYearly) + return "half-yearly"; + + if (value == FrequencyEnum.Yearly) + return "yearly"; + + return null; + } + + /// + /// JsonConverter for writing FrequencyEnum. + /// + public class FrequencyEnumJsonConverter : JsonConverter + { + public override FrequencyEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FrequencyEnum.FromStringOrDefault(value) ?? new FrequencyEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FrequencyEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FrequencyEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FrequencyOption { get; private set; } + + /// + /// The frequency at which the shopper will be charged. + /// + /// The frequency at which the shopper will be charged. + [JsonPropertyName("frequency")] + public FrequencyEnum? Frequency { get { return this._FrequencyOption; } set { this._FrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingDateOption { get; private set; } + + /// + /// The date on which the shopper's payment method will be charged, in YYYY-MM-DD format. + /// + /// The date on which the shopper's payment method will be charged, in YYYY-MM-DD format. + [JsonPropertyName("billingDate")] + public string? BillingDate { get { return this._BillingDateOption; } set { this._BillingDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessDayOnlyOption { get; private set; } + + /// + /// Flag used to define whether liquidation can happen only on business days + /// + /// Flag used to define whether liquidation can happen only on business days + [JsonPropertyName("businessDayOnly")] + public bool? BusinessDayOnly { get { return this._BusinessDayOnlyOption; } set { this._BusinessDayOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EndsAtOption { get; private set; } + + /// + /// End date of the billing plan, in YYYY-MM-DD format. The end date must align with the frequency and the start date of the billing plan. If left blank, the subscription will continue indefinitely unless it is cancelled by the shopper. + /// + /// End date of the billing plan, in YYYY-MM-DD format. The end date must align with the frequency and the start date of the billing plan. If left blank, the subscription will continue indefinitely unless it is cancelled by the shopper. + [JsonPropertyName("endsAt")] + public string? EndsAt { get { return this._EndsAtOption; } set { this._EndsAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MinAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("minAmount")] + public Amount? MinAmount { get { return this._MinAmountOption; } set { this._MinAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalPspReferenceOption { get; private set; } + + /// + /// The pspReference for the failed recurring payment. Find this in AUTHORISATION webhook you received after the billing date. + /// + /// The pspReference for the failed recurring payment. Find this in AUTHORISATION webhook you received after the billing date. + [JsonPropertyName("originalPspReference")] + public string? OriginalPspReference { get { return this._OriginalPspReferenceOption; } set { this._OriginalPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringAmount")] + public Amount? RecurringAmount { get { return this._RecurringAmountOption; } set { this._RecurringAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringStatementOption { get; private set; } + + /// + /// The text that that will be shown on the shopper's bank statement for the recurring payments. We recommend to add a descriptive text about the subscription to let your shoppers recognize your recurring payments. Maximum length: 35 characters. + /// + /// The text that that will be shown on the shopper's bank statement for the recurring payments. We recommend to add a descriptive text about the subscription to let your shoppers recognize your recurring payments. Maximum length: 35 characters. + [JsonPropertyName("recurringStatement")] + public string? RecurringStatement { get { return this._RecurringStatementOption; } set { this._RecurringStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetryPolicyOption { get; private set; } + + /// + /// When set to true, you can retry for failed recurring payments. The default value is true. + /// + /// When set to true, you can retry for failed recurring payments. The default value is true. + [JsonPropertyName("retryPolicy")] + public bool? RetryPolicy { get { return this._RetryPolicyOption; } set { this._RetryPolicyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartsAtOption { get; private set; } + + /// + /// Start date of the billing plan, in YYYY-MM-DD format. The default value is the transaction date. + /// + /// Start date of the billing plan, in YYYY-MM-DD format. The default value is the transaction date. + [JsonPropertyName("startsAt")] + public string? StartsAt { get { return this._StartsAtOption; } set { this._StartsAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PixRecurring {\n"); + sb.Append(" BillingDate: ").Append(BillingDate).Append("\n"); + sb.Append(" BusinessDayOnly: ").Append(BusinessDayOnly).Append("\n"); + sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); + sb.Append(" Frequency: ").Append(Frequency).Append("\n"); + sb.Append(" MinAmount: ").Append(MinAmount).Append("\n"); + sb.Append(" OriginalPspReference: ").Append(OriginalPspReference).Append("\n"); + sb.Append(" RecurringAmount: ").Append(RecurringAmount).Append("\n"); + sb.Append(" RecurringStatement: ").Append(RecurringStatement).Append("\n"); + sb.Append(" RetryPolicy: ").Append(RetryPolicy).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PixRecurringJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PixRecurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingDate = default; + Option businessDayOnly = default; + Option endsAt = default; + Option frequency = default; + Option minAmount = default; + Option originalPspReference = default; + Option recurringAmount = default; + Option recurringStatement = default; + Option retryPolicy = default; + Option startsAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingDate": + billingDate = new Option(utf8JsonReader.GetString()!); + break; + case "businessDayOnly": + businessDayOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "endsAt": + endsAt = new Option(utf8JsonReader.GetString()!); + break; + case "frequency": + string? frequencyRawValue = utf8JsonReader.GetString(); + frequency = new Option(PixRecurring.FrequencyEnum.FromStringOrDefault(frequencyRawValue)); + break; + case "minAmount": + minAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalPspReference": + originalPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringAmount": + recurringAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringStatement": + recurringStatement = new Option(utf8JsonReader.GetString()!); + break; + case "retryPolicy": + retryPolicy = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "startsAt": + startsAt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PixRecurring(billingDate, businessDayOnly, endsAt, frequency, minAmount, originalPspReference, recurringAmount, recurringStatement, retryPolicy, startsAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PixRecurring pixRecurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pixRecurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PixRecurring pixRecurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (pixRecurring._BillingDateOption.IsSet) + if (pixRecurring.BillingDate != null) + writer.WriteString("billingDate", pixRecurring.BillingDate); + + if (pixRecurring._BusinessDayOnlyOption.IsSet) + writer.WriteBoolean("businessDayOnly", pixRecurring._BusinessDayOnlyOption.Value!.Value); + + if (pixRecurring._EndsAtOption.IsSet) + if (pixRecurring.EndsAt != null) + writer.WriteString("endsAt", pixRecurring.EndsAt); + + if (pixRecurring._FrequencyOption.IsSet && pixRecurring.Frequency != null) + { + string? frequencyRawValue = PixRecurring.FrequencyEnum.ToJsonValue(pixRecurring._FrequencyOption.Value!.Value); + writer.WriteString("frequency", frequencyRawValue); + } + + if (pixRecurring._MinAmountOption.IsSet) + { + writer.WritePropertyName("minAmount"); + JsonSerializer.Serialize(writer, pixRecurring.MinAmount, jsonSerializerOptions); + } + if (pixRecurring._OriginalPspReferenceOption.IsSet) + if (pixRecurring.OriginalPspReference != null) + writer.WriteString("originalPspReference", pixRecurring.OriginalPspReference); + + if (pixRecurring._RecurringAmountOption.IsSet) + { + writer.WritePropertyName("recurringAmount"); + JsonSerializer.Serialize(writer, pixRecurring.RecurringAmount, jsonSerializerOptions); + } + if (pixRecurring._RecurringStatementOption.IsSet) + if (pixRecurring.RecurringStatement != null) + writer.WriteString("recurringStatement", pixRecurring.RecurringStatement); + + if (pixRecurring._RetryPolicyOption.IsSet) + writer.WriteBoolean("retryPolicy", pixRecurring._RetryPolicyOption.Value!.Value); + + if (pixRecurring._StartsAtOption.IsSet) + if (pixRecurring.StartsAt != null) + writer.WriteString("startsAt", pixRecurring.StartsAt); + } + } +} diff --git a/Adyen/Checkout/Models/PlatformChargebackLogic.cs b/Adyen/Checkout/Models/PlatformChargebackLogic.cs new file mode 100644 index 000000000..96cb63e7e --- /dev/null +++ b/Adyen/Checkout/Models/PlatformChargebackLogic.cs @@ -0,0 +1,342 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PlatformChargebackLogic. + /// + public partial class PlatformChargebackLogic : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + [JsonConstructor] + public PlatformChargebackLogic(Option behavior = default, Option costAllocationAccount = default, Option targetAccount = default) + { + _BehaviorOption = behavior; + _CostAllocationAccountOption = costAllocationAccount; + _TargetAccountOption = targetAccount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformChargebackLogic() + { + } + + partial void OnCreated(); + + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonConverter(typeof(BehaviorEnumJsonConverter))] + public class BehaviorEnum : IEnum + { + /// + /// Returns the value of the BehaviorEnum. + /// + public string? Value { get; set; } + + /// + /// BehaviorEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly BehaviorEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + /// + /// BehaviorEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly BehaviorEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// BehaviorEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly BehaviorEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private BehaviorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BehaviorEnum?(string? value) => value == null ? null : new BehaviorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BehaviorEnum? option) => option?.Value; + + public static bool operator ==(BehaviorEnum? left, BehaviorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BehaviorEnum? left, BehaviorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BehaviorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BehaviorEnum? FromStringOrDefault(string value) + { + return value switch { + "deductAccordingToSplitRatio" => BehaviorEnum.DeductAccordingToSplitRatio, + "deductFromLiableAccount" => BehaviorEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => BehaviorEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BehaviorEnum? value) + { + if (value == null) + return null; + + if (value == BehaviorEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + if (value == BehaviorEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == BehaviorEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing BehaviorEnum. + /// + public class BehaviorEnumJsonConverter : JsonConverter + { + public override BehaviorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BehaviorEnum.FromStringOrDefault(value) ?? new BehaviorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BehaviorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BehaviorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BehaviorOption { get; private set; } + + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonPropertyName("behavior")] + public BehaviorEnum? Behavior { get { return this._BehaviorOption; } set { this._BehaviorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CostAllocationAccountOption { get; private set; } + + /// + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + /// + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + [JsonPropertyName("costAllocationAccount")] + public string? CostAllocationAccount { get { return this._CostAllocationAccountOption; } set { this._CostAllocationAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAccountOption { get; private set; } + + /// + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + /// + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + [JsonPropertyName("targetAccount")] + public string? TargetAccount { get { return this._TargetAccountOption; } set { this._TargetAccountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformChargebackLogic {\n"); + sb.Append(" Behavior: ").Append(Behavior).Append("\n"); + sb.Append(" CostAllocationAccount: ").Append(CostAllocationAccount).Append("\n"); + sb.Append(" TargetAccount: ").Append(TargetAccount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformChargebackLogicJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformChargebackLogic Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option behavior = default; + Option costAllocationAccount = default; + Option targetAccount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "behavior": + string? behaviorRawValue = utf8JsonReader.GetString(); + behavior = new Option(PlatformChargebackLogic.BehaviorEnum.FromStringOrDefault(behaviorRawValue)); + break; + case "costAllocationAccount": + costAllocationAccount = new Option(utf8JsonReader.GetString()!); + break; + case "targetAccount": + targetAccount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PlatformChargebackLogic(behavior, costAllocationAccount, targetAccount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformChargebackLogic platformChargebackLogic, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformChargebackLogic, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformChargebackLogic platformChargebackLogic, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformChargebackLogic._BehaviorOption.IsSet && platformChargebackLogic.Behavior != null) + { + string? behaviorRawValue = PlatformChargebackLogic.BehaviorEnum.ToJsonValue(platformChargebackLogic._BehaviorOption.Value!.Value); + writer.WriteString("behavior", behaviorRawValue); + } + + if (platformChargebackLogic._CostAllocationAccountOption.IsSet) + if (platformChargebackLogic.CostAllocationAccount != null) + writer.WriteString("costAllocationAccount", platformChargebackLogic.CostAllocationAccount); + + if (platformChargebackLogic._TargetAccountOption.IsSet) + if (platformChargebackLogic.TargetAccount != null) + writer.WriteString("targetAccount", platformChargebackLogic.TargetAccount); + } + } +} diff --git a/Adyen/Checkout/Models/PseDetails.cs b/Adyen/Checkout/Models/PseDetails.cs new file mode 100644 index 000000000..235b4a1c2 --- /dev/null +++ b/Adyen/Checkout/Models/PseDetails.cs @@ -0,0 +1,378 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// PseDetails. + /// + public partial class PseDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The shopper's bank. + /// The client type. + /// The identification code. + /// The identification type. + /// The checkout attempt identifier. + /// The payment method type. + [JsonConstructor] + public PseDetails(string bank, string clientType, string identification, string identificationType, Option checkoutAttemptId = default, Option type = default) + { + Bank = bank; + ClientType = clientType; + Identification = identification; + IdentificationType = identificationType; + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PseDetails() + { + } + + partial void OnCreated(); + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PsePayulatam - pse_payulatam + /// + public static readonly TypeEnum PsePayulatam = new("pse_payulatam"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pse_payulatam" => TypeEnum.PsePayulatam, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PsePayulatam) + return "pse_payulatam"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The shopper's bank. + /// + /// The shopper's bank. + [JsonPropertyName("bank")] + public string Bank { get; set; } + + /// + /// The client type. + /// + /// The client type. + [JsonPropertyName("clientType")] + public string ClientType { get; set; } + + /// + /// The identification code. + /// + /// The identification code. + [JsonPropertyName("identification")] + public string Identification { get; set; } + + /// + /// The identification type. + /// + /// The identification type. + [JsonPropertyName("identificationType")] + public string IdentificationType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PseDetails {\n"); + sb.Append(" Bank: ").Append(Bank).Append("\n"); + sb.Append(" ClientType: ").Append(ClientType).Append("\n"); + sb.Append(" Identification: ").Append(Identification).Append("\n"); + sb.Append(" IdentificationType: ").Append(IdentificationType).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PseDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PseDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bank = default; + Option clientType = default; + Option identification = default; + Option identificationType = default; + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bank": + bank = new Option(utf8JsonReader.GetString()!); + break; + case "clientType": + clientType = new Option(utf8JsonReader.GetString()!); + break; + case "identification": + identification = new Option(utf8JsonReader.GetString()!); + break; + case "identificationType": + identificationType = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PseDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!bank.IsSet) + throw new ArgumentException("Property is required for class PseDetails.", nameof(bank)); + + if (!clientType.IsSet) + throw new ArgumentException("Property is required for class PseDetails.", nameof(clientType)); + + if (!identification.IsSet) + throw new ArgumentException("Property is required for class PseDetails.", nameof(identification)); + + if (!identificationType.IsSet) + throw new ArgumentException("Property is required for class PseDetails.", nameof(identificationType)); + + return new PseDetails(bank.Value!, clientType.Value!, identification.Value!, identificationType.Value!, checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PseDetails pseDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pseDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PseDetails pseDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (pseDetails.Bank != null) + writer.WriteString("bank", pseDetails.Bank); + + if (pseDetails.ClientType != null) + writer.WriteString("clientType", pseDetails.ClientType); + + if (pseDetails.Identification != null) + writer.WriteString("identification", pseDetails.Identification); + + if (pseDetails.IdentificationType != null) + writer.WriteString("identificationType", pseDetails.IdentificationType); + + if (pseDetails._CheckoutAttemptIdOption.IsSet) + if (pseDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", pseDetails.CheckoutAttemptId); + + if (pseDetails._TypeOption.IsSet && pseDetails.Type != null) + { + string? typeRawValue = PseDetails.TypeEnum.ToJsonValue(pseDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/RakutenPayDetails.cs b/Adyen/Checkout/Models/RakutenPayDetails.cs new file mode 100644 index 000000000..a73ccc642 --- /dev/null +++ b/Adyen/Checkout/Models/RakutenPayDetails.cs @@ -0,0 +1,356 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// RakutenPayDetails. + /// + public partial class RakutenPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **rakutenpay** (default to TypeEnum.Rakutenpay) + [JsonConstructor] + public RakutenPayDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RakutenPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **rakutenpay** + /// + /// **rakutenpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Rakutenpay - rakutenpay + /// + public static readonly TypeEnum Rakutenpay = new("rakutenpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "rakutenpay" => TypeEnum.Rakutenpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Rakutenpay) + return "rakutenpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **rakutenpay** + /// + /// **rakutenpay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RakutenPayDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RakutenPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RakutenPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(RakutenPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new RakutenPayDetails(checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RakutenPayDetails rakutenPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, rakutenPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RakutenPayDetails rakutenPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (rakutenPayDetails._CheckoutAttemptIdOption.IsSet) + if (rakutenPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", rakutenPayDetails.CheckoutAttemptId); + + if (rakutenPayDetails._RecurringDetailReferenceOption.IsSet) + if (rakutenPayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", rakutenPayDetails.RecurringDetailReference); + + if (rakutenPayDetails._StoredPaymentMethodIdOption.IsSet) + if (rakutenPayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", rakutenPayDetails.StoredPaymentMethodId); + + if (rakutenPayDetails._TypeOption.IsSet && rakutenPayDetails.Type != null) + { + string? typeRawValue = RakutenPayDetails.TypeEnum.ToJsonValue(rakutenPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/RatepayDetails.cs b/Adyen/Checkout/Models/RatepayDetails.cs new file mode 100644 index 000000000..d598be4da --- /dev/null +++ b/Adyen/Checkout/Models/RatepayDetails.cs @@ -0,0 +1,435 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// RatepayDetails. + /// + public partial class RatepayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address where to send the invoice. + /// The checkout attempt identifier. + /// The address where the goods should be delivered. + /// Shopper name, date of birth, phone number, and email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **ratepay** (default to TypeEnum.Ratepay) + [JsonConstructor] + public RatepayDetails(Option billingAddress = default, Option checkoutAttemptId = default, Option deliveryAddress = default, Option personalDetails = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + _BillingAddressOption = billingAddress; + _CheckoutAttemptIdOption = checkoutAttemptId; + _DeliveryAddressOption = deliveryAddress; + _PersonalDetailsOption = personalDetails; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RatepayDetails() + { + } + + partial void OnCreated(); + + /// + /// **ratepay** + /// + /// **ratepay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Ratepay - ratepay + /// + public static readonly TypeEnum Ratepay = new("ratepay"); + + /// + /// TypeEnum.RatepayDirectdebit - ratepay_directdebit + /// + public static readonly TypeEnum RatepayDirectdebit = new("ratepay_directdebit"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ratepay" => TypeEnum.Ratepay, + "ratepay_directdebit" => TypeEnum.RatepayDirectdebit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Ratepay) + return "ratepay"; + + if (value == TypeEnum.RatepayDirectdebit) + return "ratepay_directdebit"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ratepay** + /// + /// **ratepay** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// The address where to send the invoice. + /// + /// The address where to send the invoice. + [JsonPropertyName("billingAddress")] + public string? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// The address where the goods should be delivered. + /// + /// The address where the goods should be delivered. + [JsonPropertyName("deliveryAddress")] + public string? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PersonalDetailsOption { get; private set; } + + /// + /// Shopper name, date of birth, phone number, and email address. + /// + /// Shopper name, date of birth, phone number, and email address. + [JsonPropertyName("personalDetails")] + public string? PersonalDetails { get { return this._PersonalDetailsOption; } set { this._PersonalDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RatepayDetails {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RatepayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RatepayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option checkoutAttemptId = default; + Option deliveryAddress = default; + Option personalDetails = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryAddress": + deliveryAddress = new Option(utf8JsonReader.GetString()!); + break; + case "personalDetails": + personalDetails = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(RatepayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RatepayDetails.", nameof(type)); + + return new RatepayDetails(billingAddress, checkoutAttemptId, deliveryAddress, personalDetails, recurringDetailReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RatepayDetails ratepayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ratepayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RatepayDetails ratepayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (ratepayDetails._BillingAddressOption.IsSet) + if (ratepayDetails.BillingAddress != null) + writer.WriteString("billingAddress", ratepayDetails.BillingAddress); + + if (ratepayDetails._CheckoutAttemptIdOption.IsSet) + if (ratepayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", ratepayDetails.CheckoutAttemptId); + + if (ratepayDetails._DeliveryAddressOption.IsSet) + if (ratepayDetails.DeliveryAddress != null) + writer.WriteString("deliveryAddress", ratepayDetails.DeliveryAddress); + + if (ratepayDetails._PersonalDetailsOption.IsSet) + if (ratepayDetails.PersonalDetails != null) + writer.WriteString("personalDetails", ratepayDetails.PersonalDetails); + + if (ratepayDetails._RecurringDetailReferenceOption.IsSet) + if (ratepayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", ratepayDetails.RecurringDetailReference); + + if (ratepayDetails._StoredPaymentMethodIdOption.IsSet) + if (ratepayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", ratepayDetails.StoredPaymentMethodId); + + if (ratepayDetails.Type != null) + { + string? typeRawValue = RatepayDetails.TypeEnum.ToJsonValue(ratepayDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/Recurring.cs b/Adyen/Checkout/Models/Recurring.cs new file mode 100644 index 000000000..9ba8a2635 --- /dev/null +++ b/Adyen/Checkout/Models/Recurring.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Recurring. + /// + public partial class Recurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// A descriptive name for this detail. + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// The name of the token service. + [JsonConstructor] + public Recurring(Option contract = default, Option recurringDetailName = default, Option recurringExpiry = default, Option recurringFrequency = default, Option tokenService = default) + { + _ContractOption = contract; + _RecurringDetailNameOption = recurringDetailName; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _TokenServiceOption = tokenService; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Recurring() + { + } + + partial void OnCreated(); + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonConverter(typeof(ContractEnumJsonConverter))] + public class ContractEnum : IEnum + { + /// + /// Returns the value of the ContractEnum. + /// + public string? Value { get; set; } + + /// + /// ContractEnum.ONECLICK - ONECLICK + /// + public static readonly ContractEnum ONECLICK = new("ONECLICK"); + + /// + /// ContractEnum.ONECLICKRECURRING - ONECLICK,RECURRING + /// + public static readonly ContractEnum ONECLICKRECURRING = new("ONECLICK,RECURRING"); + + /// + /// ContractEnum.RECURRING - RECURRING + /// + public static readonly ContractEnum RECURRING = new("RECURRING"); + + /// + /// ContractEnum.PAYOUT - PAYOUT + /// + public static readonly ContractEnum PAYOUT = new("PAYOUT"); + + /// + /// ContractEnum.EXTERNAL - EXTERNAL + /// + public static readonly ContractEnum EXTERNAL = new("EXTERNAL"); + + private ContractEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractEnum?(string? value) => value == null ? null : new ContractEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractEnum? option) => option?.Value; + + public static bool operator ==(ContractEnum? left, ContractEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractEnum? left, ContractEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractEnum? FromStringOrDefault(string value) + { + return value switch { + "ONECLICK" => ContractEnum.ONECLICK, + "ONECLICK,RECURRING" => ContractEnum.ONECLICKRECURRING, + "RECURRING" => ContractEnum.RECURRING, + "PAYOUT" => ContractEnum.PAYOUT, + "EXTERNAL" => ContractEnum.EXTERNAL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractEnum? value) + { + if (value == null) + return null; + + if (value == ContractEnum.ONECLICK) + return "ONECLICK"; + + if (value == ContractEnum.ONECLICKRECURRING) + return "ONECLICK,RECURRING"; + + if (value == ContractEnum.RECURRING) + return "RECURRING"; + + if (value == ContractEnum.PAYOUT) + return "PAYOUT"; + + if (value == ContractEnum.EXTERNAL) + return "EXTERNAL"; + + return null; + } + + /// + /// JsonConverter for writing ContractEnum. + /// + public class ContractEnumJsonConverter : JsonConverter + { + public override ContractEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractEnum.FromStringOrDefault(value) ?? new ContractEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonPropertyName("contract")] + public ContractEnum? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonConverter(typeof(TokenServiceEnumJsonConverter))] + public class TokenServiceEnum : IEnum + { + /// + /// Returns the value of the TokenServiceEnum. + /// + public string? Value { get; set; } + + /// + /// TokenServiceEnum.VISATOKENSERVICE - VISATOKENSERVICE + /// + public static readonly TokenServiceEnum VISATOKENSERVICE = new("VISATOKENSERVICE"); + + /// + /// TokenServiceEnum.MCTOKENSERVICE - MCTOKENSERVICE + /// + public static readonly TokenServiceEnum MCTOKENSERVICE = new("MCTOKENSERVICE"); + + /// + /// TokenServiceEnum.AMEXTOKENSERVICE - AMEXTOKENSERVICE + /// + public static readonly TokenServiceEnum AMEXTOKENSERVICE = new("AMEXTOKENSERVICE"); + + /// + /// TokenServiceEnum.TOKENSHARING - TOKEN_SHARING + /// + public static readonly TokenServiceEnum TOKENSHARING = new("TOKEN_SHARING"); + + private TokenServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenServiceEnum?(string? value) => value == null ? null : new TokenServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenServiceEnum? option) => option?.Value; + + public static bool operator ==(TokenServiceEnum? left, TokenServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenServiceEnum? left, TokenServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "VISATOKENSERVICE" => TokenServiceEnum.VISATOKENSERVICE, + "MCTOKENSERVICE" => TokenServiceEnum.MCTOKENSERVICE, + "AMEXTOKENSERVICE" => TokenServiceEnum.AMEXTOKENSERVICE, + "TOKEN_SHARING" => TokenServiceEnum.TOKENSHARING, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenServiceEnum? value) + { + if (value == null) + return null; + + if (value == TokenServiceEnum.VISATOKENSERVICE) + return "VISATOKENSERVICE"; + + if (value == TokenServiceEnum.MCTOKENSERVICE) + return "MCTOKENSERVICE"; + + if (value == TokenServiceEnum.AMEXTOKENSERVICE) + return "AMEXTOKENSERVICE"; + + if (value == TokenServiceEnum.TOKENSHARING) + return "TOKEN_SHARING"; + + return null; + } + + /// + /// JsonConverter for writing TokenServiceEnum. + /// + public class TokenServiceEnumJsonConverter : JsonConverter + { + public override TokenServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenServiceEnum.FromStringOrDefault(value) ?? new TokenServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenServiceOption { get; private set; } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonPropertyName("tokenService")] + public TokenServiceEnum? TokenService { get { return this._TokenServiceOption; } set { this._TokenServiceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailNameOption { get; private set; } + + /// + /// A descriptive name for this detail. + /// + /// A descriptive name for this detail. + [JsonPropertyName("recurringDetailName")] + public string? RecurringDetailName { get { return this._RecurringDetailNameOption; } set { this._RecurringDetailNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public DateTimeOffset? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Recurring {\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" TokenService: ").Append(TokenService).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RecurringExpiry. + /// + public static string RecurringExpiryFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Recurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contract = default; + Option recurringDetailName = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option tokenService = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contract": + string? contractRawValue = utf8JsonReader.GetString(); + contract = new Option(Recurring.ContractEnum.FromStringOrDefault(contractRawValue)); + break; + case "recurringDetailName": + recurringDetailName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "tokenService": + string? tokenServiceRawValue = utf8JsonReader.GetString(); + tokenService = new Option(Recurring.TokenServiceEnum.FromStringOrDefault(tokenServiceRawValue)); + break; + default: + break; + } + } + } + + + return new Recurring(contract, recurringDetailName, recurringExpiry, recurringFrequency, tokenService); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurring._ContractOption.IsSet && recurring.Contract != null) + { + string? contractRawValue = Recurring.ContractEnum.ToJsonValue(recurring._ContractOption.Value!.Value); + writer.WriteString("contract", contractRawValue); + } + + if (recurring._RecurringDetailNameOption.IsSet) + if (recurring.RecurringDetailName != null) + writer.WriteString("recurringDetailName", recurring.RecurringDetailName); + + if (recurring._RecurringExpiryOption.IsSet) + writer.WriteString("recurringExpiry", recurring._RecurringExpiryOption.Value!.Value.ToString(RecurringExpiryFormat)); + + if (recurring._RecurringFrequencyOption.IsSet) + if (recurring.RecurringFrequency != null) + writer.WriteString("recurringFrequency", recurring.RecurringFrequency); + + if (recurring._TokenServiceOption.IsSet && recurring.TokenService != null) + { + string? tokenServiceRawValue = Recurring.TokenServiceEnum.ToJsonValue(recurring._TokenServiceOption.Value!.Value); + writer.WriteString("tokenService", tokenServiceRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalData3DSecure.cs b/Adyen/Checkout/Models/ResponseAdditionalData3DSecure.cs new file mode 100644 index 000000000..e26363bbe --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalData3DSecure.cs @@ -0,0 +1,276 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalData3DSecure. + /// + public partial class ResponseAdditionalData3DSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// The CAVV algorithm used. + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonConstructor] + public ResponseAdditionalData3DSecure(Option cardHolderInfo = default, Option cavv = default, Option cavvAlgorithm = default, Option scaExemptionRequested = default, Option threeds2CardEnrolled = default) + { + _CardHolderInfoOption = cardHolderInfo; + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _ScaExemptionRequestedOption = scaExemptionRequested; + _Threeds2CardEnrolledOption = threeds2CardEnrolled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalData3DSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderInfoOption { get; private set; } + + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + [JsonPropertyName("cardHolderInfo")] + public string? CardHolderInfo { get { return this._CardHolderInfoOption; } set { this._CardHolderInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + [JsonPropertyName("cavv")] + public string? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. + /// + /// The CAVV algorithm used. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaExemptionRequestedOption { get; private set; } + + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + [JsonPropertyName("scaExemptionRequested")] + public string? ScaExemptionRequested { get { return this._ScaExemptionRequestedOption; } set { this._ScaExemptionRequestedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Threeds2CardEnrolledOption { get; private set; } + + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonPropertyName("threeds2.cardEnrolled")] + public bool? Threeds2CardEnrolled { get { return this._Threeds2CardEnrolledOption; } set { this._Threeds2CardEnrolledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalData3DSecure {\n"); + sb.Append(" CardHolderInfo: ").Append(CardHolderInfo).Append("\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ScaExemptionRequested: ").Append(ScaExemptionRequested).Append("\n"); + sb.Append(" Threeds2CardEnrolled: ").Append(Threeds2CardEnrolled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalData3DSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalData3DSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardHolderInfo = default; + Option cavv = default; + Option cavvAlgorithm = default; + Option scaExemptionRequested = default; + Option threeds2CardEnrolled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardHolderInfo": + cardHolderInfo = new Option(utf8JsonReader.GetString()!); + break; + case "cavv": + cavv = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "scaExemptionRequested": + scaExemptionRequested = new Option(utf8JsonReader.GetString()!); + break; + case "threeds2.cardEnrolled": + threeds2CardEnrolled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalData3DSecure(cardHolderInfo, cavv, cavvAlgorithm, scaExemptionRequested, threeds2CardEnrolled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalData3DSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalData3DSecure._CardHolderInfoOption.IsSet) + if (responseAdditionalData3DSecure.CardHolderInfo != null) + writer.WriteString("cardHolderInfo", responseAdditionalData3DSecure.CardHolderInfo); + + if (responseAdditionalData3DSecure._CavvOption.IsSet) + if (responseAdditionalData3DSecure.Cavv != null) + writer.WriteString("cavv", responseAdditionalData3DSecure.Cavv); + + if (responseAdditionalData3DSecure._CavvAlgorithmOption.IsSet) + if (responseAdditionalData3DSecure.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", responseAdditionalData3DSecure.CavvAlgorithm); + + if (responseAdditionalData3DSecure._ScaExemptionRequestedOption.IsSet) + if (responseAdditionalData3DSecure.ScaExemptionRequested != null) + writer.WriteString("scaExemptionRequested", responseAdditionalData3DSecure.ScaExemptionRequested); + + if (responseAdditionalData3DSecure._Threeds2CardEnrolledOption.IsSet) + writer.WriteBoolean("threeds2.cardEnrolled", responseAdditionalData3DSecure._Threeds2CardEnrolledOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataBillingAddress.cs b/Adyen/Checkout/Models/ResponseAdditionalDataBillingAddress.cs new file mode 100644 index 000000000..945bc9114 --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataBillingAddress.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataBillingAddress. + /// + public partial class ResponseAdditionalDataBillingAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The billing address city passed in the payment request. + /// The billing address country passed in the payment request. Example: NL + /// The billing address house number or name passed in the payment request. + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// The billing address state or province passed in the payment request. Example: NH + /// The billing address street passed in the payment request. + [JsonConstructor] + public ResponseAdditionalDataBillingAddress(Option billingAddressCity = default, Option billingAddressCountry = default, Option billingAddressHouseNumberOrName = default, Option billingAddressPostalCode = default, Option billingAddressStateOrProvince = default, Option billingAddressStreet = default) + { + _BillingAddressCityOption = billingAddressCity; + _BillingAddressCountryOption = billingAddressCountry; + _BillingAddressHouseNumberOrNameOption = billingAddressHouseNumberOrName; + _BillingAddressPostalCodeOption = billingAddressPostalCode; + _BillingAddressStateOrProvinceOption = billingAddressStateOrProvince; + _BillingAddressStreetOption = billingAddressStreet; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataBillingAddress() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCityOption { get; private set; } + + /// + /// The billing address city passed in the payment request. + /// + /// The billing address city passed in the payment request. + [JsonPropertyName("billingAddress.city")] + public string? BillingAddressCity { get { return this._BillingAddressCityOption; } set { this._BillingAddressCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCountryOption { get; private set; } + + /// + /// The billing address country passed in the payment request. Example: NL + /// + /// The billing address country passed in the payment request. Example: NL + [JsonPropertyName("billingAddress.country")] + public string? BillingAddressCountry { get { return this._BillingAddressCountryOption; } set { this._BillingAddressCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressHouseNumberOrNameOption { get; private set; } + + /// + /// The billing address house number or name passed in the payment request. + /// + /// The billing address house number or name passed in the payment request. + [JsonPropertyName("billingAddress.houseNumberOrName")] + public string? BillingAddressHouseNumberOrName { get { return this._BillingAddressHouseNumberOrNameOption; } set { this._BillingAddressHouseNumberOrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressPostalCodeOption { get; private set; } + + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + [JsonPropertyName("billingAddress.postalCode")] + public string? BillingAddressPostalCode { get { return this._BillingAddressPostalCodeOption; } set { this._BillingAddressPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStateOrProvinceOption { get; private set; } + + /// + /// The billing address state or province passed in the payment request. Example: NH + /// + /// The billing address state or province passed in the payment request. Example: NH + [JsonPropertyName("billingAddress.stateOrProvince")] + public string? BillingAddressStateOrProvince { get { return this._BillingAddressStateOrProvinceOption; } set { this._BillingAddressStateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStreetOption { get; private set; } + + /// + /// The billing address street passed in the payment request. + /// + /// The billing address street passed in the payment request. + [JsonPropertyName("billingAddress.street")] + public string? BillingAddressStreet { get { return this._BillingAddressStreetOption; } set { this._BillingAddressStreetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataBillingAddress {\n"); + sb.Append(" BillingAddressCity: ").Append(BillingAddressCity).Append("\n"); + sb.Append(" BillingAddressCountry: ").Append(BillingAddressCountry).Append("\n"); + sb.Append(" BillingAddressHouseNumberOrName: ").Append(BillingAddressHouseNumberOrName).Append("\n"); + sb.Append(" BillingAddressPostalCode: ").Append(BillingAddressPostalCode).Append("\n"); + sb.Append(" BillingAddressStateOrProvince: ").Append(BillingAddressStateOrProvince).Append("\n"); + sb.Append(" BillingAddressStreet: ").Append(BillingAddressStreet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataBillingAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataBillingAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddressCity = default; + Option billingAddressCountry = default; + Option billingAddressHouseNumberOrName = default; + Option billingAddressPostalCode = default; + Option billingAddressStateOrProvince = default; + Option billingAddressStreet = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress.city": + billingAddressCity = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.country": + billingAddressCountry = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.houseNumberOrName": + billingAddressHouseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.postalCode": + billingAddressPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.stateOrProvince": + billingAddressStateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.street": + billingAddressStreet = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataBillingAddress(billingAddressCity, billingAddressCountry, billingAddressHouseNumberOrName, billingAddressPostalCode, billingAddressStateOrProvince, billingAddressStreet); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataBillingAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataBillingAddress._BillingAddressCityOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCity != null) + writer.WriteString("billingAddress.city", responseAdditionalDataBillingAddress.BillingAddressCity); + + if (responseAdditionalDataBillingAddress._BillingAddressCountryOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCountry != null) + writer.WriteString("billingAddress.country", responseAdditionalDataBillingAddress.BillingAddressCountry); + + if (responseAdditionalDataBillingAddress._BillingAddressHouseNumberOrNameOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName != null) + writer.WriteString("billingAddress.houseNumberOrName", responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName); + + if (responseAdditionalDataBillingAddress._BillingAddressPostalCodeOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressPostalCode != null) + writer.WriteString("billingAddress.postalCode", responseAdditionalDataBillingAddress.BillingAddressPostalCode); + + if (responseAdditionalDataBillingAddress._BillingAddressStateOrProvinceOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStateOrProvince != null) + writer.WriteString("billingAddress.stateOrProvince", responseAdditionalDataBillingAddress.BillingAddressStateOrProvince); + + if (responseAdditionalDataBillingAddress._BillingAddressStreetOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStreet != null) + writer.WriteString("billingAddress.street", responseAdditionalDataBillingAddress.BillingAddressStreet); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataCard.cs b/Adyen/Checkout/Models/ResponseAdditionalDataCard.cs new file mode 100644 index 000000000..806e64040 --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataCard.cs @@ -0,0 +1,564 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataCard. + /// + public partial class ResponseAdditionalDataCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// The cardholder name passed in the payment request. + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// The country where the card was issued. Example: US + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// The card payment method used for the transaction. Example: amex + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// The last four digits of a card number. > Returned only in case of a card payment. + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonConstructor] + public ResponseAdditionalDataCard(Option cardBin = default, Option cardHolderName = default, Option cardIssuingBank = default, Option cardIssuingCountry = default, Option cardIssuingCurrency = default, Option cardPaymentMethod = default, Option cardProductId = default, Option cardSummary = default, Option issuerBin = default) + { + _CardBinOption = cardBin; + _CardHolderNameOption = cardHolderName; + _CardIssuingBankOption = cardIssuingBank; + _CardIssuingCountryOption = cardIssuingCountry; + _CardIssuingCurrencyOption = cardIssuingCurrency; + _CardPaymentMethodOption = cardPaymentMethod; + _CardProductIdOption = cardProductId; + _CardSummaryOption = cardSummary; + _IssuerBinOption = issuerBin; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCard() + { + } + + partial void OnCreated(); + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonConverter(typeof(CardProductIdEnumJsonConverter))] + public class CardProductIdEnum : IEnum + { + /// + /// Returns the value of the CardProductIdEnum. + /// + public string? Value { get; set; } + + /// + /// CardProductIdEnum.A - A + /// + public static readonly CardProductIdEnum A = new("A"); + + /// + /// CardProductIdEnum.B - B + /// + public static readonly CardProductIdEnum B = new("B"); + + /// + /// CardProductIdEnum.C - C + /// + public static readonly CardProductIdEnum C = new("C"); + + /// + /// CardProductIdEnum.D - D + /// + public static readonly CardProductIdEnum D = new("D"); + + /// + /// CardProductIdEnum.F - F + /// + public static readonly CardProductIdEnum F = new("F"); + + /// + /// CardProductIdEnum.MCC - MCC + /// + public static readonly CardProductIdEnum MCC = new("MCC"); + + /// + /// CardProductIdEnum.MCE - MCE + /// + public static readonly CardProductIdEnum MCE = new("MCE"); + + /// + /// CardProductIdEnum.MCF - MCF + /// + public static readonly CardProductIdEnum MCF = new("MCF"); + + /// + /// CardProductIdEnum.MCG - MCG + /// + public static readonly CardProductIdEnum MCG = new("MCG"); + + /// + /// CardProductIdEnum.MCH - MCH + /// + public static readonly CardProductIdEnum MCH = new("MCH"); + + /// + /// CardProductIdEnum.MCI - MCI + /// + public static readonly CardProductIdEnum MCI = new("MCI"); + + private CardProductIdEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CardProductIdEnum?(string? value) => value == null ? null : new CardProductIdEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CardProductIdEnum? option) => option?.Value; + + public static bool operator ==(CardProductIdEnum? left, CardProductIdEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CardProductIdEnum? left, CardProductIdEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CardProductIdEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CardProductIdEnum? FromStringOrDefault(string value) + { + return value switch { + "A" => CardProductIdEnum.A, + "B" => CardProductIdEnum.B, + "C" => CardProductIdEnum.C, + "D" => CardProductIdEnum.D, + "F" => CardProductIdEnum.F, + "MCC" => CardProductIdEnum.MCC, + "MCE" => CardProductIdEnum.MCE, + "MCF" => CardProductIdEnum.MCF, + "MCG" => CardProductIdEnum.MCG, + "MCH" => CardProductIdEnum.MCH, + "MCI" => CardProductIdEnum.MCI, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CardProductIdEnum? value) + { + if (value == null) + return null; + + if (value == CardProductIdEnum.A) + return "A"; + + if (value == CardProductIdEnum.B) + return "B"; + + if (value == CardProductIdEnum.C) + return "C"; + + if (value == CardProductIdEnum.D) + return "D"; + + if (value == CardProductIdEnum.F) + return "F"; + + if (value == CardProductIdEnum.MCC) + return "MCC"; + + if (value == CardProductIdEnum.MCE) + return "MCE"; + + if (value == CardProductIdEnum.MCF) + return "MCF"; + + if (value == CardProductIdEnum.MCG) + return "MCG"; + + if (value == CardProductIdEnum.MCH) + return "MCH"; + + if (value == CardProductIdEnum.MCI) + return "MCI"; + + return null; + } + + /// + /// JsonConverter for writing CardProductIdEnum. + /// + public class CardProductIdEnumJsonConverter : JsonConverter + { + public override CardProductIdEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CardProductIdEnum.FromStringOrDefault(value) ?? new CardProductIdEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CardProductIdEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CardProductIdEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardProductIdOption { get; private set; } + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonPropertyName("cardProductId")] + public CardProductIdEnum? CardProductId { get { return this._CardProductIdOption; } set { this._CardProductIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardBinOption { get; private set; } + + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + [JsonPropertyName("cardBin")] + public string? CardBin { get { return this._CardBinOption; } set { this._CardBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderNameOption { get; private set; } + + /// + /// The cardholder name passed in the payment request. + /// + /// The cardholder name passed in the payment request. + [JsonPropertyName("cardHolderName")] + public string? CardHolderName { get { return this._CardHolderNameOption; } set { this._CardHolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingBankOption { get; private set; } + + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + [JsonPropertyName("cardIssuingBank")] + public string? CardIssuingBank { get { return this._CardIssuingBankOption; } set { this._CardIssuingBankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCountryOption { get; private set; } + + /// + /// The country where the card was issued. Example: US + /// + /// The country where the card was issued. Example: US + [JsonPropertyName("cardIssuingCountry")] + public string? CardIssuingCountry { get { return this._CardIssuingCountryOption; } set { this._CardIssuingCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCurrencyOption { get; private set; } + + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + [JsonPropertyName("cardIssuingCurrency")] + public string? CardIssuingCurrency { get { return this._CardIssuingCurrencyOption; } set { this._CardIssuingCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardPaymentMethodOption { get; private set; } + + /// + /// The card payment method used for the transaction. Example: amex + /// + /// The card payment method used for the transaction. Example: amex + [JsonPropertyName("cardPaymentMethod")] + public string? CardPaymentMethod { get { return this._CardPaymentMethodOption; } set { this._CardPaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardSummaryOption { get; private set; } + + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + [JsonPropertyName("cardSummary")] + public string? CardSummary { get { return this._CardSummaryOption; } set { this._CardSummaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerBinOption { get; private set; } + + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonPropertyName("issuerBin")] + public string? IssuerBin { get { return this._IssuerBinOption; } set { this._IssuerBinOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCard {\n"); + sb.Append(" CardBin: ").Append(CardBin).Append("\n"); + sb.Append(" CardHolderName: ").Append(CardHolderName).Append("\n"); + sb.Append(" CardIssuingBank: ").Append(CardIssuingBank).Append("\n"); + sb.Append(" CardIssuingCountry: ").Append(CardIssuingCountry).Append("\n"); + sb.Append(" CardIssuingCurrency: ").Append(CardIssuingCurrency).Append("\n"); + sb.Append(" CardPaymentMethod: ").Append(CardPaymentMethod).Append("\n"); + sb.Append(" CardProductId: ").Append(CardProductId).Append("\n"); + sb.Append(" CardSummary: ").Append(CardSummary).Append("\n"); + sb.Append(" IssuerBin: ").Append(IssuerBin).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardBin = default; + Option cardHolderName = default; + Option cardIssuingBank = default; + Option cardIssuingCountry = default; + Option cardIssuingCurrency = default; + Option cardPaymentMethod = default; + Option cardProductId = default; + Option cardSummary = default; + Option issuerBin = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardBin": + cardBin = new Option(utf8JsonReader.GetString()!); + break; + case "cardHolderName": + cardHolderName = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingBank": + cardIssuingBank = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCountry": + cardIssuingCountry = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCurrency": + cardIssuingCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "cardPaymentMethod": + cardPaymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "cardProductId": + string? cardProductIdRawValue = utf8JsonReader.GetString(); + cardProductId = new Option(ResponseAdditionalDataCard.CardProductIdEnum.FromStringOrDefault(cardProductIdRawValue)); + break; + case "cardSummary": + cardSummary = new Option(utf8JsonReader.GetString()!); + break; + case "issuerBin": + issuerBin = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCard(cardBin, cardHolderName, cardIssuingBank, cardIssuingCountry, cardIssuingCurrency, cardPaymentMethod, cardProductId, cardSummary, issuerBin); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCard._CardBinOption.IsSet) + if (responseAdditionalDataCard.CardBin != null) + writer.WriteString("cardBin", responseAdditionalDataCard.CardBin); + + if (responseAdditionalDataCard._CardHolderNameOption.IsSet) + if (responseAdditionalDataCard.CardHolderName != null) + writer.WriteString("cardHolderName", responseAdditionalDataCard.CardHolderName); + + if (responseAdditionalDataCard._CardIssuingBankOption.IsSet) + if (responseAdditionalDataCard.CardIssuingBank != null) + writer.WriteString("cardIssuingBank", responseAdditionalDataCard.CardIssuingBank); + + if (responseAdditionalDataCard._CardIssuingCountryOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCountry != null) + writer.WriteString("cardIssuingCountry", responseAdditionalDataCard.CardIssuingCountry); + + if (responseAdditionalDataCard._CardIssuingCurrencyOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCurrency != null) + writer.WriteString("cardIssuingCurrency", responseAdditionalDataCard.CardIssuingCurrency); + + if (responseAdditionalDataCard._CardPaymentMethodOption.IsSet) + if (responseAdditionalDataCard.CardPaymentMethod != null) + writer.WriteString("cardPaymentMethod", responseAdditionalDataCard.CardPaymentMethod); + + if (responseAdditionalDataCard._CardProductIdOption.IsSet && responseAdditionalDataCard.CardProductId != null) + { + string? cardProductIdRawValue = ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCard._CardProductIdOption.Value!.Value); + writer.WriteString("cardProductId", cardProductIdRawValue); + } + + if (responseAdditionalDataCard._CardSummaryOption.IsSet) + if (responseAdditionalDataCard.CardSummary != null) + writer.WriteString("cardSummary", responseAdditionalDataCard.CardSummary); + + if (responseAdditionalDataCard._IssuerBinOption.IsSet) + if (responseAdditionalDataCard.IssuerBin != null) + writer.WriteString("issuerBin", responseAdditionalDataCard.IssuerBin); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataCommon.cs b/Adyen/Checkout/Models/ResponseAdditionalDataCommon.cs new file mode 100644 index 000000000..668d277bc --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataCommon.cs @@ -0,0 +1,2200 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataCommon. + /// + public partial class ResponseAdditionalDataCommon : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// The Adyen alias of the card. Example: H167852639363479 + /// The type of the card alias. Example: Default + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// Merchant ID known by the acquirer. + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// Raw AVS result received from the acquirer, where available. Example: D + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// Includes the co-branded card information. + /// The result of CVC verification. + /// The raw result of CVC verification. + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// Indicates if the payment is sent to manual review. + /// The fraud result properties of the payment. + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// Indicates if the card is used for business purposes only. + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// The reference provided for the transaction. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// The payment method used in the transaction. + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// Message to be displayed on the terminal. + /// The recurring contract types applicable to the transaction. + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// The reference that uniquely identifies the recurring transaction. + /// The provided reference of the shopper for a recurring transaction. + /// The processing model used for the recurring transaction. + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// The amount of the payment request. + /// The currency of the payment request. + /// The shopper interaction type of the payment request. Example: Ecommerce + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// The raw 3DS authentication result from the card issuer. Example: N + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// The 3D Secure 2 version. + /// The reference for the shopper that you sent when tokenizing the payment details. + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// The reference that uniquely identifies tokenized payment details. + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonConstructor] + public ResponseAdditionalDataCommon(Option acquirerAccountCode = default, Option acquirerCode = default, Option acquirerReference = default, Option alias = default, Option aliasType = default, Option authCode = default, Option authorisationMid = default, Option authorisedAmountCurrency = default, Option authorisedAmountValue = default, Option avsResult = default, Option avsResultRaw = default, Option bic = default, Option coBrandedWith = default, Option cvcResult = default, Option cvcResultRaw = default, Option dsTransID = default, Option eci = default, Option expiryDate = default, Option extraCostsCurrency = default, Option extraCostsValue = default, Option fraudCheckItemNrFraudCheckname = default, Option fraudManualReview = default, Option fraudResultType = default, Option fraudRiskLevel = default, Option fundingSource = default, Option fundsAvailability = default, Option inferredRefusalReason = default, Option isCardCommercial = default, Option issuerCountry = default, Option liabilityShift = default, Option mcBankNetReferenceNumber = default, Option merchantAdviceCode = default, Option merchantReference = default, Option networkTxReference = default, Option ownerName = default, Option paymentAccountReference = default, Option paymentMethod = default, Option paymentMethodVariant = default, Option payoutEligible = default, Option realtimeAccountUpdaterStatus = default, Option receiptFreeText = default, Option recurringContractTypes = default, Option recurringFirstPspReference = default, Option recurringRecurringDetailReference = default, Option recurringShopperReference = default, Option recurringProcessingModel = default, Option referred = default, Option refusalReasonRaw = default, Option requestAmount = default, Option requestCurrencyCode = default, Option shopperInteraction = default, Option shopperReference = default, Option terminalId = default, Option threeDAuthenticated = default, Option threeDAuthenticatedResponse = default, Option threeDOffered = default, Option threeDOfferedResponse = default, Option threeDSVersion = default, Option tokenizationShopperReference = default, Option tokenizationStoreOperationType = default, Option tokenizationStoredPaymentMethodId = default, Option visaTransactionId = default, Option xid = default) + { + _AcquirerAccountCodeOption = acquirerAccountCode; + _AcquirerCodeOption = acquirerCode; + _AcquirerReferenceOption = acquirerReference; + _AliasOption = alias; + _AliasTypeOption = aliasType; + _AuthCodeOption = authCode; + _AuthorisationMidOption = authorisationMid; + _AuthorisedAmountCurrencyOption = authorisedAmountCurrency; + _AuthorisedAmountValueOption = authorisedAmountValue; + _AvsResultOption = avsResult; + _AvsResultRawOption = avsResultRaw; + _BicOption = bic; + _CoBrandedWithOption = coBrandedWith; + _CvcResultOption = cvcResult; + _CvcResultRawOption = cvcResultRaw; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _ExpiryDateOption = expiryDate; + _ExtraCostsCurrencyOption = extraCostsCurrency; + _ExtraCostsValueOption = extraCostsValue; + _FraudCheckItemNrFraudChecknameOption = fraudCheckItemNrFraudCheckname; + _FraudManualReviewOption = fraudManualReview; + _FraudResultTypeOption = fraudResultType; + _FraudRiskLevelOption = fraudRiskLevel; + _FundingSourceOption = fundingSource; + _FundsAvailabilityOption = fundsAvailability; + _InferredRefusalReasonOption = inferredRefusalReason; + _IsCardCommercialOption = isCardCommercial; + _IssuerCountryOption = issuerCountry; + _LiabilityShiftOption = liabilityShift; + _McBankNetReferenceNumberOption = mcBankNetReferenceNumber; + _MerchantAdviceCodeOption = merchantAdviceCode; + _MerchantReferenceOption = merchantReference; + _NetworkTxReferenceOption = networkTxReference; + _OwnerNameOption = ownerName; + _PaymentAccountReferenceOption = paymentAccountReference; + _PaymentMethodOption = paymentMethod; + _PaymentMethodVariantOption = paymentMethodVariant; + _PayoutEligibleOption = payoutEligible; + _RealtimeAccountUpdaterStatusOption = realtimeAccountUpdaterStatus; + _ReceiptFreeTextOption = receiptFreeText; + _RecurringContractTypesOption = recurringContractTypes; + _RecurringFirstPspReferenceOption = recurringFirstPspReference; + _RecurringRecurringDetailReferenceOption = recurringRecurringDetailReference; + _RecurringShopperReferenceOption = recurringShopperReference; + _RecurringProcessingModelOption = recurringProcessingModel; + _ReferredOption = referred; + _RefusalReasonRawOption = refusalReasonRaw; + _RequestAmountOption = requestAmount; + _RequestCurrencyCodeOption = requestCurrencyCode; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _TerminalIdOption = terminalId; + _ThreeDAuthenticatedOption = threeDAuthenticated; + _ThreeDAuthenticatedResponseOption = threeDAuthenticatedResponse; + _ThreeDOfferedOption = threeDOffered; + _ThreeDOfferedResponseOption = threeDOfferedResponse; + _ThreeDSVersionOption = threeDSVersion; + _TokenizationShopperReferenceOption = tokenizationShopperReference; + _TokenizationStoreOperationTypeOption = tokenizationStoreOperationType; + _TokenizationStoredPaymentMethodIdOption = tokenizationStoredPaymentMethodId; + _VisaTransactionIdOption = visaTransactionId; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCommon() + { + } + + partial void OnCreated(); + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonConverter(typeof(FraudResultTypeEnumJsonConverter))] + public class FraudResultTypeEnum : IEnum + { + /// + /// Returns the value of the FraudResultTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FraudResultTypeEnum.GREEN - GREEN + /// + public static readonly FraudResultTypeEnum GREEN = new("GREEN"); + + /// + /// FraudResultTypeEnum.FRAUD - FRAUD + /// + public static readonly FraudResultTypeEnum FRAUD = new("FRAUD"); + + private FraudResultTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudResultTypeEnum?(string? value) => value == null ? null : new FraudResultTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudResultTypeEnum? option) => option?.Value; + + public static bool operator ==(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudResultTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudResultTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "GREEN" => FraudResultTypeEnum.GREEN, + "FRAUD" => FraudResultTypeEnum.FRAUD, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudResultTypeEnum? value) + { + if (value == null) + return null; + + if (value == FraudResultTypeEnum.GREEN) + return "GREEN"; + + if (value == FraudResultTypeEnum.FRAUD) + return "FRAUD"; + + return null; + } + + /// + /// JsonConverter for writing FraudResultTypeEnum. + /// + public class FraudResultTypeEnumJsonConverter : JsonConverter + { + public override FraudResultTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudResultTypeEnum.FromStringOrDefault(value) ?? new FraudResultTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudResultTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudResultTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultTypeOption { get; private set; } + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonPropertyName("fraudResultType")] + public FraudResultTypeEnum? FraudResultType { get { return this._FraudResultTypeOption; } set { this._FraudResultTypeOption = new(value); } } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonConverter(typeof(FraudRiskLevelEnumJsonConverter))] + public class FraudRiskLevelEnum : IEnum + { + /// + /// Returns the value of the FraudRiskLevelEnum. + /// + public string? Value { get; set; } + + /// + /// FraudRiskLevelEnum.VeryLow - veryLow + /// + public static readonly FraudRiskLevelEnum VeryLow = new("veryLow"); + + /// + /// FraudRiskLevelEnum.Low - low + /// + public static readonly FraudRiskLevelEnum Low = new("low"); + + /// + /// FraudRiskLevelEnum.Medium - medium + /// + public static readonly FraudRiskLevelEnum Medium = new("medium"); + + /// + /// FraudRiskLevelEnum.High - high + /// + public static readonly FraudRiskLevelEnum High = new("high"); + + /// + /// FraudRiskLevelEnum.VeryHigh - veryHigh + /// + public static readonly FraudRiskLevelEnum VeryHigh = new("veryHigh"); + + private FraudRiskLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudRiskLevelEnum?(string? value) => value == null ? null : new FraudRiskLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudRiskLevelEnum? option) => option?.Value; + + public static bool operator ==(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudRiskLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudRiskLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "veryLow" => FraudRiskLevelEnum.VeryLow, + "low" => FraudRiskLevelEnum.Low, + "medium" => FraudRiskLevelEnum.Medium, + "high" => FraudRiskLevelEnum.High, + "veryHigh" => FraudRiskLevelEnum.VeryHigh, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudRiskLevelEnum? value) + { + if (value == null) + return null; + + if (value == FraudRiskLevelEnum.VeryLow) + return "veryLow"; + + if (value == FraudRiskLevelEnum.Low) + return "low"; + + if (value == FraudRiskLevelEnum.Medium) + return "medium"; + + if (value == FraudRiskLevelEnum.High) + return "high"; + + if (value == FraudRiskLevelEnum.VeryHigh) + return "veryHigh"; + + return null; + } + + /// + /// JsonConverter for writing FraudRiskLevelEnum. + /// + public class FraudRiskLevelEnumJsonConverter : JsonConverter + { + public override FraudRiskLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudRiskLevelEnum.FromStringOrDefault(value) ?? new FraudRiskLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudRiskLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudRiskLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudRiskLevelOption { get; private set; } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonPropertyName("fraudRiskLevel")] + public FraudRiskLevelEnum? FraudRiskLevel { get { return this._FraudRiskLevelOption; } set { this._FraudRiskLevelOption = new(value); } } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonConverter(typeof(TokenizationStoreOperationTypeEnumJsonConverter))] + public class TokenizationStoreOperationTypeEnum : IEnum + { + /// + /// Returns the value of the TokenizationStoreOperationTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TokenizationStoreOperationTypeEnum.Created - created + /// + public static readonly TokenizationStoreOperationTypeEnum Created = new("created"); + + /// + /// TokenizationStoreOperationTypeEnum.Updated - updated + /// + public static readonly TokenizationStoreOperationTypeEnum Updated = new("updated"); + + /// + /// TokenizationStoreOperationTypeEnum.AlreadyExisting - alreadyExisting + /// + public static readonly TokenizationStoreOperationTypeEnum AlreadyExisting = new("alreadyExisting"); + + private TokenizationStoreOperationTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenizationStoreOperationTypeEnum?(string? value) => value == null ? null : new TokenizationStoreOperationTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenizationStoreOperationTypeEnum? option) => option?.Value; + + public static bool operator ==(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenizationStoreOperationTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenizationStoreOperationTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "created" => TokenizationStoreOperationTypeEnum.Created, + "updated" => TokenizationStoreOperationTypeEnum.Updated, + "alreadyExisting" => TokenizationStoreOperationTypeEnum.AlreadyExisting, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenizationStoreOperationTypeEnum? value) + { + if (value == null) + return null; + + if (value == TokenizationStoreOperationTypeEnum.Created) + return "created"; + + if (value == TokenizationStoreOperationTypeEnum.Updated) + return "updated"; + + if (value == TokenizationStoreOperationTypeEnum.AlreadyExisting) + return "alreadyExisting"; + + return null; + } + + /// + /// JsonConverter for writing TokenizationStoreOperationTypeEnum. + /// + public class TokenizationStoreOperationTypeEnumJsonConverter : JsonConverter + { + public override TokenizationStoreOperationTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenizationStoreOperationTypeEnum.FromStringOrDefault(value) ?? new TokenizationStoreOperationTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenizationStoreOperationTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenizationStoreOperationTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoreOperationTypeOption { get; private set; } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonPropertyName("tokenization.store.operationType")] + public TokenizationStoreOperationTypeEnum? TokenizationStoreOperationType { get { return this._TokenizationStoreOperationTypeOption; } set { this._TokenizationStoreOperationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerAccountCodeOption { get; private set; } + + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + [JsonPropertyName("acquirerAccountCode")] + public string? AcquirerAccountCode { get { return this._AcquirerAccountCodeOption; } set { this._AcquirerAccountCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerCodeOption { get; private set; } + + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + [JsonPropertyName("acquirerCode")] + public string? AcquirerCode { get { return this._AcquirerCodeOption; } set { this._AcquirerCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerReferenceOption { get; private set; } + + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + [JsonPropertyName("acquirerReference")] + public string? AcquirerReference { get { return this._AcquirerReferenceOption; } set { this._AcquirerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasOption { get; private set; } + + /// + /// The Adyen alias of the card. Example: H167852639363479 + /// + /// The Adyen alias of the card. Example: H167852639363479 + [JsonPropertyName("alias")] + public string? Alias { get { return this._AliasOption; } set { this._AliasOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasTypeOption { get; private set; } + + /// + /// The type of the card alias. Example: Default + /// + /// The type of the card alias. Example: Default + [JsonPropertyName("aliasType")] + public string? AliasType { get { return this._AliasTypeOption; } set { this._AliasTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationMidOption { get; private set; } + + /// + /// Merchant ID known by the acquirer. + /// + /// Merchant ID known by the acquirer. + [JsonPropertyName("authorisationMid")] + public string? AuthorisationMid { get { return this._AuthorisationMidOption; } set { this._AuthorisationMidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountCurrencyOption { get; private set; } + + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountCurrency")] + public string? AuthorisedAmountCurrency { get { return this._AuthorisedAmountCurrencyOption; } set { this._AuthorisedAmountCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountValueOption { get; private set; } + + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountValue")] + public string? AuthorisedAmountValue { get { return this._AuthorisedAmountValueOption; } set { this._AuthorisedAmountValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultOption { get; private set; } + + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + [JsonPropertyName("avsResult")] + public string? AvsResult { get { return this._AvsResultOption; } set { this._AvsResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultRawOption { get; private set; } + + /// + /// Raw AVS result received from the acquirer, where available. Example: D + /// + /// Raw AVS result received from the acquirer, where available. Example: D + [JsonPropertyName("avsResultRaw")] + public string? AvsResultRaw { get { return this._AvsResultRawOption; } set { this._AvsResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CoBrandedWithOption { get; private set; } + + /// + /// Includes the co-branded card information. + /// + /// Includes the co-branded card information. + [JsonPropertyName("coBrandedWith")] + public string? CoBrandedWith { get { return this._CoBrandedWithOption; } set { this._CoBrandedWithOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultOption { get; private set; } + + /// + /// The result of CVC verification. + /// + /// The result of CVC verification. + /* 1 Matches */ + [JsonPropertyName("cvcResult")] + public string? CvcResult { get { return this._CvcResultOption; } set { this._CvcResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultRawOption { get; private set; } + + /// + /// The raw result of CVC verification. + /// + /// The raw result of CVC verification. + /* M */ + [JsonPropertyName("cvcResultRaw")] + public string? CvcResultRaw { get { return this._CvcResultRawOption; } set { this._CvcResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryDateOption { get; private set; } + + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + [JsonPropertyName("expiryDate")] + public string? ExpiryDate { get { return this._ExpiryDateOption; } set { this._ExpiryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsCurrencyOption { get; private set; } + + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + [JsonPropertyName("extraCostsCurrency")] + public string? ExtraCostsCurrency { get { return this._ExtraCostsCurrencyOption; } set { this._ExtraCostsCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsValueOption { get; private set; } + + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + [JsonPropertyName("extraCostsValue")] + public string? ExtraCostsValue { get { return this._ExtraCostsValueOption; } set { this._ExtraCostsValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudCheckItemNrFraudChecknameOption { get; private set; } + + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + [JsonPropertyName("fraudCheck-[itemNr]-[FraudCheckname]")] + public string? FraudCheckItemNrFraudCheckname { get { return this._FraudCheckItemNrFraudChecknameOption; } set { this._FraudCheckItemNrFraudChecknameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudManualReviewOption { get; private set; } + + /// + /// Indicates if the payment is sent to manual review. + /// + /// Indicates if the payment is sent to manual review. + [JsonPropertyName("fraudManualReview")] + public string? FraudManualReview { get { return this._FraudManualReviewOption; } set { this._FraudManualReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + [JsonPropertyName("fundingSource")] + public string? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundsAvailabilityOption { get; private set; } + + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + [JsonPropertyName("fundsAvailability")] + public string? FundsAvailability { get { return this._FundsAvailabilityOption; } set { this._FundsAvailabilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InferredRefusalReasonOption { get; private set; } + + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + [JsonPropertyName("inferredRefusalReason")] + public string? InferredRefusalReason { get { return this._InferredRefusalReasonOption; } set { this._InferredRefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IsCardCommercialOption { get; private set; } + + /// + /// Indicates if the card is used for business purposes only. + /// + /// Indicates if the card is used for business purposes only. + [JsonPropertyName("isCardCommercial")] + public string? IsCardCommercial { get { return this._IsCardCommercialOption; } set { this._IsCardCommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + [JsonPropertyName("issuerCountry")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LiabilityShiftOption { get; private set; } + + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + [JsonPropertyName("liabilityShift")] + public string? LiabilityShift { get { return this._LiabilityShiftOption; } set { this._LiabilityShiftOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McBankNetReferenceNumberOption { get; private set; } + + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + [JsonPropertyName("mcBankNetReferenceNumber")] + public string? McBankNetReferenceNumber { get { return this._McBankNetReferenceNumberOption; } set { this._McBankNetReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAdviceCodeOption { get; private set; } + + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + [JsonPropertyName("merchantAdviceCode")] + public string? MerchantAdviceCode { get { return this._MerchantAdviceCodeOption; } set { this._MerchantAdviceCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The reference provided for the transaction. + /// + /// The reference provided for the transaction. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountReferenceOption { get; private set; } + + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + [JsonPropertyName("paymentAccountReference")] + public string? PaymentAccountReference { get { return this._PaymentAccountReferenceOption; } set { this._PaymentAccountReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// The payment method used in the transaction. + /// + /// The payment method used in the transaction. + [JsonPropertyName("paymentMethod")] + public string? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodVariantOption { get; private set; } + + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + [JsonPropertyName("paymentMethodVariant")] + public string? PaymentMethodVariant { get { return this._PaymentMethodVariantOption; } set { this._PaymentMethodVariantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayoutEligibleOption { get; private set; } + + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + [JsonPropertyName("payoutEligible")] + public string? PayoutEligible { get { return this._PayoutEligibleOption; } set { this._PayoutEligibleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RealtimeAccountUpdaterStatusOption { get; private set; } + + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + [JsonPropertyName("realtimeAccountUpdaterStatus")] + public string? RealtimeAccountUpdaterStatus { get { return this._RealtimeAccountUpdaterStatusOption; } set { this._RealtimeAccountUpdaterStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiptFreeTextOption { get; private set; } + + /// + /// Message to be displayed on the terminal. + /// + /// Message to be displayed on the terminal. + [JsonPropertyName("receiptFreeText")] + public string? ReceiptFreeText { get { return this._ReceiptFreeTextOption; } set { this._ReceiptFreeTextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringContractTypesOption { get; private set; } + + /// + /// The recurring contract types applicable to the transaction. + /// + /// The recurring contract types applicable to the transaction. + [JsonPropertyName("recurring.contractTypes")] + public string? RecurringContractTypes { get { return this._RecurringContractTypesOption; } set { this._RecurringContractTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFirstPspReferenceOption { get; private set; } + + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + [JsonPropertyName("recurring.firstPspReference")] + public string? RecurringFirstPspReference { get { return this._RecurringFirstPspReferenceOption; } set { this._RecurringFirstPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringRecurringDetailReferenceOption { get; private set; } + + /// + /// The reference that uniquely identifies the recurring transaction. + /// + /// The reference that uniquely identifies the recurring transaction. + [JsonPropertyName("recurring.recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use tokenization.storedPaymentMethodId instead.")] + public string? RecurringRecurringDetailReference { get { return this._RecurringRecurringDetailReferenceOption; } set { this._RecurringRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringShopperReferenceOption { get; private set; } + + /// + /// The provided reference of the shopper for a recurring transaction. + /// + /// The provided reference of the shopper for a recurring transaction. + [JsonPropertyName("recurring.shopperReference")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use tokenization.shopperReference instead.")] + public string? RecurringShopperReference { get { return this._RecurringShopperReferenceOption; } set { this._RecurringShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferredOption { get; private set; } + + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + [JsonPropertyName("referred")] + public string? Referred { get { return this._ReferredOption; } set { this._ReferredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonRawOption { get; private set; } + + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + [JsonPropertyName("refusalReasonRaw")] + public string? RefusalReasonRaw { get { return this._RefusalReasonRawOption; } set { this._RefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestAmountOption { get; private set; } + + /// + /// The amount of the payment request. + /// + /// The amount of the payment request. + [JsonPropertyName("requestAmount")] + public string? RequestAmount { get { return this._RequestAmountOption; } set { this._RequestAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestCurrencyCodeOption { get; private set; } + + /// + /// The currency of the payment request. + /// + /// The currency of the payment request. + [JsonPropertyName("requestCurrencyCode")] + public string? RequestCurrencyCode { get { return this._RequestCurrencyCodeOption; } set { this._RequestCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + [JsonPropertyName("shopperInteraction")] + public string? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + [JsonPropertyName("threeDAuthenticated")] + public string? ThreeDAuthenticated { get { return this._ThreeDAuthenticatedOption; } set { this._ThreeDAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedResponseOption { get; private set; } + + /// + /// The raw 3DS authentication result from the card issuer. Example: N + /// + /// The raw 3DS authentication result from the card issuer. Example: N + [JsonPropertyName("threeDAuthenticatedResponse")] + public string? ThreeDAuthenticatedResponse { get { return this._ThreeDAuthenticatedResponseOption; } set { this._ThreeDAuthenticatedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + [JsonPropertyName("threeDOffered")] + public string? ThreeDOffered { get { return this._ThreeDOfferedOption; } set { this._ThreeDOfferedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedResponseOption { get; private set; } + + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + [JsonPropertyName("threeDOfferedResponse")] + public string? ThreeDOfferedResponse { get { return this._ThreeDOfferedResponseOption; } set { this._ThreeDOfferedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The 3D Secure 2 version. + /// + /// The 3D Secure 2 version. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationShopperReferenceOption { get; private set; } + + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + [JsonPropertyName("tokenization.shopperReference")] + public string? TokenizationShopperReference { get { return this._TokenizationShopperReferenceOption; } set { this._TokenizationShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoredPaymentMethodIdOption { get; private set; } + + /// + /// The reference that uniquely identifies tokenized payment details. + /// + /// The reference that uniquely identifies tokenized payment details. + [JsonPropertyName("tokenization.storedPaymentMethodId")] + public string? TokenizationStoredPaymentMethodId { get { return this._TokenizationStoredPaymentMethodIdOption; } set { this._TokenizationStoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaTransactionIdOption { get; private set; } + + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + [JsonPropertyName("visaTransactionId")] + public string? VisaTransactionId { get { return this._VisaTransactionIdOption; } set { this._VisaTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonPropertyName("xid")] + public string? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCommon {\n"); + sb.Append(" AcquirerAccountCode: ").Append(AcquirerAccountCode).Append("\n"); + sb.Append(" AcquirerCode: ").Append(AcquirerCode).Append("\n"); + sb.Append(" AcquirerReference: ").Append(AcquirerReference).Append("\n"); + sb.Append(" Alias: ").Append(Alias).Append("\n"); + sb.Append(" AliasType: ").Append(AliasType).Append("\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" AuthorisationMid: ").Append(AuthorisationMid).Append("\n"); + sb.Append(" AuthorisedAmountCurrency: ").Append(AuthorisedAmountCurrency).Append("\n"); + sb.Append(" AuthorisedAmountValue: ").Append(AuthorisedAmountValue).Append("\n"); + sb.Append(" AvsResult: ").Append(AvsResult).Append("\n"); + sb.Append(" AvsResultRaw: ").Append(AvsResultRaw).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CoBrandedWith: ").Append(CoBrandedWith).Append("\n"); + sb.Append(" CvcResult: ").Append(CvcResult).Append("\n"); + sb.Append(" CvcResultRaw: ").Append(CvcResultRaw).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ExpiryDate: ").Append(ExpiryDate).Append("\n"); + sb.Append(" ExtraCostsCurrency: ").Append(ExtraCostsCurrency).Append("\n"); + sb.Append(" ExtraCostsValue: ").Append(ExtraCostsValue).Append("\n"); + sb.Append(" FraudCheckItemNrFraudCheckname: ").Append(FraudCheckItemNrFraudCheckname).Append("\n"); + sb.Append(" FraudManualReview: ").Append(FraudManualReview).Append("\n"); + sb.Append(" FraudResultType: ").Append(FraudResultType).Append("\n"); + sb.Append(" FraudRiskLevel: ").Append(FraudRiskLevel).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" FundsAvailability: ").Append(FundsAvailability).Append("\n"); + sb.Append(" InferredRefusalReason: ").Append(InferredRefusalReason).Append("\n"); + sb.Append(" IsCardCommercial: ").Append(IsCardCommercial).Append("\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append(" LiabilityShift: ").Append(LiabilityShift).Append("\n"); + sb.Append(" McBankNetReferenceNumber: ").Append(McBankNetReferenceNumber).Append("\n"); + sb.Append(" MerchantAdviceCode: ").Append(MerchantAdviceCode).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" PaymentAccountReference: ").Append(PaymentAccountReference).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PaymentMethodVariant: ").Append(PaymentMethodVariant).Append("\n"); + sb.Append(" PayoutEligible: ").Append(PayoutEligible).Append("\n"); + sb.Append(" RealtimeAccountUpdaterStatus: ").Append(RealtimeAccountUpdaterStatus).Append("\n"); + sb.Append(" ReceiptFreeText: ").Append(ReceiptFreeText).Append("\n"); + sb.Append(" RecurringContractTypes: ").Append(RecurringContractTypes).Append("\n"); + sb.Append(" RecurringFirstPspReference: ").Append(RecurringFirstPspReference).Append("\n"); + sb.Append(" RecurringRecurringDetailReference: ").Append(RecurringRecurringDetailReference).Append("\n"); + sb.Append(" RecurringShopperReference: ").Append(RecurringShopperReference).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" Referred: ").Append(Referred).Append("\n"); + sb.Append(" RefusalReasonRaw: ").Append(RefusalReasonRaw).Append("\n"); + sb.Append(" RequestAmount: ").Append(RequestAmount).Append("\n"); + sb.Append(" RequestCurrencyCode: ").Append(RequestCurrencyCode).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append(" ThreeDAuthenticated: ").Append(ThreeDAuthenticated).Append("\n"); + sb.Append(" ThreeDAuthenticatedResponse: ").Append(ThreeDAuthenticatedResponse).Append("\n"); + sb.Append(" ThreeDOffered: ").Append(ThreeDOffered).Append("\n"); + sb.Append(" ThreeDOfferedResponse: ").Append(ThreeDOfferedResponse).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append(" TokenizationShopperReference: ").Append(TokenizationShopperReference).Append("\n"); + sb.Append(" TokenizationStoreOperationType: ").Append(TokenizationStoreOperationType).Append("\n"); + sb.Append(" TokenizationStoredPaymentMethodId: ").Append(TokenizationStoredPaymentMethodId).Append("\n"); + sb.Append(" VisaTransactionId: ").Append(VisaTransactionId).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCommonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCommon Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerAccountCode = default; + Option acquirerCode = default; + Option acquirerReference = default; + Option alias = default; + Option aliasType = default; + Option authCode = default; + Option authorisationMid = default; + Option authorisedAmountCurrency = default; + Option authorisedAmountValue = default; + Option avsResult = default; + Option avsResultRaw = default; + Option bic = default; + Option coBrandedWith = default; + Option cvcResult = default; + Option cvcResultRaw = default; + Option dsTransID = default; + Option eci = default; + Option expiryDate = default; + Option extraCostsCurrency = default; + Option extraCostsValue = default; + Option fraudCheckItemNrFraudCheckname = default; + Option fraudManualReview = default; + Option fraudResultType = default; + Option fraudRiskLevel = default; + Option fundingSource = default; + Option fundsAvailability = default; + Option inferredRefusalReason = default; + Option isCardCommercial = default; + Option issuerCountry = default; + Option liabilityShift = default; + Option mcBankNetReferenceNumber = default; + Option merchantAdviceCode = default; + Option merchantReference = default; + Option networkTxReference = default; + Option ownerName = default; + Option paymentAccountReference = default; + Option paymentMethod = default; + Option paymentMethodVariant = default; + Option payoutEligible = default; + Option realtimeAccountUpdaterStatus = default; + Option receiptFreeText = default; + Option recurringContractTypes = default; + Option recurringFirstPspReference = default; + Option recurringRecurringDetailReference = default; + Option recurringShopperReference = default; + Option recurringProcessingModel = default; + Option referred = default; + Option refusalReasonRaw = default; + Option requestAmount = default; + Option requestCurrencyCode = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option terminalId = default; + Option threeDAuthenticated = default; + Option threeDAuthenticatedResponse = default; + Option threeDOffered = default; + Option threeDOfferedResponse = default; + Option threeDSVersion = default; + Option tokenizationShopperReference = default; + Option tokenizationStoreOperationType = default; + Option tokenizationStoredPaymentMethodId = default; + Option visaTransactionId = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerAccountCode": + acquirerAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerCode": + acquirerCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerReference": + acquirerReference = new Option(utf8JsonReader.GetString()!); + break; + case "alias": + alias = new Option(utf8JsonReader.GetString()!); + break; + case "aliasType": + aliasType = new Option(utf8JsonReader.GetString()!); + break; + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "authorisationMid": + authorisationMid = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountCurrency": + authorisedAmountCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountValue": + authorisedAmountValue = new Option(utf8JsonReader.GetString()!); + break; + case "avsResult": + avsResult = new Option(utf8JsonReader.GetString()!); + break; + case "avsResultRaw": + avsResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "coBrandedWith": + coBrandedWith = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResult": + cvcResult = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResultRaw": + cvcResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "expiryDate": + expiryDate = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsCurrency": + extraCostsCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsValue": + extraCostsValue = new Option(utf8JsonReader.GetString()!); + break; + case "fraudCheck-[itemNr]-[FraudCheckname]": + fraudCheckItemNrFraudCheckname = new Option(utf8JsonReader.GetString()!); + break; + case "fraudManualReview": + fraudManualReview = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResultType": + string? fraudResultTypeRawValue = utf8JsonReader.GetString(); + fraudResultType = new Option(ResponseAdditionalDataCommon.FraudResultTypeEnum.FromStringOrDefault(fraudResultTypeRawValue)); + break; + case "fraudRiskLevel": + string? fraudRiskLevelRawValue = utf8JsonReader.GetString(); + fraudRiskLevel = new Option(ResponseAdditionalDataCommon.FraudRiskLevelEnum.FromStringOrDefault(fraudRiskLevelRawValue)); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "fundsAvailability": + fundsAvailability = new Option(utf8JsonReader.GetString()!); + break; + case "inferredRefusalReason": + inferredRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "isCardCommercial": + isCardCommercial = new Option(utf8JsonReader.GetString()!); + break; + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + case "liabilityShift": + liabilityShift = new Option(utf8JsonReader.GetString()!); + break; + case "mcBankNetReferenceNumber": + mcBankNetReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAdviceCode": + merchantAdviceCode = new Option(utf8JsonReader.GetString()!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccountReference": + paymentAccountReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodVariant": + paymentMethodVariant = new Option(utf8JsonReader.GetString()!); + break; + case "payoutEligible": + payoutEligible = new Option(utf8JsonReader.GetString()!); + break; + case "realtimeAccountUpdaterStatus": + realtimeAccountUpdaterStatus = new Option(utf8JsonReader.GetString()!); + break; + case "receiptFreeText": + receiptFreeText = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.contractTypes": + recurringContractTypes = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.firstPspReference": + recurringFirstPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.recurringDetailReference": + recurringRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.shopperReference": + recurringShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(ResponseAdditionalDataCommon.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "referred": + referred = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReasonRaw": + refusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "requestAmount": + requestAmount = new Option(utf8JsonReader.GetString()!); + break; + case "requestCurrencyCode": + requestCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + shopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticated": + threeDAuthenticated = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticatedResponse": + threeDAuthenticatedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOffered": + threeDOffered = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOfferedResponse": + threeDOfferedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.shopperReference": + tokenizationShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.store.operationType": + string? tokenizationStoreOperationTypeRawValue = utf8JsonReader.GetString(); + tokenizationStoreOperationType = new Option(ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.FromStringOrDefault(tokenizationStoreOperationTypeRawValue)); + break; + case "tokenization.storedPaymentMethodId": + tokenizationStoredPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "visaTransactionId": + visaTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCommon(acquirerAccountCode, acquirerCode, acquirerReference, alias, aliasType, authCode, authorisationMid, authorisedAmountCurrency, authorisedAmountValue, avsResult, avsResultRaw, bic, coBrandedWith, cvcResult, cvcResultRaw, dsTransID, eci, expiryDate, extraCostsCurrency, extraCostsValue, fraudCheckItemNrFraudCheckname, fraudManualReview, fraudResultType, fraudRiskLevel, fundingSource, fundsAvailability, inferredRefusalReason, isCardCommercial, issuerCountry, liabilityShift, mcBankNetReferenceNumber, merchantAdviceCode, merchantReference, networkTxReference, ownerName, paymentAccountReference, paymentMethod, paymentMethodVariant, payoutEligible, realtimeAccountUpdaterStatus, receiptFreeText, recurringContractTypes, recurringFirstPspReference, recurringRecurringDetailReference, recurringShopperReference, recurringProcessingModel, referred, refusalReasonRaw, requestAmount, requestCurrencyCode, shopperInteraction, shopperReference, terminalId, threeDAuthenticated, threeDAuthenticatedResponse, threeDOffered, threeDOfferedResponse, threeDSVersion, tokenizationShopperReference, tokenizationStoreOperationType, tokenizationStoredPaymentMethodId, visaTransactionId, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCommon, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCommon._AcquirerAccountCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerAccountCode != null) + writer.WriteString("acquirerAccountCode", responseAdditionalDataCommon.AcquirerAccountCode); + + if (responseAdditionalDataCommon._AcquirerCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerCode != null) + writer.WriteString("acquirerCode", responseAdditionalDataCommon.AcquirerCode); + + if (responseAdditionalDataCommon._AcquirerReferenceOption.IsSet) + if (responseAdditionalDataCommon.AcquirerReference != null) + writer.WriteString("acquirerReference", responseAdditionalDataCommon.AcquirerReference); + + if (responseAdditionalDataCommon._AliasOption.IsSet) + if (responseAdditionalDataCommon.Alias != null) + writer.WriteString("alias", responseAdditionalDataCommon.Alias); + + if (responseAdditionalDataCommon._AliasTypeOption.IsSet) + if (responseAdditionalDataCommon.AliasType != null) + writer.WriteString("aliasType", responseAdditionalDataCommon.AliasType); + + if (responseAdditionalDataCommon._AuthCodeOption.IsSet) + if (responseAdditionalDataCommon.AuthCode != null) + writer.WriteString("authCode", responseAdditionalDataCommon.AuthCode); + + if (responseAdditionalDataCommon._AuthorisationMidOption.IsSet) + if (responseAdditionalDataCommon.AuthorisationMid != null) + writer.WriteString("authorisationMid", responseAdditionalDataCommon.AuthorisationMid); + + if (responseAdditionalDataCommon._AuthorisedAmountCurrencyOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountCurrency != null) + writer.WriteString("authorisedAmountCurrency", responseAdditionalDataCommon.AuthorisedAmountCurrency); + + if (responseAdditionalDataCommon._AuthorisedAmountValueOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountValue != null) + writer.WriteString("authorisedAmountValue", responseAdditionalDataCommon.AuthorisedAmountValue); + + if (responseAdditionalDataCommon._AvsResultOption.IsSet) + if (responseAdditionalDataCommon.AvsResult != null) + writer.WriteString("avsResult", responseAdditionalDataCommon.AvsResult); + + if (responseAdditionalDataCommon._AvsResultRawOption.IsSet) + if (responseAdditionalDataCommon.AvsResultRaw != null) + writer.WriteString("avsResultRaw", responseAdditionalDataCommon.AvsResultRaw); + + if (responseAdditionalDataCommon._BicOption.IsSet) + if (responseAdditionalDataCommon.Bic != null) + writer.WriteString("bic", responseAdditionalDataCommon.Bic); + + if (responseAdditionalDataCommon._CoBrandedWithOption.IsSet) + if (responseAdditionalDataCommon.CoBrandedWith != null) + writer.WriteString("coBrandedWith", responseAdditionalDataCommon.CoBrandedWith); + + if (responseAdditionalDataCommon._CvcResultOption.IsSet) + if (responseAdditionalDataCommon.CvcResult != null) + writer.WriteString("cvcResult", responseAdditionalDataCommon.CvcResult); + + if (responseAdditionalDataCommon._CvcResultRawOption.IsSet) + if (responseAdditionalDataCommon.CvcResultRaw != null) + writer.WriteString("cvcResultRaw", responseAdditionalDataCommon.CvcResultRaw); + + if (responseAdditionalDataCommon._DsTransIDOption.IsSet) + if (responseAdditionalDataCommon.DsTransID != null) + writer.WriteString("dsTransID", responseAdditionalDataCommon.DsTransID); + + if (responseAdditionalDataCommon._EciOption.IsSet) + if (responseAdditionalDataCommon.Eci != null) + writer.WriteString("eci", responseAdditionalDataCommon.Eci); + + if (responseAdditionalDataCommon._ExpiryDateOption.IsSet) + if (responseAdditionalDataCommon.ExpiryDate != null) + writer.WriteString("expiryDate", responseAdditionalDataCommon.ExpiryDate); + + if (responseAdditionalDataCommon._ExtraCostsCurrencyOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsCurrency != null) + writer.WriteString("extraCostsCurrency", responseAdditionalDataCommon.ExtraCostsCurrency); + + if (responseAdditionalDataCommon._ExtraCostsValueOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsValue != null) + writer.WriteString("extraCostsValue", responseAdditionalDataCommon.ExtraCostsValue); + + if (responseAdditionalDataCommon._FraudCheckItemNrFraudChecknameOption.IsSet) + if (responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname != null) + writer.WriteString("fraudCheck-[itemNr]-[FraudCheckname]", responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname); + + if (responseAdditionalDataCommon._FraudManualReviewOption.IsSet) + if (responseAdditionalDataCommon.FraudManualReview != null) + writer.WriteString("fraudManualReview", responseAdditionalDataCommon.FraudManualReview); + + if (responseAdditionalDataCommon._FraudResultTypeOption.IsSet && responseAdditionalDataCommon.FraudResultType != null) + { + string? fraudResultTypeRawValue = ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommon._FraudResultTypeOption.Value!.Value); + writer.WriteString("fraudResultType", fraudResultTypeRawValue); + } + + if (responseAdditionalDataCommon._FraudRiskLevelOption.IsSet && responseAdditionalDataCommon.FraudRiskLevel != null) + { + string? fraudRiskLevelRawValue = ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommon._FraudRiskLevelOption.Value!.Value); + writer.WriteString("fraudRiskLevel", fraudRiskLevelRawValue); + } + + if (responseAdditionalDataCommon._FundingSourceOption.IsSet) + if (responseAdditionalDataCommon.FundingSource != null) + writer.WriteString("fundingSource", responseAdditionalDataCommon.FundingSource); + + if (responseAdditionalDataCommon._FundsAvailabilityOption.IsSet) + if (responseAdditionalDataCommon.FundsAvailability != null) + writer.WriteString("fundsAvailability", responseAdditionalDataCommon.FundsAvailability); + + if (responseAdditionalDataCommon._InferredRefusalReasonOption.IsSet) + if (responseAdditionalDataCommon.InferredRefusalReason != null) + writer.WriteString("inferredRefusalReason", responseAdditionalDataCommon.InferredRefusalReason); + + if (responseAdditionalDataCommon._IsCardCommercialOption.IsSet) + if (responseAdditionalDataCommon.IsCardCommercial != null) + writer.WriteString("isCardCommercial", responseAdditionalDataCommon.IsCardCommercial); + + if (responseAdditionalDataCommon._IssuerCountryOption.IsSet) + if (responseAdditionalDataCommon.IssuerCountry != null) + writer.WriteString("issuerCountry", responseAdditionalDataCommon.IssuerCountry); + + if (responseAdditionalDataCommon._LiabilityShiftOption.IsSet) + if (responseAdditionalDataCommon.LiabilityShift != null) + writer.WriteString("liabilityShift", responseAdditionalDataCommon.LiabilityShift); + + if (responseAdditionalDataCommon._McBankNetReferenceNumberOption.IsSet) + if (responseAdditionalDataCommon.McBankNetReferenceNumber != null) + writer.WriteString("mcBankNetReferenceNumber", responseAdditionalDataCommon.McBankNetReferenceNumber); + + if (responseAdditionalDataCommon._MerchantAdviceCodeOption.IsSet) + if (responseAdditionalDataCommon.MerchantAdviceCode != null) + writer.WriteString("merchantAdviceCode", responseAdditionalDataCommon.MerchantAdviceCode); + + if (responseAdditionalDataCommon._MerchantReferenceOption.IsSet) + if (responseAdditionalDataCommon.MerchantReference != null) + writer.WriteString("merchantReference", responseAdditionalDataCommon.MerchantReference); + + if (responseAdditionalDataCommon._NetworkTxReferenceOption.IsSet) + if (responseAdditionalDataCommon.NetworkTxReference != null) + writer.WriteString("networkTxReference", responseAdditionalDataCommon.NetworkTxReference); + + if (responseAdditionalDataCommon._OwnerNameOption.IsSet) + if (responseAdditionalDataCommon.OwnerName != null) + writer.WriteString("ownerName", responseAdditionalDataCommon.OwnerName); + + if (responseAdditionalDataCommon._PaymentAccountReferenceOption.IsSet) + if (responseAdditionalDataCommon.PaymentAccountReference != null) + writer.WriteString("paymentAccountReference", responseAdditionalDataCommon.PaymentAccountReference); + + if (responseAdditionalDataCommon._PaymentMethodOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethod != null) + writer.WriteString("paymentMethod", responseAdditionalDataCommon.PaymentMethod); + + if (responseAdditionalDataCommon._PaymentMethodVariantOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethodVariant != null) + writer.WriteString("paymentMethodVariant", responseAdditionalDataCommon.PaymentMethodVariant); + + if (responseAdditionalDataCommon._PayoutEligibleOption.IsSet) + if (responseAdditionalDataCommon.PayoutEligible != null) + writer.WriteString("payoutEligible", responseAdditionalDataCommon.PayoutEligible); + + if (responseAdditionalDataCommon._RealtimeAccountUpdaterStatusOption.IsSet) + if (responseAdditionalDataCommon.RealtimeAccountUpdaterStatus != null) + writer.WriteString("realtimeAccountUpdaterStatus", responseAdditionalDataCommon.RealtimeAccountUpdaterStatus); + + if (responseAdditionalDataCommon._ReceiptFreeTextOption.IsSet) + if (responseAdditionalDataCommon.ReceiptFreeText != null) + writer.WriteString("receiptFreeText", responseAdditionalDataCommon.ReceiptFreeText); + + if (responseAdditionalDataCommon._RecurringContractTypesOption.IsSet) + if (responseAdditionalDataCommon.RecurringContractTypes != null) + writer.WriteString("recurring.contractTypes", responseAdditionalDataCommon.RecurringContractTypes); + + if (responseAdditionalDataCommon._RecurringFirstPspReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringFirstPspReference != null) + writer.WriteString("recurring.firstPspReference", responseAdditionalDataCommon.RecurringFirstPspReference); + + if (responseAdditionalDataCommon._RecurringRecurringDetailReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringRecurringDetailReference != null) + writer.WriteString("recurring.recurringDetailReference", responseAdditionalDataCommon.RecurringRecurringDetailReference); + + if (responseAdditionalDataCommon._RecurringShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringShopperReference != null) + writer.WriteString("recurring.shopperReference", responseAdditionalDataCommon.RecurringShopperReference); + + if (responseAdditionalDataCommon._RecurringProcessingModelOption.IsSet && responseAdditionalDataCommon.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommon._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (responseAdditionalDataCommon._ReferredOption.IsSet) + if (responseAdditionalDataCommon.Referred != null) + writer.WriteString("referred", responseAdditionalDataCommon.Referred); + + if (responseAdditionalDataCommon._RefusalReasonRawOption.IsSet) + if (responseAdditionalDataCommon.RefusalReasonRaw != null) + writer.WriteString("refusalReasonRaw", responseAdditionalDataCommon.RefusalReasonRaw); + + if (responseAdditionalDataCommon._RequestAmountOption.IsSet) + if (responseAdditionalDataCommon.RequestAmount != null) + writer.WriteString("requestAmount", responseAdditionalDataCommon.RequestAmount); + + if (responseAdditionalDataCommon._RequestCurrencyCodeOption.IsSet) + if (responseAdditionalDataCommon.RequestCurrencyCode != null) + writer.WriteString("requestCurrencyCode", responseAdditionalDataCommon.RequestCurrencyCode); + + if (responseAdditionalDataCommon._ShopperInteractionOption.IsSet) + if (responseAdditionalDataCommon.ShopperInteraction != null) + writer.WriteString("shopperInteraction", responseAdditionalDataCommon.ShopperInteraction); + + if (responseAdditionalDataCommon._ShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.ShopperReference != null) + writer.WriteString("shopperReference", responseAdditionalDataCommon.ShopperReference); + + if (responseAdditionalDataCommon._TerminalIdOption.IsSet) + if (responseAdditionalDataCommon.TerminalId != null) + writer.WriteString("terminalId", responseAdditionalDataCommon.TerminalId); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticated != null) + writer.WriteString("threeDAuthenticated", responseAdditionalDataCommon.ThreeDAuthenticated); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticatedResponse != null) + writer.WriteString("threeDAuthenticatedResponse", responseAdditionalDataCommon.ThreeDAuthenticatedResponse); + + if (responseAdditionalDataCommon._ThreeDOfferedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOffered != null) + writer.WriteString("threeDOffered", responseAdditionalDataCommon.ThreeDOffered); + + if (responseAdditionalDataCommon._ThreeDOfferedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOfferedResponse != null) + writer.WriteString("threeDOfferedResponse", responseAdditionalDataCommon.ThreeDOfferedResponse); + + if (responseAdditionalDataCommon._ThreeDSVersionOption.IsSet) + if (responseAdditionalDataCommon.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", responseAdditionalDataCommon.ThreeDSVersion); + + if (responseAdditionalDataCommon._TokenizationShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.TokenizationShopperReference != null) + writer.WriteString("tokenization.shopperReference", responseAdditionalDataCommon.TokenizationShopperReference); + + if (responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.IsSet && responseAdditionalDataCommon.TokenizationStoreOperationType != null) + { + string? tokenizationStoreOperationTypeRawValue = ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.Value!.Value); + writer.WriteString("tokenization.store.operationType", tokenizationStoreOperationTypeRawValue); + } + + if (responseAdditionalDataCommon._TokenizationStoredPaymentMethodIdOption.IsSet) + if (responseAdditionalDataCommon.TokenizationStoredPaymentMethodId != null) + writer.WriteString("tokenization.storedPaymentMethodId", responseAdditionalDataCommon.TokenizationStoredPaymentMethodId); + + if (responseAdditionalDataCommon._VisaTransactionIdOption.IsSet) + if (responseAdditionalDataCommon.VisaTransactionId != null) + writer.WriteString("visaTransactionId", responseAdditionalDataCommon.VisaTransactionId); + + if (responseAdditionalDataCommon._XidOption.IsSet) + if (responseAdditionalDataCommon.Xid != null) + writer.WriteString("xid", responseAdditionalDataCommon.Xid); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataDomesticError.cs b/Adyen/Checkout/Models/ResponseAdditionalDataDomesticError.cs new file mode 100644 index 000000000..58c374411 --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataDomesticError.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataDomesticError. + /// + public partial class ResponseAdditionalDataDomesticError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonConstructor] + public ResponseAdditionalDataDomesticError(Option domesticRefusalReasonRaw = default, Option domesticShopperAdvice = default) + { + _DomesticRefusalReasonRawOption = domesticRefusalReasonRaw; + _DomesticShopperAdviceOption = domesticShopperAdvice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataDomesticError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticRefusalReasonRawOption { get; private set; } + + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + [JsonPropertyName("domesticRefusalReasonRaw")] + public string? DomesticRefusalReasonRaw { get { return this._DomesticRefusalReasonRawOption; } set { this._DomesticRefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticShopperAdviceOption { get; private set; } + + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonPropertyName("domesticShopperAdvice")] + public string? DomesticShopperAdvice { get { return this._DomesticShopperAdviceOption; } set { this._DomesticShopperAdviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataDomesticError {\n"); + sb.Append(" DomesticRefusalReasonRaw: ").Append(DomesticRefusalReasonRaw).Append("\n"); + sb.Append(" DomesticShopperAdvice: ").Append(DomesticShopperAdvice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataDomesticErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataDomesticError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option domesticRefusalReasonRaw = default; + Option domesticShopperAdvice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domesticRefusalReasonRaw": + domesticRefusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "domesticShopperAdvice": + domesticShopperAdvice = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataDomesticError(domesticRefusalReasonRaw, domesticShopperAdvice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataDomesticError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataDomesticError._DomesticRefusalReasonRawOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticRefusalReasonRaw != null) + writer.WriteString("domesticRefusalReasonRaw", responseAdditionalDataDomesticError.DomesticRefusalReasonRaw); + + if (responseAdditionalDataDomesticError._DomesticShopperAdviceOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticShopperAdvice != null) + writer.WriteString("domesticShopperAdvice", responseAdditionalDataDomesticError.DomesticShopperAdvice); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataInstallments.cs b/Adyen/Checkout/Models/ResponseAdditionalDataInstallments.cs new file mode 100644 index 000000000..2f9ff3a44 --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataInstallments.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataInstallments. + /// + public partial class ResponseAdditionalDataInstallments : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// Annual interest rate. + /// First Installment Amount in minor units. + /// Installment fee amount in minor units. + /// Interest rate for the installment period. + /// Maximum number of installments possible for this payment. + /// Minimum number of installments possible for this payment. + /// Total number of installments possible for this payment. + /// Subsequent Installment Amount in minor units. + /// Total amount in minor units. + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonConstructor] + public ResponseAdditionalDataInstallments(Option installmentPaymentDataInstallmentType = default, Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default, Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default, Option installmentPaymentDataOptionItemNrInstallmentFee = default, Option installmentPaymentDataOptionItemNrInterestRate = default, Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default, Option installmentPaymentDataOptionItemNrTotalAmountDue = default, Option installmentPaymentDataPaymentOptions = default, Option installmentsValue = default) + { + _InstallmentPaymentDataInstallmentTypeOption = installmentPaymentDataInstallmentType; + _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = installmentPaymentDataOptionItemNrAnnualPercentageRate; + _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = installmentPaymentDataOptionItemNrFirstInstallmentAmount; + _InstallmentPaymentDataOptionItemNrInstallmentFeeOption = installmentPaymentDataOptionItemNrInstallmentFee; + _InstallmentPaymentDataOptionItemNrInterestRateOption = installmentPaymentDataOptionItemNrInterestRate; + _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMaximumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMinimumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = installmentPaymentDataOptionItemNrSubsequentInstallmentAmount; + _InstallmentPaymentDataOptionItemNrTotalAmountDueOption = installmentPaymentDataOptionItemNrTotalAmountDue; + _InstallmentPaymentDataPaymentOptionsOption = installmentPaymentDataPaymentOptions; + _InstallmentsValueOption = installmentsValue; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataInstallments() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataInstallmentTypeOption { get; private set; } + + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + [JsonPropertyName("installmentPaymentData.installmentType")] + public string? InstallmentPaymentDataInstallmentType { get { return this._InstallmentPaymentDataInstallmentTypeOption; } set { this._InstallmentPaymentDataInstallmentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption { get; private set; } + + /// + /// Annual interest rate. + /// + /// Annual interest rate. + [JsonPropertyName("installmentPaymentData.option[itemNr].annualPercentageRate")] + public string? InstallmentPaymentDataOptionItemNrAnnualPercentageRate { get { return this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption; } set { this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption { get; private set; } + + /// + /// First Installment Amount in minor units. + /// + /// First Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].firstInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrFirstInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInstallmentFeeOption { get; private set; } + + /// + /// Installment fee amount in minor units. + /// + /// Installment fee amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].installmentFee")] + public string? InstallmentPaymentDataOptionItemNrInstallmentFee { get { return this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption; } set { this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInterestRateOption { get; private set; } + + /// + /// Interest rate for the installment period. + /// + /// Interest rate for the installment period. + [JsonPropertyName("installmentPaymentData.option[itemNr].interestRate")] + public string? InstallmentPaymentDataOptionItemNrInterestRate { get { return this._InstallmentPaymentDataOptionItemNrInterestRateOption; } set { this._InstallmentPaymentDataOptionItemNrInterestRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption { get; private set; } + + /// + /// Maximum number of installments possible for this payment. + /// + /// Maximum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].maximumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption { get; private set; } + + /// + /// Minimum number of installments possible for this payment. + /// + /// Minimum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].minimumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption { get; private set; } + + /// + /// Total number of installments possible for this payment. + /// + /// Total number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].numberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption { get; private set; } + + /// + /// Subsequent Installment Amount in minor units. + /// + /// Subsequent Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].subsequentInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrTotalAmountDueOption { get; private set; } + + /// + /// Total amount in minor units. + /// + /// Total amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].totalAmountDue")] + public string? InstallmentPaymentDataOptionItemNrTotalAmountDue { get { return this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption; } set { this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataPaymentOptionsOption { get; private set; } + + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + [JsonPropertyName("installmentPaymentData.paymentOptions")] + public string? InstallmentPaymentDataPaymentOptions { get { return this._InstallmentPaymentDataPaymentOptionsOption; } set { this._InstallmentPaymentDataPaymentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsValueOption { get; private set; } + + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonPropertyName("installments.value")] + public string? InstallmentsValue { get { return this._InstallmentsValueOption; } set { this._InstallmentsValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataInstallments {\n"); + sb.Append(" InstallmentPaymentDataInstallmentType: ").Append(InstallmentPaymentDataInstallmentType).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrAnnualPercentageRate: ").Append(InstallmentPaymentDataOptionItemNrAnnualPercentageRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrFirstInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrFirstInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInstallmentFee: ").Append(InstallmentPaymentDataOptionItemNrInstallmentFee).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInterestRate: ").Append(InstallmentPaymentDataOptionItemNrInterestRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrTotalAmountDue: ").Append(InstallmentPaymentDataOptionItemNrTotalAmountDue).Append("\n"); + sb.Append(" InstallmentPaymentDataPaymentOptions: ").Append(InstallmentPaymentDataPaymentOptions).Append("\n"); + sb.Append(" InstallmentsValue: ").Append(InstallmentsValue).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataInstallmentsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataInstallments Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option installmentPaymentDataInstallmentType = default; + Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default; + Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrInstallmentFee = default; + Option installmentPaymentDataOptionItemNrInterestRate = default; + Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrTotalAmountDue = default; + Option installmentPaymentDataPaymentOptions = default; + Option installmentsValue = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "installmentPaymentData.installmentType": + installmentPaymentDataInstallmentType = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].annualPercentageRate": + installmentPaymentDataOptionItemNrAnnualPercentageRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].firstInstallmentAmount": + installmentPaymentDataOptionItemNrFirstInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].installmentFee": + installmentPaymentDataOptionItemNrInstallmentFee = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].interestRate": + installmentPaymentDataOptionItemNrInterestRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].maximumNumberOfInstallments": + installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].minimumNumberOfInstallments": + installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].numberOfInstallments": + installmentPaymentDataOptionItemNrNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].subsequentInstallmentAmount": + installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].totalAmountDue": + installmentPaymentDataOptionItemNrTotalAmountDue = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.paymentOptions": + installmentPaymentDataPaymentOptions = new Option(utf8JsonReader.GetString()!); + break; + case "installments.value": + installmentsValue = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataInstallments(installmentPaymentDataInstallmentType, installmentPaymentDataOptionItemNrAnnualPercentageRate, installmentPaymentDataOptionItemNrFirstInstallmentAmount, installmentPaymentDataOptionItemNrInstallmentFee, installmentPaymentDataOptionItemNrInterestRate, installmentPaymentDataOptionItemNrMaximumNumberOfInstallments, installmentPaymentDataOptionItemNrMinimumNumberOfInstallments, installmentPaymentDataOptionItemNrNumberOfInstallments, installmentPaymentDataOptionItemNrSubsequentInstallmentAmount, installmentPaymentDataOptionItemNrTotalAmountDue, installmentPaymentDataPaymentOptions, installmentsValue); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataInstallments, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataInstallments._InstallmentPaymentDataInstallmentTypeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType != null) + writer.WriteString("installmentPaymentData.installmentType", responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].annualPercentageRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].firstInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInstallmentFeeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee != null) + writer.WriteString("installmentPaymentData.option[itemNr].installmentFee", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInterestRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].interestRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].maximumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].minimumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].numberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].subsequentInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrTotalAmountDueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue != null) + writer.WriteString("installmentPaymentData.option[itemNr].totalAmountDue", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataPaymentOptionsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions != null) + writer.WriteString("installmentPaymentData.paymentOptions", responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions); + + if (responseAdditionalDataInstallments._InstallmentsValueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentsValue != null) + writer.WriteString("installments.value", responseAdditionalDataInstallments.InstallmentsValue); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataNetworkTokens.cs b/Adyen/Checkout/Models/ResponseAdditionalDataNetworkTokens.cs new file mode 100644 index 000000000..cdd33075f --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataNetworkTokens.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataNetworkTokens. + /// + public partial class ResponseAdditionalDataNetworkTokens : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether a network token is available for the specified card. + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// The last four digits of a network token. + [JsonConstructor] + public ResponseAdditionalDataNetworkTokens(Option networkTokenAvailable = default, Option networkTokenBin = default, Option networkTokenTokenSummary = default) + { + _NetworkTokenAvailableOption = networkTokenAvailable; + _NetworkTokenBinOption = networkTokenBin; + _NetworkTokenTokenSummaryOption = networkTokenTokenSummary; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataNetworkTokens() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenAvailableOption { get; private set; } + + /// + /// Indicates whether a network token is available for the specified card. + /// + /// Indicates whether a network token is available for the specified card. + [JsonPropertyName("networkToken.available")] + public string? NetworkTokenAvailable { get { return this._NetworkTokenAvailableOption; } set { this._NetworkTokenAvailableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenBinOption { get; private set; } + + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + [JsonPropertyName("networkToken.bin")] + public string? NetworkTokenBin { get { return this._NetworkTokenBinOption; } set { this._NetworkTokenBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenTokenSummaryOption { get; private set; } + + /// + /// The last four digits of a network token. + /// + /// The last four digits of a network token. + [JsonPropertyName("networkToken.tokenSummary")] + public string? NetworkTokenTokenSummary { get { return this._NetworkTokenTokenSummaryOption; } set { this._NetworkTokenTokenSummaryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataNetworkTokens {\n"); + sb.Append(" NetworkTokenAvailable: ").Append(NetworkTokenAvailable).Append("\n"); + sb.Append(" NetworkTokenBin: ").Append(NetworkTokenBin).Append("\n"); + sb.Append(" NetworkTokenTokenSummary: ").Append(NetworkTokenTokenSummary).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataNetworkTokensJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataNetworkTokens Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option networkTokenAvailable = default; + Option networkTokenBin = default; + Option networkTokenTokenSummary = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "networkToken.available": + networkTokenAvailable = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.bin": + networkTokenBin = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.tokenSummary": + networkTokenTokenSummary = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataNetworkTokens(networkTokenAvailable, networkTokenBin, networkTokenTokenSummary); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataNetworkTokens, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataNetworkTokens._NetworkTokenAvailableOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenAvailable != null) + writer.WriteString("networkToken.available", responseAdditionalDataNetworkTokens.NetworkTokenAvailable); + + if (responseAdditionalDataNetworkTokens._NetworkTokenBinOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenBin != null) + writer.WriteString("networkToken.bin", responseAdditionalDataNetworkTokens.NetworkTokenBin); + + if (responseAdditionalDataNetworkTokens._NetworkTokenTokenSummaryOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary != null) + writer.WriteString("networkToken.tokenSummary", responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataOpi.cs b/Adyen/Checkout/Models/ResponseAdditionalDataOpi.cs new file mode 100644 index 000000000..eb9deaeda --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataOpi.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataOpi. + /// + public partial class ResponseAdditionalDataOpi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonConstructor] + public ResponseAdditionalDataOpi(Option opiTransToken = default) + { + _OpiTransTokenOption = opiTransToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataOpi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiTransTokenOption { get; private set; } + + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonPropertyName("opi.transToken")] + public string? OpiTransToken { get { return this._OpiTransTokenOption; } set { this._OpiTransTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataOpi {\n"); + sb.Append(" OpiTransToken: ").Append(OpiTransToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataOpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataOpi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option opiTransToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "opi.transToken": + opiTransToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataOpi(opiTransToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataOpi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataOpi._OpiTransTokenOption.IsSet) + if (responseAdditionalDataOpi.OpiTransToken != null) + writer.WriteString("opi.transToken", responseAdditionalDataOpi.OpiTransToken); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataSepa.cs b/Adyen/Checkout/Models/ResponseAdditionalDataSepa.cs new file mode 100644 index 000000000..a2b9ddf23 --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataSepa.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataSepa. + /// + public partial class ResponseAdditionalDataSepa : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// Its value corresponds to the pspReference value of the transaction. + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonConstructor] + public ResponseAdditionalDataSepa(Option sepadirectdebitDateOfSignature = default, Option sepadirectdebitMandateId = default, Option sepadirectdebitSequenceType = default) + { + _SepadirectdebitDateOfSignatureOption = sepadirectdebitDateOfSignature; + _SepadirectdebitMandateIdOption = sepadirectdebitMandateId; + _SepadirectdebitSequenceTypeOption = sepadirectdebitSequenceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSepa() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitDateOfSignatureOption { get; private set; } + + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// + /// The transaction signature date. Format: yyyy-MM-dd + [JsonPropertyName("sepadirectdebit.dateOfSignature")] + public string? SepadirectdebitDateOfSignature { get { return this._SepadirectdebitDateOfSignatureOption; } set { this._SepadirectdebitDateOfSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitMandateIdOption { get; private set; } + + /// + /// Its value corresponds to the pspReference value of the transaction. + /// + /// Its value corresponds to the pspReference value of the transaction. + [JsonPropertyName("sepadirectdebit.mandateId")] + public string? SepadirectdebitMandateId { get { return this._SepadirectdebitMandateIdOption; } set { this._SepadirectdebitMandateIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitSequenceTypeOption { get; private set; } + + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonPropertyName("sepadirectdebit.sequenceType")] + public string? SepadirectdebitSequenceType { get { return this._SepadirectdebitSequenceTypeOption; } set { this._SepadirectdebitSequenceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSepa {\n"); + sb.Append(" SepadirectdebitDateOfSignature: ").Append(SepadirectdebitDateOfSignature).Append("\n"); + sb.Append(" SepadirectdebitMandateId: ").Append(SepadirectdebitMandateId).Append("\n"); + sb.Append(" SepadirectdebitSequenceType: ").Append(SepadirectdebitSequenceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSepaJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSepa Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sepadirectdebitDateOfSignature = default; + Option sepadirectdebitMandateId = default; + Option sepadirectdebitSequenceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sepadirectdebit.dateOfSignature": + sepadirectdebitDateOfSignature = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.mandateId": + sepadirectdebitMandateId = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.sequenceType": + sepadirectdebitSequenceType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSepa(sepadirectdebitDateOfSignature, sepadirectdebitMandateId, sepadirectdebitSequenceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSepa, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSepa._SepadirectdebitDateOfSignatureOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitDateOfSignature != null) + writer.WriteString("sepadirectdebit.dateOfSignature", responseAdditionalDataSepa.SepadirectdebitDateOfSignature); + + if (responseAdditionalDataSepa._SepadirectdebitMandateIdOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitMandateId != null) + writer.WriteString("sepadirectdebit.mandateId", responseAdditionalDataSepa.SepadirectdebitMandateId); + + if (responseAdditionalDataSepa._SepadirectdebitSequenceTypeOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitSequenceType != null) + writer.WriteString("sepadirectdebit.sequenceType", responseAdditionalDataSepa.SepadirectdebitSequenceType); + } + } +} diff --git a/Adyen/Checkout/Models/ResponseAdditionalDataSwish.cs b/Adyen/Checkout/Models/ResponseAdditionalDataSwish.cs new file mode 100644 index 000000000..4d0ed163a --- /dev/null +++ b/Adyen/Checkout/Models/ResponseAdditionalDataSwish.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponseAdditionalDataSwish. + /// + public partial class ResponseAdditionalDataSwish : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A Swish shopper's telephone number. + [JsonConstructor] + public ResponseAdditionalDataSwish(Option swishPayerAlias = default) + { + _SwishPayerAliasOption = swishPayerAlias; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSwish() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SwishPayerAliasOption { get; private set; } + + /// + /// A Swish shopper's telephone number. + /// + /// A Swish shopper's telephone number. + [JsonPropertyName("swish.payerAlias")] + public string? SwishPayerAlias { get { return this._SwishPayerAliasOption; } set { this._SwishPayerAliasOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSwish {\n"); + sb.Append(" SwishPayerAlias: ").Append(SwishPayerAlias).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSwishJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSwish Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option swishPayerAlias = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "swish.payerAlias": + swishPayerAlias = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSwish(swishPayerAlias); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSwish, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSwish._SwishPayerAliasOption.IsSet) + if (responseAdditionalDataSwish.SwishPayerAlias != null) + writer.WriteString("swish.payerAlias", responseAdditionalDataSwish.SwishPayerAlias); + } + } +} diff --git a/Adyen/Checkout/Models/ResponsePaymentMethod.cs b/Adyen/Checkout/Models/ResponsePaymentMethod.cs new file mode 100644 index 000000000..8cffae60c --- /dev/null +++ b/Adyen/Checkout/Models/ResponsePaymentMethod.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ResponsePaymentMethod. + /// + public partial class ResponsePaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The card brand that the shopper used to pay. Only returned if `paymentMethod.type` is **scheme**. + /// The `paymentMethod.type` value used in the request. + [JsonConstructor] + public ResponsePaymentMethod(Option brand = default, Option type = default) + { + _BrandOption = brand; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponsePaymentMethod() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// The card brand that the shopper used to pay. Only returned if `paymentMethod.type` is **scheme**. + /// + /// The card brand that the shopper used to pay. Only returned if `paymentMethod.type` is **scheme**. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The `paymentMethod.type` value used in the request. + /// + /// The `paymentMethod.type` value used in the request. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponsePaymentMethod {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponsePaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponsePaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponsePaymentMethod(brand, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponsePaymentMethod responsePaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responsePaymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponsePaymentMethod responsePaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (responsePaymentMethod._BrandOption.IsSet) + if (responsePaymentMethod.Brand != null) + writer.WriteString("brand", responsePaymentMethod.Brand); + + if (responsePaymentMethod._TypeOption.IsSet) + if (responsePaymentMethod.Type != null) + writer.WriteString("type", responsePaymentMethod.Type); + } + } +} diff --git a/Adyen/Checkout/Models/Result.cs b/Adyen/Checkout/Models/Result.cs new file mode 100644 index 000000000..2bad55f98 --- /dev/null +++ b/Adyen/Checkout/Models/Result.cs @@ -0,0 +1,190 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Defines Result + /// + public enum Result + { + /// + /// Enum VALID for value: VALID + /// + VALID = 1, + + /// + /// Enum INVALID for value: INVALID + /// + INVALID = 2, + + /// + /// Enum UNKNOWN for value: UNKNOWN + /// + UNKNOWN = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class ResultValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static Result FromString(string value) + { + if (value.Equals("VALID")) + return Result.VALID; + + if (value.Equals("INVALID")) + return Result.INVALID; + + if (value.Equals("UNKNOWN")) + return Result.UNKNOWN; + + throw new NotImplementedException($"Could not convert value to type Result: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static Result? FromStringOrDefault(string value) + { + if (value.Equals("VALID")) + return Result.VALID; + + if (value.Equals("INVALID")) + return Result.INVALID; + + if (value.Equals("UNKNOWN")) + return Result.UNKNOWN; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(Result value) + { + if (value == Result.VALID) + return "VALID"; + + if (value == Result.INVALID) + return "INVALID"; + + if (value == Result.UNKNOWN) + return "UNKNOWN"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ResultJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override Result Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Result? result = rawValue == null + ? null + : ResultValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Result to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Result result, JsonSerializerOptions options) + { + writer.WriteStringValue(ResultValueConverter.ToJsonValue(result).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ResultNullableJsonConverter : JsonConverter + { + /// + /// Returns a Result from the Json object + /// + /// + /// + /// + /// + public override Result? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Result? result = rawValue == null + ? null + : ResultValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Result to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Result? result, JsonSerializerOptions options) + { + writer.WriteStringValue(result.HasValue ? ResultValueConverter.ToJsonValue(result.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/Checkout/Models/RiskData.cs b/Adyen/Checkout/Models/RiskData.cs new file mode 100644 index 000000000..d4a735c7a --- /dev/null +++ b/Adyen/Checkout/Models/RiskData.cs @@ -0,0 +1,258 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// RiskData. + /// + public partial class RiskData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains client-side data, like the device fingerprint, cookies, and specific browser settings. + /// Any custom fields used as part of the input to configured risk rules. + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// The risk profile to assign to this payment. When left empty, the merchant-level account's default risk profile will be applied. + [JsonConstructor] + public RiskData(Option clientData = default, Option?> customFields = default, Option fraudOffset = default, Option profileReference = default) + { + _ClientDataOption = clientData; + _CustomFieldsOption = customFields; + _FraudOffsetOption = fraudOffset; + _ProfileReferenceOption = profileReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RiskData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClientDataOption { get; private set; } + + /// + /// Contains client-side data, like the device fingerprint, cookies, and specific browser settings. + /// + /// Contains client-side data, like the device fingerprint, cookies, and specific browser settings. + [JsonPropertyName("clientData")] + public string? ClientData { get { return this._ClientDataOption; } set { this._ClientDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CustomFieldsOption { get; private set; } + + /// + /// Any custom fields used as part of the input to configured risk rules. + /// + /// Any custom fields used as part of the input to configured risk rules. + [JsonPropertyName("customFields")] + public Dictionary? CustomFields { get { return this._CustomFieldsOption; } set { this._CustomFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProfileReferenceOption { get; private set; } + + /// + /// The risk profile to assign to this payment. When left empty, the merchant-level account's default risk profile will be applied. + /// + /// The risk profile to assign to this payment. When left empty, the merchant-level account's default risk profile will be applied. + [JsonPropertyName("profileReference")] + public string? ProfileReference { get { return this._ProfileReferenceOption; } set { this._ProfileReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RiskData {\n"); + sb.Append(" ClientData: ").Append(ClientData).Append("\n"); + sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" ProfileReference: ").Append(ProfileReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ClientData (string) maxLength + if (this.ClientData != null && this.ClientData.Length > 5000) + { + yield return new ValidationResult("Invalid value for ClientData, length must be less than 5000.", new [] { "ClientData" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RiskDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RiskData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option clientData = default; + Option?> customFields = default; + Option fraudOffset = default; + Option profileReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "clientData": + clientData = new Option(utf8JsonReader.GetString()!); + break; + case "customFields": + customFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "profileReference": + profileReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RiskData(clientData, customFields, fraudOffset, profileReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RiskData riskData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, riskData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RiskData riskData, JsonSerializerOptions jsonSerializerOptions) + { + + if (riskData._ClientDataOption.IsSet) + if (riskData.ClientData != null) + writer.WriteString("clientData", riskData.ClientData); + + if (riskData._CustomFieldsOption.IsSet) + { + writer.WritePropertyName("customFields"); + JsonSerializer.Serialize(writer, riskData.CustomFields, jsonSerializerOptions); + } + if (riskData._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", riskData._FraudOffsetOption.Value!.Value); + + if (riskData._ProfileReferenceOption.IsSet) + if (riskData.ProfileReference != null) + writer.WriteString("profileReference", riskData.ProfileReference); + } + } +} diff --git a/Adyen/Checkout/Models/RivertyDetails.cs b/Adyen/Checkout/Models/RivertyDetails.cs new file mode 100644 index 000000000..3669113c3 --- /dev/null +++ b/Adyen/Checkout/Models/RivertyDetails.cs @@ -0,0 +1,540 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// RivertyDetails. + /// + public partial class RivertyDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address where to send the invoice. + /// The checkout attempt identifier. + /// The address where the goods should be delivered. + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// The iban number of the customer + /// Shopper name, date of birth, phone number, and email address. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The payment method subtype. + /// **riverty** (default to TypeEnum.Riverty) + [JsonConstructor] + public RivertyDetails(Option billingAddress = default, Option checkoutAttemptId = default, Option deliveryAddress = default, Option deviceFingerprint = default, Option iban = default, Option personalDetails = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option subtype = default, TypeEnum type = default) + { + _BillingAddressOption = billingAddress; + _CheckoutAttemptIdOption = checkoutAttemptId; + _DeliveryAddressOption = deliveryAddress; + _DeviceFingerprintOption = deviceFingerprint; + _IbanOption = iban; + _PersonalDetailsOption = personalDetails; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubtypeOption = subtype; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RivertyDetails() + { + } + + partial void OnCreated(); + + /// + /// **riverty** + /// + /// **riverty** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Riverty - riverty + /// + public static readonly TypeEnum Riverty = new("riverty"); + + /// + /// TypeEnum.RivertyAccount - riverty_account + /// + public static readonly TypeEnum RivertyAccount = new("riverty_account"); + + /// + /// TypeEnum.RivertyInstallments - riverty_installments + /// + public static readonly TypeEnum RivertyInstallments = new("riverty_installments"); + + /// + /// TypeEnum.SepadirectdebitRiverty - sepadirectdebit_riverty + /// + public static readonly TypeEnum SepadirectdebitRiverty = new("sepadirectdebit_riverty"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "riverty" => TypeEnum.Riverty, + "riverty_account" => TypeEnum.RivertyAccount, + "riverty_installments" => TypeEnum.RivertyInstallments, + "sepadirectdebit_riverty" => TypeEnum.SepadirectdebitRiverty, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Riverty) + return "riverty"; + + if (value == TypeEnum.RivertyAccount) + return "riverty_account"; + + if (value == TypeEnum.RivertyInstallments) + return "riverty_installments"; + + if (value == TypeEnum.SepadirectdebitRiverty) + return "sepadirectdebit_riverty"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **riverty** + /// + /// **riverty** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// The address where to send the invoice. + /// + /// The address where to send the invoice. + [JsonPropertyName("billingAddress")] + public string? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// The address where the goods should be delivered. + /// + /// The address where the goods should be delivered. + [JsonPropertyName("deliveryAddress")] + public string? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The iban number of the customer + /// + /// The iban number of the customer + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PersonalDetailsOption { get; private set; } + + /// + /// Shopper name, date of birth, phone number, and email address. + /// + /// Shopper name, date of birth, phone number, and email address. + [JsonPropertyName("personalDetails")] + public string? PersonalDetails { get { return this._PersonalDetailsOption; } set { this._PersonalDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// The payment method subtype. + /// + /// The payment method subtype. + [JsonPropertyName("subtype")] + public string? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RivertyDetails {\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Iban (string) maxLength + if (this.Iban != null && this.Iban.Length > 34) + { + yield return new ValidationResult("Invalid value for Iban, length must be less than 34.", new [] { "Iban" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RivertyDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RivertyDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddress = default; + Option checkoutAttemptId = default; + Option deliveryAddress = default; + Option deviceFingerprint = default; + Option iban = default; + Option personalDetails = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option subtype = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress": + billingAddress = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryAddress": + deliveryAddress = new Option(utf8JsonReader.GetString()!); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "personalDetails": + personalDetails = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + subtype = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(RivertyDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RivertyDetails.", nameof(type)); + + return new RivertyDetails(billingAddress, checkoutAttemptId, deliveryAddress, deviceFingerprint, iban, personalDetails, recurringDetailReference, storedPaymentMethodId, subtype, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RivertyDetails rivertyDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, rivertyDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RivertyDetails rivertyDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (rivertyDetails._BillingAddressOption.IsSet) + if (rivertyDetails.BillingAddress != null) + writer.WriteString("billingAddress", rivertyDetails.BillingAddress); + + if (rivertyDetails._CheckoutAttemptIdOption.IsSet) + if (rivertyDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", rivertyDetails.CheckoutAttemptId); + + if (rivertyDetails._DeliveryAddressOption.IsSet) + if (rivertyDetails.DeliveryAddress != null) + writer.WriteString("deliveryAddress", rivertyDetails.DeliveryAddress); + + if (rivertyDetails._DeviceFingerprintOption.IsSet) + if (rivertyDetails.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", rivertyDetails.DeviceFingerprint); + + if (rivertyDetails._IbanOption.IsSet) + if (rivertyDetails.Iban != null) + writer.WriteString("iban", rivertyDetails.Iban); + + if (rivertyDetails._PersonalDetailsOption.IsSet) + if (rivertyDetails.PersonalDetails != null) + writer.WriteString("personalDetails", rivertyDetails.PersonalDetails); + + if (rivertyDetails._RecurringDetailReferenceOption.IsSet) + if (rivertyDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", rivertyDetails.RecurringDetailReference); + + if (rivertyDetails._StoredPaymentMethodIdOption.IsSet) + if (rivertyDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", rivertyDetails.StoredPaymentMethodId); + + if (rivertyDetails._SubtypeOption.IsSet) + if (rivertyDetails.Subtype != null) + writer.WriteString("subtype", rivertyDetails.Subtype); + + if (rivertyDetails.Type != null) + { + string? typeRawValue = RivertyDetails.TypeEnum.ToJsonValue(rivertyDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/SDKEphemPubKey.cs b/Adyen/Checkout/Models/SDKEphemPubKey.cs new file mode 100644 index 000000000..c2acf6250 --- /dev/null +++ b/Adyen/Checkout/Models/SDKEphemPubKey.cs @@ -0,0 +1,252 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SDKEphemPubKey. + /// + public partial class SDKEphemPubKey : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + /// The `kty` value as received from the 3D Secure 2 SDK. + /// The `x` value as received from the 3D Secure 2 SDK. + /// The `y` value as received from the 3D Secure 2 SDK. + [JsonConstructor] + public SDKEphemPubKey(Option crv = default, Option kty = default, Option x = default, Option y = default) + { + _CrvOption = crv; + _KtyOption = kty; + _XOption = x; + _YOption = y; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SDKEphemPubKey() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CrvOption { get; private set; } + + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("crv")] + public string? Crv { get { return this._CrvOption; } set { this._CrvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KtyOption { get; private set; } + + /// + /// The `kty` value as received from the 3D Secure 2 SDK. + /// + /// The `kty` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("kty")] + public string? Kty { get { return this._KtyOption; } set { this._KtyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XOption { get; private set; } + + /// + /// The `x` value as received from the 3D Secure 2 SDK. + /// + /// The `x` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("x")] + public string? X { get { return this._XOption; } set { this._XOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _YOption { get; private set; } + + /// + /// The `y` value as received from the 3D Secure 2 SDK. + /// + /// The `y` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("y")] + public string? Y { get { return this._YOption; } set { this._YOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SDKEphemPubKey {\n"); + sb.Append(" Crv: ").Append(Crv).Append("\n"); + sb.Append(" Kty: ").Append(Kty).Append("\n"); + sb.Append(" X: ").Append(X).Append("\n"); + sb.Append(" Y: ").Append(Y).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SDKEphemPubKeyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SDKEphemPubKey Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option crv = default; + Option kty = default; + Option x = default; + Option y = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "crv": + crv = new Option(utf8JsonReader.GetString()!); + break; + case "kty": + kty = new Option(utf8JsonReader.GetString()!); + break; + case "x": + x = new Option(utf8JsonReader.GetString()!); + break; + case "y": + y = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SDKEphemPubKey(crv, kty, x, y); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SDKEphemPubKey sDKEphemPubKey, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sDKEphemPubKey, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SDKEphemPubKey sDKEphemPubKey, JsonSerializerOptions jsonSerializerOptions) + { + + if (sDKEphemPubKey._CrvOption.IsSet) + if (sDKEphemPubKey.Crv != null) + writer.WriteString("crv", sDKEphemPubKey.Crv); + + if (sDKEphemPubKey._KtyOption.IsSet) + if (sDKEphemPubKey.Kty != null) + writer.WriteString("kty", sDKEphemPubKey.Kty); + + if (sDKEphemPubKey._XOption.IsSet) + if (sDKEphemPubKey.X != null) + writer.WriteString("x", sDKEphemPubKey.X); + + if (sDKEphemPubKey._YOption.IsSet) + if (sDKEphemPubKey.Y != null) + writer.WriteString("y", sDKEphemPubKey.Y); + } + } +} diff --git a/Adyen/Checkout/Models/SamsungPayDetails.cs b/Adyen/Checkout/Models/SamsungPayDetails.cs new file mode 100644 index 000000000..ad606e832 --- /dev/null +++ b/Adyen/Checkout/Models/SamsungPayDetails.cs @@ -0,0 +1,512 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SamsungPayDetails. + /// + public partial class SamsungPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The payload you received from the Samsung Pay SDK response. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **samsungpay** (default to TypeEnum.Samsungpay) + [JsonConstructor] + public SamsungPayDetails(string samsungPayToken, Option checkoutAttemptId = default, Option fundingSource = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + SamsungPayToken = samsungPayToken; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SamsungPayDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **samsungpay** + /// + /// **samsungpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Samsungpay - samsungpay + /// + public static readonly TypeEnum Samsungpay = new("samsungpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "samsungpay" => TypeEnum.Samsungpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Samsungpay) + return "samsungpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **samsungpay** + /// + /// **samsungpay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The payload you received from the Samsung Pay SDK response. + /// + /// The payload you received from the Samsung Pay SDK response. + [JsonPropertyName("samsungPayToken")] + public string SamsungPayToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SamsungPayDetails {\n"); + sb.Append(" SamsungPayToken: ").Append(SamsungPayToken).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SamsungPayToken (string) maxLength + if (this.SamsungPayToken != null && this.SamsungPayToken.Length > 10000) + { + yield return new ValidationResult("Invalid value for SamsungPayToken, length must be less than 10000.", new [] { "SamsungPayToken" }); + } + + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SamsungPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SamsungPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option samsungPayToken = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "samsungPayToken": + samsungPayToken = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(SamsungPayDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SamsungPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!samsungPayToken.IsSet) + throw new ArgumentException("Property is required for class SamsungPayDetails.", nameof(samsungPayToken)); + + return new SamsungPayDetails(samsungPayToken.Value!, checkoutAttemptId, fundingSource, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SamsungPayDetails samsungPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, samsungPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SamsungPayDetails samsungPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (samsungPayDetails.SamsungPayToken != null) + writer.WriteString("samsungPayToken", samsungPayDetails.SamsungPayToken); + + if (samsungPayDetails._CheckoutAttemptIdOption.IsSet) + if (samsungPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", samsungPayDetails.CheckoutAttemptId); + + if (samsungPayDetails._FundingSourceOption.IsSet && samsungPayDetails.FundingSource != null) + { + string? fundingSourceRawValue = SamsungPayDetails.FundingSourceEnum.ToJsonValue(samsungPayDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (samsungPayDetails._RecurringDetailReferenceOption.IsSet) + if (samsungPayDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", samsungPayDetails.RecurringDetailReference); + + if (samsungPayDetails._StoredPaymentMethodIdOption.IsSet) + if (samsungPayDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", samsungPayDetails.StoredPaymentMethodId); + + if (samsungPayDetails._TypeOption.IsSet && samsungPayDetails.Type != null) + { + string? typeRawValue = SamsungPayDetails.TypeEnum.ToJsonValue(samsungPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/SepaDirectDebitDetails.cs b/Adyen/Checkout/Models/SepaDirectDebitDetails.cs new file mode 100644 index 000000000..ba67757ca --- /dev/null +++ b/Adyen/Checkout/Models/SepaDirectDebitDetails.cs @@ -0,0 +1,429 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SepaDirectDebitDetails. + /// + public partial class SepaDirectDebitDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The International Bank Account Number (IBAN). + /// The name of the bank account holder. + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// **sepadirectdebit** (default to TypeEnum.Sepadirectdebit) + [JsonConstructor] + public SepaDirectDebitDetails(string iban, string ownerName, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option transferInstrumentId = default, Option type = default) + { + Iban = iban; + OwnerName = ownerName; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TransferInstrumentIdOption = transferInstrumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SepaDirectDebitDetails() + { + } + + partial void OnCreated(); + + /// + /// **sepadirectdebit** + /// + /// **sepadirectdebit** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Sepadirectdebit - sepadirectdebit + /// + public static readonly TypeEnum Sepadirectdebit = new("sepadirectdebit"); + + /// + /// TypeEnum.SepadirectdebitAmazonpay - sepadirectdebit_amazonpay + /// + public static readonly TypeEnum SepadirectdebitAmazonpay = new("sepadirectdebit_amazonpay"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sepadirectdebit" => TypeEnum.Sepadirectdebit, + "sepadirectdebit_amazonpay" => TypeEnum.SepadirectdebitAmazonpay, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Sepadirectdebit) + return "sepadirectdebit"; + + if (value == TypeEnum.SepadirectdebitAmazonpay) + return "sepadirectdebit_amazonpay"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **sepadirectdebit** + /// + /// **sepadirectdebit** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The International Bank Account Number (IBAN). + /// + /// The International Bank Account Number (IBAN). + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// The name of the bank account holder. + /// + /// The name of the bank account holder. + [JsonPropertyName("ownerName")] + public string OwnerName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + /// + /// The unique identifier of your user's verified transfer instrument, which you can use to top up their balance accounts. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SepaDirectDebitDetails {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SepaDirectDebitDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SepaDirectDebitDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option ownerName = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option transferInstrumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SepaDirectDebitDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class SepaDirectDebitDetails.", nameof(iban)); + + if (!ownerName.IsSet) + throw new ArgumentException("Property is required for class SepaDirectDebitDetails.", nameof(ownerName)); + + return new SepaDirectDebitDetails(iban.Value!, ownerName.Value!, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, transferInstrumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SepaDirectDebitDetails sepaDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sepaDirectDebitDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SepaDirectDebitDetails sepaDirectDebitDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (sepaDirectDebitDetails.Iban != null) + writer.WriteString("iban", sepaDirectDebitDetails.Iban); + + if (sepaDirectDebitDetails.OwnerName != null) + writer.WriteString("ownerName", sepaDirectDebitDetails.OwnerName); + + if (sepaDirectDebitDetails._CheckoutAttemptIdOption.IsSet) + if (sepaDirectDebitDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", sepaDirectDebitDetails.CheckoutAttemptId); + + if (sepaDirectDebitDetails._RecurringDetailReferenceOption.IsSet) + if (sepaDirectDebitDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", sepaDirectDebitDetails.RecurringDetailReference); + + if (sepaDirectDebitDetails._StoredPaymentMethodIdOption.IsSet) + if (sepaDirectDebitDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", sepaDirectDebitDetails.StoredPaymentMethodId); + + if (sepaDirectDebitDetails._TransferInstrumentIdOption.IsSet) + if (sepaDirectDebitDetails.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", sepaDirectDebitDetails.TransferInstrumentId); + + if (sepaDirectDebitDetails._TypeOption.IsSet && sepaDirectDebitDetails.Type != null) + { + string? typeRawValue = SepaDirectDebitDetails.TypeEnum.ToJsonValue(sepaDirectDebitDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ServiceError.cs b/Adyen/Checkout/Models/ServiceError.cs new file mode 100644 index 000000000..964f2baf3 --- /dev/null +++ b/Adyen/Checkout/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Checkout/Models/SessionResultResponse.cs b/Adyen/Checkout/Models/SessionResultResponse.cs new file mode 100644 index 000000000..b115c33dc --- /dev/null +++ b/Adyen/Checkout/Models/SessionResultResponse.cs @@ -0,0 +1,421 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SessionResultResponse. + /// + public partial class SessionResultResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**. + /// A unique identifier of the session. + /// A list of all authorised payments done for this session. + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status. + /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created. + [JsonConstructor] + public SessionResultResponse(Option?> additionalData = default, Option id = default, Option?> payments = default, Option reference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _IdOption = id; + _PaymentsOption = payments; + _ReferenceOption = reference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SessionResultResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created. + /// + /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Canceled - canceled + /// + public static readonly StatusEnum Canceled = new("canceled"); + + /// + /// StatusEnum.Completed - completed + /// + public static readonly StatusEnum Completed = new("completed"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.PaymentPending - paymentPending + /// + public static readonly StatusEnum PaymentPending = new("paymentPending"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "canceled" => StatusEnum.Canceled, + "completed" => StatusEnum.Completed, + "expired" => StatusEnum.Expired, + "paymentPending" => StatusEnum.PaymentPending, + "refused" => StatusEnum.Refused, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Canceled) + return "canceled"; + + if (value == StatusEnum.Completed) + return "completed"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.PaymentPending) + return "paymentPending"; + + if (value == StatusEnum.Refused) + return "refused"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created. + /// + /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// A unique identifier of the session. + /// + /// A unique identifier of the session. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PaymentsOption { get; private set; } + + /// + /// A list of all authorised payments done for this session. + /// + /// A list of all authorised payments done for this session. + [JsonPropertyName("payments")] + public List? Payments { get { return this._PaymentsOption; } set { this._PaymentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status. + /// + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SessionResultResponse {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Payments: ").Append(Payments).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SessionResultResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SessionResultResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option id = default; + Option?> payments = default; + Option reference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "payments": + payments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(SessionResultResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new SessionResultResponse(additionalData, id, payments, reference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SessionResultResponse sessionResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sessionResultResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SessionResultResponse sessionResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (sessionResultResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, sessionResultResponse.AdditionalData, jsonSerializerOptions); + } + if (sessionResultResponse._IdOption.IsSet) + if (sessionResultResponse.Id != null) + writer.WriteString("id", sessionResultResponse.Id); + + if (sessionResultResponse._PaymentsOption.IsSet) + { + writer.WritePropertyName("payments"); + JsonSerializer.Serialize(writer, sessionResultResponse.Payments, jsonSerializerOptions); + } + if (sessionResultResponse._ReferenceOption.IsSet) + if (sessionResultResponse.Reference != null) + writer.WriteString("reference", sessionResultResponse.Reference); + + if (sessionResultResponse._StatusOption.IsSet && sessionResultResponse.Status != null) + { + string? statusRawValue = SessionResultResponse.StatusEnum.ToJsonValue(sessionResultResponse._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ShopperIdPaymentMethod.cs b/Adyen/Checkout/Models/ShopperIdPaymentMethod.cs new file mode 100644 index 000000000..84f01d3c3 --- /dev/null +++ b/Adyen/Checkout/Models/ShopperIdPaymentMethod.cs @@ -0,0 +1,213 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ShopperIdPaymentMethod. + /// + public partial class ShopperIdPaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructor] + public ShopperIdPaymentMethod() + { + Type = this.GetType().Name; + OnCreated(); + } + + + partial void OnCreated(); + + /// + /// The discriminator. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public string Type { get; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShopperIdPaymentMethod {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + // Type (string) maxLength + if (this.Type != null && this.Type.Length > 50) + { + yield return new ValidationResult("Invalid value for Type, length must be less than 50.", new [] { "Type" }); + } + + // Type (string) minLength + if (this.Type != null && this.Type.Length < 0) + { + yield return new ValidationResult("Invalid value for Type, length must be greater than 0.", new [] { "Type" }); + } + + if (this.Type != null) { + // Type (string) pattern + Regex regexType = new Regex(@"payTo|upi_collect", RegexOptions.CultureInvariant); + + if (!regexType.Match(this.Type).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" }); + } + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShopperIdPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShopperIdPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + + string? discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "type"); + + if (discriminator != null && discriminator.Equals("PayToPaymentMethod")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + if (discriminator != null && discriminator.Equals("UPIPaymentMethod")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ShopperIdPaymentMethod.", nameof(type)); + + return new ShopperIdPaymentMethod(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShopperIdPaymentMethod shopperIdPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + if (shopperIdPaymentMethod is PayToPaymentMethod payToPaymentMethod){ + JsonSerializer.Serialize(writer, payToPaymentMethod, jsonSerializerOptions); + return; + } + + if (shopperIdPaymentMethod is UPIPaymentMethod uPIPaymentMethod){ + JsonSerializer.Serialize(writer, uPIPaymentMethod, jsonSerializerOptions); + return; + } + + + writer.WriteStartObject(); + + WriteProperties(writer, shopperIdPaymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShopperIdPaymentMethod shopperIdPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (shopperIdPaymentMethod.Type != null) + writer.WriteString("type", shopperIdPaymentMethod.Type); + } + } +} diff --git a/Adyen/Checkout/Models/ShopperInteractionDevice.cs b/Adyen/Checkout/Models/ShopperInteractionDevice.cs new file mode 100644 index 000000000..6324fcc17 --- /dev/null +++ b/Adyen/Checkout/Models/ShopperInteractionDevice.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ShopperInteractionDevice. + /// + public partial class ShopperInteractionDevice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Locale on the shopper interaction device. + /// Operating system running on the shopper interaction device. + /// Version of the operating system on the shopper interaction device. + [JsonConstructor] + public ShopperInteractionDevice(Option locale = default, Option os = default, Option osVersion = default) + { + _LocaleOption = locale; + _OsOption = os; + _OsVersionOption = osVersion; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ShopperInteractionDevice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LocaleOption { get; private set; } + + /// + /// Locale on the shopper interaction device. + /// + /// Locale on the shopper interaction device. + [JsonPropertyName("locale")] + public string? Locale { get { return this._LocaleOption; } set { this._LocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsOption { get; private set; } + + /// + /// Operating system running on the shopper interaction device. + /// + /// Operating system running on the shopper interaction device. + [JsonPropertyName("os")] + public string? Os { get { return this._OsOption; } set { this._OsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsVersionOption { get; private set; } + + /// + /// Version of the operating system on the shopper interaction device. + /// + /// Version of the operating system on the shopper interaction device. + [JsonPropertyName("osVersion")] + public string? OsVersion { get { return this._OsVersionOption; } set { this._OsVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShopperInteractionDevice {\n"); + sb.Append(" Locale: ").Append(Locale).Append("\n"); + sb.Append(" Os: ").Append(Os).Append("\n"); + sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShopperInteractionDeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShopperInteractionDevice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option locale = default; + Option os = default; + Option osVersion = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "locale": + locale = new Option(utf8JsonReader.GetString()!); + break; + case "os": + os = new Option(utf8JsonReader.GetString()!); + break; + case "osVersion": + osVersion = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ShopperInteractionDevice(locale, os, osVersion); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShopperInteractionDevice shopperInteractionDevice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, shopperInteractionDevice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShopperInteractionDevice shopperInteractionDevice, JsonSerializerOptions jsonSerializerOptions) + { + + if (shopperInteractionDevice._LocaleOption.IsSet) + if (shopperInteractionDevice.Locale != null) + writer.WriteString("locale", shopperInteractionDevice.Locale); + + if (shopperInteractionDevice._OsOption.IsSet) + if (shopperInteractionDevice.Os != null) + writer.WriteString("os", shopperInteractionDevice.Os); + + if (shopperInteractionDevice._OsVersionOption.IsSet) + if (shopperInteractionDevice.OsVersion != null) + writer.WriteString("osVersion", shopperInteractionDevice.OsVersion); + } + } +} diff --git a/Adyen/Checkout/Models/ShopperName.cs b/Adyen/Checkout/Models/ShopperName.cs new file mode 100644 index 000000000..6683045e8 --- /dev/null +++ b/Adyen/Checkout/Models/ShopperName.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ShopperName. + /// + public partial class ShopperName : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public ShopperName(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ShopperName() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShopperName {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShopperNameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShopperName Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class ShopperName.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class ShopperName.", nameof(lastName)); + + return new ShopperName(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShopperName shopperName, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, shopperName, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShopperName shopperName, JsonSerializerOptions jsonSerializerOptions) + { + + if (shopperName.FirstName != null) + writer.WriteString("firstName", shopperName.FirstName); + + if (shopperName.LastName != null) + writer.WriteString("lastName", shopperName.LastName); + } + } +} diff --git a/Adyen/Checkout/Models/Split.cs b/Adyen/Checkout/Models/Split.cs new file mode 100644 index 000000000..1fca2eb52 --- /dev/null +++ b/Adyen/Checkout/Models/Split.cs @@ -0,0 +1,504 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Split. + /// + public partial class Split : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + /// amount + /// Your description for the split item. + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + [JsonConstructor] + public Split(TypeEnum type, Option account = default, Option amount = default, Option description = default, Option reference = default) + { + Type = type; + _AccountOption = account; + _AmountOption = amount; + _DescriptionOption = description; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Split() + { + } + + partial void OnCreated(); + + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AcquiringFees - AcquiringFees + /// + public static readonly TypeEnum AcquiringFees = new("AcquiringFees"); + + /// + /// TypeEnum.AdyenCommission - AdyenCommission + /// + public static readonly TypeEnum AdyenCommission = new("AdyenCommission"); + + /// + /// TypeEnum.AdyenFees - AdyenFees + /// + public static readonly TypeEnum AdyenFees = new("AdyenFees"); + + /// + /// TypeEnum.AdyenMarkup - AdyenMarkup + /// + public static readonly TypeEnum AdyenMarkup = new("AdyenMarkup"); + + /// + /// TypeEnum.BalanceAccount - BalanceAccount + /// + public static readonly TypeEnum BalanceAccount = new("BalanceAccount"); + + /// + /// TypeEnum.Commission - Commission + /// + public static readonly TypeEnum Commission = new("Commission"); + + /// + /// TypeEnum.Default - Default + /// + public static readonly TypeEnum Default = new("Default"); + + /// + /// TypeEnum.Interchange - Interchange + /// + public static readonly TypeEnum Interchange = new("Interchange"); + + /// + /// TypeEnum.MarketPlace - MarketPlace + /// + public static readonly TypeEnum MarketPlace = new("MarketPlace"); + + /// + /// TypeEnum.PaymentFee - PaymentFee + /// + public static readonly TypeEnum PaymentFee = new("PaymentFee"); + + /// + /// TypeEnum.Remainder - Remainder + /// + public static readonly TypeEnum Remainder = new("Remainder"); + + /// + /// TypeEnum.SchemeFee - SchemeFee + /// + public static readonly TypeEnum SchemeFee = new("SchemeFee"); + + /// + /// TypeEnum.Surcharge - Surcharge + /// + public static readonly TypeEnum Surcharge = new("Surcharge"); + + /// + /// TypeEnum.Tip - Tip + /// + public static readonly TypeEnum Tip = new("Tip"); + + /// + /// TypeEnum.TopUp - TopUp + /// + public static readonly TypeEnum TopUp = new("TopUp"); + + /// + /// TypeEnum.VAT - VAT + /// + public static readonly TypeEnum VAT = new("VAT"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "AcquiringFees" => TypeEnum.AcquiringFees, + "AdyenCommission" => TypeEnum.AdyenCommission, + "AdyenFees" => TypeEnum.AdyenFees, + "AdyenMarkup" => TypeEnum.AdyenMarkup, + "BalanceAccount" => TypeEnum.BalanceAccount, + "Commission" => TypeEnum.Commission, + "Default" => TypeEnum.Default, + "Interchange" => TypeEnum.Interchange, + "MarketPlace" => TypeEnum.MarketPlace, + "PaymentFee" => TypeEnum.PaymentFee, + "Remainder" => TypeEnum.Remainder, + "SchemeFee" => TypeEnum.SchemeFee, + "Surcharge" => TypeEnum.Surcharge, + "Tip" => TypeEnum.Tip, + "TopUp" => TypeEnum.TopUp, + "VAT" => TypeEnum.VAT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AcquiringFees) + return "AcquiringFees"; + + if (value == TypeEnum.AdyenCommission) + return "AdyenCommission"; + + if (value == TypeEnum.AdyenFees) + return "AdyenFees"; + + if (value == TypeEnum.AdyenMarkup) + return "AdyenMarkup"; + + if (value == TypeEnum.BalanceAccount) + return "BalanceAccount"; + + if (value == TypeEnum.Commission) + return "Commission"; + + if (value == TypeEnum.Default) + return "Default"; + + if (value == TypeEnum.Interchange) + return "Interchange"; + + if (value == TypeEnum.MarketPlace) + return "MarketPlace"; + + if (value == TypeEnum.PaymentFee) + return "PaymentFee"; + + if (value == TypeEnum.Remainder) + return "Remainder"; + + if (value == TypeEnum.SchemeFee) + return "SchemeFee"; + + if (value == TypeEnum.Surcharge) + return "Surcharge"; + + if (value == TypeEnum.Tip) + return "Tip"; + + if (value == TypeEnum.TopUp) + return "TopUp"; + + if (value == TypeEnum.VAT) + return "VAT"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountOption { get; private set; } + + /// + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + /// + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + [JsonPropertyName("account")] + public string? Account { get { return this._AccountOption; } set { this._AccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public SplitAmount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the split item. + /// + /// Your description for the split item. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + /// + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Split {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Account: ").Append(Account).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Split Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option account = default; + Option amount = default; + Option description = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Split.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "account": + account = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Split.", nameof(type)); + + return new Split(type.Value!.Value!, account, amount, description, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Split split, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, split, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Split split, JsonSerializerOptions jsonSerializerOptions) + { + + if (split.Type != null) + { + string? typeRawValue = Split.TypeEnum.ToJsonValue(split.Type); + writer.WriteString("type", typeRawValue); + } + + if (split._AccountOption.IsSet) + if (split.Account != null) + writer.WriteString("account", split.Account); + + if (split._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, split.Amount, jsonSerializerOptions); + } + if (split._DescriptionOption.IsSet) + if (split.Description != null) + writer.WriteString("description", split.Description); + + if (split._ReferenceOption.IsSet) + if (split.Reference != null) + writer.WriteString("reference", split.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/SplitAmount.cs b/Adyen/Checkout/Models/SplitAmount.cs new file mode 100644 index 000000000..943a1ee5c --- /dev/null +++ b/Adyen/Checkout/Models/SplitAmount.cs @@ -0,0 +1,207 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SplitAmount. + /// + public partial class SplitAmount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + [JsonConstructor] + public SplitAmount(long value, Option currency = default) + { + Value = value; + _CurrencyOption = currency; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitAmount() + { + } + + partial void OnCreated(); + + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitAmount {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitAmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitAmount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option value = default; + Option currency = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!value.IsSet) + throw new ArgumentException("Property is required for class SplitAmount.", nameof(value)); + + return new SplitAmount(value.Value!.Value!, currency); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitAmount splitAmount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitAmount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitAmount splitAmount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("value", splitAmount.Value); + + if (splitAmount._CurrencyOption.IsSet) + if (splitAmount.Currency != null) + writer.WriteString("currency", splitAmount.Currency); + } + } +} diff --git a/Adyen/Checkout/Models/StandalonePaymentCancelRequest.cs b/Adyen/Checkout/Models/StandalonePaymentCancelRequest.cs new file mode 100644 index 000000000..b61102b8f --- /dev/null +++ b/Adyen/Checkout/Models/StandalonePaymentCancelRequest.cs @@ -0,0 +1,266 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StandalonePaymentCancelRequest. + /// + public partial class StandalonePaymentCancelRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment that you want to cancel. + /// applicationInfo + /// enhancedSchemeData + /// Your reference for the cancel request. Maximum length: 80 characters. + [JsonConstructor] + public StandalonePaymentCancelRequest(string merchantAccount, string paymentReference, Option applicationInfo = default, Option enhancedSchemeData = default, Option reference = default) + { + MerchantAccount = merchantAccount; + PaymentReference = paymentReference; + _ApplicationInfoOption = applicationInfo; + _EnhancedSchemeDataOption = enhancedSchemeData; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StandalonePaymentCancelRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment that you want to cancel. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment that you want to cancel. + [JsonPropertyName("paymentReference")] + public string PaymentReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("enhancedSchemeData")] + public EnhancedSchemeData? EnhancedSchemeData { get { return this._EnhancedSchemeDataOption; } set { this._EnhancedSchemeDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the cancel request. Maximum length: 80 characters. + /// + /// Your reference for the cancel request. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StandalonePaymentCancelRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentReference: ").Append(PaymentReference).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StandalonePaymentCancelRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StandalonePaymentCancelRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentReference = default; + Option applicationInfo = default; + Option enhancedSchemeData = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentReference": + paymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enhancedSchemeData": + enhancedSchemeData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelRequest.", nameof(merchantAccount)); + + if (!paymentReference.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelRequest.", nameof(paymentReference)); + + return new StandalonePaymentCancelRequest(merchantAccount.Value!, paymentReference.Value!, applicationInfo, enhancedSchemeData, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StandalonePaymentCancelRequest standalonePaymentCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, standalonePaymentCancelRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StandalonePaymentCancelRequest standalonePaymentCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (standalonePaymentCancelRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", standalonePaymentCancelRequest.MerchantAccount); + + if (standalonePaymentCancelRequest.PaymentReference != null) + writer.WriteString("paymentReference", standalonePaymentCancelRequest.PaymentReference); + + if (standalonePaymentCancelRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, standalonePaymentCancelRequest.ApplicationInfo, jsonSerializerOptions); + } + if (standalonePaymentCancelRequest._EnhancedSchemeDataOption.IsSet) + { + writer.WritePropertyName("enhancedSchemeData"); + JsonSerializer.Serialize(writer, standalonePaymentCancelRequest.EnhancedSchemeData, jsonSerializerOptions); + } + if (standalonePaymentCancelRequest._ReferenceOption.IsSet) + if (standalonePaymentCancelRequest.Reference != null) + writer.WriteString("reference", standalonePaymentCancelRequest.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/StandalonePaymentCancelResponse.cs b/Adyen/Checkout/Models/StandalonePaymentCancelResponse.cs new file mode 100644 index 000000000..c28abc7c3 --- /dev/null +++ b/Adyen/Checkout/Models/StandalonePaymentCancelResponse.cs @@ -0,0 +1,354 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StandalonePaymentCancelResponse. + /// + public partial class StandalonePaymentCancelResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment to cancel. + /// Adyen's 16-character reference associated with the cancel request. + /// The status of your request. This will always have the value **received**. + /// Your reference for the cancel request. + [JsonConstructor] + public StandalonePaymentCancelResponse(string merchantAccount, string paymentReference, string pspReference, StatusEnum status, Option reference = default) + { + MerchantAccount = merchantAccount; + PaymentReference = paymentReference; + PspReference = pspReference; + Status = status; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StandalonePaymentCancelResponse() + { + } + + partial void OnCreated(); + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "received" => StatusEnum.Received, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Received) + return "received"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of your request. This will always have the value **received**. + /// + /// The status of your request. This will always have the value **received**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment to cancel. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment to cancel. + [JsonPropertyName("paymentReference")] + public string PaymentReference { get; set; } + + /// + /// Adyen's 16-character reference associated with the cancel request. + /// + /// Adyen's 16-character reference associated with the cancel request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the cancel request. + /// + /// Your reference for the cancel request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StandalonePaymentCancelResponse {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentReference: ").Append(PaymentReference).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StandalonePaymentCancelResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StandalonePaymentCancelResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentReference = default; + Option pspReference = default; + Option status = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentReference": + paymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(StandalonePaymentCancelResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelResponse.", nameof(merchantAccount)); + + if (!paymentReference.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelResponse.", nameof(paymentReference)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelResponse.", nameof(pspReference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class StandalonePaymentCancelResponse.", nameof(status)); + + return new StandalonePaymentCancelResponse(merchantAccount.Value!, paymentReference.Value!, pspReference.Value!, status.Value!.Value!, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StandalonePaymentCancelResponse standalonePaymentCancelResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, standalonePaymentCancelResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StandalonePaymentCancelResponse standalonePaymentCancelResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (standalonePaymentCancelResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", standalonePaymentCancelResponse.MerchantAccount); + + if (standalonePaymentCancelResponse.PaymentReference != null) + writer.WriteString("paymentReference", standalonePaymentCancelResponse.PaymentReference); + + if (standalonePaymentCancelResponse.PspReference != null) + writer.WriteString("pspReference", standalonePaymentCancelResponse.PspReference); + + if (standalonePaymentCancelResponse.Status != null) + { + string? statusRawValue = StandalonePaymentCancelResponse.StatusEnum.ToJsonValue(standalonePaymentCancelResponse.Status); + writer.WriteString("status", statusRawValue); + } + + if (standalonePaymentCancelResponse._ReferenceOption.IsSet) + if (standalonePaymentCancelResponse.Reference != null) + writer.WriteString("reference", standalonePaymentCancelResponse.Reference); + } + } +} diff --git a/Adyen/Checkout/Models/StoredPaymentMethod.cs b/Adyen/Checkout/Models/StoredPaymentMethod.cs new file mode 100644 index 000000000..492c8e5cf --- /dev/null +++ b/Adyen/Checkout/Models/StoredPaymentMethod.cs @@ -0,0 +1,579 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StoredPaymentMethod. + /// + public partial class StoredPaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The location id of the bank. The field value is `nil` in most cases. + /// The brand of the card. + /// The two-digit month when the card expires + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + /// The unique payment method code. + /// The IBAN of the bank account. + /// A unique identifier of this stored payment method. + /// The shopper’s issuer account label + /// The last four digits of the PAN. + /// The display name of the stored payment method. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The name of the bank account holder. + /// The shopper’s email address. + /// The supported recurring processing models for this stored payment method. + /// The supported shopper interactions for this stored payment method. + /// The type of payment method. + [JsonConstructor] + public StoredPaymentMethod(Option bankAccountNumber = default, Option bankLocationId = default, Option brand = default, Option expiryMonth = default, Option expiryYear = default, Option holderName = default, Option iban = default, Option id = default, Option label = default, Option lastFour = default, Option name = default, Option networkTxReference = default, Option ownerName = default, Option shopperEmail = default, Option?> supportedRecurringProcessingModels = default, Option?> supportedShopperInteractions = default, Option type = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankLocationIdOption = bankLocationId; + _BrandOption = brand; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _HolderNameOption = holderName; + _IbanOption = iban; + _IdOption = id; + _LabelOption = label; + _LastFourOption = lastFour; + _NameOption = name; + _NetworkTxReferenceOption = networkTxReference; + _OwnerNameOption = ownerName; + _ShopperEmailOption = shopperEmail; + _SupportedRecurringProcessingModelsOption = supportedRecurringProcessingModels; + _SupportedShopperInteractionsOption = supportedShopperInteractions; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredPaymentMethod() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The location id of the bank. The field value is `nil` in most cases. + /// + /// The location id of the bank. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// The brand of the card. + /// + /// The brand of the card. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The two-digit month when the card expires + /// + /// The two-digit month when the card expires + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + /// + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The unique payment method code. + /// + /// The unique payment method code. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The IBAN of the bank account. + /// + /// The IBAN of the bank account. + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// A unique identifier of this stored payment method. + /// + /// A unique identifier of this stored payment method. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LabelOption { get; private set; } + + /// + /// The shopper’s issuer account label + /// + /// The shopper’s issuer account label + [JsonPropertyName("label")] + public string? Label { get { return this._LabelOption; } set { this._LabelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastFourOption { get; private set; } + + /// + /// The last four digits of the PAN. + /// + /// The last four digits of the PAN. + [JsonPropertyName("lastFour")] + public string? LastFour { get { return this._LastFourOption; } set { this._LastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The display name of the stored payment method. + /// + /// The display name of the stored payment method. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. + /// + /// The name of the bank account holder. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper’s email address. + /// + /// The shopper’s email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SupportedRecurringProcessingModelsOption { get; private set; } + + /// + /// The supported recurring processing models for this stored payment method. + /// + /// The supported recurring processing models for this stored payment method. + [JsonPropertyName("supportedRecurringProcessingModels")] + public List? SupportedRecurringProcessingModels { get { return this._SupportedRecurringProcessingModelsOption; } set { this._SupportedRecurringProcessingModelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SupportedShopperInteractionsOption { get; private set; } + + /// + /// The supported shopper interactions for this stored payment method. + /// + /// The supported shopper interactions for this stored payment method. + [JsonPropertyName("supportedShopperInteractions")] + public List? SupportedShopperInteractions { get { return this._SupportedShopperInteractionsOption; } set { this._SupportedShopperInteractionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of payment method. + /// + /// The type of payment method. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredPaymentMethod {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Label: ").Append(Label).Append("\n"); + sb.Append(" LastFour: ").Append(LastFour).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" SupportedRecurringProcessingModels: ").Append(SupportedRecurringProcessingModels).Append("\n"); + sb.Append(" SupportedShopperInteractions: ").Append(SupportedShopperInteractions).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankLocationId = default; + Option brand = default; + Option expiryMonth = default; + Option expiryYear = default; + Option holderName = default; + Option iban = default; + Option id = default; + Option label = default; + Option lastFour = default; + Option name = default; + Option networkTxReference = default; + Option ownerName = default; + Option shopperEmail = default; + Option?> supportedRecurringProcessingModels = default; + Option?> supportedShopperInteractions = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "label": + label = new Option(utf8JsonReader.GetString()!); + break; + case "lastFour": + lastFour = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "supportedRecurringProcessingModels": + supportedRecurringProcessingModels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "supportedShopperInteractions": + supportedShopperInteractions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredPaymentMethod(bankAccountNumber, bankLocationId, brand, expiryMonth, expiryYear, holderName, iban, id, label, lastFour, name, networkTxReference, ownerName, shopperEmail, supportedRecurringProcessingModels, supportedShopperInteractions, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredPaymentMethod storedPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedPaymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredPaymentMethod storedPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedPaymentMethod._BankAccountNumberOption.IsSet) + if (storedPaymentMethod.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", storedPaymentMethod.BankAccountNumber); + + if (storedPaymentMethod._BankLocationIdOption.IsSet) + if (storedPaymentMethod.BankLocationId != null) + writer.WriteString("bankLocationId", storedPaymentMethod.BankLocationId); + + if (storedPaymentMethod._BrandOption.IsSet) + if (storedPaymentMethod.Brand != null) + writer.WriteString("brand", storedPaymentMethod.Brand); + + if (storedPaymentMethod._ExpiryMonthOption.IsSet) + if (storedPaymentMethod.ExpiryMonth != null) + writer.WriteString("expiryMonth", storedPaymentMethod.ExpiryMonth); + + if (storedPaymentMethod._ExpiryYearOption.IsSet) + if (storedPaymentMethod.ExpiryYear != null) + writer.WriteString("expiryYear", storedPaymentMethod.ExpiryYear); + + if (storedPaymentMethod._HolderNameOption.IsSet) + if (storedPaymentMethod.HolderName != null) + writer.WriteString("holderName", storedPaymentMethod.HolderName); + + if (storedPaymentMethod._IbanOption.IsSet) + if (storedPaymentMethod.Iban != null) + writer.WriteString("iban", storedPaymentMethod.Iban); + + if (storedPaymentMethod._IdOption.IsSet) + if (storedPaymentMethod.Id != null) + writer.WriteString("id", storedPaymentMethod.Id); + + if (storedPaymentMethod._LabelOption.IsSet) + if (storedPaymentMethod.Label != null) + writer.WriteString("label", storedPaymentMethod.Label); + + if (storedPaymentMethod._LastFourOption.IsSet) + if (storedPaymentMethod.LastFour != null) + writer.WriteString("lastFour", storedPaymentMethod.LastFour); + + if (storedPaymentMethod._NameOption.IsSet) + if (storedPaymentMethod.Name != null) + writer.WriteString("name", storedPaymentMethod.Name); + + if (storedPaymentMethod._NetworkTxReferenceOption.IsSet) + if (storedPaymentMethod.NetworkTxReference != null) + writer.WriteString("networkTxReference", storedPaymentMethod.NetworkTxReference); + + if (storedPaymentMethod._OwnerNameOption.IsSet) + if (storedPaymentMethod.OwnerName != null) + writer.WriteString("ownerName", storedPaymentMethod.OwnerName); + + if (storedPaymentMethod._ShopperEmailOption.IsSet) + if (storedPaymentMethod.ShopperEmail != null) + writer.WriteString("shopperEmail", storedPaymentMethod.ShopperEmail); + + if (storedPaymentMethod._SupportedRecurringProcessingModelsOption.IsSet) + { + writer.WritePropertyName("supportedRecurringProcessingModels"); + JsonSerializer.Serialize(writer, storedPaymentMethod.SupportedRecurringProcessingModels, jsonSerializerOptions); + } + if (storedPaymentMethod._SupportedShopperInteractionsOption.IsSet) + { + writer.WritePropertyName("supportedShopperInteractions"); + JsonSerializer.Serialize(writer, storedPaymentMethod.SupportedShopperInteractions, jsonSerializerOptions); + } + if (storedPaymentMethod._TypeOption.IsSet) + if (storedPaymentMethod.Type != null) + writer.WriteString("type", storedPaymentMethod.Type); + } + } +} diff --git a/Adyen/Checkout/Models/StoredPaymentMethodDetails.cs b/Adyen/Checkout/Models/StoredPaymentMethodDetails.cs new file mode 100644 index 000000000..4778b0838 --- /dev/null +++ b/Adyen/Checkout/Models/StoredPaymentMethodDetails.cs @@ -0,0 +1,509 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StoredPaymentMethodDetails. + /// + public partial class StoredPaymentMethodDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The payment method type. + [JsonConstructor] + public StoredPaymentMethodDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredPaymentMethodDetails() + { + } + + partial void OnCreated(); + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BcmcMobile - bcmc_mobile + /// + public static readonly TypeEnum BcmcMobile = new("bcmc_mobile"); + + /// + /// TypeEnum.BcmcMobileQR - bcmc_mobile_QR + /// + public static readonly TypeEnum BcmcMobileQR = new("bcmc_mobile_QR"); + + /// + /// TypeEnum.BcmcMobileApp - bcmc_mobile_app + /// + public static readonly TypeEnum BcmcMobileApp = new("bcmc_mobile_app"); + + /// + /// TypeEnum.MomoWallet - momo_wallet + /// + public static readonly TypeEnum MomoWallet = new("momo_wallet"); + + /// + /// TypeEnum.MomoWalletApp - momo_wallet_app + /// + public static readonly TypeEnum MomoWalletApp = new("momo_wallet_app"); + + /// + /// TypeEnum.PaymayaWallet - paymaya_wallet + /// + public static readonly TypeEnum PaymayaWallet = new("paymaya_wallet"); + + /// + /// TypeEnum.GrabpaySG - grabpay_SG + /// + public static readonly TypeEnum GrabpaySG = new("grabpay_SG"); + + /// + /// TypeEnum.GrabpayMY - grabpay_MY + /// + public static readonly TypeEnum GrabpayMY = new("grabpay_MY"); + + /// + /// TypeEnum.GrabpayTH - grabpay_TH + /// + public static readonly TypeEnum GrabpayTH = new("grabpay_TH"); + + /// + /// TypeEnum.GrabpayID - grabpay_ID + /// + public static readonly TypeEnum GrabpayID = new("grabpay_ID"); + + /// + /// TypeEnum.GrabpayVN - grabpay_VN + /// + public static readonly TypeEnum GrabpayVN = new("grabpay_VN"); + + /// + /// TypeEnum.GrabpayPH - grabpay_PH + /// + public static readonly TypeEnum GrabpayPH = new("grabpay_PH"); + + /// + /// TypeEnum.Oxxo - oxxo + /// + public static readonly TypeEnum Oxxo = new("oxxo"); + + /// + /// TypeEnum.Gcash - gcash + /// + public static readonly TypeEnum Gcash = new("gcash"); + + /// + /// TypeEnum.Dana - dana + /// + public static readonly TypeEnum Dana = new("dana"); + + /// + /// TypeEnum.Kakaopay - kakaopay + /// + public static readonly TypeEnum Kakaopay = new("kakaopay"); + + /// + /// TypeEnum.Truemoney - truemoney + /// + public static readonly TypeEnum Truemoney = new("truemoney"); + + /// + /// TypeEnum.Paysafecard - paysafecard + /// + public static readonly TypeEnum Paysafecard = new("paysafecard"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bcmc_mobile" => TypeEnum.BcmcMobile, + "bcmc_mobile_QR" => TypeEnum.BcmcMobileQR, + "bcmc_mobile_app" => TypeEnum.BcmcMobileApp, + "momo_wallet" => TypeEnum.MomoWallet, + "momo_wallet_app" => TypeEnum.MomoWalletApp, + "paymaya_wallet" => TypeEnum.PaymayaWallet, + "grabpay_SG" => TypeEnum.GrabpaySG, + "grabpay_MY" => TypeEnum.GrabpayMY, + "grabpay_TH" => TypeEnum.GrabpayTH, + "grabpay_ID" => TypeEnum.GrabpayID, + "grabpay_VN" => TypeEnum.GrabpayVN, + "grabpay_PH" => TypeEnum.GrabpayPH, + "oxxo" => TypeEnum.Oxxo, + "gcash" => TypeEnum.Gcash, + "dana" => TypeEnum.Dana, + "kakaopay" => TypeEnum.Kakaopay, + "truemoney" => TypeEnum.Truemoney, + "paysafecard" => TypeEnum.Paysafecard, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BcmcMobile) + return "bcmc_mobile"; + + if (value == TypeEnum.BcmcMobileQR) + return "bcmc_mobile_QR"; + + if (value == TypeEnum.BcmcMobileApp) + return "bcmc_mobile_app"; + + if (value == TypeEnum.MomoWallet) + return "momo_wallet"; + + if (value == TypeEnum.MomoWalletApp) + return "momo_wallet_app"; + + if (value == TypeEnum.PaymayaWallet) + return "paymaya_wallet"; + + if (value == TypeEnum.GrabpaySG) + return "grabpay_SG"; + + if (value == TypeEnum.GrabpayMY) + return "grabpay_MY"; + + if (value == TypeEnum.GrabpayTH) + return "grabpay_TH"; + + if (value == TypeEnum.GrabpayID) + return "grabpay_ID"; + + if (value == TypeEnum.GrabpayVN) + return "grabpay_VN"; + + if (value == TypeEnum.GrabpayPH) + return "grabpay_PH"; + + if (value == TypeEnum.Oxxo) + return "oxxo"; + + if (value == TypeEnum.Gcash) + return "gcash"; + + if (value == TypeEnum.Dana) + return "dana"; + + if (value == TypeEnum.Kakaopay) + return "kakaopay"; + + if (value == TypeEnum.Truemoney) + return "truemoney"; + + if (value == TypeEnum.Paysafecard) + return "paysafecard"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredPaymentMethodDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredPaymentMethodDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredPaymentMethodDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(StoredPaymentMethodDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new StoredPaymentMethodDetails(checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredPaymentMethodDetails storedPaymentMethodDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedPaymentMethodDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredPaymentMethodDetails storedPaymentMethodDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedPaymentMethodDetails._CheckoutAttemptIdOption.IsSet) + if (storedPaymentMethodDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", storedPaymentMethodDetails.CheckoutAttemptId); + + if (storedPaymentMethodDetails._RecurringDetailReferenceOption.IsSet) + if (storedPaymentMethodDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedPaymentMethodDetails.RecurringDetailReference); + + if (storedPaymentMethodDetails._StoredPaymentMethodIdOption.IsSet) + if (storedPaymentMethodDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", storedPaymentMethodDetails.StoredPaymentMethodId); + + if (storedPaymentMethodDetails._TypeOption.IsSet && storedPaymentMethodDetails.Type != null) + { + string? typeRawValue = StoredPaymentMethodDetails.TypeEnum.ToJsonValue(storedPaymentMethodDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/StoredPaymentMethodRequest.cs b/Adyen/Checkout/Models/StoredPaymentMethodRequest.cs new file mode 100644 index 000000000..91d507830 --- /dev/null +++ b/Adyen/Checkout/Models/StoredPaymentMethodRequest.cs @@ -0,0 +1,395 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StoredPaymentMethodRequest. + /// + public partial class StoredPaymentMethodRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// paymentMethod + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// A unique identifier for the shopper (for example, user ID or account ID). + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. + /// The IP address of a shopper. + [JsonConstructor] + public StoredPaymentMethodRequest(string merchantAccount, PaymentMethodToStore paymentMethod, RecurringProcessingModelEnum recurringProcessingModel, string shopperReference, Option shopperEmail = default, Option shopperIP = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + RecurringProcessingModel = recurringProcessingModel; + ShopperReference = shopperReference; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredPaymentMethodRequest() + { + } + + partial void OnCreated(); + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum RecurringProcessingModel { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public PaymentMethodToStore PaymentMethod { get; set; } + + /// + /// A unique identifier for the shopper (for example, user ID or account ID). + /// + /// A unique identifier for the shopper (for example, user ID or account ID). + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The IP address of a shopper. + /// + /// The IP address of a shopper. + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredPaymentMethodRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredPaymentMethodRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredPaymentMethodRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentMethod = default; + Option recurringProcessingModel = default; + Option shopperReference = default; + Option shopperEmail = default; + Option shopperIP = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(StoredPaymentMethodRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredPaymentMethodRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredPaymentMethodRequest.", nameof(paymentMethod)); + + if (!recurringProcessingModel.IsSet) + throw new ArgumentException("Property is required for class StoredPaymentMethodRequest.", nameof(recurringProcessingModel)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class StoredPaymentMethodRequest.", nameof(shopperReference)); + + return new StoredPaymentMethodRequest(merchantAccount.Value!, paymentMethod.Value!, recurringProcessingModel.Value!.Value!, shopperReference.Value!, shopperEmail, shopperIP); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredPaymentMethodRequest storedPaymentMethodRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedPaymentMethodRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredPaymentMethodRequest storedPaymentMethodRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedPaymentMethodRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedPaymentMethodRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedPaymentMethodRequest.PaymentMethod, jsonSerializerOptions); + if (storedPaymentMethodRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = StoredPaymentMethodRequest.RecurringProcessingModelEnum.ToJsonValue(storedPaymentMethodRequest.RecurringProcessingModel); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (storedPaymentMethodRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedPaymentMethodRequest.ShopperReference); + + if (storedPaymentMethodRequest._ShopperEmailOption.IsSet) + if (storedPaymentMethodRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", storedPaymentMethodRequest.ShopperEmail); + + if (storedPaymentMethodRequest._ShopperIPOption.IsSet) + if (storedPaymentMethodRequest.ShopperIP != null) + writer.WriteString("shopperIP", storedPaymentMethodRequest.ShopperIP); + } + } +} diff --git a/Adyen/Checkout/Models/StoredPaymentMethodResource.cs b/Adyen/Checkout/Models/StoredPaymentMethodResource.cs new file mode 100644 index 000000000..d23ed40cb --- /dev/null +++ b/Adyen/Checkout/Models/StoredPaymentMethodResource.cs @@ -0,0 +1,590 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// StoredPaymentMethodResource. + /// + public partial class StoredPaymentMethodResource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The brand of the card. + /// The month the card expires. + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + /// The response code returned by an external system (for example after a provisioning operation). + /// The token reference of a linked token in an external system (for example a network token reference). + /// The unique payment method code. + /// The IBAN of the bank account. + /// A unique identifier of this stored payment method. + /// The name of the issuer of token or card. + /// The last four digits of the PAN. + /// The display name of the stored payment method. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The name of the bank account holder. + /// The shopper’s email address. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// Defines a recurring payment type. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// The type of payment method. + [JsonConstructor] + public StoredPaymentMethodResource(Option brand = default, Option expiryMonth = default, Option expiryYear = default, Option externalResponseCode = default, Option externalTokenReference = default, Option holderName = default, Option iban = default, Option id = default, Option issuerName = default, Option lastFour = default, Option name = default, Option networkTxReference = default, Option ownerName = default, Option shopperEmail = default, Option shopperReference = default, Option?> supportedRecurringProcessingModels = default, Option type = default) + { + _BrandOption = brand; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _ExternalResponseCodeOption = externalResponseCode; + _ExternalTokenReferenceOption = externalTokenReference; + _HolderNameOption = holderName; + _IbanOption = iban; + _IdOption = id; + _IssuerNameOption = issuerName; + _LastFourOption = lastFour; + _NameOption = name; + _NetworkTxReferenceOption = networkTxReference; + _OwnerNameOption = ownerName; + _ShopperEmailOption = shopperEmail; + _ShopperReferenceOption = shopperReference; + _SupportedRecurringProcessingModelsOption = supportedRecurringProcessingModels; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredPaymentMethodResource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrandOption { get; private set; } + + /// + /// The brand of the card. + /// + /// The brand of the card. + [JsonPropertyName("brand")] + public string? Brand { get { return this._BrandOption; } set { this._BrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The month the card expires. + /// + /// The month the card expires. + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + /// + /// The last two digits of the year the card expires. For example, **22** for the year 2022. + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalResponseCodeOption { get; private set; } + + /// + /// The response code returned by an external system (for example after a provisioning operation). + /// + /// The response code returned by an external system (for example after a provisioning operation). + [JsonPropertyName("externalResponseCode")] + public string? ExternalResponseCode { get { return this._ExternalResponseCodeOption; } set { this._ExternalResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalTokenReferenceOption { get; private set; } + + /// + /// The token reference of a linked token in an external system (for example a network token reference). + /// + /// The token reference of a linked token in an external system (for example a network token reference). + [JsonPropertyName("externalTokenReference")] + public string? ExternalTokenReference { get { return this._ExternalTokenReferenceOption; } set { this._ExternalTokenReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The unique payment method code. + /// + /// The unique payment method code. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The IBAN of the bank account. + /// + /// The IBAN of the bank account. + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// A unique identifier of this stored payment method. + /// + /// A unique identifier of this stored payment method. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerNameOption { get; private set; } + + /// + /// The name of the issuer of token or card. + /// + /// The name of the issuer of token or card. + [JsonPropertyName("issuerName")] + public string? IssuerName { get { return this._IssuerNameOption; } set { this._IssuerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastFourOption { get; private set; } + + /// + /// The last four digits of the PAN. + /// + /// The last four digits of the PAN. + [JsonPropertyName("lastFour")] + public string? LastFour { get { return this._LastFourOption; } set { this._LastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The display name of the stored payment method. + /// + /// The display name of the stored payment method. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. + /// + /// The name of the bank account holder. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper’s email address. + /// + /// The shopper’s email address. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SupportedRecurringProcessingModelsOption { get; private set; } + + /// + /// Defines a recurring payment type. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("supportedRecurringProcessingModels")] + public List? SupportedRecurringProcessingModels { get { return this._SupportedRecurringProcessingModelsOption; } set { this._SupportedRecurringProcessingModelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of payment method. + /// + /// The type of payment method. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredPaymentMethodResource {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" ExternalResponseCode: ").Append(ExternalResponseCode).Append("\n"); + sb.Append(" ExternalTokenReference: ").Append(ExternalTokenReference).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IssuerName: ").Append(IssuerName).Append("\n"); + sb.Append(" LastFour: ").Append(LastFour).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" SupportedRecurringProcessingModels: ").Append(SupportedRecurringProcessingModels).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 3) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 3.", new [] { "ShopperReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredPaymentMethodResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredPaymentMethodResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option expiryMonth = default; + Option expiryYear = default; + Option externalResponseCode = default; + Option externalTokenReference = default; + Option holderName = default; + Option iban = default; + Option id = default; + Option issuerName = default; + Option lastFour = default; + Option name = default; + Option networkTxReference = default; + Option ownerName = default; + Option shopperEmail = default; + Option shopperReference = default; + Option?> supportedRecurringProcessingModels = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "externalResponseCode": + externalResponseCode = new Option(utf8JsonReader.GetString()!); + break; + case "externalTokenReference": + externalTokenReference = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "issuerName": + issuerName = new Option(utf8JsonReader.GetString()!); + break; + case "lastFour": + lastFour = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "supportedRecurringProcessingModels": + supportedRecurringProcessingModels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredPaymentMethodResource(brand, expiryMonth, expiryYear, externalResponseCode, externalTokenReference, holderName, iban, id, issuerName, lastFour, name, networkTxReference, ownerName, shopperEmail, shopperReference, supportedRecurringProcessingModels, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredPaymentMethodResource storedPaymentMethodResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedPaymentMethodResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredPaymentMethodResource storedPaymentMethodResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedPaymentMethodResource._BrandOption.IsSet) + if (storedPaymentMethodResource.Brand != null) + writer.WriteString("brand", storedPaymentMethodResource.Brand); + + if (storedPaymentMethodResource._ExpiryMonthOption.IsSet) + if (storedPaymentMethodResource.ExpiryMonth != null) + writer.WriteString("expiryMonth", storedPaymentMethodResource.ExpiryMonth); + + if (storedPaymentMethodResource._ExpiryYearOption.IsSet) + if (storedPaymentMethodResource.ExpiryYear != null) + writer.WriteString("expiryYear", storedPaymentMethodResource.ExpiryYear); + + if (storedPaymentMethodResource._ExternalResponseCodeOption.IsSet) + if (storedPaymentMethodResource.ExternalResponseCode != null) + writer.WriteString("externalResponseCode", storedPaymentMethodResource.ExternalResponseCode); + + if (storedPaymentMethodResource._ExternalTokenReferenceOption.IsSet) + if (storedPaymentMethodResource.ExternalTokenReference != null) + writer.WriteString("externalTokenReference", storedPaymentMethodResource.ExternalTokenReference); + + if (storedPaymentMethodResource._HolderNameOption.IsSet) + if (storedPaymentMethodResource.HolderName != null) + writer.WriteString("holderName", storedPaymentMethodResource.HolderName); + + if (storedPaymentMethodResource._IbanOption.IsSet) + if (storedPaymentMethodResource.Iban != null) + writer.WriteString("iban", storedPaymentMethodResource.Iban); + + if (storedPaymentMethodResource._IdOption.IsSet) + if (storedPaymentMethodResource.Id != null) + writer.WriteString("id", storedPaymentMethodResource.Id); + + if (storedPaymentMethodResource._IssuerNameOption.IsSet) + if (storedPaymentMethodResource.IssuerName != null) + writer.WriteString("issuerName", storedPaymentMethodResource.IssuerName); + + if (storedPaymentMethodResource._LastFourOption.IsSet) + if (storedPaymentMethodResource.LastFour != null) + writer.WriteString("lastFour", storedPaymentMethodResource.LastFour); + + if (storedPaymentMethodResource._NameOption.IsSet) + if (storedPaymentMethodResource.Name != null) + writer.WriteString("name", storedPaymentMethodResource.Name); + + if (storedPaymentMethodResource._NetworkTxReferenceOption.IsSet) + if (storedPaymentMethodResource.NetworkTxReference != null) + writer.WriteString("networkTxReference", storedPaymentMethodResource.NetworkTxReference); + + if (storedPaymentMethodResource._OwnerNameOption.IsSet) + if (storedPaymentMethodResource.OwnerName != null) + writer.WriteString("ownerName", storedPaymentMethodResource.OwnerName); + + if (storedPaymentMethodResource._ShopperEmailOption.IsSet) + if (storedPaymentMethodResource.ShopperEmail != null) + writer.WriteString("shopperEmail", storedPaymentMethodResource.ShopperEmail); + + if (storedPaymentMethodResource._ShopperReferenceOption.IsSet) + if (storedPaymentMethodResource.ShopperReference != null) + writer.WriteString("shopperReference", storedPaymentMethodResource.ShopperReference); + + if (storedPaymentMethodResource._SupportedRecurringProcessingModelsOption.IsSet) + { + writer.WritePropertyName("supportedRecurringProcessingModels"); + JsonSerializer.Serialize(writer, storedPaymentMethodResource.SupportedRecurringProcessingModels, jsonSerializerOptions); + } + if (storedPaymentMethodResource._TypeOption.IsSet) + if (storedPaymentMethodResource.Type != null) + writer.WriteString("type", storedPaymentMethodResource.Type); + } + } +} diff --git a/Adyen/Checkout/Models/SubInputDetail.cs b/Adyen/Checkout/Models/SubInputDetail.cs new file mode 100644 index 000000000..59506e5e0 --- /dev/null +++ b/Adyen/Checkout/Models/SubInputDetail.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SubInputDetail. + /// + public partial class SubInputDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Configuration parameters for the required input. + /// In case of a select, the items to choose from. + /// The value to provide in the result. + /// True if this input is optional to provide. + /// The type of the required input. + /// The value can be pre-filled, if available. + [JsonConstructor] + public SubInputDetail(Option?> configuration = default, Option?> items = default, Option key = default, Option optional = default, Option type = default, Option value = default) + { + _ConfigurationOption = configuration; + _ItemsOption = items; + _KeyOption = key; + _OptionalOption = optional; + _TypeOption = type; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubInputDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConfigurationOption { get; private set; } + + /// + /// Configuration parameters for the required input. + /// + /// Configuration parameters for the required input. + [JsonPropertyName("configuration")] + public Dictionary? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsOption { get; private set; } + + /// + /// In case of a select, the items to choose from. + /// + /// In case of a select, the items to choose from. + [JsonPropertyName("items")] + public List? Items { get { return this._ItemsOption; } set { this._ItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KeyOption { get; private set; } + + /// + /// The value to provide in the result. + /// + /// The value to provide in the result. + [JsonPropertyName("key")] + public string? Key { get { return this._KeyOption; } set { this._KeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OptionalOption { get; private set; } + + /// + /// True if this input is optional to provide. + /// + /// True if this input is optional to provide. + [JsonPropertyName("optional")] + public bool? Optional { get { return this._OptionalOption; } set { this._OptionalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the required input. + /// + /// The type of the required input. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The value can be pre-filled, if available. + /// + /// The value can be pre-filled, if available. + [JsonPropertyName("value")] + public string? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubInputDetail {\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" Items: ").Append(Items).Append("\n"); + sb.Append(" Key: ").Append(Key).Append("\n"); + sb.Append(" Optional: ").Append(Optional).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubInputDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubInputDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> configuration = default; + Option?> items = default; + Option key = default; + Option optional = default; + Option type = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "configuration": + configuration = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "items": + items = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "key": + key = new Option(utf8JsonReader.GetString()!); + break; + case "optional": + optional = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SubInputDetail(configuration, items, key, optional, type, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubInputDetail subInputDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subInputDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubInputDetail subInputDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (subInputDetail._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, subInputDetail.Configuration, jsonSerializerOptions); + } + if (subInputDetail._ItemsOption.IsSet) + { + writer.WritePropertyName("items"); + JsonSerializer.Serialize(writer, subInputDetail.Items, jsonSerializerOptions); + } + if (subInputDetail._KeyOption.IsSet) + if (subInputDetail.Key != null) + writer.WriteString("key", subInputDetail.Key); + + if (subInputDetail._OptionalOption.IsSet) + writer.WriteBoolean("optional", subInputDetail._OptionalOption.Value!.Value); + + if (subInputDetail._TypeOption.IsSet) + if (subInputDetail.Type != null) + writer.WriteString("type", subInputDetail.Type); + + if (subInputDetail._ValueOption.IsSet) + if (subInputDetail.Value != null) + writer.WriteString("value", subInputDetail.Value); + } + } +} diff --git a/Adyen/Checkout/Models/SubMerchant.cs b/Adyen/Checkout/Models/SubMerchant.cs new file mode 100644 index 000000000..549c40b72 --- /dev/null +++ b/Adyen/Checkout/Models/SubMerchant.cs @@ -0,0 +1,277 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SubMerchant. + /// + public partial class SubMerchant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonConstructor] + public SubMerchant(Option city = default, Option country = default, Option mcc = default, Option name = default, Option taxId = default) + { + _CityOption = city; + _CountryOption = country; + _MccOption = mcc; + _NameOption = name; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubMerchant() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubMerchant {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubMerchantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubMerchant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option mcc = default; + Option name = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SubMerchant(city, country, mcc, name, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubMerchant subMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subMerchant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubMerchant subMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + if (subMerchant._CityOption.IsSet) + if (subMerchant.City != null) + writer.WriteString("city", subMerchant.City); + + if (subMerchant._CountryOption.IsSet) + if (subMerchant.Country != null) + writer.WriteString("country", subMerchant.Country); + + if (subMerchant._MccOption.IsSet) + if (subMerchant.Mcc != null) + writer.WriteString("mcc", subMerchant.Mcc); + + if (subMerchant._NameOption.IsSet) + if (subMerchant.Name != null) + writer.WriteString("name", subMerchant.Name); + + if (subMerchant._TaxIdOption.IsSet) + if (subMerchant.TaxId != null) + writer.WriteString("taxId", subMerchant.TaxId); + } + } +} diff --git a/Adyen/Checkout/Models/SubMerchantInfo.cs b/Adyen/Checkout/Models/SubMerchantInfo.cs new file mode 100644 index 000000000..75e246b41 --- /dev/null +++ b/Adyen/Checkout/Models/SubMerchantInfo.cs @@ -0,0 +1,419 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// SubMerchantInfo. + /// + public partial class SubMerchantInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// amount + /// Required for transactions performed by registered payment facilitators. The email associated with the sub-merchant's account. + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The phone number associated with the sub-merchant's account. + /// registeredSince + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// Required for transactions performed by registered payment facilitators. The sub-merchant's URL on the platform, i.e. the sub-merchant's shop. + [JsonConstructor] + public SubMerchantInfo(Option address = default, Option amount = default, Option email = default, Option id = default, Option mcc = default, Option name = default, Option phoneNumber = default, Option registeredSince = default, Option taxId = default, Option url = default) + { + _AddressOption = address; + _AmountOption = amount; + _EmailOption = email; + _IdOption = id; + _MccOption = mcc; + _NameOption = name; + _PhoneNumberOption = phoneNumber; + _RegisteredSinceOption = registeredSince; + _TaxIdOption = taxId; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubMerchantInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public BillingAddress? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The email associated with the sub-merchant's account. + /// + /// Required for transactions performed by registered payment facilitators. The email associated with the sub-merchant's account. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The phone number associated with the sub-merchant's account. + /// + /// Required for transactions performed by registered payment facilitators. The phone number associated with the sub-merchant's account. + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegisteredSinceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("registeredSince")] + public string? RegisteredSince { get { return this._RegisteredSinceOption; } set { this._RegisteredSinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's URL on the platform, i.e. the sub-merchant's shop. + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's URL on the platform, i.e. the sub-merchant's shop. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubMerchantInfo {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" RegisteredSince: ").Append(RegisteredSince).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) maxLength + if (this.Email != null && this.Email.Length > 320) + { + yield return new ValidationResult("Invalid value for Email, length must be less than 320.", new [] { "Email" }); + } + + // PhoneNumber (string) maxLength + if (this.PhoneNumber != null && this.PhoneNumber.Length > 20) + { + yield return new ValidationResult("Invalid value for PhoneNumber, length must be less than 20.", new [] { "PhoneNumber" }); + } + + // Url (string) maxLength + if (this.Url != null && this.Url.Length > 320) + { + yield return new ValidationResult("Invalid value for Url, length must be less than 320.", new [] { "Url" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubMerchantInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubMerchantInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option amount = default; + Option email = default; + Option id = default; + Option mcc = default; + Option name = default; + Option phoneNumber = default; + Option registeredSince = default; + Option taxId = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "registeredSince": + registeredSince = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SubMerchantInfo(address, amount, email, id, mcc, name, phoneNumber, registeredSince, taxId, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubMerchantInfo subMerchantInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subMerchantInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubMerchantInfo subMerchantInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (subMerchantInfo._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, subMerchantInfo.Address, jsonSerializerOptions); + } + if (subMerchantInfo._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, subMerchantInfo.Amount, jsonSerializerOptions); + } + if (subMerchantInfo._EmailOption.IsSet) + if (subMerchantInfo.Email != null) + writer.WriteString("email", subMerchantInfo.Email); + + if (subMerchantInfo._IdOption.IsSet) + if (subMerchantInfo.Id != null) + writer.WriteString("id", subMerchantInfo.Id); + + if (subMerchantInfo._MccOption.IsSet) + if (subMerchantInfo.Mcc != null) + writer.WriteString("mcc", subMerchantInfo.Mcc); + + if (subMerchantInfo._NameOption.IsSet) + if (subMerchantInfo.Name != null) + writer.WriteString("name", subMerchantInfo.Name); + + if (subMerchantInfo._PhoneNumberOption.IsSet) + if (subMerchantInfo.PhoneNumber != null) + writer.WriteString("phoneNumber", subMerchantInfo.PhoneNumber); + + if (subMerchantInfo._RegisteredSinceOption.IsSet) + if (subMerchantInfo.RegisteredSince != null) + writer.WriteString("registeredSince", subMerchantInfo.RegisteredSince); + + if (subMerchantInfo._TaxIdOption.IsSet) + if (subMerchantInfo.TaxId != null) + writer.WriteString("taxId", subMerchantInfo.TaxId); + + if (subMerchantInfo._UrlOption.IsSet) + if (subMerchantInfo.Url != null) + writer.WriteString("url", subMerchantInfo.Url); + } + } +} diff --git a/Adyen/Checkout/Models/Surcharge.cs b/Adyen/Checkout/Models/Surcharge.cs new file mode 100644 index 000000000..180d1c649 --- /dev/null +++ b/Adyen/Checkout/Models/Surcharge.cs @@ -0,0 +1,170 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Surcharge. + /// + public partial class Surcharge : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [surcharge](https://docs.adyen.com/online-payments/surcharge/) amount to apply to the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). When you apply surcharge, include the surcharge in the `amount.value` field. Review our [Surcharge compliance guide](https://docs.adyen.com/development-resources/surcharge-compliance/) to learn about how to comply with regulatory requirements when applying surcharge. + [JsonConstructor] + public Surcharge(long value) + { + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Surcharge() + { + } + + partial void OnCreated(); + + /// + /// The [surcharge](https://docs.adyen.com/online-payments/surcharge/) amount to apply to the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). When you apply surcharge, include the surcharge in the `amount.value` field. Review our [Surcharge compliance guide](https://docs.adyen.com/development-resources/surcharge-compliance/) to learn about how to comply with regulatory requirements when applying surcharge. + /// + /// The [surcharge](https://docs.adyen.com/online-payments/surcharge/) amount to apply to the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). When you apply surcharge, include the surcharge in the `amount.value` field. Review our [Surcharge compliance guide](https://docs.adyen.com/development-resources/surcharge-compliance/) to learn about how to comply with regulatory requirements when applying surcharge. + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Surcharge {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SurchargeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Surcharge Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Surcharge.", nameof(value)); + + return new Surcharge(value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Surcharge surcharge, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, surcharge, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Surcharge surcharge, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("value", surcharge.Value); + } + } +} diff --git a/Adyen/Checkout/Models/TaxTotal.cs b/Adyen/Checkout/Models/TaxTotal.cs new file mode 100644 index 000000000..60cf73d79 --- /dev/null +++ b/Adyen/Checkout/Models/TaxTotal.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// TaxTotal. + /// + public partial class TaxTotal : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public TaxTotal(Option amount = default) + { + _AmountOption = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TaxTotal() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaxTotal {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaxTotalJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TaxTotal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TaxTotal(amount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaxTotal taxTotal, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, taxTotal, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaxTotal taxTotal, JsonSerializerOptions jsonSerializerOptions) + { + + if (taxTotal._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, taxTotal.Amount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDS2RequestData.cs b/Adyen/Checkout/Models/ThreeDS2RequestData.cs new file mode 100644 index 000000000..2ea7bb267 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDS2RequestData.cs @@ -0,0 +1,1892 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDS2RequestData. + /// + public partial class ThreeDS2RequestData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + /// acctInfo + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false) + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// deviceRenderOptions + /// homePhone + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// mobilePhone + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// Indicates the type of payment for which an authentication is requested (message extension) + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// sdkEphemPubKey + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. (default to 60) + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + /// Completion indicator for the device fingerprinting. + /// Indicates the type of Authentication request. + /// threeDSRequestorAuthenticationInfo + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// threeDSRequestorPriorAuthenticationInfo + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// Identify the type of the transaction being authenticated. + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// workPhone + [JsonConstructor] + public ThreeDS2RequestData(string deviceChannel, Option acctInfo = default, Option acctType = default, Option acquirerBIN = default, Option acquirerMerchantID = default, Option addrMatch = default, Option authenticationOnly = default, Option challengeIndicator = default, Option deviceRenderOptions = default, Option homePhone = default, Option mcc = default, Option merchantName = default, Option messageVersion = default, Option mobilePhone = default, Option notificationURL = default, Option payTokenInd = default, Option paymentAuthenticationUseCase = default, Option purchaseInstalData = default, Option recurringExpiry = default, Option recurringFrequency = default, Option sdkAppID = default, Option sdkEncData = default, Option sdkEphemPubKey = default, Option sdkMaxTimeout = default, Option sdkReferenceNumber = default, Option sdkTransID = default, Option sdkVersion = default, Option threeDSCompInd = default, Option threeDSRequestorAuthenticationInd = default, Option threeDSRequestorAuthenticationInfo = default, Option threeDSRequestorChallengeInd = default, Option threeDSRequestorID = default, Option threeDSRequestorName = default, Option threeDSRequestorPriorAuthenticationInfo = default, Option threeDSRequestorURL = default, Option transType = default, Option transactionType = default, Option whiteListStatus = default, Option workPhone = default) + { + DeviceChannel = deviceChannel; + _AcctInfoOption = acctInfo; + _AcctTypeOption = acctType; + _AcquirerBINOption = acquirerBIN; + _AcquirerMerchantIDOption = acquirerMerchantID; + _AddrMatchOption = addrMatch; + _AuthenticationOnlyOption = authenticationOnly; + _ChallengeIndicatorOption = challengeIndicator; + _DeviceRenderOptionsOption = deviceRenderOptions; + _HomePhoneOption = homePhone; + _MccOption = mcc; + _MerchantNameOption = merchantName; + _MessageVersionOption = messageVersion; + _MobilePhoneOption = mobilePhone; + _NotificationURLOption = notificationURL; + _PayTokenIndOption = payTokenInd; + _PaymentAuthenticationUseCaseOption = paymentAuthenticationUseCase; + _PurchaseInstalDataOption = purchaseInstalData; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _SdkAppIDOption = sdkAppID; + _SdkEncDataOption = sdkEncData; + _SdkEphemPubKeyOption = sdkEphemPubKey; + _SdkMaxTimeoutOption = sdkMaxTimeout; + _SdkReferenceNumberOption = sdkReferenceNumber; + _SdkTransIDOption = sdkTransID; + _SdkVersionOption = sdkVersion; + _ThreeDSCompIndOption = threeDSCompInd; + _ThreeDSRequestorAuthenticationIndOption = threeDSRequestorAuthenticationInd; + _ThreeDSRequestorAuthenticationInfoOption = threeDSRequestorAuthenticationInfo; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _ThreeDSRequestorIDOption = threeDSRequestorID; + _ThreeDSRequestorNameOption = threeDSRequestorName; + _ThreeDSRequestorPriorAuthenticationInfoOption = threeDSRequestorPriorAuthenticationInfo; + _ThreeDSRequestorURLOption = threeDSRequestorURL; + _TransTypeOption = transType; + _TransactionTypeOption = transactionType; + _WhiteListStatusOption = whiteListStatus; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2RequestData() + { + } + + partial void OnCreated(); + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonConverter(typeof(AcctTypeEnumJsonConverter))] + public class AcctTypeEnum : IEnum + { + /// + /// Returns the value of the AcctTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AcctTypeEnum._01 - 01 + /// + public static readonly AcctTypeEnum _01 = new("01"); + + /// + /// AcctTypeEnum._02 - 02 + /// + public static readonly AcctTypeEnum _02 = new("02"); + + /// + /// AcctTypeEnum._03 - 03 + /// + public static readonly AcctTypeEnum _03 = new("03"); + + private AcctTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AcctTypeEnum?(string? value) => value == null ? null : new AcctTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AcctTypeEnum? option) => option?.Value; + + public static bool operator ==(AcctTypeEnum? left, AcctTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AcctTypeEnum? left, AcctTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AcctTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AcctTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => AcctTypeEnum._01, + "02" => AcctTypeEnum._02, + "03" => AcctTypeEnum._03, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AcctTypeEnum? value) + { + if (value == null) + return null; + + if (value == AcctTypeEnum._01) + return "01"; + + if (value == AcctTypeEnum._02) + return "02"; + + if (value == AcctTypeEnum._03) + return "03"; + + return null; + } + + /// + /// JsonConverter for writing AcctTypeEnum. + /// + public class AcctTypeEnumJsonConverter : JsonConverter + { + public override AcctTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AcctTypeEnum.FromStringOrDefault(value) ?? new AcctTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AcctTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AcctTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctTypeOption { get; private set; } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonPropertyName("acctType")] + public AcctTypeEnum? AcctType { get { return this._AcctTypeOption; } set { this._AcctTypeOption = new(value); } } + + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + [JsonConverter(typeof(AddrMatchEnumJsonConverter))] + public class AddrMatchEnum : IEnum + { + /// + /// Returns the value of the AddrMatchEnum. + /// + public string? Value { get; set; } + + /// + /// AddrMatchEnum.Y - Y + /// + public static readonly AddrMatchEnum Y = new("Y"); + + /// + /// AddrMatchEnum.N - N + /// + public static readonly AddrMatchEnum N = new("N"); + + private AddrMatchEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AddrMatchEnum?(string? value) => value == null ? null : new AddrMatchEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AddrMatchEnum? option) => option?.Value; + + public static bool operator ==(AddrMatchEnum? left, AddrMatchEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AddrMatchEnum? left, AddrMatchEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AddrMatchEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AddrMatchEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => AddrMatchEnum.Y, + "N" => AddrMatchEnum.N, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AddrMatchEnum? value) + { + if (value == null) + return null; + + if (value == AddrMatchEnum.Y) + return "Y"; + + if (value == AddrMatchEnum.N) + return "N"; + + return null; + } + + /// + /// JsonConverter for writing AddrMatchEnum. + /// + public class AddrMatchEnumJsonConverter : JsonConverter + { + public override AddrMatchEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AddrMatchEnum.FromStringOrDefault(value) ?? new AddrMatchEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AddrMatchEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AddrMatchEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddrMatchOption { get; private set; } + + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + [JsonPropertyName("addrMatch")] + public AddrMatchEnum? AddrMatch { get { return this._AddrMatchOption; } set { this._AddrMatchOption = new(value); } } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonConverter(typeof(ChallengeIndicatorEnumJsonConverter))] + public class ChallengeIndicatorEnum : IEnum + { + /// + /// Returns the value of the ChallengeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeIndicatorEnum.NoPreference - noPreference + /// + public static readonly ChallengeIndicatorEnum NoPreference = new("noPreference"); + + /// + /// ChallengeIndicatorEnum.RequestNoChallenge - requestNoChallenge + /// + public static readonly ChallengeIndicatorEnum RequestNoChallenge = new("requestNoChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallenge - requestChallenge + /// + public static readonly ChallengeIndicatorEnum RequestChallenge = new("requestChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallengeAsMandate - requestChallengeAsMandate + /// + public static readonly ChallengeIndicatorEnum RequestChallengeAsMandate = new("requestChallengeAsMandate"); + + private ChallengeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeIndicatorEnum?(string? value) => value == null ? null : new ChallengeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "noPreference" => ChallengeIndicatorEnum.NoPreference, + "requestNoChallenge" => ChallengeIndicatorEnum.RequestNoChallenge, + "requestChallenge" => ChallengeIndicatorEnum.RequestChallenge, + "requestChallengeAsMandate" => ChallengeIndicatorEnum.RequestChallengeAsMandate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeIndicatorEnum.NoPreference) + return "noPreference"; + + if (value == ChallengeIndicatorEnum.RequestNoChallenge) + return "requestNoChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallenge) + return "requestChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallengeAsMandate) + return "requestChallengeAsMandate"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeIndicatorEnum. + /// + public class ChallengeIndicatorEnumJsonConverter : JsonConverter + { + public override ChallengeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeIndicatorEnum.FromStringOrDefault(value) ?? new ChallengeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeIndicatorOption { get; private set; } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonPropertyName("challengeIndicator")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `threeDSRequestorChallengeInd` instead.")] + public ChallengeIndicatorEnum? ChallengeIndicator { get { return this._ChallengeIndicatorOption; } set { this._ChallengeIndicatorOption = new(value); } } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonConverter(typeof(TransTypeEnumJsonConverter))] + public class TransTypeEnum : IEnum + { + /// + /// Returns the value of the TransTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransTypeEnum._01 - 01 + /// + public static readonly TransTypeEnum _01 = new("01"); + + /// + /// TransTypeEnum._03 - 03 + /// + public static readonly TransTypeEnum _03 = new("03"); + + /// + /// TransTypeEnum._10 - 10 + /// + public static readonly TransTypeEnum _10 = new("10"); + + /// + /// TransTypeEnum._11 - 11 + /// + public static readonly TransTypeEnum _11 = new("11"); + + /// + /// TransTypeEnum._28 - 28 + /// + public static readonly TransTypeEnum _28 = new("28"); + + private TransTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransTypeEnum?(string? value) => value == null ? null : new TransTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransTypeEnum? option) => option?.Value; + + public static bool operator ==(TransTypeEnum? left, TransTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransTypeEnum? left, TransTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => TransTypeEnum._01, + "03" => TransTypeEnum._03, + "10" => TransTypeEnum._10, + "11" => TransTypeEnum._11, + "28" => TransTypeEnum._28, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransTypeEnum._01) + return "01"; + + if (value == TransTypeEnum._03) + return "03"; + + if (value == TransTypeEnum._10) + return "10"; + + if (value == TransTypeEnum._11) + return "11"; + + if (value == TransTypeEnum._28) + return "28"; + + return null; + } + + /// + /// JsonConverter for writing TransTypeEnum. + /// + public class TransTypeEnumJsonConverter : JsonConverter + { + public override TransTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransTypeEnum.FromStringOrDefault(value) ?? new TransTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransTypeOption { get; private set; } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonPropertyName("transType")] + public TransTypeEnum? TransType { get { return this._TransTypeOption; } set { this._TransTypeOption = new(value); } } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonConverter(typeof(TransactionTypeEnumJsonConverter))] + public class TransactionTypeEnum : IEnum + { + /// + /// Returns the value of the TransactionTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransactionTypeEnum.GoodsOrServicePurchase - goodsOrServicePurchase + /// + public static readonly TransactionTypeEnum GoodsOrServicePurchase = new("goodsOrServicePurchase"); + + /// + /// TransactionTypeEnum.CheckAcceptance - checkAcceptance + /// + public static readonly TransactionTypeEnum CheckAcceptance = new("checkAcceptance"); + + /// + /// TransactionTypeEnum.AccountFunding - accountFunding + /// + public static readonly TransactionTypeEnum AccountFunding = new("accountFunding"); + + /// + /// TransactionTypeEnum.QuasiCashTransaction - quasiCashTransaction + /// + public static readonly TransactionTypeEnum QuasiCashTransaction = new("quasiCashTransaction"); + + /// + /// TransactionTypeEnum.PrepaidActivationAndLoad - prepaidActivationAndLoad + /// + public static readonly TransactionTypeEnum PrepaidActivationAndLoad = new("prepaidActivationAndLoad"); + + private TransactionTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransactionTypeEnum?(string? value) => value == null ? null : new TransactionTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransactionTypeEnum? option) => option?.Value; + + public static bool operator ==(TransactionTypeEnum? left, TransactionTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransactionTypeEnum? left, TransactionTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransactionTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransactionTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "goodsOrServicePurchase" => TransactionTypeEnum.GoodsOrServicePurchase, + "checkAcceptance" => TransactionTypeEnum.CheckAcceptance, + "accountFunding" => TransactionTypeEnum.AccountFunding, + "quasiCashTransaction" => TransactionTypeEnum.QuasiCashTransaction, + "prepaidActivationAndLoad" => TransactionTypeEnum.PrepaidActivationAndLoad, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransactionTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransactionTypeEnum.GoodsOrServicePurchase) + return "goodsOrServicePurchase"; + + if (value == TransactionTypeEnum.CheckAcceptance) + return "checkAcceptance"; + + if (value == TransactionTypeEnum.AccountFunding) + return "accountFunding"; + + if (value == TransactionTypeEnum.QuasiCashTransaction) + return "quasiCashTransaction"; + + if (value == TransactionTypeEnum.PrepaidActivationAndLoad) + return "prepaidActivationAndLoad"; + + return null; + } + + /// + /// JsonConverter for writing TransactionTypeEnum. + /// + public class TransactionTypeEnumJsonConverter : JsonConverter + { + public override TransactionTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransactionTypeEnum.FromStringOrDefault(value) ?? new TransactionTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransactionTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransactionTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionTypeOption { get; private set; } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonPropertyName("transactionType")] + public TransactionTypeEnum? TransactionType { get { return this._TransactionTypeOption; } set { this._TransactionTypeOption = new(value); } } + + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + [JsonPropertyName("deviceChannel")] + public string DeviceChannel { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acctInfo")] + public AcctInfo? AcctInfo { get { return this._AcctInfoOption; } set { this._AcctInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerBINOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerBIN")] + public string? AcquirerBIN { get { return this._AcquirerBINOption; } set { this._AcquirerBINOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerMerchantIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerMerchantID")] + public string? AcquirerMerchantID { get { return this._AcquirerMerchantIDOption; } set { this._AcquirerMerchantIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOnlyOption { get; private set; } + + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + [JsonPropertyName("authenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v50. Use `threeDSAuthenticationOnly` instead.")] + public bool? AuthenticationOnly { get { return this._AuthenticationOnlyOption; } set { this._AuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceRenderOptionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deviceRenderOptions")] + public DeviceRenderOptions? DeviceRenderOptions { get { return this._DeviceRenderOptionsOption; } set { this._DeviceRenderOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("homePhone")] + public Phone? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + [JsonPropertyName("merchantName")] + public string? MerchantName { get { return this._MerchantNameOption; } set { this._MerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mobilePhone")] + public Phone? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationURLOption { get; private set; } + + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + [JsonPropertyName("notificationURL")] + public string? NotificationURL { get { return this._NotificationURLOption; } set { this._NotificationURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayTokenIndOption { get; private set; } + + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + [JsonPropertyName("payTokenInd")] + public bool? PayTokenInd { get { return this._PayTokenIndOption; } set { this._PayTokenIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAuthenticationUseCaseOption { get; private set; } + + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + [JsonPropertyName("paymentAuthenticationUseCase")] + public string? PaymentAuthenticationUseCase { get { return this._PaymentAuthenticationUseCaseOption; } set { this._PaymentAuthenticationUseCaseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurchaseInstalDataOption { get; private set; } + + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + [JsonPropertyName("purchaseInstalData")] + public string? PurchaseInstalData { get { return this._PurchaseInstalDataOption; } set { this._PurchaseInstalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkAppIDOption { get; private set; } + + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + [JsonPropertyName("sdkAppID")] + public string? SdkAppID { get { return this._SdkAppIDOption; } set { this._SdkAppIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEncDataOption { get; private set; } + + /// + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + [JsonPropertyName("sdkEncData")] + public string? SdkEncData { get { return this._SdkEncDataOption; } set { this._SdkEncDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEphemPubKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sdkEphemPubKey")] + public SDKEphemPubKey? SdkEphemPubKey { get { return this._SdkEphemPubKeyOption; } set { this._SdkEphemPubKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkMaxTimeoutOption { get; private set; } + + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + [JsonPropertyName("sdkMaxTimeout")] + public int? SdkMaxTimeout { get { return this._SdkMaxTimeoutOption; } set { this._SdkMaxTimeoutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkReferenceNumberOption { get; private set; } + + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkReferenceNumber")] + public string? SdkReferenceNumber { get { return this._SdkReferenceNumberOption; } set { this._SdkReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkTransIDOption { get; private set; } + + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkTransID")] + public string? SdkTransID { get { return this._SdkTransIDOption; } set { this._SdkTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkVersionOption { get; private set; } + + /// + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + /// + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkVersion")] + public string? SdkVersion { get { return this._SdkVersionOption; } set { this._SdkVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSCompIndOption { get; private set; } + + /// + /// Completion indicator for the device fingerprinting. + /// + /// Completion indicator for the device fingerprinting. + [JsonPropertyName("threeDSCompInd")] + public string? ThreeDSCompInd { get { return this._ThreeDSCompIndOption; } set { this._ThreeDSCompIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationIndOption { get; private set; } + + /// + /// Indicates the type of Authentication request. + /// + /// Indicates the type of Authentication request. + [JsonPropertyName("threeDSRequestorAuthenticationInd")] + public string? ThreeDSRequestorAuthenticationInd { get { return this._ThreeDSRequestorAuthenticationIndOption; } set { this._ThreeDSRequestorAuthenticationIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorAuthenticationInfo")] + public ThreeDSRequestorAuthenticationInfo? ThreeDSRequestorAuthenticationInfo { get { return this._ThreeDSRequestorAuthenticationInfoOption; } set { this._ThreeDSRequestorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorID")] + public string? ThreeDSRequestorID { get { return this._ThreeDSRequestorIDOption; } set { this._ThreeDSRequestorIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorName")] + public string? ThreeDSRequestorName { get { return this._ThreeDSRequestorNameOption; } set { this._ThreeDSRequestorNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorPriorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorPriorAuthenticationInfo")] + public ThreeDSRequestorPriorAuthenticationInfo? ThreeDSRequestorPriorAuthenticationInfo { get { return this._ThreeDSRequestorPriorAuthenticationInfoOption; } set { this._ThreeDSRequestorPriorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorURLOption { get; private set; } + + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + [JsonPropertyName("threeDSRequestorURL")] + public string? ThreeDSRequestorURL { get { return this._ThreeDSRequestorURLOption; } set { this._ThreeDSRequestorURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WhiteListStatusOption { get; private set; } + + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + [JsonPropertyName("whiteListStatus")] + public string? WhiteListStatus { get { return this._WhiteListStatusOption; } set { this._WhiteListStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("workPhone")] + public Phone? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2RequestData {\n"); + sb.Append(" DeviceChannel: ").Append(DeviceChannel).Append("\n"); + sb.Append(" AcctInfo: ").Append(AcctInfo).Append("\n"); + sb.Append(" AcctType: ").Append(AcctType).Append("\n"); + sb.Append(" AcquirerBIN: ").Append(AcquirerBIN).Append("\n"); + sb.Append(" AcquirerMerchantID: ").Append(AcquirerMerchantID).Append("\n"); + sb.Append(" AddrMatch: ").Append(AddrMatch).Append("\n"); + sb.Append(" AuthenticationOnly: ").Append(AuthenticationOnly).Append("\n"); + sb.Append(" ChallengeIndicator: ").Append(ChallengeIndicator).Append("\n"); + sb.Append(" DeviceRenderOptions: ").Append(DeviceRenderOptions).Append("\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" NotificationURL: ").Append(NotificationURL).Append("\n"); + sb.Append(" PayTokenInd: ").Append(PayTokenInd).Append("\n"); + sb.Append(" PaymentAuthenticationUseCase: ").Append(PaymentAuthenticationUseCase).Append("\n"); + sb.Append(" PurchaseInstalData: ").Append(PurchaseInstalData).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" SdkAppID: ").Append(SdkAppID).Append("\n"); + sb.Append(" SdkEncData: ").Append(SdkEncData).Append("\n"); + sb.Append(" SdkEphemPubKey: ").Append(SdkEphemPubKey).Append("\n"); + sb.Append(" SdkMaxTimeout: ").Append(SdkMaxTimeout).Append("\n"); + sb.Append(" SdkReferenceNumber: ").Append(SdkReferenceNumber).Append("\n"); + sb.Append(" SdkTransID: ").Append(SdkTransID).Append("\n"); + sb.Append(" SdkVersion: ").Append(SdkVersion).Append("\n"); + sb.Append(" ThreeDSCompInd: ").Append(ThreeDSCompInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInd: ").Append(ThreeDSRequestorAuthenticationInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInfo: ").Append(ThreeDSRequestorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" ThreeDSRequestorID: ").Append(ThreeDSRequestorID).Append("\n"); + sb.Append(" ThreeDSRequestorName: ").Append(ThreeDSRequestorName).Append("\n"); + sb.Append(" ThreeDSRequestorPriorAuthenticationInfo: ").Append(ThreeDSRequestorPriorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorURL: ").Append(ThreeDSRequestorURL).Append("\n"); + sb.Append(" TransType: ").Append(TransType).Append("\n"); + sb.Append(" TransactionType: ").Append(TransactionType).Append("\n"); + sb.Append(" WhiteListStatus: ").Append(WhiteListStatus).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // PurchaseInstalData (string) maxLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length > 3) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be less than 3.", new [] { "PurchaseInstalData" }); + } + + // PurchaseInstalData (string) minLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length < 1) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be greater than 1.", new [] { "PurchaseInstalData" }); + } + + // RecurringFrequency (string) maxLength + if (this.RecurringFrequency != null && this.RecurringFrequency.Length > 4) + { + yield return new ValidationResult("Invalid value for RecurringFrequency, length must be less than 4.", new [] { "RecurringFrequency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2RequestDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2RequestData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option deviceChannel = default; + Option acctInfo = default; + Option acctType = default; + Option acquirerBIN = default; + Option acquirerMerchantID = default; + Option addrMatch = default; + Option authenticationOnly = default; + Option challengeIndicator = default; + Option deviceRenderOptions = default; + Option homePhone = default; + Option mcc = default; + Option merchantName = default; + Option messageVersion = default; + Option mobilePhone = default; + Option notificationURL = default; + Option payTokenInd = default; + Option paymentAuthenticationUseCase = default; + Option purchaseInstalData = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option sdkAppID = default; + Option sdkEncData = default; + Option sdkEphemPubKey = default; + Option sdkMaxTimeout = default; + Option sdkReferenceNumber = default; + Option sdkTransID = default; + Option sdkVersion = default; + Option threeDSCompInd = default; + Option threeDSRequestorAuthenticationInd = default; + Option threeDSRequestorAuthenticationInfo = default; + Option threeDSRequestorChallengeInd = default; + Option threeDSRequestorID = default; + Option threeDSRequestorName = default; + Option threeDSRequestorPriorAuthenticationInfo = default; + Option threeDSRequestorURL = default; + Option transType = default; + Option transactionType = default; + Option whiteListStatus = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "deviceChannel": + deviceChannel = new Option(utf8JsonReader.GetString()!); + break; + case "acctInfo": + acctInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acctType": + string? acctTypeRawValue = utf8JsonReader.GetString(); + acctType = new Option(ThreeDS2RequestData.AcctTypeEnum.FromStringOrDefault(acctTypeRawValue)); + break; + case "acquirerBIN": + acquirerBIN = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerMerchantID": + acquirerMerchantID = new Option(utf8JsonReader.GetString()!); + break; + case "addrMatch": + string? addrMatchRawValue = utf8JsonReader.GetString(); + addrMatch = new Option(ThreeDS2RequestData.AddrMatchEnum.FromStringOrDefault(addrMatchRawValue)); + break; + case "authenticationOnly": + authenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "challengeIndicator": + string? challengeIndicatorRawValue = utf8JsonReader.GetString(); + challengeIndicator = new Option(ThreeDS2RequestData.ChallengeIndicatorEnum.FromStringOrDefault(challengeIndicatorRawValue)); + break; + case "deviceRenderOptions": + deviceRenderOptions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "homePhone": + homePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "mobilePhone": + mobilePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notificationURL": + notificationURL = new Option(utf8JsonReader.GetString()!); + break; + case "payTokenInd": + payTokenInd = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentAuthenticationUseCase": + paymentAuthenticationUseCase = new Option(utf8JsonReader.GetString()!); + break; + case "purchaseInstalData": + purchaseInstalData = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "sdkAppID": + sdkAppID = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEncData": + sdkEncData = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEphemPubKey": + sdkEphemPubKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sdkMaxTimeout": + sdkMaxTimeout = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "sdkReferenceNumber": + sdkReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sdkTransID": + sdkTransID = new Option(utf8JsonReader.GetString()!); + break; + case "sdkVersion": + sdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSCompInd": + threeDSCompInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInd": + threeDSRequestorAuthenticationInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInfo": + threeDSRequestorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "threeDSRequestorID": + threeDSRequestorID = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorName": + threeDSRequestorName = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorPriorAuthenticationInfo": + threeDSRequestorPriorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorURL": + threeDSRequestorURL = new Option(utf8JsonReader.GetString()!); + break; + case "transType": + string? transTypeRawValue = utf8JsonReader.GetString(); + transType = new Option(ThreeDS2RequestData.TransTypeEnum.FromStringOrDefault(transTypeRawValue)); + break; + case "transactionType": + string? transactionTypeRawValue = utf8JsonReader.GetString(); + transactionType = new Option(ThreeDS2RequestData.TransactionTypeEnum.FromStringOrDefault(transactionTypeRawValue)); + break; + case "whiteListStatus": + whiteListStatus = new Option(utf8JsonReader.GetString()!); + break; + case "workPhone": + workPhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!deviceChannel.IsSet) + throw new ArgumentException("Property is required for class ThreeDS2RequestData.", nameof(deviceChannel)); + + return new ThreeDS2RequestData(deviceChannel.Value!, acctInfo, acctType, acquirerBIN, acquirerMerchantID, addrMatch, authenticationOnly, challengeIndicator, deviceRenderOptions, homePhone, mcc, merchantName, messageVersion, mobilePhone, notificationURL, payTokenInd, paymentAuthenticationUseCase, purchaseInstalData, recurringExpiry, recurringFrequency, sdkAppID, sdkEncData, sdkEphemPubKey, sdkMaxTimeout, sdkReferenceNumber, sdkTransID, sdkVersion, threeDSCompInd, threeDSRequestorAuthenticationInd, threeDSRequestorAuthenticationInfo, threeDSRequestorChallengeInd, threeDSRequestorID, threeDSRequestorName, threeDSRequestorPriorAuthenticationInfo, threeDSRequestorURL, transType, transactionType, whiteListStatus, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2RequestData threeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2RequestData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2RequestData threeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2RequestData.DeviceChannel != null) + writer.WriteString("deviceChannel", threeDS2RequestData.DeviceChannel); + + if (threeDS2RequestData._AcctInfoOption.IsSet) + { + writer.WritePropertyName("acctInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.AcctInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._AcctTypeOption.IsSet && threeDS2RequestData.AcctType != null) + { + string? acctTypeRawValue = ThreeDS2RequestData.AcctTypeEnum.ToJsonValue(threeDS2RequestData._AcctTypeOption.Value!.Value); + writer.WriteString("acctType", acctTypeRawValue); + } + + if (threeDS2RequestData._AcquirerBINOption.IsSet) + if (threeDS2RequestData.AcquirerBIN != null) + writer.WriteString("acquirerBIN", threeDS2RequestData.AcquirerBIN); + + if (threeDS2RequestData._AcquirerMerchantIDOption.IsSet) + if (threeDS2RequestData.AcquirerMerchantID != null) + writer.WriteString("acquirerMerchantID", threeDS2RequestData.AcquirerMerchantID); + + if (threeDS2RequestData._AddrMatchOption.IsSet && threeDS2RequestData.AddrMatch != null) + { + string? addrMatchRawValue = ThreeDS2RequestData.AddrMatchEnum.ToJsonValue(threeDS2RequestData._AddrMatchOption.Value!.Value); + writer.WriteString("addrMatch", addrMatchRawValue); + } + + if (threeDS2RequestData._AuthenticationOnlyOption.IsSet) + writer.WriteBoolean("authenticationOnly", threeDS2RequestData._AuthenticationOnlyOption.Value!.Value); + + if (threeDS2RequestData._ChallengeIndicatorOption.IsSet && threeDS2RequestData.ChallengeIndicator != null) + { + string? challengeIndicatorRawValue = ThreeDS2RequestData.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestData._ChallengeIndicatorOption.Value!.Value); + writer.WriteString("challengeIndicator", challengeIndicatorRawValue); + } + + if (threeDS2RequestData._DeviceRenderOptionsOption.IsSet) + { + writer.WritePropertyName("deviceRenderOptions"); + JsonSerializer.Serialize(writer, threeDS2RequestData.DeviceRenderOptions, jsonSerializerOptions); + } + if (threeDS2RequestData._HomePhoneOption.IsSet) + { + writer.WritePropertyName("homePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.HomePhone, jsonSerializerOptions); + } + if (threeDS2RequestData._MccOption.IsSet) + if (threeDS2RequestData.Mcc != null) + writer.WriteString("mcc", threeDS2RequestData.Mcc); + + if (threeDS2RequestData._MerchantNameOption.IsSet) + if (threeDS2RequestData.MerchantName != null) + writer.WriteString("merchantName", threeDS2RequestData.MerchantName); + + if (threeDS2RequestData._MessageVersionOption.IsSet) + if (threeDS2RequestData.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2RequestData.MessageVersion); + + if (threeDS2RequestData._MobilePhoneOption.IsSet) + { + writer.WritePropertyName("mobilePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.MobilePhone, jsonSerializerOptions); + } + if (threeDS2RequestData._NotificationURLOption.IsSet) + if (threeDS2RequestData.NotificationURL != null) + writer.WriteString("notificationURL", threeDS2RequestData.NotificationURL); + + if (threeDS2RequestData._PayTokenIndOption.IsSet) + writer.WriteBoolean("payTokenInd", threeDS2RequestData._PayTokenIndOption.Value!.Value); + + if (threeDS2RequestData._PaymentAuthenticationUseCaseOption.IsSet) + if (threeDS2RequestData.PaymentAuthenticationUseCase != null) + writer.WriteString("paymentAuthenticationUseCase", threeDS2RequestData.PaymentAuthenticationUseCase); + + if (threeDS2RequestData._PurchaseInstalDataOption.IsSet) + if (threeDS2RequestData.PurchaseInstalData != null) + writer.WriteString("purchaseInstalData", threeDS2RequestData.PurchaseInstalData); + + if (threeDS2RequestData._RecurringExpiryOption.IsSet) + if (threeDS2RequestData.RecurringExpiry != null) + writer.WriteString("recurringExpiry", threeDS2RequestData.RecurringExpiry); + + if (threeDS2RequestData._RecurringFrequencyOption.IsSet) + if (threeDS2RequestData.RecurringFrequency != null) + writer.WriteString("recurringFrequency", threeDS2RequestData.RecurringFrequency); + + if (threeDS2RequestData._SdkAppIDOption.IsSet) + if (threeDS2RequestData.SdkAppID != null) + writer.WriteString("sdkAppID", threeDS2RequestData.SdkAppID); + + if (threeDS2RequestData._SdkEncDataOption.IsSet) + if (threeDS2RequestData.SdkEncData != null) + writer.WriteString("sdkEncData", threeDS2RequestData.SdkEncData); + + if (threeDS2RequestData._SdkEphemPubKeyOption.IsSet) + { + writer.WritePropertyName("sdkEphemPubKey"); + JsonSerializer.Serialize(writer, threeDS2RequestData.SdkEphemPubKey, jsonSerializerOptions); + } + if (threeDS2RequestData._SdkMaxTimeoutOption.IsSet) + writer.WriteNumber("sdkMaxTimeout", threeDS2RequestData._SdkMaxTimeoutOption.Value!.Value); + + if (threeDS2RequestData._SdkReferenceNumberOption.IsSet) + if (threeDS2RequestData.SdkReferenceNumber != null) + writer.WriteString("sdkReferenceNumber", threeDS2RequestData.SdkReferenceNumber); + + if (threeDS2RequestData._SdkTransIDOption.IsSet) + if (threeDS2RequestData.SdkTransID != null) + writer.WriteString("sdkTransID", threeDS2RequestData.SdkTransID); + + if (threeDS2RequestData._SdkVersionOption.IsSet) + if (threeDS2RequestData.SdkVersion != null) + writer.WriteString("sdkVersion", threeDS2RequestData.SdkVersion); + + if (threeDS2RequestData._ThreeDSCompIndOption.IsSet) + if (threeDS2RequestData.ThreeDSCompInd != null) + writer.WriteString("threeDSCompInd", threeDS2RequestData.ThreeDSCompInd); + + if (threeDS2RequestData._ThreeDSRequestorAuthenticationIndOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorAuthenticationInd != null) + writer.WriteString("threeDSRequestorAuthenticationInd", threeDS2RequestData.ThreeDSRequestorAuthenticationInd); + + if (threeDS2RequestData._ThreeDSRequestorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.ThreeDSRequestorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._ThreeDSRequestorChallengeIndOption.IsSet && threeDS2RequestData.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestData._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (threeDS2RequestData._ThreeDSRequestorIDOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorID != null) + writer.WriteString("threeDSRequestorID", threeDS2RequestData.ThreeDSRequestorID); + + if (threeDS2RequestData._ThreeDSRequestorNameOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorName != null) + writer.WriteString("threeDSRequestorName", threeDS2RequestData.ThreeDSRequestorName); + + if (threeDS2RequestData._ThreeDSRequestorPriorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorPriorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.ThreeDSRequestorPriorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._ThreeDSRequestorURLOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorURL != null) + writer.WriteString("threeDSRequestorURL", threeDS2RequestData.ThreeDSRequestorURL); + + if (threeDS2RequestData._TransTypeOption.IsSet && threeDS2RequestData.TransType != null) + { + string? transTypeRawValue = ThreeDS2RequestData.TransTypeEnum.ToJsonValue(threeDS2RequestData._TransTypeOption.Value!.Value); + writer.WriteString("transType", transTypeRawValue); + } + + if (threeDS2RequestData._TransactionTypeOption.IsSet && threeDS2RequestData.TransactionType != null) + { + string? transactionTypeRawValue = ThreeDS2RequestData.TransactionTypeEnum.ToJsonValue(threeDS2RequestData._TransactionTypeOption.Value!.Value); + writer.WriteString("transactionType", transactionTypeRawValue); + } + + if (threeDS2RequestData._WhiteListStatusOption.IsSet) + if (threeDS2RequestData.WhiteListStatus != null) + writer.WriteString("whiteListStatus", threeDS2RequestData.WhiteListStatus); + + if (threeDS2RequestData._WorkPhoneOption.IsSet) + { + writer.WritePropertyName("workPhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.WorkPhone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDS2RequestFields.cs b/Adyen/Checkout/Models/ThreeDS2RequestFields.cs new file mode 100644 index 000000000..9033a464b --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDS2RequestFields.cs @@ -0,0 +1,1823 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDS2RequestFields. + /// + public partial class ThreeDS2RequestFields : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// acctInfo + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false) + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// deviceRenderOptions + /// homePhone + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// mobilePhone + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// Indicates the type of payment for which an authentication is requested (message extension) + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. + /// sdkEphemPubKey + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. (default to 60) + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. + /// Completion indicator for the device fingerprinting. + /// Indicates the type of Authentication request. + /// threeDSRequestorAuthenticationInfo + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// threeDSRequestorPriorAuthenticationInfo + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// Identify the type of the transaction being authenticated. + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// workPhone + [JsonConstructor] + public ThreeDS2RequestFields(Option acctInfo = default, Option acctType = default, Option acquirerBIN = default, Option acquirerMerchantID = default, Option addrMatch = default, Option authenticationOnly = default, Option challengeIndicator = default, Option deviceRenderOptions = default, Option homePhone = default, Option mcc = default, Option merchantName = default, Option messageVersion = default, Option mobilePhone = default, Option notificationURL = default, Option payTokenInd = default, Option paymentAuthenticationUseCase = default, Option purchaseInstalData = default, Option recurringExpiry = default, Option recurringFrequency = default, Option sdkAppID = default, Option sdkEphemPubKey = default, Option sdkMaxTimeout = default, Option sdkReferenceNumber = default, Option sdkTransID = default, Option threeDSCompInd = default, Option threeDSRequestorAuthenticationInd = default, Option threeDSRequestorAuthenticationInfo = default, Option threeDSRequestorChallengeInd = default, Option threeDSRequestorID = default, Option threeDSRequestorName = default, Option threeDSRequestorPriorAuthenticationInfo = default, Option threeDSRequestorURL = default, Option transType = default, Option transactionType = default, Option whiteListStatus = default, Option workPhone = default) + { + _AcctInfoOption = acctInfo; + _AcctTypeOption = acctType; + _AcquirerBINOption = acquirerBIN; + _AcquirerMerchantIDOption = acquirerMerchantID; + _AddrMatchOption = addrMatch; + _AuthenticationOnlyOption = authenticationOnly; + _ChallengeIndicatorOption = challengeIndicator; + _DeviceRenderOptionsOption = deviceRenderOptions; + _HomePhoneOption = homePhone; + _MccOption = mcc; + _MerchantNameOption = merchantName; + _MessageVersionOption = messageVersion; + _MobilePhoneOption = mobilePhone; + _NotificationURLOption = notificationURL; + _PayTokenIndOption = payTokenInd; + _PaymentAuthenticationUseCaseOption = paymentAuthenticationUseCase; + _PurchaseInstalDataOption = purchaseInstalData; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _SdkAppIDOption = sdkAppID; + _SdkEphemPubKeyOption = sdkEphemPubKey; + _SdkMaxTimeoutOption = sdkMaxTimeout; + _SdkReferenceNumberOption = sdkReferenceNumber; + _SdkTransIDOption = sdkTransID; + _ThreeDSCompIndOption = threeDSCompInd; + _ThreeDSRequestorAuthenticationIndOption = threeDSRequestorAuthenticationInd; + _ThreeDSRequestorAuthenticationInfoOption = threeDSRequestorAuthenticationInfo; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _ThreeDSRequestorIDOption = threeDSRequestorID; + _ThreeDSRequestorNameOption = threeDSRequestorName; + _ThreeDSRequestorPriorAuthenticationInfoOption = threeDSRequestorPriorAuthenticationInfo; + _ThreeDSRequestorURLOption = threeDSRequestorURL; + _TransTypeOption = transType; + _TransactionTypeOption = transactionType; + _WhiteListStatusOption = whiteListStatus; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2RequestFields() + { + } + + partial void OnCreated(); + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonConverter(typeof(AcctTypeEnumJsonConverter))] + public class AcctTypeEnum : IEnum + { + /// + /// Returns the value of the AcctTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AcctTypeEnum._01 - 01 + /// + public static readonly AcctTypeEnum _01 = new("01"); + + /// + /// AcctTypeEnum._02 - 02 + /// + public static readonly AcctTypeEnum _02 = new("02"); + + /// + /// AcctTypeEnum._03 - 03 + /// + public static readonly AcctTypeEnum _03 = new("03"); + + private AcctTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AcctTypeEnum?(string? value) => value == null ? null : new AcctTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AcctTypeEnum? option) => option?.Value; + + public static bool operator ==(AcctTypeEnum? left, AcctTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AcctTypeEnum? left, AcctTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AcctTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AcctTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => AcctTypeEnum._01, + "02" => AcctTypeEnum._02, + "03" => AcctTypeEnum._03, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AcctTypeEnum? value) + { + if (value == null) + return null; + + if (value == AcctTypeEnum._01) + return "01"; + + if (value == AcctTypeEnum._02) + return "02"; + + if (value == AcctTypeEnum._03) + return "03"; + + return null; + } + + /// + /// JsonConverter for writing AcctTypeEnum. + /// + public class AcctTypeEnumJsonConverter : JsonConverter + { + public override AcctTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AcctTypeEnum.FromStringOrDefault(value) ?? new AcctTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AcctTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AcctTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctTypeOption { get; private set; } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonPropertyName("acctType")] + public AcctTypeEnum? AcctType { get { return this._AcctTypeOption; } set { this._AcctTypeOption = new(value); } } + + /// + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + [JsonConverter(typeof(AddrMatchEnumJsonConverter))] + public class AddrMatchEnum : IEnum + { + /// + /// Returns the value of the AddrMatchEnum. + /// + public string? Value { get; set; } + + /// + /// AddrMatchEnum.Y - Y + /// + public static readonly AddrMatchEnum Y = new("Y"); + + /// + /// AddrMatchEnum.N - N + /// + public static readonly AddrMatchEnum N = new("N"); + + private AddrMatchEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AddrMatchEnum?(string? value) => value == null ? null : new AddrMatchEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AddrMatchEnum? option) => option?.Value; + + public static bool operator ==(AddrMatchEnum? left, AddrMatchEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AddrMatchEnum? left, AddrMatchEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AddrMatchEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AddrMatchEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => AddrMatchEnum.Y, + "N" => AddrMatchEnum.N, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AddrMatchEnum? value) + { + if (value == null) + return null; + + if (value == AddrMatchEnum.Y) + return "Y"; + + if (value == AddrMatchEnum.N) + return "N"; + + return null; + } + + /// + /// JsonConverter for writing AddrMatchEnum. + /// + public class AddrMatchEnumJsonConverter : JsonConverter + { + public override AddrMatchEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AddrMatchEnum.FromStringOrDefault(value) ?? new AddrMatchEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AddrMatchEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AddrMatchEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddrMatchOption { get; private set; } + + /// + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + [JsonPropertyName("addrMatch")] + public AddrMatchEnum? AddrMatch { get { return this._AddrMatchOption; } set { this._AddrMatchOption = new(value); } } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonConverter(typeof(ChallengeIndicatorEnumJsonConverter))] + public class ChallengeIndicatorEnum : IEnum + { + /// + /// Returns the value of the ChallengeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeIndicatorEnum.NoPreference - noPreference + /// + public static readonly ChallengeIndicatorEnum NoPreference = new("noPreference"); + + /// + /// ChallengeIndicatorEnum.RequestNoChallenge - requestNoChallenge + /// + public static readonly ChallengeIndicatorEnum RequestNoChallenge = new("requestNoChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallenge - requestChallenge + /// + public static readonly ChallengeIndicatorEnum RequestChallenge = new("requestChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallengeAsMandate - requestChallengeAsMandate + /// + public static readonly ChallengeIndicatorEnum RequestChallengeAsMandate = new("requestChallengeAsMandate"); + + private ChallengeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeIndicatorEnum?(string? value) => value == null ? null : new ChallengeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "noPreference" => ChallengeIndicatorEnum.NoPreference, + "requestNoChallenge" => ChallengeIndicatorEnum.RequestNoChallenge, + "requestChallenge" => ChallengeIndicatorEnum.RequestChallenge, + "requestChallengeAsMandate" => ChallengeIndicatorEnum.RequestChallengeAsMandate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeIndicatorEnum.NoPreference) + return "noPreference"; + + if (value == ChallengeIndicatorEnum.RequestNoChallenge) + return "requestNoChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallenge) + return "requestChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallengeAsMandate) + return "requestChallengeAsMandate"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeIndicatorEnum. + /// + public class ChallengeIndicatorEnumJsonConverter : JsonConverter + { + public override ChallengeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeIndicatorEnum.FromStringOrDefault(value) ?? new ChallengeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeIndicatorOption { get; private set; } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonPropertyName("challengeIndicator")] + [Obsolete("Deprecated since Adyen Checkout API v68. Use `threeDSRequestorChallengeInd` instead.")] + public ChallengeIndicatorEnum? ChallengeIndicator { get { return this._ChallengeIndicatorOption; } set { this._ChallengeIndicatorOption = new(value); } } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonConverter(typeof(TransTypeEnumJsonConverter))] + public class TransTypeEnum : IEnum + { + /// + /// Returns the value of the TransTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransTypeEnum._01 - 01 + /// + public static readonly TransTypeEnum _01 = new("01"); + + /// + /// TransTypeEnum._03 - 03 + /// + public static readonly TransTypeEnum _03 = new("03"); + + /// + /// TransTypeEnum._10 - 10 + /// + public static readonly TransTypeEnum _10 = new("10"); + + /// + /// TransTypeEnum._11 - 11 + /// + public static readonly TransTypeEnum _11 = new("11"); + + /// + /// TransTypeEnum._28 - 28 + /// + public static readonly TransTypeEnum _28 = new("28"); + + private TransTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransTypeEnum?(string? value) => value == null ? null : new TransTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransTypeEnum? option) => option?.Value; + + public static bool operator ==(TransTypeEnum? left, TransTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransTypeEnum? left, TransTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => TransTypeEnum._01, + "03" => TransTypeEnum._03, + "10" => TransTypeEnum._10, + "11" => TransTypeEnum._11, + "28" => TransTypeEnum._28, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransTypeEnum._01) + return "01"; + + if (value == TransTypeEnum._03) + return "03"; + + if (value == TransTypeEnum._10) + return "10"; + + if (value == TransTypeEnum._11) + return "11"; + + if (value == TransTypeEnum._28) + return "28"; + + return null; + } + + /// + /// JsonConverter for writing TransTypeEnum. + /// + public class TransTypeEnumJsonConverter : JsonConverter + { + public override TransTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransTypeEnum.FromStringOrDefault(value) ?? new TransTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransTypeOption { get; private set; } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonPropertyName("transType")] + public TransTypeEnum? TransType { get { return this._TransTypeOption; } set { this._TransTypeOption = new(value); } } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonConverter(typeof(TransactionTypeEnumJsonConverter))] + public class TransactionTypeEnum : IEnum + { + /// + /// Returns the value of the TransactionTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransactionTypeEnum.GoodsOrServicePurchase - goodsOrServicePurchase + /// + public static readonly TransactionTypeEnum GoodsOrServicePurchase = new("goodsOrServicePurchase"); + + /// + /// TransactionTypeEnum.CheckAcceptance - checkAcceptance + /// + public static readonly TransactionTypeEnum CheckAcceptance = new("checkAcceptance"); + + /// + /// TransactionTypeEnum.AccountFunding - accountFunding + /// + public static readonly TransactionTypeEnum AccountFunding = new("accountFunding"); + + /// + /// TransactionTypeEnum.QuasiCashTransaction - quasiCashTransaction + /// + public static readonly TransactionTypeEnum QuasiCashTransaction = new("quasiCashTransaction"); + + /// + /// TransactionTypeEnum.PrepaidActivationAndLoad - prepaidActivationAndLoad + /// + public static readonly TransactionTypeEnum PrepaidActivationAndLoad = new("prepaidActivationAndLoad"); + + private TransactionTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransactionTypeEnum?(string? value) => value == null ? null : new TransactionTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransactionTypeEnum? option) => option?.Value; + + public static bool operator ==(TransactionTypeEnum? left, TransactionTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransactionTypeEnum? left, TransactionTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransactionTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransactionTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "goodsOrServicePurchase" => TransactionTypeEnum.GoodsOrServicePurchase, + "checkAcceptance" => TransactionTypeEnum.CheckAcceptance, + "accountFunding" => TransactionTypeEnum.AccountFunding, + "quasiCashTransaction" => TransactionTypeEnum.QuasiCashTransaction, + "prepaidActivationAndLoad" => TransactionTypeEnum.PrepaidActivationAndLoad, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransactionTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransactionTypeEnum.GoodsOrServicePurchase) + return "goodsOrServicePurchase"; + + if (value == TransactionTypeEnum.CheckAcceptance) + return "checkAcceptance"; + + if (value == TransactionTypeEnum.AccountFunding) + return "accountFunding"; + + if (value == TransactionTypeEnum.QuasiCashTransaction) + return "quasiCashTransaction"; + + if (value == TransactionTypeEnum.PrepaidActivationAndLoad) + return "prepaidActivationAndLoad"; + + return null; + } + + /// + /// JsonConverter for writing TransactionTypeEnum. + /// + public class TransactionTypeEnumJsonConverter : JsonConverter + { + public override TransactionTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransactionTypeEnum.FromStringOrDefault(value) ?? new TransactionTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransactionTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransactionTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionTypeOption { get; private set; } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonPropertyName("transactionType")] + public TransactionTypeEnum? TransactionType { get { return this._TransactionTypeOption; } set { this._TransactionTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acctInfo")] + public AcctInfo? AcctInfo { get { return this._AcctInfoOption; } set { this._AcctInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerBINOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerBIN")] + public string? AcquirerBIN { get { return this._AcquirerBINOption; } set { this._AcquirerBINOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerMerchantIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerMerchantID")] + public string? AcquirerMerchantID { get { return this._AcquirerMerchantIDOption; } set { this._AcquirerMerchantIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOnlyOption { get; private set; } + + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + [JsonPropertyName("authenticationOnly")] + [Obsolete("Deprecated since Adyen Checkout API v50. Use `threeDSAuthenticationOnly` instead.")] + public bool? AuthenticationOnly { get { return this._AuthenticationOnlyOption; } set { this._AuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceRenderOptionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deviceRenderOptions")] + public DeviceRenderOptions? DeviceRenderOptions { get { return this._DeviceRenderOptionsOption; } set { this._DeviceRenderOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("homePhone")] + public Phone? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + [JsonPropertyName("merchantName")] + public string? MerchantName { get { return this._MerchantNameOption; } set { this._MerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mobilePhone")] + public Phone? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationURLOption { get; private set; } + + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + [JsonPropertyName("notificationURL")] + public string? NotificationURL { get { return this._NotificationURLOption; } set { this._NotificationURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayTokenIndOption { get; private set; } + + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + [JsonPropertyName("payTokenInd")] + public bool? PayTokenInd { get { return this._PayTokenIndOption; } set { this._PayTokenIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAuthenticationUseCaseOption { get; private set; } + + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + [JsonPropertyName("paymentAuthenticationUseCase")] + public string? PaymentAuthenticationUseCase { get { return this._PaymentAuthenticationUseCaseOption; } set { this._PaymentAuthenticationUseCaseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurchaseInstalDataOption { get; private set; } + + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + [JsonPropertyName("purchaseInstalData")] + public string? PurchaseInstalData { get { return this._PurchaseInstalDataOption; } set { this._PurchaseInstalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkAppIDOption { get; private set; } + + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("sdkAppID")] + public string? SdkAppID { get { return this._SdkAppIDOption; } set { this._SdkAppIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEphemPubKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sdkEphemPubKey")] + public SDKEphemPubKey? SdkEphemPubKey { get { return this._SdkEphemPubKeyOption; } set { this._SdkEphemPubKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkMaxTimeoutOption { get; private set; } + + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + [JsonPropertyName("sdkMaxTimeout")] + public int? SdkMaxTimeout { get { return this._SdkMaxTimeoutOption; } set { this._SdkMaxTimeoutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkReferenceNumberOption { get; private set; } + + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("sdkReferenceNumber")] + public string? SdkReferenceNumber { get { return this._SdkReferenceNumberOption; } set { this._SdkReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkTransIDOption { get; private set; } + + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("sdkTransID")] + public string? SdkTransID { get { return this._SdkTransIDOption; } set { this._SdkTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSCompIndOption { get; private set; } + + /// + /// Completion indicator for the device fingerprinting. + /// + /// Completion indicator for the device fingerprinting. + [JsonPropertyName("threeDSCompInd")] + public string? ThreeDSCompInd { get { return this._ThreeDSCompIndOption; } set { this._ThreeDSCompIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationIndOption { get; private set; } + + /// + /// Indicates the type of Authentication request. + /// + /// Indicates the type of Authentication request. + [JsonPropertyName("threeDSRequestorAuthenticationInd")] + public string? ThreeDSRequestorAuthenticationInd { get { return this._ThreeDSRequestorAuthenticationIndOption; } set { this._ThreeDSRequestorAuthenticationIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorAuthenticationInfo")] + public ThreeDSRequestorAuthenticationInfo? ThreeDSRequestorAuthenticationInfo { get { return this._ThreeDSRequestorAuthenticationInfoOption; } set { this._ThreeDSRequestorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorID")] + public string? ThreeDSRequestorID { get { return this._ThreeDSRequestorIDOption; } set { this._ThreeDSRequestorIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorName")] + public string? ThreeDSRequestorName { get { return this._ThreeDSRequestorNameOption; } set { this._ThreeDSRequestorNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorPriorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorPriorAuthenticationInfo")] + public ThreeDSRequestorPriorAuthenticationInfo? ThreeDSRequestorPriorAuthenticationInfo { get { return this._ThreeDSRequestorPriorAuthenticationInfoOption; } set { this._ThreeDSRequestorPriorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorURLOption { get; private set; } + + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + [JsonPropertyName("threeDSRequestorURL")] + public string? ThreeDSRequestorURL { get { return this._ThreeDSRequestorURLOption; } set { this._ThreeDSRequestorURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WhiteListStatusOption { get; private set; } + + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + [JsonPropertyName("whiteListStatus")] + public string? WhiteListStatus { get { return this._WhiteListStatusOption; } set { this._WhiteListStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("workPhone")] + public Phone? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2RequestFields {\n"); + sb.Append(" AcctInfo: ").Append(AcctInfo).Append("\n"); + sb.Append(" AcctType: ").Append(AcctType).Append("\n"); + sb.Append(" AcquirerBIN: ").Append(AcquirerBIN).Append("\n"); + sb.Append(" AcquirerMerchantID: ").Append(AcquirerMerchantID).Append("\n"); + sb.Append(" AddrMatch: ").Append(AddrMatch).Append("\n"); + sb.Append(" AuthenticationOnly: ").Append(AuthenticationOnly).Append("\n"); + sb.Append(" ChallengeIndicator: ").Append(ChallengeIndicator).Append("\n"); + sb.Append(" DeviceRenderOptions: ").Append(DeviceRenderOptions).Append("\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" NotificationURL: ").Append(NotificationURL).Append("\n"); + sb.Append(" PayTokenInd: ").Append(PayTokenInd).Append("\n"); + sb.Append(" PaymentAuthenticationUseCase: ").Append(PaymentAuthenticationUseCase).Append("\n"); + sb.Append(" PurchaseInstalData: ").Append(PurchaseInstalData).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" SdkAppID: ").Append(SdkAppID).Append("\n"); + sb.Append(" SdkEphemPubKey: ").Append(SdkEphemPubKey).Append("\n"); + sb.Append(" SdkMaxTimeout: ").Append(SdkMaxTimeout).Append("\n"); + sb.Append(" SdkReferenceNumber: ").Append(SdkReferenceNumber).Append("\n"); + sb.Append(" SdkTransID: ").Append(SdkTransID).Append("\n"); + sb.Append(" ThreeDSCompInd: ").Append(ThreeDSCompInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInd: ").Append(ThreeDSRequestorAuthenticationInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInfo: ").Append(ThreeDSRequestorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" ThreeDSRequestorID: ").Append(ThreeDSRequestorID).Append("\n"); + sb.Append(" ThreeDSRequestorName: ").Append(ThreeDSRequestorName).Append("\n"); + sb.Append(" ThreeDSRequestorPriorAuthenticationInfo: ").Append(ThreeDSRequestorPriorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorURL: ").Append(ThreeDSRequestorURL).Append("\n"); + sb.Append(" TransType: ").Append(TransType).Append("\n"); + sb.Append(" TransactionType: ").Append(TransactionType).Append("\n"); + sb.Append(" WhiteListStatus: ").Append(WhiteListStatus).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // PurchaseInstalData (string) maxLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length > 3) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be less than 3.", new [] { "PurchaseInstalData" }); + } + + // PurchaseInstalData (string) minLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length < 1) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be greater than 1.", new [] { "PurchaseInstalData" }); + } + + // RecurringFrequency (string) maxLength + if (this.RecurringFrequency != null && this.RecurringFrequency.Length > 4) + { + yield return new ValidationResult("Invalid value for RecurringFrequency, length must be less than 4.", new [] { "RecurringFrequency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2RequestFieldsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2RequestFields Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acctInfo = default; + Option acctType = default; + Option acquirerBIN = default; + Option acquirerMerchantID = default; + Option addrMatch = default; + Option authenticationOnly = default; + Option challengeIndicator = default; + Option deviceRenderOptions = default; + Option homePhone = default; + Option mcc = default; + Option merchantName = default; + Option messageVersion = default; + Option mobilePhone = default; + Option notificationURL = default; + Option payTokenInd = default; + Option paymentAuthenticationUseCase = default; + Option purchaseInstalData = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option sdkAppID = default; + Option sdkEphemPubKey = default; + Option sdkMaxTimeout = default; + Option sdkReferenceNumber = default; + Option sdkTransID = default; + Option threeDSCompInd = default; + Option threeDSRequestorAuthenticationInd = default; + Option threeDSRequestorAuthenticationInfo = default; + Option threeDSRequestorChallengeInd = default; + Option threeDSRequestorID = default; + Option threeDSRequestorName = default; + Option threeDSRequestorPriorAuthenticationInfo = default; + Option threeDSRequestorURL = default; + Option transType = default; + Option transactionType = default; + Option whiteListStatus = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acctInfo": + acctInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acctType": + string? acctTypeRawValue = utf8JsonReader.GetString(); + acctType = new Option(ThreeDS2RequestFields.AcctTypeEnum.FromStringOrDefault(acctTypeRawValue)); + break; + case "acquirerBIN": + acquirerBIN = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerMerchantID": + acquirerMerchantID = new Option(utf8JsonReader.GetString()!); + break; + case "addrMatch": + string? addrMatchRawValue = utf8JsonReader.GetString(); + addrMatch = new Option(ThreeDS2RequestFields.AddrMatchEnum.FromStringOrDefault(addrMatchRawValue)); + break; + case "authenticationOnly": + authenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "challengeIndicator": + string? challengeIndicatorRawValue = utf8JsonReader.GetString(); + challengeIndicator = new Option(ThreeDS2RequestFields.ChallengeIndicatorEnum.FromStringOrDefault(challengeIndicatorRawValue)); + break; + case "deviceRenderOptions": + deviceRenderOptions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "homePhone": + homePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "mobilePhone": + mobilePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notificationURL": + notificationURL = new Option(utf8JsonReader.GetString()!); + break; + case "payTokenInd": + payTokenInd = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentAuthenticationUseCase": + paymentAuthenticationUseCase = new Option(utf8JsonReader.GetString()!); + break; + case "purchaseInstalData": + purchaseInstalData = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "sdkAppID": + sdkAppID = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEphemPubKey": + sdkEphemPubKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sdkMaxTimeout": + sdkMaxTimeout = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "sdkReferenceNumber": + sdkReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sdkTransID": + sdkTransID = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSCompInd": + threeDSCompInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInd": + threeDSRequestorAuthenticationInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInfo": + threeDSRequestorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(ThreeDS2RequestFields.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "threeDSRequestorID": + threeDSRequestorID = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorName": + threeDSRequestorName = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorPriorAuthenticationInfo": + threeDSRequestorPriorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorURL": + threeDSRequestorURL = new Option(utf8JsonReader.GetString()!); + break; + case "transType": + string? transTypeRawValue = utf8JsonReader.GetString(); + transType = new Option(ThreeDS2RequestFields.TransTypeEnum.FromStringOrDefault(transTypeRawValue)); + break; + case "transactionType": + string? transactionTypeRawValue = utf8JsonReader.GetString(); + transactionType = new Option(ThreeDS2RequestFields.TransactionTypeEnum.FromStringOrDefault(transactionTypeRawValue)); + break; + case "whiteListStatus": + whiteListStatus = new Option(utf8JsonReader.GetString()!); + break; + case "workPhone": + workPhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ThreeDS2RequestFields(acctInfo, acctType, acquirerBIN, acquirerMerchantID, addrMatch, authenticationOnly, challengeIndicator, deviceRenderOptions, homePhone, mcc, merchantName, messageVersion, mobilePhone, notificationURL, payTokenInd, paymentAuthenticationUseCase, purchaseInstalData, recurringExpiry, recurringFrequency, sdkAppID, sdkEphemPubKey, sdkMaxTimeout, sdkReferenceNumber, sdkTransID, threeDSCompInd, threeDSRequestorAuthenticationInd, threeDSRequestorAuthenticationInfo, threeDSRequestorChallengeInd, threeDSRequestorID, threeDSRequestorName, threeDSRequestorPriorAuthenticationInfo, threeDSRequestorURL, transType, transactionType, whiteListStatus, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2RequestFields threeDS2RequestFields, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2RequestFields, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2RequestFields threeDS2RequestFields, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2RequestFields._AcctInfoOption.IsSet) + { + writer.WritePropertyName("acctInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.AcctInfo, jsonSerializerOptions); + } + if (threeDS2RequestFields._AcctTypeOption.IsSet && threeDS2RequestFields.AcctType != null) + { + string? acctTypeRawValue = ThreeDS2RequestFields.AcctTypeEnum.ToJsonValue(threeDS2RequestFields._AcctTypeOption.Value!.Value); + writer.WriteString("acctType", acctTypeRawValue); + } + + if (threeDS2RequestFields._AcquirerBINOption.IsSet) + if (threeDS2RequestFields.AcquirerBIN != null) + writer.WriteString("acquirerBIN", threeDS2RequestFields.AcquirerBIN); + + if (threeDS2RequestFields._AcquirerMerchantIDOption.IsSet) + if (threeDS2RequestFields.AcquirerMerchantID != null) + writer.WriteString("acquirerMerchantID", threeDS2RequestFields.AcquirerMerchantID); + + if (threeDS2RequestFields._AddrMatchOption.IsSet && threeDS2RequestFields.AddrMatch != null) + { + string? addrMatchRawValue = ThreeDS2RequestFields.AddrMatchEnum.ToJsonValue(threeDS2RequestFields._AddrMatchOption.Value!.Value); + writer.WriteString("addrMatch", addrMatchRawValue); + } + + if (threeDS2RequestFields._AuthenticationOnlyOption.IsSet) + writer.WriteBoolean("authenticationOnly", threeDS2RequestFields._AuthenticationOnlyOption.Value!.Value); + + if (threeDS2RequestFields._ChallengeIndicatorOption.IsSet && threeDS2RequestFields.ChallengeIndicator != null) + { + string? challengeIndicatorRawValue = ThreeDS2RequestFields.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestFields._ChallengeIndicatorOption.Value!.Value); + writer.WriteString("challengeIndicator", challengeIndicatorRawValue); + } + + if (threeDS2RequestFields._DeviceRenderOptionsOption.IsSet) + { + writer.WritePropertyName("deviceRenderOptions"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.DeviceRenderOptions, jsonSerializerOptions); + } + if (threeDS2RequestFields._HomePhoneOption.IsSet) + { + writer.WritePropertyName("homePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.HomePhone, jsonSerializerOptions); + } + if (threeDS2RequestFields._MccOption.IsSet) + if (threeDS2RequestFields.Mcc != null) + writer.WriteString("mcc", threeDS2RequestFields.Mcc); + + if (threeDS2RequestFields._MerchantNameOption.IsSet) + if (threeDS2RequestFields.MerchantName != null) + writer.WriteString("merchantName", threeDS2RequestFields.MerchantName); + + if (threeDS2RequestFields._MessageVersionOption.IsSet) + if (threeDS2RequestFields.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2RequestFields.MessageVersion); + + if (threeDS2RequestFields._MobilePhoneOption.IsSet) + { + writer.WritePropertyName("mobilePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.MobilePhone, jsonSerializerOptions); + } + if (threeDS2RequestFields._NotificationURLOption.IsSet) + if (threeDS2RequestFields.NotificationURL != null) + writer.WriteString("notificationURL", threeDS2RequestFields.NotificationURL); + + if (threeDS2RequestFields._PayTokenIndOption.IsSet) + writer.WriteBoolean("payTokenInd", threeDS2RequestFields._PayTokenIndOption.Value!.Value); + + if (threeDS2RequestFields._PaymentAuthenticationUseCaseOption.IsSet) + if (threeDS2RequestFields.PaymentAuthenticationUseCase != null) + writer.WriteString("paymentAuthenticationUseCase", threeDS2RequestFields.PaymentAuthenticationUseCase); + + if (threeDS2RequestFields._PurchaseInstalDataOption.IsSet) + if (threeDS2RequestFields.PurchaseInstalData != null) + writer.WriteString("purchaseInstalData", threeDS2RequestFields.PurchaseInstalData); + + if (threeDS2RequestFields._RecurringExpiryOption.IsSet) + if (threeDS2RequestFields.RecurringExpiry != null) + writer.WriteString("recurringExpiry", threeDS2RequestFields.RecurringExpiry); + + if (threeDS2RequestFields._RecurringFrequencyOption.IsSet) + if (threeDS2RequestFields.RecurringFrequency != null) + writer.WriteString("recurringFrequency", threeDS2RequestFields.RecurringFrequency); + + if (threeDS2RequestFields._SdkAppIDOption.IsSet) + if (threeDS2RequestFields.SdkAppID != null) + writer.WriteString("sdkAppID", threeDS2RequestFields.SdkAppID); + + if (threeDS2RequestFields._SdkEphemPubKeyOption.IsSet) + { + writer.WritePropertyName("sdkEphemPubKey"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.SdkEphemPubKey, jsonSerializerOptions); + } + if (threeDS2RequestFields._SdkMaxTimeoutOption.IsSet) + writer.WriteNumber("sdkMaxTimeout", threeDS2RequestFields._SdkMaxTimeoutOption.Value!.Value); + + if (threeDS2RequestFields._SdkReferenceNumberOption.IsSet) + if (threeDS2RequestFields.SdkReferenceNumber != null) + writer.WriteString("sdkReferenceNumber", threeDS2RequestFields.SdkReferenceNumber); + + if (threeDS2RequestFields._SdkTransIDOption.IsSet) + if (threeDS2RequestFields.SdkTransID != null) + writer.WriteString("sdkTransID", threeDS2RequestFields.SdkTransID); + + if (threeDS2RequestFields._ThreeDSCompIndOption.IsSet) + if (threeDS2RequestFields.ThreeDSCompInd != null) + writer.WriteString("threeDSCompInd", threeDS2RequestFields.ThreeDSCompInd); + + if (threeDS2RequestFields._ThreeDSRequestorAuthenticationIndOption.IsSet) + if (threeDS2RequestFields.ThreeDSRequestorAuthenticationInd != null) + writer.WriteString("threeDSRequestorAuthenticationInd", threeDS2RequestFields.ThreeDSRequestorAuthenticationInd); + + if (threeDS2RequestFields._ThreeDSRequestorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.ThreeDSRequestorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestFields._ThreeDSRequestorChallengeIndOption.IsSet && threeDS2RequestFields.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = ThreeDS2RequestFields.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestFields._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (threeDS2RequestFields._ThreeDSRequestorIDOption.IsSet) + if (threeDS2RequestFields.ThreeDSRequestorID != null) + writer.WriteString("threeDSRequestorID", threeDS2RequestFields.ThreeDSRequestorID); + + if (threeDS2RequestFields._ThreeDSRequestorNameOption.IsSet) + if (threeDS2RequestFields.ThreeDSRequestorName != null) + writer.WriteString("threeDSRequestorName", threeDS2RequestFields.ThreeDSRequestorName); + + if (threeDS2RequestFields._ThreeDSRequestorPriorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorPriorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.ThreeDSRequestorPriorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestFields._ThreeDSRequestorURLOption.IsSet) + if (threeDS2RequestFields.ThreeDSRequestorURL != null) + writer.WriteString("threeDSRequestorURL", threeDS2RequestFields.ThreeDSRequestorURL); + + if (threeDS2RequestFields._TransTypeOption.IsSet && threeDS2RequestFields.TransType != null) + { + string? transTypeRawValue = ThreeDS2RequestFields.TransTypeEnum.ToJsonValue(threeDS2RequestFields._TransTypeOption.Value!.Value); + writer.WriteString("transType", transTypeRawValue); + } + + if (threeDS2RequestFields._TransactionTypeOption.IsSet && threeDS2RequestFields.TransactionType != null) + { + string? transactionTypeRawValue = ThreeDS2RequestFields.TransactionTypeEnum.ToJsonValue(threeDS2RequestFields._TransactionTypeOption.Value!.Value); + writer.WriteString("transactionType", transactionTypeRawValue); + } + + if (threeDS2RequestFields._WhiteListStatusOption.IsSet) + if (threeDS2RequestFields.WhiteListStatus != null) + writer.WriteString("whiteListStatus", threeDS2RequestFields.WhiteListStatus); + + if (threeDS2RequestFields._WorkPhoneOption.IsSet) + { + writer.WritePropertyName("workPhone"); + JsonSerializer.Serialize(writer, threeDS2RequestFields.WorkPhone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDS2ResponseData.cs b/Adyen/Checkout/Models/ThreeDS2ResponseData.cs new file mode 100644 index 000000000..bb93b7a50 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDS2ResponseData.cs @@ -0,0 +1,608 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDS2ResponseData. + /// + public partial class ThreeDS2ResponseData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// acsChallengeMandated + /// acsOperatorID + /// acsReferenceNumber + /// acsSignedContent + /// acsTransID + /// acsURL + /// authenticationType + /// cardHolderInfo + /// cavvAlgorithm + /// challengeIndicator + /// dsReferenceNumber + /// dsTransID + /// exemptionIndicator + /// messageVersion + /// riskScore + /// sdkEphemPubKey + /// threeDSServerTransID + /// transStatus + /// transStatusReason + [JsonConstructor] + public ThreeDS2ResponseData(Option acsChallengeMandated = default, Option acsOperatorID = default, Option acsReferenceNumber = default, Option acsSignedContent = default, Option acsTransID = default, Option acsURL = default, Option authenticationType = default, Option cardHolderInfo = default, Option cavvAlgorithm = default, Option challengeIndicator = default, Option dsReferenceNumber = default, Option dsTransID = default, Option exemptionIndicator = default, Option messageVersion = default, Option riskScore = default, Option sdkEphemPubKey = default, Option threeDSServerTransID = default, Option transStatus = default, Option transStatusReason = default) + { + _AcsChallengeMandatedOption = acsChallengeMandated; + _AcsOperatorIDOption = acsOperatorID; + _AcsReferenceNumberOption = acsReferenceNumber; + _AcsSignedContentOption = acsSignedContent; + _AcsTransIDOption = acsTransID; + _AcsURLOption = acsURL; + _AuthenticationTypeOption = authenticationType; + _CardHolderInfoOption = cardHolderInfo; + _CavvAlgorithmOption = cavvAlgorithm; + _ChallengeIndicatorOption = challengeIndicator; + _DsReferenceNumberOption = dsReferenceNumber; + _DsTransIDOption = dsTransID; + _ExemptionIndicatorOption = exemptionIndicator; + _MessageVersionOption = messageVersion; + _RiskScoreOption = riskScore; + _SdkEphemPubKeyOption = sdkEphemPubKey; + _ThreeDSServerTransIDOption = threeDSServerTransID; + _TransStatusOption = transStatus; + _TransStatusReasonOption = transStatusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2ResponseData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsChallengeMandatedOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsChallengeMandated")] + public string? AcsChallengeMandated { get { return this._AcsChallengeMandatedOption; } set { this._AcsChallengeMandatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsOperatorIDOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsOperatorID")] + public string? AcsOperatorID { get { return this._AcsOperatorIDOption; } set { this._AcsOperatorIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsReferenceNumberOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsReferenceNumber")] + public string? AcsReferenceNumber { get { return this._AcsReferenceNumberOption; } set { this._AcsReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsSignedContentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsSignedContent")] + public string? AcsSignedContent { get { return this._AcsSignedContentOption; } set { this._AcsSignedContentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsTransIDOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsTransID")] + public string? AcsTransID { get { return this._AcsTransIDOption; } set { this._AcsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsURLOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acsURL")] + public string? AcsURL { get { return this._AcsURLOption; } set { this._AcsURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationTypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authenticationType")] + public string? AuthenticationType { get { return this._AuthenticationTypeOption; } set { this._AuthenticationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cardHolderInfo")] + public string? CardHolderInfo { get { return this._CardHolderInfoOption; } set { this._CardHolderInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("challengeIndicator")] + public string? ChallengeIndicator { get { return this._ChallengeIndicatorOption; } set { this._ChallengeIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsReferenceNumberOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dsReferenceNumber")] + public string? DsReferenceNumber { get { return this._DsReferenceNumberOption; } set { this._DsReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("exemptionIndicator")] + public string? ExemptionIndicator { get { return this._ExemptionIndicatorOption; } set { this._ExemptionIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("riskScore")] + public string? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEphemPubKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sdkEphemPubKey")] + public string? SdkEphemPubKey { get { return this._SdkEphemPubKeyOption; } set { this._SdkEphemPubKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSServerTransIDOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSServerTransID")] + public string? ThreeDSServerTransID { get { return this._ThreeDSServerTransIDOption; } set { this._ThreeDSServerTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transStatus")] + public string? TransStatus { get { return this._TransStatusOption; } set { this._TransStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transStatusReason")] + public string? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2ResponseData {\n"); + sb.Append(" AcsChallengeMandated: ").Append(AcsChallengeMandated).Append("\n"); + sb.Append(" AcsOperatorID: ").Append(AcsOperatorID).Append("\n"); + sb.Append(" AcsReferenceNumber: ").Append(AcsReferenceNumber).Append("\n"); + sb.Append(" AcsSignedContent: ").Append(AcsSignedContent).Append("\n"); + sb.Append(" AcsTransID: ").Append(AcsTransID).Append("\n"); + sb.Append(" AcsURL: ").Append(AcsURL).Append("\n"); + sb.Append(" AuthenticationType: ").Append(AuthenticationType).Append("\n"); + sb.Append(" CardHolderInfo: ").Append(CardHolderInfo).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ChallengeIndicator: ").Append(ChallengeIndicator).Append("\n"); + sb.Append(" DsReferenceNumber: ").Append(DsReferenceNumber).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" ExemptionIndicator: ").Append(ExemptionIndicator).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" SdkEphemPubKey: ").Append(SdkEphemPubKey).Append("\n"); + sb.Append(" ThreeDSServerTransID: ").Append(ThreeDSServerTransID).Append("\n"); + sb.Append(" TransStatus: ").Append(TransStatus).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2ResponseDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2ResponseData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acsChallengeMandated = default; + Option acsOperatorID = default; + Option acsReferenceNumber = default; + Option acsSignedContent = default; + Option acsTransID = default; + Option acsURL = default; + Option authenticationType = default; + Option cardHolderInfo = default; + Option cavvAlgorithm = default; + Option challengeIndicator = default; + Option dsReferenceNumber = default; + Option dsTransID = default; + Option exemptionIndicator = default; + Option messageVersion = default; + Option riskScore = default; + Option sdkEphemPubKey = default; + Option threeDSServerTransID = default; + Option transStatus = default; + Option transStatusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsChallengeMandated": + acsChallengeMandated = new Option(utf8JsonReader.GetString()!); + break; + case "acsOperatorID": + acsOperatorID = new Option(utf8JsonReader.GetString()!); + break; + case "acsReferenceNumber": + acsReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "acsSignedContent": + acsSignedContent = new Option(utf8JsonReader.GetString()!); + break; + case "acsTransID": + acsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "acsURL": + acsURL = new Option(utf8JsonReader.GetString()!); + break; + case "authenticationType": + authenticationType = new Option(utf8JsonReader.GetString()!); + break; + case "cardHolderInfo": + cardHolderInfo = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "challengeIndicator": + challengeIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "dsReferenceNumber": + dsReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "exemptionIndicator": + exemptionIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEphemPubKey": + sdkEphemPubKey = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSServerTransID": + threeDSServerTransID = new Option(utf8JsonReader.GetString()!); + break; + case "transStatus": + transStatus = new Option(utf8JsonReader.GetString()!); + break; + case "transStatusReason": + transStatusReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDS2ResponseData(acsChallengeMandated, acsOperatorID, acsReferenceNumber, acsSignedContent, acsTransID, acsURL, authenticationType, cardHolderInfo, cavvAlgorithm, challengeIndicator, dsReferenceNumber, dsTransID, exemptionIndicator, messageVersion, riskScore, sdkEphemPubKey, threeDSServerTransID, transStatus, transStatusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2ResponseData threeDS2ResponseData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2ResponseData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2ResponseData threeDS2ResponseData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2ResponseData._AcsChallengeMandatedOption.IsSet) + if (threeDS2ResponseData.AcsChallengeMandated != null) + writer.WriteString("acsChallengeMandated", threeDS2ResponseData.AcsChallengeMandated); + + if (threeDS2ResponseData._AcsOperatorIDOption.IsSet) + if (threeDS2ResponseData.AcsOperatorID != null) + writer.WriteString("acsOperatorID", threeDS2ResponseData.AcsOperatorID); + + if (threeDS2ResponseData._AcsReferenceNumberOption.IsSet) + if (threeDS2ResponseData.AcsReferenceNumber != null) + writer.WriteString("acsReferenceNumber", threeDS2ResponseData.AcsReferenceNumber); + + if (threeDS2ResponseData._AcsSignedContentOption.IsSet) + if (threeDS2ResponseData.AcsSignedContent != null) + writer.WriteString("acsSignedContent", threeDS2ResponseData.AcsSignedContent); + + if (threeDS2ResponseData._AcsTransIDOption.IsSet) + if (threeDS2ResponseData.AcsTransID != null) + writer.WriteString("acsTransID", threeDS2ResponseData.AcsTransID); + + if (threeDS2ResponseData._AcsURLOption.IsSet) + if (threeDS2ResponseData.AcsURL != null) + writer.WriteString("acsURL", threeDS2ResponseData.AcsURL); + + if (threeDS2ResponseData._AuthenticationTypeOption.IsSet) + if (threeDS2ResponseData.AuthenticationType != null) + writer.WriteString("authenticationType", threeDS2ResponseData.AuthenticationType); + + if (threeDS2ResponseData._CardHolderInfoOption.IsSet) + if (threeDS2ResponseData.CardHolderInfo != null) + writer.WriteString("cardHolderInfo", threeDS2ResponseData.CardHolderInfo); + + if (threeDS2ResponseData._CavvAlgorithmOption.IsSet) + if (threeDS2ResponseData.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDS2ResponseData.CavvAlgorithm); + + if (threeDS2ResponseData._ChallengeIndicatorOption.IsSet) + if (threeDS2ResponseData.ChallengeIndicator != null) + writer.WriteString("challengeIndicator", threeDS2ResponseData.ChallengeIndicator); + + if (threeDS2ResponseData._DsReferenceNumberOption.IsSet) + if (threeDS2ResponseData.DsReferenceNumber != null) + writer.WriteString("dsReferenceNumber", threeDS2ResponseData.DsReferenceNumber); + + if (threeDS2ResponseData._DsTransIDOption.IsSet) + if (threeDS2ResponseData.DsTransID != null) + writer.WriteString("dsTransID", threeDS2ResponseData.DsTransID); + + if (threeDS2ResponseData._ExemptionIndicatorOption.IsSet) + if (threeDS2ResponseData.ExemptionIndicator != null) + writer.WriteString("exemptionIndicator", threeDS2ResponseData.ExemptionIndicator); + + if (threeDS2ResponseData._MessageVersionOption.IsSet) + if (threeDS2ResponseData.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2ResponseData.MessageVersion); + + if (threeDS2ResponseData._RiskScoreOption.IsSet) + if (threeDS2ResponseData.RiskScore != null) + writer.WriteString("riskScore", threeDS2ResponseData.RiskScore); + + if (threeDS2ResponseData._SdkEphemPubKeyOption.IsSet) + if (threeDS2ResponseData.SdkEphemPubKey != null) + writer.WriteString("sdkEphemPubKey", threeDS2ResponseData.SdkEphemPubKey); + + if (threeDS2ResponseData._ThreeDSServerTransIDOption.IsSet) + if (threeDS2ResponseData.ThreeDSServerTransID != null) + writer.WriteString("threeDSServerTransID", threeDS2ResponseData.ThreeDSServerTransID); + + if (threeDS2ResponseData._TransStatusOption.IsSet) + if (threeDS2ResponseData.TransStatus != null) + writer.WriteString("transStatus", threeDS2ResponseData.TransStatus); + + if (threeDS2ResponseData._TransStatusReasonOption.IsSet) + if (threeDS2ResponseData.TransStatusReason != null) + writer.WriteString("transStatusReason", threeDS2ResponseData.TransStatusReason); + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDS2Result.cs b/Adyen/Checkout/Models/ThreeDS2Result.cs new file mode 100644 index 000000000..d60cdcdd6 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDS2Result.cs @@ -0,0 +1,919 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDS2Result. + /// + public partial class ThreeDS2Result : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + /// The `eci` value as defined in the 3D Secure 2 specification. + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// The `timestamp` value of the 3D Secure 2 authentication. + /// The `transStatus` value as defined in the 3D Secure 2 specification. + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + [JsonConstructor] + public ThreeDS2Result(Option authenticationValue = default, Option cavvAlgorithm = default, Option challengeCancel = default, Option dsTransID = default, Option eci = default, Option exemptionIndicator = default, Option messageVersion = default, Option riskScore = default, Option threeDSRequestorChallengeInd = default, Option threeDSServerTransID = default, Option timestamp = default, Option transStatus = default, Option transStatusReason = default, Option whiteListStatus = default) + { + _AuthenticationValueOption = authenticationValue; + _CavvAlgorithmOption = cavvAlgorithm; + _ChallengeCancelOption = challengeCancel; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _ExemptionIndicatorOption = exemptionIndicator; + _MessageVersionOption = messageVersion; + _RiskScoreOption = riskScore; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _ThreeDSServerTransIDOption = threeDSServerTransID; + _TimestampOption = timestamp; + _TransStatusOption = transStatus; + _TransStatusReasonOption = transStatusReason; + _WhiteListStatusOption = whiteListStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2Result() + { + } + + partial void OnCreated(); + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonConverter(typeof(ChallengeCancelEnumJsonConverter))] + public class ChallengeCancelEnum : IEnum + { + /// + /// Returns the value of the ChallengeCancelEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeCancelEnum._01 - 01 + /// + public static readonly ChallengeCancelEnum _01 = new("01"); + + /// + /// ChallengeCancelEnum._02 - 02 + /// + public static readonly ChallengeCancelEnum _02 = new("02"); + + /// + /// ChallengeCancelEnum._03 - 03 + /// + public static readonly ChallengeCancelEnum _03 = new("03"); + + /// + /// ChallengeCancelEnum._04 - 04 + /// + public static readonly ChallengeCancelEnum _04 = new("04"); + + /// + /// ChallengeCancelEnum._05 - 05 + /// + public static readonly ChallengeCancelEnum _05 = new("05"); + + /// + /// ChallengeCancelEnum._06 - 06 + /// + public static readonly ChallengeCancelEnum _06 = new("06"); + + /// + /// ChallengeCancelEnum._07 - 07 + /// + public static readonly ChallengeCancelEnum _07 = new("07"); + + private ChallengeCancelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeCancelEnum?(string? value) => value == null ? null : new ChallengeCancelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeCancelEnum? option) => option?.Value; + + public static bool operator ==(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeCancelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeCancelEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeCancelEnum._01, + "02" => ChallengeCancelEnum._02, + "03" => ChallengeCancelEnum._03, + "04" => ChallengeCancelEnum._04, + "05" => ChallengeCancelEnum._05, + "06" => ChallengeCancelEnum._06, + "07" => ChallengeCancelEnum._07, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeCancelEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeCancelEnum._01) + return "01"; + + if (value == ChallengeCancelEnum._02) + return "02"; + + if (value == ChallengeCancelEnum._03) + return "03"; + + if (value == ChallengeCancelEnum._04) + return "04"; + + if (value == ChallengeCancelEnum._05) + return "05"; + + if (value == ChallengeCancelEnum._06) + return "06"; + + if (value == ChallengeCancelEnum._07) + return "07"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeCancelEnum. + /// + public class ChallengeCancelEnumJsonConverter : JsonConverter + { + public override ChallengeCancelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeCancelEnum.FromStringOrDefault(value) ?? new ChallengeCancelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeCancelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeCancelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeCancelOption { get; private set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonPropertyName("challengeCancel")] + public ChallengeCancelEnum? ChallengeCancel { get { return this._ChallengeCancelOption; } set { this._ChallengeCancelOption = new(value); } } + + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + [JsonConverter(typeof(ExemptionIndicatorEnumJsonConverter))] + public class ExemptionIndicatorEnum : IEnum + { + /// + /// Returns the value of the ExemptionIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ExemptionIndicatorEnum.LowValue - lowValue + /// + public static readonly ExemptionIndicatorEnum LowValue = new("lowValue"); + + /// + /// ExemptionIndicatorEnum.SecureCorporate - secureCorporate + /// + public static readonly ExemptionIndicatorEnum SecureCorporate = new("secureCorporate"); + + /// + /// ExemptionIndicatorEnum.TrustedBeneficiary - trustedBeneficiary + /// + public static readonly ExemptionIndicatorEnum TrustedBeneficiary = new("trustedBeneficiary"); + + /// + /// ExemptionIndicatorEnum.TransactionRiskAnalysis - transactionRiskAnalysis + /// + public static readonly ExemptionIndicatorEnum TransactionRiskAnalysis = new("transactionRiskAnalysis"); + + private ExemptionIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ExemptionIndicatorEnum?(string? value) => value == null ? null : new ExemptionIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ExemptionIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ExemptionIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ExemptionIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "lowValue" => ExemptionIndicatorEnum.LowValue, + "secureCorporate" => ExemptionIndicatorEnum.SecureCorporate, + "trustedBeneficiary" => ExemptionIndicatorEnum.TrustedBeneficiary, + "transactionRiskAnalysis" => ExemptionIndicatorEnum.TransactionRiskAnalysis, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ExemptionIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ExemptionIndicatorEnum.LowValue) + return "lowValue"; + + if (value == ExemptionIndicatorEnum.SecureCorporate) + return "secureCorporate"; + + if (value == ExemptionIndicatorEnum.TrustedBeneficiary) + return "trustedBeneficiary"; + + if (value == ExemptionIndicatorEnum.TransactionRiskAnalysis) + return "transactionRiskAnalysis"; + + return null; + } + + /// + /// JsonConverter for writing ExemptionIndicatorEnum. + /// + public class ExemptionIndicatorEnumJsonConverter : JsonConverter + { + public override ExemptionIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ExemptionIndicatorEnum.FromStringOrDefault(value) ?? new ExemptionIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ExemptionIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ExemptionIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionIndicatorOption { get; private set; } + + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + [JsonPropertyName("exemptionIndicator")] + public ExemptionIndicatorEnum? ExemptionIndicator { get { return this._ExemptionIndicatorOption; } set { this._ExemptionIndicatorOption = new(value); } } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationValueOption { get; private set; } + + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("authenticationValue")] + public string? AuthenticationValue { get { return this._AuthenticationValueOption; } set { this._AuthenticationValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + /// + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + /// + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The `eci` value as defined in the 3D Secure 2 specification. + /// + /// The `eci` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + /// + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + [JsonPropertyName("riskScore")] + public string? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSServerTransIDOption { get; private set; } + + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("threeDSServerTransID")] + public string? ThreeDSServerTransID { get { return this._ThreeDSServerTransIDOption; } set { this._ThreeDSServerTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// The `timestamp` value of the 3D Secure 2 authentication. + /// + /// The `timestamp` value of the 3D Secure 2 authentication. + [JsonPropertyName("timestamp")] + public string? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusOption { get; private set; } + + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("transStatus")] + public string? TransStatus { get { return this._TransStatusOption; } set { this._TransStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonPropertyName("transStatusReason")] + public string? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WhiteListStatusOption { get; private set; } + + /// + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + /// + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("whiteListStatus")] + public string? WhiteListStatus { get { return this._WhiteListStatusOption; } set { this._WhiteListStatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2Result {\n"); + sb.Append(" AuthenticationValue: ").Append(AuthenticationValue).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ChallengeCancel: ").Append(ChallengeCancel).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ExemptionIndicator: ").Append(ExemptionIndicator).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" ThreeDSServerTransID: ").Append(ThreeDSServerTransID).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" TransStatus: ").Append(TransStatus).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append(" WhiteListStatus: ").Append(WhiteListStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2ResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2Result Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationValue = default; + Option cavvAlgorithm = default; + Option challengeCancel = default; + Option dsTransID = default; + Option eci = default; + Option exemptionIndicator = default; + Option messageVersion = default; + Option riskScore = default; + Option threeDSRequestorChallengeInd = default; + Option threeDSServerTransID = default; + Option timestamp = default; + Option transStatus = default; + Option transStatusReason = default; + Option whiteListStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationValue": + authenticationValue = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "challengeCancel": + string? challengeCancelRawValue = utf8JsonReader.GetString(); + challengeCancel = new Option(ThreeDS2Result.ChallengeCancelEnum.FromStringOrDefault(challengeCancelRawValue)); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "exemptionIndicator": + string? exemptionIndicatorRawValue = utf8JsonReader.GetString(); + exemptionIndicator = new Option(ThreeDS2Result.ExemptionIndicatorEnum.FromStringOrDefault(exemptionIndicatorRawValue)); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "threeDSServerTransID": + threeDSServerTransID = new Option(utf8JsonReader.GetString()!); + break; + case "timestamp": + timestamp = new Option(utf8JsonReader.GetString()!); + break; + case "transStatus": + transStatus = new Option(utf8JsonReader.GetString()!); + break; + case "transStatusReason": + transStatusReason = new Option(utf8JsonReader.GetString()!); + break; + case "whiteListStatus": + whiteListStatus = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDS2Result(authenticationValue, cavvAlgorithm, challengeCancel, dsTransID, eci, exemptionIndicator, messageVersion, riskScore, threeDSRequestorChallengeInd, threeDSServerTransID, timestamp, transStatus, transStatusReason, whiteListStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2Result threeDS2Result, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2Result, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2Result threeDS2Result, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2Result._AuthenticationValueOption.IsSet) + if (threeDS2Result.AuthenticationValue != null) + writer.WriteString("authenticationValue", threeDS2Result.AuthenticationValue); + + if (threeDS2Result._CavvAlgorithmOption.IsSet) + if (threeDS2Result.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDS2Result.CavvAlgorithm); + + if (threeDS2Result._ChallengeCancelOption.IsSet && threeDS2Result.ChallengeCancel != null) + { + string? challengeCancelRawValue = ThreeDS2Result.ChallengeCancelEnum.ToJsonValue(threeDS2Result._ChallengeCancelOption.Value!.Value); + writer.WriteString("challengeCancel", challengeCancelRawValue); + } + + if (threeDS2Result._DsTransIDOption.IsSet) + if (threeDS2Result.DsTransID != null) + writer.WriteString("dsTransID", threeDS2Result.DsTransID); + + if (threeDS2Result._EciOption.IsSet) + if (threeDS2Result.Eci != null) + writer.WriteString("eci", threeDS2Result.Eci); + + if (threeDS2Result._ExemptionIndicatorOption.IsSet && threeDS2Result.ExemptionIndicator != null) + { + string? exemptionIndicatorRawValue = ThreeDS2Result.ExemptionIndicatorEnum.ToJsonValue(threeDS2Result._ExemptionIndicatorOption.Value!.Value); + writer.WriteString("exemptionIndicator", exemptionIndicatorRawValue); + } + + if (threeDS2Result._MessageVersionOption.IsSet) + if (threeDS2Result.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2Result.MessageVersion); + + if (threeDS2Result._RiskScoreOption.IsSet) + if (threeDS2Result.RiskScore != null) + writer.WriteString("riskScore", threeDS2Result.RiskScore); + + if (threeDS2Result._ThreeDSRequestorChallengeIndOption.IsSet && threeDS2Result.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2Result._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (threeDS2Result._ThreeDSServerTransIDOption.IsSet) + if (threeDS2Result.ThreeDSServerTransID != null) + writer.WriteString("threeDSServerTransID", threeDS2Result.ThreeDSServerTransID); + + if (threeDS2Result._TimestampOption.IsSet) + if (threeDS2Result.Timestamp != null) + writer.WriteString("timestamp", threeDS2Result.Timestamp); + + if (threeDS2Result._TransStatusOption.IsSet) + if (threeDS2Result.TransStatus != null) + writer.WriteString("transStatus", threeDS2Result.TransStatus); + + if (threeDS2Result._TransStatusReasonOption.IsSet) + if (threeDS2Result.TransStatusReason != null) + writer.WriteString("transStatusReason", threeDS2Result.TransStatusReason); + + if (threeDS2Result._WhiteListStatusOption.IsSet) + if (threeDS2Result.WhiteListStatus != null) + writer.WriteString("whiteListStatus", threeDS2Result.WhiteListStatus); + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDSRequestData.cs b/Adyen/Checkout/Models/ThreeDSRequestData.cs new file mode 100644 index 000000000..545ac11bf --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDSRequestData.cs @@ -0,0 +1,703 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDSRequestData. + /// + public partial class ThreeDSRequestData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. + /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0** + [JsonConstructor] + public ThreeDSRequestData(Option challengeWindowSize = default, Option dataOnly = default, Option nativeThreeDS = default, Option threeDSVersion = default) + { + _ChallengeWindowSizeOption = challengeWindowSize; + _DataOnlyOption = dataOnly; + _NativeThreeDSOption = nativeThreeDS; + _ThreeDSVersionOption = threeDSVersion; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSRequestData() + { + } + + partial void OnCreated(); + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonConverter(typeof(ChallengeWindowSizeEnumJsonConverter))] + public class ChallengeWindowSizeEnum : IEnum + { + /// + /// Returns the value of the ChallengeWindowSizeEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeWindowSizeEnum._01 - 01 + /// + public static readonly ChallengeWindowSizeEnum _01 = new("01"); + + /// + /// ChallengeWindowSizeEnum._02 - 02 + /// + public static readonly ChallengeWindowSizeEnum _02 = new("02"); + + /// + /// ChallengeWindowSizeEnum._03 - 03 + /// + public static readonly ChallengeWindowSizeEnum _03 = new("03"); + + /// + /// ChallengeWindowSizeEnum._04 - 04 + /// + public static readonly ChallengeWindowSizeEnum _04 = new("04"); + + /// + /// ChallengeWindowSizeEnum._05 - 05 + /// + public static readonly ChallengeWindowSizeEnum _05 = new("05"); + + private ChallengeWindowSizeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeWindowSizeEnum?(string? value) => value == null ? null : new ChallengeWindowSizeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeWindowSizeEnum? option) => option?.Value; + + public static bool operator ==(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeWindowSizeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeWindowSizeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeWindowSizeEnum._01, + "02" => ChallengeWindowSizeEnum._02, + "03" => ChallengeWindowSizeEnum._03, + "04" => ChallengeWindowSizeEnum._04, + "05" => ChallengeWindowSizeEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeWindowSizeEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeWindowSizeEnum._01) + return "01"; + + if (value == ChallengeWindowSizeEnum._02) + return "02"; + + if (value == ChallengeWindowSizeEnum._03) + return "03"; + + if (value == ChallengeWindowSizeEnum._04) + return "04"; + + if (value == ChallengeWindowSizeEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeWindowSizeEnum. + /// + public class ChallengeWindowSizeEnumJsonConverter : JsonConverter + { + public override ChallengeWindowSizeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeWindowSizeEnum.FromStringOrDefault(value) ?? new ChallengeWindowSizeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeWindowSizeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeWindowSizeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeWindowSizeOption { get; private set; } + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonPropertyName("challengeWindowSize")] + public ChallengeWindowSizeEnum? ChallengeWindowSize { get { return this._ChallengeWindowSizeOption; } set { this._ChallengeWindowSizeOption = new(value); } } + + /// + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. + /// + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. + [JsonConverter(typeof(DataOnlyEnumJsonConverter))] + public class DataOnlyEnum : IEnum + { + /// + /// Returns the value of the DataOnlyEnum. + /// + public string? Value { get; set; } + + /// + /// DataOnlyEnum.False - false + /// + public static readonly DataOnlyEnum False = new("false"); + + /// + /// DataOnlyEnum.True - true + /// + public static readonly DataOnlyEnum True = new("true"); + + private DataOnlyEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DataOnlyEnum?(string? value) => value == null ? null : new DataOnlyEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DataOnlyEnum? option) => option?.Value; + + public static bool operator ==(DataOnlyEnum? left, DataOnlyEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DataOnlyEnum? left, DataOnlyEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DataOnlyEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DataOnlyEnum? FromStringOrDefault(string value) + { + return value switch { + "false" => DataOnlyEnum.False, + "true" => DataOnlyEnum.True, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DataOnlyEnum? value) + { + if (value == null) + return null; + + if (value == DataOnlyEnum.False) + return "false"; + + if (value == DataOnlyEnum.True) + return "true"; + + return null; + } + + /// + /// JsonConverter for writing DataOnlyEnum. + /// + public class DataOnlyEnumJsonConverter : JsonConverter + { + public override DataOnlyEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DataOnlyEnum.FromStringOrDefault(value) ?? new DataOnlyEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DataOnlyEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DataOnlyEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DataOnlyOption { get; private set; } + + /// + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. + /// + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. + [JsonPropertyName("dataOnly")] + public DataOnlyEnum? DataOnly { get { return this._DataOnlyOption; } set { this._DataOnlyOption = new(value); } } + + /// + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. + /// + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. + [JsonConverter(typeof(NativeThreeDSEnumJsonConverter))] + public class NativeThreeDSEnum : IEnum + { + /// + /// Returns the value of the NativeThreeDSEnum. + /// + public string? Value { get; set; } + + /// + /// NativeThreeDSEnum.Preferred - preferred + /// + public static readonly NativeThreeDSEnum Preferred = new("preferred"); + + /// + /// NativeThreeDSEnum.Disabled - disabled + /// + public static readonly NativeThreeDSEnum Disabled = new("disabled"); + + private NativeThreeDSEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NativeThreeDSEnum?(string? value) => value == null ? null : new NativeThreeDSEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NativeThreeDSEnum? option) => option?.Value; + + public static bool operator ==(NativeThreeDSEnum? left, NativeThreeDSEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NativeThreeDSEnum? left, NativeThreeDSEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NativeThreeDSEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NativeThreeDSEnum? FromStringOrDefault(string value) + { + return value switch { + "preferred" => NativeThreeDSEnum.Preferred, + "disabled" => NativeThreeDSEnum.Disabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NativeThreeDSEnum? value) + { + if (value == null) + return null; + + if (value == NativeThreeDSEnum.Preferred) + return "preferred"; + + if (value == NativeThreeDSEnum.Disabled) + return "disabled"; + + return null; + } + + /// + /// JsonConverter for writing NativeThreeDSEnum. + /// + public class NativeThreeDSEnumJsonConverter : JsonConverter + { + public override NativeThreeDSEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NativeThreeDSEnum.FromStringOrDefault(value) ?? new NativeThreeDSEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NativeThreeDSEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NativeThreeDSEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NativeThreeDSOption { get; private set; } + + /// + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. + /// + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. + [JsonPropertyName("nativeThreeDS")] + public NativeThreeDSEnum? NativeThreeDS { get { return this._NativeThreeDSOption; } set { this._NativeThreeDSOption = new(value); } } + + /// + /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0** + /// + /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0** + [JsonConverter(typeof(ThreeDSVersionEnumJsonConverter))] + public class ThreeDSVersionEnum : IEnum + { + /// + /// Returns the value of the ThreeDSVersionEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSVersionEnum._210 - 2.1.0 + /// + public static readonly ThreeDSVersionEnum _210 = new("2.1.0"); + + /// + /// ThreeDSVersionEnum._220 - 2.2.0 + /// + public static readonly ThreeDSVersionEnum _220 = new("2.2.0"); + + private ThreeDSVersionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSVersionEnum?(string? value) => value == null ? null : new ThreeDSVersionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSVersionEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSVersionEnum? left, ThreeDSVersionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSVersionEnum? left, ThreeDSVersionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSVersionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSVersionEnum? FromStringOrDefault(string value) + { + return value switch { + "2.1.0" => ThreeDSVersionEnum._210, + "2.2.0" => ThreeDSVersionEnum._220, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSVersionEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSVersionEnum._210) + return "2.1.0"; + + if (value == ThreeDSVersionEnum._220) + return "2.2.0"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSVersionEnum. + /// + public class ThreeDSVersionEnumJsonConverter : JsonConverter + { + public override ThreeDSVersionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSVersionEnum.FromStringOrDefault(value) ?? new ThreeDSVersionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSVersionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSVersionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0** + /// + /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0** + [JsonPropertyName("threeDSVersion")] + public ThreeDSVersionEnum? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSRequestData {\n"); + sb.Append(" ChallengeWindowSize: ").Append(ChallengeWindowSize).Append("\n"); + sb.Append(" DataOnly: ").Append(DataOnly).Append("\n"); + sb.Append(" NativeThreeDS: ").Append(NativeThreeDS).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSRequestDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSRequestData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option challengeWindowSize = default; + Option dataOnly = default; + Option nativeThreeDS = default; + Option threeDSVersion = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "challengeWindowSize": + string? challengeWindowSizeRawValue = utf8JsonReader.GetString(); + challengeWindowSize = new Option(ThreeDSRequestData.ChallengeWindowSizeEnum.FromStringOrDefault(challengeWindowSizeRawValue)); + break; + case "dataOnly": + string? dataOnlyRawValue = utf8JsonReader.GetString(); + dataOnly = new Option(ThreeDSRequestData.DataOnlyEnum.FromStringOrDefault(dataOnlyRawValue)); + break; + case "nativeThreeDS": + string? nativeThreeDSRawValue = utf8JsonReader.GetString(); + nativeThreeDS = new Option(ThreeDSRequestData.NativeThreeDSEnum.FromStringOrDefault(nativeThreeDSRawValue)); + break; + case "threeDSVersion": + string? threeDSVersionRawValue = utf8JsonReader.GetString(); + threeDSVersion = new Option(ThreeDSRequestData.ThreeDSVersionEnum.FromStringOrDefault(threeDSVersionRawValue)); + break; + default: + break; + } + } + } + + + return new ThreeDSRequestData(challengeWindowSize, dataOnly, nativeThreeDS, threeDSVersion); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSRequestData threeDSRequestData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSRequestData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSRequestData threeDSRequestData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSRequestData._ChallengeWindowSizeOption.IsSet && threeDSRequestData.ChallengeWindowSize != null) + { + string? challengeWindowSizeRawValue = ThreeDSRequestData.ChallengeWindowSizeEnum.ToJsonValue(threeDSRequestData._ChallengeWindowSizeOption.Value!.Value); + writer.WriteString("challengeWindowSize", challengeWindowSizeRawValue); + } + + if (threeDSRequestData._DataOnlyOption.IsSet && threeDSRequestData.DataOnly != null) + { + string? dataOnlyRawValue = ThreeDSRequestData.DataOnlyEnum.ToJsonValue(threeDSRequestData._DataOnlyOption.Value!.Value); + writer.WriteString("dataOnly", dataOnlyRawValue); + } + + if (threeDSRequestData._NativeThreeDSOption.IsSet && threeDSRequestData.NativeThreeDS != null) + { + string? nativeThreeDSRawValue = ThreeDSRequestData.NativeThreeDSEnum.ToJsonValue(threeDSRequestData._NativeThreeDSOption.Value!.Value); + writer.WriteString("nativeThreeDS", nativeThreeDSRawValue); + } + + if (threeDSRequestData._ThreeDSVersionOption.IsSet && threeDSRequestData.ThreeDSVersion != null) + { + string? threeDSVersionRawValue = ThreeDSRequestData.ThreeDSVersionEnum.ToJsonValue(threeDSRequestData._ThreeDSVersionOption.Value!.Value); + writer.WriteString("threeDSVersion", threeDSVersionRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDSRequestorAuthenticationInfo.cs b/Adyen/Checkout/Models/ThreeDSRequestorAuthenticationInfo.cs new file mode 100644 index 000000000..955916fd7 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDSRequestorAuthenticationInfo.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDSRequestorAuthenticationInfo. + /// + public partial class ThreeDSRequestorAuthenticationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + [JsonConstructor] + public ThreeDSRequestorAuthenticationInfo(Option threeDSReqAuthData = default, Option threeDSReqAuthMethod = default, Option threeDSReqAuthTimestamp = default) + { + _ThreeDSReqAuthDataOption = threeDSReqAuthData; + _ThreeDSReqAuthMethodOption = threeDSReqAuthMethod; + _ThreeDSReqAuthTimestampOption = threeDSReqAuthTimestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSRequestorAuthenticationInfo() + { + } + + partial void OnCreated(); + + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + [JsonConverter(typeof(ThreeDSReqAuthMethodEnumJsonConverter))] + public class ThreeDSReqAuthMethodEnum : IEnum + { + /// + /// Returns the value of the ThreeDSReqAuthMethodEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSReqAuthMethodEnum._01 - 01 + /// + public static readonly ThreeDSReqAuthMethodEnum _01 = new("01"); + + /// + /// ThreeDSReqAuthMethodEnum._02 - 02 + /// + public static readonly ThreeDSReqAuthMethodEnum _02 = new("02"); + + /// + /// ThreeDSReqAuthMethodEnum._03 - 03 + /// + public static readonly ThreeDSReqAuthMethodEnum _03 = new("03"); + + /// + /// ThreeDSReqAuthMethodEnum._04 - 04 + /// + public static readonly ThreeDSReqAuthMethodEnum _04 = new("04"); + + /// + /// ThreeDSReqAuthMethodEnum._05 - 05 + /// + public static readonly ThreeDSReqAuthMethodEnum _05 = new("05"); + + /// + /// ThreeDSReqAuthMethodEnum._06 - 06 + /// + public static readonly ThreeDSReqAuthMethodEnum _06 = new("06"); + + private ThreeDSReqAuthMethodEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSReqAuthMethodEnum?(string? value) => value == null ? null : new ThreeDSReqAuthMethodEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSReqAuthMethodEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSReqAuthMethodEnum? left, ThreeDSReqAuthMethodEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSReqAuthMethodEnum? left, ThreeDSReqAuthMethodEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSReqAuthMethodEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSReqAuthMethodEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSReqAuthMethodEnum._01, + "02" => ThreeDSReqAuthMethodEnum._02, + "03" => ThreeDSReqAuthMethodEnum._03, + "04" => ThreeDSReqAuthMethodEnum._04, + "05" => ThreeDSReqAuthMethodEnum._05, + "06" => ThreeDSReqAuthMethodEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSReqAuthMethodEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSReqAuthMethodEnum._01) + return "01"; + + if (value == ThreeDSReqAuthMethodEnum._02) + return "02"; + + if (value == ThreeDSReqAuthMethodEnum._03) + return "03"; + + if (value == ThreeDSReqAuthMethodEnum._04) + return "04"; + + if (value == ThreeDSReqAuthMethodEnum._05) + return "05"; + + if (value == ThreeDSReqAuthMethodEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSReqAuthMethodEnum. + /// + public class ThreeDSReqAuthMethodEnumJsonConverter : JsonConverter + { + public override ThreeDSReqAuthMethodEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSReqAuthMethodEnum.FromStringOrDefault(value) ?? new ThreeDSReqAuthMethodEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSReqAuthMethodEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSReqAuthMethodEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthMethodOption { get; private set; } + + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + [JsonPropertyName("threeDSReqAuthMethod")] + public ThreeDSReqAuthMethodEnum? ThreeDSReqAuthMethod { get { return this._ThreeDSReqAuthMethodOption; } set { this._ThreeDSReqAuthMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthDataOption { get; private set; } + + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + [JsonPropertyName("threeDSReqAuthData")] + public string? ThreeDSReqAuthData { get { return this._ThreeDSReqAuthDataOption; } set { this._ThreeDSReqAuthDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthTimestampOption { get; private set; } + + /// + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + /// + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + [JsonPropertyName("threeDSReqAuthTimestamp")] + public string? ThreeDSReqAuthTimestamp { get { return this._ThreeDSReqAuthTimestampOption; } set { this._ThreeDSReqAuthTimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSRequestorAuthenticationInfo {\n"); + sb.Append(" ThreeDSReqAuthData: ").Append(ThreeDSReqAuthData).Append("\n"); + sb.Append(" ThreeDSReqAuthMethod: ").Append(ThreeDSReqAuthMethod).Append("\n"); + sb.Append(" ThreeDSReqAuthTimestamp: ").Append(ThreeDSReqAuthTimestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ThreeDSReqAuthTimestamp (string) maxLength + if (this.ThreeDSReqAuthTimestamp != null && this.ThreeDSReqAuthTimestamp.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqAuthTimestamp, length must be less than 12.", new [] { "ThreeDSReqAuthTimestamp" }); + } + + // ThreeDSReqAuthTimestamp (string) minLength + if (this.ThreeDSReqAuthTimestamp != null && this.ThreeDSReqAuthTimestamp.Length < 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqAuthTimestamp, length must be greater than 12.", new [] { "ThreeDSReqAuthTimestamp" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSRequestorAuthenticationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSRequestorAuthenticationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDSReqAuthData = default; + Option threeDSReqAuthMethod = default; + Option threeDSReqAuthTimestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDSReqAuthData": + threeDSReqAuthData = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqAuthMethod": + string? threeDSReqAuthMethodRawValue = utf8JsonReader.GetString(); + threeDSReqAuthMethod = new Option(ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.FromStringOrDefault(threeDSReqAuthMethodRawValue)); + break; + case "threeDSReqAuthTimestamp": + threeDSReqAuthTimestamp = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSRequestorAuthenticationInfo(threeDSReqAuthData, threeDSReqAuthMethod, threeDSReqAuthTimestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorAuthenticationInfo threeDSRequestorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSRequestorAuthenticationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSRequestorAuthenticationInfo threeDSRequestorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthDataOption.IsSet) + if (threeDSRequestorAuthenticationInfo.ThreeDSReqAuthData != null) + writer.WriteString("threeDSReqAuthData", threeDSRequestorAuthenticationInfo.ThreeDSReqAuthData); + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthMethodOption.IsSet && threeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethod != null) + { + string? threeDSReqAuthMethodRawValue = ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.ToJsonValue(threeDSRequestorAuthenticationInfo._ThreeDSReqAuthMethodOption.Value!.Value); + writer.WriteString("threeDSReqAuthMethod", threeDSReqAuthMethodRawValue); + } + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthTimestampOption.IsSet) + if (threeDSRequestorAuthenticationInfo.ThreeDSReqAuthTimestamp != null) + writer.WriteString("threeDSReqAuthTimestamp", threeDSRequestorAuthenticationInfo.ThreeDSReqAuthTimestamp); + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDSRequestorPriorAuthenticationInfo.cs b/Adyen/Checkout/Models/ThreeDSRequestorPriorAuthenticationInfo.cs new file mode 100644 index 000000000..b32cba963 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDSRequestorPriorAuthenticationInfo.cs @@ -0,0 +1,400 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDSRequestorPriorAuthenticationInfo. + /// + public partial class ThreeDSRequestorPriorAuthenticationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + [JsonConstructor] + public ThreeDSRequestorPriorAuthenticationInfo(Option threeDSReqPriorAuthData = default, Option threeDSReqPriorAuthMethod = default, Option threeDSReqPriorAuthTimestamp = default, Option threeDSReqPriorRef = default) + { + _ThreeDSReqPriorAuthDataOption = threeDSReqPriorAuthData; + _ThreeDSReqPriorAuthMethodOption = threeDSReqPriorAuthMethod; + _ThreeDSReqPriorAuthTimestampOption = threeDSReqPriorAuthTimestamp; + _ThreeDSReqPriorRefOption = threeDSReqPriorRef; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSRequestorPriorAuthenticationInfo() + { + } + + partial void OnCreated(); + + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + [JsonConverter(typeof(ThreeDSReqPriorAuthMethodEnumJsonConverter))] + public class ThreeDSReqPriorAuthMethodEnum : IEnum + { + /// + /// Returns the value of the ThreeDSReqPriorAuthMethodEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSReqPriorAuthMethodEnum._01 - 01 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _01 = new("01"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._02 - 02 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _02 = new("02"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._03 - 03 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _03 = new("03"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._04 - 04 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _04 = new("04"); + + private ThreeDSReqPriorAuthMethodEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSReqPriorAuthMethodEnum?(string? value) => value == null ? null : new ThreeDSReqPriorAuthMethodEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSReqPriorAuthMethodEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSReqPriorAuthMethodEnum? left, ThreeDSReqPriorAuthMethodEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSReqPriorAuthMethodEnum? left, ThreeDSReqPriorAuthMethodEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSReqPriorAuthMethodEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSReqPriorAuthMethodEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSReqPriorAuthMethodEnum._01, + "02" => ThreeDSReqPriorAuthMethodEnum._02, + "03" => ThreeDSReqPriorAuthMethodEnum._03, + "04" => ThreeDSReqPriorAuthMethodEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSReqPriorAuthMethodEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSReqPriorAuthMethodEnum._01) + return "01"; + + if (value == ThreeDSReqPriorAuthMethodEnum._02) + return "02"; + + if (value == ThreeDSReqPriorAuthMethodEnum._03) + return "03"; + + if (value == ThreeDSReqPriorAuthMethodEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSReqPriorAuthMethodEnum. + /// + public class ThreeDSReqPriorAuthMethodEnumJsonConverter : JsonConverter + { + public override ThreeDSReqPriorAuthMethodEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSReqPriorAuthMethodEnum.FromStringOrDefault(value) ?? new ThreeDSReqPriorAuthMethodEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSReqPriorAuthMethodEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSReqPriorAuthMethodEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthMethodOption { get; private set; } + + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + [JsonPropertyName("threeDSReqPriorAuthMethod")] + public ThreeDSReqPriorAuthMethodEnum? ThreeDSReqPriorAuthMethod { get { return this._ThreeDSReqPriorAuthMethodOption; } set { this._ThreeDSReqPriorAuthMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthDataOption { get; private set; } + + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + [JsonPropertyName("threeDSReqPriorAuthData")] + public string? ThreeDSReqPriorAuthData { get { return this._ThreeDSReqPriorAuthDataOption; } set { this._ThreeDSReqPriorAuthDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthTimestampOption { get; private set; } + + /// + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + /// + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + [JsonPropertyName("threeDSReqPriorAuthTimestamp")] + public string? ThreeDSReqPriorAuthTimestamp { get { return this._ThreeDSReqPriorAuthTimestampOption; } set { this._ThreeDSReqPriorAuthTimestampOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorRefOption { get; private set; } + + /// + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + /// + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + [JsonPropertyName("threeDSReqPriorRef")] + public string? ThreeDSReqPriorRef { get { return this._ThreeDSReqPriorRefOption; } set { this._ThreeDSReqPriorRefOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSRequestorPriorAuthenticationInfo {\n"); + sb.Append(" ThreeDSReqPriorAuthData: ").Append(ThreeDSReqPriorAuthData).Append("\n"); + sb.Append(" ThreeDSReqPriorAuthMethod: ").Append(ThreeDSReqPriorAuthMethod).Append("\n"); + sb.Append(" ThreeDSReqPriorAuthTimestamp: ").Append(ThreeDSReqPriorAuthTimestamp).Append("\n"); + sb.Append(" ThreeDSReqPriorRef: ").Append(ThreeDSReqPriorRef).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ThreeDSReqPriorAuthTimestamp (string) maxLength + if (this.ThreeDSReqPriorAuthTimestamp != null && this.ThreeDSReqPriorAuthTimestamp.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorAuthTimestamp, length must be less than 12.", new [] { "ThreeDSReqPriorAuthTimestamp" }); + } + + // ThreeDSReqPriorAuthTimestamp (string) minLength + if (this.ThreeDSReqPriorAuthTimestamp != null && this.ThreeDSReqPriorAuthTimestamp.Length < 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorAuthTimestamp, length must be greater than 12.", new [] { "ThreeDSReqPriorAuthTimestamp" }); + } + + // ThreeDSReqPriorRef (string) maxLength + if (this.ThreeDSReqPriorRef != null && this.ThreeDSReqPriorRef.Length > 36) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorRef, length must be less than 36.", new [] { "ThreeDSReqPriorRef" }); + } + + // ThreeDSReqPriorRef (string) minLength + if (this.ThreeDSReqPriorRef != null && this.ThreeDSReqPriorRef.Length < 36) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorRef, length must be greater than 36.", new [] { "ThreeDSReqPriorRef" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSRequestorPriorAuthenticationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSRequestorPriorAuthenticationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDSReqPriorAuthData = default; + Option threeDSReqPriorAuthMethod = default; + Option threeDSReqPriorAuthTimestamp = default; + Option threeDSReqPriorRef = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDSReqPriorAuthData": + threeDSReqPriorAuthData = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqPriorAuthMethod": + string? threeDSReqPriorAuthMethodRawValue = utf8JsonReader.GetString(); + threeDSReqPriorAuthMethod = new Option(ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.FromStringOrDefault(threeDSReqPriorAuthMethodRawValue)); + break; + case "threeDSReqPriorAuthTimestamp": + threeDSReqPriorAuthTimestamp = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqPriorRef": + threeDSReqPriorRef = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSRequestorPriorAuthenticationInfo(threeDSReqPriorAuthData, threeDSReqPriorAuthMethod, threeDSReqPriorAuthTimestamp, threeDSReqPriorRef); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorPriorAuthenticationInfo threeDSRequestorPriorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSRequestorPriorAuthenticationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSRequestorPriorAuthenticationInfo threeDSRequestorPriorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthDataOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthData != null) + writer.WriteString("threeDSReqPriorAuthData", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthData); + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthMethodOption.IsSet && threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethod != null) + { + string? threeDSReqPriorAuthMethodRawValue = ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.ToJsonValue(threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthMethodOption.Value!.Value); + writer.WriteString("threeDSReqPriorAuthMethod", threeDSReqPriorAuthMethodRawValue); + } + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthTimestampOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthTimestamp != null) + writer.WriteString("threeDSReqPriorAuthTimestamp", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthTimestamp); + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorRefOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorRef != null) + writer.WriteString("threeDSReqPriorRef", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorRef); + } + } +} diff --git a/Adyen/Checkout/Models/ThreeDSecureData.cs b/Adyen/Checkout/Models/ThreeDSecureData.cs new file mode 100644 index 000000000..58a8b77d9 --- /dev/null +++ b/Adyen/Checkout/Models/ThreeDSecureData.cs @@ -0,0 +1,891 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ThreeDSecureData. + /// + public partial class ThreeDSecureData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + /// The CAVV algorithm used. Include this only for 3D Secure 1. + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + /// The electronic commerce indicator. + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + /// The version of the 3D Secure protocol. + /// Network token authentication verification value (TAVV). The network token cryptogram. + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + [JsonConstructor] + public ThreeDSecureData(Option authenticationResponse = default, Option cavv = default, Option cavvAlgorithm = default, Option challengeCancel = default, Option directoryResponse = default, Option dsTransID = default, Option eci = default, Option riskScore = default, Option threeDSVersion = default, Option tokenAuthenticationVerificationValue = default, Option transStatusReason = default, Option xid = default) + { + _AuthenticationResponseOption = authenticationResponse; + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _ChallengeCancelOption = challengeCancel; + _DirectoryResponseOption = directoryResponse; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _RiskScoreOption = riskScore; + _ThreeDSVersionOption = threeDSVersion; + _TokenAuthenticationVerificationValueOption = tokenAuthenticationVerificationValue; + _TransStatusReasonOption = transStatusReason; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSecureData() + { + } + + partial void OnCreated(); + + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + [JsonConverter(typeof(AuthenticationResponseEnumJsonConverter))] + public class AuthenticationResponseEnum : IEnum + { + /// + /// Returns the value of the AuthenticationResponseEnum. + /// + public string? Value { get; set; } + + /// + /// AuthenticationResponseEnum.Y - Y + /// + public static readonly AuthenticationResponseEnum Y = new("Y"); + + /// + /// AuthenticationResponseEnum.N - N + /// + public static readonly AuthenticationResponseEnum N = new("N"); + + /// + /// AuthenticationResponseEnum.U - U + /// + public static readonly AuthenticationResponseEnum U = new("U"); + + /// + /// AuthenticationResponseEnum.A - A + /// + public static readonly AuthenticationResponseEnum A = new("A"); + + private AuthenticationResponseEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AuthenticationResponseEnum?(string? value) => value == null ? null : new AuthenticationResponseEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AuthenticationResponseEnum? option) => option?.Value; + + public static bool operator ==(AuthenticationResponseEnum? left, AuthenticationResponseEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AuthenticationResponseEnum? left, AuthenticationResponseEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AuthenticationResponseEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AuthenticationResponseEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => AuthenticationResponseEnum.Y, + "N" => AuthenticationResponseEnum.N, + "U" => AuthenticationResponseEnum.U, + "A" => AuthenticationResponseEnum.A, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AuthenticationResponseEnum? value) + { + if (value == null) + return null; + + if (value == AuthenticationResponseEnum.Y) + return "Y"; + + if (value == AuthenticationResponseEnum.N) + return "N"; + + if (value == AuthenticationResponseEnum.U) + return "U"; + + if (value == AuthenticationResponseEnum.A) + return "A"; + + return null; + } + + /// + /// JsonConverter for writing AuthenticationResponseEnum. + /// + public class AuthenticationResponseEnumJsonConverter : JsonConverter + { + public override AuthenticationResponseEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AuthenticationResponseEnum.FromStringOrDefault(value) ?? new AuthenticationResponseEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AuthenticationResponseEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AuthenticationResponseEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationResponseOption { get; private set; } + + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + [JsonPropertyName("authenticationResponse")] + public AuthenticationResponseEnum? AuthenticationResponse { get { return this._AuthenticationResponseOption; } set { this._AuthenticationResponseOption = new(value); } } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonConverter(typeof(ChallengeCancelEnumJsonConverter))] + public class ChallengeCancelEnum : IEnum + { + /// + /// Returns the value of the ChallengeCancelEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeCancelEnum._01 - 01 + /// + public static readonly ChallengeCancelEnum _01 = new("01"); + + /// + /// ChallengeCancelEnum._02 - 02 + /// + public static readonly ChallengeCancelEnum _02 = new("02"); + + /// + /// ChallengeCancelEnum._03 - 03 + /// + public static readonly ChallengeCancelEnum _03 = new("03"); + + /// + /// ChallengeCancelEnum._04 - 04 + /// + public static readonly ChallengeCancelEnum _04 = new("04"); + + /// + /// ChallengeCancelEnum._05 - 05 + /// + public static readonly ChallengeCancelEnum _05 = new("05"); + + /// + /// ChallengeCancelEnum._06 - 06 + /// + public static readonly ChallengeCancelEnum _06 = new("06"); + + /// + /// ChallengeCancelEnum._07 - 07 + /// + public static readonly ChallengeCancelEnum _07 = new("07"); + + private ChallengeCancelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeCancelEnum?(string? value) => value == null ? null : new ChallengeCancelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeCancelEnum? option) => option?.Value; + + public static bool operator ==(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeCancelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeCancelEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeCancelEnum._01, + "02" => ChallengeCancelEnum._02, + "03" => ChallengeCancelEnum._03, + "04" => ChallengeCancelEnum._04, + "05" => ChallengeCancelEnum._05, + "06" => ChallengeCancelEnum._06, + "07" => ChallengeCancelEnum._07, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeCancelEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeCancelEnum._01) + return "01"; + + if (value == ChallengeCancelEnum._02) + return "02"; + + if (value == ChallengeCancelEnum._03) + return "03"; + + if (value == ChallengeCancelEnum._04) + return "04"; + + if (value == ChallengeCancelEnum._05) + return "05"; + + if (value == ChallengeCancelEnum._06) + return "06"; + + if (value == ChallengeCancelEnum._07) + return "07"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeCancelEnum. + /// + public class ChallengeCancelEnumJsonConverter : JsonConverter + { + public override ChallengeCancelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeCancelEnum.FromStringOrDefault(value) ?? new ChallengeCancelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeCancelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeCancelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeCancelOption { get; private set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonPropertyName("challengeCancel")] + public ChallengeCancelEnum? ChallengeCancel { get { return this._ChallengeCancelOption; } set { this._ChallengeCancelOption = new(value); } } + + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + [JsonConverter(typeof(DirectoryResponseEnumJsonConverter))] + public class DirectoryResponseEnum : IEnum + { + /// + /// Returns the value of the DirectoryResponseEnum. + /// + public string? Value { get; set; } + + /// + /// DirectoryResponseEnum.A - A + /// + public static readonly DirectoryResponseEnum A = new("A"); + + /// + /// DirectoryResponseEnum.C - C + /// + public static readonly DirectoryResponseEnum C = new("C"); + + /// + /// DirectoryResponseEnum.D - D + /// + public static readonly DirectoryResponseEnum D = new("D"); + + /// + /// DirectoryResponseEnum.I - I + /// + public static readonly DirectoryResponseEnum I = new("I"); + + /// + /// DirectoryResponseEnum.N - N + /// + public static readonly DirectoryResponseEnum N = new("N"); + + /// + /// DirectoryResponseEnum.R - R + /// + public static readonly DirectoryResponseEnum R = new("R"); + + /// + /// DirectoryResponseEnum.U - U + /// + public static readonly DirectoryResponseEnum U = new("U"); + + /// + /// DirectoryResponseEnum.Y - Y + /// + public static readonly DirectoryResponseEnum Y = new("Y"); + + private DirectoryResponseEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DirectoryResponseEnum?(string? value) => value == null ? null : new DirectoryResponseEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DirectoryResponseEnum? option) => option?.Value; + + public static bool operator ==(DirectoryResponseEnum? left, DirectoryResponseEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DirectoryResponseEnum? left, DirectoryResponseEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DirectoryResponseEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DirectoryResponseEnum? FromStringOrDefault(string value) + { + return value switch { + "A" => DirectoryResponseEnum.A, + "C" => DirectoryResponseEnum.C, + "D" => DirectoryResponseEnum.D, + "I" => DirectoryResponseEnum.I, + "N" => DirectoryResponseEnum.N, + "R" => DirectoryResponseEnum.R, + "U" => DirectoryResponseEnum.U, + "Y" => DirectoryResponseEnum.Y, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DirectoryResponseEnum? value) + { + if (value == null) + return null; + + if (value == DirectoryResponseEnum.A) + return "A"; + + if (value == DirectoryResponseEnum.C) + return "C"; + + if (value == DirectoryResponseEnum.D) + return "D"; + + if (value == DirectoryResponseEnum.I) + return "I"; + + if (value == DirectoryResponseEnum.N) + return "N"; + + if (value == DirectoryResponseEnum.R) + return "R"; + + if (value == DirectoryResponseEnum.U) + return "U"; + + if (value == DirectoryResponseEnum.Y) + return "Y"; + + return null; + } + + /// + /// JsonConverter for writing DirectoryResponseEnum. + /// + public class DirectoryResponseEnumJsonConverter : JsonConverter + { + public override DirectoryResponseEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DirectoryResponseEnum.FromStringOrDefault(value) ?? new DirectoryResponseEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DirectoryResponseEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DirectoryResponseEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectoryResponseOption { get; private set; } + + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + [JsonPropertyName("directoryResponse")] + public DirectoryResponseEnum? DirectoryResponse { get { return this._DirectoryResponseOption; } set { this._DirectoryResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + /// + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + [JsonPropertyName("cavv")] + public byte[]? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. Include this only for 3D Secure 1. + /// + /// The CAVV algorithm used. Include this only for 3D Secure 1. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The electronic commerce indicator. + /// + /// The electronic commerce indicator. + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + /// + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + [JsonPropertyName("riskScore")] + public string? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The version of the 3D Secure protocol. + /// + /// The version of the 3D Secure protocol. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenAuthenticationVerificationValueOption { get; private set; } + + /// + /// Network token authentication verification value (TAVV). The network token cryptogram. + /// + /// Network token authentication verification value (TAVV). The network token cryptogram. + [JsonPropertyName("tokenAuthenticationVerificationValue")] + public byte[]? TokenAuthenticationVerificationValue { get { return this._TokenAuthenticationVerificationValueOption; } set { this._TokenAuthenticationVerificationValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonPropertyName("transStatusReason")] + public string? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + /// + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + [JsonPropertyName("xid")] + public byte[]? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecureData {\n"); + sb.Append(" AuthenticationResponse: ").Append(AuthenticationResponse).Append("\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ChallengeCancel: ").Append(ChallengeCancel).Append("\n"); + sb.Append(" DirectoryResponse: ").Append(DirectoryResponse).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append(" TokenAuthenticationVerificationValue: ").Append(TokenAuthenticationVerificationValue).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSecureDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSecureData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationResponse = default; + Option cavv = default; + Option cavvAlgorithm = default; + Option challengeCancel = default; + Option directoryResponse = default; + Option dsTransID = default; + Option eci = default; + Option riskScore = default; + Option threeDSVersion = default; + Option tokenAuthenticationVerificationValue = default; + Option transStatusReason = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationResponse": + string? authenticationResponseRawValue = utf8JsonReader.GetString(); + authenticationResponse = new Option(ThreeDSecureData.AuthenticationResponseEnum.FromStringOrDefault(authenticationResponseRawValue)); + break; + case "cavv": + cavv = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "challengeCancel": + string? challengeCancelRawValue = utf8JsonReader.GetString(); + challengeCancel = new Option(ThreeDSecureData.ChallengeCancelEnum.FromStringOrDefault(challengeCancelRawValue)); + break; + case "directoryResponse": + string? directoryResponseRawValue = utf8JsonReader.GetString(); + directoryResponse = new Option(ThreeDSecureData.DirectoryResponseEnum.FromStringOrDefault(directoryResponseRawValue)); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + case "tokenAuthenticationVerificationValue": + tokenAuthenticationVerificationValue = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transStatusReason": + transStatusReason = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ThreeDSecureData(authenticationResponse, cavv, cavvAlgorithm, challengeCancel, directoryResponse, dsTransID, eci, riskScore, threeDSVersion, tokenAuthenticationVerificationValue, transStatusReason, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSecureData threeDSecureData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSecureData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSecureData threeDSecureData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSecureData._AuthenticationResponseOption.IsSet && threeDSecureData.AuthenticationResponse != null) + { + string? authenticationResponseRawValue = ThreeDSecureData.AuthenticationResponseEnum.ToJsonValue(threeDSecureData._AuthenticationResponseOption.Value!.Value); + writer.WriteString("authenticationResponse", authenticationResponseRawValue); + } + + if (threeDSecureData._CavvOption.IsSet) + { + writer.WritePropertyName("cavv"); + JsonSerializer.Serialize(writer, threeDSecureData.Cavv, jsonSerializerOptions); + } + if (threeDSecureData._CavvAlgorithmOption.IsSet) + if (threeDSecureData.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDSecureData.CavvAlgorithm); + + if (threeDSecureData._ChallengeCancelOption.IsSet && threeDSecureData.ChallengeCancel != null) + { + string? challengeCancelRawValue = ThreeDSecureData.ChallengeCancelEnum.ToJsonValue(threeDSecureData._ChallengeCancelOption.Value!.Value); + writer.WriteString("challengeCancel", challengeCancelRawValue); + } + + if (threeDSecureData._DirectoryResponseOption.IsSet && threeDSecureData.DirectoryResponse != null) + { + string? directoryResponseRawValue = ThreeDSecureData.DirectoryResponseEnum.ToJsonValue(threeDSecureData._DirectoryResponseOption.Value!.Value); + writer.WriteString("directoryResponse", directoryResponseRawValue); + } + + if (threeDSecureData._DsTransIDOption.IsSet) + if (threeDSecureData.DsTransID != null) + writer.WriteString("dsTransID", threeDSecureData.DsTransID); + + if (threeDSecureData._EciOption.IsSet) + if (threeDSecureData.Eci != null) + writer.WriteString("eci", threeDSecureData.Eci); + + if (threeDSecureData._RiskScoreOption.IsSet) + if (threeDSecureData.RiskScore != null) + writer.WriteString("riskScore", threeDSecureData.RiskScore); + + if (threeDSecureData._ThreeDSVersionOption.IsSet) + if (threeDSecureData.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", threeDSecureData.ThreeDSVersion); + + if (threeDSecureData._TokenAuthenticationVerificationValueOption.IsSet) + { + writer.WritePropertyName("tokenAuthenticationVerificationValue"); + JsonSerializer.Serialize(writer, threeDSecureData.TokenAuthenticationVerificationValue, jsonSerializerOptions); + } + if (threeDSecureData._TransStatusReasonOption.IsSet) + if (threeDSecureData.TransStatusReason != null) + writer.WriteString("transStatusReason", threeDSecureData.TransStatusReason); + + if (threeDSecureData._XidOption.IsSet) + { + writer.WritePropertyName("xid"); + JsonSerializer.Serialize(writer, threeDSecureData.Xid, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/Ticket.cs b/Adyen/Checkout/Models/Ticket.cs new file mode 100644 index 000000000..83ecb1100 --- /dev/null +++ b/Adyen/Checkout/Models/Ticket.cs @@ -0,0 +1,231 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// Ticket. + /// + public partial class Ticket : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// The date that the ticket was issued to the passenger. * minLength: 10 characters * maxLength: 10 characters * Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): yyyy-MM-dd + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonConstructor] + public Ticket(Option issueAddress = default, Option issueDate = default, Option number = default) + { + _IssueAddressOption = issueAddress; + _IssueDateOption = issueDate; + _NumberOption = number; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Ticket() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueAddressOption { get; private set; } + + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + [JsonPropertyName("issueAddress")] + public string? IssueAddress { get { return this._IssueAddressOption; } set { this._IssueAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueDateOption { get; private set; } + + /// + /// The date that the ticket was issued to the passenger. * minLength: 10 characters * maxLength: 10 characters * Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): yyyy-MM-dd + /// + /// The date that the ticket was issued to the passenger. * minLength: 10 characters * maxLength: 10 characters * Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): yyyy-MM-dd + [JsonPropertyName("issueDate")] + public DateOnly? IssueDate { get { return this._IssueDateOption; } set { this._IssueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Ticket {\n"); + sb.Append(" IssueAddress: ").Append(IssueAddress).Append("\n"); + sb.Append(" IssueDate: ").Append(IssueDate).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TicketJsonConverter : JsonConverter + { + /// + /// The format to use to serialize IssueDate. + /// + public static string IssueDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Ticket Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option issueAddress = default; + Option issueDate = default; + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "issueAddress": + issueAddress = new Option(utf8JsonReader.GetString()!); + break; + case "issueDate": + issueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Ticket(issueAddress, issueDate, number); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Ticket ticket, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ticket, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Ticket ticket, JsonSerializerOptions jsonSerializerOptions) + { + + if (ticket._IssueAddressOption.IsSet) + if (ticket.IssueAddress != null) + writer.WriteString("issueAddress", ticket.IssueAddress); + + if (ticket._IssueDateOption.IsSet) + writer.WriteString("issueDate", ticket._IssueDateOption.Value!.Value.ToString(IssueDateFormat)); + + if (ticket._NumberOption.IsSet) + if (ticket.Number != null) + writer.WriteString("number", ticket.Number); + } + } +} diff --git a/Adyen/Checkout/Models/TravelAgency.cs b/Adyen/Checkout/Models/TravelAgency.cs new file mode 100644 index 000000000..4f32cdc42 --- /dev/null +++ b/Adyen/Checkout/Models/TravelAgency.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// TravelAgency. + /// + public partial class TravelAgency : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonConstructor] + public TravelAgency(Option code = default, Option name = default) + { + _CodeOption = code; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TravelAgency() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TravelAgency {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TravelAgencyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TravelAgency Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TravelAgency(code, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TravelAgency travelAgency, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, travelAgency, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TravelAgency travelAgency, JsonSerializerOptions jsonSerializerOptions) + { + + if (travelAgency._CodeOption.IsSet) + if (travelAgency.Code != null) + writer.WriteString("code", travelAgency.Code); + + if (travelAgency._NameOption.IsSet) + if (travelAgency.Name != null) + writer.WriteString("name", travelAgency.Name); + } + } +} diff --git a/Adyen/Checkout/Models/TwintDetails.cs b/Adyen/Checkout/Models/TwintDetails.cs new file mode 100644 index 000000000..aa6494cd0 --- /dev/null +++ b/Adyen/Checkout/Models/TwintDetails.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// TwintDetails. + /// + public partial class TwintDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The type of flow to initiate. + /// The payment method type. + [JsonConstructor] + public TwintDetails(Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option subtype = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _SubtypeOption = subtype; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TwintDetails() + { + } + + partial void OnCreated(); + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Twint - twint + /// + public static readonly TypeEnum Twint = new("twint"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "twint" => TypeEnum.Twint, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Twint) + return "twint"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The payment method type. + /// + /// The payment method type. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubtypeOption { get; private set; } + + /// + /// The type of flow to initiate. + /// + /// The type of flow to initiate. + [JsonPropertyName("subtype")] + public string? Subtype { get { return this._SubtypeOption; } set { this._SubtypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TwintDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TwintDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TwintDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option subtype = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "subtype": + subtype = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TwintDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new TwintDetails(checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, subtype, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TwintDetails twintDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, twintDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TwintDetails twintDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (twintDetails._CheckoutAttemptIdOption.IsSet) + if (twintDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", twintDetails.CheckoutAttemptId); + + if (twintDetails._RecurringDetailReferenceOption.IsSet) + if (twintDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", twintDetails.RecurringDetailReference); + + if (twintDetails._StoredPaymentMethodIdOption.IsSet) + if (twintDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", twintDetails.StoredPaymentMethodId); + + if (twintDetails._SubtypeOption.IsSet) + if (twintDetails.Subtype != null) + writer.WriteString("subtype", twintDetails.Subtype); + + if (twintDetails._TypeOption.IsSet && twintDetails.Type != null) + { + string? typeRawValue = TwintDetails.TypeEnum.ToJsonValue(twintDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/UPIPaymentMethod.cs b/Adyen/Checkout/Models/UPIPaymentMethod.cs new file mode 100644 index 000000000..b4d474c01 --- /dev/null +++ b/Adyen/Checkout/Models/UPIPaymentMethod.cs @@ -0,0 +1,170 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UPIPaymentMethod. + /// + public partial class UPIPaymentMethod : ShopperIdPaymentMethod, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// virtualPaymentAddress + [JsonConstructor] + public UPIPaymentMethod(Option virtualPaymentAddress = default) : base() + { + _VirtualPaymentAddressOption = virtualPaymentAddress; + OnCreated(); + } + + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VirtualPaymentAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("virtualPaymentAddress")] + public string? VirtualPaymentAddress { get { return this._VirtualPaymentAddressOption; } set { this._VirtualPaymentAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UPIPaymentMethod {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" VirtualPaymentAddress: ").Append(VirtualPaymentAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class UPIPaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UPIPaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option virtualPaymentAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "virtualPaymentAddress": + virtualPaymentAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UPIPaymentMethod.", nameof(type)); + + return new UPIPaymentMethod(virtualPaymentAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UPIPaymentMethod uPIPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uPIPaymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UPIPaymentMethod uPIPaymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (uPIPaymentMethod.Type != null) + writer.WriteString("type", uPIPaymentMethod.Type); + + if (uPIPaymentMethod._VirtualPaymentAddressOption.IsSet) + if (uPIPaymentMethod.VirtualPaymentAddress != null) + writer.WriteString("virtualPaymentAddress", uPIPaymentMethod.VirtualPaymentAddress); + } + } +} diff --git a/Adyen/Checkout/Models/UpdatePaymentLinkRequest.cs b/Adyen/Checkout/Models/UpdatePaymentLinkRequest.cs new file mode 100644 index 000000000..293d75316 --- /dev/null +++ b/Adyen/Checkout/Models/UpdatePaymentLinkRequest.cs @@ -0,0 +1,269 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UpdatePaymentLinkRequest. + /// + public partial class UpdatePaymentLinkRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Status of the payment link. Possible values: * **expired** + [JsonConstructor] + public UpdatePaymentLinkRequest(StatusEnum status) + { + Status = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdatePaymentLinkRequest() + { + } + + partial void OnCreated(); + + /// + /// Status of the payment link. Possible values: * **expired** + /// + /// Status of the payment link. Possible values: * **expired** + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "expired" => StatusEnum.Expired, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Expired) + return "expired"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// Status of the payment link. Possible values: * **expired** + /// + /// Status of the payment link. Possible values: * **expired** + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdatePaymentLinkRequest {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdatePaymentLinkRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdatePaymentLinkRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(UpdatePaymentLinkRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class UpdatePaymentLinkRequest.", nameof(status)); + + return new UpdatePaymentLinkRequest(status.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdatePaymentLinkRequest updatePaymentLinkRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updatePaymentLinkRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdatePaymentLinkRequest updatePaymentLinkRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updatePaymentLinkRequest.Status != null) + { + string? statusRawValue = UpdatePaymentLinkRequest.StatusEnum.ToJsonValue(updatePaymentLinkRequest.Status); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/UpiCollectDetails.cs b/Adyen/Checkout/Models/UpiCollectDetails.cs new file mode 100644 index 000000000..edf439e32 --- /dev/null +++ b/Adyen/Checkout/Models/UpiCollectDetails.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UpiCollectDetails. + /// + public partial class UpiCollectDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **upi_collect** (default to TypeEnum.UpiCollect) + /// The virtual payment address for UPI. + [JsonConstructor] + public UpiCollectDetails(Option billingSequenceNumber = default, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option storedPaymentMethodId = default, TypeEnum type = default, Option virtualPaymentAddress = default) + { + _BillingSequenceNumberOption = billingSequenceNumber; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + _VirtualPaymentAddressOption = virtualPaymentAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpiCollectDetails() + { + } + + partial void OnCreated(); + + /// + /// **upi_collect** + /// + /// **upi_collect** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UpiCollect - upi_collect + /// + public static readonly TypeEnum UpiCollect = new("upi_collect"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "upi_collect" => TypeEnum.UpiCollect, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UpiCollect) + return "upi_collect"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **upi_collect** + /// + /// **upi_collect** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VirtualPaymentAddressOption { get; private set; } + + /// + /// The virtual payment address for UPI. + /// + /// The virtual payment address for UPI. + [JsonPropertyName("virtualPaymentAddress")] + public string? VirtualPaymentAddress { get { return this._VirtualPaymentAddressOption; } set { this._VirtualPaymentAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpiCollectDetails {\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" VirtualPaymentAddress: ").Append(VirtualPaymentAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpiCollectDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpiCollectDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingSequenceNumber = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option storedPaymentMethodId = default; + Option type = default; + Option virtualPaymentAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UpiCollectDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "virtualPaymentAddress": + virtualPaymentAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UpiCollectDetails.", nameof(type)); + + return new UpiCollectDetails(billingSequenceNumber, checkoutAttemptId, recurringDetailReference, shopperNotificationReference, storedPaymentMethodId, type.Value!.Value!, virtualPaymentAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpiCollectDetails upiCollectDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, upiCollectDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpiCollectDetails upiCollectDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (upiCollectDetails._BillingSequenceNumberOption.IsSet) + if (upiCollectDetails.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", upiCollectDetails.BillingSequenceNumber); + + if (upiCollectDetails._CheckoutAttemptIdOption.IsSet) + if (upiCollectDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", upiCollectDetails.CheckoutAttemptId); + + if (upiCollectDetails._RecurringDetailReferenceOption.IsSet) + if (upiCollectDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", upiCollectDetails.RecurringDetailReference); + + if (upiCollectDetails._ShopperNotificationReferenceOption.IsSet) + if (upiCollectDetails.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", upiCollectDetails.ShopperNotificationReference); + + if (upiCollectDetails._StoredPaymentMethodIdOption.IsSet) + if (upiCollectDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", upiCollectDetails.StoredPaymentMethodId); + + if (upiCollectDetails.Type != null) + { + string? typeRawValue = UpiCollectDetails.TypeEnum.ToJsonValue(upiCollectDetails.Type); + writer.WriteString("type", typeRawValue); + } + + if (upiCollectDetails._VirtualPaymentAddressOption.IsSet) + if (upiCollectDetails.VirtualPaymentAddress != null) + writer.WriteString("virtualPaymentAddress", upiCollectDetails.VirtualPaymentAddress); + } + } +} diff --git a/Adyen/Checkout/Models/UpiIntentDetails.cs b/Adyen/Checkout/Models/UpiIntentDetails.cs new file mode 100644 index 000000000..76cb53cdc --- /dev/null +++ b/Adyen/Checkout/Models/UpiIntentDetails.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UpiIntentDetails. + /// + public partial class UpiIntentDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// TPAP (Third Party Application) Id that is being used to make the UPI payment + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **upi_intent** (default to TypeEnum.UpiIntent) + [JsonConstructor] + public UpiIntentDetails(Option appId = default, Option billingSequenceNumber = default, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + _AppIdOption = appId; + _BillingSequenceNumberOption = billingSequenceNumber; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpiIntentDetails() + { + } + + partial void OnCreated(); + + /// + /// **upi_intent** + /// + /// **upi_intent** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UpiIntent - upi_intent + /// + public static readonly TypeEnum UpiIntent = new("upi_intent"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "upi_intent" => TypeEnum.UpiIntent, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UpiIntent) + return "upi_intent"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **upi_intent** + /// + /// **upi_intent** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AppIdOption { get; private set; } + + /// + /// TPAP (Third Party Application) Id that is being used to make the UPI payment + /// + /// TPAP (Third Party Application) Id that is being used to make the UPI payment + [JsonPropertyName("appId")] + public string? AppId { get { return this._AppIdOption; } set { this._AppIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpiIntentDetails {\n"); + sb.Append(" AppId: ").Append(AppId).Append("\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpiIntentDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpiIntentDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option appId = default; + Option billingSequenceNumber = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "appId": + appId = new Option(utf8JsonReader.GetString()!); + break; + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UpiIntentDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UpiIntentDetails.", nameof(type)); + + return new UpiIntentDetails(appId, billingSequenceNumber, checkoutAttemptId, recurringDetailReference, shopperNotificationReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpiIntentDetails upiIntentDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, upiIntentDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpiIntentDetails upiIntentDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (upiIntentDetails._AppIdOption.IsSet) + if (upiIntentDetails.AppId != null) + writer.WriteString("appId", upiIntentDetails.AppId); + + if (upiIntentDetails._BillingSequenceNumberOption.IsSet) + if (upiIntentDetails.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", upiIntentDetails.BillingSequenceNumber); + + if (upiIntentDetails._CheckoutAttemptIdOption.IsSet) + if (upiIntentDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", upiIntentDetails.CheckoutAttemptId); + + if (upiIntentDetails._RecurringDetailReferenceOption.IsSet) + if (upiIntentDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", upiIntentDetails.RecurringDetailReference); + + if (upiIntentDetails._ShopperNotificationReferenceOption.IsSet) + if (upiIntentDetails.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", upiIntentDetails.ShopperNotificationReference); + + if (upiIntentDetails._StoredPaymentMethodIdOption.IsSet) + if (upiIntentDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", upiIntentDetails.StoredPaymentMethodId); + + if (upiIntentDetails.Type != null) + { + string? typeRawValue = UpiIntentDetails.TypeEnum.ToJsonValue(upiIntentDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/UpiQrDetails.cs b/Adyen/Checkout/Models/UpiQrDetails.cs new file mode 100644 index 000000000..6157f624a --- /dev/null +++ b/Adyen/Checkout/Models/UpiQrDetails.cs @@ -0,0 +1,401 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UpiQrDetails. + /// + public partial class UpiQrDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **upi_qr** (default to TypeEnum.UpiQr) + [JsonConstructor] + public UpiQrDetails(Option billingSequenceNumber = default, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option shopperNotificationReference = default, Option storedPaymentMethodId = default, TypeEnum type = default) + { + _BillingSequenceNumberOption = billingSequenceNumber; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpiQrDetails() + { + } + + partial void OnCreated(); + + /// + /// **upi_qr** + /// + /// **upi_qr** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UpiQr - upi_qr + /// + public static readonly TypeEnum UpiQr = new("upi_qr"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "upi_qr" => TypeEnum.UpiQr, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UpiQr) + return "upi_qr"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **upi_qr** + /// + /// **upi_qr** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + /// + /// The sequence number for the debit. For example, send **2** if this is the second debit for the subscription. The sequence number is included in the notification sent to the shopper. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + /// + /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used for recurring payment only. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpiQrDetails {\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpiQrDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpiQrDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingSequenceNumber = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option shopperNotificationReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UpiQrDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UpiQrDetails.", nameof(type)); + + return new UpiQrDetails(billingSequenceNumber, checkoutAttemptId, recurringDetailReference, shopperNotificationReference, storedPaymentMethodId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpiQrDetails upiQrDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, upiQrDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpiQrDetails upiQrDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (upiQrDetails._BillingSequenceNumberOption.IsSet) + if (upiQrDetails.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", upiQrDetails.BillingSequenceNumber); + + if (upiQrDetails._CheckoutAttemptIdOption.IsSet) + if (upiQrDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", upiQrDetails.CheckoutAttemptId); + + if (upiQrDetails._RecurringDetailReferenceOption.IsSet) + if (upiQrDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", upiQrDetails.RecurringDetailReference); + + if (upiQrDetails._ShopperNotificationReferenceOption.IsSet) + if (upiQrDetails.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", upiQrDetails.ShopperNotificationReference); + + if (upiQrDetails._StoredPaymentMethodIdOption.IsSet) + if (upiQrDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", upiQrDetails.StoredPaymentMethodId); + + if (upiQrDetails.Type != null) + { + string? typeRawValue = UpiQrDetails.TypeEnum.ToJsonValue(upiQrDetails.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/UtilityRequest.cs b/Adyen/Checkout/Models/UtilityRequest.cs new file mode 100644 index 000000000..ed25bc30e --- /dev/null +++ b/Adyen/Checkout/Models/UtilityRequest.cs @@ -0,0 +1,171 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UtilityRequest. + /// + public partial class UtilityRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of origin domains, for which origin keys are requested. + [JsonConstructor] + public UtilityRequest(List originDomains) + { + OriginDomains = originDomains; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UtilityRequest() + { + } + + partial void OnCreated(); + + /// + /// The list of origin domains, for which origin keys are requested. + /// + /// The list of origin domains, for which origin keys are requested. + [JsonPropertyName("originDomains")] + public List OriginDomains { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UtilityRequest {\n"); + sb.Append(" OriginDomains: ").Append(OriginDomains).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UtilityRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UtilityRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> originDomains = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "originDomains": + originDomains = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!originDomains.IsSet) + throw new ArgumentException("Property is required for class UtilityRequest.", nameof(originDomains)); + + return new UtilityRequest(originDomains.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UtilityRequest utilityRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, utilityRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UtilityRequest utilityRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("originDomains"); + JsonSerializer.Serialize(writer, utilityRequest.OriginDomains, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Checkout/Models/UtilityResponse.cs b/Adyen/Checkout/Models/UtilityResponse.cs new file mode 100644 index 000000000..b6b0173cc --- /dev/null +++ b/Adyen/Checkout/Models/UtilityResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// UtilityResponse. + /// + public partial class UtilityResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of origin keys for all requested domains. For each list item, the key is the domain and the value is the origin key. + [JsonConstructor] + public UtilityResponse(Option?> originKeys = default) + { + _OriginKeysOption = originKeys; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UtilityResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _OriginKeysOption { get; private set; } + + /// + /// The list of origin keys for all requested domains. For each list item, the key is the domain and the value is the origin key. + /// + /// The list of origin keys for all requested domains. For each list item, the key is the domain and the value is the origin key. + [JsonPropertyName("originKeys")] + public Dictionary? OriginKeys { get { return this._OriginKeysOption; } set { this._OriginKeysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UtilityResponse {\n"); + sb.Append(" OriginKeys: ").Append(OriginKeys).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UtilityResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UtilityResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> originKeys = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "originKeys": + originKeys = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new UtilityResponse(originKeys); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UtilityResponse utilityResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, utilityResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UtilityResponse utilityResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (utilityResponse._OriginKeysOption.IsSet) + { + writer.WritePropertyName("originKeys"); + JsonSerializer.Serialize(writer, utilityResponse.OriginKeys, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Checkout/Models/ValidateShopperIdRequest.cs b/Adyen/Checkout/Models/ValidateShopperIdRequest.cs new file mode 100644 index 000000000..46d2b7a64 --- /dev/null +++ b/Adyen/Checkout/Models/ValidateShopperIdRequest.cs @@ -0,0 +1,309 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ValidateShopperIdRequest. + /// + public partial class ValidateShopperIdRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// paymentMethod + /// shopperEmail + /// shopperIP + /// shopperReference + [JsonConstructor] + public ValidateShopperIdRequest(string merchantAccount, ShopperIdPaymentMethod paymentMethod, Option shopperEmail = default, Option shopperIP = default, Option shopperReference = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ValidateShopperIdRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("paymentMethod")] + public ShopperIdPaymentMethod PaymentMethod { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ValidateShopperIdRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MerchantAccount (string) maxLength + if (this.MerchantAccount != null && this.MerchantAccount.Length > 1000) + { + yield return new ValidationResult("Invalid value for MerchantAccount, length must be less than 1000.", new [] { "MerchantAccount" }); + } + + // MerchantAccount (string) minLength + if (this.MerchantAccount != null && this.MerchantAccount.Length < 0) + { + yield return new ValidationResult("Invalid value for MerchantAccount, length must be greater than 0.", new [] { "MerchantAccount" }); + } + + // ShopperEmail (string) maxLength + if (this.ShopperEmail != null && this.ShopperEmail.Length > 300) + { + yield return new ValidationResult("Invalid value for ShopperEmail, length must be less than 300.", new [] { "ShopperEmail" }); + } + + // ShopperEmail (string) minLength + if (this.ShopperEmail != null && this.ShopperEmail.Length < 0) + { + yield return new ValidationResult("Invalid value for ShopperEmail, length must be greater than 0.", new [] { "ShopperEmail" }); + } + + // ShopperIP (string) maxLength + if (this.ShopperIP != null && this.ShopperIP.Length > 15) + { + yield return new ValidationResult("Invalid value for ShopperIP, length must be less than 15.", new [] { "ShopperIP" }); + } + + // ShopperIP (string) minLength + if (this.ShopperIP != null && this.ShopperIP.Length < 0) + { + yield return new ValidationResult("Invalid value for ShopperIP, length must be greater than 0.", new [] { "ShopperIP" }); + } + + // ShopperReference (string) maxLength + if (this.ShopperReference != null && this.ShopperReference.Length > 256) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be less than 256.", new [] { "ShopperReference" }); + } + + // ShopperReference (string) minLength + if (this.ShopperReference != null && this.ShopperReference.Length < 0) + { + yield return new ValidationResult("Invalid value for ShopperReference, length must be greater than 0.", new [] { "ShopperReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ValidateShopperIdRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ValidateShopperIdRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option paymentMethod = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class ValidateShopperIdRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class ValidateShopperIdRequest.", nameof(paymentMethod)); + + return new ValidateShopperIdRequest(merchantAccount.Value!, paymentMethod.Value!, shopperEmail, shopperIP, shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ValidateShopperIdRequest validateShopperIdRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, validateShopperIdRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ValidateShopperIdRequest validateShopperIdRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (validateShopperIdRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", validateShopperIdRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, validateShopperIdRequest.PaymentMethod, jsonSerializerOptions); + if (validateShopperIdRequest._ShopperEmailOption.IsSet) + if (validateShopperIdRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", validateShopperIdRequest.ShopperEmail); + + if (validateShopperIdRequest._ShopperIPOption.IsSet) + if (validateShopperIdRequest.ShopperIP != null) + writer.WriteString("shopperIP", validateShopperIdRequest.ShopperIP); + + if (validateShopperIdRequest._ShopperReferenceOption.IsSet) + if (validateShopperIdRequest.ShopperReference != null) + writer.WriteString("shopperReference", validateShopperIdRequest.ShopperReference); + } + } +} diff --git a/Adyen/Checkout/Models/ValidateShopperIdResponse.cs b/Adyen/Checkout/Models/ValidateShopperIdResponse.cs new file mode 100644 index 000000000..0402d92cc --- /dev/null +++ b/Adyen/Checkout/Models/ValidateShopperIdResponse.cs @@ -0,0 +1,205 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ValidateShopperIdResponse. + /// + public partial class ValidateShopperIdResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Reason for the result. + /// result + [JsonConstructor] + public ValidateShopperIdResponse(Option reason = default, Option result = default) + { + _ReasonOption = reason; + _ResultOption = result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ValidateShopperIdResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("result")] + public Result? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// Reason for the result. + /// + /// Reason for the result. + [JsonPropertyName("reason")] + public string? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ValidateShopperIdResponse {\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ValidateShopperIdResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ValidateShopperIdResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reason = default; + Option result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reason": + reason = new Option(utf8JsonReader.GetString()!); + break; + case "result": + string? resultRawValue = utf8JsonReader.GetString(); + if (resultRawValue != null) + result = new Option(ResultValueConverter.FromStringOrDefault(resultRawValue)); + break; + default: + break; + } + } + } + + + return new ValidateShopperIdResponse(reason, result); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ValidateShopperIdResponse validateShopperIdResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, validateShopperIdResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ValidateShopperIdResponse validateShopperIdResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (validateShopperIdResponse._ReasonOption.IsSet) + if (validateShopperIdResponse.Reason != null) + writer.WriteString("reason", validateShopperIdResponse.Reason); + + if (validateShopperIdResponse._ResultOption.IsSet) + { + var resultRawValue = ResultValueConverter.ToJsonValue(validateShopperIdResponse.Result!.Value); + writer.WriteString("result", resultRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/VippsDetails.cs b/Adyen/Checkout/Models/VippsDetails.cs new file mode 100644 index 000000000..3d4ca6683 --- /dev/null +++ b/Adyen/Checkout/Models/VippsDetails.cs @@ -0,0 +1,374 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// VippsDetails. + /// + public partial class VippsDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// telephoneNumber + /// The checkout attempt identifier. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **vipps** (default to TypeEnum.Vipps) + [JsonConstructor] + public VippsDetails(string telephoneNumber, Option checkoutAttemptId = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + TelephoneNumber = telephoneNumber; + _CheckoutAttemptIdOption = checkoutAttemptId; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VippsDetails() + { + } + + partial void OnCreated(); + + /// + /// **vipps** + /// + /// **vipps** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Vipps - vipps + /// + public static readonly TypeEnum Vipps = new("vipps"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "vipps" => TypeEnum.Vipps, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Vipps) + return "vipps"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **vipps** + /// + /// **vipps** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("telephoneNumber")] + public string TelephoneNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VippsDetails {\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VippsDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VippsDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option telephoneNumber = default; + Option checkoutAttemptId = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VippsDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!telephoneNumber.IsSet) + throw new ArgumentException("Property is required for class VippsDetails.", nameof(telephoneNumber)); + + return new VippsDetails(telephoneNumber.Value!, checkoutAttemptId, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VippsDetails vippsDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, vippsDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VippsDetails vippsDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (vippsDetails.TelephoneNumber != null) + writer.WriteString("telephoneNumber", vippsDetails.TelephoneNumber); + + if (vippsDetails._CheckoutAttemptIdOption.IsSet) + if (vippsDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", vippsDetails.CheckoutAttemptId); + + if (vippsDetails._RecurringDetailReferenceOption.IsSet) + if (vippsDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", vippsDetails.RecurringDetailReference); + + if (vippsDetails._StoredPaymentMethodIdOption.IsSet) + if (vippsDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", vippsDetails.StoredPaymentMethodId); + + if (vippsDetails._TypeOption.IsSet && vippsDetails.Type != null) + { + string? typeRawValue = VippsDetails.TypeEnum.ToJsonValue(vippsDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/VisaCheckoutDetails.cs b/Adyen/Checkout/Models/VisaCheckoutDetails.cs new file mode 100644 index 000000000..fdfe09781 --- /dev/null +++ b/Adyen/Checkout/Models/VisaCheckoutDetails.cs @@ -0,0 +1,449 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// VisaCheckoutDetails. + /// + public partial class VisaCheckoutDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Visa Click to Pay Call ID value. When your shopper selects a payment and/or a shipping address from Visa Click to Pay, you will receive a Visa Click to Pay Call ID. + /// The checkout attempt identifier. + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// **visacheckout** (default to TypeEnum.Visacheckout) + [JsonConstructor] + public VisaCheckoutDetails(string visaCheckoutCallId, Option checkoutAttemptId = default, Option fundingSource = default, Option type = default) + { + VisaCheckoutCallId = visaCheckoutCallId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _FundingSourceOption = fundingSource; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VisaCheckoutDetails() + { + } + + partial void OnCreated(); + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// **visacheckout** + /// + /// **visacheckout** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Visacheckout - visacheckout + /// + public static readonly TypeEnum Visacheckout = new("visacheckout"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "visacheckout" => TypeEnum.Visacheckout, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Visacheckout) + return "visacheckout"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **visacheckout** + /// + /// **visacheckout** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The Visa Click to Pay Call ID value. When your shopper selects a payment and/or a shipping address from Visa Click to Pay, you will receive a Visa Click to Pay Call ID. + /// + /// The Visa Click to Pay Call ID value. When your shopper selects a payment and/or a shipping address from Visa Click to Pay, you will receive a Visa Click to Pay Call ID. + [JsonPropertyName("visaCheckoutCallId")] + public string VisaCheckoutCallId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VisaCheckoutDetails {\n"); + sb.Append(" VisaCheckoutCallId: ").Append(VisaCheckoutCallId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VisaCheckoutDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VisaCheckoutDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option visaCheckoutCallId = default; + Option checkoutAttemptId = default; + Option fundingSource = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "visaCheckoutCallId": + visaCheckoutCallId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(VisaCheckoutDetails.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VisaCheckoutDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!visaCheckoutCallId.IsSet) + throw new ArgumentException("Property is required for class VisaCheckoutDetails.", nameof(visaCheckoutCallId)); + + return new VisaCheckoutDetails(visaCheckoutCallId.Value!, checkoutAttemptId, fundingSource, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VisaCheckoutDetails visaCheckoutDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, visaCheckoutDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VisaCheckoutDetails visaCheckoutDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (visaCheckoutDetails.VisaCheckoutCallId != null) + writer.WriteString("visaCheckoutCallId", visaCheckoutDetails.VisaCheckoutCallId); + + if (visaCheckoutDetails._CheckoutAttemptIdOption.IsSet) + if (visaCheckoutDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", visaCheckoutDetails.CheckoutAttemptId); + + if (visaCheckoutDetails._FundingSourceOption.IsSet && visaCheckoutDetails.FundingSource != null) + { + string? fundingSourceRawValue = VisaCheckoutDetails.FundingSourceEnum.ToJsonValue(visaCheckoutDetails._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (visaCheckoutDetails._TypeOption.IsSet && visaCheckoutDetails.Type != null) + { + string? typeRawValue = VisaCheckoutDetails.TypeEnum.ToJsonValue(visaCheckoutDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/WeChatPayDetails.cs b/Adyen/Checkout/Models/WeChatPayDetails.cs new file mode 100644 index 000000000..658569609 --- /dev/null +++ b/Adyen/Checkout/Models/WeChatPayDetails.cs @@ -0,0 +1,308 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// WeChatPayDetails. + /// + public partial class WeChatPayDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// **wechatpay** (default to TypeEnum.Wechatpay) + [JsonConstructor] + public WeChatPayDetails(Option checkoutAttemptId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WeChatPayDetails() + { + } + + partial void OnCreated(); + + /// + /// **wechatpay** + /// + /// **wechatpay** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Wechatpay - wechatpay + /// + public static readonly TypeEnum Wechatpay = new("wechatpay"); + + /// + /// TypeEnum.WechatpayPos - wechatpay_pos + /// + public static readonly TypeEnum WechatpayPos = new("wechatpay_pos"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "wechatpay" => TypeEnum.Wechatpay, + "wechatpay_pos" => TypeEnum.WechatpayPos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Wechatpay) + return "wechatpay"; + + if (value == TypeEnum.WechatpayPos) + return "wechatpay_pos"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **wechatpay** + /// + /// **wechatpay** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WeChatPayDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WeChatPayDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WeChatPayDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(WeChatPayDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new WeChatPayDetails(checkoutAttemptId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WeChatPayDetails weChatPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, weChatPayDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WeChatPayDetails weChatPayDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (weChatPayDetails._CheckoutAttemptIdOption.IsSet) + if (weChatPayDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", weChatPayDetails.CheckoutAttemptId); + + if (weChatPayDetails._TypeOption.IsSet && weChatPayDetails.Type != null) + { + string? typeRawValue = WeChatPayDetails.TypeEnum.ToJsonValue(weChatPayDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/WeChatPayMiniProgramDetails.cs b/Adyen/Checkout/Models/WeChatPayMiniProgramDetails.cs new file mode 100644 index 000000000..4f6f2649c --- /dev/null +++ b/Adyen/Checkout/Models/WeChatPayMiniProgramDetails.cs @@ -0,0 +1,404 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// WeChatPayMiniProgramDetails. + /// + public partial class WeChatPayMiniProgramDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// appId + /// The checkout attempt identifier. + /// openid + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **wechatpayMiniProgram** (default to TypeEnum.WechatpayMiniProgram) + [JsonConstructor] + public WeChatPayMiniProgramDetails(Option appId = default, Option checkoutAttemptId = default, Option openid = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _AppIdOption = appId; + _CheckoutAttemptIdOption = checkoutAttemptId; + _OpenidOption = openid; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WeChatPayMiniProgramDetails() + { + } + + partial void OnCreated(); + + /// + /// **wechatpayMiniProgram** + /// + /// **wechatpayMiniProgram** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.WechatpayMiniProgram - wechatpayMiniProgram + /// + public static readonly TypeEnum WechatpayMiniProgram = new("wechatpayMiniProgram"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "wechatpayMiniProgram" => TypeEnum.WechatpayMiniProgram, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.WechatpayMiniProgram) + return "wechatpayMiniProgram"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **wechatpayMiniProgram** + /// + /// **wechatpayMiniProgram** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AppIdOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("appId")] + public string? AppId { get { return this._AppIdOption; } set { this._AppIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpenidOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("openid")] + public string? Openid { get { return this._OpenidOption; } set { this._OpenidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WeChatPayMiniProgramDetails {\n"); + sb.Append(" AppId: ").Append(AppId).Append("\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" Openid: ").Append(Openid).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WeChatPayMiniProgramDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WeChatPayMiniProgramDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option appId = default; + Option checkoutAttemptId = default; + Option openid = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "appId": + appId = new Option(utf8JsonReader.GetString()!); + break; + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "openid": + openid = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(WeChatPayMiniProgramDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new WeChatPayMiniProgramDetails(appId, checkoutAttemptId, openid, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WeChatPayMiniProgramDetails weChatPayMiniProgramDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, weChatPayMiniProgramDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WeChatPayMiniProgramDetails weChatPayMiniProgramDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (weChatPayMiniProgramDetails._AppIdOption.IsSet) + if (weChatPayMiniProgramDetails.AppId != null) + writer.WriteString("appId", weChatPayMiniProgramDetails.AppId); + + if (weChatPayMiniProgramDetails._CheckoutAttemptIdOption.IsSet) + if (weChatPayMiniProgramDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", weChatPayMiniProgramDetails.CheckoutAttemptId); + + if (weChatPayMiniProgramDetails._OpenidOption.IsSet) + if (weChatPayMiniProgramDetails.Openid != null) + writer.WriteString("openid", weChatPayMiniProgramDetails.Openid); + + if (weChatPayMiniProgramDetails._RecurringDetailReferenceOption.IsSet) + if (weChatPayMiniProgramDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", weChatPayMiniProgramDetails.RecurringDetailReference); + + if (weChatPayMiniProgramDetails._StoredPaymentMethodIdOption.IsSet) + if (weChatPayMiniProgramDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", weChatPayMiniProgramDetails.StoredPaymentMethodId); + + if (weChatPayMiniProgramDetails._TypeOption.IsSet && weChatPayMiniProgramDetails.Type != null) + { + string? typeRawValue = WeChatPayMiniProgramDetails.TypeEnum.ToJsonValue(weChatPayMiniProgramDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Models/ZipDetails.cs b/Adyen/Checkout/Models/ZipDetails.cs new file mode 100644 index 000000000..52f8a672f --- /dev/null +++ b/Adyen/Checkout/Models/ZipDetails.cs @@ -0,0 +1,390 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Checkout.Client; + +namespace Adyen.Checkout.Models +{ + /// + /// ZipDetails. + /// + public partial class ZipDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The checkout attempt identifier. + /// Set this to **true** if the shopper would like to pick up and collect their order, instead of having the goods delivered to them. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// **zip** (default to TypeEnum.Zip) + [JsonConstructor] + public ZipDetails(Option checkoutAttemptId = default, Option clickAndCollect = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default, Option type = default) + { + _CheckoutAttemptIdOption = checkoutAttemptId; + _ClickAndCollectOption = clickAndCollect; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ZipDetails() + { + } + + partial void OnCreated(); + + /// + /// **zip** + /// + /// **zip** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Zip - zip + /// + public static readonly TypeEnum Zip = new("zip"); + + /// + /// TypeEnum.ZipPos - zip_pos + /// + public static readonly TypeEnum ZipPos = new("zip_pos"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "zip" => TypeEnum.Zip, + "zip_pos" => TypeEnum.ZipPos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Zip) + return "zip"; + + if (value == TypeEnum.ZipPos) + return "zip_pos"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **zip** + /// + /// **zip** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutAttemptIdOption { get; private set; } + + /// + /// The checkout attempt identifier. + /// + /// The checkout attempt identifier. + [JsonPropertyName("checkoutAttemptId")] + public string? CheckoutAttemptId { get { return this._CheckoutAttemptIdOption; } set { this._CheckoutAttemptIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClickAndCollectOption { get; private set; } + + /// + /// Set this to **true** if the shopper would like to pick up and collect their order, instead of having the goods delivered to them. + /// + /// Set this to **true** if the shopper would like to pick up and collect their order, instead of having the goods delivered to them. + [JsonPropertyName("clickAndCollect")] + public string? ClickAndCollect { get { return this._ClickAndCollectOption; } set { this._ClickAndCollectOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + [Obsolete("Deprecated since Adyen Checkout API v49. Use `storedPaymentMethodId` instead.")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ZipDetails {\n"); + sb.Append(" CheckoutAttemptId: ").Append(CheckoutAttemptId).Append("\n"); + sb.Append(" ClickAndCollect: ").Append(ClickAndCollect).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // StoredPaymentMethodId (string) maxLength + if (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Length > 64) + { + yield return new ValidationResult("Invalid value for StoredPaymentMethodId, length must be less than 64.", new [] { "StoredPaymentMethodId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ZipDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ZipDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutAttemptId = default; + Option clickAndCollect = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutAttemptId": + checkoutAttemptId = new Option(utf8JsonReader.GetString()!); + break; + case "clickAndCollect": + clickAndCollect = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ZipDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new ZipDetails(checkoutAttemptId, clickAndCollect, recurringDetailReference, storedPaymentMethodId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ZipDetails zipDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, zipDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ZipDetails zipDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (zipDetails._CheckoutAttemptIdOption.IsSet) + if (zipDetails.CheckoutAttemptId != null) + writer.WriteString("checkoutAttemptId", zipDetails.CheckoutAttemptId); + + if (zipDetails._ClickAndCollectOption.IsSet) + if (zipDetails.ClickAndCollect != null) + writer.WriteString("clickAndCollect", zipDetails.ClickAndCollect); + + if (zipDetails._RecurringDetailReferenceOption.IsSet) + if (zipDetails.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", zipDetails.RecurringDetailReference); + + if (zipDetails._StoredPaymentMethodIdOption.IsSet) + if (zipDetails.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", zipDetails.StoredPaymentMethodId); + + if (zipDetails._TypeOption.IsSet && zipDetails.Type != null) + { + string? typeRawValue = ZipDetails.TypeEnum.ToJsonValue(zipDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Checkout/Services/DonationsService.cs b/Adyen/Checkout/Services/DonationsService.cs new file mode 100644 index 000000000..421f16bd1 --- /dev/null +++ b/Adyen/Checkout/Services/DonationsService.cs @@ -0,0 +1,989 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IDonationsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + DonationsServiceEvents Events { get; } + + /// + /// Get a list of donation campaigns. + /// + /// + /// Queries the available donation campaigns for a donation based on the donation context (like merchant account, currency, and locale). The response contains active donation campaigns. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task DonationCampaignsAsync(DonationCampaignsRequest donationCampaignsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Make a donation + /// + /// + /// Takes in the donation token generated by the `/payments` request and uses it to make the donation. For more information, see [Donations](https://docs.adyen.com/online-payments/donations). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task DonationsAsync(DonationPaymentRequest donationPaymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IDonationCampaignsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDonationsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class DonationsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDonationCampaigns; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDonationCampaigns; + + internal void ExecuteOnDonationCampaigns(DonationsService.DonationCampaignsApiResponse apiResponse) + { + OnDonationCampaigns?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDonationCampaigns(Exception exception) + { + OnErrorDonationCampaigns?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDonations; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDonations; + + internal void ExecuteOnDonations(DonationsService.DonationsApiResponse apiResponse) + { + OnDonations?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDonations(Exception exception) + { + OnErrorDonations?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class DonationsService : IDonationsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public DonationsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public DonationsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DonationsServiceEvents donationsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = donationsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a list of donation campaigns. Queries the available donation campaigns for a donation based on the donation context (like merchant account, currency, and locale). The response contains active donation campaigns. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DonationCampaignsAsync(DonationCampaignsRequest donationCampaignsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/donationCampaigns" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/donationCampaigns"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (donationCampaignsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(donationCampaignsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DonationCampaignsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/donationCampaigns", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDonationCampaigns(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDonationCampaigns(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DonationCampaignsApiResponse : Adyen.Core.Client.ApiResponse, IDonationCampaignsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonationCampaignsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonationCampaignsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.DonationCampaignsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DonationCampaignsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Make a donation Takes in the donation token generated by the `/payments` request and uses it to make the donation. For more information, see [Donations](https://docs.adyen.com/online-payments/donations). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DonationsAsync(DonationPaymentRequest donationPaymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/donations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/donations"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (donationPaymentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(donationPaymentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DonationsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/donations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDonations(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDonations(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DonationsApiResponse : Adyen.Core.Client.ApiResponse, IDonationsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.DonationPaymentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DonationPaymentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/ModificationsService.cs b/Adyen/Checkout/Services/ModificationsService.cs new file mode 100644 index 000000000..3437b2b6d --- /dev/null +++ b/Adyen/Checkout/Services/ModificationsService.cs @@ -0,0 +1,2788 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IModificationsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ModificationsServiceEvents Events { get; } + + /// + /// Cancel an authorised payment + /// + /// + /// Cancels the authorisation on a payment that has not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**TECHNICAL_CANCEL** webhook](https://docs.adyen.com/online-payments/cancel#cancellation-webhook). If you want to cancel a payment using the [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference), use the [`/payments/{paymentPspReference}/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/cancels) endpoint instead. If you want to cancel a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/cancel). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CancelAuthorisedPaymentAsync(StandalonePaymentCancelRequest standalonePaymentCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel an authorised payment + /// + /// + /// Cancels the authorisation on a payment that has not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CANCELLATION** webhook](https://docs.adyen.com/online-payments/cancel#cancellation-webhook). If you want to cancel a payment but don't have the [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference), use the [`/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/cancels) endpoint instead. If you want to cancel a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/cancel). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to cancel. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CancelAuthorisedPaymentByPspReferenceAsync(string paymentPspReference, PaymentCancelRequest paymentCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Capture an authorised payment + /// + /// + /// Captures an authorised payment and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CAPTURE** webhook](https://docs.adyen.com/online-payments/capture#capture-notification). You can capture either the full authorised amount or a part of the authorised amount. By default, any unclaimed amount after a partial capture gets cancelled. This does not apply if you enabled multiple partial captures on your account and the payment method supports multiple partial captures. [Automatic capture](https://docs.adyen.com/online-payments/capture#automatic-capture) is the default setting for most payment methods. In these cases, you don't need to make capture requests. However, making capture requests for payments that are captured automatically does not result in double charges. For more information, refer to [Capture](https://docs.adyen.com/online-payments/capture). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to capture. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CaptureAuthorisedPaymentAsync(string paymentPspReference, PaymentCaptureRequest paymentCaptureRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Refund a captured payment + /// + /// + /// Refunds a payment that has been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**REFUND** webhook](https://docs.adyen.com/online-payments/refund#refund-webhook). You can refund either the full captured amount or a part of the captured amount. You can also perform multiple partial refunds, as long as their sum doesn't exceed the captured amount. > Some payment methods do not support partial refunds. To learn if a payment method supports partial refunds, refer to the payment method page such as [cards](https://docs.adyen.com/payment-methods/cards#supported-cards), [iDEAL](https://docs.adyen.com/payment-methods/ideal), or [Klarna](https://docs.adyen.com/payment-methods/klarna). If you want to refund a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Refund](https://docs.adyen.com/online-payments/refund). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to refund. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task RefundCapturedPaymentAsync(string paymentPspReference, PaymentRefundRequest paymentRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Refund or cancel a payment + /// + /// + /// [Refunds](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/refunds) a payment if it has already been captured, and [cancels](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/cancels) a payment if it has not yet been captured. Returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CANCEL_OR_REFUND** webhook](https://docs.adyen.com/online-payments/reversal/#cancel-or-refund-webhook). The reversed amount is always the full payment amount. > Do not use this request for payments that involve multiple partial captures. For more information, refer to [Reversal](https://docs.adyen.com/online-payments/reversal). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to reverse. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task RefundOrCancelPaymentAsync(string paymentPspReference, PaymentReversalRequest paymentReversalRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an authorised amount + /// + /// + /// Increases or decreases the authorised payment amount and returns a unique reference for this request. You get the outcome of the request asynchronously, in an [**AUTHORISATION_ADJUSTMENT** webhook](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes). You can only update authorised amounts that have not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures). The amount you specify in the request is the updated amount, which is larger or smaller than the initial authorised amount. For more information, refer to [Authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#use-cases). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UpdateAuthorisedAmountAsync(string paymentPspReference, PaymentAmountUpdateRequest paymentAmountUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICancelAuthorisedPaymentApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICancelAuthorisedPaymentByPspReferenceApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICaptureAuthorisedPaymentApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRefundCapturedPaymentApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRefundOrCancelPaymentApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateAuthorisedAmountApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ModificationsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelAuthorisedPayment; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelAuthorisedPayment; + + internal void ExecuteOnCancelAuthorisedPayment(ModificationsService.CancelAuthorisedPaymentApiResponse apiResponse) + { + OnCancelAuthorisedPayment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelAuthorisedPayment(Exception exception) + { + OnErrorCancelAuthorisedPayment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelAuthorisedPaymentByPspReference; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelAuthorisedPaymentByPspReference; + + internal void ExecuteOnCancelAuthorisedPaymentByPspReference(ModificationsService.CancelAuthorisedPaymentByPspReferenceApiResponse apiResponse) + { + OnCancelAuthorisedPaymentByPspReference?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelAuthorisedPaymentByPspReference(Exception exception) + { + OnErrorCancelAuthorisedPaymentByPspReference?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCaptureAuthorisedPayment; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCaptureAuthorisedPayment; + + internal void ExecuteOnCaptureAuthorisedPayment(ModificationsService.CaptureAuthorisedPaymentApiResponse apiResponse) + { + OnCaptureAuthorisedPayment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCaptureAuthorisedPayment(Exception exception) + { + OnErrorCaptureAuthorisedPayment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRefundCapturedPayment; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRefundCapturedPayment; + + internal void ExecuteOnRefundCapturedPayment(ModificationsService.RefundCapturedPaymentApiResponse apiResponse) + { + OnRefundCapturedPayment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRefundCapturedPayment(Exception exception) + { + OnErrorRefundCapturedPayment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRefundOrCancelPayment; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRefundOrCancelPayment; + + internal void ExecuteOnRefundOrCancelPayment(ModificationsService.RefundOrCancelPaymentApiResponse apiResponse) + { + OnRefundOrCancelPayment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRefundOrCancelPayment(Exception exception) + { + OnErrorRefundOrCancelPayment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateAuthorisedAmount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateAuthorisedAmount; + + internal void ExecuteOnUpdateAuthorisedAmount(ModificationsService.UpdateAuthorisedAmountApiResponse apiResponse) + { + OnUpdateAuthorisedAmount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateAuthorisedAmount(Exception exception) + { + OnErrorUpdateAuthorisedAmount?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ModificationsService : IModificationsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ModificationsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ModificationsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ModificationsServiceEvents modificationsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = modificationsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Cancel an authorised payment Cancels the authorisation on a payment that has not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**TECHNICAL_CANCEL** webhook](https://docs.adyen.com/online-payments/cancel#cancellation-webhook). If you want to cancel a payment using the [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference), use the [`/payments/{paymentPspReference}/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/cancels) endpoint instead. If you want to cancel a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/cancel). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelAuthorisedPaymentAsync(StandalonePaymentCancelRequest standalonePaymentCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cancels" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cancels"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (standalonePaymentCancelRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(standalonePaymentCancelRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelAuthorisedPaymentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cancels", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelAuthorisedPayment(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelAuthorisedPayment(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelAuthorisedPaymentApiResponse : Adyen.Core.Client.ApiResponse, ICancelAuthorisedPaymentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelAuthorisedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelAuthorisedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.StandalonePaymentCancelResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.StandalonePaymentCancelResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel an authorised payment Cancels the authorisation on a payment that has not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CANCELLATION** webhook](https://docs.adyen.com/online-payments/cancel#cancellation-webhook). If you want to cancel a payment but don't have the [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference), use the [`/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/cancels) endpoint instead. If you want to cancel a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/cancel). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to cancel. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelAuthorisedPaymentByPspReferenceAsync(string paymentPspReference, PaymentCancelRequest paymentCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/{paymentPspReference}/cancels" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/{paymentPspReference}/cancels"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentPspReference%7D", Uri.EscapeDataString(paymentPspReference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentCancelRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentCancelRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelAuthorisedPaymentByPspReferenceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/{paymentPspReference}/cancels", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelAuthorisedPaymentByPspReference(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelAuthorisedPaymentByPspReference(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelAuthorisedPaymentByPspReferenceApiResponse : Adyen.Core.Client.ApiResponse, ICancelAuthorisedPaymentByPspReferenceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelAuthorisedPaymentByPspReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelAuthorisedPaymentByPspReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentCancelResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentCancelResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Capture an authorised payment Captures an authorised payment and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CAPTURE** webhook](https://docs.adyen.com/online-payments/capture#capture-notification). You can capture either the full authorised amount or a part of the authorised amount. By default, any unclaimed amount after a partial capture gets cancelled. This does not apply if you enabled multiple partial captures on your account and the payment method supports multiple partial captures. [Automatic capture](https://docs.adyen.com/online-payments/capture#automatic-capture) is the default setting for most payment methods. In these cases, you don't need to make capture requests. However, making capture requests for payments that are captured automatically does not result in double charges. For more information, refer to [Capture](https://docs.adyen.com/online-payments/capture). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to capture. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CaptureAuthorisedPaymentAsync(string paymentPspReference, PaymentCaptureRequest paymentCaptureRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/{paymentPspReference}/captures" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/{paymentPspReference}/captures"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentPspReference%7D", Uri.EscapeDataString(paymentPspReference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentCaptureRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentCaptureRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CaptureAuthorisedPaymentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/{paymentPspReference}/captures", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCaptureAuthorisedPayment(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCaptureAuthorisedPayment(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CaptureAuthorisedPaymentApiResponse : Adyen.Core.Client.ApiResponse, ICaptureAuthorisedPaymentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CaptureAuthorisedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CaptureAuthorisedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentCaptureResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentCaptureResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Refund a captured payment Refunds a payment that has been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures), and returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**REFUND** webhook](https://docs.adyen.com/online-payments/refund#refund-webhook). You can refund either the full captured amount or a part of the captured amount. You can also perform multiple partial refunds, as long as their sum doesn't exceed the captured amount. > Some payment methods do not support partial refunds. To learn if a payment method supports partial refunds, refer to the payment method page such as [cards](https://docs.adyen.com/payment-methods/cards#supported-cards), [iDEAL](https://docs.adyen.com/payment-methods/ideal), or [Klarna](https://docs.adyen.com/payment-methods/klarna). If you want to refund a payment but are not sure whether it has been captured, use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/reversals) endpoint instead. For more information, refer to [Refund](https://docs.adyen.com/online-payments/refund). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to refund. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RefundCapturedPaymentAsync(string paymentPspReference, PaymentRefundRequest paymentRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/{paymentPspReference}/refunds" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/{paymentPspReference}/refunds"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentPspReference%7D", Uri.EscapeDataString(paymentPspReference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentRefundRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentRefundRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RefundCapturedPaymentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/{paymentPspReference}/refunds", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRefundCapturedPayment(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRefundCapturedPayment(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RefundCapturedPaymentApiResponse : Adyen.Core.Client.ApiResponse, IRefundCapturedPaymentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundCapturedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundCapturedPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentRefundResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentRefundResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Refund or cancel a payment [Refunds](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/refunds) a payment if it has already been captured, and [cancels](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/cancels) a payment if it has not yet been captured. Returns a unique reference for this request. You get the outcome of the request asynchronously, in a [**CANCEL_OR_REFUND** webhook](https://docs.adyen.com/online-payments/reversal/#cancel-or-refund-webhook). The reversed amount is always the full payment amount. > Do not use this request for payments that involve multiple partial captures. For more information, refer to [Reversal](https://docs.adyen.com/online-payments/reversal). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to reverse. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RefundOrCancelPaymentAsync(string paymentPspReference, PaymentReversalRequest paymentReversalRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/{paymentPspReference}/reversals" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/{paymentPspReference}/reversals"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentPspReference%7D", Uri.EscapeDataString(paymentPspReference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentReversalRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentReversalRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RefundOrCancelPaymentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/{paymentPspReference}/reversals", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRefundOrCancelPayment(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRefundOrCancelPayment(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RefundOrCancelPaymentApiResponse : Adyen.Core.Client.ApiResponse, IRefundOrCancelPaymentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundOrCancelPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundOrCancelPaymentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentReversalResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentReversalResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update an authorised amount Increases or decreases the authorised payment amount and returns a unique reference for this request. You get the outcome of the request asynchronously, in an [**AUTHORISATION_ADJUSTMENT** webhook](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes). You can only update authorised amounts that have not yet been [captured](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments/{paymentPspReference}/captures). The amount you specify in the request is the updated amount, which is larger or smaller than the initial authorised amount. For more information, refer to [Authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#use-cases). + /// + /// Thrown when fails to make API call. + /// The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateAuthorisedAmountAsync(string paymentPspReference, PaymentAmountUpdateRequest paymentAmountUpdateRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/{paymentPspReference}/amountUpdates" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/{paymentPspReference}/amountUpdates"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentPspReference%7D", Uri.EscapeDataString(paymentPspReference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentAmountUpdateRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentAmountUpdateRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateAuthorisedAmountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/{paymentPspReference}/amountUpdates", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateAuthorisedAmount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateAuthorisedAmount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateAuthorisedAmountApiResponse : Adyen.Core.Client.ApiResponse, IUpdateAuthorisedAmountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAuthorisedAmountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateAuthorisedAmountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentAmountUpdateResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentAmountUpdateResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/OrdersService.cs b/Adyen/Checkout/Services/OrdersService.cs new file mode 100644 index 000000000..285fd317a --- /dev/null +++ b/Adyen/Checkout/Services/OrdersService.cs @@ -0,0 +1,1435 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IOrdersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + OrdersServiceEvents Events { get; } + + /// + /// Cancel an order + /// + /// + /// Cancels an order. Cancellation of an order results in an automatic rollback of all payments made in the order, either by canceling or refunding the payment, depending on the type of payment method. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CancelOrderAsync(CancelOrderRequest cancelOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the balance of a gift card + /// + /// + /// Retrieves the balance remaining on a shopper's gift card. To check a gift card's balance, make a POST `/paymentMethods/balance` call and include the gift card's details inside a `paymentMethod` object. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task GetBalanceOfGiftCardAsync(BalanceCheckRequest balanceCheckRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create an order + /// + /// + /// Creates an order to be used for partial payments. Make a POST `/orders` call before making a `/payments` call when processing payments with different payment methods. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task OrdersAsync(CreateOrderRequest createOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICancelOrderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetBalanceOfGiftCardApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IOrdersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class OrdersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelOrder; + + internal void ExecuteOnCancelOrder(OrdersService.CancelOrderApiResponse apiResponse) + { + OnCancelOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelOrder(Exception exception) + { + OnErrorCancelOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetBalanceOfGiftCard; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetBalanceOfGiftCard; + + internal void ExecuteOnGetBalanceOfGiftCard(OrdersService.GetBalanceOfGiftCardApiResponse apiResponse) + { + OnGetBalanceOfGiftCard?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetBalanceOfGiftCard(Exception exception) + { + OnErrorGetBalanceOfGiftCard?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnOrders; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorOrders; + + internal void ExecuteOnOrders(OrdersService.OrdersApiResponse apiResponse) + { + OnOrders?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorOrders(Exception exception) + { + OnErrorOrders?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class OrdersService : IOrdersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public OrdersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public OrdersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, OrdersServiceEvents ordersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = ordersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Cancel an order Cancels an order. Cancellation of an order results in an automatic rollback of all payments made in the order, either by canceling or refunding the payment, depending on the type of payment method. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelOrderAsync(CancelOrderRequest cancelOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/orders/cancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/orders/cancel"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (cancelOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(cancelOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/orders/cancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelOrder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelOrderApiResponse : Adyen.Core.Client.ApiResponse, ICancelOrderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.CancelOrderResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.CancelOrderResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the balance of a gift card Retrieves the balance remaining on a shopper's gift card. To check a gift card's balance, make a POST `/paymentMethods/balance` call and include the gift card's details inside a `paymentMethod` object. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetBalanceOfGiftCardAsync(BalanceCheckRequest balanceCheckRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentMethods/balance" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentMethods/balance"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (balanceCheckRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(balanceCheckRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetBalanceOfGiftCardApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentMethods/balance", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetBalanceOfGiftCard(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetBalanceOfGiftCard(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetBalanceOfGiftCardApiResponse : Adyen.Core.Client.ApiResponse, IGetBalanceOfGiftCardApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalanceOfGiftCardApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBalanceOfGiftCardApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.BalanceCheckResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.BalanceCheckResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create an order Creates an order to be used for partial payments. Make a POST `/orders` call before making a `/payments` call when processing payments with different payment methods. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task OrdersAsync(CreateOrderRequest createOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/orders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/orders"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + OrdersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/orders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnOrders(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorOrders(exception); + throw; + } + } + + /// + /// The . + /// + public partial class OrdersApiResponse : Adyen.Core.Client.ApiResponse, IOrdersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public OrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public OrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.CreateOrderResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.CreateOrderResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/PaymentLinksService.cs b/Adyen/Checkout/Services/PaymentLinksService.cs new file mode 100644 index 000000000..740b3c386 --- /dev/null +++ b/Adyen/Checkout/Services/PaymentLinksService.cs @@ -0,0 +1,1419 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentLinksService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentLinksServiceEvents Events { get; } + + /// + /// Get a payment link + /// + /// + /// Retrieves the payment link details using the payment link `id`. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the payment link. + /// . + /// . + /// of . + Task GetPaymentLinkAsync(string linkId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a payment link + /// + /// + /// Creates a payment link to a [Pay by Link](https://docs.adyen.com/unified-commerce/pay-by-link/) page where the shopper can pay. The list of payment methods presented to the shopper depends on the `currency` and `country` parameters sent in the request. For more information, refer to [Pay by Link documentation](https://docs.adyen.com/online-payments/pay-by-link#create-payment-links-through-api). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task PaymentLinksAsync(PaymentLinkRequest paymentLinkRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the status of a payment link + /// + /// + /// Updates the status of a payment link. Use this endpoint to [force the expiry of a payment link](https://docs.adyen.com/online-payments/pay-by-link#update-payment-link-status). + /// + /// Thrown when fails to make API call. + /// Unique identifier of the payment link. + /// + /// . + /// . + /// of . + Task UpdatePaymentLinkAsync(string linkId, UpdatePaymentLinkRequest updatePaymentLinkRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetPaymentLinkApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IPaymentLinksApiResponse : Adyen.Core.Client.IApiResponse, ICreated, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdatePaymentLinkApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentLinksServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPaymentLink; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPaymentLink; + + internal void ExecuteOnGetPaymentLink(PaymentLinksService.GetPaymentLinkApiResponse apiResponse) + { + OnGetPaymentLink?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPaymentLink(Exception exception) + { + OnErrorGetPaymentLink?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPaymentLinks; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPaymentLinks; + + internal void ExecuteOnPaymentLinks(PaymentLinksService.PaymentLinksApiResponse apiResponse) + { + OnPaymentLinks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPaymentLinks(Exception exception) + { + OnErrorPaymentLinks?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdatePaymentLink; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdatePaymentLink; + + internal void ExecuteOnUpdatePaymentLink(PaymentLinksService.UpdatePaymentLinkApiResponse apiResponse) + { + OnUpdatePaymentLink?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePaymentLink(Exception exception) + { + OnErrorUpdatePaymentLink?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentLinksService : IPaymentLinksService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentLinksServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentLinksService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentLinksServiceEvents paymentLinksServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentLinksServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a payment link Retrieves the payment link details using the payment link `id`. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the payment link. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPaymentLinkAsync(string linkId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentLinks/{linkId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentLinks/{linkId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BlinkId%7D", Uri.EscapeDataString(linkId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPaymentLinkApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentLinks/{linkId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPaymentLink(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPaymentLink(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPaymentLinkApiResponse : Adyen.Core.Client.ApiResponse, IGetPaymentLinkApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentLinkApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentLinkApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaymentLinkResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentLinkResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a payment link Creates a payment link to a [Pay by Link](https://docs.adyen.com/unified-commerce/pay-by-link/) page where the shopper can pay. The list of payment methods presented to the shopper depends on the `currency` and `country` parameters sent in the request. For more information, refer to [Pay by Link documentation](https://docs.adyen.com/online-payments/pay-by-link#create-payment-links-through-api). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PaymentLinksAsync(PaymentLinkRequest paymentLinkRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentLinks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentLinks"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentLinkRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentLinkRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PaymentLinksApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentLinks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPaymentLinks(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPaymentLinks(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PaymentLinksApiResponse : Adyen.Core.Client.ApiResponse, IPaymentLinksApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentLinksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentLinksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.PaymentLinkResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentLinkResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the status of a payment link Updates the status of a payment link. Use this endpoint to [force the expiry of a payment link](https://docs.adyen.com/online-payments/pay-by-link#update-payment-link-status). + /// + /// Thrown when fails to make API call. + /// Unique identifier of the payment link. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdatePaymentLinkAsync(string linkId, UpdatePaymentLinkRequest updatePaymentLinkRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentLinks/{linkId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentLinks/{linkId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BlinkId%7D", Uri.EscapeDataString(linkId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updatePaymentLinkRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updatePaymentLinkRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdatePaymentLinkApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentLinks/{linkId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdatePaymentLink(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdatePaymentLink(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdatePaymentLinkApiResponse : Adyen.Core.Client.ApiResponse, IUpdatePaymentLinkApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentLinkApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentLinkApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaymentLinkResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentLinkResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/PaymentsService.cs b/Adyen/Checkout/Services/PaymentsService.cs new file mode 100644 index 000000000..4cd07c2b6 --- /dev/null +++ b/Adyen/Checkout/Services/PaymentsService.cs @@ -0,0 +1,2104 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentsServiceEvents Events { get; } + + /// + /// Get the brands and other details of a card + /// + /// + /// Use this endpoint to get information about the card or network token that enables you to decide on the routing of the transaction and the eligibility of the card for the type of transaction. If you include [your supported brands](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/cardDetails__reqParam_supportedBrands) in the request, the response also tells you if you support each [brand that was identified on the card](https://docs.adyen.com/api-explorer/Checkout/latest/post/cardDetails#responses-200-brands). If you have an API-only integration and collect card data, use this endpoint to find out if the shopper's card is co-bad. For co-badged cards, you must let the shopper choose the brand to pay with if you support both brands. ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources BIN Lookup API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments**&nbsp;>&nbsp;**Adyen&nbsp;APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-677c7679-a695-4ebb-91da-68b4e7c9228a?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-677c7679-a695-4ebb-91da-68b4e7c9228a%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CardDetailsAsync(CardDetailsRequest cardDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the result of a payment session + /// + /// + /// Returns the status of the payment session with the `sessionId` and `sessionResult` specified in the path. + /// + /// Thrown when fails to make API call. + /// A unique identifier of the session. + /// The `sessionResult` value from the Drop-in or Component. + /// . + /// . + /// of . + Task GetResultOfPaymentSessionAsync(string sessionId, string sessionResult, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of available payment methods + /// + /// + /// Retrieves the list of available payment methods for the transaction, based on the transaction information like amount, country, and currency. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task PaymentMethodsAsync(PaymentMethodsRequest paymentMethodsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Start a transaction + /// + /// + /// Sends payment parameters (like amount, country, and currency) together with other required input details collected from the shopper. To know more about required parameters for specific payment methods, refer to our [payment method guides](https://docs.adyen.com/payment-methods). The response depends on the [payment flow](https://docs.adyen.com/payment-methods#payment-flow): * For a direct flow, the response includes a `pspReference` and a `resultCode` with the payment result, for example **Authorised** or **Refused**. * For a redirect or additional action, the response contains an `action` object. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task PaymentsAsync(PaymentRequest paymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Submit details for a payment + /// + /// + /// Submits details for a payment created using `/payments`. This step is only needed when no final state has been reached on the `/payments` request, for example when the shopper was redirected to another page to complete the payment. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task PaymentsDetailsAsync(PaymentDetailsRequest paymentDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a payment session + /// + /// + /// Creates a payment session for [Drop-in](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Drop-in), [Components](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Components), and [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Hosted+Checkout) integrations. The response contains encrypted payment session data. The front end then uses the session data to make any required server-side calls for the payment flow. You get the payment outcome asynchronously, in an [AUTHORISATION](https://docs.adyen.com/api-explorer/#/Webhooks/latest/post/AUTHORISATION) webhook. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task SessionsAsync(CreateCheckoutSessionRequest createCheckoutSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICardDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + } + + /// + /// The , wraps . + /// + public interface IGetResultOfPaymentSessionApiResponse : Adyen.Core.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + } + + /// + /// The , wraps . + /// + public interface IPaymentMethodsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IPaymentsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IPaymentsDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISessionsApiResponse : Adyen.Core.Client.IApiResponse, ICreated + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCardDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCardDetails; + + internal void ExecuteOnCardDetails(PaymentsService.CardDetailsApiResponse apiResponse) + { + OnCardDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCardDetails(Exception exception) + { + OnErrorCardDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetResultOfPaymentSession; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetResultOfPaymentSession; + + internal void ExecuteOnGetResultOfPaymentSession(PaymentsService.GetResultOfPaymentSessionApiResponse apiResponse) + { + OnGetResultOfPaymentSession?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetResultOfPaymentSession(Exception exception) + { + OnErrorGetResultOfPaymentSession?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPaymentMethods; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPaymentMethods; + + internal void ExecuteOnPaymentMethods(PaymentsService.PaymentMethodsApiResponse apiResponse) + { + OnPaymentMethods?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPaymentMethods(Exception exception) + { + OnErrorPaymentMethods?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPayments; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPayments; + + internal void ExecuteOnPayments(PaymentsService.PaymentsApiResponse apiResponse) + { + OnPayments?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPayments(Exception exception) + { + OnErrorPayments?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPaymentsDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPaymentsDetails; + + internal void ExecuteOnPaymentsDetails(PaymentsService.PaymentsDetailsApiResponse apiResponse) + { + OnPaymentsDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPaymentsDetails(Exception exception) + { + OnErrorPaymentsDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSessions; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSessions; + + internal void ExecuteOnSessions(PaymentsService.SessionsApiResponse apiResponse) + { + OnSessions?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSessions(Exception exception) + { + OnErrorSessions?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentsService : IPaymentsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentsServiceEvents paymentsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get the brands and other details of a card Use this endpoint to get information about the card or network token that enables you to decide on the routing of the transaction and the eligibility of the card for the type of transaction. If you include [your supported brands](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/cardDetails__reqParam_supportedBrands) in the request, the response also tells you if you support each [brand that was identified on the card](https://docs.adyen.com/api-explorer/Checkout/latest/post/cardDetails#responses-200-brands). If you have an API-only integration and collect card data, use this endpoint to find out if the shopper's card is co-bad. For co-badged cards, you must let the shopper choose the brand to pay with if you support both brands. ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources BIN Lookup API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments**&nbsp;>&nbsp;**Adyen&nbsp;APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-677c7679-a695-4ebb-91da-68b4e7c9228a?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-677c7679-a695-4ebb-91da-68b4e7c9228a%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CardDetailsAsync(CardDetailsRequest cardDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cardDetails" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cardDetails"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (cardDetailsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(cardDetailsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CardDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cardDetails", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCardDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCardDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CardDetailsApiResponse : Adyen.Core.Client.ApiResponse, ICardDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CardDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CardDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.CardDetailsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.CardDetailsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the result of a payment session Returns the status of the payment session with the `sessionId` and `sessionResult` specified in the path. + /// + /// Thrown when fails to make API call. + /// A unique identifier of the session. + /// The `sessionResult` value from the Drop-in or Component. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetResultOfPaymentSessionAsync(string sessionId, string sessionResult, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/sessions/{sessionId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/sessions/{sessionId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsessionId%7D", Uri.EscapeDataString(sessionId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["sessionResult"] = ClientUtils.ParameterToString(sessionResult); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetResultOfPaymentSessionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/sessions/{sessionId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetResultOfPaymentSession(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetResultOfPaymentSession(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetResultOfPaymentSessionApiResponse : Adyen.Core.Client.ApiResponse, IGetResultOfPaymentSessionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetResultOfPaymentSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetResultOfPaymentSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.SessionResultResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.SessionResultResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of available payment methods Retrieves the list of available payment methods for the transaction, based on the transaction information like amount, country, and currency. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PaymentMethodsAsync(PaymentMethodsRequest paymentMethodsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paymentMethods" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paymentMethods"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentMethodsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentMethodsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PaymentMethodsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paymentMethods", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPaymentMethods(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPaymentMethods(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PaymentMethodsApiResponse : Adyen.Core.Client.ApiResponse, IPaymentMethodsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaymentMethodsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentMethodsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Start a transaction Sends payment parameters (like amount, country, and currency) together with other required input details collected from the shopper. To know more about required parameters for specific payment methods, refer to our [payment method guides](https://docs.adyen.com/payment-methods). The response depends on the [payment flow](https://docs.adyen.com/payment-methods#payment-flow): * For a direct flow, the response includes a `pspReference` and a `resultCode` with the payment result, for example **Authorised** or **Refused**. * For a redirect or additional action, the response contains an `action` object. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PaymentsAsync(PaymentRequest paymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PaymentsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPayments(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPayments(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PaymentsApiResponse : Adyen.Core.Client.ApiResponse, IPaymentsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaymentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Submit details for a payment Submits details for a payment created using `/payments`. This step is only needed when no final state has been reached on the `/payments` request, for example when the shopper was redirected to another page to complete the payment. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PaymentsDetailsAsync(PaymentDetailsRequest paymentDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payments/details" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payments/details"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentDetailsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentDetailsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PaymentsDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payments/details", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPaymentsDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPaymentsDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PaymentsDetailsApiResponse : Adyen.Core.Client.ApiResponse, IPaymentsDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentsDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PaymentsDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaymentDetailsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaymentDetailsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a payment session Creates a payment session for [Drop-in](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Drop-in), [Components](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Components), and [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/sessions-flow/?platform=Web&integration=Hosted+Checkout) integrations. The response contains encrypted payment session data. The front end then uses the session data to make any required server-side calls for the payment flow. You get the payment outcome asynchronously, in an [AUTHORISATION](https://docs.adyen.com/api-explorer/#/Webhooks/latest/post/AUTHORISATION) webhook. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SessionsAsync(CreateCheckoutSessionRequest createCheckoutSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/sessions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/sessions"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createCheckoutSessionRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createCheckoutSessionRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SessionsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/sessions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSessions(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSessions(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SessionsApiResponse : Adyen.Core.Client.ApiResponse, ISessionsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SessionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SessionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.CreateCheckoutSessionResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.CreateCheckoutSessionResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/RecurringService.cs b/Adyen/Checkout/Services/RecurringService.cs new file mode 100644 index 000000000..ec225442e --- /dev/null +++ b/Adyen/Checkout/Services/RecurringService.cs @@ -0,0 +1,722 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IRecurringService : IAdyenApiService + { + /// + /// The class containing the events. + /// + RecurringServiceEvents Events { get; } + + /// + /// Delete a token for stored payment details + /// + /// + /// Deletes the token identified in the path. The token can no longer be used with payment requests. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the token. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// Your merchant account. + /// . + /// . + /// of . + Task DeleteTokenForStoredPaymentDetailsAsync(string storedPaymentMethodId, string shopperReference, string merchantAccount, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get tokens for stored payment details + /// + /// + /// Lists the tokens for stored payment details for the shopper identified in the path, if there are any available. The token ID can be used with payment requests for the shopper's payment. A summary of the stored details is included. + /// + /// Thrown when fails to make API call. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// Your merchant account. + /// . + /// . + /// of . + Task GetTokensForStoredPaymentDetailsAsync(Option shopperReference = default, Option merchantAccount = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a token to store payment details + /// + /// + /// Creates a token to store the shopper's payment details. This token can be used for the shopper's future payments. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task StoredPaymentMethodsAsync(StoredPaymentMethodRequest storedPaymentMethodRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IDeleteTokenForStoredPaymentDetailsApiResponse : Adyen.Core.Client.IApiResponse + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTokensForStoredPaymentDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + } + + /// + /// The , wraps . + /// + public interface IStoredPaymentMethodsApiResponse : Adyen.Core.Client.IApiResponse, ICreated + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class RecurringServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteTokenForStoredPaymentDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteTokenForStoredPaymentDetails; + + internal void ExecuteOnDeleteTokenForStoredPaymentDetails(RecurringService.DeleteTokenForStoredPaymentDetailsApiResponse apiResponse) + { + OnDeleteTokenForStoredPaymentDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTokenForStoredPaymentDetails(Exception exception) + { + OnErrorDeleteTokenForStoredPaymentDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTokensForStoredPaymentDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTokensForStoredPaymentDetails; + + internal void ExecuteOnGetTokensForStoredPaymentDetails(RecurringService.GetTokensForStoredPaymentDetailsApiResponse apiResponse) + { + OnGetTokensForStoredPaymentDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTokensForStoredPaymentDetails(Exception exception) + { + OnErrorGetTokensForStoredPaymentDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnStoredPaymentMethods; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorStoredPaymentMethods; + + internal void ExecuteOnStoredPaymentMethods(RecurringService.StoredPaymentMethodsApiResponse apiResponse) + { + OnStoredPaymentMethods?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorStoredPaymentMethods(Exception exception) + { + OnErrorStoredPaymentMethods?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class RecurringService : IRecurringService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public RecurringServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public RecurringService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, RecurringServiceEvents recurringServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = recurringServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Delete a token for stored payment details Deletes the token identified in the path. The token can no longer be used with payment requests. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the token. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. + /// Your merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteTokenForStoredPaymentDetailsAsync(string storedPaymentMethodId, string shopperReference, string merchantAccount, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/storedPaymentMethods/{storedPaymentMethodId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/storedPaymentMethods/{storedPaymentMethodId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoredPaymentMethodId%7D", Uri.EscapeDataString(storedPaymentMethodId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["shopperReference"] = ClientUtils.ParameterToString(shopperReference); + parseQueryString["merchantAccount"] = ClientUtils.ParameterToString(merchantAccount); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteTokenForStoredPaymentDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/storedPaymentMethods/{storedPaymentMethodId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteTokenForStoredPaymentDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteTokenForStoredPaymentDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteTokenForStoredPaymentDetailsApiResponse : Adyen.Core.Client.ApiResponse, IDeleteTokenForStoredPaymentDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTokenForStoredPaymentDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTokenForStoredPaymentDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get tokens for stored payment details Lists the tokens for stored payment details for the shopper identified in the path, if there are any available. The token ID can be used with payment requests for the shopper's payment. A summary of the stored details is included. + /// + /// Thrown when fails to make API call. + /// Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. () + /// Your merchant account. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTokensForStoredPaymentDetailsAsync(Option shopperReference = default, Option merchantAccount = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/storedPaymentMethods" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/storedPaymentMethods"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (shopperReference.IsSet) + parseQueryString["shopperReference"] = ClientUtils.ParameterToString(shopperReference.Value); + + if (merchantAccount.IsSet) + parseQueryString["merchantAccount"] = ClientUtils.ParameterToString(merchantAccount.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTokensForStoredPaymentDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/storedPaymentMethods", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTokensForStoredPaymentDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTokensForStoredPaymentDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTokensForStoredPaymentDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetTokensForStoredPaymentDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTokensForStoredPaymentDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTokensForStoredPaymentDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.ListStoredPaymentMethodsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ListStoredPaymentMethodsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a token to store payment details Creates a token to store the shopper's payment details. This token can be used for the shopper's future payments. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task StoredPaymentMethodsAsync(StoredPaymentMethodRequest storedPaymentMethodRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/storedPaymentMethods" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/storedPaymentMethods"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedPaymentMethodRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedPaymentMethodRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + StoredPaymentMethodsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/storedPaymentMethods", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnStoredPaymentMethods(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorStoredPaymentMethods(exception); + throw; + } + } + + /// + /// The . + /// + public partial class StoredPaymentMethodsApiResponse : Adyen.Core.Client.ApiResponse, IStoredPaymentMethodsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoredPaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoredPaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.Checkout.Models.StoredPaymentMethodResource? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.StoredPaymentMethodResource? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Checkout/Services/UtilityService.cs b/Adyen/Checkout/Services/UtilityService.cs new file mode 100644 index 000000000..59cb6d390 --- /dev/null +++ b/Adyen/Checkout/Services/UtilityService.cs @@ -0,0 +1,1656 @@ +// +/* + * Adyen Checkout API + * + * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Checkout API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-46ad970e-dc9e-4246-bac2-769c6083e7b5%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! + * + * The version of the OpenAPI document: 71 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Checkout.Client; +using Adyen.Checkout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Checkout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IUtilityService : IAdyenApiService + { + /// + /// The class containing the events. + /// + UtilityServiceEvents Events { get; } + + /// + /// Get an Apple Pay session + /// + /// + /// You need to use this endpoint if you have an API-only integration with Apple Pay which uses Adyen's Apple Pay certificate. The endpoint returns the Apple Pay session data which you need to complete the [Apple Pay session validation](https://docs.adyen.com/payment-methods/apple-pay/api-only?tab=adyen-certificate-validation_1#complete-apple-pay-session-validation). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task GetApplePaySessionAsync(ApplePaySessionRequest applePaySessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create originKey values for domains + /// + /// + /// This operation takes the origin domains and returns a JSON object containing the corresponding origin keys for the domains. > If you're still using origin key for your Web Drop-in or Components integration, we recommend [switching to client key](https://docs.adyen.com/development-resources/client-side-authentication/migrate-from-origin-key-to-client-key). This allows you to use a single key for all origins, add or remove origins without generating a new key, and detect the card type from the number entered in your payment form. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + [Obsolete("Deprecated since Adyen Checkout API v67.")] + Task OriginKeysAsync(UtilityRequest utilityRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Updates the order for PayPal Express Checkout + /// + /// + /// Updates the order for PayPal Express Checkout. This can be used to update the PayPal lightbox with an updated amount and delivery methods based on the delivery address. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UpdatesOrderForPaypalExpressCheckoutAsync(PaypalUpdateOrderRequest paypalUpdateOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Validates shopper Id + /// + /// + /// Validates the shopperId. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ValidateShopperIdAsync(ValidateShopperIdRequest validateShopperIdRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetApplePaySessionApiResponse : Adyen.Core.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + } + + /// + /// The , wraps . + /// + public interface IOriginKeysApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdatesOrderForPaypalExpressCheckoutApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IValidateShopperIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class UtilityServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetApplePaySession; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetApplePaySession; + + internal void ExecuteOnGetApplePaySession(UtilityService.GetApplePaySessionApiResponse apiResponse) + { + OnGetApplePaySession?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetApplePaySession(Exception exception) + { + OnErrorGetApplePaySession?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnOriginKeys; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorOriginKeys; + + internal void ExecuteOnOriginKeys(UtilityService.OriginKeysApiResponse apiResponse) + { + OnOriginKeys?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorOriginKeys(Exception exception) + { + OnErrorOriginKeys?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdatesOrderForPaypalExpressCheckout; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdatesOrderForPaypalExpressCheckout; + + internal void ExecuteOnUpdatesOrderForPaypalExpressCheckout(UtilityService.UpdatesOrderForPaypalExpressCheckoutApiResponse apiResponse) + { + OnUpdatesOrderForPaypalExpressCheckout?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatesOrderForPaypalExpressCheckout(Exception exception) + { + OnErrorUpdatesOrderForPaypalExpressCheckout?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnValidateShopperId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorValidateShopperId; + + internal void ExecuteOnValidateShopperId(UtilityService.ValidateShopperIdApiResponse apiResponse) + { + OnValidateShopperId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorValidateShopperId(Exception exception) + { + OnErrorValidateShopperId?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class UtilityService : IUtilityService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public UtilityServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public UtilityService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, UtilityServiceEvents utilityServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = utilityServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get an Apple Pay session You need to use this endpoint if you have an API-only integration with Apple Pay which uses Adyen's Apple Pay certificate. The endpoint returns the Apple Pay session data which you need to complete the [Apple Pay session validation](https://docs.adyen.com/payment-methods/apple-pay/api-only?tab=adyen-certificate-validation_1#complete-apple-pay-session-validation). + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetApplePaySessionAsync(ApplePaySessionRequest applePaySessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/applePay/sessions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/applePay/sessions"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (applePaySessionRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(applePaySessionRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetApplePaySessionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/applePay/sessions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetApplePaySession(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetApplePaySession(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetApplePaySessionApiResponse : Adyen.Core.Client.ApiResponse, IGetApplePaySessionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApplePaySessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApplePaySessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.ApplePaySessionResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ApplePaySessionResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create originKey values for domains This operation takes the origin domains and returns a JSON object containing the corresponding origin keys for the domains. > If you're still using origin key for your Web Drop-in or Components integration, we recommend [switching to client key](https://docs.adyen.com/development-resources/client-side-authentication/migrate-from-origin-key-to-client-key). This allows you to use a single key for all origins, add or remove origins without generating a new key, and detect the card type from the number entered in your payment form. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task OriginKeysAsync(UtilityRequest utilityRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/originKeys" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/originKeys"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (utilityRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(utilityRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + OriginKeysApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/originKeys", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnOriginKeys(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorOriginKeys(exception); + throw; + } + } + + /// + /// The . + /// + public partial class OriginKeysApiResponse : Adyen.Core.Client.ApiResponse, IOriginKeysApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public OriginKeysApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public OriginKeysApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.UtilityResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.UtilityResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Updates the order for PayPal Express Checkout Updates the order for PayPal Express Checkout. This can be used to update the PayPal lightbox with an updated amount and delivery methods based on the delivery address. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdatesOrderForPaypalExpressCheckoutAsync(PaypalUpdateOrderRequest paypalUpdateOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/paypal/updateOrder" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/paypal/updateOrder"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paypalUpdateOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paypalUpdateOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdatesOrderForPaypalExpressCheckoutApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/paypal/updateOrder", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdatesOrderForPaypalExpressCheckout(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdatesOrderForPaypalExpressCheckout(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdatesOrderForPaypalExpressCheckoutApiResponse : Adyen.Core.Client.ApiResponse, IUpdatesOrderForPaypalExpressCheckoutApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatesOrderForPaypalExpressCheckoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatesOrderForPaypalExpressCheckoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.PaypalUpdateOrderResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.PaypalUpdateOrderResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Validates shopper Id Validates the shopperId. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ValidateShopperIdAsync(ValidateShopperIdRequest validateShopperIdRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/validateShopperId" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/validateShopperId"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (validateShopperIdRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(validateShopperIdRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ValidateShopperIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/validateShopperId", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnValidateShopperId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorValidateShopperId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ValidateShopperIdApiResponse : Adyen.Core.Client.ApiResponse, IValidateShopperIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ValidateShopperIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ValidateShopperIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Checkout.Models.ValidateShopperIdResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Checkout.Models.ValidateShopperIdResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Checkout.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Checkout.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Checkout.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Checkout.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Checkout.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Checkout.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/ConfigurationWebhooks/Client/ClientUtils.cs b/Adyen/ConfigurationWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..7b49a38dc --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Client/ClientUtils.cs @@ -0,0 +1,367 @@ +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.ConfigurationWebhooks.Models; +using Models = Adyen.ConfigurationWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.ConfigurationWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AccountHolder.StatusEnum accountHolderStatusEnum) + return Models.AccountHolder.StatusEnum.ToJsonValue(accountHolderStatusEnum); + if (obj is Models.AccountHolderCapability.AllowedLevelEnum accountHolderCapabilityAllowedLevelEnum) + return Models.AccountHolderCapability.AllowedLevelEnum.ToJsonValue(accountHolderCapabilityAllowedLevelEnum); + if (obj is Models.AccountHolderCapability.RequestedLevelEnum accountHolderCapabilityRequestedLevelEnum) + return Models.AccountHolderCapability.RequestedLevelEnum.ToJsonValue(accountHolderCapabilityRequestedLevelEnum); + if (obj is Models.AccountHolderCapability.VerificationStatusEnum accountHolderCapabilityVerificationStatusEnum) + return Models.AccountHolderCapability.VerificationStatusEnum.ToJsonValue(accountHolderCapabilityVerificationStatusEnum); + if (obj is Models.AccountHolderNotificationRequest.TypeEnum accountHolderNotificationRequestTypeEnum) + return Models.AccountHolderNotificationRequest.TypeEnum.ToJsonValue(accountHolderNotificationRequestTypeEnum); + if (obj is Models.AccountSupportingEntityCapability.AllowedLevelEnum accountSupportingEntityCapabilityAllowedLevelEnum) + return Models.AccountSupportingEntityCapability.AllowedLevelEnum.ToJsonValue(accountSupportingEntityCapabilityAllowedLevelEnum); + if (obj is Models.AccountSupportingEntityCapability.RequestedLevelEnum accountSupportingEntityCapabilityRequestedLevelEnum) + return Models.AccountSupportingEntityCapability.RequestedLevelEnum.ToJsonValue(accountSupportingEntityCapabilityRequestedLevelEnum); + if (obj is Models.AccountSupportingEntityCapability.VerificationStatusEnum accountSupportingEntityCapabilityVerificationStatusEnum) + return Models.AccountSupportingEntityCapability.VerificationStatusEnum.ToJsonValue(accountSupportingEntityCapabilityVerificationStatusEnum); + if (obj is Models.BalanceAccount.StatusEnum balanceAccountStatusEnum) + return Models.BalanceAccount.StatusEnum.ToJsonValue(balanceAccountStatusEnum); + if (obj is Models.BalanceAccountNotificationRequest.TypeEnum balanceAccountNotificationRequestTypeEnum) + return Models.BalanceAccountNotificationRequest.TypeEnum.ToJsonValue(balanceAccountNotificationRequestTypeEnum); + if (obj is Models.CapabilityProblemEntity.TypeEnum capabilityProblemEntityTypeEnum) + return Models.CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntityTypeEnum); + if (obj is Models.CapabilityProblemEntityRecursive.TypeEnum capabilityProblemEntityRecursiveTypeEnum) + return Models.CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursiveTypeEnum); + if (obj is Models.CapabilitySettings.FundingSourceEnum capabilitySettingsFundingSourceEnum) + return CapabilitySettings.FundingSourceEnum.ToJsonValue(capabilitySettingsFundingSourceEnum); + if (obj is Models.CapabilitySettings.IntervalEnum capabilitySettingsIntervalEnum) + return Models.CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettingsIntervalEnum); + if (obj is Models.Card.FormFactorEnum cardFormFactorEnum) + return Models.Card.FormFactorEnum.ToJsonValue(cardFormFactorEnum); + if (obj is Models.CardOrderItemDeliveryStatus.StatusEnum cardOrderItemDeliveryStatusStatusEnum) + return Models.CardOrderItemDeliveryStatus.StatusEnum.ToJsonValue(cardOrderItemDeliveryStatusStatusEnum); + if (obj is Models.CardOrderNotificationRequest.TypeEnum cardOrderNotificationRequestTypeEnum) + return Models.CardOrderNotificationRequest.TypeEnum.ToJsonValue(cardOrderNotificationRequestTypeEnum); + if (obj is Models.IbanAccountIdentification.TypeEnum ibanAccountIdentificationTypeEnum) + return Models.IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentificationTypeEnum); + if (obj is Models.NetworkTokenNotificationRequest.TypeEnum networkTokenNotificationRequestTypeEnum) + return Models.NetworkTokenNotificationRequest.TypeEnum.ToJsonValue(networkTokenNotificationRequestTypeEnum); + if (obj is Models.PaymentInstrument.TypeEnum paymentInstrumentTypeEnum) + return Models.PaymentInstrument.TypeEnum.ToJsonValue(paymentInstrumentTypeEnum); + if (obj is Models.PaymentInstrument.StatusEnum paymentInstrumentStatusEnum) + return Models.PaymentInstrument.StatusEnum.ToJsonValue(paymentInstrumentStatusEnum); + if (obj is Models.PaymentInstrument.StatusReasonEnum paymentInstrumentStatusReasonEnum) + return Models.PaymentInstrument.StatusReasonEnum.ToJsonValue(paymentInstrumentStatusReasonEnum); + if (obj is Models.PaymentNotificationRequest.TypeEnum paymentNotificationRequestTypeEnum) + return Models.PaymentNotificationRequest.TypeEnum.ToJsonValue(paymentNotificationRequestTypeEnum); + if (obj is Models.Phone.TypeEnum phoneTypeEnum) + return Models.Phone.TypeEnum.ToJsonValue(phoneTypeEnum); + if (obj is Models.PhoneNumber.PhoneTypeEnum phoneNumberPhoneTypeEnum) + return Models.PhoneNumber.PhoneTypeEnum.ToJsonValue(phoneNumberPhoneTypeEnum); + if (obj is Models.ScoreNotificationRequest.TypeEnum scoreNotificationRequestTypeEnum) + return Models.ScoreNotificationRequest.TypeEnum.ToJsonValue(scoreNotificationRequestTypeEnum); + if (obj is Models.SweepConfigurationNotificationRequest.TypeEnum sweepConfigurationNotificationRequestTypeEnum) + return Models.SweepConfigurationNotificationRequest.TypeEnum.ToJsonValue(sweepConfigurationNotificationRequestTypeEnum); + if (obj is Models.SweepConfigurationV2.CategoryEnum sweepConfigurationV2CategoryEnum) + return Models.SweepConfigurationV2.CategoryEnum.ToJsonValue(sweepConfigurationV2CategoryEnum); + if (obj is Models.SweepConfigurationV2.PrioritiesEnum sweepConfigurationV2PrioritiesEnum) + return SweepConfigurationV2.PrioritiesEnum.ToJsonValue(sweepConfigurationV2PrioritiesEnum); + if (obj is Models.SweepConfigurationV2.ReasonEnum sweepConfigurationV2ReasonEnum) + return Models.SweepConfigurationV2.ReasonEnum.ToJsonValue(sweepConfigurationV2ReasonEnum); + if (obj is Models.SweepConfigurationV2.StatusEnum sweepConfigurationV2StatusEnum) + return Models.SweepConfigurationV2.StatusEnum.ToJsonValue(sweepConfigurationV2StatusEnum); + if (obj is Models.SweepConfigurationV2.TypeEnum sweepConfigurationV2TypeEnum) + return Models.SweepConfigurationV2.TypeEnum.ToJsonValue(sweepConfigurationV2TypeEnum); + if (obj is Models.SweepSchedule.TypeEnum sweepScheduleTypeEnum) + return Models.SweepSchedule.TypeEnum.ToJsonValue(sweepScheduleTypeEnum); + if (obj is Models.ValidationFacts.ResultEnum validationFactsResultEnum) + return Models.ValidationFacts.ResultEnum.ToJsonValue(validationFactsResultEnum); + if (obj is Models.VerificationDeadline.CapabilitiesEnum verificationDeadlineCapabilitiesEnum) + return VerificationDeadline.CapabilitiesEnum.ToJsonValue(verificationDeadlineCapabilitiesEnum); + if (obj is Models.VerificationError.CapabilitiesEnum verificationErrorCapabilitiesEnum) + return VerificationError.CapabilitiesEnum.ToJsonValue(verificationErrorCapabilitiesEnum); + if (obj is Models.VerificationError.TypeEnum verificationErrorTypeEnum) + return Models.VerificationError.TypeEnum.ToJsonValue(verificationErrorTypeEnum); + if (obj is Models.VerificationErrorRecursive.CapabilitiesEnum verificationErrorRecursiveCapabilitiesEnum) + return VerificationErrorRecursive.CapabilitiesEnum.ToJsonValue(verificationErrorRecursiveCapabilitiesEnum); + if (obj is Models.VerificationErrorRecursive.TypeEnum verificationErrorRecursiveTypeEnum) + return Models.VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursiveTypeEnum); + if (obj is Models.Wallet.RecommendationReasonsEnum walletRecommendationReasonsEnum) + return Wallet.RecommendationReasonsEnum.ToJsonValue(walletRecommendationReasonsEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/ConfigurationWebhooks/Client/HmacKeyToken.cs b/Adyen/ConfigurationWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..89796b934 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.ConfigurationWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/ConfigurationWebhooks/Client/HostConfiguration.cs b/Adyen/ConfigurationWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..09da7409f --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,188 @@ +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.ConfigurationWebhooks.Client; +using Adyen.ConfigurationWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.ConfigurationWebhooks.Client +{ + /// + /// Provides hosting configuration for ConfigurationWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new AccountSupportingEntityCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationJsonConverter()); + _jsonOptions.Converters.Add(new BalanceJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountDetailsJsonConverter()); + _jsonOptions.Converters.Add(new BankScoreSignalTriggeredDataJsonConverter()); + _jsonOptions.Converters.Add(new BulkAddressJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new CapabilitySettingsJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CardConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderItemJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderItemDeliveryStatusJsonConverter()); + _jsonOptions.Converters.Add(new CardOrderNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new ContactDetailsJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryAddressJsonConverter()); + _jsonOptions.Converters.Add(new DeliveryContactJsonConverter()); + _jsonOptions.Converters.Add(new DeviceJsonConverter()); + _jsonOptions.Converters.Add(new ExpiryJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenNotificationDataV2JsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenRequestorJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenRiskRuleDataJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenRiskRuleSourceJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenTransactionRulesResultJsonConverter()); + _jsonOptions.Converters.Add(new NetworkTokenTriggeredRiskRuleJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentAdditionalBankAccountIdentificationsInnerJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new PaymentNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new PhoneJsonConverter()); + _jsonOptions.Converters.Add(new PhoneNumberJsonConverter()); + _jsonOptions.Converters.Add(new PlatformPaymentConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new RemediatingActionJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + _jsonOptions.Converters.Add(new ScoreNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new SweepConfigurationNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new SweepConfigurationNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new SweepConfigurationV2JsonConverter()); + _jsonOptions.Converters.Add(new SweepCounterpartyJsonConverter()); + _jsonOptions.Converters.Add(new SweepScheduleJsonConverter()); + _jsonOptions.Converters.Add(new TokenAuthenticationJsonConverter()); + _jsonOptions.Converters.Add(new ValidationFactsJsonConverter()); + _jsonOptions.Converters.Add(new VerificationDeadlineJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new WalletJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddConfigurationWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/ConfigurationWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..a21e142b8 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.ConfigurationWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/ConfigurationWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/ConfigurationWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..986b93680 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.ConfigurationWebhooks; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the ConfigurationWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureConfigurationWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddConfigurationWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/ConfigurationWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..4aa36d2fd --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen ConfigurationWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddConfigurationWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddConfigurationWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Handlers/ConfigurationWebhooksHandler.cs b/Adyen/ConfigurationWebhooks/Handlers/ConfigurationWebhooksHandler.cs new file mode 100644 index 000000000..a52f463d2 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Handlers/ConfigurationWebhooksHandler.cs @@ -0,0 +1,160 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.ConfigurationWebhooks.Client; +using Adyen.ConfigurationWebhooks.Models; + +namespace Adyen.ConfigurationWebhooks.Handlers +{ + /// + /// Interface for deserializing ConfigurationWebhooks webhooks or verify its HMAC signature. + /// + public interface IConfigurationWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.ConfigurationWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + AccountHolderNotificationRequest? DeserializeAccountHolderNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + BalanceAccountNotificationRequest? DeserializeBalanceAccountNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + CardOrderNotificationRequest? DeserializeCardOrderNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + NetworkTokenNotificationRequest? DeserializeNetworkTokenNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + PaymentNotificationRequest? DeserializePaymentNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + ScoreNotificationRequest? DeserializeScoreNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + SweepConfigurationNotificationRequest? DeserializeSweepConfigurationNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize ConfigurationWebhooks or verify the HMAC signature of the webhook. + /// + public partial class ConfigurationWebhooksHandler : IConfigurationWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.ConfigurationWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing ConfigurationWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public ConfigurationWebhooksHandler(Adyen.ConfigurationWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public AccountHolderNotificationRequest? DeserializeAccountHolderNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public BalanceAccountNotificationRequest? DeserializeBalanceAccountNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public CardOrderNotificationRequest? DeserializeCardOrderNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public NetworkTokenNotificationRequest? DeserializeNetworkTokenNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public PaymentNotificationRequest? DeserializePaymentNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public ScoreNotificationRequest? DeserializeScoreNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public SweepConfigurationNotificationRequest? DeserializeSweepConfigurationNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/AccountHolder.cs b/Adyen/ConfigurationWebhooks/Models/AccountHolder.cs new file mode 100644 index 000000000..f84d42290 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/AccountHolder.cs @@ -0,0 +1,598 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// AccountHolder. + /// + public partial class AccountHolder : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the account holder. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// contactDetails + /// Your description for the account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the migrated account holder in the classic integration. + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// Your reference for the account holder. + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonConstructor] + public AccountHolder(string id, string legalEntityId, Option balancePlatform = default, Option?> capabilities = default, Option contactDetails = default, Option description = default, Option?> metadata = default, Option migratedAccountHolderCode = default, Option primaryBalanceAccount = default, Option reference = default, Option status = default, Option timeZone = default, Option?> verificationDeadlines = default) + { + Id = id; + LegalEntityId = legalEntityId; + _BalancePlatformOption = balancePlatform; + _CapabilitiesOption = capabilities; + _ContactDetailsOption = contactDetails; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountHolderCodeOption = migratedAccountHolderCode; + _PrimaryBalanceAccountOption = primaryBalanceAccount; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + _VerificationDeadlinesOption = verificationDeadlines; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolder() + { + } + + partial void OnCreated(); + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + /// + /// The status of the account holder. Possible values: * **active**: The account holder is active and allowed to use its capabilities. This is the initial status for account holders and balance accounts. You can change this status to **suspended** or **closed**. * **suspended**: The account holder is temporarily disabled and payouts are blocked. You can change this status to **active** or **closed**. * **closed**: The account holder and all of its capabilities are permanently disabled. This is a final status and cannot be changed. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The unique identifier of the account holder. + /// + /// The unique identifier of the account holder. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) associated with the account holder. Adyen performs a verification process against the legal entity of the account holder. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + /// + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id) to which the account holder belongs. Required in the request if your API credentials can be used for multiple balance platforms. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that an account holder can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("contactDetails")] + [Obsolete("")] + public ContactDetails? ContactDetails { get { return this._ContactDetailsOption; } set { this._ContactDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the account holder. + /// + /// Your description for the account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountHolderCodeOption { get; private set; } + + /// + /// The unique identifier of the migrated account holder in the classic integration. + /// + /// The unique identifier of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountHolderCode")] + public string? MigratedAccountHolderCode { get { return this._MigratedAccountHolderCodeOption; } set { this._MigratedAccountHolderCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrimaryBalanceAccountOption { get; private set; } + + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + /// + /// The ID of the account holder's primary balance account. By default, this is set to the first balance account that you create for the account holder. To assign a different balance account, send a PATCH request. + [JsonPropertyName("primaryBalanceAccount")] + public string? PrimaryBalanceAccount { get { return this._PrimaryBalanceAccountOption; } set { this._PrimaryBalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the account holder. + /// + /// Your reference for the account holder. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the account holder. For example, **Europe/Amsterdam**. Defaults to the time zone of the balance platform if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationDeadlinesOption { get; private set; } + + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonPropertyName("verificationDeadlines")] + public List? VerificationDeadlines { get { return this._VerificationDeadlinesOption; } set { this._VerificationDeadlinesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolder {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ContactDetails: ").Append(ContactDetails).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountHolderCode: ").Append(MigratedAccountHolderCode).Append("\n"); + sb.Append(" PrimaryBalanceAccount: ").Append(PrimaryBalanceAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append(" VerificationDeadlines: ").Append(VerificationDeadlines).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolder Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option legalEntityId = default; + Option balancePlatform = default; + Option?> capabilities = default; + Option contactDetails = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountHolderCode = default; + Option primaryBalanceAccount = default; + Option reference = default; + Option status = default; + Option timeZone = default; + Option?> verificationDeadlines = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contactDetails": + contactDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountHolderCode": + migratedAccountHolderCode = new Option(utf8JsonReader.GetString()!); + break; + case "primaryBalanceAccount": + primaryBalanceAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AccountHolder.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + case "verificationDeadlines": + verificationDeadlines = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class AccountHolder.", nameof(id)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class AccountHolder.", nameof(legalEntityId)); + + return new AccountHolder(id.Value!, legalEntityId.Value!, balancePlatform, capabilities, contactDetails, description, metadata, migratedAccountHolderCode, primaryBalanceAccount, reference, status, timeZone, verificationDeadlines); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolder accountHolder, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolder, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolder accountHolder, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolder.Id != null) + writer.WriteString("id", accountHolder.Id); + + if (accountHolder.LegalEntityId != null) + writer.WriteString("legalEntityId", accountHolder.LegalEntityId); + + if (accountHolder._BalancePlatformOption.IsSet) + if (accountHolder.BalancePlatform != null) + writer.WriteString("balancePlatform", accountHolder.BalancePlatform); + + if (accountHolder._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountHolder.Capabilities, jsonSerializerOptions); + } + if (accountHolder._ContactDetailsOption.IsSet) + { + writer.WritePropertyName("contactDetails"); + JsonSerializer.Serialize(writer, accountHolder.ContactDetails, jsonSerializerOptions); + } + if (accountHolder._DescriptionOption.IsSet) + if (accountHolder.Description != null) + writer.WriteString("description", accountHolder.Description); + + if (accountHolder._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, accountHolder.Metadata, jsonSerializerOptions); + } + if (accountHolder._MigratedAccountHolderCodeOption.IsSet) + if (accountHolder.MigratedAccountHolderCode != null) + writer.WriteString("migratedAccountHolderCode", accountHolder.MigratedAccountHolderCode); + + if (accountHolder._PrimaryBalanceAccountOption.IsSet) + if (accountHolder.PrimaryBalanceAccount != null) + writer.WriteString("primaryBalanceAccount", accountHolder.PrimaryBalanceAccount); + + if (accountHolder._ReferenceOption.IsSet) + if (accountHolder.Reference != null) + writer.WriteString("reference", accountHolder.Reference); + + if (accountHolder._StatusOption.IsSet && accountHolder.Status != null) + { + string? statusRawValue = AccountHolder.StatusEnum.ToJsonValue(accountHolder._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (accountHolder._TimeZoneOption.IsSet) + if (accountHolder.TimeZone != null) + writer.WriteString("timeZone", accountHolder.TimeZone); + + if (accountHolder._VerificationDeadlinesOption.IsSet) + { + writer.WritePropertyName("verificationDeadlines"); + JsonSerializer.Serialize(writer, accountHolder.VerificationDeadlines, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/AccountHolderCapability.cs b/Adyen/ConfigurationWebhooks/Models/AccountHolderCapability.cs new file mode 100644 index 000000000..38daba720 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/AccountHolderCapability.cs @@ -0,0 +1,773 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// AccountHolderCapability. + /// + public partial class AccountHolderCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// allowedSettings + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// Contains verification errors and the actions that you can take to resolve them. + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// requestedSettings + /// Contains the status of the transfer instruments associated with this capability. + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + public AccountHolderCapability(Option allowed = default, Option allowedLevel = default, Option allowedSettings = default, Option enabled = default, Option?> problems = default, Option requested = default, Option requestedLevel = default, Option requestedSettings = default, Option?> transferInstruments = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _AllowedSettingsOption = allowedSettings; + _EnabledOption = enabled; + _ProblemsOption = problems; + _RequestedOption = requested; + _RequestedLevelOption = requestedLevel; + _RequestedSettingsOption = requestedSettings; + _TransferInstrumentsOption = transferInstruments; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderCapability() + { + } + + partial void OnCreated(); + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(AllowedLevelEnumJsonConverter))] + public class AllowedLevelEnum : IEnum + { + /// + /// Returns the value of the AllowedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// AllowedLevelEnum.High - high + /// + public static readonly AllowedLevelEnum High = new("high"); + + /// + /// AllowedLevelEnum.Low - low + /// + public static readonly AllowedLevelEnum Low = new("low"); + + /// + /// AllowedLevelEnum.Medium - medium + /// + public static readonly AllowedLevelEnum Medium = new("medium"); + + /// + /// AllowedLevelEnum.NotApplicable - notApplicable + /// + public static readonly AllowedLevelEnum NotApplicable = new("notApplicable"); + + private AllowedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AllowedLevelEnum?(string? value) => value == null ? null : new AllowedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AllowedLevelEnum? option) => option?.Value; + + public static bool operator ==(AllowedLevelEnum? left, AllowedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AllowedLevelEnum? left, AllowedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AllowedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AllowedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => AllowedLevelEnum.High, + "low" => AllowedLevelEnum.Low, + "medium" => AllowedLevelEnum.Medium, + "notApplicable" => AllowedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AllowedLevelEnum? value) + { + if (value == null) + return null; + + if (value == AllowedLevelEnum.High) + return "high"; + + if (value == AllowedLevelEnum.Low) + return "low"; + + if (value == AllowedLevelEnum.Medium) + return "medium"; + + if (value == AllowedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing AllowedLevelEnum. + /// + public class AllowedLevelEnumJsonConverter : JsonConverter + { + public override AllowedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AllowedLevelEnum.FromStringOrDefault(value) ?? new AllowedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AllowedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AllowedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; private set; } + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public AllowedLevelEnum? AllowedLevel { get { return this._AllowedLevelOption; } set { this._AllowedLevelOption = new(value); } } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(RequestedLevelEnumJsonConverter))] + public class RequestedLevelEnum : IEnum + { + /// + /// Returns the value of the RequestedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// RequestedLevelEnum.High - high + /// + public static readonly RequestedLevelEnum High = new("high"); + + /// + /// RequestedLevelEnum.Low - low + /// + public static readonly RequestedLevelEnum Low = new("low"); + + /// + /// RequestedLevelEnum.Medium - medium + /// + public static readonly RequestedLevelEnum Medium = new("medium"); + + /// + /// RequestedLevelEnum.NotApplicable - notApplicable + /// + public static readonly RequestedLevelEnum NotApplicable = new("notApplicable"); + + private RequestedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestedLevelEnum?(string? value) => value == null ? null : new RequestedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestedLevelEnum? option) => option?.Value; + + public static bool operator ==(RequestedLevelEnum? left, RequestedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestedLevelEnum? left, RequestedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => RequestedLevelEnum.High, + "low" => RequestedLevelEnum.Low, + "medium" => RequestedLevelEnum.Medium, + "notApplicable" => RequestedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestedLevelEnum? value) + { + if (value == null) + return null; + + if (value == RequestedLevelEnum.High) + return "high"; + + if (value == RequestedLevelEnum.Low) + return "low"; + + if (value == RequestedLevelEnum.Medium) + return "medium"; + + if (value == RequestedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing RequestedLevelEnum. + /// + public class RequestedLevelEnumJsonConverter : JsonConverter + { + public override RequestedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestedLevelEnum.FromStringOrDefault(value) ?? new RequestedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedLevelOption { get; private set; } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public RequestedLevelEnum? RequestedLevel { get { return this._RequestedLevelOption; } set { this._RequestedLevelOption = new(value); } } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => VerificationStatusEnum.Invalid, + "pending" => VerificationStatusEnum.Pending, + "rejected" => VerificationStatusEnum.Rejected, + "valid" => VerificationStatusEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("allowedSettings")] + public CapabilitySettings? AllowedSettings { get { return this._AllowedSettingsOption; } set { this._AllowedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// Contains verification errors and the actions that you can take to resolve them. + /// + /// Contains verification errors and the actions that you can take to resolve them. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; private set; } + + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } set { this._RequestedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("requestedSettings")] + public CapabilitySettings? RequestedSettings { get { return this._RequestedSettingsOption; } set { this._RequestedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferInstrumentsOption { get; private set; } + + /// + /// Contains the status of the transfer instruments associated with this capability. + /// + /// Contains the status of the transfer instruments associated with this capability. + [JsonPropertyName("transferInstruments")] + public List? TransferInstruments { get { return this._TransferInstrumentsOption; } set { this._TransferInstrumentsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" AllowedSettings: ").Append(AllowedSettings).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" RequestedSettings: ").Append(RequestedSettings).Append("\n"); + sb.Append(" TransferInstruments: ").Append(TransferInstruments).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option allowedLevel = default; + Option allowedSettings = default; + Option enabled = default; + Option?> problems = default; + Option requested = default; + Option requestedLevel = default; + Option requestedSettings = default; + Option?> transferInstruments = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + string? allowedLevelRawValue = utf8JsonReader.GetString(); + allowedLevel = new Option(AccountHolderCapability.AllowedLevelEnum.FromStringOrDefault(allowedLevelRawValue)); + break; + case "allowedSettings": + allowedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + string? requestedLevelRawValue = utf8JsonReader.GetString(); + requestedLevel = new Option(AccountHolderCapability.RequestedLevelEnum.FromStringOrDefault(requestedLevelRawValue)); + break; + case "requestedSettings": + requestedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstruments": + transferInstruments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(AccountHolderCapability.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + + return new AccountHolderCapability(allowed, allowedLevel, allowedSettings, enabled, problems, requested, requestedLevel, requestedSettings, transferInstruments, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderCapability accountHolderCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderCapability accountHolderCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", accountHolderCapability._AllowedOption.Value!.Value); + + if (accountHolderCapability._AllowedLevelOption.IsSet && accountHolderCapability.AllowedLevel != null) + { + string? allowedLevelRawValue = AccountHolderCapability.AllowedLevelEnum.ToJsonValue(accountHolderCapability._AllowedLevelOption.Value!.Value); + writer.WriteString("allowedLevel", allowedLevelRawValue); + } + + if (accountHolderCapability._AllowedSettingsOption.IsSet) + { + writer.WritePropertyName("allowedSettings"); + JsonSerializer.Serialize(writer, accountHolderCapability.AllowedSettings, jsonSerializerOptions); + } + if (accountHolderCapability._EnabledOption.IsSet) + writer.WriteBoolean("enabled", accountHolderCapability._EnabledOption.Value!.Value); + + if (accountHolderCapability._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, accountHolderCapability.Problems, jsonSerializerOptions); + } + if (accountHolderCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", accountHolderCapability._RequestedOption.Value!.Value); + + if (accountHolderCapability._RequestedLevelOption.IsSet && accountHolderCapability.RequestedLevel != null) + { + string? requestedLevelRawValue = AccountHolderCapability.RequestedLevelEnum.ToJsonValue(accountHolderCapability._RequestedLevelOption.Value!.Value); + writer.WriteString("requestedLevel", requestedLevelRawValue); + } + + if (accountHolderCapability._RequestedSettingsOption.IsSet) + { + writer.WritePropertyName("requestedSettings"); + JsonSerializer.Serialize(writer, accountHolderCapability.RequestedSettings, jsonSerializerOptions); + } + if (accountHolderCapability._TransferInstrumentsOption.IsSet) + { + writer.WritePropertyName("transferInstruments"); + JsonSerializer.Serialize(writer, accountHolderCapability.TransferInstruments, jsonSerializerOptions); + } + if (accountHolderCapability._VerificationStatusOption.IsSet && accountHolderCapability.VerificationStatus != null) + { + string? verificationStatusRawValue = AccountHolderCapability.VerificationStatusEnum.ToJsonValue(accountHolderCapability._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationData.cs b/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationData.cs new file mode 100644 index 000000000..6693b91bd --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationData.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// AccountHolderNotificationData. + /// + public partial class AccountHolderNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// The unique identifier of the balance platform. + [JsonConstructor] + public AccountHolderNotificationData(Option accountHolder = default, Option balancePlatform = default) + { + _AccountHolderOption = accountHolder; + _BalancePlatformOption = balancePlatform; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderNotificationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public AccountHolder? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderNotificationData {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option balancePlatform = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AccountHolderNotificationData(accountHolder, balancePlatform); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderNotificationData accountHolderNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderNotificationData accountHolderNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderNotificationData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, accountHolderNotificationData.AccountHolder, jsonSerializerOptions); + } + if (accountHolderNotificationData._BalancePlatformOption.IsSet) + if (accountHolderNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", accountHolderNotificationData.BalancePlatform); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationRequest.cs new file mode 100644 index 000000000..d19a46bbe --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/AccountHolderNotificationRequest.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// AccountHolderNotificationRequest. + /// + public partial class AccountHolderNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public AccountHolderNotificationRequest(AccountHolderNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformAccountHolderUpdated - balancePlatform.accountHolder.updated + /// + public static readonly TypeEnum BalancePlatformAccountHolderUpdated = new("balancePlatform.accountHolder.updated"); + + /// + /// TypeEnum.BalancePlatformAccountHolderCreated - balancePlatform.accountHolder.created + /// + public static readonly TypeEnum BalancePlatformAccountHolderCreated = new("balancePlatform.accountHolder.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.accountHolder.updated" => TypeEnum.BalancePlatformAccountHolderUpdated, + "balancePlatform.accountHolder.created" => TypeEnum.BalancePlatformAccountHolderCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformAccountHolderUpdated) + return "balancePlatform.accountHolder.updated"; + + if (value == TypeEnum.BalancePlatformAccountHolderCreated) + return "balancePlatform.accountHolder.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public AccountHolderNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AccountHolderNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class AccountHolderNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class AccountHolderNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AccountHolderNotificationRequest.", nameof(type)); + + return new AccountHolderNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderNotificationRequest accountHolderNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderNotificationRequest accountHolderNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, accountHolderNotificationRequest.Data, jsonSerializerOptions); + if (accountHolderNotificationRequest.Environment != null) + writer.WriteString("environment", accountHolderNotificationRequest.Environment); + + if (accountHolderNotificationRequest.Type != null) + { + string? typeRawValue = AccountHolderNotificationRequest.TypeEnum.ToJsonValue(accountHolderNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (accountHolderNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", accountHolderNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/AccountSupportingEntityCapability.cs b/Adyen/ConfigurationWebhooks/Models/AccountSupportingEntityCapability.cs new file mode 100644 index 000000000..a71634df1 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/AccountSupportingEntityCapability.cs @@ -0,0 +1,696 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// AccountSupportingEntityCapability. + /// + public partial class AccountSupportingEntityCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// The ID of the supporting entity. + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + public AccountSupportingEntityCapability(Option allowed = default, Option allowedLevel = default, Option enabled = default, Option id = default, Option requested = default, Option requestedLevel = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _EnabledOption = enabled; + _IdOption = id; + _RequestedOption = requested; + _RequestedLevelOption = requestedLevel; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountSupportingEntityCapability() + { + } + + partial void OnCreated(); + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(AllowedLevelEnumJsonConverter))] + public class AllowedLevelEnum : IEnum + { + /// + /// Returns the value of the AllowedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// AllowedLevelEnum.High - high + /// + public static readonly AllowedLevelEnum High = new("high"); + + /// + /// AllowedLevelEnum.Low - low + /// + public static readonly AllowedLevelEnum Low = new("low"); + + /// + /// AllowedLevelEnum.Medium - medium + /// + public static readonly AllowedLevelEnum Medium = new("medium"); + + /// + /// AllowedLevelEnum.NotApplicable - notApplicable + /// + public static readonly AllowedLevelEnum NotApplicable = new("notApplicable"); + + private AllowedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AllowedLevelEnum?(string? value) => value == null ? null : new AllowedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AllowedLevelEnum? option) => option?.Value; + + public static bool operator ==(AllowedLevelEnum? left, AllowedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AllowedLevelEnum? left, AllowedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AllowedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AllowedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => AllowedLevelEnum.High, + "low" => AllowedLevelEnum.Low, + "medium" => AllowedLevelEnum.Medium, + "notApplicable" => AllowedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AllowedLevelEnum? value) + { + if (value == null) + return null; + + if (value == AllowedLevelEnum.High) + return "high"; + + if (value == AllowedLevelEnum.Low) + return "low"; + + if (value == AllowedLevelEnum.Medium) + return "medium"; + + if (value == AllowedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing AllowedLevelEnum. + /// + public class AllowedLevelEnumJsonConverter : JsonConverter + { + public override AllowedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AllowedLevelEnum.FromStringOrDefault(value) ?? new AllowedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AllowedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AllowedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; private set; } + + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the account holder. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public AllowedLevelEnum? AllowedLevel { get { return this._AllowedLevelOption; } set { this._AllowedLevelOption = new(value); } } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(RequestedLevelEnumJsonConverter))] + public class RequestedLevelEnum : IEnum + { + /// + /// Returns the value of the RequestedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// RequestedLevelEnum.High - high + /// + public static readonly RequestedLevelEnum High = new("high"); + + /// + /// RequestedLevelEnum.Low - low + /// + public static readonly RequestedLevelEnum Low = new("low"); + + /// + /// RequestedLevelEnum.Medium - medium + /// + public static readonly RequestedLevelEnum Medium = new("medium"); + + /// + /// RequestedLevelEnum.NotApplicable - notApplicable + /// + public static readonly RequestedLevelEnum NotApplicable = new("notApplicable"); + + private RequestedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestedLevelEnum?(string? value) => value == null ? null : new RequestedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestedLevelEnum? option) => option?.Value; + + public static bool operator ==(RequestedLevelEnum? left, RequestedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestedLevelEnum? left, RequestedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => RequestedLevelEnum.High, + "low" => RequestedLevelEnum.Low, + "medium" => RequestedLevelEnum.Medium, + "notApplicable" => RequestedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestedLevelEnum? value) + { + if (value == null) + return null; + + if (value == RequestedLevelEnum.High) + return "high"; + + if (value == RequestedLevelEnum.Low) + return "low"; + + if (value == RequestedLevelEnum.Medium) + return "medium"; + + if (value == RequestedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing RequestedLevelEnum. + /// + public class RequestedLevelEnumJsonConverter : JsonConverter + { + public override RequestedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestedLevelEnum.FromStringOrDefault(value) ?? new RequestedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedLevelOption { get; private set; } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public RequestedLevelEnum? RequestedLevel { get { return this._RequestedLevelOption; } set { this._RequestedLevelOption = new(value); } } + + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => VerificationStatusEnum.Invalid, + "pending" => VerificationStatusEnum.Pending, + "rejected" => VerificationStatusEnum.Rejected, + "valid" => VerificationStatusEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the supporting entity capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + /// + /// Indicates whether the supporting entity capability is allowed. Adyen sets this to **true** if the verification is successful and the account holder is permitted to use the capability. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + /// + /// Indicates whether the capability is enabled. If **false**, the capability is temporarily disabled for the account holder. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the supporting entity. + /// + /// The ID of the supporting entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; private set; } + + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + /// + /// Indicates whether the capability is requested. To check whether the account holder is permitted to use the capability, refer to the `allowed` field. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } set { this._RequestedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountSupportingEntityCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountSupportingEntityCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountSupportingEntityCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option allowedLevel = default; + Option enabled = default; + Option id = default; + Option requested = default; + Option requestedLevel = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + string? allowedLevelRawValue = utf8JsonReader.GetString(); + allowedLevel = new Option(AccountSupportingEntityCapability.AllowedLevelEnum.FromStringOrDefault(allowedLevelRawValue)); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + string? requestedLevelRawValue = utf8JsonReader.GetString(); + requestedLevel = new Option(AccountSupportingEntityCapability.RequestedLevelEnum.FromStringOrDefault(requestedLevelRawValue)); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(AccountSupportingEntityCapability.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + + return new AccountSupportingEntityCapability(allowed, allowedLevel, enabled, id, requested, requestedLevel, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountSupportingEntityCapability accountSupportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountSupportingEntityCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountSupportingEntityCapability accountSupportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountSupportingEntityCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", accountSupportingEntityCapability._AllowedOption.Value!.Value); + + if (accountSupportingEntityCapability._AllowedLevelOption.IsSet && accountSupportingEntityCapability.AllowedLevel != null) + { + string? allowedLevelRawValue = AccountSupportingEntityCapability.AllowedLevelEnum.ToJsonValue(accountSupportingEntityCapability._AllowedLevelOption.Value!.Value); + writer.WriteString("allowedLevel", allowedLevelRawValue); + } + + if (accountSupportingEntityCapability._EnabledOption.IsSet) + writer.WriteBoolean("enabled", accountSupportingEntityCapability._EnabledOption.Value!.Value); + + if (accountSupportingEntityCapability._IdOption.IsSet) + if (accountSupportingEntityCapability.Id != null) + writer.WriteString("id", accountSupportingEntityCapability.Id); + + if (accountSupportingEntityCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", accountSupportingEntityCapability._RequestedOption.Value!.Value); + + if (accountSupportingEntityCapability._RequestedLevelOption.IsSet && accountSupportingEntityCapability.RequestedLevel != null) + { + string? requestedLevelRawValue = AccountSupportingEntityCapability.RequestedLevelEnum.ToJsonValue(accountSupportingEntityCapability._RequestedLevelOption.Value!.Value); + writer.WriteString("requestedLevel", requestedLevelRawValue); + } + + if (accountSupportingEntityCapability._VerificationStatusOption.IsSet && accountSupportingEntityCapability.VerificationStatus != null) + { + string? verificationStatusRawValue = AccountSupportingEntityCapability.VerificationStatusEnum.ToJsonValue(accountSupportingEntityCapability._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Address.cs b/Adyen/ConfigurationWebhooks/Models/Address.cs new file mode 100644 index 000000000..34ea647b1 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Amount.cs b/Adyen/ConfigurationWebhooks/Models/Amount.cs new file mode 100644 index 000000000..d549f63ab --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Authentication.cs b/Adyen/ConfigurationWebhooks/Models/Authentication.cs new file mode 100644 index 000000000..5f675b555 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Authentication.cs @@ -0,0 +1,240 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Authentication. + /// + public partial class Authentication : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address where the one-time password (OTP) is sent. + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + /// phone + [JsonConstructor] + public Authentication(Option email = default, Option password = default, Option phone = default) + { + _EmailOption = email; + _PasswordOption = password; + _PhoneOption = phone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Authentication() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address where the one-time password (OTP) is sent. + /// + /// The email address where the one-time password (OTP) is sent. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + /// + /// The password used for 3D Secure password-based authentication. The value must be between 1 to 30 characters and must only contain the following supported characters. * Characters between **a-z**, **A-Z**, and **0-9** * Special characters: **äöüßÄÖÜ+-*_/ç%()=?!~#'\",;:$&àùòâôûáúó** + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public Phone? Phone { get { return this._PhoneOption; } set { this._PhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Authentication {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 30) + { + yield return new ValidationResult("Invalid value for Password, length must be less than 30.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 1) + { + yield return new ValidationResult("Invalid value for Password, length must be greater than 1.", new [] { "Password" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Authentication Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option password = default; + Option phone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Authentication(email, password, phone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Authentication authentication, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authentication, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Authentication authentication, JsonSerializerOptions jsonSerializerOptions) + { + + if (authentication._EmailOption.IsSet) + if (authentication.Email != null) + writer.WriteString("email", authentication.Email); + + if (authentication._PasswordOption.IsSet) + if (authentication.Password != null) + writer.WriteString("password", authentication.Password); + + if (authentication._PhoneOption.IsSet) + { + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, authentication.Phone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Balance.cs b/Adyen/ConfigurationWebhooks/Models/Balance.cs new file mode 100644 index 000000000..00ae8502e --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Balance.cs @@ -0,0 +1,252 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Balance. + /// + public partial class Balance : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The balance available for use. + /// The sum of the transactions that have already been settled. + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// The balance currently held in reserve. + /// The sum of the transactions that will be settled in the future. + [JsonConstructor] + public Balance(long available, long varBalance, string currency, long reserved, Option pending = default) + { + Available = available; + VarBalance = varBalance; + Currency = currency; + Reserved = reserved; + _PendingOption = pending; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Balance() + { + } + + partial void OnCreated(); + + /// + /// The balance available for use. + /// + /// The balance available for use. + [JsonPropertyName("available")] + public long Available { get; set; } + + /// + /// The sum of the transactions that have already been settled. + /// + /// The sum of the transactions that have already been settled. + [JsonPropertyName("balance")] + public long VarBalance { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance. + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The balance currently held in reserve. + /// + /// The balance currently held in reserve. + [JsonPropertyName("reserved")] + public long Reserved { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PendingOption { get; private set; } + + /// + /// The sum of the transactions that will be settled in the future. + /// + /// The sum of the transactions that will be settled in the future. + [JsonPropertyName("pending")] + public long? Pending { get { return this._PendingOption; } set { this._PendingOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Balance {\n"); + sb.Append(" Available: ").Append(Available).Append("\n"); + sb.Append(" VarBalance: ").Append(VarBalance).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Reserved: ").Append(Reserved).Append("\n"); + sb.Append(" Pending: ").Append(Pending).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Balance Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option available = default; + Option varBalance = default; + Option currency = default; + Option reserved = default; + Option pending = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "available": + available = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "balance": + varBalance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "reserved": + reserved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "pending": + pending = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!available.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(available)); + + if (!varBalance.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(varBalance)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(currency)); + + if (!reserved.IsSet) + throw new ArgumentException("Property is required for class Balance.", nameof(reserved)); + + return new Balance(available.Value!.Value!, varBalance.Value!.Value!, currency.Value!, reserved.Value!.Value!, pending); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Balance balance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balance, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Balance balance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("available", balance.Available); + + writer.WriteNumber("balance", balance.VarBalance); + + if (balance.Currency != null) + writer.WriteString("currency", balance.Currency); + + writer.WriteNumber("reserved", balance.Reserved); + + if (balance._PendingOption.IsSet) + writer.WriteNumber("pending", balance._PendingOption.Value!.Value); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BalanceAccount.cs b/Adyen/ConfigurationWebhooks/Models/BalanceAccount.cs new file mode 100644 index 000000000..f1a23693a --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BalanceAccount.cs @@ -0,0 +1,554 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BalanceAccount. + /// + public partial class BalanceAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// The unique identifier of the balance account. + /// List of balances with the amount and currency. + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// platformPaymentConfiguration + /// Your reference for the balance account, maximum 150 characters. + /// The status of the balance account, set to **active** by default. + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonConstructor] + public BalanceAccount(string accountHolderId, string id, Option?> balances = default, Option defaultCurrencyCode = default, Option description = default, Option?> metadata = default, Option migratedAccountCode = default, Option platformPaymentConfiguration = default, Option reference = default, Option status = default, Option timeZone = default) + { + AccountHolderId = accountHolderId; + Id = id; + _BalancesOption = balances; + _DefaultCurrencyCodeOption = defaultCurrencyCode; + _DescriptionOption = description; + _MetadataOption = metadata; + _MigratedAccountCodeOption = migratedAccountCode; + _PlatformPaymentConfigurationOption = platformPaymentConfiguration; + _ReferenceOption = reference; + _StatusOption = status; + _TimeZoneOption = timeZone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccount() + { + } + + partial void OnCreated(); + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the balance account, set to **active** by default. + /// + /// The status of the balance account, set to **active** by default. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + /// + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/accountHolders#responses-200-id) associated with the balance account. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// The unique identifier of the balance account. + /// + /// The unique identifier of the balance account. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BalancesOption { get; private set; } + + /// + /// List of balances with the amount and currency. + /// + /// List of balances with the amount and currency. + [JsonPropertyName("balances")] + public List? Balances { get { return this._BalancesOption; } set { this._BalancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultCurrencyCodeOption { get; private set; } + + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + /// + /// The default three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) of the balance account. This is the currency displayed on the Balance Account overview page in your Customer Area. The default value is **EUR**. > After a balance account is created, you cannot change its default currency. + [JsonPropertyName("defaultCurrencyCode")] + public string? DefaultCurrencyCode { get { return this._DefaultCurrencyCodeOption; } set { this._DefaultCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + /// + /// A human-readable description of the balance account, maximum 300 characters. You can use this parameter to distinguish between multiple balance accounts under an account holder. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + /// + /// A set of key and value pairs for general use. The keys do not have specific names and may be used for storing miscellaneous data as desired. > Note that during an update of metadata, the omission of existing key-value pairs will result in the deletion of those key-value pairs. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MigratedAccountCodeOption { get; private set; } + + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + /// + /// The unique identifier of the account of the migrated account holder in the classic integration. + [JsonPropertyName("migratedAccountCode")] + public string? MigratedAccountCode { get { return this._MigratedAccountCodeOption; } set { this._MigratedAccountCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformPaymentConfiguration")] + public PlatformPaymentConfiguration? PlatformPaymentConfiguration { get { return this._PlatformPaymentConfigurationOption; } set { this._PlatformPaymentConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the balance account, maximum 150 characters. + /// + /// Your reference for the balance account, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneOption { get; private set; } + + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + /// + /// The time zone of the balance account. For example, **Europe/Amsterdam**. Defaults to the time zone of the account holder if no time zone is set. For possible values, see the [list of time zone codes](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + [JsonPropertyName("timeZone")] + public string? TimeZone { get { return this._TimeZoneOption; } set { this._TimeZoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccount {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" DefaultCurrencyCode: ").Append(DefaultCurrencyCode).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MigratedAccountCode: ").Append(MigratedAccountCode).Append("\n"); + sb.Append(" PlatformPaymentConfiguration: ").Append(PlatformPaymentConfiguration).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option id = default; + Option?> balances = default; + Option defaultCurrencyCode = default; + Option description = default; + Option?> metadata = default; + Option migratedAccountCode = default; + Option platformPaymentConfiguration = default; + Option reference = default; + Option status = default; + Option timeZone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "balances": + balances = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "defaultCurrencyCode": + defaultCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "migratedAccountCode": + migratedAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentConfiguration": + platformPaymentConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(BalanceAccount.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "timeZone": + timeZone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class BalanceAccount.", nameof(accountHolderId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BalanceAccount.", nameof(id)); + + return new BalanceAccount(accountHolderId.Value!, id.Value!, balances, defaultCurrencyCode, description, metadata, migratedAccountCode, platformPaymentConfiguration, reference, status, timeZone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccount balanceAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccount balanceAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccount.AccountHolderId != null) + writer.WriteString("accountHolderId", balanceAccount.AccountHolderId); + + if (balanceAccount.Id != null) + writer.WriteString("id", balanceAccount.Id); + + if (balanceAccount._BalancesOption.IsSet) + { + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, balanceAccount.Balances, jsonSerializerOptions); + } + if (balanceAccount._DefaultCurrencyCodeOption.IsSet) + if (balanceAccount.DefaultCurrencyCode != null) + writer.WriteString("defaultCurrencyCode", balanceAccount.DefaultCurrencyCode); + + if (balanceAccount._DescriptionOption.IsSet) + if (balanceAccount.Description != null) + writer.WriteString("description", balanceAccount.Description); + + if (balanceAccount._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, balanceAccount.Metadata, jsonSerializerOptions); + } + if (balanceAccount._MigratedAccountCodeOption.IsSet) + if (balanceAccount.MigratedAccountCode != null) + writer.WriteString("migratedAccountCode", balanceAccount.MigratedAccountCode); + + if (balanceAccount._PlatformPaymentConfigurationOption.IsSet) + { + writer.WritePropertyName("platformPaymentConfiguration"); + JsonSerializer.Serialize(writer, balanceAccount.PlatformPaymentConfiguration, jsonSerializerOptions); + } + if (balanceAccount._ReferenceOption.IsSet) + if (balanceAccount.Reference != null) + writer.WriteString("reference", balanceAccount.Reference); + + if (balanceAccount._StatusOption.IsSet && balanceAccount.Status != null) + { + string? statusRawValue = BalanceAccount.StatusEnum.ToJsonValue(balanceAccount._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (balanceAccount._TimeZoneOption.IsSet) + if (balanceAccount.TimeZone != null) + writer.WriteString("timeZone", balanceAccount.TimeZone); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationData.cs b/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationData.cs new file mode 100644 index 000000000..e1f50144f --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationData.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BalanceAccountNotificationData. + /// + public partial class BalanceAccountNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balanceAccount + /// The unique identifier of the balance platform. + [JsonConstructor] + public BalanceAccountNotificationData(Option balanceAccount = default, Option balancePlatform = default) + { + _BalanceAccountOption = balanceAccount; + _BalancePlatformOption = balancePlatform; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountNotificationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public BalanceAccount? BalanceAccount { get { return this._BalanceAccountOption; } set { this._BalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountNotificationData {\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccount = default; + Option balancePlatform = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalanceAccountNotificationData(balanceAccount, balancePlatform); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountNotificationData balanceAccountNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountNotificationData balanceAccountNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccountNotificationData._BalanceAccountOption.IsSet) + { + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, balanceAccountNotificationData.BalanceAccount, jsonSerializerOptions); + } + if (balanceAccountNotificationData._BalancePlatformOption.IsSet) + if (balanceAccountNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", balanceAccountNotificationData.BalancePlatform); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationRequest.cs new file mode 100644 index 000000000..ce9923da3 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BalanceAccountNotificationRequest.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BalanceAccountNotificationRequest. + /// + public partial class BalanceAccountNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public BalanceAccountNotificationRequest(BalanceAccountNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformBalanceAccountUpdated - balancePlatform.balanceAccount.updated + /// + public static readonly TypeEnum BalancePlatformBalanceAccountUpdated = new("balancePlatform.balanceAccount.updated"); + + /// + /// TypeEnum.BalancePlatformBalanceAccountCreated - balancePlatform.balanceAccount.created + /// + public static readonly TypeEnum BalancePlatformBalanceAccountCreated = new("balancePlatform.balanceAccount.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.balanceAccount.updated" => TypeEnum.BalancePlatformBalanceAccountUpdated, + "balancePlatform.balanceAccount.created" => TypeEnum.BalancePlatformBalanceAccountCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformBalanceAccountUpdated) + return "balancePlatform.balanceAccount.updated"; + + if (value == TypeEnum.BalancePlatformBalanceAccountCreated) + return "balancePlatform.balanceAccount.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public BalanceAccountNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BalanceAccountNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountNotificationRequest.", nameof(type)); + + return new BalanceAccountNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountNotificationRequest balanceAccountNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountNotificationRequest balanceAccountNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, balanceAccountNotificationRequest.Data, jsonSerializerOptions); + if (balanceAccountNotificationRequest.Environment != null) + writer.WriteString("environment", balanceAccountNotificationRequest.Environment); + + if (balanceAccountNotificationRequest.Type != null) + { + string? typeRawValue = BalanceAccountNotificationRequest.TypeEnum.ToJsonValue(balanceAccountNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (balanceAccountNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", balanceAccountNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/ConfigurationWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..4ef686087 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BankAccountDetails.cs b/Adyen/ConfigurationWebhooks/Models/BankAccountDetails.cs new file mode 100644 index 000000000..ca28a3230 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BankAccountDetails.cs @@ -0,0 +1,346 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BankAccountDetails. + /// + public partial class BankAccountDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to "checking") + /// The bank account branch number, without separators or whitespace + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. (default to "physical") + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **iban** or **usLocal** or **ukLocal** (default to "iban") + [JsonConstructor] + public BankAccountDetails(Option accountNumber = default, Option accountType = default, Option branchNumber = default, Option formFactor = default, Option iban = default, Option routingNumber = default, Option sortCode = default, string type = @"iban") + { + _AccountNumberOption = accountNumber; + _AccountTypeOption = accountType; + _BranchNumberOption = branchNumber; + _FormFactorOption = formFactor; + _IbanOption = iban; + _RoutingNumberOption = routingNumber; + _SortCodeOption = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountNumberOption { get; private set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string? AccountNumber { get { return this._AccountNumberOption; } set { this._AccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public string? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BranchNumberOption { get; private set; } + + /// + /// The bank account branch number, without separators or whitespace + /// + /// The bank account branch number, without separators or whitespace + [JsonPropertyName("branchNumber")] + public string? BranchNumber { get { return this._BranchNumberOption; } set { this._BranchNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FormFactorOption { get; private set; } + + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + /// + /// Business accounts with a `formFactor` value of **physical** are business accounts issued under the central bank of that country. The default value is **physical** for NL, US, and UK business accounts. Adyen creates a local IBAN for business accounts when the `formFactor` value is set to **virtual**. The local IBANs that are supported are for DE and FR, which reference a physical NL account, with funds being routed through the central bank of NL. + [JsonPropertyName("formFactor")] + public string? FormFactor { get { return this._FormFactorOption; } set { this._FormFactorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RoutingNumberOption { get; private set; } + + /// + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string? RoutingNumber { get { return this._RoutingNumberOption; } set { this._RoutingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SortCodeOption { get; private set; } + + /// + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string? SortCode { get { return this._SortCodeOption; } set { this._SortCodeOption = new(value); } } + + /// + /// **iban** or **usLocal** or **ukLocal** + /// + /// **iban** or **usLocal** or **ukLocal** + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountDetails {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BranchNumber: ").Append(BranchNumber).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option accountType = default; + Option branchNumber = default; + Option formFactor = default; + Option iban = default; + Option routingNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + accountType = new Option(utf8JsonReader.GetString()!); + break; + case "branchNumber": + branchNumber = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + formFactor = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BankAccountDetails.", nameof(type)); + + return new BankAccountDetails(accountNumber, accountType, branchNumber, formFactor, iban, routingNumber, sortCode, type.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountDetails bankAccountDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountDetails bankAccountDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccountDetails._AccountNumberOption.IsSet) + if (bankAccountDetails.AccountNumber != null) + writer.WriteString("accountNumber", bankAccountDetails.AccountNumber); + + if (bankAccountDetails._AccountTypeOption.IsSet) + if (bankAccountDetails.AccountType != null) + writer.WriteString("accountType", bankAccountDetails.AccountType); + + if (bankAccountDetails._BranchNumberOption.IsSet) + if (bankAccountDetails.BranchNumber != null) + writer.WriteString("branchNumber", bankAccountDetails.BranchNumber); + + if (bankAccountDetails._FormFactorOption.IsSet) + if (bankAccountDetails.FormFactor != null) + writer.WriteString("formFactor", bankAccountDetails.FormFactor); + + if (bankAccountDetails._IbanOption.IsSet) + if (bankAccountDetails.Iban != null) + writer.WriteString("iban", bankAccountDetails.Iban); + + if (bankAccountDetails._RoutingNumberOption.IsSet) + if (bankAccountDetails.RoutingNumber != null) + writer.WriteString("routingNumber", bankAccountDetails.RoutingNumber); + + if (bankAccountDetails._SortCodeOption.IsSet) + if (bankAccountDetails.SortCode != null) + writer.WriteString("sortCode", bankAccountDetails.SortCode); + + if (bankAccountDetails.Type != null) + writer.WriteString("type", bankAccountDetails.Type); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BankScoreSignalTriggeredData.cs b/Adyen/ConfigurationWebhooks/Models/BankScoreSignalTriggeredData.cs new file mode 100644 index 000000000..ce26cd22b --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BankScoreSignalTriggeredData.cs @@ -0,0 +1,384 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BankScoreSignalTriggeredData. + /// + public partial class BankScoreSignalTriggeredData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// The status of the account holder. + /// The automated action(s) taken as a result of the score signals that were triggered. + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + /// The score of the identity resulting from the signal(s) that were triggered. + /// The name(s) of the score signals that were triggered. + /// The type(s) of the score signals that were triggered. + [JsonConstructor] + public BankScoreSignalTriggeredData(Option accountHolder = default, Option accountHolderStatus = default, Option?> automatedActions = default, Option balancePlatform = default, Option creationDate = default, Option id = default, Option riskScore = default, Option?> scoreSignalsTriggered = default, Option?> signalSourceTypes = default) + { + _AccountHolderOption = accountHolder; + _AccountHolderStatusOption = accountHolderStatus; + _AutomatedActionsOption = automatedActions; + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + _RiskScoreOption = riskScore; + _ScoreSignalsTriggeredOption = scoreSignalsTriggered; + _SignalSourceTypesOption = signalSourceTypes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankScoreSignalTriggeredData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderStatusOption { get; private set; } + + /// + /// The status of the account holder. + /// + /// The status of the account holder. + [JsonPropertyName("accountHolderStatus")] + public string? AccountHolderStatus { get { return this._AccountHolderStatusOption; } set { this._AccountHolderStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AutomatedActionsOption { get; private set; } + + /// + /// The automated action(s) taken as a result of the score signals that were triggered. + /// + /// The automated action(s) taken as a result of the score signals that were triggered. + [JsonPropertyName("automatedActions")] + public List? AutomatedActions { get { return this._AutomatedActionsOption; } set { this._AutomatedActionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// The score of the identity resulting from the signal(s) that were triggered. + /// + /// The score of the identity resulting from the signal(s) that were triggered. + [JsonPropertyName("riskScore")] + public int? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ScoreSignalsTriggeredOption { get; private set; } + + /// + /// The name(s) of the score signals that were triggered. + /// + /// The name(s) of the score signals that were triggered. + [JsonPropertyName("scoreSignalsTriggered")] + public List? ScoreSignalsTriggered { get { return this._ScoreSignalsTriggeredOption; } set { this._ScoreSignalsTriggeredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SignalSourceTypesOption { get; private set; } + + /// + /// The type(s) of the score signals that were triggered. + /// + /// The type(s) of the score signals that were triggered. + [JsonPropertyName("signalSourceTypes")] + public List? SignalSourceTypes { get { return this._SignalSourceTypesOption; } set { this._SignalSourceTypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankScoreSignalTriggeredData {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" AccountHolderStatus: ").Append(AccountHolderStatus).Append("\n"); + sb.Append(" AutomatedActions: ").Append(AutomatedActions).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" ScoreSignalsTriggered: ").Append(ScoreSignalsTriggered).Append("\n"); + sb.Append(" SignalSourceTypes: ").Append(SignalSourceTypes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankScoreSignalTriggeredDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankScoreSignalTriggeredData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option accountHolderStatus = default; + Option?> automatedActions = default; + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + Option riskScore = default; + Option?> scoreSignalsTriggered = default; + Option?> signalSourceTypes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountHolderStatus": + accountHolderStatus = new Option(utf8JsonReader.GetString()!); + break; + case "automatedActions": + automatedActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "scoreSignalsTriggered": + scoreSignalsTriggered = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signalSourceTypes": + signalSourceTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new BankScoreSignalTriggeredData(accountHolder, accountHolderStatus, automatedActions, balancePlatform, creationDate, id, riskScore, scoreSignalsTriggered, signalSourceTypes); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankScoreSignalTriggeredData bankScoreSignalTriggeredData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankScoreSignalTriggeredData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankScoreSignalTriggeredData bankScoreSignalTriggeredData, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankScoreSignalTriggeredData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, bankScoreSignalTriggeredData.AccountHolder, jsonSerializerOptions); + } + if (bankScoreSignalTriggeredData._AccountHolderStatusOption.IsSet) + if (bankScoreSignalTriggeredData.AccountHolderStatus != null) + writer.WriteString("accountHolderStatus", bankScoreSignalTriggeredData.AccountHolderStatus); + + if (bankScoreSignalTriggeredData._AutomatedActionsOption.IsSet) + { + writer.WritePropertyName("automatedActions"); + JsonSerializer.Serialize(writer, bankScoreSignalTriggeredData.AutomatedActions, jsonSerializerOptions); + } + if (bankScoreSignalTriggeredData._BalancePlatformOption.IsSet) + if (bankScoreSignalTriggeredData.BalancePlatform != null) + writer.WriteString("balancePlatform", bankScoreSignalTriggeredData.BalancePlatform); + + if (bankScoreSignalTriggeredData._CreationDateOption.IsSet) + writer.WriteString("creationDate", bankScoreSignalTriggeredData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (bankScoreSignalTriggeredData._IdOption.IsSet) + if (bankScoreSignalTriggeredData.Id != null) + writer.WriteString("id", bankScoreSignalTriggeredData.Id); + + if (bankScoreSignalTriggeredData._RiskScoreOption.IsSet) + writer.WriteNumber("riskScore", bankScoreSignalTriggeredData._RiskScoreOption.Value!.Value); + + if (bankScoreSignalTriggeredData._ScoreSignalsTriggeredOption.IsSet) + { + writer.WritePropertyName("scoreSignalsTriggered"); + JsonSerializer.Serialize(writer, bankScoreSignalTriggeredData.ScoreSignalsTriggered, jsonSerializerOptions); + } + if (bankScoreSignalTriggeredData._SignalSourceTypesOption.IsSet) + { + writer.WritePropertyName("signalSourceTypes"); + JsonSerializer.Serialize(writer, bankScoreSignalTriggeredData.SignalSourceTypes, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/BulkAddress.cs b/Adyen/ConfigurationWebhooks/Models/BulkAddress.cs new file mode 100644 index 000000000..145d45d74 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/BulkAddress.cs @@ -0,0 +1,446 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// BulkAddress. + /// + public partial class BulkAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + /// The name of the city. + /// The name of the company. + /// The email address. + /// The house number or name. + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + /// Additional information about the delivery address. For example, an apartment number. + /// Additional information about the delivery address. + /// The full telephone number. + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + /// The streetname of the house. + [JsonConstructor] + public BulkAddress(string country, Option city = default, Option company = default, Option email = default, Option houseNumberOrName = default, Option line1 = default, Option line2 = default, Option line3 = default, Option mobile = default, Option postalCode = default, Option stateOrProvince = default, Option street = default) + { + Country = country; + _CityOption = city; + _CompanyOption = company; + _EmailOption = email; + _HouseNumberOrNameOption = houseNumberOrName; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _MobileOption = mobile; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + _StreetOption = street; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BulkAddress() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// The name of the company. + /// + /// The name of the company. + [JsonPropertyName("company")] + public string? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address. + /// + /// The email address. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HouseNumberOrNameOption { get; private set; } + + /// + /// The house number or name. + /// + /// The house number or name. + [JsonPropertyName("houseNumberOrName")] + public string? HouseNumberOrName { get { return this._HouseNumberOrNameOption; } set { this._HouseNumberOrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + /// + /// The name of the street and the number of the building. For example: **Simon Carmiggeltstraat 6-50**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// Additional information about the delivery address. For example, an apartment number. + /// + /// Additional information about the delivery address. For example, an apartment number. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Additional information about the delivery address. + /// + /// Additional information about the delivery address. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobileOption { get; private set; } + + /// + /// The full telephone number. + /// + /// The full telephone number. + [JsonPropertyName("mobile")] + public string? Mobile { get { return this._MobileOption; } set { this._MobileOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + /// + /// The postal code. Maximum length: * 5 digits for addresses in the US. * 10 characters for all other countries. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + /// + /// The two-letter ISO 3166-2 state or province code. Maximum length: 2 characters for addresses in the US. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StreetOption { get; private set; } + + /// + /// The streetname of the house. + /// + /// The streetname of the house. + [JsonPropertyName("street")] + public string? Street { get { return this._StreetOption; } set { this._StreetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BulkAddress {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" Mobile: ").Append(Mobile).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BulkAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BulkAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option company = default; + Option email = default; + Option houseNumberOrName = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option mobile = default; + Option postalCode = default; + Option stateOrProvince = default; + Option street = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "company": + company = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "mobile": + mobile = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class BulkAddress.", nameof(country)); + + return new BulkAddress(country.Value!, city, company, email, houseNumberOrName, line1, line2, line3, mobile, postalCode, stateOrProvince, street); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BulkAddress bulkAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bulkAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BulkAddress bulkAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (bulkAddress.Country != null) + writer.WriteString("country", bulkAddress.Country); + + if (bulkAddress._CityOption.IsSet) + if (bulkAddress.City != null) + writer.WriteString("city", bulkAddress.City); + + if (bulkAddress._CompanyOption.IsSet) + if (bulkAddress.Company != null) + writer.WriteString("company", bulkAddress.Company); + + if (bulkAddress._EmailOption.IsSet) + if (bulkAddress.Email != null) + writer.WriteString("email", bulkAddress.Email); + + if (bulkAddress._HouseNumberOrNameOption.IsSet) + if (bulkAddress.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", bulkAddress.HouseNumberOrName); + + if (bulkAddress._Line1Option.IsSet) + if (bulkAddress.Line1 != null) + writer.WriteString("line1", bulkAddress.Line1); + + if (bulkAddress._Line2Option.IsSet) + if (bulkAddress.Line2 != null) + writer.WriteString("line2", bulkAddress.Line2); + + if (bulkAddress._Line3Option.IsSet) + if (bulkAddress.Line3 != null) + writer.WriteString("line3", bulkAddress.Line3); + + if (bulkAddress._MobileOption.IsSet) + if (bulkAddress.Mobile != null) + writer.WriteString("mobile", bulkAddress.Mobile); + + if (bulkAddress._PostalCodeOption.IsSet) + if (bulkAddress.PostalCode != null) + writer.WriteString("postalCode", bulkAddress.PostalCode); + + if (bulkAddress._StateOrProvinceOption.IsSet) + if (bulkAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", bulkAddress.StateOrProvince); + + if (bulkAddress._StreetOption.IsSet) + if (bulkAddress.Street != null) + writer.WriteString("street", bulkAddress.Street); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CapabilityProblem.cs b/Adyen/ConfigurationWebhooks/Models/CapabilityProblem.cs new file mode 100644 index 000000000..5bb4f70a2 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CapabilityProblem.cs @@ -0,0 +1,204 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CapabilityProblem. + /// + public partial class CapabilityProblem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// entity + /// Contains information about the verification error. + [JsonConstructor] + public CapabilityProblem(Option entity = default, Option?> verificationErrors = default) + { + _EntityOption = entity; + _VerificationErrorsOption = verificationErrors; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("entity")] + public CapabilityProblemEntity? Entity { get { return this._EntityOption; } set { this._EntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationErrorsOption { get; private set; } + + /// + /// Contains information about the verification error. + /// + /// Contains information about the verification error. + [JsonPropertyName("verificationErrors")] + public List? VerificationErrors { get { return this._VerificationErrorsOption; } set { this._VerificationErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblem {\n"); + sb.Append(" Entity: ").Append(Entity).Append("\n"); + sb.Append(" VerificationErrors: ").Append(VerificationErrors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entity = default; + Option?> verificationErrors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entity": + entity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationErrors": + verificationErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilityProblem(entity, verificationErrors); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblem._EntityOption.IsSet) + { + writer.WritePropertyName("entity"); + JsonSerializer.Serialize(writer, capabilityProblem.Entity, jsonSerializerOptions); + } + if (capabilityProblem._VerificationErrorsOption.IsSet) + { + writer.WritePropertyName("verificationErrors"); + JsonSerializer.Serialize(writer, capabilityProblem.VerificationErrors, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntity.cs b/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntity.cs new file mode 100644 index 000000000..4dd72a843 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntity.cs @@ -0,0 +1,368 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CapabilityProblemEntity. + /// + public partial class CapabilityProblemEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// owner + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConstructor] + public CapabilityProblemEntity(Option?> documents = default, Option id = default, Option owner = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _OwnerOption = owner; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntity() + { + } + + partial void OnCreated(); + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("owner")] + public CapabilityProblemEntityRecursive? Owner { get { return this._OwnerOption; } set { this._OwnerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntity {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Owner: ").Append(Owner).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option owner = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "owner": + owner = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntity.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntity(documents, id, owner, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntity._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntity._IdOption.IsSet) + if (capabilityProblemEntity.Id != null) + writer.WriteString("id", capabilityProblemEntity.Id); + + if (capabilityProblemEntity._OwnerOption.IsSet) + { + writer.WritePropertyName("owner"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Owner, jsonSerializerOptions); + } + if (capabilityProblemEntity._TypeOption.IsSet && capabilityProblemEntity.Type != null) + { + string? typeRawValue = CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntity._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntityRecursive.cs b/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntityRecursive.cs new file mode 100644 index 000000000..2ae0e550a --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CapabilityProblemEntityRecursive.cs @@ -0,0 +1,343 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CapabilityProblemEntityRecursive. + /// + public partial class CapabilityProblemEntityRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConstructor] + public CapabilityProblemEntityRecursive(Option?> documents = default, Option id = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntityRecursive() + { + } + + partial void OnCreated(); + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + /// + /// Type of entity. Possible values: **LegalEntity**, **BankAccount**, **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntityRecursive {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntityRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntityRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntityRecursive(documents, id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntityRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntityRecursive._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntityRecursive.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntityRecursive._IdOption.IsSet) + if (capabilityProblemEntityRecursive.Id != null) + writer.WriteString("id", capabilityProblemEntityRecursive.Id); + + if (capabilityProblemEntityRecursive._TypeOption.IsSet && capabilityProblemEntityRecursive.Type != null) + { + string? typeRawValue = CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CapabilitySettings.cs b/Adyen/ConfigurationWebhooks/Models/CapabilitySettings.cs new file mode 100644 index 000000000..e9ce2c246 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CapabilitySettings.cs @@ -0,0 +1,500 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CapabilitySettings. + /// + public partial class CapabilitySettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amountPerIndustry + /// authorizedCardUsers + /// fundingSource + /// interval + /// maxAmount + [JsonConstructor] + public CapabilitySettings(Option?> amountPerIndustry = default, Option authorizedCardUsers = default, Option?> fundingSource = default, Option interval = default, Option maxAmount = default) + { + _AmountPerIndustryOption = amountPerIndustry; + _AuthorizedCardUsersOption = authorizedCardUsers; + _FundingSourceOption = fundingSource; + _IntervalOption = interval; + _MaxAmountOption = maxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilitySettings() + { + } + + partial void OnCreated(); + + /// + /// Defines FundingSource. + /// + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + /// + /// FundingSourceEnum.Prepaid - prepaid + /// + public static readonly FundingSourceEnum Prepaid = new("prepaid"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + "prepaid" => FundingSourceEnum.Prepaid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + if (value == FundingSourceEnum.Prepaid) + return "prepaid"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines Interval. + /// + [JsonConverter(typeof(IntervalEnumJsonConverter))] + public class IntervalEnum : IEnum + { + /// + /// Returns the value of the IntervalEnum. + /// + public string? Value { get; set; } + + /// + /// IntervalEnum.Daily - daily + /// + public static readonly IntervalEnum Daily = new("daily"); + + /// + /// IntervalEnum.Monthly - monthly + /// + public static readonly IntervalEnum Monthly = new("monthly"); + + /// + /// IntervalEnum.Weekly - weekly + /// + public static readonly IntervalEnum Weekly = new("weekly"); + + private IntervalEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IntervalEnum?(string? value) => value == null ? null : new IntervalEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IntervalEnum? option) => option?.Value; + + public static bool operator ==(IntervalEnum? left, IntervalEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IntervalEnum? left, IntervalEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IntervalEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IntervalEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => IntervalEnum.Daily, + "monthly" => IntervalEnum.Monthly, + "weekly" => IntervalEnum.Weekly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IntervalEnum? value) + { + if (value == null) + return null; + + if (value == IntervalEnum.Daily) + return "daily"; + + if (value == IntervalEnum.Monthly) + return "monthly"; + + if (value == IntervalEnum.Weekly) + return "weekly"; + + return null; + } + + /// + /// JsonConverter for writing IntervalEnum. + /// + public class IntervalEnumJsonConverter : JsonConverter + { + public override IntervalEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IntervalEnum.FromStringOrDefault(value) ?? new IntervalEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IntervalEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IntervalEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IntervalOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interval")] + public IntervalEnum? Interval { get { return this._IntervalOption; } set { this._IntervalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AmountPerIndustryOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amountPerIndustry")] + public Dictionary? AmountPerIndustry { get { return this._AmountPerIndustryOption; } set { this._AmountPerIndustryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorizedCardUsersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authorizedCardUsers")] + public bool? AuthorizedCardUsers { get { return this._AuthorizedCardUsersOption; } set { this._AuthorizedCardUsersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FundingSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundingSource")] + public List? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maxAmount")] + public Amount? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilitySettings {\n"); + sb.Append(" AmountPerIndustry: ").Append(AmountPerIndustry).Append("\n"); + sb.Append(" AuthorizedCardUsers: ").Append(AuthorizedCardUsers).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Interval: ").Append(Interval).Append("\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilitySettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilitySettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> amountPerIndustry = default; + Option authorizedCardUsers = default; + Option?> fundingSource = default; + Option interval = default; + Option maxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amountPerIndustry": + amountPerIndustry = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authorizedCardUsers": + authorizedCardUsers = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "fundingSource": + fundingSource = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interval": + string? intervalRawValue = utf8JsonReader.GetString(); + interval = new Option(CapabilitySettings.IntervalEnum.FromStringOrDefault(intervalRawValue)); + break; + case "maxAmount": + maxAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilitySettings(amountPerIndustry, authorizedCardUsers, fundingSource, interval, maxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilitySettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilitySettings._AmountPerIndustryOption.IsSet) + { + writer.WritePropertyName("amountPerIndustry"); + JsonSerializer.Serialize(writer, capabilitySettings.AmountPerIndustry, jsonSerializerOptions); + } + if (capabilitySettings._AuthorizedCardUsersOption.IsSet) + writer.WriteBoolean("authorizedCardUsers", capabilitySettings._AuthorizedCardUsersOption.Value!.Value); + + if (capabilitySettings._FundingSourceOption.IsSet) + { + writer.WritePropertyName("fundingSource"); + JsonSerializer.Serialize(writer, capabilitySettings.FundingSource, jsonSerializerOptions); + } + if (capabilitySettings._IntervalOption.IsSet && capabilitySettings.Interval != null) + { + string? intervalRawValue = CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettings._IntervalOption.Value!.Value); + writer.WriteString("interval", intervalRawValue); + } + + if (capabilitySettings._MaxAmountOption.IsSet) + { + writer.WritePropertyName("maxAmount"); + JsonSerializer.Serialize(writer, capabilitySettings.MaxAmount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Card.cs b/Adyen/ConfigurationWebhooks/Models/Card.cs new file mode 100644 index 000000000..28983a174 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Card.cs @@ -0,0 +1,598 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// The name of the cardholder. Maximum length: 26 characters. + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + /// authentication + /// The bank identification number (BIN) of the card number. + /// configuration + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + /// deliveryContact + /// expiration + /// Last last four digits of the card number. + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonConstructor] + public Card(string brand, string brandVariant, string cardholderName, FormFactorEnum formFactor, string number, Option authentication = default, Option bin = default, Option configuration = default, Option cvc = default, Option deliveryContact = default, Option expiration = default, Option lastFour = default, Option threeDSecure = default, Option usage = default) + { + Brand = brand; + BrandVariant = brandVariant; + CardholderName = cardholderName; + FormFactor = formFactor; + Number = number; + _AuthenticationOption = authentication; + _BinOption = bin; + _ConfigurationOption = configuration; + _CvcOption = cvc; + _DeliveryContactOption = deliveryContact; + _ExpirationOption = expiration; + _LastFourOption = lastFour; + _ThreeDSecureOption = threeDSecure; + _UsageOption = usage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonConverter(typeof(FormFactorEnumJsonConverter))] + public class FormFactorEnum : IEnum + { + /// + /// Returns the value of the FormFactorEnum. + /// + public string? Value { get; set; } + + /// + /// FormFactorEnum.Physical - physical + /// + public static readonly FormFactorEnum Physical = new("physical"); + + /// + /// FormFactorEnum.Unknown - unknown + /// + public static readonly FormFactorEnum Unknown = new("unknown"); + + /// + /// FormFactorEnum.Virtual - virtual + /// + public static readonly FormFactorEnum Virtual = new("virtual"); + + private FormFactorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FormFactorEnum?(string? value) => value == null ? null : new FormFactorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FormFactorEnum? option) => option?.Value; + + public static bool operator ==(FormFactorEnum? left, FormFactorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FormFactorEnum? left, FormFactorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FormFactorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FormFactorEnum? FromStringOrDefault(string value) + { + return value switch { + "physical" => FormFactorEnum.Physical, + "unknown" => FormFactorEnum.Unknown, + "virtual" => FormFactorEnum.Virtual, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FormFactorEnum? value) + { + if (value == null) + return null; + + if (value == FormFactorEnum.Physical) + return "physical"; + + if (value == FormFactorEnum.Unknown) + return "unknown"; + + if (value == FormFactorEnum.Virtual) + return "virtual"; + + return null; + } + + /// + /// JsonConverter for writing FormFactorEnum. + /// + public class FormFactorEnumJsonConverter : JsonConverter + { + public override FormFactorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FormFactorEnum.FromStringOrDefault(value) ?? new FormFactorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FormFactorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FormFactorEnum.ToJsonValue(value)); + } + } + } + + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + /// + /// The form factor of the card. Possible values: **virtual**, **physical**. + [JsonPropertyName("formFactor")] + public FormFactorEnum FormFactor { get; set; } + + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + /// + /// The brand of the physical or the virtual card. Possible values: **visa**, **mc**. + [JsonPropertyName("brand")] + public string Brand { get; set; } + + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The brand variant of the physical or the virtual card. For example, **visadebit** or **mcprepaid**. >Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("brandVariant")] + public string BrandVariant { get; set; } + + /// + /// The name of the cardholder. Maximum length: 26 characters. + /// + /// The name of the cardholder. Maximum length: 26 characters. + [JsonPropertyName("cardholderName")] + public string CardholderName { get; set; } + + /// + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + /// + /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. + [JsonPropertyName("number")] + public string Number { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authentication")] + public Authentication? Authentication { get { return this._AuthenticationOption; } set { this._AuthenticationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinOption { get; private set; } + + /// + /// The bank identification number (BIN) of the card number. + /// + /// The bank identification number (BIN) of the card number. + [JsonPropertyName("bin")] + public string? Bin { get { return this._BinOption; } set { this._BinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("configuration")] + public CardConfiguration? Configuration { get { return this._ConfigurationOption; } set { this._ConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + /// + /// The CVC2 value of the card. > The CVC2 is not sent by default. This is only returned in the `POST` response for single-use virtual cards. + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryContactOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryContact")] + public DeliveryContact? DeliveryContact { get { return this._DeliveryContactOption; } set { this._DeliveryContactOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpirationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("expiration")] + public Expiry? Expiration { get { return this._ExpirationOption; } set { this._ExpirationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastFourOption { get; private set; } + + /// + /// Last last four digits of the card number. + /// + /// Last last four digits of the card number. + [JsonPropertyName("lastFour")] + public string? LastFour { get { return this._LastFourOption; } set { this._LastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + /// + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. + [JsonPropertyName("threeDSecure")] + public string? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsageOption { get; private set; } + + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + /// + /// Specifies how many times the card can be used. Possible values: **singleUse**, **multiUse**. > Reach out to your Adyen contact to determine the value relevant for your integration. + [JsonPropertyName("usage")] + public string? Usage { get { return this._UsageOption; } set { this._UsageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" BrandVariant: ").Append(BrandVariant).Append("\n"); + sb.Append(" CardholderName: ").Append(CardholderName).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" Bin: ").Append(Bin).Append("\n"); + sb.Append(" Configuration: ").Append(Configuration).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" DeliveryContact: ").Append(DeliveryContact).Append("\n"); + sb.Append(" Expiration: ").Append(Expiration).Append("\n"); + sb.Append(" LastFour: ").Append(LastFour).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Usage: ").Append(Usage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CardholderName (string) maxLength + if (this.CardholderName != null && this.CardholderName.Length > 26) + { + yield return new ValidationResult("Invalid value for CardholderName, length must be less than 26.", new [] { "CardholderName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option brandVariant = default; + Option cardholderName = default; + Option formFactor = default; + Option number = default; + Option authentication = default; + Option bin = default; + Option configuration = default; + Option cvc = default; + Option deliveryContact = default; + Option expiration = default; + Option lastFour = default; + Option threeDSecure = default; + Option usage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "brandVariant": + brandVariant = new Option(utf8JsonReader.GetString()!); + break; + case "cardholderName": + cardholderName = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + string? formFactorRawValue = utf8JsonReader.GetString(); + formFactor = new Option(Card.FormFactorEnum.FromStringOrDefault(formFactorRawValue)); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "authentication": + authentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bin": + bin = new Option(utf8JsonReader.GetString()!); + break; + case "configuration": + configuration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryContact": + deliveryContact = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiration": + expiration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lastFour": + lastFour = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSecure": + threeDSecure = new Option(utf8JsonReader.GetString()!); + break; + case "usage": + usage = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!brand.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(brand)); + + if (!brandVariant.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(brandVariant)); + + if (!cardholderName.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardholderName)); + + if (!formFactor.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(formFactor)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(number)); + + return new Card(brand.Value!, brandVariant.Value!, cardholderName.Value!, formFactor.Value!.Value!, number.Value!, authentication, bin, configuration, cvc, deliveryContact, expiration, lastFour, threeDSecure, usage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + if (card.Brand != null) + writer.WriteString("brand", card.Brand); + + if (card.BrandVariant != null) + writer.WriteString("brandVariant", card.BrandVariant); + + if (card.CardholderName != null) + writer.WriteString("cardholderName", card.CardholderName); + + if (card.FormFactor != null) + { + string? formFactorRawValue = Card.FormFactorEnum.ToJsonValue(card.FormFactor); + writer.WriteString("formFactor", formFactorRawValue); + } + + if (card.Number != null) + writer.WriteString("number", card.Number); + + if (card._AuthenticationOption.IsSet) + { + writer.WritePropertyName("authentication"); + JsonSerializer.Serialize(writer, card.Authentication, jsonSerializerOptions); + } + if (card._BinOption.IsSet) + if (card.Bin != null) + writer.WriteString("bin", card.Bin); + + if (card._ConfigurationOption.IsSet) + { + writer.WritePropertyName("configuration"); + JsonSerializer.Serialize(writer, card.Configuration, jsonSerializerOptions); + } + if (card._CvcOption.IsSet) + if (card.Cvc != null) + writer.WriteString("cvc", card.Cvc); + + if (card._DeliveryContactOption.IsSet) + { + writer.WritePropertyName("deliveryContact"); + JsonSerializer.Serialize(writer, card.DeliveryContact, jsonSerializerOptions); + } + if (card._ExpirationOption.IsSet) + { + writer.WritePropertyName("expiration"); + JsonSerializer.Serialize(writer, card.Expiration, jsonSerializerOptions); + } + if (card._LastFourOption.IsSet) + if (card.LastFour != null) + writer.WriteString("lastFour", card.LastFour); + + if (card._ThreeDSecureOption.IsSet) + if (card.ThreeDSecure != null) + writer.WriteString("threeDSecure", card.ThreeDSecure); + + if (card._UsageOption.IsSet) + if (card.Usage != null) + writer.WriteString("usage", card.Usage); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CardConfiguration.cs b/Adyen/ConfigurationWebhooks/Models/CardConfiguration.cs new file mode 100644 index 000000000..c8a859153 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CardConfiguration.cs @@ -0,0 +1,502 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CardConfiguration. + /// + public partial class CardConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + /// bulkAddress + /// The ID of the card image. This is the image that will be printed on the full front of the card. + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + /// Overrides the envelope design ID defined in the `configurationProfileId`. + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + /// Overrides the logistics company defined in the `configurationProfileId`. + [JsonConstructor] + public CardConfiguration(string configurationProfileId, Option activation = default, Option activationUrl = default, Option bulkAddress = default, Option cardImageId = default, Option carrier = default, Option carrierImageId = default, Option currency = default, Option envelope = default, Option insert = default, Option language = default, Option logoImageId = default, Option pinMailer = default, Option shipmentMethod = default) + { + ConfigurationProfileId = configurationProfileId; + _ActivationOption = activation; + _ActivationUrlOption = activationUrl; + _BulkAddressOption = bulkAddress; + _CardImageIdOption = cardImageId; + _CarrierOption = carrier; + _CarrierImageIdOption = carrierImageId; + _CurrencyOption = currency; + _EnvelopeOption = envelope; + _InsertOption = insert; + _LanguageOption = language; + _LogoImageIdOption = logoImageId; + _PinMailerOption = pinMailer; + _ShipmentMethodOption = shipmentMethod; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardConfiguration() + { + } + + partial void OnCreated(); + + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + /// + /// The ID of the card configuration profile that contains the settings of the card. For example, the envelope and PIN mailer designs or the logistics company handling the shipment. All the settings in the profile are applied to the card, unless you provide other fields to override them. For example, send the `shipmentMethod` to override the logistics company defined in the card configuration profile. + [JsonPropertyName("configurationProfileId")] + public string ConfigurationProfileId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActivationOption { get; private set; } + + /// + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + /// + /// Overrides the activation label design ID defined in the `configurationProfileId`. The activation label is attached to the card and contains the activation instructions. + [JsonPropertyName("activation")] + public string? Activation { get { return this._ActivationOption; } set { this._ActivationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActivationUrlOption { get; private set; } + + /// + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + /// + /// Your app's URL, if you want to activate cards through your app. For example, **my-app://ref1236a7d**. A QR code is created based on this URL, and is included in the carrier. Before you use this field, reach out to your Adyen contact to set up the QR code process. Maximum length: 255 characters. + [JsonPropertyName("activationUrl")] + public string? ActivationUrl { get { return this._ActivationUrlOption; } set { this._ActivationUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BulkAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bulkAddress")] + public BulkAddress? BulkAddress { get { return this._BulkAddressOption; } set { this._BulkAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardImageIdOption { get; private set; } + + /// + /// The ID of the card image. This is the image that will be printed on the full front of the card. + /// + /// The ID of the card image. This is the image that will be printed on the full front of the card. + [JsonPropertyName("cardImageId")] + public string? CardImageId { get { return this._CardImageIdOption; } set { this._CardImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierOption { get; private set; } + + /// + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + /// + /// Overrides the carrier design ID defined in the `configurationProfileId`. The carrier is the letter or packaging to which the card is attached. + [JsonPropertyName("carrier")] + public string? Carrier { get { return this._CarrierOption; } set { this._CarrierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierImageIdOption { get; private set; } + + /// + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + /// + /// The ID of the carrier image. This is the image that will printed on the letter to which the card is attached. + [JsonPropertyName("carrierImageId")] + public string? CarrierImageId { get { return this._CarrierImageIdOption; } set { this._CarrierImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + /// + /// The three-letter [ISO-4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of the card. For example, **EUR**. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnvelopeOption { get; private set; } + + /// + /// Overrides the envelope design ID defined in the `configurationProfileId`. + /// + /// Overrides the envelope design ID defined in the `configurationProfileId`. + [JsonPropertyName("envelope")] + public string? Envelope { get { return this._EnvelopeOption; } set { this._EnvelopeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InsertOption { get; private set; } + + /// + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + /// + /// Overrides the insert design ID defined in the `configurationProfileId`. An insert is any additional material, such as marketing materials, that are shipped together with the card. + [JsonPropertyName("insert")] + public string? Insert { get { return this._InsertOption; } set { this._InsertOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code of the card. For example, **en**. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LogoImageIdOption { get; private set; } + + /// + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + /// + /// The ID of the logo image. This is the image that will be printed on the partial front of the card, such as a logo on the upper right corner. + [JsonPropertyName("logoImageId")] + public string? LogoImageId { get { return this._LogoImageIdOption; } set { this._LogoImageIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PinMailerOption { get; private set; } + + /// + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + /// + /// Overrides the PIN mailer design ID defined in the `configurationProfileId`. The PIN mailer is the letter on which the PIN is printed. + [JsonPropertyName("pinMailer")] + public string? PinMailer { get { return this._PinMailerOption; } set { this._PinMailerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipmentMethodOption { get; private set; } + + /// + /// Overrides the logistics company defined in the `configurationProfileId`. + /// + /// Overrides the logistics company defined in the `configurationProfileId`. + [JsonPropertyName("shipmentMethod")] + public string? ShipmentMethod { get { return this._ShipmentMethodOption; } set { this._ShipmentMethodOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardConfiguration {\n"); + sb.Append(" ConfigurationProfileId: ").Append(ConfigurationProfileId).Append("\n"); + sb.Append(" Activation: ").Append(Activation).Append("\n"); + sb.Append(" ActivationUrl: ").Append(ActivationUrl).Append("\n"); + sb.Append(" BulkAddress: ").Append(BulkAddress).Append("\n"); + sb.Append(" CardImageId: ").Append(CardImageId).Append("\n"); + sb.Append(" Carrier: ").Append(Carrier).Append("\n"); + sb.Append(" CarrierImageId: ").Append(CarrierImageId).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Envelope: ").Append(Envelope).Append("\n"); + sb.Append(" Insert: ").Append(Insert).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" LogoImageId: ").Append(LogoImageId).Append("\n"); + sb.Append(" PinMailer: ").Append(PinMailer).Append("\n"); + sb.Append(" ShipmentMethod: ").Append(ShipmentMethod).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ActivationUrl (string) maxLength + if (this.ActivationUrl != null && this.ActivationUrl.Length > 255) + { + yield return new ValidationResult("Invalid value for ActivationUrl, length must be less than 255.", new [] { "ActivationUrl" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option configurationProfileId = default; + Option activation = default; + Option activationUrl = default; + Option bulkAddress = default; + Option cardImageId = default; + Option carrier = default; + Option carrierImageId = default; + Option currency = default; + Option envelope = default; + Option insert = default; + Option language = default; + Option logoImageId = default; + Option pinMailer = default; + Option shipmentMethod = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "configurationProfileId": + configurationProfileId = new Option(utf8JsonReader.GetString()!); + break; + case "activation": + activation = new Option(utf8JsonReader.GetString()!); + break; + case "activationUrl": + activationUrl = new Option(utf8JsonReader.GetString()!); + break; + case "bulkAddress": + bulkAddress = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardImageId": + cardImageId = new Option(utf8JsonReader.GetString()!); + break; + case "carrier": + carrier = new Option(utf8JsonReader.GetString()!); + break; + case "carrierImageId": + carrierImageId = new Option(utf8JsonReader.GetString()!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "envelope": + envelope = new Option(utf8JsonReader.GetString()!); + break; + case "insert": + insert = new Option(utf8JsonReader.GetString()!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "logoImageId": + logoImageId = new Option(utf8JsonReader.GetString()!); + break; + case "pinMailer": + pinMailer = new Option(utf8JsonReader.GetString()!); + break; + case "shipmentMethod": + shipmentMethod = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!configurationProfileId.IsSet) + throw new ArgumentException("Property is required for class CardConfiguration.", nameof(configurationProfileId)); + + return new CardConfiguration(configurationProfileId.Value!, activation, activationUrl, bulkAddress, cardImageId, carrier, carrierImageId, currency, envelope, insert, language, logoImageId, pinMailer, shipmentMethod); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardConfiguration cardConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardConfiguration cardConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardConfiguration.ConfigurationProfileId != null) + writer.WriteString("configurationProfileId", cardConfiguration.ConfigurationProfileId); + + if (cardConfiguration._ActivationOption.IsSet) + if (cardConfiguration.Activation != null) + writer.WriteString("activation", cardConfiguration.Activation); + + if (cardConfiguration._ActivationUrlOption.IsSet) + if (cardConfiguration.ActivationUrl != null) + writer.WriteString("activationUrl", cardConfiguration.ActivationUrl); + + if (cardConfiguration._BulkAddressOption.IsSet) + { + writer.WritePropertyName("bulkAddress"); + JsonSerializer.Serialize(writer, cardConfiguration.BulkAddress, jsonSerializerOptions); + } + if (cardConfiguration._CardImageIdOption.IsSet) + if (cardConfiguration.CardImageId != null) + writer.WriteString("cardImageId", cardConfiguration.CardImageId); + + if (cardConfiguration._CarrierOption.IsSet) + if (cardConfiguration.Carrier != null) + writer.WriteString("carrier", cardConfiguration.Carrier); + + if (cardConfiguration._CarrierImageIdOption.IsSet) + if (cardConfiguration.CarrierImageId != null) + writer.WriteString("carrierImageId", cardConfiguration.CarrierImageId); + + if (cardConfiguration._CurrencyOption.IsSet) + if (cardConfiguration.Currency != null) + writer.WriteString("currency", cardConfiguration.Currency); + + if (cardConfiguration._EnvelopeOption.IsSet) + if (cardConfiguration.Envelope != null) + writer.WriteString("envelope", cardConfiguration.Envelope); + + if (cardConfiguration._InsertOption.IsSet) + if (cardConfiguration.Insert != null) + writer.WriteString("insert", cardConfiguration.Insert); + + if (cardConfiguration._LanguageOption.IsSet) + if (cardConfiguration.Language != null) + writer.WriteString("language", cardConfiguration.Language); + + if (cardConfiguration._LogoImageIdOption.IsSet) + if (cardConfiguration.LogoImageId != null) + writer.WriteString("logoImageId", cardConfiguration.LogoImageId); + + if (cardConfiguration._PinMailerOption.IsSet) + if (cardConfiguration.PinMailer != null) + writer.WriteString("pinMailer", cardConfiguration.PinMailer); + + if (cardConfiguration._ShipmentMethodOption.IsSet) + if (cardConfiguration.ShipmentMethod != null) + writer.WriteString("shipmentMethod", cardConfiguration.ShipmentMethod); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CardOrderItem.cs b/Adyen/ConfigurationWebhooks/Models/CardOrderItem.cs new file mode 100644 index 000000000..6ad04e8ad --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CardOrderItem.cs @@ -0,0 +1,356 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CardOrderItem. + /// + public partial class CardOrderItem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// card + /// The unique identifier of the card order item. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + /// The unique identifier of the payment instrument related to the card order item. + /// pin + /// The shipping method used to deliver the card or the PIN. + [JsonConstructor] + public CardOrderItem(Option balancePlatform = default, Option card = default, Option cardOrderItemId = default, Option creationDate = default, Option id = default, Option paymentInstrumentId = default, Option pin = default, Option shippingMethod = default) + { + _BalancePlatformOption = balancePlatform; + _CardOption = card; + _CardOrderItemIdOption = cardOrderItemId; + _CreationDateOption = creationDate; + _IdOption = id; + _PaymentInstrumentIdOption = paymentInstrumentId; + _PinOption = pin; + _ShippingMethodOption = shippingMethod; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrderItem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public CardOrderItemDeliveryStatus? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOrderItemIdOption { get; private set; } + + /// + /// The unique identifier of the card order item. + /// + /// The unique identifier of the card order item. + [JsonPropertyName("cardOrderItemId")] + public string? CardOrderItemId { get { return this._CardOrderItemIdOption; } set { this._CardOrderItemIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument related to the card order item. + /// + /// The unique identifier of the payment instrument related to the card order item. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PinOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pin")] + public CardOrderItemDeliveryStatus? Pin { get { return this._PinOption; } set { this._PinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShippingMethodOption { get; private set; } + + /// + /// The shipping method used to deliver the card or the PIN. + /// + /// The shipping method used to deliver the card or the PIN. + [JsonPropertyName("shippingMethod")] + public string? ShippingMethod { get { return this._ShippingMethodOption; } set { this._ShippingMethodOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrderItem {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" CardOrderItemId: ").Append(CardOrderItemId).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Pin: ").Append(Pin).Append("\n"); + sb.Append(" ShippingMethod: ").Append(ShippingMethod).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderItemJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrderItem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option card = default; + Option cardOrderItemId = default; + Option creationDate = default; + Option id = default; + Option paymentInstrumentId = default; + Option pin = default; + Option shippingMethod = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardOrderItemId": + cardOrderItemId = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "pin": + pin = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shippingMethod": + shippingMethod = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardOrderItem(balancePlatform, card, cardOrderItemId, creationDate, id, paymentInstrumentId, pin, shippingMethod); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrderItem cardOrderItem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrderItem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrderItem cardOrderItem, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardOrderItem._BalancePlatformOption.IsSet) + if (cardOrderItem.BalancePlatform != null) + writer.WriteString("balancePlatform", cardOrderItem.BalancePlatform); + + if (cardOrderItem._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, cardOrderItem.Card, jsonSerializerOptions); + } + if (cardOrderItem._CardOrderItemIdOption.IsSet) + if (cardOrderItem.CardOrderItemId != null) + writer.WriteString("cardOrderItemId", cardOrderItem.CardOrderItemId); + + if (cardOrderItem._CreationDateOption.IsSet) + writer.WriteString("creationDate", cardOrderItem._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (cardOrderItem._IdOption.IsSet) + if (cardOrderItem.Id != null) + writer.WriteString("id", cardOrderItem.Id); + + if (cardOrderItem._PaymentInstrumentIdOption.IsSet) + if (cardOrderItem.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", cardOrderItem.PaymentInstrumentId); + + if (cardOrderItem._PinOption.IsSet) + { + writer.WritePropertyName("pin"); + JsonSerializer.Serialize(writer, cardOrderItem.Pin, jsonSerializerOptions); + } + if (cardOrderItem._ShippingMethodOption.IsSet) + if (cardOrderItem.ShippingMethod != null) + writer.WriteString("shippingMethod", cardOrderItem.ShippingMethod); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CardOrderItemDeliveryStatus.cs b/Adyen/ConfigurationWebhooks/Models/CardOrderItemDeliveryStatus.cs new file mode 100644 index 000000000..16f8112c5 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CardOrderItemDeliveryStatus.cs @@ -0,0 +1,387 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CardOrderItemDeliveryStatus. + /// + public partial class CardOrderItemDeliveryStatus : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An error message. + /// The status of the PIN delivery. + /// The tracking number of the PIN delivery. + [JsonConstructor] + public CardOrderItemDeliveryStatus(Option errorMessage = default, Option status = default, Option trackingNumber = default) + { + _ErrorMessageOption = errorMessage; + _StatusOption = status; + _TrackingNumberOption = trackingNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrderItemDeliveryStatus() + { + } + + partial void OnCreated(); + + /// + /// The status of the PIN delivery. + /// + /// The status of the PIN delivery. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Created - created + /// + public static readonly StatusEnum Created = new("created"); + + /// + /// StatusEnum.Delivered - delivered + /// + public static readonly StatusEnum Delivered = new("delivered"); + + /// + /// StatusEnum.NotApplicable - notApplicable + /// + public static readonly StatusEnum NotApplicable = new("notApplicable"); + + /// + /// StatusEnum.Processing - processing + /// + public static readonly StatusEnum Processing = new("processing"); + + /// + /// StatusEnum.Produced - produced + /// + public static readonly StatusEnum Produced = new("produced"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.Shipped - shipped + /// + public static readonly StatusEnum Shipped = new("shipped"); + + /// + /// StatusEnum.Unknown - unknown + /// + public static readonly StatusEnum Unknown = new("unknown"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "created" => StatusEnum.Created, + "delivered" => StatusEnum.Delivered, + "notApplicable" => StatusEnum.NotApplicable, + "processing" => StatusEnum.Processing, + "produced" => StatusEnum.Produced, + "rejected" => StatusEnum.Rejected, + "shipped" => StatusEnum.Shipped, + "unknown" => StatusEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Created) + return "created"; + + if (value == StatusEnum.Delivered) + return "delivered"; + + if (value == StatusEnum.NotApplicable) + return "notApplicable"; + + if (value == StatusEnum.Processing) + return "processing"; + + if (value == StatusEnum.Produced) + return "produced"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.Shipped) + return "shipped"; + + if (value == StatusEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the PIN delivery. + /// + /// The status of the PIN delivery. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorMessageOption { get; private set; } + + /// + /// An error message. + /// + /// An error message. + [JsonPropertyName("errorMessage")] + public string? ErrorMessage { get { return this._ErrorMessageOption; } set { this._ErrorMessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingNumberOption { get; private set; } + + /// + /// The tracking number of the PIN delivery. + /// + /// The tracking number of the PIN delivery. + [JsonPropertyName("trackingNumber")] + public string? TrackingNumber { get { return this._TrackingNumberOption; } set { this._TrackingNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrderItemDeliveryStatus {\n"); + sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TrackingNumber: ").Append(TrackingNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderItemDeliveryStatusJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrderItemDeliveryStatus Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorMessage = default; + Option status = default; + Option trackingNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorMessage": + errorMessage = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(CardOrderItemDeliveryStatus.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "trackingNumber": + trackingNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardOrderItemDeliveryStatus(errorMessage, status, trackingNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrderItemDeliveryStatus cardOrderItemDeliveryStatus, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrderItemDeliveryStatus, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrderItemDeliveryStatus cardOrderItemDeliveryStatus, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardOrderItemDeliveryStatus._ErrorMessageOption.IsSet) + if (cardOrderItemDeliveryStatus.ErrorMessage != null) + writer.WriteString("errorMessage", cardOrderItemDeliveryStatus.ErrorMessage); + + if (cardOrderItemDeliveryStatus._StatusOption.IsSet && cardOrderItemDeliveryStatus.Status != null) + { + string? statusRawValue = CardOrderItemDeliveryStatus.StatusEnum.ToJsonValue(cardOrderItemDeliveryStatus._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (cardOrderItemDeliveryStatus._TrackingNumberOption.IsSet) + if (cardOrderItemDeliveryStatus.TrackingNumber != null) + writer.WriteString("trackingNumber", cardOrderItemDeliveryStatus.TrackingNumber); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/CardOrderNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/CardOrderNotificationRequest.cs new file mode 100644 index 000000000..201d9af25 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/CardOrderNotificationRequest.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// CardOrderNotificationRequest. + /// + public partial class CardOrderNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public CardOrderNotificationRequest(CardOrderItem data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardOrderNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformCardorderCreated - balancePlatform.cardorder.created + /// + public static readonly TypeEnum BalancePlatformCardorderCreated = new("balancePlatform.cardorder.created"); + + /// + /// TypeEnum.BalancePlatformCardorderUpdated - balancePlatform.cardorder.updated + /// + public static readonly TypeEnum BalancePlatformCardorderUpdated = new("balancePlatform.cardorder.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.cardorder.created" => TypeEnum.BalancePlatformCardorderCreated, + "balancePlatform.cardorder.updated" => TypeEnum.BalancePlatformCardorderUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformCardorderCreated) + return "balancePlatform.cardorder.created"; + + if (value == TypeEnum.BalancePlatformCardorderUpdated) + return "balancePlatform.cardorder.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public CardOrderItem Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardOrderNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardOrderNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardOrderNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CardOrderNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class CardOrderNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class CardOrderNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CardOrderNotificationRequest.", nameof(type)); + + return new CardOrderNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardOrderNotificationRequest cardOrderNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardOrderNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardOrderNotificationRequest cardOrderNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, cardOrderNotificationRequest.Data, jsonSerializerOptions); + if (cardOrderNotificationRequest.Environment != null) + writer.WriteString("environment", cardOrderNotificationRequest.Environment); + + if (cardOrderNotificationRequest.Type != null) + { + string? typeRawValue = CardOrderNotificationRequest.TypeEnum.ToJsonValue(cardOrderNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (cardOrderNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", cardOrderNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/ContactDetails.cs b/Adyen/ConfigurationWebhooks/Models/ContactDetails.cs new file mode 100644 index 000000000..82b6b2a48 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/ContactDetails.cs @@ -0,0 +1,232 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// ContactDetails. + /// + public partial class ContactDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The email address of the account holder. + /// phone + /// The URL of the account holder's website. + [JsonConstructor] + public ContactDetails(Address address, string email, Phone phone, Option webAddress = default) + { + Address = address; + Email = email; + Phone = phone; + _WebAddressOption = webAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ContactDetails() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public Address Address { get; set; } + + /// + /// The email address of the account holder. + /// + /// The email address of the account holder. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public Phone Phone { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressOption { get; private set; } + + /// + /// The URL of the account holder's website. + /// + /// The URL of the account holder's website. + [JsonPropertyName("webAddress")] + public string? WebAddress { get { return this._WebAddressOption; } set { this._WebAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ContactDetails {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" WebAddress: ").Append(WebAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ContactDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ContactDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option email = default; + Option phone = default; + Option webAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webAddress": + webAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(address)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(email)); + + if (!phone.IsSet) + throw new ArgumentException("Property is required for class ContactDetails.", nameof(phone)); + + return new ContactDetails(address.Value!, email.Value!, phone.Value!, webAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ContactDetails contactDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, contactDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ContactDetails contactDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, contactDetails.Address, jsonSerializerOptions); + if (contactDetails.Email != null) + writer.WriteString("email", contactDetails.Email); + + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, contactDetails.Phone, jsonSerializerOptions); + if (contactDetails._WebAddressOption.IsSet) + if (contactDetails.WebAddress != null) + writer.WriteString("webAddress", contactDetails.WebAddress); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/DeliveryAddress.cs b/Adyen/ConfigurationWebhooks/Models/DeliveryAddress.cs new file mode 100644 index 000000000..a7aaa9600 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/DeliveryAddress.cs @@ -0,0 +1,321 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// DeliveryAddress. + /// + public partial class DeliveryAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The name of the city. + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + /// Additional information about the delivery address. + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + [JsonConstructor] + public DeliveryAddress(string country, Option city = default, Option line1 = default, Option line2 = default, Option line3 = default, Option postalCode = default, Option stateOrProvince = default) + { + Country = country; + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryAddress() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. >If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + /// + /// The name of the street. Do not include the number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **Simon Carmiggeltstraat**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + /// + /// The number of the building. For example, if the address is Simon Carmiggeltstraat 6-50, provide **6-50**. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Additional information about the delivery address. + /// + /// Additional information about the delivery address. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + /// + /// The state or province code, maximum 3 characters. For example, **CA** for California in the US or **ON** for Ontario in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryAddress {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class DeliveryAddress.", nameof(country)); + + return new DeliveryAddress(country.Value!, city, line1, line2, line3, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryAddress deliveryAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (deliveryAddress.Country != null) + writer.WriteString("country", deliveryAddress.Country); + + if (deliveryAddress._CityOption.IsSet) + if (deliveryAddress.City != null) + writer.WriteString("city", deliveryAddress.City); + + if (deliveryAddress._Line1Option.IsSet) + if (deliveryAddress.Line1 != null) + writer.WriteString("line1", deliveryAddress.Line1); + + if (deliveryAddress._Line2Option.IsSet) + if (deliveryAddress.Line2 != null) + writer.WriteString("line2", deliveryAddress.Line2); + + if (deliveryAddress._Line3Option.IsSet) + if (deliveryAddress.Line3 != null) + writer.WriteString("line3", deliveryAddress.Line3); + + if (deliveryAddress._PostalCodeOption.IsSet) + if (deliveryAddress.PostalCode != null) + writer.WriteString("postalCode", deliveryAddress.PostalCode); + + if (deliveryAddress._StateOrProvinceOption.IsSet) + if (deliveryAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", deliveryAddress.StateOrProvince); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/DeliveryContact.cs b/Adyen/ConfigurationWebhooks/Models/DeliveryContact.cs new file mode 100644 index 000000000..21607b6a2 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/DeliveryContact.cs @@ -0,0 +1,312 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// DeliveryContact. + /// + public partial class DeliveryContact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// name + /// The company name of the contact. + /// The email address of the contact. + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + /// phoneNumber + /// The URL of the contact's website. + [JsonConstructor] + public DeliveryContact(DeliveryAddress address, Name name, Option company = default, Option email = default, Option fullPhoneNumber = default, Option phoneNumber = default, Option webAddress = default) + { + Address = address; + Name = name; + _CompanyOption = company; + _EmailOption = email; + _FullPhoneNumberOption = fullPhoneNumber; + _PhoneNumberOption = phoneNumber; + _WebAddressOption = webAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeliveryContact() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public DeliveryAddress Address { get; set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name Name { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// The company name of the contact. + /// + /// The company name of the contact. + [JsonPropertyName("company")] + public string? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the contact. + /// + /// The email address of the contact. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullPhoneNumberOption { get; private set; } + + /// + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + /// + /// The full phone number of the contact provided as a single string. It will be handled as a landline phone. **Examples:** \"0031 6 11 22 33 44\", \"+316/1122-3344\", \"(0031) 611223344\" + [JsonPropertyName("fullPhoneNumber")] + public string? FullPhoneNumber { get { return this._FullPhoneNumberOption; } set { this._FullPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phoneNumber")] + public PhoneNumber? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressOption { get; private set; } + + /// + /// The URL of the contact's website. + /// + /// The URL of the contact's website. + [JsonPropertyName("webAddress")] + public string? WebAddress { get { return this._WebAddressOption; } set { this._WebAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeliveryContact {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FullPhoneNumber: ").Append(FullPhoneNumber).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" WebAddress: ").Append(WebAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeliveryContactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeliveryContact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option name = default; + Option company = default; + Option email = default; + Option fullPhoneNumber = default; + Option phoneNumber = default; + Option webAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "company": + company = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "fullPhoneNumber": + fullPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webAddress": + webAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class DeliveryContact.", nameof(address)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class DeliveryContact.", nameof(name)); + + return new DeliveryContact(address.Value!, name.Value!, company, email, fullPhoneNumber, phoneNumber, webAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeliveryContact deliveryContact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deliveryContact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeliveryContact deliveryContact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, deliveryContact.Address, jsonSerializerOptions); + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, deliveryContact.Name, jsonSerializerOptions); + if (deliveryContact._CompanyOption.IsSet) + if (deliveryContact.Company != null) + writer.WriteString("company", deliveryContact.Company); + + if (deliveryContact._EmailOption.IsSet) + if (deliveryContact.Email != null) + writer.WriteString("email", deliveryContact.Email); + + if (deliveryContact._FullPhoneNumberOption.IsSet) + if (deliveryContact.FullPhoneNumber != null) + writer.WriteString("fullPhoneNumber", deliveryContact.FullPhoneNumber); + + if (deliveryContact._PhoneNumberOption.IsSet) + { + writer.WritePropertyName("phoneNumber"); + JsonSerializer.Serialize(writer, deliveryContact.PhoneNumber, jsonSerializerOptions); + } + if (deliveryContact._WebAddressOption.IsSet) + if (deliveryContact.WebAddress != null) + writer.WriteString("webAddress", deliveryContact.WebAddress); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Device.cs b/Adyen/ConfigurationWebhooks/Models/Device.cs new file mode 100644 index 000000000..7f3f283d4 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Device.cs @@ -0,0 +1,227 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Device. + /// + public partial class Device : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the device used for provisioning the network token. + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc + /// The operating system of the device used for provisioning the network token. + [JsonConstructor] + public Device(Option deviceId = default, Option formFactor = default, Option osName = default) + { + _DeviceIdOption = deviceId; + _FormFactorOption = formFactor; + _OsNameOption = osName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Device() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceIdOption { get; private set; } + + /// + /// The unique identifier of the device used for provisioning the network token. + /// + /// The unique identifier of the device used for provisioning the network token. + [JsonPropertyName("deviceId")] + public string? DeviceId { get { return this._DeviceIdOption; } set { this._DeviceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FormFactorOption { get; private set; } + + /// + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc + /// + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc + [JsonPropertyName("formFactor")] + public string? FormFactor { get { return this._FormFactorOption; } set { this._FormFactorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsNameOption { get; private set; } + + /// + /// The operating system of the device used for provisioning the network token. + /// + /// The operating system of the device used for provisioning the network token. + [JsonPropertyName("osName")] + public string? OsName { get { return this._OsNameOption; } set { this._OsNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Device {\n"); + sb.Append(" DeviceId: ").Append(DeviceId).Append("\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" OsName: ").Append(OsName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Device Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option deviceId = default; + Option formFactor = default; + Option osName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "deviceId": + deviceId = new Option(utf8JsonReader.GetString()!); + break; + case "formFactor": + formFactor = new Option(utf8JsonReader.GetString()!); + break; + case "osName": + osName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Device(deviceId, formFactor, osName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Device device, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, device, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Device device, JsonSerializerOptions jsonSerializerOptions) + { + + if (device._DeviceIdOption.IsSet) + if (device.DeviceId != null) + writer.WriteString("deviceId", device.DeviceId); + + if (device._FormFactorOption.IsSet) + if (device.FormFactor != null) + writer.WriteString("formFactor", device.FormFactor); + + if (device._OsNameOption.IsSet) + if (device.OsName != null) + writer.WriteString("osName", device.OsName); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Expiry.cs b/Adyen/ConfigurationWebhooks/Models/Expiry.cs new file mode 100644 index 000000000..265ca79b7 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Expiry.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Expiry. + /// + public partial class Expiry : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The month in which the card will expire. + /// The year in which the card will expire. + [JsonConstructor] + public Expiry(Option month = default, Option year = default) + { + _MonthOption = month; + _YearOption = year; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Expiry() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MonthOption { get; private set; } + + /// + /// The month in which the card will expire. + /// + /// The month in which the card will expire. + [JsonPropertyName("month")] + public string? Month { get { return this._MonthOption; } set { this._MonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _YearOption { get; private set; } + + /// + /// The year in which the card will expire. + /// + /// The year in which the card will expire. + [JsonPropertyName("year")] + public string? Year { get { return this._YearOption; } set { this._YearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Expiry {\n"); + sb.Append(" Month: ").Append(Month).Append("\n"); + sb.Append(" Year: ").Append(Year).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExpiryJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Expiry Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option month = default; + Option year = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "month": + month = new Option(utf8JsonReader.GetString()!); + break; + case "year": + year = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Expiry(month, year); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Expiry expiry, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, expiry, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Expiry expiry, JsonSerializerOptions jsonSerializerOptions) + { + + if (expiry._MonthOption.IsSet) + if (expiry.Month != null) + writer.WriteString("month", expiry.Month); + + if (expiry._YearOption.IsSet) + if (expiry.Year != null) + writer.WriteString("year", expiry.Year); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/IbanAccountIdentification.cs b/Adyen/ConfigurationWebhooks/Models/IbanAccountIdentification.cs new file mode 100644 index 000000000..3e3899677 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/IbanAccountIdentification.cs @@ -0,0 +1,289 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// IbanAccountIdentification. + /// + public partial class IbanAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// **iban** (default to TypeEnum.Iban) + [JsonConstructor] + public IbanAccountIdentification(string iban, TypeEnum type = default) + { + Iban = iban; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **iban** + /// + /// **iban** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Iban - iban + /// + public static readonly TypeEnum Iban = new("iban"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "iban" => TypeEnum.Iban, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Iban) + return "iban"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **iban** + /// + /// **iban** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentification {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(iban)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(type)); + + return new IbanAccountIdentification(iban.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentification.Iban != null) + writer.WriteString("iban", ibanAccountIdentification.Iban); + + if (ibanAccountIdentification.Type != null) + { + string? typeRawValue = IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Name.cs b/Adyen/ConfigurationWebhooks/Models/Name.cs new file mode 100644 index 000000000..650c23495 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationDataV2.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationDataV2.cs new file mode 100644 index 000000000..464854354 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationDataV2.cs @@ -0,0 +1,503 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenNotificationDataV2. + /// + public partial class NetworkTokenNotificationDataV2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// authentication + /// Specifies whether the authentication process was triggered during token provisioning. + /// The unique identifier of the balance platform. + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**. + /// The unique identifier of the network token. + /// The unique identifier of the payment instrument to which the network token is associated. + /// The confidence score of scheme, indicating the degree of risk associated with a token. A high score indicates a high level of risk. A low score indicates a low level of risk. Possible values for visa : **00** to **99**, a value of 00 signifies no score was provided by visa + /// The status of the network token. + /// The last four digits of the network token. Use this value to help your user to identify their network token. + /// tokenRequestor + /// transactionRulesResult + /// The type of network token. Possible values: **wallet**, **cof**. + /// The rules used to validate the request for provisioning the network token. + /// wallet + [JsonConstructor] + public NetworkTokenNotificationDataV2(Option authentication = default, Option authenticationApplied = default, Option balancePlatform = default, Option decision = default, Option id = default, Option paymentInstrumentId = default, Option schemeRiskScore = default, Option status = default, Option tokenLastFour = default, Option tokenRequestor = default, Option transactionRulesResult = default, Option type = default, Option?> validationFacts = default, Option wallet = default) + { + _AuthenticationOption = authentication; + _AuthenticationAppliedOption = authenticationApplied; + _BalancePlatformOption = balancePlatform; + _DecisionOption = decision; + _IdOption = id; + _PaymentInstrumentIdOption = paymentInstrumentId; + _SchemeRiskScoreOption = schemeRiskScore; + _StatusOption = status; + _TokenLastFourOption = tokenLastFour; + _TokenRequestorOption = tokenRequestor; + _TransactionRulesResultOption = transactionRulesResult; + _TypeOption = type; + _ValidationFactsOption = validationFacts; + _WalletOption = wallet; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenNotificationDataV2() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("authentication")] + public TokenAuthentication? Authentication { get { return this._AuthenticationOption; } set { this._AuthenticationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationAppliedOption { get; private set; } + + /// + /// Specifies whether the authentication process was triggered during token provisioning. + /// + /// Specifies whether the authentication process was triggered during token provisioning. + [JsonPropertyName("authenticationApplied")] + public bool? AuthenticationApplied { get { return this._AuthenticationAppliedOption; } set { this._AuthenticationAppliedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DecisionOption { get; private set; } + + /// + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**. + /// + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**. + [JsonPropertyName("decision")] + public string? Decision { get { return this._DecisionOption; } set { this._DecisionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the network token. + /// + /// The unique identifier of the network token. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument to which the network token is associated. + /// + /// The unique identifier of the payment instrument to which the network token is associated. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeRiskScoreOption { get; private set; } + + /// + /// The confidence score of scheme, indicating the degree of risk associated with a token. A high score indicates a high level of risk. A low score indicates a low level of risk. Possible values for visa : **00** to **99**, a value of 00 signifies no score was provided by visa + /// + /// The confidence score of scheme, indicating the degree of risk associated with a token. A high score indicates a high level of risk. A low score indicates a low level of risk. Possible values for visa : **00** to **99**, a value of 00 signifies no score was provided by visa + [JsonPropertyName("schemeRiskScore")] + public string? SchemeRiskScore { get { return this._SchemeRiskScoreOption; } set { this._SchemeRiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the network token. + /// + /// The status of the network token. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenLastFourOption { get; private set; } + + /// + /// The last four digits of the network token. Use this value to help your user to identify their network token. + /// + /// The last four digits of the network token. Use this value to help your user to identify their network token. + [JsonPropertyName("tokenLastFour")] + public string? TokenLastFour { get { return this._TokenLastFourOption; } set { this._TokenLastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenRequestorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenRequestor")] + public NetworkTokenRequestor? TokenRequestor { get { return this._TokenRequestorOption; } set { this._TokenRequestorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRulesResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRulesResult")] + public NetworkTokenTransactionRulesResult? TransactionRulesResult { get { return this._TransactionRulesResultOption; } set { this._TransactionRulesResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of network token. Possible values: **wallet**, **cof**. + /// + /// The type of network token. Possible values: **wallet**, **cof**. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValidationFactsOption { get; private set; } + + /// + /// The rules used to validate the request for provisioning the network token. + /// + /// The rules used to validate the request for provisioning the network token. + [JsonPropertyName("validationFacts")] + public List? ValidationFacts { get { return this._ValidationFactsOption; } set { this._ValidationFactsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wallet")] + public Wallet? Wallet { get { return this._WalletOption; } set { this._WalletOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenNotificationDataV2 {\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" AuthenticationApplied: ").Append(AuthenticationApplied).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Decision: ").Append(Decision).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" SchemeRiskScore: ").Append(SchemeRiskScore).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TokenLastFour: ").Append(TokenLastFour).Append("\n"); + sb.Append(" TokenRequestor: ").Append(TokenRequestor).Append("\n"); + sb.Append(" TransactionRulesResult: ").Append(TransactionRulesResult).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); + sb.Append(" Wallet: ").Append(Wallet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenNotificationDataV2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenNotificationDataV2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authentication = default; + Option authenticationApplied = default; + Option balancePlatform = default; + Option decision = default; + Option id = default; + Option paymentInstrumentId = default; + Option schemeRiskScore = default; + Option status = default; + Option tokenLastFour = default; + Option tokenRequestor = default; + Option transactionRulesResult = default; + Option type = default; + Option?> validationFacts = default; + Option wallet = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authentication": + authentication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authenticationApplied": + authenticationApplied = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "decision": + decision = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "schemeRiskScore": + schemeRiskScore = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "tokenLastFour": + tokenLastFour = new Option(utf8JsonReader.GetString()!); + break; + case "tokenRequestor": + tokenRequestor = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRulesResult": + transactionRulesResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "validationFacts": + validationFacts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wallet": + wallet = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new NetworkTokenNotificationDataV2(authentication, authenticationApplied, balancePlatform, decision, id, paymentInstrumentId, schemeRiskScore, status, tokenLastFour, tokenRequestor, transactionRulesResult, type, validationFacts, wallet); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenNotificationDataV2 networkTokenNotificationDataV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenNotificationDataV2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenNotificationDataV2 networkTokenNotificationDataV2, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenNotificationDataV2._AuthenticationOption.IsSet) + { + writer.WritePropertyName("authentication"); + JsonSerializer.Serialize(writer, networkTokenNotificationDataV2.Authentication, jsonSerializerOptions); + } + if (networkTokenNotificationDataV2._AuthenticationAppliedOption.IsSet) + writer.WriteBoolean("authenticationApplied", networkTokenNotificationDataV2._AuthenticationAppliedOption.Value!.Value); + + if (networkTokenNotificationDataV2._BalancePlatformOption.IsSet) + if (networkTokenNotificationDataV2.BalancePlatform != null) + writer.WriteString("balancePlatform", networkTokenNotificationDataV2.BalancePlatform); + + if (networkTokenNotificationDataV2._DecisionOption.IsSet) + if (networkTokenNotificationDataV2.Decision != null) + writer.WriteString("decision", networkTokenNotificationDataV2.Decision); + + if (networkTokenNotificationDataV2._IdOption.IsSet) + if (networkTokenNotificationDataV2.Id != null) + writer.WriteString("id", networkTokenNotificationDataV2.Id); + + if (networkTokenNotificationDataV2._PaymentInstrumentIdOption.IsSet) + if (networkTokenNotificationDataV2.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", networkTokenNotificationDataV2.PaymentInstrumentId); + + if (networkTokenNotificationDataV2._SchemeRiskScoreOption.IsSet) + if (networkTokenNotificationDataV2.SchemeRiskScore != null) + writer.WriteString("schemeRiskScore", networkTokenNotificationDataV2.SchemeRiskScore); + + if (networkTokenNotificationDataV2._StatusOption.IsSet) + if (networkTokenNotificationDataV2.Status != null) + writer.WriteString("status", networkTokenNotificationDataV2.Status); + + if (networkTokenNotificationDataV2._TokenLastFourOption.IsSet) + if (networkTokenNotificationDataV2.TokenLastFour != null) + writer.WriteString("tokenLastFour", networkTokenNotificationDataV2.TokenLastFour); + + if (networkTokenNotificationDataV2._TokenRequestorOption.IsSet) + { + writer.WritePropertyName("tokenRequestor"); + JsonSerializer.Serialize(writer, networkTokenNotificationDataV2.TokenRequestor, jsonSerializerOptions); + } + if (networkTokenNotificationDataV2._TransactionRulesResultOption.IsSet) + { + writer.WritePropertyName("transactionRulesResult"); + JsonSerializer.Serialize(writer, networkTokenNotificationDataV2.TransactionRulesResult, jsonSerializerOptions); + } + if (networkTokenNotificationDataV2._TypeOption.IsSet) + if (networkTokenNotificationDataV2.Type != null) + writer.WriteString("type", networkTokenNotificationDataV2.Type); + + if (networkTokenNotificationDataV2._ValidationFactsOption.IsSet) + { + writer.WritePropertyName("validationFacts"); + JsonSerializer.Serialize(writer, networkTokenNotificationDataV2.ValidationFacts, jsonSerializerOptions); + } + if (networkTokenNotificationDataV2._WalletOption.IsSet) + { + writer.WritePropertyName("wallet"); + JsonSerializer.Serialize(writer, networkTokenNotificationDataV2.Wallet, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationRequest.cs new file mode 100644 index 000000000..b88ed2139 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenNotificationRequest.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenNotificationRequest. + /// + public partial class NetworkTokenNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The type of webhook. + /// When the event was queued. + [JsonConstructor] + public NetworkTokenNotificationRequest(NetworkTokenNotificationDataV2 data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformNetworkTokenCreated - balancePlatform.networkToken.created + /// + public static readonly TypeEnum BalancePlatformNetworkTokenCreated = new("balancePlatform.networkToken.created"); + + /// + /// TypeEnum.BalancePlatformNetworkTokenUpdated - balancePlatform.networkToken.updated + /// + public static readonly TypeEnum BalancePlatformNetworkTokenUpdated = new("balancePlatform.networkToken.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.networkToken.created" => TypeEnum.BalancePlatformNetworkTokenCreated, + "balancePlatform.networkToken.updated" => TypeEnum.BalancePlatformNetworkTokenUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformNetworkTokenCreated) + return "balancePlatform.networkToken.created"; + + if (value == TypeEnum.BalancePlatformNetworkTokenUpdated) + return "balancePlatform.networkToken.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public NetworkTokenNotificationDataV2 Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NetworkTokenNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class NetworkTokenNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class NetworkTokenNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NetworkTokenNotificationRequest.", nameof(type)); + + return new NetworkTokenNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenNotificationRequest networkTokenNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenNotificationRequest networkTokenNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, networkTokenNotificationRequest.Data, jsonSerializerOptions); + if (networkTokenNotificationRequest.Environment != null) + writer.WriteString("environment", networkTokenNotificationRequest.Environment); + + if (networkTokenNotificationRequest.Type != null) + { + string? typeRawValue = NetworkTokenNotificationRequest.TypeEnum.ToJsonValue(networkTokenNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (networkTokenNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", networkTokenNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenRequestor.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRequestor.cs new file mode 100644 index 000000000..463eb505d --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRequestor.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenRequestor. + /// + public partial class NetworkTokenRequestor : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the network token requestor. + /// The name of the network token requestor. + [JsonConstructor] + public NetworkTokenRequestor(Option id = default, Option name = default) + { + _IdOption = id; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenRequestor() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the network token requestor. + /// + /// The unique identifier of the network token requestor. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the network token requestor. + /// + /// The name of the network token requestor. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenRequestor {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenRequestorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenRequestor Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkTokenRequestor(id, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenRequestor networkTokenRequestor, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenRequestor, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenRequestor networkTokenRequestor, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenRequestor._IdOption.IsSet) + if (networkTokenRequestor.Id != null) + writer.WriteString("id", networkTokenRequestor.Id); + + if (networkTokenRequestor._NameOption.IsSet) + if (networkTokenRequestor.Name != null) + writer.WriteString("name", networkTokenRequestor.Name); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleData.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleData.cs new file mode 100644 index 000000000..8f7f168fc --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleData.cs @@ -0,0 +1,276 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenRiskRuleData. + /// + public partial class NetworkTokenRiskRuleData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the transaction rule. + /// The unique identifier of the transaction rule. + /// The outcome type of the transaction rule. + /// The reference for the transaction rule. + /// The transaction score determined by the rule. + [JsonConstructor] + public NetworkTokenRiskRuleData(Option description = default, Option id = default, Option outcomeType = default, Option reference = default, Option score = default) + { + _DescriptionOption = description; + _IdOption = id; + _OutcomeTypeOption = outcomeType; + _ReferenceOption = reference; + _ScoreOption = score; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenRiskRuleData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the transaction rule. + /// + /// The description of the transaction rule. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the transaction rule. + /// + /// The unique identifier of the transaction rule. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutcomeTypeOption { get; private set; } + + /// + /// The outcome type of the transaction rule. + /// + /// The outcome type of the transaction rule. + [JsonPropertyName("outcomeType")] + public string? OutcomeType { get { return this._OutcomeTypeOption; } set { this._OutcomeTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the transaction rule. + /// + /// The reference for the transaction rule. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The transaction score determined by the rule. + /// + /// The transaction score determined by the rule. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenRiskRuleData {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" OutcomeType: ").Append(OutcomeType).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenRiskRuleDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenRiskRuleData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option outcomeType = default; + Option reference = default; + Option score = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "outcomeType": + outcomeType = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new NetworkTokenRiskRuleData(description, id, outcomeType, reference, score); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenRiskRuleData networkTokenRiskRuleData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenRiskRuleData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenRiskRuleData networkTokenRiskRuleData, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenRiskRuleData._DescriptionOption.IsSet) + if (networkTokenRiskRuleData.Description != null) + writer.WriteString("description", networkTokenRiskRuleData.Description); + + if (networkTokenRiskRuleData._IdOption.IsSet) + if (networkTokenRiskRuleData.Id != null) + writer.WriteString("id", networkTokenRiskRuleData.Id); + + if (networkTokenRiskRuleData._OutcomeTypeOption.IsSet) + if (networkTokenRiskRuleData.OutcomeType != null) + writer.WriteString("outcomeType", networkTokenRiskRuleData.OutcomeType); + + if (networkTokenRiskRuleData._ReferenceOption.IsSet) + if (networkTokenRiskRuleData.Reference != null) + writer.WriteString("reference", networkTokenRiskRuleData.Reference); + + if (networkTokenRiskRuleData._ScoreOption.IsSet) + writer.WriteNumber("score", networkTokenRiskRuleData._ScoreOption.Value!.Value); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleSource.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleSource.cs new file mode 100644 index 000000000..44f5e9fbd --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenRiskRuleSource.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenRiskRuleSource. + /// + public partial class NetworkTokenRiskRuleSource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource to which the transaction rule applies. + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonConstructor] + public NetworkTokenRiskRuleSource(Option id = default, Option type = default) + { + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenRiskRuleSource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource to which the transaction rule applies. + /// + /// The unique identifier of the resource to which the transaction rule applies. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenRiskRuleSource {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenRiskRuleSourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenRiskRuleSource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NetworkTokenRiskRuleSource(id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenRiskRuleSource networkTokenRiskRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenRiskRuleSource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenRiskRuleSource networkTokenRiskRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenRiskRuleSource._IdOption.IsSet) + if (networkTokenRiskRuleSource.Id != null) + writer.WriteString("id", networkTokenRiskRuleSource.Id); + + if (networkTokenRiskRuleSource._TypeOption.IsSet) + if (networkTokenRiskRuleSource.Type != null) + writer.WriteString("type", networkTokenRiskRuleSource.Type); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenTransactionRulesResult.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenTransactionRulesResult.cs new file mode 100644 index 000000000..eab83f5e6 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenTransactionRulesResult.cs @@ -0,0 +1,252 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenTransactionRulesResult. + /// + public partial class NetworkTokenTransactionRulesResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The advice given by the Risk analysis. + /// Indicates whether the transaction passed all rules with `outcomeType` **hardBlock**. + /// The score of the Risk analysis. + /// Contains a list of all triggered transaction rules and the corresponding data. + [JsonConstructor] + public NetworkTokenTransactionRulesResult(Option advice = default, Option allHardBlockRulesPassed = default, Option score = default, Option?> triggeredTransactionRules = default) + { + _AdviceOption = advice; + _AllHardBlockRulesPassedOption = allHardBlockRulesPassed; + _ScoreOption = score; + _TriggeredTransactionRulesOption = triggeredTransactionRules; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenTransactionRulesResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdviceOption { get; private set; } + + /// + /// The advice given by the Risk analysis. + /// + /// The advice given by the Risk analysis. + [JsonPropertyName("advice")] + public string? Advice { get { return this._AdviceOption; } set { this._AdviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllHardBlockRulesPassedOption { get; private set; } + + /// + /// Indicates whether the transaction passed all rules with `outcomeType` **hardBlock**. + /// + /// Indicates whether the transaction passed all rules with `outcomeType` **hardBlock**. + [JsonPropertyName("allHardBlockRulesPassed")] + public bool? AllHardBlockRulesPassed { get { return this._AllHardBlockRulesPassedOption; } set { this._AllHardBlockRulesPassedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The score of the Risk analysis. + /// + /// The score of the Risk analysis. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TriggeredTransactionRulesOption { get; private set; } + + /// + /// Contains a list of all triggered transaction rules and the corresponding data. + /// + /// Contains a list of all triggered transaction rules and the corresponding data. + [JsonPropertyName("triggeredTransactionRules")] + public List? TriggeredTransactionRules { get { return this._TriggeredTransactionRulesOption; } set { this._TriggeredTransactionRulesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenTransactionRulesResult {\n"); + sb.Append(" Advice: ").Append(Advice).Append("\n"); + sb.Append(" AllHardBlockRulesPassed: ").Append(AllHardBlockRulesPassed).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append(" TriggeredTransactionRules: ").Append(TriggeredTransactionRules).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenTransactionRulesResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenTransactionRulesResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option advice = default; + Option allHardBlockRulesPassed = default; + Option score = default; + Option?> triggeredTransactionRules = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "advice": + advice = new Option(utf8JsonReader.GetString()!); + break; + case "allHardBlockRulesPassed": + allHardBlockRulesPassed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "triggeredTransactionRules": + triggeredTransactionRules = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new NetworkTokenTransactionRulesResult(advice, allHardBlockRulesPassed, score, triggeredTransactionRules); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenTransactionRulesResult networkTokenTransactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenTransactionRulesResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenTransactionRulesResult networkTokenTransactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenTransactionRulesResult._AdviceOption.IsSet) + if (networkTokenTransactionRulesResult.Advice != null) + writer.WriteString("advice", networkTokenTransactionRulesResult.Advice); + + if (networkTokenTransactionRulesResult._AllHardBlockRulesPassedOption.IsSet) + writer.WriteBoolean("allHardBlockRulesPassed", networkTokenTransactionRulesResult._AllHardBlockRulesPassedOption.Value!.Value); + + if (networkTokenTransactionRulesResult._ScoreOption.IsSet) + writer.WriteNumber("score", networkTokenTransactionRulesResult._ScoreOption.Value!.Value); + + if (networkTokenTransactionRulesResult._TriggeredTransactionRulesOption.IsSet) + { + writer.WritePropertyName("triggeredTransactionRules"); + JsonSerializer.Serialize(writer, networkTokenTransactionRulesResult.TriggeredTransactionRules, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/NetworkTokenTriggeredRiskRule.cs b/Adyen/ConfigurationWebhooks/Models/NetworkTokenTriggeredRiskRule.cs new file mode 100644 index 000000000..c3cd61403 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/NetworkTokenTriggeredRiskRule.cs @@ -0,0 +1,228 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// NetworkTokenTriggeredRiskRule. + /// + public partial class NetworkTokenTriggeredRiskRule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Explains why the transaction rule failed. + /// transactionRule + /// transactionRuleSource + [JsonConstructor] + public NetworkTokenTriggeredRiskRule(Option reason = default, Option transactionRule = default, Option transactionRuleSource = default) + { + _ReasonOption = reason; + _TransactionRuleOption = transactionRule; + _TransactionRuleSourceOption = transactionRuleSource; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NetworkTokenTriggeredRiskRule() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// Explains why the transaction rule failed. + /// + /// Explains why the transaction rule failed. + [JsonPropertyName("reason")] + public string? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRule")] + public NetworkTokenRiskRuleData? TransactionRule { get { return this._TransactionRuleOption; } set { this._TransactionRuleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRuleSource")] + public NetworkTokenRiskRuleSource? TransactionRuleSource { get { return this._TransactionRuleSourceOption; } set { this._TransactionRuleSourceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenTriggeredRiskRule {\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" TransactionRule: ").Append(TransactionRule).Append("\n"); + sb.Append(" TransactionRuleSource: ").Append(TransactionRuleSource).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NetworkTokenTriggeredRiskRuleJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NetworkTokenTriggeredRiskRule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reason = default; + Option transactionRule = default; + Option transactionRuleSource = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reason": + reason = new Option(utf8JsonReader.GetString()!); + break; + case "transactionRule": + transactionRule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRuleSource": + transactionRuleSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new NetworkTokenTriggeredRiskRule(reason, transactionRule, transactionRuleSource); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NetworkTokenTriggeredRiskRule networkTokenTriggeredRiskRule, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, networkTokenTriggeredRiskRule, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NetworkTokenTriggeredRiskRule networkTokenTriggeredRiskRule, JsonSerializerOptions jsonSerializerOptions) + { + + if (networkTokenTriggeredRiskRule._ReasonOption.IsSet) + if (networkTokenTriggeredRiskRule.Reason != null) + writer.WriteString("reason", networkTokenTriggeredRiskRule.Reason); + + if (networkTokenTriggeredRiskRule._TransactionRuleOption.IsSet) + { + writer.WritePropertyName("transactionRule"); + JsonSerializer.Serialize(writer, networkTokenTriggeredRiskRule.TransactionRule, jsonSerializerOptions); + } + if (networkTokenTriggeredRiskRule._TransactionRuleSourceOption.IsSet) + { + writer.WritePropertyName("transactionRuleSource"); + JsonSerializer.Serialize(writer, networkTokenTriggeredRiskRule.TransactionRuleSource, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PaymentInstrument.cs b/Adyen/ConfigurationWebhooks/Models/PaymentInstrument.cs new file mode 100644 index 000000000..d8801f1b0 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PaymentInstrument.cs @@ -0,0 +1,920 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PaymentInstrument. + /// + public partial class PaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// The unique identifier of the payment instrument. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// bankAccount + /// card + /// Your description for the payment instrument, maximum 300 characters. + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// Your reference for the payment instrument, maximum 150 characters. + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// The status comment provides additional information for the statusReason of the payment instrument. + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConstructor] + public PaymentInstrument(string balanceAccountId, string id, string issuingCountryCode, TypeEnum type, Option?> additionalBankAccountIdentifications = default, Option bankAccount = default, Option card = default, Option description = default, Option paymentInstrumentGroupId = default, Option reference = default, Option replacedById = default, Option replacementOfId = default, Option status = default, Option statusComment = default, Option statusReason = default) + { + BalanceAccountId = balanceAccountId; + Id = id; + IssuingCountryCode = issuingCountryCode; + Type = type; + _AdditionalBankAccountIdentificationsOption = additionalBankAccountIdentifications; + _BankAccountOption = bankAccount; + _CardOption = card; + _DescriptionOption = description; + _PaymentInstrumentGroupIdOption = paymentInstrumentGroupId; + _ReferenceOption = reference; + _ReplacedByIdOption = replacedById; + _ReplacementOfIdOption = replacementOfId; + _StatusOption = status; + _StatusCommentOption = statusComment; + _StatusReasonOption = statusReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.Card - card + /// + public static readonly TypeEnum Card = new("card"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "card" => TypeEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.Card) + return "card"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + /// + /// The type of payment instrument. Possible values: **card**, **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + /// + /// StatusEnum.Suspended - suspended + /// + public static readonly StatusEnum Suspended = new("suspended"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + "suspended" => StatusEnum.Suspended, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + if (value == StatusEnum.Suspended) + return "suspended"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + /// + /// The status of the payment instrument. If a status is not specified when creating a payment instrument, it is set to **active** by default. However, there can be exceptions for cards based on the `card.formFactor` and the `issuingCountryCode`. For example, when issuing physical cards in the US, the default status is **inactive**. Possible values: * **active**: The payment instrument is active and can be used to make payments. * **inactive**: The payment instrument is inactive and cannot be used to make payments. * **suspended**: The payment instrument is suspended, either because it was stolen or lost. * **closed**: The payment instrument is permanently closed. This action cannot be undone. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonConverter(typeof(StatusReasonEnumJsonConverter))] + public class StatusReasonEnum : IEnum + { + /// + /// Returns the value of the StatusReasonEnum. + /// + public string? Value { get; set; } + + /// + /// StatusReasonEnum.AccountClosure - accountClosure + /// + public static readonly StatusReasonEnum AccountClosure = new("accountClosure"); + + /// + /// StatusReasonEnum.Damaged - damaged + /// + public static readonly StatusReasonEnum Damaged = new("damaged"); + + /// + /// StatusReasonEnum.EndOfLife - endOfLife + /// + public static readonly StatusReasonEnum EndOfLife = new("endOfLife"); + + /// + /// StatusReasonEnum.Expired - expired + /// + public static readonly StatusReasonEnum Expired = new("expired"); + + /// + /// StatusReasonEnum.Lost - lost + /// + public static readonly StatusReasonEnum Lost = new("lost"); + + /// + /// StatusReasonEnum.Other - other + /// + public static readonly StatusReasonEnum Other = new("other"); + + /// + /// StatusReasonEnum.Stolen - stolen + /// + public static readonly StatusReasonEnum Stolen = new("stolen"); + + /// + /// StatusReasonEnum.SuspectedFraud - suspectedFraud + /// + public static readonly StatusReasonEnum SuspectedFraud = new("suspectedFraud"); + + /// + /// StatusReasonEnum.TransactionRule - transactionRule + /// + public static readonly StatusReasonEnum TransactionRule = new("transactionRule"); + + private StatusReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusReasonEnum?(string? value) => value == null ? null : new StatusReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusReasonEnum? option) => option?.Value; + + public static bool operator ==(StatusReasonEnum? left, StatusReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusReasonEnum? left, StatusReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountClosure" => StatusReasonEnum.AccountClosure, + "damaged" => StatusReasonEnum.Damaged, + "endOfLife" => StatusReasonEnum.EndOfLife, + "expired" => StatusReasonEnum.Expired, + "lost" => StatusReasonEnum.Lost, + "other" => StatusReasonEnum.Other, + "stolen" => StatusReasonEnum.Stolen, + "suspectedFraud" => StatusReasonEnum.SuspectedFraud, + "transactionRule" => StatusReasonEnum.TransactionRule, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusReasonEnum? value) + { + if (value == null) + return null; + + if (value == StatusReasonEnum.AccountClosure) + return "accountClosure"; + + if (value == StatusReasonEnum.Damaged) + return "damaged"; + + if (value == StatusReasonEnum.EndOfLife) + return "endOfLife"; + + if (value == StatusReasonEnum.Expired) + return "expired"; + + if (value == StatusReasonEnum.Lost) + return "lost"; + + if (value == StatusReasonEnum.Other) + return "other"; + + if (value == StatusReasonEnum.Stolen) + return "stolen"; + + if (value == StatusReasonEnum.SuspectedFraud) + return "suspectedFraud"; + + if (value == StatusReasonEnum.TransactionRule) + return "transactionRule"; + + return null; + } + + /// + /// JsonConverter for writing StatusReasonEnum. + /// + public class StatusReasonEnumJsonConverter : JsonConverter + { + public override StatusReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusReasonEnum.FromStringOrDefault(value) ?? new StatusReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusReasonOption { get; private set; } + + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + /// + /// The reason for the status of the payment instrument. Possible values: **accountClosure**, **damaged**, **endOfLife**, **expired**, **lost**, **stolen**, **suspectedFraud**, **transactionRule**, **other**. If the reason is **other**, you must also send the `statusComment` parameter describing the status change. + [JsonPropertyName("statusReason")] + public StatusReasonEnum? StatusReason { get { return this._StatusReasonOption; } set { this._StatusReasonOption = new(value); } } + + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + /// + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/balanceAccounts__resParam_id) associated with the payment instrument. + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// The unique identifier of the payment instrument. + /// + /// The unique identifier of the payment instrument. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the payment instrument is issued. For example, **NL** or **US**. + [JsonPropertyName("issuingCountryCode")] + public string IssuingCountryCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalBankAccountIdentificationsOption { get; private set; } + + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + /// + /// Contains optional, additional business account details. Returned when you create a payment instrument with `type` **bankAccount**. + [JsonPropertyName("additionalBankAccountIdentifications")] + [Obsolete("Deprecated since Configuration webhooks v2. Please use `bankAccount` object instead")] + public List? AdditionalBankAccountIdentifications { get { return this._AdditionalBankAccountIdentificationsOption; } set { this._AdditionalBankAccountIdentificationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountDetails? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the payment instrument, maximum 300 characters. + /// + /// Your description for the payment instrument, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentGroupIdOption { get; private set; } + + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + /// + /// The unique identifier of the [payment instrument group](https://docs.adyen.com/api-explorer/#/balanceplatform/v1/post/paymentInstrumentGroups__resParam_id) to which the payment instrument belongs. + [JsonPropertyName("paymentInstrumentGroupId")] + public string? PaymentInstrumentGroupId { get { return this._PaymentInstrumentGroupIdOption; } set { this._PaymentInstrumentGroupIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment instrument, maximum 150 characters. + /// + /// Your reference for the payment instrument, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacedByIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + /// + /// The unique identifier of the payment instrument that replaced this payment instrument. + [JsonPropertyName("replacedById")] + public string? ReplacedById { get { return this._ReplacedByIdOption; } set { this._ReplacedByIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReplacementOfIdOption { get; private set; } + + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + /// + /// The unique identifier of the payment instrument that is replaced by this payment instrument. + [JsonPropertyName("replacementOfId")] + public string? ReplacementOfId { get { return this._ReplacementOfIdOption; } set { this._ReplacementOfIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusCommentOption { get; private set; } + + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + /// + /// The status comment provides additional information for the statusReason of the payment instrument. + [JsonPropertyName("statusComment")] + public string? StatusComment { get { return this._StatusCommentOption; } set { this._StatusCommentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrument {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IssuingCountryCode: ").Append(IssuingCountryCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AdditionalBankAccountIdentifications: ").Append(AdditionalBankAccountIdentifications).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrumentGroupId: ").Append(PaymentInstrumentGroupId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReplacedById: ").Append(ReplacedById).Append("\n"); + sb.Append(" ReplacementOfId: ").Append(ReplacementOfId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); + sb.Append(" StatusReason: ").Append(StatusReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option id = default; + Option issuingCountryCode = default; + Option type = default; + Option?> additionalBankAccountIdentifications = default; + Option bankAccount = default; + Option card = default; + Option description = default; + Option paymentInstrumentGroupId = default; + Option reference = default; + Option replacedById = default; + Option replacementOfId = default; + Option status = default; + Option statusComment = default; + Option statusReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "issuingCountryCode": + issuingCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentInstrument.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "additionalBankAccountIdentifications": + additionalBankAccountIdentifications = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrumentGroupId": + paymentInstrumentGroupId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "replacedById": + replacedById = new Option(utf8JsonReader.GetString()!); + break; + case "replacementOfId": + replacementOfId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(PaymentInstrument.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "statusComment": + statusComment = new Option(utf8JsonReader.GetString()!); + break; + case "statusReason": + string? statusReasonRawValue = utf8JsonReader.GetString(); + statusReason = new Option(PaymentInstrument.StatusReasonEnum.FromStringOrDefault(statusReasonRawValue)); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(balanceAccountId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(id)); + + if (!issuingCountryCode.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(issuingCountryCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrument.", nameof(type)); + + return new PaymentInstrument(balanceAccountId.Value!, id.Value!, issuingCountryCode.Value!, type.Value!.Value!, additionalBankAccountIdentifications, bankAccount, card, description, paymentInstrumentGroupId, reference, replacedById, replacementOfId, status, statusComment, statusReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrument.BalanceAccountId != null) + writer.WriteString("balanceAccountId", paymentInstrument.BalanceAccountId); + + if (paymentInstrument.Id != null) + writer.WriteString("id", paymentInstrument.Id); + + if (paymentInstrument.IssuingCountryCode != null) + writer.WriteString("issuingCountryCode", paymentInstrument.IssuingCountryCode); + + if (paymentInstrument.Type != null) + { + string? typeRawValue = PaymentInstrument.TypeEnum.ToJsonValue(paymentInstrument.Type); + writer.WriteString("type", typeRawValue); + } + + if (paymentInstrument._AdditionalBankAccountIdentificationsOption.IsSet) + { + writer.WritePropertyName("additionalBankAccountIdentifications"); + JsonSerializer.Serialize(writer, paymentInstrument.AdditionalBankAccountIdentifications, jsonSerializerOptions); + } + if (paymentInstrument._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, paymentInstrument.BankAccount, jsonSerializerOptions); + } + if (paymentInstrument._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, paymentInstrument.Card, jsonSerializerOptions); + } + if (paymentInstrument._DescriptionOption.IsSet) + if (paymentInstrument.Description != null) + writer.WriteString("description", paymentInstrument.Description); + + if (paymentInstrument._PaymentInstrumentGroupIdOption.IsSet) + if (paymentInstrument.PaymentInstrumentGroupId != null) + writer.WriteString("paymentInstrumentGroupId", paymentInstrument.PaymentInstrumentGroupId); + + if (paymentInstrument._ReferenceOption.IsSet) + if (paymentInstrument.Reference != null) + writer.WriteString("reference", paymentInstrument.Reference); + + if (paymentInstrument._ReplacedByIdOption.IsSet) + if (paymentInstrument.ReplacedById != null) + writer.WriteString("replacedById", paymentInstrument.ReplacedById); + + if (paymentInstrument._ReplacementOfIdOption.IsSet) + if (paymentInstrument.ReplacementOfId != null) + writer.WriteString("replacementOfId", paymentInstrument.ReplacementOfId); + + if (paymentInstrument._StatusOption.IsSet && paymentInstrument.Status != null) + { + string? statusRawValue = PaymentInstrument.StatusEnum.ToJsonValue(paymentInstrument._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (paymentInstrument._StatusCommentOption.IsSet) + if (paymentInstrument.StatusComment != null) + writer.WriteString("statusComment", paymentInstrument.StatusComment); + + if (paymentInstrument._StatusReasonOption.IsSet && paymentInstrument.StatusReason != null) + { + string? statusReasonRawValue = PaymentInstrument.StatusReasonEnum.ToJsonValue(paymentInstrument._StatusReasonOption.Value!.Value); + writer.WriteString("statusReason", statusReasonRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs b/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs new file mode 100644 index 000000000..64a3f7ea9 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentAdditionalBankAccountIdentificationsInner.cs @@ -0,0 +1,175 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PaymentInstrumentAdditionalBankAccountIdentificationsInner. + /// + public partial class PaymentInstrumentAdditionalBankAccountIdentificationsInner : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public PaymentInstrumentAdditionalBankAccountIdentificationsInner(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentAdditionalBankAccountIdentificationsInner {\n"); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentAdditionalBankAccountIdentificationsInnerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentAdditionalBankAccountIdentificationsInner Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + IbanAccountIdentification? ibanAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (ibanAccountIdentification?.Type != null) + return new PaymentInstrumentAdditionalBankAccountIdentificationsInner(ibanAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentAdditionalBankAccountIdentificationsInner paymentInstrumentAdditionalBankAccountIdentificationsInner, JsonSerializerOptions jsonSerializerOptions) + { + if (paymentInstrumentAdditionalBankAccountIdentificationsInner.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, paymentInstrumentAdditionalBankAccountIdentificationsInner.IbanAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, paymentInstrumentAdditionalBankAccountIdentificationsInner, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentAdditionalBankAccountIdentificationsInner paymentInstrumentAdditionalBankAccountIdentificationsInner, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentNotificationData.cs b/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentNotificationData.cs new file mode 100644 index 000000000..b21d4b37e --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PaymentInstrumentNotificationData.cs @@ -0,0 +1,203 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PaymentInstrumentNotificationData. + /// + public partial class PaymentInstrumentNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// paymentInstrument + [JsonConstructor] + public PaymentInstrumentNotificationData(Option balancePlatform = default, Option paymentInstrument = default) + { + _BalancePlatformOption = balancePlatform; + _PaymentInstrumentOption = paymentInstrument; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentNotificationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentNotificationData {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option paymentInstrument = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PaymentInstrumentNotificationData(balancePlatform, paymentInstrument); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentNotificationData paymentInstrumentNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentNotificationData paymentInstrumentNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentNotificationData._BalancePlatformOption.IsSet) + if (paymentInstrumentNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", paymentInstrumentNotificationData.BalancePlatform); + + if (paymentInstrumentNotificationData._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, paymentInstrumentNotificationData.PaymentInstrument, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PaymentNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/PaymentNotificationRequest.cs new file mode 100644 index 000000000..34d07f141 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PaymentNotificationRequest.cs @@ -0,0 +1,345 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PaymentNotificationRequest. + /// + public partial class PaymentNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public PaymentNotificationRequest(PaymentInstrumentNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformPaymentInstrumentCreated - balancePlatform.paymentInstrument.created + /// + public static readonly TypeEnum BalancePlatformPaymentInstrumentCreated = new("balancePlatform.paymentInstrument.created"); + + /// + /// TypeEnum.BalancePlatformPaymentInstrumentUpdated - balancePlatform.paymentInstrument.updated + /// + public static readonly TypeEnum BalancePlatformPaymentInstrumentUpdated = new("balancePlatform.paymentInstrument.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.paymentInstrument.created" => TypeEnum.BalancePlatformPaymentInstrumentCreated, + "balancePlatform.paymentInstrument.updated" => TypeEnum.BalancePlatformPaymentInstrumentUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformPaymentInstrumentCreated) + return "balancePlatform.paymentInstrument.created"; + + if (value == TypeEnum.BalancePlatformPaymentInstrumentUpdated) + return "balancePlatform.paymentInstrument.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public PaymentInstrumentNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class PaymentNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class PaymentNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentNotificationRequest.", nameof(type)); + + return new PaymentNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentNotificationRequest paymentNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentNotificationRequest paymentNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paymentNotificationRequest.Data, jsonSerializerOptions); + if (paymentNotificationRequest.Environment != null) + writer.WriteString("environment", paymentNotificationRequest.Environment); + + if (paymentNotificationRequest.Type != null) + { + string? typeRawValue = PaymentNotificationRequest.TypeEnum.ToJsonValue(paymentNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (paymentNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", paymentNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Phone.cs b/Adyen/ConfigurationWebhooks/Models/Phone.cs new file mode 100644 index 000000000..0f97c3ae0 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Phone.cs @@ -0,0 +1,298 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Phone. + /// + public partial class Phone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonConstructor] + public Phone(string number, TypeEnum type) + { + Number = number; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Phone() + { + } + + partial void OnCreated(); + + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Landline - landline + /// + public static readonly TypeEnum Landline = new("landline"); + + /// + /// TypeEnum.Mobile - mobile + /// + public static readonly TypeEnum Mobile = new("mobile"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "landline" => TypeEnum.Landline, + "mobile" => TypeEnum.Mobile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Landline) + return "landline"; + + if (value == TypeEnum.Mobile) + return "mobile"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + /// + /// Type of phone number. Possible values: **Landline**, **Mobile**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + /// + /// The full phone number provided as a single string. For example, **\"0031 6 11 22 33 44\"**, **\"+316/1122-3344\"**, or **\"(0031) 611223344\"**. + [JsonPropertyName("number")] + public string Number { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Phone {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Phone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Phone.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!number.IsSet) + throw new ArgumentException("Property is required for class Phone.", nameof(number)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Phone.", nameof(type)); + + return new Phone(number.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + if (phone.Number != null) + writer.WriteString("number", phone.Number); + + if (phone.Type != null) + { + string? typeRawValue = Phone.TypeEnum.ToJsonValue(phone.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PhoneNumber.cs b/Adyen/ConfigurationWebhooks/Models/PhoneNumber.cs new file mode 100644 index 000000000..fc043a380 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PhoneNumber.cs @@ -0,0 +1,351 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PhoneNumber. + /// + public partial class PhoneNumber : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + /// The phone number. The inclusion of the phone number country code is not necessary. + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonConstructor] + public PhoneNumber(Option phoneCountryCode = default, Option varPhoneNumber = default, Option phoneType = default) + { + _PhoneCountryCodeOption = phoneCountryCode; + _VarPhoneNumberOption = varPhoneNumber; + _PhoneTypeOption = phoneType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PhoneNumber() + { + } + + partial void OnCreated(); + + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonConverter(typeof(PhoneTypeEnumJsonConverter))] + public class PhoneTypeEnum : IEnum + { + /// + /// Returns the value of the PhoneTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PhoneTypeEnum.Fax - Fax + /// + public static readonly PhoneTypeEnum Fax = new("Fax"); + + /// + /// PhoneTypeEnum.Landline - Landline + /// + public static readonly PhoneTypeEnum Landline = new("Landline"); + + /// + /// PhoneTypeEnum.Mobile - Mobile + /// + public static readonly PhoneTypeEnum Mobile = new("Mobile"); + + /// + /// PhoneTypeEnum.SIP - SIP + /// + public static readonly PhoneTypeEnum SIP = new("SIP"); + + private PhoneTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PhoneTypeEnum?(string? value) => value == null ? null : new PhoneTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PhoneTypeEnum? option) => option?.Value; + + public static bool operator ==(PhoneTypeEnum? left, PhoneTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PhoneTypeEnum? left, PhoneTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PhoneTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PhoneTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "Fax" => PhoneTypeEnum.Fax, + "Landline" => PhoneTypeEnum.Landline, + "Mobile" => PhoneTypeEnum.Mobile, + "SIP" => PhoneTypeEnum.SIP, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PhoneTypeEnum? value) + { + if (value == null) + return null; + + if (value == PhoneTypeEnum.Fax) + return "Fax"; + + if (value == PhoneTypeEnum.Landline) + return "Landline"; + + if (value == PhoneTypeEnum.Mobile) + return "Mobile"; + + if (value == PhoneTypeEnum.SIP) + return "SIP"; + + return null; + } + + /// + /// JsonConverter for writing PhoneTypeEnum. + /// + public class PhoneTypeEnumJsonConverter : JsonConverter + { + public override PhoneTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PhoneTypeEnum.FromStringOrDefault(value) ?? new PhoneTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PhoneTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PhoneTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneTypeOption { get; private set; } + + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + /// + /// The type of the phone number. Possible values: **Landline**, **Mobile**, **SIP**, **Fax**. + [JsonPropertyName("phoneType")] + public PhoneTypeEnum? PhoneType { get { return this._PhoneTypeOption; } set { this._PhoneTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneCountryCodeOption { get; private set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + /// + /// The two-character ISO-3166-1 alpha-2 country code of the phone number. For example, **US** or **NL**. + [JsonPropertyName("phoneCountryCode")] + public string? PhoneCountryCode { get { return this._PhoneCountryCodeOption; } set { this._PhoneCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VarPhoneNumberOption { get; private set; } + + /// + /// The phone number. The inclusion of the phone number country code is not necessary. + /// + /// The phone number. The inclusion of the phone number country code is not necessary. + [JsonPropertyName("phoneNumber")] + public string? VarPhoneNumber { get { return this._VarPhoneNumberOption; } set { this._VarPhoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PhoneNumber {\n"); + sb.Append(" PhoneCountryCode: ").Append(PhoneCountryCode).Append("\n"); + sb.Append(" VarPhoneNumber: ").Append(VarPhoneNumber).Append("\n"); + sb.Append(" PhoneType: ").Append(PhoneType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneNumberJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PhoneNumber Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option phoneCountryCode = default; + Option varPhoneNumber = default; + Option phoneType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "phoneCountryCode": + phoneCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + varPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "phoneType": + string? phoneTypeRawValue = utf8JsonReader.GetString(); + phoneType = new Option(PhoneNumber.PhoneTypeEnum.FromStringOrDefault(phoneTypeRawValue)); + break; + default: + break; + } + } + } + + + return new PhoneNumber(phoneCountryCode, varPhoneNumber, phoneType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phoneNumber, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + if (phoneNumber._PhoneCountryCodeOption.IsSet) + if (phoneNumber.PhoneCountryCode != null) + writer.WriteString("phoneCountryCode", phoneNumber.PhoneCountryCode); + + if (phoneNumber._VarPhoneNumberOption.IsSet) + if (phoneNumber.VarPhoneNumber != null) + writer.WriteString("phoneNumber", phoneNumber.VarPhoneNumber); + + if (phoneNumber._PhoneTypeOption.IsSet && phoneNumber.PhoneType != null) + { + string? phoneTypeRawValue = PhoneNumber.PhoneTypeEnum.ToJsonValue(phoneNumber._PhoneTypeOption.Value!.Value); + writer.WriteString("phoneType", phoneTypeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/PlatformPaymentConfiguration.cs b/Adyen/ConfigurationWebhooks/Models/PlatformPaymentConfiguration.cs new file mode 100644 index 000000000..3aba7a531 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/PlatformPaymentConfiguration.cs @@ -0,0 +1,201 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// PlatformPaymentConfiguration. + /// + public partial class PlatformPaymentConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + [JsonConstructor] + public PlatformPaymentConfiguration(Option salesDayClosingTime = default, Option settlementDelayDays = default) + { + _SalesDayClosingTimeOption = salesDayClosingTime; + _SettlementDelayDaysOption = settlementDelayDays; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformPaymentConfiguration() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SalesDayClosingTimeOption { get; private set; } + + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + [JsonPropertyName("salesDayClosingTime")] + public string? SalesDayClosingTime { get { return this._SalesDayClosingTimeOption; } set { this._SalesDayClosingTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SettlementDelayDaysOption { get; private set; } + + /// + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + /// + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. + [JsonPropertyName("settlementDelayDays")] + public int? SettlementDelayDays { get { return this._SettlementDelayDaysOption; } set { this._SettlementDelayDaysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformPaymentConfiguration {\n"); + sb.Append(" SalesDayClosingTime: ").Append(SalesDayClosingTime).Append("\n"); + sb.Append(" SettlementDelayDays: ").Append(SettlementDelayDays).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformPaymentConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformPaymentConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option salesDayClosingTime = default; + Option settlementDelayDays = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "salesDayClosingTime": + salesDayClosingTime = new Option(utf8JsonReader.GetString()!); + break; + case "settlementDelayDays": + settlementDelayDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new PlatformPaymentConfiguration(salesDayClosingTime, settlementDelayDays); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformPaymentConfiguration platformPaymentConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformPaymentConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformPaymentConfiguration platformPaymentConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformPaymentConfiguration._SalesDayClosingTimeOption.IsSet) + if (platformPaymentConfiguration.SalesDayClosingTime != null) + writer.WriteString("salesDayClosingTime", platformPaymentConfiguration.SalesDayClosingTime); + + if (platformPaymentConfiguration._SettlementDelayDaysOption.IsSet) + writer.WriteNumber("settlementDelayDays", platformPaymentConfiguration._SettlementDelayDaysOption.Value!.Value); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/RemediatingAction.cs b/Adyen/ConfigurationWebhooks/Models/RemediatingAction.cs new file mode 100644 index 000000000..3055272e4 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/RemediatingAction.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// RemediatingAction. + /// + public partial class RemediatingAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The remediating action code. + /// A description of how you can resolve the verification error. + [JsonConstructor] + public RemediatingAction(Option code = default, Option message = default) + { + _CodeOption = code; + _MessageOption = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RemediatingAction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The remediating action code. + /// + /// The remediating action code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of how you can resolve the verification error. + /// + /// A description of how you can resolve the verification error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RemediatingAction {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RemediatingActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RemediatingAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RemediatingAction(code, message); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, remediatingAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (remediatingAction._CodeOption.IsSet) + if (remediatingAction.Code != null) + writer.WriteString("code", remediatingAction.Code); + + if (remediatingAction._MessageOption.IsSet) + if (remediatingAction.Message != null) + writer.WriteString("message", remediatingAction.Message); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Resource.cs b/Adyen/ConfigurationWebhooks/Models/Resource.cs new file mode 100644 index 000000000..4e34e0d9b --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/ResourceReference.cs b/Adyen/ConfigurationWebhooks/Models/ResourceReference.cs new file mode 100644 index 000000000..5048c3cd3 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/ScoreNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/ScoreNotificationRequest.cs new file mode 100644 index 000000000..c80c1cd75 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/ScoreNotificationRequest.cs @@ -0,0 +1,336 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// ScoreNotificationRequest. + /// + public partial class ScoreNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public ScoreNotificationRequest(BankScoreSignalTriggeredData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScoreNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformScoreTriggered - balancePlatform.score.triggered + /// + public static readonly TypeEnum BalancePlatformScoreTriggered = new("balancePlatform.score.triggered"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.score.triggered" => TypeEnum.BalancePlatformScoreTriggered, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformScoreTriggered) + return "balancePlatform.score.triggered"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public BankScoreSignalTriggeredData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScoreNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScoreNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScoreNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ScoreNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class ScoreNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class ScoreNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ScoreNotificationRequest.", nameof(type)); + + return new ScoreNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScoreNotificationRequest scoreNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scoreNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScoreNotificationRequest scoreNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, scoreNotificationRequest.Data, jsonSerializerOptions); + if (scoreNotificationRequest.Environment != null) + writer.WriteString("environment", scoreNotificationRequest.Environment); + + if (scoreNotificationRequest.Type != null) + { + string? typeRawValue = ScoreNotificationRequest.TypeEnum.ToJsonValue(scoreNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (scoreNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", scoreNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationData.cs b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationData.cs new file mode 100644 index 000000000..565055d71 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationData.cs @@ -0,0 +1,228 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// SweepConfigurationNotificationData. + /// + public partial class SweepConfigurationNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance account for which the sweep was configured. + /// The unique identifier of the balance platform. + /// sweep + [JsonConstructor] + public SweepConfigurationNotificationData(Option accountId = default, Option balancePlatform = default, Option sweep = default) + { + _AccountIdOption = accountId; + _BalancePlatformOption = balancePlatform; + _SweepOption = sweep; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepConfigurationNotificationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountIdOption { get; private set; } + + /// + /// The unique identifier of the balance account for which the sweep was configured. + /// + /// The unique identifier of the balance account for which the sweep was configured. + [JsonPropertyName("accountId")] + public string? AccountId { get { return this._AccountIdOption; } set { this._AccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SweepOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sweep")] + public SweepConfigurationV2? Sweep { get { return this._SweepOption; } set { this._SweepOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepConfigurationNotificationData {\n"); + sb.Append(" AccountId: ").Append(AccountId).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Sweep: ").Append(Sweep).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepConfigurationNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepConfigurationNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountId = default; + Option balancePlatform = default; + Option sweep = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountId": + accountId = new Option(utf8JsonReader.GetString()!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "sweep": + sweep = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new SweepConfigurationNotificationData(accountId, balancePlatform, sweep); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepConfigurationNotificationData sweepConfigurationNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepConfigurationNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepConfigurationNotificationData sweepConfigurationNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (sweepConfigurationNotificationData._AccountIdOption.IsSet) + if (sweepConfigurationNotificationData.AccountId != null) + writer.WriteString("accountId", sweepConfigurationNotificationData.AccountId); + + if (sweepConfigurationNotificationData._BalancePlatformOption.IsSet) + if (sweepConfigurationNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", sweepConfigurationNotificationData.BalancePlatform); + + if (sweepConfigurationNotificationData._SweepOption.IsSet) + { + writer.WritePropertyName("sweep"); + JsonSerializer.Serialize(writer, sweepConfigurationNotificationData.Sweep, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationRequest.cs b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationRequest.cs new file mode 100644 index 000000000..b4e07ad3d --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationNotificationRequest.cs @@ -0,0 +1,354 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// SweepConfigurationNotificationRequest. + /// + public partial class SweepConfigurationNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public SweepConfigurationNotificationRequest(SweepConfigurationNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepConfigurationNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformBalanceAccountSweepCreated - balancePlatform.balanceAccountSweep.created + /// + public static readonly TypeEnum BalancePlatformBalanceAccountSweepCreated = new("balancePlatform.balanceAccountSweep.created"); + + /// + /// TypeEnum.BalancePlatformBalanceAccountSweepUpdated - balancePlatform.balanceAccountSweep.updated + /// + public static readonly TypeEnum BalancePlatformBalanceAccountSweepUpdated = new("balancePlatform.balanceAccountSweep.updated"); + + /// + /// TypeEnum.BalancePlatformBalanceAccountSweepDeleted - balancePlatform.balanceAccountSweep.deleted + /// + public static readonly TypeEnum BalancePlatformBalanceAccountSweepDeleted = new("balancePlatform.balanceAccountSweep.deleted"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.balanceAccountSweep.created" => TypeEnum.BalancePlatformBalanceAccountSweepCreated, + "balancePlatform.balanceAccountSweep.updated" => TypeEnum.BalancePlatformBalanceAccountSweepUpdated, + "balancePlatform.balanceAccountSweep.deleted" => TypeEnum.BalancePlatformBalanceAccountSweepDeleted, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformBalanceAccountSweepCreated) + return "balancePlatform.balanceAccountSweep.created"; + + if (value == TypeEnum.BalancePlatformBalanceAccountSweepUpdated) + return "balancePlatform.balanceAccountSweep.updated"; + + if (value == TypeEnum.BalancePlatformBalanceAccountSweepDeleted) + return "balancePlatform.balanceAccountSweep.deleted"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public SweepConfigurationNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepConfigurationNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepConfigurationNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepConfigurationNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SweepConfigurationNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationNotificationRequest.", nameof(type)); + + return new SweepConfigurationNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepConfigurationNotificationRequest sweepConfigurationNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepConfigurationNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepConfigurationNotificationRequest sweepConfigurationNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, sweepConfigurationNotificationRequest.Data, jsonSerializerOptions); + if (sweepConfigurationNotificationRequest.Environment != null) + writer.WriteString("environment", sweepConfigurationNotificationRequest.Environment); + + if (sweepConfigurationNotificationRequest.Type != null) + { + string? typeRawValue = SweepConfigurationNotificationRequest.TypeEnum.ToJsonValue(sweepConfigurationNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (sweepConfigurationNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", sweepConfigurationNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/SweepConfigurationV2.cs b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationV2.cs new file mode 100644 index 000000000..8cd4e7c65 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/SweepConfigurationV2.cs @@ -0,0 +1,1318 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// SweepConfigurationV2. + /// + public partial class SweepConfigurationV2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// counterparty + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// The unique identifier of the sweep. + /// schedule + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The reason for disabling the sweep. + /// The human readable reason for disabling the sweep. + /// Your reference for the sweep configuration. + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// sweepAmount + /// targetAmount + /// triggerAmount + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. (default to TypeEnum.Push) + [JsonConstructor] + public SweepConfigurationV2(SweepCounterparty counterparty, string currency, string id, SweepSchedule schedule, Option category = default, Option description = default, Option?> priorities = default, Option reason = default, Option reasonDetail = default, Option reference = default, Option referenceForBeneficiary = default, Option status = default, Option sweepAmount = default, Option targetAmount = default, Option triggerAmount = default, Option type = default) + { + Counterparty = counterparty; + Currency = currency; + Id = id; + Schedule = schedule; + _CategoryOption = category; + _DescriptionOption = description; + _PrioritiesOption = priorities; + _ReasonOption = reason; + _ReasonDetailOption = reasonDetail; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _StatusOption = status; + _SweepAmountOption = sweepAmount; + _TargetAmountOption = targetAmount; + _TriggerAmountOption = triggerAmount; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepConfigurationV2() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "internal" => CategoryEnum.Internal, + "platformPayment" => CategoryEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + /// + /// The type of transfer that results from the sweep. Possible values: - **bank**: Sweep to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. Required when setting `priorities`. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason for disabling the sweep. + /// + /// The reason for disabling the sweep. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + /// + /// The status of the sweep. If not provided, by default, this is set to **active**. Possible values: * **active**: the sweep is enabled and funds will be pulled in or pushed out based on the defined configuration. * **inactive**: the sweep is disabled and cannot be triggered. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Pull - pull + /// + public static readonly TypeEnum Pull = new("pull"); + + /// + /// TypeEnum.Push - push + /// + public static readonly TypeEnum Push = new("push"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "pull" => TypeEnum.Pull, + "push" => TypeEnum.Push, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Pull) + return "pull"; + + if (value == TypeEnum.Push) + return "push"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + /// + /// The direction of sweep, whether pushing out or pulling in funds to the balance account. If not provided, by default, this is set to **push**. Possible values: * **push**: _push out funds_ to a destination balance account or transfer instrument. * **pull**: _pull in funds_ from a source merchant account, transfer instrument, or balance account. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public SweepCounterparty Counterparty { get; set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The unique identifier of the sweep. + /// + /// The unique identifier of the sweep. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// . + /// + [JsonPropertyName("schedule")] + public SweepSchedule Schedule { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + /// + /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonDetailOption { get; private set; } + + /// + /// The human readable reason for disabling the sweep. + /// + /// The human readable reason for disabling the sweep. + [JsonPropertyName("reasonDetail")] + public string? ReasonDetail { get { return this._ReasonDetailOption; } set { this._ReasonDetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the sweep configuration. + /// + /// Your reference for the sweep configuration. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + /// + /// The reference sent to or received from the counterparty. Only alphanumeric characters are allowed. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SweepAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sweepAmount")] + public Amount? SweepAmount { get { return this._SweepAmountOption; } set { this._SweepAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("targetAmount")] + public Amount? TargetAmount { get { return this._TargetAmountOption; } set { this._TargetAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TriggerAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("triggerAmount")] + public Amount? TriggerAmount { get { return this._TriggerAmountOption; } set { this._TriggerAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepConfigurationV2 {\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Schedule: ").Append(Schedule).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" ReasonDetail: ").Append(ReasonDetail).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SweepAmount: ").Append(SweepAmount).Append("\n"); + sb.Append(" TargetAmount: ").Append(TargetAmount).Append("\n"); + sb.Append(" TriggerAmount: ").Append(TriggerAmount).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + // ReferenceForBeneficiary (string) maxLength + if (this.ReferenceForBeneficiary != null && this.ReferenceForBeneficiary.Length > 80) + { + yield return new ValidationResult("Invalid value for ReferenceForBeneficiary, length must be less than 80.", new [] { "ReferenceForBeneficiary" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepConfigurationV2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepConfigurationV2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option counterparty = default; + Option currency = default; + Option id = default; + Option schedule = default; + Option category = default; + Option description = default; + Option?> priorities = default; + Option reason = default; + Option reasonDetail = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option status = default; + Option sweepAmount = default; + Option targetAmount = default; + Option triggerAmount = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "schedule": + schedule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(SweepConfigurationV2.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(SweepConfigurationV2.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reasonDetail": + reasonDetail = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(SweepConfigurationV2.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "sweepAmount": + sweepAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "targetAmount": + targetAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "triggerAmount": + triggerAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SweepConfigurationV2.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!counterparty.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(counterparty)); + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(currency)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(id)); + + if (!schedule.IsSet) + throw new ArgumentException("Property is required for class SweepConfigurationV2.", nameof(schedule)); + + return new SweepConfigurationV2(counterparty.Value!, currency.Value!, id.Value!, schedule.Value!, category, description, priorities, reason, reasonDetail, reference, referenceForBeneficiary, status, sweepAmount, targetAmount, triggerAmount, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepConfigurationV2 sweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepConfigurationV2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepConfigurationV2 sweepConfigurationV2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Counterparty, jsonSerializerOptions); + if (sweepConfigurationV2.Currency != null) + writer.WriteString("currency", sweepConfigurationV2.Currency); + + if (sweepConfigurationV2.Id != null) + writer.WriteString("id", sweepConfigurationV2.Id); + + writer.WritePropertyName("schedule"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Schedule, jsonSerializerOptions); + if (sweepConfigurationV2._CategoryOption.IsSet && sweepConfigurationV2.Category != null) + { + string? categoryRawValue = SweepConfigurationV2.CategoryEnum.ToJsonValue(sweepConfigurationV2._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (sweepConfigurationV2._DescriptionOption.IsSet) + if (sweepConfigurationV2.Description != null) + writer.WriteString("description", sweepConfigurationV2.Description); + + if (sweepConfigurationV2._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.Priorities, jsonSerializerOptions); + } + if (sweepConfigurationV2._ReasonOption.IsSet && sweepConfigurationV2.Reason != null) + { + string? reasonRawValue = SweepConfigurationV2.ReasonEnum.ToJsonValue(sweepConfigurationV2._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (sweepConfigurationV2._ReasonDetailOption.IsSet) + if (sweepConfigurationV2.ReasonDetail != null) + writer.WriteString("reasonDetail", sweepConfigurationV2.ReasonDetail); + + if (sweepConfigurationV2._ReferenceOption.IsSet) + if (sweepConfigurationV2.Reference != null) + writer.WriteString("reference", sweepConfigurationV2.Reference); + + if (sweepConfigurationV2._ReferenceForBeneficiaryOption.IsSet) + if (sweepConfigurationV2.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", sweepConfigurationV2.ReferenceForBeneficiary); + + if (sweepConfigurationV2._StatusOption.IsSet && sweepConfigurationV2.Status != null) + { + string? statusRawValue = SweepConfigurationV2.StatusEnum.ToJsonValue(sweepConfigurationV2._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (sweepConfigurationV2._SweepAmountOption.IsSet) + { + writer.WritePropertyName("sweepAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.SweepAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TargetAmountOption.IsSet) + { + writer.WritePropertyName("targetAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.TargetAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TriggerAmountOption.IsSet) + { + writer.WritePropertyName("triggerAmount"); + JsonSerializer.Serialize(writer, sweepConfigurationV2.TriggerAmount, jsonSerializerOptions); + } + if (sweepConfigurationV2._TypeOption.IsSet && sweepConfigurationV2.Type != null) + { + string? typeRawValue = SweepConfigurationV2.TypeEnum.ToJsonValue(sweepConfigurationV2._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/SweepCounterparty.cs b/Adyen/ConfigurationWebhooks/Models/SweepCounterparty.cs new file mode 100644 index 000000000..4ff7f4bc1 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/SweepCounterparty.cs @@ -0,0 +1,227 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// SweepCounterparty. + /// + public partial class SweepCounterparty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + [JsonConstructor] + public SweepCounterparty(Option balanceAccountId = default, Option merchantAccount = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _MerchantAccountOption = merchantAccount; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepCounterparty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + /// + /// The unique identifier of the destination or source [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id). > If you are updating the counterparty from a transfer instrument to a balance account, set `transferInstrumentId` to **null**. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + /// + /// The merchant account that will be the source of funds. You can only use this parameter with sweeps of `type` **pull** and if you are processing payments with Adyen. + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + /// + /// The unique identifier of the destination or source [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id) depending on the sweep `type` . To set up automated top-up sweeps to balance accounts in your [marketplace](https://docs.adyen.com/marketplaces/top-up-balance-account/#before-you-begin) or [platform](https://docs.adyen.com/platforms/top-up-balance-account/#before-you-begin), use this parameter in combination with a `merchantAccount` and a sweep `type` of **pull**. Top-up sweeps start a direct debit request from the source transfer instrument. Contact Adyen Support to enable this feature.> If you are updating the counterparty from a balance account to a transfer instrument, set `balanceAccountId` to **null**. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepCounterparty {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepCounterpartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepCounterparty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option merchantAccount = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SweepCounterparty(balanceAccountId, merchantAccount, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepCounterparty sweepCounterparty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepCounterparty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepCounterparty sweepCounterparty, JsonSerializerOptions jsonSerializerOptions) + { + + if (sweepCounterparty._BalanceAccountIdOption.IsSet) + if (sweepCounterparty.BalanceAccountId != null) + writer.WriteString("balanceAccountId", sweepCounterparty.BalanceAccountId); + + if (sweepCounterparty._MerchantAccountOption.IsSet) + if (sweepCounterparty.MerchantAccount != null) + writer.WriteString("merchantAccount", sweepCounterparty.MerchantAccount); + + if (sweepCounterparty._TransferInstrumentIdOption.IsSet) + if (sweepCounterparty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", sweepCounterparty.TransferInstrumentId); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/SweepSchedule.cs b/Adyen/ConfigurationWebhooks/Models/SweepSchedule.cs new file mode 100644 index 000000000..35edae66a --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/SweepSchedule.cs @@ -0,0 +1,330 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// SweepSchedule. + /// + public partial class SweepSchedule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: **&ast;**, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + [JsonConstructor] + public SweepSchedule(TypeEnum type, Option cronExpression = default) + { + Type = type; + _CronExpressionOption = cronExpression; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SweepSchedule() + { + } + + partial void OnCreated(); + + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Daily - daily + /// + public static readonly TypeEnum Daily = new("daily"); + + /// + /// TypeEnum.Weekly - weekly + /// + public static readonly TypeEnum Weekly = new("weekly"); + + /// + /// TypeEnum.Monthly - monthly + /// + public static readonly TypeEnum Monthly = new("monthly"); + + /// + /// TypeEnum.Balance - balance + /// + public static readonly TypeEnum Balance = new("balance"); + + /// + /// TypeEnum.Cron - cron + /// + public static readonly TypeEnum Cron = new("cron"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => TypeEnum.Daily, + "weekly" => TypeEnum.Weekly, + "monthly" => TypeEnum.Monthly, + "balance" => TypeEnum.Balance, + "cron" => TypeEnum.Cron, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Daily) + return "daily"; + + if (value == TypeEnum.Weekly) + return "weekly"; + + if (value == TypeEnum.Monthly) + return "monthly"; + + if (value == TypeEnum.Balance) + return "balance"; + + if (value == TypeEnum.Cron) + return "cron"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + /// + /// The schedule type. Possible values: * **cron**: push out funds based on a `cronExpression`. * **daily**: push out funds daily at 07:00 AM CET. * **weekly**: push out funds every Monday at 07:00 AM CET. * **monthly**: push out funds every first of the month at 07:00 AM CET. * **balance**: execute the sweep instantly if the `triggerAmount` is reached. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CronExpressionOption { get; private set; } + + /// + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: **&ast;**, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + /// + /// A [cron expression](https://en.wikipedia.org/wiki/Cron#CRON_expression) that is used to set the sweep schedule. The schedule uses the time zone of the balance account. For example, **30 17 * * MON** schedules a sweep every Monday at 17:30. The expression must have five values separated by a single space in the following order: * Minute: **0-59** * Hour: **0-23** * Day of the month: **1-31** * Month: **1-12** or **JAN-DEC** * Day of the week: **0-7** (0 and 7 are Sunday) or **MON-SUN**. The following non-standard characters are supported: *****, **L**, **#**, **W** and **_/_**. See [crontab guru](https://crontab.guru/) for more examples. Required when `type` is **cron**. + [JsonPropertyName("cronExpression")] + public string? CronExpression { get { return this._CronExpressionOption; } set { this._CronExpressionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SweepSchedule {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CronExpression: ").Append(CronExpression).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SweepScheduleJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SweepSchedule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option cronExpression = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SweepSchedule.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "cronExpression": + cronExpression = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SweepSchedule.", nameof(type)); + + return new SweepSchedule(type.Value!.Value!, cronExpression); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SweepSchedule sweepSchedule, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sweepSchedule, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SweepSchedule sweepSchedule, JsonSerializerOptions jsonSerializerOptions) + { + + if (sweepSchedule.Type != null) + { + string? typeRawValue = SweepSchedule.TypeEnum.ToJsonValue(sweepSchedule.Type); + writer.WriteString("type", typeRawValue); + } + + if (sweepSchedule._CronExpressionOption.IsSet) + if (sweepSchedule.CronExpression != null) + writer.WriteString("cronExpression", sweepSchedule.CronExpression); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/TokenAuthentication.cs b/Adyen/ConfigurationWebhooks/Models/TokenAuthentication.cs new file mode 100644 index 000000000..06d466798 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/TokenAuthentication.cs @@ -0,0 +1,202 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// TokenAuthentication. + /// + public partial class TokenAuthentication : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**. + /// The result of the authentication process. + [JsonConstructor] + public TokenAuthentication(Option method = default, Option result = default) + { + _MethodOption = method; + _ResultOption = result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenAuthentication() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MethodOption { get; private set; } + + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**. + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**. + [JsonPropertyName("method")] + public string? Method { get { return this._MethodOption; } set { this._MethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The result of the authentication process. + /// + /// The result of the authentication process. + [JsonPropertyName("result")] + public string? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenAuthentication {\n"); + sb.Append(" Method: ").Append(Method).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenAuthenticationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenAuthentication Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option method = default; + Option result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "method": + method = new Option(utf8JsonReader.GetString()!); + break; + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TokenAuthentication(method, result); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenAuthentication tokenAuthentication, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenAuthentication, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenAuthentication tokenAuthentication, JsonSerializerOptions jsonSerializerOptions) + { + + if (tokenAuthentication._MethodOption.IsSet) + if (tokenAuthentication.Method != null) + writer.WriteString("method", tokenAuthentication.Method); + + if (tokenAuthentication._ResultOption.IsSet) + if (tokenAuthentication.Result != null) + writer.WriteString("result", tokenAuthentication.Result); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/ValidationFacts.cs b/Adyen/ConfigurationWebhooks/Models/ValidationFacts.cs new file mode 100644 index 000000000..dbf41a7fe --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/ValidationFacts.cs @@ -0,0 +1,352 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// ValidationFacts. + /// + public partial class ValidationFacts : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**. + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + /// The type of the validation fact. + [JsonConstructor] + public ValidationFacts(Option?> reasons = default, Option result = default, Option type = default) + { + _ReasonsOption = reasons; + _ResultOption = result; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ValidationFacts() + { + } + + partial void OnCreated(); + + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + [JsonConverter(typeof(ResultEnumJsonConverter))] + public class ResultEnum : IEnum + { + /// + /// Returns the value of the ResultEnum. + /// + public string? Value { get; set; } + + /// + /// ResultEnum.Invalid - invalid + /// + public static readonly ResultEnum Invalid = new("invalid"); + + /// + /// ResultEnum.NotApplicable - notApplicable + /// + public static readonly ResultEnum NotApplicable = new("notApplicable"); + + /// + /// ResultEnum.NotValidated - notValidated + /// + public static readonly ResultEnum NotValidated = new("notValidated"); + + /// + /// ResultEnum.Valid - valid + /// + public static readonly ResultEnum Valid = new("valid"); + + private ResultEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultEnum?(string? value) => value == null ? null : new ResultEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultEnum? option) => option?.Value; + + public static bool operator ==(ResultEnum? left, ResultEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultEnum? left, ResultEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => ResultEnum.Invalid, + "notApplicable" => ResultEnum.NotApplicable, + "notValidated" => ResultEnum.NotValidated, + "valid" => ResultEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultEnum? value) + { + if (value == null) + return null; + + if (value == ResultEnum.Invalid) + return "invalid"; + + if (value == ResultEnum.NotApplicable) + return "notApplicable"; + + if (value == ResultEnum.NotValidated) + return "notValidated"; + + if (value == ResultEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing ResultEnum. + /// + public class ResultEnumJsonConverter : JsonConverter + { + public override ResultEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultEnum.FromStringOrDefault(value) ?? new ResultEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + [JsonPropertyName("result")] + public ResultEnum? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ReasonsOption { get; private set; } + + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**. + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**. + [JsonPropertyName("reasons")] + public List? Reasons { get { return this._ReasonsOption; } set { this._ReasonsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the validation fact. + /// + /// The type of the validation fact. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ValidationFacts {\n"); + sb.Append(" Reasons: ").Append(Reasons).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ValidationFactsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ValidationFacts Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> reasons = default; + Option result = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reasons": + reasons = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "result": + string? resultRawValue = utf8JsonReader.GetString(); + result = new Option(ValidationFacts.ResultEnum.FromStringOrDefault(resultRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ValidationFacts(reasons, result, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ValidationFacts validationFacts, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, validationFacts, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ValidationFacts validationFacts, JsonSerializerOptions jsonSerializerOptions) + { + + if (validationFacts._ReasonsOption.IsSet) + { + writer.WritePropertyName("reasons"); + JsonSerializer.Serialize(writer, validationFacts.Reasons, jsonSerializerOptions); + } + if (validationFacts._ResultOption.IsSet && validationFacts.Result != null) + { + string? resultRawValue = ValidationFacts.ResultEnum.ToJsonValue(validationFacts._ResultOption.Value!.Value); + writer.WriteString("result", resultRawValue); + } + + if (validationFacts._TypeOption.IsSet) + if (validationFacts.Type != null) + writer.WriteString("type", validationFacts.Type); + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/VerificationDeadline.cs b/Adyen/ConfigurationWebhooks/Models/VerificationDeadline.cs new file mode 100644 index 000000000..77c649324 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/VerificationDeadline.cs @@ -0,0 +1,800 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// VerificationDeadline. + /// + public partial class VerificationDeadline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The names of the capabilities to be disallowed. + /// The date that verification is due by before capabilities are disallowed. + /// The unique identifiers of the bank account(s) that the deadline applies to + [JsonConstructor] + public VerificationDeadline(List capabilities, DateTimeOffset expiresAt, Option?> entityIds = default) + { + Capabilities = capabilities; + ExpiresAt = expiresAt; + _EntityIdsOption = entityIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationDeadline() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The names of the capabilities to be disallowed. + /// + /// The names of the capabilities to be disallowed. + [JsonPropertyName("capabilities")] + public List Capabilities { get; set; } + + /// + /// The date that verification is due by before capabilities are disallowed. + /// + /// The date that verification is due by before capabilities are disallowed. + [JsonPropertyName("expiresAt")] + public DateTimeOffset ExpiresAt { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityIdsOption { get; private set; } + + /// + /// The unique identifiers of the bank account(s) that the deadline applies to + /// + /// The unique identifiers of the bank account(s) that the deadline applies to + [JsonPropertyName("entityIds")] + public List? EntityIds { get { return this._EntityIdsOption; } set { this._EntityIdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationDeadline {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" EntityIds: ").Append(EntityIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationDeadlineJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationDeadline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option expiresAt = default; + Option?> entityIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityIds": + entityIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!capabilities.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(capabilities)); + + if (!expiresAt.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(expiresAt)); + + return new VerificationDeadline(capabilities.Value!, expiresAt.Value!.Value!, entityIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationDeadline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationDeadline.Capabilities, jsonSerializerOptions); + writer.WriteString("expiresAt", verificationDeadline.ExpiresAt.ToString(ExpiresAtFormat)); + + if (verificationDeadline._EntityIdsOption.IsSet) + { + writer.WritePropertyName("entityIds"); + JsonSerializer.Serialize(writer, verificationDeadline.EntityIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/VerificationError.cs b/Adyen/ConfigurationWebhooks/Models/VerificationError.cs new file mode 100644 index 000000000..7b85701e2 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/VerificationError.cs @@ -0,0 +1,1008 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// VerificationError. + /// + public partial class VerificationError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the capabilities that the verification error applies to. + /// The verification error code. + /// A description of the error. + /// Contains the actions that you can take to resolve the verification error. + /// Contains more granular information about the verification error. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConstructor] + public VerificationError(Option?> capabilities = default, Option code = default, Option message = default, Option?> remediatingActions = default, Option?> subErrors = default, Option type = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _RemediatingActionsOption = remediatingActions; + _SubErrorsOption = subErrors; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationError() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains the capabilities that the verification error applies to. + /// + /// Contains the capabilities that the verification error applies to. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of the error. + /// + /// A description of the error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// Contains the actions that you can take to resolve the verification error. + /// + /// Contains the actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubErrorsOption { get; private set; } + + /// + /// Contains more granular information about the verification error. + /// + /// Contains more granular information about the verification error. + [JsonPropertyName("subErrors")] + public List? SubErrors { get { return this._SubErrorsOption; } set { this._SubErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationError {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append(" SubErrors: ").Append(SubErrors).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option?> remediatingActions = default; + Option?> subErrors = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subErrors": + subErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationError.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new VerificationError(capabilities, code, message, remediatingActions, subErrors, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationError._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationError.Capabilities, jsonSerializerOptions); + } + if (verificationError._CodeOption.IsSet) + if (verificationError.Code != null) + writer.WriteString("code", verificationError.Code); + + if (verificationError._MessageOption.IsSet) + if (verificationError.Message != null) + writer.WriteString("message", verificationError.Message); + + if (verificationError._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationError.RemediatingActions, jsonSerializerOptions); + } + if (verificationError._SubErrorsOption.IsSet) + { + writer.WritePropertyName("subErrors"); + JsonSerializer.Serialize(writer, verificationError.SubErrors, jsonSerializerOptions); + } + if (verificationError._TypeOption.IsSet && verificationError.Type != null) + { + string? typeRawValue = VerificationError.TypeEnum.ToJsonValue(verificationError._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/VerificationErrorRecursive.cs b/Adyen/ConfigurationWebhooks/Models/VerificationErrorRecursive.cs new file mode 100644 index 000000000..c9116b732 --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/VerificationErrorRecursive.cs @@ -0,0 +1,983 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// VerificationErrorRecursive. + /// + public partial class VerificationErrorRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the capabilities that the verification error applies to. + /// The verification error code. + /// A description of the error. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// Contains the actions that you can take to resolve the verification error. + [JsonConstructor] + public VerificationErrorRecursive(Option?> capabilities = default, Option code = default, Option message = default, Option type = default, Option?> remediatingActions = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _TypeOption = type; + _RemediatingActionsOption = remediatingActions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationErrorRecursive() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains the capabilities that the verification error applies to. + /// + /// Contains the capabilities that the verification error applies to. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of the error. + /// + /// A description of the error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// Contains the actions that you can take to resolve the verification error. + /// + /// Contains the actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationErrorRecursive {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationErrorRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option type = default; + Option?> remediatingActions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationErrorRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new VerificationErrorRecursive(capabilities, code, message, type, remediatingActions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationErrorRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationErrorRecursive._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.Capabilities, jsonSerializerOptions); + } + if (verificationErrorRecursive._CodeOption.IsSet) + if (verificationErrorRecursive.Code != null) + writer.WriteString("code", verificationErrorRecursive.Code); + + if (verificationErrorRecursive._MessageOption.IsSet) + if (verificationErrorRecursive.Message != null) + writer.WriteString("message", verificationErrorRecursive.Message); + + if (verificationErrorRecursive._TypeOption.IsSet && verificationErrorRecursive.Type != null) + { + string? typeRawValue = VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (verificationErrorRecursive._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.RemediatingActions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ConfigurationWebhooks/Models/Wallet.cs b/Adyen/ConfigurationWebhooks/Models/Wallet.cs new file mode 100644 index 000000000..6c973b8ca --- /dev/null +++ b/Adyen/ConfigurationWebhooks/Models/Wallet.cs @@ -0,0 +1,757 @@ +// +/* + * Configuration webhooks + * + * Adyen sends webhooks to inform your system about events that occur in your platform. These events include, for example, when an account holder's capabilities are updated, or when a sweep configuration is created or updated. When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. You can use these webhooks to build your implementation. For example, you can use this information to update internal statuses when the status of a capability is changed. + * + * The version of the OpenAPI document: 2 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ConfigurationWebhooks.Client; + +namespace Adyen.ConfigurationWebhooks.Models +{ + /// + /// Wallet. + /// + public partial class Wallet : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**. + /// device + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**. + /// The method used for provisioning the network token. Possible values: **push**, **manual**, **cof**, **unknown**. + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**. + [JsonConstructor] + public Wallet(Option accountScore = default, Option device = default, Option deviceScore = default, Option provisioningMethod = default, Option?> recommendationReasons = default, Option type = default) + { + _AccountScoreOption = accountScore; + _DeviceOption = device; + _DeviceScoreOption = deviceScore; + _ProvisioningMethodOption = provisioningMethod; + _RecommendationReasonsOption = recommendationReasons; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Wallet() + { + } + + partial void OnCreated(); + + /// + /// Defines RecommendationReasons. + /// + [JsonConverter(typeof(RecommendationReasonsEnumJsonConverter))] + public class RecommendationReasonsEnum : IEnum + { + /// + /// Returns the value of the RecommendationReasonsEnum. + /// + public string? Value { get; set; } + + /// + /// RecommendationReasonsEnum.AccountCardTooNew - accountCardTooNew + /// + public static readonly RecommendationReasonsEnum AccountCardTooNew = new("accountCardTooNew"); + + /// + /// RecommendationReasonsEnum.AccountHighRisk - accountHighRisk + /// + public static readonly RecommendationReasonsEnum AccountHighRisk = new("accountHighRisk"); + + /// + /// RecommendationReasonsEnum.AccountRecentlyChanged - accountRecentlyChanged + /// + public static readonly RecommendationReasonsEnum AccountRecentlyChanged = new("accountRecentlyChanged"); + + /// + /// RecommendationReasonsEnum.AccountTooNew - accountTooNew + /// + public static readonly RecommendationReasonsEnum AccountTooNew = new("accountTooNew"); + + /// + /// RecommendationReasonsEnum.AccountTooNewSinceLaunch - accountTooNewSinceLaunch + /// + public static readonly RecommendationReasonsEnum AccountTooNewSinceLaunch = new("accountTooNewSinceLaunch"); + + /// + /// RecommendationReasonsEnum.CardholderPanAssociatedToAccountWithinThresholdDays - cardholderPanAssociatedToAccountWithinThresholdDays + /// + public static readonly RecommendationReasonsEnum CardholderPanAssociatedToAccountWithinThresholdDays = new("cardholderPanAssociatedToAccountWithinThresholdDays"); + + /// + /// RecommendationReasonsEnum.ChangesMadeToAccountDataWithinThresholdDays - changesMadeToAccountDataWithinThresholdDays + /// + public static readonly RecommendationReasonsEnum ChangesMadeToAccountDataWithinThresholdDays = new("changesMadeToAccountDataWithinThresholdDays"); + + /// + /// RecommendationReasonsEnum.DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry - deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry + /// + public static readonly RecommendationReasonsEnum DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry = new("deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry"); + + /// + /// RecommendationReasonsEnum.DeviceRecentlyLost - deviceRecentlyLost + /// + public static readonly RecommendationReasonsEnum DeviceRecentlyLost = new("deviceRecentlyLost"); + + /// + /// RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication - encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication + /// + public static readonly RecommendationReasonsEnum EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication = new("encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication"); + + /// + /// RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication - encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication + /// + public static readonly RecommendationReasonsEnum EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication = new("encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication"); + + /// + /// RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated - encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated + /// + public static readonly RecommendationReasonsEnum EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated = new("encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated"); + + /// + /// RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder - encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder + /// + public static readonly RecommendationReasonsEnum EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder = new("encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder"); + + /// + /// RecommendationReasonsEnum.HasSuspendedTokens - hasSuspendedTokens + /// + public static readonly RecommendationReasonsEnum HasSuspendedTokens = new("hasSuspendedTokens"); + + /// + /// RecommendationReasonsEnum.InactiveAccount - inactiveAccount + /// + public static readonly RecommendationReasonsEnum InactiveAccount = new("inactiveAccount"); + + /// + /// RecommendationReasonsEnum.IssuerDeferredIDVDecision - issuerDeferredIDVDecision + /// + public static readonly RecommendationReasonsEnum IssuerDeferredIDVDecision = new("issuerDeferredIDVDecision"); + + /// + /// RecommendationReasonsEnum.IssuerEncryptedPaymentInstrumentDataExpired - issuerEncryptedPaymentInstrumentDataExpired + /// + public static readonly RecommendationReasonsEnum IssuerEncryptedPaymentInstrumentDataExpired = new("issuerEncryptedPaymentInstrumentDataExpired"); + + /// + /// RecommendationReasonsEnum.LowAccountScore - lowAccountScore + /// + public static readonly RecommendationReasonsEnum LowAccountScore = new("lowAccountScore"); + + /// + /// RecommendationReasonsEnum.LowDeviceScore - lowDeviceScore + /// + public static readonly RecommendationReasonsEnum LowDeviceScore = new("lowDeviceScore"); + + /// + /// RecommendationReasonsEnum.LowPhoneNumberScore - lowPhoneNumberScore + /// + public static readonly RecommendationReasonsEnum LowPhoneNumberScore = new("lowPhoneNumberScore"); + + /// + /// RecommendationReasonsEnum.NumberOfActiveTokensGreaterThanThreshold - numberOfActiveTokensGreaterThanThreshold + /// + public static readonly RecommendationReasonsEnum NumberOfActiveTokensGreaterThanThreshold = new("numberOfActiveTokensGreaterThanThreshold"); + + /// + /// RecommendationReasonsEnum.NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold - numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold + /// + public static readonly RecommendationReasonsEnum NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold = new("numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold"); + + /// + /// RecommendationReasonsEnum.NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays - numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays + /// + public static readonly RecommendationReasonsEnum NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays = new("numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays"); + + /// + /// RecommendationReasonsEnum.NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold - numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold + /// + public static readonly RecommendationReasonsEnum NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold = new("numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold"); + + /// + /// RecommendationReasonsEnum.NumberOfTransactionsInLast12MonthsLessThanThresholdNumber - numberOfTransactionsInLast12MonthsLessThanThresholdNumber + /// + public static readonly RecommendationReasonsEnum NumberOfTransactionsInLast12MonthsLessThanThresholdNumber = new("numberOfTransactionsInLast12MonthsLessThanThresholdNumber"); + + /// + /// RecommendationReasonsEnum.OutSideHomeTerritory - outSideHomeTerritory + /// + public static readonly RecommendationReasonsEnum OutSideHomeTerritory = new("outSideHomeTerritory"); + + /// + /// RecommendationReasonsEnum.SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold - suspendedCardsInTheWALLETAccountIsGreaterThanThreshold + /// + public static readonly RecommendationReasonsEnum SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold = new("suspendedCardsInTheWALLETAccountIsGreaterThanThreshold"); + + /// + /// RecommendationReasonsEnum.SuspiciousActivity - suspiciousActivity + /// + public static readonly RecommendationReasonsEnum SuspiciousActivity = new("suspiciousActivity"); + + /// + /// RecommendationReasonsEnum.TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold - theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold + /// + public static readonly RecommendationReasonsEnum TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold = new("theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold"); + + /// + /// RecommendationReasonsEnum.TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold - theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold + /// + public static readonly RecommendationReasonsEnum TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold = new("theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold"); + + /// + /// RecommendationReasonsEnum.ThisAccountHasNotHadActivityWithinThresholdPeriod - thisAccountHasNotHadActivityWithinThresholdPeriod + /// + public static readonly RecommendationReasonsEnum ThisAccountHasNotHadActivityWithinThresholdPeriod = new("thisAccountHasNotHadActivityWithinThresholdPeriod"); + + /// + /// RecommendationReasonsEnum.TooManyDifferentCardholders - tooManyDifferentCardholders + /// + public static readonly RecommendationReasonsEnum TooManyDifferentCardholders = new("tooManyDifferentCardholders"); + + /// + /// RecommendationReasonsEnum.TooManyRecentAttempts - tooManyRecentAttempts + /// + public static readonly RecommendationReasonsEnum TooManyRecentAttempts = new("tooManyRecentAttempts"); + + /// + /// RecommendationReasonsEnum.TooManyRecentTokens - tooManyRecentTokens + /// + public static readonly RecommendationReasonsEnum TooManyRecentTokens = new("tooManyRecentTokens"); + + /// + /// RecommendationReasonsEnum.UnableToAssess - unableToAssess + /// + public static readonly RecommendationReasonsEnum UnableToAssess = new("unableToAssess"); + + /// + /// RecommendationReasonsEnum.Unknown - unknown + /// + public static readonly RecommendationReasonsEnum Unknown = new("unknown"); + + /// + /// RecommendationReasonsEnum.UserAccountWasCreatedWithinThresholdDays - userAccountWasCreatedWithinThresholdDays + /// + public static readonly RecommendationReasonsEnum UserAccountWasCreatedWithinThresholdDays = new("userAccountWasCreatedWithinThresholdDays"); + + /// + /// RecommendationReasonsEnum.UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken - userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken + /// + public static readonly RecommendationReasonsEnum UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken = new("userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken"); + + /// + /// RecommendationReasonsEnum.UsersAccountOnDeviceLessThanThresholdDays - usersAccountOnDeviceLessThanThresholdDays + /// + public static readonly RecommendationReasonsEnum UsersAccountOnDeviceLessThanThresholdDays = new("usersAccountOnDeviceLessThanThresholdDays"); + + /// + /// RecommendationReasonsEnum.WalletAccountCreatedWithinThresholdDays - walletAccountCreatedWithinThresholdDays + /// + public static readonly RecommendationReasonsEnum WalletAccountCreatedWithinThresholdDays = new("walletAccountCreatedWithinThresholdDays"); + + /// + /// RecommendationReasonsEnum.WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName - walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName + /// + public static readonly RecommendationReasonsEnum WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName = new("walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName"); + + private RecommendationReasonsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecommendationReasonsEnum?(string? value) => value == null ? null : new RecommendationReasonsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecommendationReasonsEnum? option) => option?.Value; + + public static bool operator ==(RecommendationReasonsEnum? left, RecommendationReasonsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecommendationReasonsEnum? left, RecommendationReasonsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecommendationReasonsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecommendationReasonsEnum? FromStringOrDefault(string value) + { + return value switch { + "accountCardTooNew" => RecommendationReasonsEnum.AccountCardTooNew, + "accountHighRisk" => RecommendationReasonsEnum.AccountHighRisk, + "accountRecentlyChanged" => RecommendationReasonsEnum.AccountRecentlyChanged, + "accountTooNew" => RecommendationReasonsEnum.AccountTooNew, + "accountTooNewSinceLaunch" => RecommendationReasonsEnum.AccountTooNewSinceLaunch, + "cardholderPanAssociatedToAccountWithinThresholdDays" => RecommendationReasonsEnum.CardholderPanAssociatedToAccountWithinThresholdDays, + "changesMadeToAccountDataWithinThresholdDays" => RecommendationReasonsEnum.ChangesMadeToAccountDataWithinThresholdDays, + "deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry" => RecommendationReasonsEnum.DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry, + "deviceRecentlyLost" => RecommendationReasonsEnum.DeviceRecentlyLost, + "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication" => RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication, + "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication" => RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication, + "encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated" => RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated, + "encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder" => RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder, + "hasSuspendedTokens" => RecommendationReasonsEnum.HasSuspendedTokens, + "inactiveAccount" => RecommendationReasonsEnum.InactiveAccount, + "issuerDeferredIDVDecision" => RecommendationReasonsEnum.IssuerDeferredIDVDecision, + "issuerEncryptedPaymentInstrumentDataExpired" => RecommendationReasonsEnum.IssuerEncryptedPaymentInstrumentDataExpired, + "lowAccountScore" => RecommendationReasonsEnum.LowAccountScore, + "lowDeviceScore" => RecommendationReasonsEnum.LowDeviceScore, + "lowPhoneNumberScore" => RecommendationReasonsEnum.LowPhoneNumberScore, + "numberOfActiveTokensGreaterThanThreshold" => RecommendationReasonsEnum.NumberOfActiveTokensGreaterThanThreshold, + "numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold" => RecommendationReasonsEnum.NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold, + "numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays" => RecommendationReasonsEnum.NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays, + "numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold" => RecommendationReasonsEnum.NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold, + "numberOfTransactionsInLast12MonthsLessThanThresholdNumber" => RecommendationReasonsEnum.NumberOfTransactionsInLast12MonthsLessThanThresholdNumber, + "outSideHomeTerritory" => RecommendationReasonsEnum.OutSideHomeTerritory, + "suspendedCardsInTheWALLETAccountIsGreaterThanThreshold" => RecommendationReasonsEnum.SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold, + "suspiciousActivity" => RecommendationReasonsEnum.SuspiciousActivity, + "theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold" => RecommendationReasonsEnum.TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold, + "theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold" => RecommendationReasonsEnum.TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold, + "thisAccountHasNotHadActivityWithinThresholdPeriod" => RecommendationReasonsEnum.ThisAccountHasNotHadActivityWithinThresholdPeriod, + "tooManyDifferentCardholders" => RecommendationReasonsEnum.TooManyDifferentCardholders, + "tooManyRecentAttempts" => RecommendationReasonsEnum.TooManyRecentAttempts, + "tooManyRecentTokens" => RecommendationReasonsEnum.TooManyRecentTokens, + "unableToAssess" => RecommendationReasonsEnum.UnableToAssess, + "unknown" => RecommendationReasonsEnum.Unknown, + "userAccountWasCreatedWithinThresholdDays" => RecommendationReasonsEnum.UserAccountWasCreatedWithinThresholdDays, + "userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken" => RecommendationReasonsEnum.UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken, + "usersAccountOnDeviceLessThanThresholdDays" => RecommendationReasonsEnum.UsersAccountOnDeviceLessThanThresholdDays, + "walletAccountCreatedWithinThresholdDays" => RecommendationReasonsEnum.WalletAccountCreatedWithinThresholdDays, + "walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName" => RecommendationReasonsEnum.WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecommendationReasonsEnum? value) + { + if (value == null) + return null; + + if (value == RecommendationReasonsEnum.AccountCardTooNew) + return "accountCardTooNew"; + + if (value == RecommendationReasonsEnum.AccountHighRisk) + return "accountHighRisk"; + + if (value == RecommendationReasonsEnum.AccountRecentlyChanged) + return "accountRecentlyChanged"; + + if (value == RecommendationReasonsEnum.AccountTooNew) + return "accountTooNew"; + + if (value == RecommendationReasonsEnum.AccountTooNewSinceLaunch) + return "accountTooNewSinceLaunch"; + + if (value == RecommendationReasonsEnum.CardholderPanAssociatedToAccountWithinThresholdDays) + return "cardholderPanAssociatedToAccountWithinThresholdDays"; + + if (value == RecommendationReasonsEnum.ChangesMadeToAccountDataWithinThresholdDays) + return "changesMadeToAccountDataWithinThresholdDays"; + + if (value == RecommendationReasonsEnum.DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry) + return "deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry"; + + if (value == RecommendationReasonsEnum.DeviceRecentlyLost) + return "deviceRecentlyLost"; + + if (value == RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication) + return "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication"; + + if (value == RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication) + return "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication"; + + if (value == RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated) + return "encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated"; + + if (value == RecommendationReasonsEnum.EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder) + return "encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder"; + + if (value == RecommendationReasonsEnum.HasSuspendedTokens) + return "hasSuspendedTokens"; + + if (value == RecommendationReasonsEnum.InactiveAccount) + return "inactiveAccount"; + + if (value == RecommendationReasonsEnum.IssuerDeferredIDVDecision) + return "issuerDeferredIDVDecision"; + + if (value == RecommendationReasonsEnum.IssuerEncryptedPaymentInstrumentDataExpired) + return "issuerEncryptedPaymentInstrumentDataExpired"; + + if (value == RecommendationReasonsEnum.LowAccountScore) + return "lowAccountScore"; + + if (value == RecommendationReasonsEnum.LowDeviceScore) + return "lowDeviceScore"; + + if (value == RecommendationReasonsEnum.LowPhoneNumberScore) + return "lowPhoneNumberScore"; + + if (value == RecommendationReasonsEnum.NumberOfActiveTokensGreaterThanThreshold) + return "numberOfActiveTokensGreaterThanThreshold"; + + if (value == RecommendationReasonsEnum.NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold) + return "numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold"; + + if (value == RecommendationReasonsEnum.NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays) + return "numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays"; + + if (value == RecommendationReasonsEnum.NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold) + return "numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold"; + + if (value == RecommendationReasonsEnum.NumberOfTransactionsInLast12MonthsLessThanThresholdNumber) + return "numberOfTransactionsInLast12MonthsLessThanThresholdNumber"; + + if (value == RecommendationReasonsEnum.OutSideHomeTerritory) + return "outSideHomeTerritory"; + + if (value == RecommendationReasonsEnum.SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold) + return "suspendedCardsInTheWALLETAccountIsGreaterThanThreshold"; + + if (value == RecommendationReasonsEnum.SuspiciousActivity) + return "suspiciousActivity"; + + if (value == RecommendationReasonsEnum.TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold) + return "theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold"; + + if (value == RecommendationReasonsEnum.TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold) + return "theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold"; + + if (value == RecommendationReasonsEnum.ThisAccountHasNotHadActivityWithinThresholdPeriod) + return "thisAccountHasNotHadActivityWithinThresholdPeriod"; + + if (value == RecommendationReasonsEnum.TooManyDifferentCardholders) + return "tooManyDifferentCardholders"; + + if (value == RecommendationReasonsEnum.TooManyRecentAttempts) + return "tooManyRecentAttempts"; + + if (value == RecommendationReasonsEnum.TooManyRecentTokens) + return "tooManyRecentTokens"; + + if (value == RecommendationReasonsEnum.UnableToAssess) + return "unableToAssess"; + + if (value == RecommendationReasonsEnum.Unknown) + return "unknown"; + + if (value == RecommendationReasonsEnum.UserAccountWasCreatedWithinThresholdDays) + return "userAccountWasCreatedWithinThresholdDays"; + + if (value == RecommendationReasonsEnum.UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken) + return "userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken"; + + if (value == RecommendationReasonsEnum.UsersAccountOnDeviceLessThanThresholdDays) + return "usersAccountOnDeviceLessThanThresholdDays"; + + if (value == RecommendationReasonsEnum.WalletAccountCreatedWithinThresholdDays) + return "walletAccountCreatedWithinThresholdDays"; + + if (value == RecommendationReasonsEnum.WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName) + return "walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName"; + + return null; + } + + /// + /// JsonConverter for writing RecommendationReasonsEnum. + /// + public class RecommendationReasonsEnumJsonConverter : JsonConverter + { + public override RecommendationReasonsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecommendationReasonsEnum.FromStringOrDefault(value) ?? new RecommendationReasonsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecommendationReasonsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecommendationReasonsEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountScoreOption { get; private set; } + + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**. + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**. + [JsonPropertyName("accountScore")] + public string? AccountScore { get { return this._AccountScoreOption; } set { this._AccountScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("device")] + public Device? Device { get { return this._DeviceOption; } set { this._DeviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceScoreOption { get; private set; } + + /// + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**. + /// + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**. + [JsonPropertyName("deviceScore")] + public string? DeviceScore { get { return this._DeviceScoreOption; } set { this._DeviceScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProvisioningMethodOption { get; private set; } + + /// + /// The method used for provisioning the network token. Possible values: **push**, **manual**, **cof**, **unknown**. + /// + /// The method used for provisioning the network token. Possible values: **push**, **manual**, **cof**, **unknown**. + [JsonPropertyName("provisioningMethod")] + public string? ProvisioningMethod { get { return this._ProvisioningMethodOption; } set { this._ProvisioningMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RecommendationReasonsOption { get; private set; } + + /// + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** + /// + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** + [JsonPropertyName("recommendationReasons")] + public List? RecommendationReasons { get { return this._RecommendationReasonsOption; } set { this._RecommendationReasonsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**. + /// + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**. + [JsonPropertyName("type")] + [Obsolete("Deprecated since Configuration webhooks v2. Use name of the `tokenRequestor` instead.")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Wallet {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" Device: ").Append(Device).Append("\n"); + sb.Append(" DeviceScore: ").Append(DeviceScore).Append("\n"); + sb.Append(" ProvisioningMethod: ").Append(ProvisioningMethod).Append("\n"); + sb.Append(" RecommendationReasons: ").Append(RecommendationReasons).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WalletJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Wallet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option device = default; + Option deviceScore = default; + Option provisioningMethod = default; + Option?> recommendationReasons = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.GetString()!); + break; + case "device": + device = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deviceScore": + deviceScore = new Option(utf8JsonReader.GetString()!); + break; + case "provisioningMethod": + provisioningMethod = new Option(utf8JsonReader.GetString()!); + break; + case "recommendationReasons": + recommendationReasons = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Wallet(accountScore, device, deviceScore, provisioningMethod, recommendationReasons, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Wallet wallet, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, wallet, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Wallet wallet, JsonSerializerOptions jsonSerializerOptions) + { + + if (wallet._AccountScoreOption.IsSet) + if (wallet.AccountScore != null) + writer.WriteString("accountScore", wallet.AccountScore); + + if (wallet._DeviceOption.IsSet) + { + writer.WritePropertyName("device"); + JsonSerializer.Serialize(writer, wallet.Device, jsonSerializerOptions); + } + if (wallet._DeviceScoreOption.IsSet) + if (wallet.DeviceScore != null) + writer.WriteString("deviceScore", wallet.DeviceScore); + + if (wallet._ProvisioningMethodOption.IsSet) + if (wallet.ProvisioningMethod != null) + writer.WriteString("provisioningMethod", wallet.ProvisioningMethod); + + if (wallet._RecommendationReasonsOption.IsSet) + { + writer.WritePropertyName("recommendationReasons"); + JsonSerializer.Serialize(writer, wallet.RecommendationReasons, jsonSerializerOptions); + } + if (wallet._TypeOption.IsSet) + if (wallet.Type != null) + writer.WriteString("type", wallet.Type); + } + } +} diff --git a/Adyen/Constants/ApiConstants.cs b/Adyen/Constants/ApiConstants.cs deleted file mode 100644 index ce75cf190..000000000 --- a/Adyen/Constants/ApiConstants.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Adyen.Constants -{ - public class ApiConstants - { - public const string AdyenLibraryName = "adyen-library-name"; - public const string AdyenLibraryVersion = "adyen-library-version"; - } -} diff --git a/Adyen/Constants/ClientConfig.cs b/Adyen/Constants/ClientConfig.cs deleted file mode 100644 index 8e6ce0e55..000000000 --- a/Adyen/Constants/ClientConfig.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Adyen.Constants -{ - public class ClientConfig - { - //Test cloud api endpoints - public const string CloudApiEndPointTest = "https://terminal-api-test.adyen.com"; - - //Live cloud api endpoints - public const string CloudApiEndPointEULive = "https://terminal-api-live.adyen.com"; - public const string CloudApiEndPointAULive = "https://terminal-api-live-au.adyen.com"; - public const string CloudApiEndPointUSLive = "https://terminal-api-live-us.adyen.com"; - public const string CloudApiEndPointAPSELive = "https://terminal-api-live-apse.adyen.com"; - - public const string UserAgentSuffix = "adyen-dotnet-api-library/"; - public const string NexoProtocolVersion = "3.0"; - - public const string LibName = "adyen-dotnet-api-library"; - public const string LibVersion = "32.0.0"; - } -} diff --git a/Adyen/Core/Auth/TokenBase.cs b/Adyen/Core/Auth/TokenBase.cs new file mode 100644 index 000000000..a0afd072c --- /dev/null +++ b/Adyen/Core/Auth/TokenBase.cs @@ -0,0 +1,20 @@ +#nullable enable + +using System; + +namespace Adyen.Core.Auth +{ + /// + /// The base class for all auth tokens. + /// + public abstract class TokenBase + { + /// + /// The constructor for the TokenBase object, used by . + /// + protected TokenBase() + { + + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Auth/TokenProvider.cs b/Adyen/Core/Auth/TokenProvider.cs new file mode 100644 index 000000000..745cca691 --- /dev/null +++ b/Adyen/Core/Auth/TokenProvider.cs @@ -0,0 +1,42 @@ +namespace Adyen.Core.Auth +{ + /// + /// An interface for providing tokens in a generic way. + /// + /// + public interface ITokenProvider where TTokenBase : TokenBase + { + /// + /// Retrieves the stored token. + /// + /// + TTokenBase Get(); + } + + /// + /// A class which will provide tokens from type . + /// + /// + public class TokenProvider : ITokenProvider where TTokenBase : TokenBase + { + private readonly TTokenBase _token; + + /// + /// Initializes a token with type . + /// + /// + public TokenProvider(TTokenBase token) + { + _token = token; + } + + /// + /// Retrieves the stored token. + /// + /// + public TTokenBase Get() + { + return _token; + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Client/ApiException.cs b/Adyen/Core/Client/ApiException.cs new file mode 100644 index 000000000..23a732bc9 --- /dev/null +++ b/Adyen/Core/Client/ApiException.cs @@ -0,0 +1,40 @@ +#nullable enable + +using System; + +namespace Adyen.Core.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the API + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// Reason for ApiException + /// + /// Raw content + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + StatusCode = statusCode; + RawContent = rawContent; + } + } +} diff --git a/Adyen/Core/Client/ApiFactory.cs b/Adyen/Core/Client/ApiFactory.cs new file mode 100644 index 000000000..2c073ba34 --- /dev/null +++ b/Adyen/Core/Client/ApiFactory.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace Adyen.Core.Client +{ + /// + /// The factory interface for creating the services that can communicate with the Adyen APIs. + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IAdyenApiService; + } + + /// + /// The implementation of . + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IAdyenApiService + { + return Services.GetRequiredService(); + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Client/ApiResponse.cs b/Adyen/Core/Client/ApiResponse.cs new file mode 100644 index 000000000..1eb24e24b --- /dev/null +++ b/Adyen/Core/Client/ApiResponse.cs @@ -0,0 +1,371 @@ +#nullable enable +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; + +namespace Adyen.Core.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the API response. + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (). + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The raw binary stream (only set for binary responses). + /// + System.IO.Stream? ContentStream { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the API response. + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the API response. + /// + string? ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri? RequestUri { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code). + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data. + /// + public string RawContent { get; protected set; } + + /// + /// The raw binary stream (only set for binary responses). + /// + public System.IO.Stream? ContentStream { get; protected set; } + + /// + /// The IsSuccessStatusCode from the API response. + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the API response. + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the API response. + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime (default: UtcNow) when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The used when making the request. + /// + public Uri? RequestUri { get; } + + /// + /// The . + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage. + /// + /// . + /// + /// The raw data. + /// The path used when making the request. + /// The when the request was sent. + /// The . + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + } + + /// + /// Construct the response using the . + /// + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was sent. + /// The . + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + ContentStream = contentStream; + RawContent = string.Empty; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + } + } + + /// + /// An interface for responses of type BadRequest. + /// + /// + public interface IBadRequest : IApiResponse + { + /// + /// Deserializes the response if the response is BadRequest. + /// + /// + TType BadRequest(); + + /// + /// Returns true if the response is BadRequest and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type TooManyRequests. + /// + /// + public interface ITooManyRequests : IApiResponse + { + /// + /// Deserializes the response if the response is TooManyRequests. + /// + /// + TType TooManyRequests(); + + /// + /// Returns true if the response is TooManyRequests and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type Unauthorized. + /// + /// + public interface IUnauthorized : IApiResponse + { + /// + /// Deserializes the response if the response is Unauthorized. + /// + /// + TType Unauthorized(); + + /// + /// Returns true if the response is Unauthorized and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type Forbidden. + /// + /// + public interface IForbidden : IApiResponse + { + /// + /// Deserializes the response if the response is Forbidden. + /// + /// + TType Forbidden(); + + /// + /// Returns true if the response is Forbidden and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type Ok. + /// + /// + public interface IOk : IApiResponse + { + /// + /// Deserializes the response if the response is Ok. + /// + /// + TType Ok(); + + /// + /// Returns true if the response is Ok and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeOkResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type UnprocessableContent. + /// + /// + public interface IUnprocessableContent : IApiResponse + { + /// + /// Deserializes the response if the response is UnprocessableContent. + /// + /// + TType UnprocessableContent(); + + /// + /// Returns true if the response is UnprocessableContent and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type InternalServerError. + /// + /// + public interface IInternalServerError : IApiResponse + { + /// + /// Deserializes the response if the response is InternalServerError. + /// + /// + TType InternalServerError(); + + /// + /// Returns true if the response is InternalServerError and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type Created. + /// + /// + public interface ICreated : IApiResponse + { + /// + /// Deserializes the response if the response is Created. + /// + /// + TType Created(); + + /// + /// Returns true if the response is Created and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeCreatedResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type Accepted. + /// + /// + public interface IAccepted : IApiResponse + { + /// + /// Deserializes the response if the response is Accepted. + /// + /// + TType Accepted(); + + /// + /// Returns true if the response is Accepted and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeAcceptedResponse([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type NotFound. + /// + /// + public interface INotFound : IApiResponse + { + /// + /// Deserializes the response if the response is NotFound. + /// + /// + TType NotFound(); + + /// + /// Returns true if the response is NotFound and the deserialized response is not null. + /// + /// + /// + bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out TType? result); + } +} diff --git a/Adyen/Core/Client/ApiResponseEventArgs.cs b/Adyen/Core/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000..7f6d48f23 --- /dev/null +++ b/Adyen/Core/Client/ApiResponseEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace Adyen.Core.Client +{ + /// + /// This class is used for wrapping the . + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The . + /// + public ApiResponse ApiResponse { get; } + + /// + /// The constructed from the Adyen . + /// + /// . + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/Adyen/Core/Client/ExceptionEventArgs.cs b/Adyen/Core/Client/ExceptionEventArgs.cs new file mode 100644 index 000000000..1cbfc25fa --- /dev/null +++ b/Adyen/Core/Client/ExceptionEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace Adyen.Core.Client +{ + /// + /// Useful for tracking server health + /// + public class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse exception + /// + public Exception Exception { get; } + + /// + /// The ExceptionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/Adyen/Core/Client/Extensions/HttpClientBuilderExtensions.cs b/Adyen/Core/Client/Extensions/HttpClientBuilderExtensions.cs new file mode 100644 index 000000000..bc5187d30 --- /dev/null +++ b/Adyen/Core/Client/Extensions/HttpClientBuilderExtensions.cs @@ -0,0 +1,68 @@ +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Adyen.Core.Client.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class HttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// . + /// The number of retries. + /// . + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder httpClient, int numberOfRetries) + { + httpClient.AddPolicyHandler(RetryPolicy(numberOfRetries)); + return httpClient; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int numberOfRetries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(numberOfRetries); + + /// + /// Adds a Polly timeout policy to your clients. + /// Use this when you need resilient policies (using the ) and want to combine this with a retry & circuit breaker. + /// + /// . + /// . + /// . + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder httpClient, TimeSpan timeout) + { + httpClient.AddPolicyHandler(TimeoutPolicy(timeout)); + return httpClient; + } + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// . + /// Example: if set to 3 - if 3 consecutive request fail, Polly will 'open' the circuit for the duration of and fail all incoming requests. After that, the circuit will be 'half-open'. + /// . + /// . + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder httpClient, int numberOfEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + httpClient.AddTransientHttpErrorPolicy(policyBuilder => CircuitBreakerPolicy(policyBuilder, numberOfEventsAllowedBeforeBreaking, durationOfBreak)); + return httpClient; + } + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder policyBuilder, int numberOfEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => policyBuilder.CircuitBreakerAsync(numberOfEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/Adyen/Core/Client/Extensions/HttpRequestMessageExtensions.cs b/Adyen/Core/Client/Extensions/HttpRequestMessageExtensions.cs new file mode 100644 index 000000000..815a00ac7 --- /dev/null +++ b/Adyen/Core/Client/Extensions/HttpRequestMessageExtensions.cs @@ -0,0 +1,63 @@ +namespace Adyen.Core.Client.Extensions +{ + /// + /// Extension function that adds custom headers and UserAgent to the . + /// + public static class HttpRequestMessageExtensions + { + /// + /// The name of the application. + /// + public static string ApplicationName { get; set; } + + /// + /// Name of this library. This will be sent as a part of the headers. + /// + public const string AdyenLibraryName = "adyen-dotnet-api-library"; + + /// + /// Version of this library. + /// + public const string AdyenLibraryVersion = "32.2.1"; // Updated by release-automation-action + + /// + /// Adds the UserAgent to the headers of the object. + /// + /// . + /// . + public static HttpRequestMessage AddUserAgentToHeaders(this HttpRequestMessage httpRequestMessage) + { + // Add application name if set. + if (!string.IsNullOrWhiteSpace(ApplicationName)) + { + httpRequestMessage.Headers.Add("UserAgent", $"{ApplicationName} {AdyenLibraryName}/{AdyenLibraryVersion}"); + return httpRequestMessage; + } + + httpRequestMessage.Headers.Add("UserAgent", $"{AdyenLibraryName}/{AdyenLibraryVersion}"); + return httpRequestMessage; + } + + /// + /// Adds the to the headers of the object. + /// + /// . + /// . + public static HttpRequestMessage AddLibraryNameToHeader(this HttpRequestMessage httpRequestMessage) + { + httpRequestMessage.Headers.Add("adyen-library-name", AdyenLibraryName); + return httpRequestMessage; + } + + /// + /// Adds the to the headers of the object. + /// + /// . + /// . + public static HttpRequestMessage AddLibraryVersionToHeader(this HttpRequestMessage httpRequestMessage) + { + httpRequestMessage.Headers.Add("adyen-library-version", AdyenLibraryVersion); + return httpRequestMessage; + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Client/IAdyenApiService.cs b/Adyen/Core/Client/IAdyenApiService.cs new file mode 100644 index 000000000..ca6e164d6 --- /dev/null +++ b/Adyen/Core/Client/IAdyenApiService.cs @@ -0,0 +1,13 @@ +namespace Adyen.Core.Client +{ + /// + /// Interface for interacting with any Adyen API using . + /// + public interface IAdyenApiService + { + /// + /// The object, best practice: instantiate and manage object using the . + /// + System.Net.Http.HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/Adyen/Core/Client/RequestOptions.cs b/Adyen/Core/Client/RequestOptions.cs new file mode 100644 index 000000000..8c61091cb --- /dev/null +++ b/Adyen/Core/Client/RequestOptions.cs @@ -0,0 +1,75 @@ +#nullable enable + +namespace Adyen.Core.Client +{ + public class RequestOptions + { + /// + /// Dictionary containing the optional header values. If set, these values will be sent in the HttpRequest when is called. + /// + public IDictionary Headers { get; private set; } = new Dictionary(); + + + #region Helper functions to append headers to the Headers dictionary. + + /// + /// Add the "IdempotencyKey" to the headers with the given value. + /// The Adyen API supports idempotency, allowing you to retry a request multiple times while only performing the action once. + /// This helps avoid unwanted duplication in case of failures and retries. + /// + /// The value of the IdempotencyKey. + /// . + public RequestOptions AddIdempotencyKey(string idempotencyKey) + { + this.Headers.Add("Idempotency-Key", idempotencyKey); + return this; + } + + /// + /// Adds additional custom headers with the given keys and values. + /// + /// The values. + /// . + public RequestOptions AddAdditionalHeaders(IDictionary additionalHeaders) + { + foreach (KeyValuePair kvp in additionalHeaders) + this.Headers.Add(kvp.Key, kvp.Value); + return this; + } + + /// + /// Adds the "WWW-Authenticate" to the headers with the given value. Used in the Configuration and Transfers API. + /// + /// The value of WWW-Authenticate. + /// . + public RequestOptions AddWWWAuthenticateHeader(string wwwAuthenticate) + { + this.Headers.Add("WWW-Authenticate", wwwAuthenticate); + return this; + } + + /// + /// Adds the "x-requested-verification-code" to the headers with the given value. Used in the LegalEntityManagement API. + /// + /// The value of x-requested-verification-code. + /// . + public RequestOptions AddxRequestedVerificationCodeHeader(string xRequestedVerificationCodeHeader) + { + this.Headers.Add("x-requested-verification-code", xRequestedVerificationCodeHeader); + return this; + } + + #endregion + + /// + /// Adds all key-value-pairs from to the header. + /// + /// + public System.Net.Http.HttpRequestMessage AddHeadersToHttpRequestMessage(System.Net.Http.HttpRequestMessage httpRequestMessage) + { + foreach (KeyValuePair header in this.Headers) + httpRequestMessage.Headers.Add(header.Key, header.Value); + return httpRequestMessage; + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Client/UrlBuilderExtensions.cs b/Adyen/Core/Client/UrlBuilderExtensions.cs new file mode 100644 index 000000000..37885f81a --- /dev/null +++ b/Adyen/Core/Client/UrlBuilderExtensions.cs @@ -0,0 +1,80 @@ +using Adyen.Core.Options; + +namespace Adyen.Core.Client +{ + /// + /// Helper utility functions to construct the Adyen live-urls for our APIs. + /// + public static class UrlBuilderExtensions + { + /// + /// Constructs the Host URL based on the selected , used to populate the `HttpClient.BaseAddress`. + /// + /// . + /// The base URL of the API. + /// String containing the Host URL. + /// + public static string ConstructHostUrl(AdyenOptions adyenOptions, string baseUrl) + { + if (adyenOptions.Environment == AdyenEnvironment.Live) + return ConstructLiveUrl(adyenOptions.LiveEndpointUrlPrefix, baseUrl); + + // Some Adyen OpenApi Specifications use the live-url, instead of the test-url, this line replaces "-live" with "-test". + // If you need to override this URL, you can do so by replacing the BASE_URL in ClientUtils.cs. + if (adyenOptions.Environment == AdyenEnvironment.Test) + return baseUrl.Replace("-live", "-test"); + + throw new ArgumentOutOfRangeException(adyenOptions.Environment.ToString()); + } + + /// + /// Construct LIVE BaseUrl, add the liveEndpointUrlPrefix it's the Checkout API or the Classic Payment API. + /// This helper function can be removed when all URLs (test & live) are included in the Adyen OpenApi Specifications: https://github.com/Adyen/adyen-openapi. + /// + /// The Live endpoint url prefix. + /// The base URL of the API. + /// String containing the LIVE URL. + /// + public static string ConstructLiveUrl(string liveEndpointUrlPrefix, string url) + { + // Change base url for Live environment + if (url.Contains("pal-")) // Payment API prefix + { + if (liveEndpointUrlPrefix == null) + { + throw new InvalidOperationException("LiveEndpointUrlPrefix is null - please configure your AdyenOptions.LiveEndpointUrlPrefix"); + } + + url = url.Replace("https://pal-test.adyen.com/pal/servlet/", + "https://" + liveEndpointUrlPrefix + "-pal-live.adyenpayments.com/pal/servlet/"); + } + else if (url.Contains("checkout-")) // Checkout API prefix + { + if (liveEndpointUrlPrefix == null) + { + throw new InvalidOperationException("LiveEndpointUrlPrefix is null - please configure your AdyenOptions.LiveEndpointUrlPrefix"); + } + + if (url.Contains("possdk")) + { + url = url.Replace("https://checkout-test.adyen.com/", + "https://" + liveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/"); + } + else + { + url = url.Replace("https://checkout-test.adyen.com/", + "https://" + liveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/checkout/"); + } + } + else if (url.Contains("https://test.adyen.com/authe/api/")) // SessionAuthentication + { + url = url.Replace("https://test.adyen.com/authe/api/", + "https://authe-live.adyen.com/authe/api/"); + } + + // If no prefix is required, we replace "test" -> "live" + url = url.Replace("-test", "-live"); + return url; + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Converters/ByteArrayConverter.cs b/Adyen/Core/Converters/ByteArrayConverter.cs new file mode 100644 index 000000000..0b1ba4071 --- /dev/null +++ b/Adyen/Core/Converters/ByteArrayConverter.cs @@ -0,0 +1,45 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Adyen.Core.Converters +{ + /// + /// JsonConverter for byte arrays. + /// + public class ByteArrayConverter : JsonConverter + { + /// + /// Reads a byte array during deserialization. + /// + /// . + /// . + /// . + /// Byte array. + public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(); + return Encoding.UTF8.GetBytes(value); + } + + /// + /// Writes a byte array during serialization. + /// + /// . + /// . + /// . + public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + + writer.WriteStringValue(Encoding.UTF8.GetString(value)); + } + } +} \ No newline at end of file diff --git a/Adyen/Core/Converters/DateOnlyJsonConverter.cs b/Adyen/Core/Converters/DateOnlyJsonConverter.cs new file mode 100644 index 000000000..523644b08 --- /dev/null +++ b/Adyen/Core/Converters/DateOnlyJsonConverter.cs @@ -0,0 +1,52 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Adyen.Core.Converters +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date. + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a from the Json object. + /// + /// . + /// . + /// . + /// . + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the to the . + /// + /// . + /// . + /// . + public override void Write(Utf8JsonWriter writer, DateOnly dateOnly, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnly.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/Adyen/Core/Converters/DateOnlyNullableJsonConverter.cs b/Adyen/Core/Converters/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000..91ddb3b49 --- /dev/null +++ b/Adyen/Core/Converters/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,57 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Adyen.Core.Converters +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date. + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a nullable from the Json object. + /// + /// . + /// . + /// . + /// . + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the to the . + /// + /// . + /// . + /// . + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnly, JsonSerializerOptions options) + { + if (dateOnly == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnly.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/Adyen/Core/Converters/DateTimeJsonConverter.cs b/Adyen/Core/Converters/DateTimeJsonConverter.cs new file mode 100644 index 000000000..43a758362 --- /dev/null +++ b/Adyen/Core/Converters/DateTimeJsonConverter.cs @@ -0,0 +1,66 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Adyen.Core.Converters +{ + /// + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date. + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + + }; + + /// + /// Returns a from the Json object. + /// + /// . + /// . + /// . + /// . + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the to the . + /// + /// . + /// . + /// . + public override void Write(Utf8JsonWriter writer, DateTime dateTime, JsonSerializerOptions options) => + writer.WriteStringValue(dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } +} diff --git a/Adyen/Core/Converters/DateTimeNullableJsonConverter.cs b/Adyen/Core/Converters/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000..abfa0c099 --- /dev/null +++ b/Adyen/Core/Converters/DateTimeNullableJsonConverter.cs @@ -0,0 +1,71 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Adyen.Core.Converters +{ + /// + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date. + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + + }; + + /// + /// Returns a nullable from the Json object. + /// + /// . + /// . + /// . + /// . + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the to the . + /// + /// . + /// . + /// . + public override void Write(Utf8JsonWriter writer, DateTime? dateTime, JsonSerializerOptions options) + { + if (dateTime == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } + } +} diff --git a/Adyen/Core/IEnum.cs b/Adyen/Core/IEnum.cs new file mode 100644 index 000000000..11055cb53 --- /dev/null +++ b/Adyen/Core/IEnum.cs @@ -0,0 +1,11 @@ +namespace Adyen.Core +{ + /// + /// Interface for defining enums. + /// This interface is used to make enums forward-compatible. + /// + public interface IEnum + { + string? Value { get; set; } + } +} \ No newline at end of file diff --git a/Adyen/Core/Option.cs b/Adyen/Core/Option.cs new file mode 100644 index 000000000..407cd4532 --- /dev/null +++ b/Adyen/Core/Option.cs @@ -0,0 +1,48 @@ +#nullable enable + + +namespace Adyen.Core +{ + /// + /// A wrapper for operation parameters which are not required. + /// + public struct Option + { + /// + /// The value to send to the server. + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server. + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required. + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type. + /// + /// + /// + /// . + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option. + /// + /// . + /// + /// Option of . + public static implicit operator Option(TType value) => new Option(value); + + } +} \ No newline at end of file diff --git a/Adyen/Core/Options/AdyenEnvironment.cs b/Adyen/Core/Options/AdyenEnvironment.cs new file mode 100644 index 000000000..6d98e4fe0 --- /dev/null +++ b/Adyen/Core/Options/AdyenEnvironment.cs @@ -0,0 +1,12 @@ +namespace Adyen.Core.Options +{ + /// + /// The Adyen Environment. + /// Changing this value affects the ClientUtils.BASE_URL where your API requests are sent. + /// + public enum AdyenEnvironment + { + Test, + Live + } +} \ No newline at end of file diff --git a/Adyen/Core/Options/AdyenOptions.cs b/Adyen/Core/Options/AdyenOptions.cs new file mode 100644 index 000000000..3c7e257cd --- /dev/null +++ b/Adyen/Core/Options/AdyenOptions.cs @@ -0,0 +1,36 @@ +namespace Adyen.Core.Options +{ + /// + /// Stores the variables used to communicate with the Adyen platforms. + /// + public class AdyenOptions + { + /// + /// The Adyen Environment. + /// + public AdyenEnvironment Environment { get; set; } = AdyenEnvironment.Test; + + /// + /// Used in the LIVE environment only. + /// This prefix is appended to HttpClient.BaseAddress when is set to `AdyenEnvironment.Live` + /// See: https://docs.adyen.com/development-resources/live-endpoints/ + /// + public string LiveEndpointUrlPrefix { get; set; } + + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public string AdyenApiKey { get; set; } + + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public string AdyenHmacKey { get; set; } + } +} \ No newline at end of file diff --git a/Adyen/Core/Utilities/HmacValidatorUtility.cs b/Adyen/Core/Utilities/HmacValidatorUtility.cs new file mode 100644 index 000000000..0a44ed2b0 --- /dev/null +++ b/Adyen/Core/Utilities/HmacValidatorUtility.cs @@ -0,0 +1,86 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Adyen.Core.Utilities +{ + /// + /// Utility class to help verify hmac signatures from incoming webhooks. + /// + public static class HmacValidatorUtility + { + /// + /// Generates the Base64 encoded signature using the HMAC algorithm with the SHA256 hashing function. + /// + /// The JSON payload. + /// The secret ADYEN_HMAC_KEY, retrieved from the Adyen Customer Area. + /// The HMAC string for the payload. + /// + public static string GenerateBase64Sha256HmacSignature(string payload, string hmacKey) + { + byte[] key = ConvertHexadecimalToBytes(hmacKey); + byte[] data = Encoding.UTF8.GetBytes(payload); + + try + { + using (HMACSHA256 hmac = new HMACSHA256(key)) + { + // Compute the hmac on input data bytes + byte[] rawHmac = hmac.ComputeHash(data); + + // Base64-encode the hmac + return Convert.ToBase64String(rawHmac); + } + } + catch (Exception e) + { + throw new Exception("Failed to generate HMAC signature: " + e.Message, e); + } + } + + /// + /// Converts a hexadecimal into a byte array. + /// + /// The hexadecimal string. + /// An array of bytes that repesents the hexadecimalString. + private static byte[] ConvertHexadecimalToBytes(string hexadecimalString) + { + if ((hexadecimalString.Length % 2) == 1) + { + hexadecimalString += '0'; + } + + byte[] bytes = new byte[hexadecimalString.Length / 2]; + for (int i = 0; i < hexadecimalString.Length; i += 2) + { + bytes[i / 2] = Convert.ToByte(hexadecimalString.Substring(i, 2), 16); + } + + return bytes; + } + + /// + /// Validates a balance platform and management webhook payload with the given and . + /// + /// The HMAC signature, retrieved from the request header. + /// The HMAC key, retrieved from the Adyen Customer Area. + /// The webhook JSON payload. + /// A return value indicates the HMAC validation succeeded. + public static bool IsHmacSignatureValid(string hmacSignature, string hmacKey, string payload) + { + string signature = GenerateBase64Sha256HmacSignature(payload, hmacKey); + return TimeSafeEquals(Encoding.UTF8.GetBytes(hmacSignature), Encoding.UTF8.GetBytes(signature)); + } + + /// + /// This method compares two bytestrings in constant time based on length of shortest bytestring to prevent timing attacks. + /// + /// True if there's a difference. + private static bool TimeSafeEquals(byte[] a, byte[] b) + { + uint diff = (uint)a.Length ^ (uint)b.Length; + for (int i = 0; i < a.Length && i < b.Length; i++) { diff |= (uint)(a[i] ^ b[i]); } + return diff == 0; + } + } +} + diff --git a/Adyen/DataProtection/Client/ApiKeyToken.cs b/Adyen/DataProtection/Client/ApiKeyToken.cs new file mode 100644 index 000000000..fb9d6491b --- /dev/null +++ b/Adyen/DataProtection/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.DataProtection.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/DataProtection/Client/ClientUtils.cs b/Adyen/DataProtection/Client/ClientUtils.cs new file mode 100644 index 000000000..c047a4d75 --- /dev/null +++ b/Adyen/DataProtection/Client/ClientUtils.cs @@ -0,0 +1,315 @@ +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.DataProtection.Models; +using Models = Adyen.DataProtection.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.DataProtection.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.SubjectErasureResponse.ResultEnum subjectErasureResponseResultEnum) + return Models.SubjectErasureResponse.ResultEnum.ToJsonValue(subjectErasureResponseResultEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/DataProtection/Client/HostConfiguration.cs b/Adyen/DataProtection/Client/HostConfiguration.cs new file mode 100644 index 000000000..db50deb45 --- /dev/null +++ b/Adyen/DataProtection/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.DataProtection.Services; +using Adyen.DataProtection.Client; +using Adyen.DataProtection.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.DataProtection.Client +{ + /// + /// Provides hosting configuration for DataProtection + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://ca-test.adyen.com/ca/services/DataProtectionService/v1"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new SubjectErasureByPspReferenceRequestJsonConverter()); + _jsonOptions.Converters.Add(new SubjectErasureResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddDataProtectionHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/DataProtection/Client/JsonSerializerOptionsProvider.cs b/Adyen/DataProtection/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..9d7c5c0d0 --- /dev/null +++ b/Adyen/DataProtection/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.DataProtection.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/DataProtection/Extensions/HostBuilderExtensions.cs b/Adyen/DataProtection/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..38bbba7f0 --- /dev/null +++ b/Adyen/DataProtection/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.DataProtection; +using Adyen.DataProtection.Client; + +namespace Adyen.DataProtection.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the DataProtection API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureDataProtection(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddDataProtectionHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/DataProtection/Extensions/ServiceCollectionExtensions.cs b/Adyen/DataProtection/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..7e132e30c --- /dev/null +++ b/Adyen/DataProtection/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.DataProtection.Client; + +namespace Adyen.DataProtection.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen DataProtection API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddDataProtectionServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddDataProtectionHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/DataProtection/Models/ServiceError.cs b/Adyen/DataProtection/Models/ServiceError.cs new file mode 100644 index 000000000..7a804ada0 --- /dev/null +++ b/Adyen/DataProtection/Models/ServiceError.cs @@ -0,0 +1,276 @@ +// +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DataProtection.Client; + +namespace Adyen.DataProtection.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/DataProtection/Models/SubjectErasureByPspReferenceRequest.cs b/Adyen/DataProtection/Models/SubjectErasureByPspReferenceRequest.cs new file mode 100644 index 000000000..383cd8954 --- /dev/null +++ b/Adyen/DataProtection/Models/SubjectErasureByPspReferenceRequest.cs @@ -0,0 +1,226 @@ +// +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DataProtection.Client; + +namespace Adyen.DataProtection.Models +{ + /// + /// SubjectErasureByPspReferenceRequest. + /// + public partial class SubjectErasureByPspReferenceRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Set this to **true** if you want to delete shopper-related data, even if the shopper has an existing recurring transaction. This only deletes the shopper-related data for the specific payment, but does not cancel the existing recurring transaction. + /// Your merchant account + /// The PSP reference of the payment. We will delete all shopper-related data for this payment. + [JsonConstructor] + public SubjectErasureByPspReferenceRequest(Option forceErasure = default, Option merchantAccount = default, Option pspReference = default) + { + _ForceErasureOption = forceErasure; + _MerchantAccountOption = merchantAccount; + _PspReferenceOption = pspReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubjectErasureByPspReferenceRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ForceErasureOption { get; private set; } + + /// + /// Set this to **true** if you want to delete shopper-related data, even if the shopper has an existing recurring transaction. This only deletes the shopper-related data for the specific payment, but does not cancel the existing recurring transaction. + /// + /// Set this to **true** if you want to delete shopper-related data, even if the shopper has an existing recurring transaction. This only deletes the shopper-related data for the specific payment, but does not cancel the existing recurring transaction. + [JsonPropertyName("forceErasure")] + public bool? ForceErasure { get { return this._ForceErasureOption; } set { this._ForceErasureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// Your merchant account + /// + /// Your merchant account + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. We will delete all shopper-related data for this payment. + /// + /// The PSP reference of the payment. We will delete all shopper-related data for this payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubjectErasureByPspReferenceRequest {\n"); + sb.Append(" ForceErasure: ").Append(ForceErasure).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubjectErasureByPspReferenceRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubjectErasureByPspReferenceRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option forceErasure = default; + Option merchantAccount = default; + Option pspReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "forceErasure": + forceErasure = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SubjectErasureByPspReferenceRequest(forceErasure, merchantAccount, pspReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubjectErasureByPspReferenceRequest subjectErasureByPspReferenceRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subjectErasureByPspReferenceRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubjectErasureByPspReferenceRequest subjectErasureByPspReferenceRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (subjectErasureByPspReferenceRequest._ForceErasureOption.IsSet) + writer.WriteBoolean("forceErasure", subjectErasureByPspReferenceRequest._ForceErasureOption.Value!.Value); + + if (subjectErasureByPspReferenceRequest._MerchantAccountOption.IsSet) + if (subjectErasureByPspReferenceRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", subjectErasureByPspReferenceRequest.MerchantAccount); + + if (subjectErasureByPspReferenceRequest._PspReferenceOption.IsSet) + if (subjectErasureByPspReferenceRequest.PspReference != null) + writer.WriteString("pspReference", subjectErasureByPspReferenceRequest.PspReference); + } + } +} diff --git a/Adyen/DataProtection/Models/SubjectErasureResponse.cs b/Adyen/DataProtection/Models/SubjectErasureResponse.cs new file mode 100644 index 000000000..01fdacc58 --- /dev/null +++ b/Adyen/DataProtection/Models/SubjectErasureResponse.cs @@ -0,0 +1,301 @@ +// +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DataProtection.Client; + +namespace Adyen.DataProtection.Models +{ + /// + /// SubjectErasureResponse. + /// + public partial class SubjectErasureResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The result of this operation. + [JsonConstructor] + public SubjectErasureResponse(Option result = default) + { + _ResultOption = result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubjectErasureResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of this operation. + /// + /// The result of this operation. + [JsonConverter(typeof(ResultEnumJsonConverter))] + public class ResultEnum : IEnum + { + /// + /// Returns the value of the ResultEnum. + /// + public string? Value { get; set; } + + /// + /// ResultEnum.ACTIVERECURRINGTOKENEXISTS - ACTIVE_RECURRING_TOKEN_EXISTS + /// + public static readonly ResultEnum ACTIVERECURRINGTOKENEXISTS = new("ACTIVE_RECURRING_TOKEN_EXISTS"); + + /// + /// ResultEnum.ALREADYPROCESSED - ALREADY_PROCESSED + /// + public static readonly ResultEnum ALREADYPROCESSED = new("ALREADY_PROCESSED"); + + /// + /// ResultEnum.PAYMENTNOTFOUND - PAYMENT_NOT_FOUND + /// + public static readonly ResultEnum PAYMENTNOTFOUND = new("PAYMENT_NOT_FOUND"); + + /// + /// ResultEnum.SUCCESS - SUCCESS + /// + public static readonly ResultEnum SUCCESS = new("SUCCESS"); + + private ResultEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultEnum?(string? value) => value == null ? null : new ResultEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultEnum? option) => option?.Value; + + public static bool operator ==(ResultEnum? left, ResultEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultEnum? left, ResultEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultEnum? FromStringOrDefault(string value) + { + return value switch { + "ACTIVE_RECURRING_TOKEN_EXISTS" => ResultEnum.ACTIVERECURRINGTOKENEXISTS, + "ALREADY_PROCESSED" => ResultEnum.ALREADYPROCESSED, + "PAYMENT_NOT_FOUND" => ResultEnum.PAYMENTNOTFOUND, + "SUCCESS" => ResultEnum.SUCCESS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultEnum? value) + { + if (value == null) + return null; + + if (value == ResultEnum.ACTIVERECURRINGTOKENEXISTS) + return "ACTIVE_RECURRING_TOKEN_EXISTS"; + + if (value == ResultEnum.ALREADYPROCESSED) + return "ALREADY_PROCESSED"; + + if (value == ResultEnum.PAYMENTNOTFOUND) + return "PAYMENT_NOT_FOUND"; + + if (value == ResultEnum.SUCCESS) + return "SUCCESS"; + + return null; + } + + /// + /// JsonConverter for writing ResultEnum. + /// + public class ResultEnumJsonConverter : JsonConverter + { + public override ResultEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultEnum.FromStringOrDefault(value) ?? new ResultEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The result of this operation. + /// + /// The result of this operation. + [JsonPropertyName("result")] + public ResultEnum? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubjectErasureResponse {\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubjectErasureResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubjectErasureResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "result": + string? resultRawValue = utf8JsonReader.GetString(); + result = new Option(SubjectErasureResponse.ResultEnum.FromStringOrDefault(resultRawValue)); + break; + default: + break; + } + } + } + + + return new SubjectErasureResponse(result); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubjectErasureResponse subjectErasureResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subjectErasureResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubjectErasureResponse subjectErasureResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (subjectErasureResponse._ResultOption.IsSet && subjectErasureResponse.Result != null) + { + string? resultRawValue = SubjectErasureResponse.ResultEnum.ToJsonValue(subjectErasureResponse._ResultOption.Value!.Value); + writer.WriteString("result", resultRawValue); + } + } + } +} diff --git a/Adyen/DataProtection/Services/DataProtectionService.cs b/Adyen/DataProtection/Services/DataProtectionService.cs new file mode 100644 index 000000000..a3cdb2c12 --- /dev/null +++ b/Adyen/DataProtection/Services/DataProtectionService.cs @@ -0,0 +1,541 @@ +// +/* + * Adyen Data Protection API + * + * Adyen Data Protection API provides a way for you to process [Subject Erasure Requests](https://gdpr-info.eu/art-17-gdpr/) as mandated in GDPR. Use our API to submit a request to delete shopper's data, including payment details and other related information (for example, delivery address or shopper email).## Authentication Each request to the Data Protection API must be signed with an API key. Get your API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate a new API Key to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Data Protection Service API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DataProtectionService/v1/requestSubjectErasure ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.DataProtection.Client; +using Adyen.DataProtection.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.DataProtection.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IDataProtectionService : IAdyenApiService + { + /// + /// The class containing the events. + /// + DataProtectionServiceEvents Events { get; } + + /// + /// Submit a Subject Erasure Request. + /// + /// + /// Sends the PSP reference containing the shopper data that should be deleted. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task RequestSubjectErasureAsync(SubjectErasureByPspReferenceRequest subjectErasureByPspReferenceRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IRequestSubjectErasureApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class DataProtectionServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRequestSubjectErasure; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRequestSubjectErasure; + + internal void ExecuteOnRequestSubjectErasure(DataProtectionService.RequestSubjectErasureApiResponse apiResponse) + { + OnRequestSubjectErasure?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRequestSubjectErasure(Exception exception) + { + OnErrorRequestSubjectErasure?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class DataProtectionService : IDataProtectionService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public DataProtectionServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public DataProtectionService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DataProtectionServiceEvents dataProtectionServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = dataProtectionServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Submit a Subject Erasure Request. Sends the PSP reference containing the shopper data that should be deleted. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RequestSubjectErasureAsync(SubjectErasureByPspReferenceRequest subjectErasureByPspReferenceRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/requestSubjectErasure" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/requestSubjectErasure"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (subjectErasureByPspReferenceRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(subjectErasureByPspReferenceRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RequestSubjectErasureApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/requestSubjectErasure", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRequestSubjectErasure(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRequestSubjectErasure(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RequestSubjectErasureApiResponse : Adyen.Core.Client.ApiResponse, IRequestSubjectErasureApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestSubjectErasureApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestSubjectErasureApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.DataProtection.Models.SubjectErasureResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.SubjectErasureResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.DataProtection.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.DataProtection.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.DataProtection.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.DataProtection.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.DataProtection.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.DataProtection.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/DisputeWebhooks/Client/ClientUtils.cs b/Adyen/DisputeWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..e31bc5928 --- /dev/null +++ b/Adyen/DisputeWebhooks/Client/ClientUtils.cs @@ -0,0 +1,291 @@ +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.DisputeWebhooks.Models; +using Models = Adyen.DisputeWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.DisputeWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.DisputeEventNotification.TypeEnum disputeEventNotificationTypeEnum) + return Models.DisputeEventNotification.TypeEnum.ToJsonValue(disputeEventNotificationTypeEnum); + if (obj is Models.DisputeNotificationRequest.TypeEnum disputeNotificationRequestTypeEnum) + return Models.DisputeNotificationRequest.TypeEnum.ToJsonValue(disputeNotificationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/DisputeWebhooks/Client/HmacKeyToken.cs b/Adyen/DisputeWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..55177ec4b --- /dev/null +++ b/Adyen/DisputeWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.DisputeWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/DisputeWebhooks/Client/HostConfiguration.cs b/Adyen/DisputeWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..81e917ff8 --- /dev/null +++ b/Adyen/DisputeWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.DisputeWebhooks.Client; +using Adyen.DisputeWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.DisputeWebhooks.Client +{ + /// + /// Provides hosting configuration for DisputeWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new DisputeEventNotificationJsonConverter()); + _jsonOptions.Converters.Add(new DisputeNotificationRequestJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddDisputeWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/DisputeWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/DisputeWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..0692fb1b5 --- /dev/null +++ b/Adyen/DisputeWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.DisputeWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/DisputeWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/DisputeWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..3561f9533 --- /dev/null +++ b/Adyen/DisputeWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.DisputeWebhooks; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the DisputeWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureDisputeWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddDisputeWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/DisputeWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/DisputeWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..c99de6901 --- /dev/null +++ b/Adyen/DisputeWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen DisputeWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddDisputeWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddDisputeWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/DisputeWebhooks/Handlers/DisputeWebhooksHandler.cs b/Adyen/DisputeWebhooks/Handlers/DisputeWebhooksHandler.cs new file mode 100644 index 000000000..c0bdc5d62 --- /dev/null +++ b/Adyen/DisputeWebhooks/Handlers/DisputeWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.DisputeWebhooks.Client; +using Adyen.DisputeWebhooks.Models; + +namespace Adyen.DisputeWebhooks.Handlers +{ + /// + /// Interface for deserializing DisputeWebhooks webhooks or verify its HMAC signature. + /// + public interface IDisputeWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.DisputeWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + DisputeNotificationRequest? DeserializeDisputeNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize DisputeWebhooks or verify the HMAC signature of the webhook. + /// + public partial class DisputeWebhooksHandler : IDisputeWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.DisputeWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing DisputeWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public DisputeWebhooksHandler(Adyen.DisputeWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public DisputeNotificationRequest? DeserializeDisputeNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/DisputeWebhooks/Models/Amount.cs b/Adyen/DisputeWebhooks/Models/Amount.cs new file mode 100644 index 000000000..b4d88e41e --- /dev/null +++ b/Adyen/DisputeWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/DisputeWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/DisputeWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..145789d2f --- /dev/null +++ b/Adyen/DisputeWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/DisputeWebhooks/Models/DisputeEventNotification.cs b/Adyen/DisputeWebhooks/Models/DisputeEventNotification.cs new file mode 100644 index 000000000..4d0d4eee3 --- /dev/null +++ b/Adyen/DisputeWebhooks/Models/DisputeEventNotification.cs @@ -0,0 +1,530 @@ +// +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Models +{ + /// + /// DisputeEventNotification. + /// + public partial class DisputeEventNotification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique Acquirer Reference Number (arn) generated by the card scheme for each capture. You can use the arn to trace the transaction through its lifecycle. + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// Contains information about the dispute. + /// disputedAmount + /// The ID of the resource. + /// The current status of the dispute. + /// Additional information about the status of the dispute, when available. + /// The unique reference of the transaction for which the dispute is requested. + /// The type of dispute raised for the transaction. + [JsonConstructor] + public DisputeEventNotification(Option arn = default, Option balancePlatform = default, Option creationDate = default, Option description = default, Option disputedAmount = default, Option id = default, Option status = default, Option statusDetail = default, Option transactionId = default, Option type = default) + { + _ArnOption = arn; + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _DisputedAmountOption = disputedAmount; + _IdOption = id; + _StatusOption = status; + _StatusDetailOption = statusDetail; + _TransactionIdOption = transactionId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisputeEventNotification() + { + } + + partial void OnCreated(); + + /// + /// The type of dispute raised for the transaction. + /// + /// The type of dispute raised for the transaction. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Fraud - fraud + /// + public static readonly TypeEnum Fraud = new("fraud"); + + /// + /// TypeEnum.NotDelivered - notDelivered + /// + public static readonly TypeEnum NotDelivered = new("notDelivered"); + + /// + /// TypeEnum.Duplicate - duplicate + /// + public static readonly TypeEnum Duplicate = new("duplicate"); + + /// + /// TypeEnum.Other - other + /// + public static readonly TypeEnum Other = new("other"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "fraud" => TypeEnum.Fraud, + "notDelivered" => TypeEnum.NotDelivered, + "duplicate" => TypeEnum.Duplicate, + "other" => TypeEnum.Other, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Fraud) + return "fraud"; + + if (value == TypeEnum.NotDelivered) + return "notDelivered"; + + if (value == TypeEnum.Duplicate) + return "duplicate"; + + if (value == TypeEnum.Other) + return "other"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of dispute raised for the transaction. + /// + /// The type of dispute raised for the transaction. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ArnOption { get; private set; } + + /// + /// The unique Acquirer Reference Number (arn) generated by the card scheme for each capture. You can use the arn to trace the transaction through its lifecycle. + /// + /// The unique Acquirer Reference Number (arn) generated by the card scheme for each capture. You can use the arn to trace the transaction through its lifecycle. + [JsonPropertyName("arn")] + public string? Arn { get { return this._ArnOption; } set { this._ArnOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Contains information about the dispute. + /// + /// Contains information about the dispute. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisputedAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("disputedAmount")] + public Amount? DisputedAmount { get { return this._DisputedAmountOption; } set { this._DisputedAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The current status of the dispute. + /// + /// The current status of the dispute. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusDetailOption { get; private set; } + + /// + /// Additional information about the status of the dispute, when available. + /// + /// Additional information about the status of the dispute, when available. + [JsonPropertyName("statusDetail")] + public string? StatusDetail { get { return this._StatusDetailOption; } set { this._StatusDetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionIdOption { get; private set; } + + /// + /// The unique reference of the transaction for which the dispute is requested. + /// + /// The unique reference of the transaction for which the dispute is requested. + [JsonPropertyName("transactionId")] + public string? TransactionId { get { return this._TransactionIdOption; } set { this._TransactionIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisputeEventNotification {\n"); + sb.Append(" Arn: ").Append(Arn).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DisputedAmount: ").Append(DisputedAmount).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" StatusDetail: ").Append(StatusDetail).Append("\n"); + sb.Append(" TransactionId: ").Append(TransactionId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisputeEventNotificationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisputeEventNotification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option arn = default; + Option balancePlatform = default; + Option creationDate = default; + Option description = default; + Option disputedAmount = default; + Option id = default; + Option status = default; + Option statusDetail = default; + Option transactionId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "arn": + arn = new Option(utf8JsonReader.GetString()!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "disputedAmount": + disputedAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "statusDetail": + statusDetail = new Option(utf8JsonReader.GetString()!); + break; + case "transactionId": + transactionId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DisputeEventNotification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new DisputeEventNotification(arn, balancePlatform, creationDate, description, disputedAmount, id, status, statusDetail, transactionId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisputeEventNotification disputeEventNotification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disputeEventNotification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisputeEventNotification disputeEventNotification, JsonSerializerOptions jsonSerializerOptions) + { + + if (disputeEventNotification._ArnOption.IsSet) + if (disputeEventNotification.Arn != null) + writer.WriteString("arn", disputeEventNotification.Arn); + + if (disputeEventNotification._BalancePlatformOption.IsSet) + if (disputeEventNotification.BalancePlatform != null) + writer.WriteString("balancePlatform", disputeEventNotification.BalancePlatform); + + if (disputeEventNotification._CreationDateOption.IsSet) + writer.WriteString("creationDate", disputeEventNotification._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (disputeEventNotification._DescriptionOption.IsSet) + if (disputeEventNotification.Description != null) + writer.WriteString("description", disputeEventNotification.Description); + + if (disputeEventNotification._DisputedAmountOption.IsSet) + { + writer.WritePropertyName("disputedAmount"); + JsonSerializer.Serialize(writer, disputeEventNotification.DisputedAmount, jsonSerializerOptions); + } + if (disputeEventNotification._IdOption.IsSet) + if (disputeEventNotification.Id != null) + writer.WriteString("id", disputeEventNotification.Id); + + if (disputeEventNotification._StatusOption.IsSet) + if (disputeEventNotification.Status != null) + writer.WriteString("status", disputeEventNotification.Status); + + if (disputeEventNotification._StatusDetailOption.IsSet) + if (disputeEventNotification.StatusDetail != null) + writer.WriteString("statusDetail", disputeEventNotification.StatusDetail); + + if (disputeEventNotification._TransactionIdOption.IsSet) + if (disputeEventNotification.TransactionId != null) + writer.WriteString("transactionId", disputeEventNotification.TransactionId); + + if (disputeEventNotification._TypeOption.IsSet && disputeEventNotification.Type != null) + { + string? typeRawValue = DisputeEventNotification.TypeEnum.ToJsonValue(disputeEventNotification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/DisputeWebhooks/Models/DisputeNotificationRequest.cs b/Adyen/DisputeWebhooks/Models/DisputeNotificationRequest.cs new file mode 100644 index 000000000..92f10d475 --- /dev/null +++ b/Adyen/DisputeWebhooks/Models/DisputeNotificationRequest.cs @@ -0,0 +1,296 @@ +// +/* + * Dispute webhooks + * + * Adyen sends webhooks to inform your system about the creation or update of raised disputes, and chargebacks resulting from raised disputes. You can use these webhooks to build your implementation. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.DisputeWebhooks.Client; + +namespace Adyen.DisputeWebhooks.Models +{ + /// + /// DisputeNotificationRequest. + /// + public partial class DisputeNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Type of webhook. + [JsonConstructor] + public DisputeNotificationRequest(DisputeEventNotification data, TypeEnum type) + { + Data = data; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisputeNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformDisputeCreated - balancePlatform.dispute.created + /// + public static readonly TypeEnum BalancePlatformDisputeCreated = new("balancePlatform.dispute.created"); + + /// + /// TypeEnum.BalancePlatformDisputeUpdated - balancePlatform.dispute.updated + /// + public static readonly TypeEnum BalancePlatformDisputeUpdated = new("balancePlatform.dispute.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.dispute.created" => TypeEnum.BalancePlatformDisputeCreated, + "balancePlatform.dispute.updated" => TypeEnum.BalancePlatformDisputeUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformDisputeCreated) + return "balancePlatform.dispute.created"; + + if (value == TypeEnum.BalancePlatformDisputeUpdated) + return "balancePlatform.dispute.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public DisputeEventNotification Data { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisputeNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisputeNotificationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisputeNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DisputeNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class DisputeNotificationRequest.", nameof(data)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DisputeNotificationRequest.", nameof(type)); + + return new DisputeNotificationRequest(data.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisputeNotificationRequest disputeNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disputeNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisputeNotificationRequest disputeNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, disputeNotificationRequest.Data, jsonSerializerOptions); + if (disputeNotificationRequest.Type != null) + { + string? typeRawValue = DisputeNotificationRequest.TypeEnum.ToJsonValue(disputeNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Disputes/Client/ApiKeyToken.cs b/Adyen/Disputes/Client/ApiKeyToken.cs new file mode 100644 index 000000000..85a906929 --- /dev/null +++ b/Adyen/Disputes/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Disputes.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Disputes/Client/ClientUtils.cs b/Adyen/Disputes/Client/ClientUtils.cs new file mode 100644 index 000000000..2f4f753e0 --- /dev/null +++ b/Adyen/Disputes/Client/ClientUtils.cs @@ -0,0 +1,313 @@ +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Disputes.Models; +using Models = Adyen.Disputes.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Disputes.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Disputes/Client/HostConfiguration.cs b/Adyen/Disputes/Client/HostConfiguration.cs new file mode 100644 index 000000000..99ab7c762 --- /dev/null +++ b/Adyen/Disputes/Client/HostConfiguration.cs @@ -0,0 +1,143 @@ +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Disputes.Services; +using Adyen.Disputes.Client; +using Adyen.Disputes.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Disputes.Client +{ + /// + /// Provides hosting configuration for Disputes + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://ca-test.adyen.com/ca/services/DisputeService/v30"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AcceptDisputeRequestJsonConverter()); + _jsonOptions.Converters.Add(new AcceptDisputeResponseJsonConverter()); + _jsonOptions.Converters.Add(new DefendDisputeRequestJsonConverter()); + _jsonOptions.Converters.Add(new DefendDisputeResponseJsonConverter()); + _jsonOptions.Converters.Add(new DefenseDocumentJsonConverter()); + _jsonOptions.Converters.Add(new DefenseDocumentTypeJsonConverter()); + _jsonOptions.Converters.Add(new DefenseReasonJsonConverter()); + _jsonOptions.Converters.Add(new DefenseReasonsRequestJsonConverter()); + _jsonOptions.Converters.Add(new DefenseReasonsResponseJsonConverter()); + _jsonOptions.Converters.Add(new DeleteDefenseDocumentRequestJsonConverter()); + _jsonOptions.Converters.Add(new DeleteDefenseDocumentResponseJsonConverter()); + _jsonOptions.Converters.Add(new DisputeServiceResultJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new SupplyDefenseDocumentRequestJsonConverter()); + _jsonOptions.Converters.Add(new SupplyDefenseDocumentResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddDisputesHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Disputes/Client/JsonSerializerOptionsProvider.cs b/Adyen/Disputes/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..38a0cde32 --- /dev/null +++ b/Adyen/Disputes/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Disputes.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Disputes/Extensions/HostBuilderExtensions.cs b/Adyen/Disputes/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..f23affda6 --- /dev/null +++ b/Adyen/Disputes/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Disputes; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Disputes API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureDisputes(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddDisputesHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Disputes/Extensions/ServiceCollectionExtensions.cs b/Adyen/Disputes/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..34de0b01a --- /dev/null +++ b/Adyen/Disputes/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Disputes API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddDisputesServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddDisputesHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Disputes/Models/AcceptDisputeRequest.cs b/Adyen/Disputes/Models/AcceptDisputeRequest.cs new file mode 100644 index 000000000..65ebef203 --- /dev/null +++ b/Adyen/Disputes/Models/AcceptDisputeRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// AcceptDisputeRequest. + /// + public partial class AcceptDisputeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The PSP reference assigned to the dispute. + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonConstructor] + public AcceptDisputeRequest(string disputePspReference, string merchantAccountCode) + { + DisputePspReference = disputePspReference; + MerchantAccountCode = merchantAccountCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcceptDisputeRequest() + { + } + + partial void OnCreated(); + + /// + /// The PSP reference assigned to the dispute. + /// + /// The PSP reference assigned to the dispute. + [JsonPropertyName("disputePspReference")] + public string DisputePspReference { get; set; } + + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcceptDisputeRequest {\n"); + sb.Append(" DisputePspReference: ").Append(DisputePspReference).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcceptDisputeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcceptDisputeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputePspReference = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputePspReference": + disputePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!disputePspReference.IsSet) + throw new ArgumentException("Property is required for class AcceptDisputeRequest.", nameof(disputePspReference)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class AcceptDisputeRequest.", nameof(merchantAccountCode)); + + return new AcceptDisputeRequest(disputePspReference.Value!, merchantAccountCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcceptDisputeRequest acceptDisputeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acceptDisputeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcceptDisputeRequest acceptDisputeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (acceptDisputeRequest.DisputePspReference != null) + writer.WriteString("disputePspReference", acceptDisputeRequest.DisputePspReference); + + if (acceptDisputeRequest.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", acceptDisputeRequest.MerchantAccountCode); + } + } +} diff --git a/Adyen/Disputes/Models/AcceptDisputeResponse.cs b/Adyen/Disputes/Models/AcceptDisputeResponse.cs new file mode 100644 index 000000000..ccb117d02 --- /dev/null +++ b/Adyen/Disputes/Models/AcceptDisputeResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// AcceptDisputeResponse. + /// + public partial class AcceptDisputeResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// disputeServiceResult + [JsonConstructor] + public AcceptDisputeResponse(DisputeServiceResult disputeServiceResult) + { + DisputeServiceResult = disputeServiceResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcceptDisputeResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("disputeServiceResult")] + public DisputeServiceResult DisputeServiceResult { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcceptDisputeResponse {\n"); + sb.Append(" DisputeServiceResult: ").Append(DisputeServiceResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcceptDisputeResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcceptDisputeResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeServiceResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeServiceResult": + disputeServiceResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!disputeServiceResult.IsSet) + throw new ArgumentException("Property is required for class AcceptDisputeResponse.", nameof(disputeServiceResult)); + + return new AcceptDisputeResponse(disputeServiceResult.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcceptDisputeResponse acceptDisputeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acceptDisputeResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcceptDisputeResponse acceptDisputeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("disputeServiceResult"); + JsonSerializer.Serialize(writer, acceptDisputeResponse.DisputeServiceResult, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Disputes/Models/DefendDisputeRequest.cs b/Adyen/Disputes/Models/DefendDisputeRequest.cs new file mode 100644 index 000000000..b72b8ce92 --- /dev/null +++ b/Adyen/Disputes/Models/DefendDisputeRequest.cs @@ -0,0 +1,211 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefendDisputeRequest. + /// + public partial class DefendDisputeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The defense reason code that was selected to defend this dispute. + /// The PSP reference assigned to the dispute. + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonConstructor] + public DefendDisputeRequest(string defenseReasonCode, string disputePspReference, string merchantAccountCode) + { + DefenseReasonCode = defenseReasonCode; + DisputePspReference = disputePspReference; + MerchantAccountCode = merchantAccountCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefendDisputeRequest() + { + } + + partial void OnCreated(); + + /// + /// The defense reason code that was selected to defend this dispute. + /// + /// The defense reason code that was selected to defend this dispute. + [JsonPropertyName("defenseReasonCode")] + public string DefenseReasonCode { get; set; } + + /// + /// The PSP reference assigned to the dispute. + /// + /// The PSP reference assigned to the dispute. + [JsonPropertyName("disputePspReference")] + public string DisputePspReference { get; set; } + + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefendDisputeRequest {\n"); + sb.Append(" DefenseReasonCode: ").Append(DefenseReasonCode).Append("\n"); + sb.Append(" DisputePspReference: ").Append(DisputePspReference).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefendDisputeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefendDisputeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option defenseReasonCode = default; + Option disputePspReference = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "defenseReasonCode": + defenseReasonCode = new Option(utf8JsonReader.GetString()!); + break; + case "disputePspReference": + disputePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!defenseReasonCode.IsSet) + throw new ArgumentException("Property is required for class DefendDisputeRequest.", nameof(defenseReasonCode)); + + if (!disputePspReference.IsSet) + throw new ArgumentException("Property is required for class DefendDisputeRequest.", nameof(disputePspReference)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class DefendDisputeRequest.", nameof(merchantAccountCode)); + + return new DefendDisputeRequest(defenseReasonCode.Value!, disputePspReference.Value!, merchantAccountCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefendDisputeRequest defendDisputeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defendDisputeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefendDisputeRequest defendDisputeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (defendDisputeRequest.DefenseReasonCode != null) + writer.WriteString("defenseReasonCode", defendDisputeRequest.DefenseReasonCode); + + if (defendDisputeRequest.DisputePspReference != null) + writer.WriteString("disputePspReference", defendDisputeRequest.DisputePspReference); + + if (defendDisputeRequest.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", defendDisputeRequest.MerchantAccountCode); + } + } +} diff --git a/Adyen/Disputes/Models/DefendDisputeResponse.cs b/Adyen/Disputes/Models/DefendDisputeResponse.cs new file mode 100644 index 000000000..4f848f0b6 --- /dev/null +++ b/Adyen/Disputes/Models/DefendDisputeResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefendDisputeResponse. + /// + public partial class DefendDisputeResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// disputeServiceResult + [JsonConstructor] + public DefendDisputeResponse(DisputeServiceResult disputeServiceResult) + { + DisputeServiceResult = disputeServiceResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefendDisputeResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("disputeServiceResult")] + public DisputeServiceResult DisputeServiceResult { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefendDisputeResponse {\n"); + sb.Append(" DisputeServiceResult: ").Append(DisputeServiceResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefendDisputeResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefendDisputeResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeServiceResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeServiceResult": + disputeServiceResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!disputeServiceResult.IsSet) + throw new ArgumentException("Property is required for class DefendDisputeResponse.", nameof(disputeServiceResult)); + + return new DefendDisputeResponse(disputeServiceResult.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefendDisputeResponse defendDisputeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defendDisputeResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefendDisputeResponse defendDisputeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("disputeServiceResult"); + JsonSerializer.Serialize(writer, defendDisputeResponse.DisputeServiceResult, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Disputes/Models/DefenseDocument.cs b/Adyen/Disputes/Models/DefenseDocument.cs new file mode 100644 index 000000000..0c5a44605 --- /dev/null +++ b/Adyen/Disputes/Models/DefenseDocument.cs @@ -0,0 +1,210 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefenseDocument. + /// + public partial class DefenseDocument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The content of the defense document. + /// The content type of the defense document. + /// The document type code of the defense document. + [JsonConstructor] + public DefenseDocument(byte[] content, string contentType, string defenseDocumentTypeCode) + { + Content = content; + ContentType = contentType; + DefenseDocumentTypeCode = defenseDocumentTypeCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefenseDocument() + { + } + + partial void OnCreated(); + + /// + /// The content of the defense document. + /// + /// The content of the defense document. + [JsonPropertyName("content")] + public byte[] Content { get; set; } + + /// + /// The content type of the defense document. + /// + /// The content type of the defense document. + [JsonPropertyName("contentType")] + public string ContentType { get; set; } + + /// + /// The document type code of the defense document. + /// + /// The document type code of the defense document. + [JsonPropertyName("defenseDocumentTypeCode")] + public string DefenseDocumentTypeCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefenseDocument {\n"); + sb.Append(" Content: ").Append(Content).Append("\n"); + sb.Append(" ContentType: ").Append(ContentType).Append("\n"); + sb.Append(" DefenseDocumentTypeCode: ").Append(DefenseDocumentTypeCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefenseDocumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefenseDocument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option content = default; + Option contentType = default; + Option defenseDocumentTypeCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "content": + content = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contentType": + contentType = new Option(utf8JsonReader.GetString()!); + break; + case "defenseDocumentTypeCode": + defenseDocumentTypeCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!content.IsSet) + throw new ArgumentException("Property is required for class DefenseDocument.", nameof(content)); + + if (!contentType.IsSet) + throw new ArgumentException("Property is required for class DefenseDocument.", nameof(contentType)); + + if (!defenseDocumentTypeCode.IsSet) + throw new ArgumentException("Property is required for class DefenseDocument.", nameof(defenseDocumentTypeCode)); + + return new DefenseDocument(content.Value!, contentType.Value!, defenseDocumentTypeCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefenseDocument defenseDocument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defenseDocument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefenseDocument defenseDocument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("content"); + JsonSerializer.Serialize(writer, defenseDocument.Content, jsonSerializerOptions); + if (defenseDocument.ContentType != null) + writer.WriteString("contentType", defenseDocument.ContentType); + + if (defenseDocument.DefenseDocumentTypeCode != null) + writer.WriteString("defenseDocumentTypeCode", defenseDocument.DefenseDocumentTypeCode); + } + } +} diff --git a/Adyen/Disputes/Models/DefenseDocumentType.cs b/Adyen/Disputes/Models/DefenseDocumentType.cs new file mode 100644 index 000000000..a450efd03 --- /dev/null +++ b/Adyen/Disputes/Models/DefenseDocumentType.cs @@ -0,0 +1,210 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefenseDocumentType. + /// + public partial class DefenseDocumentType : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// When **true**, you've successfully uploaded this type of defense document. When **false**, you haven't uploaded this defense document type. + /// The document type code of the defense document. + /// Indicates to what extent the defense document is required in the defense process. Possible values: * **Required**: You must supply the document. * **OneOrMore**: You must supply at least one of the documents with this label. * **Optional**: You can choose to supply the document. * **AlternativeRequired**: You must supply a generic defense document. To enable this functionality, contact our Support Team. When enabled, you can supply a generic defense document for all schemes. + [JsonConstructor] + public DefenseDocumentType(bool available, string defenseDocumentTypeCode, string requirementLevel) + { + Available = available; + DefenseDocumentTypeCode = defenseDocumentTypeCode; + RequirementLevel = requirementLevel; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefenseDocumentType() + { + } + + partial void OnCreated(); + + /// + /// When **true**, you've successfully uploaded this type of defense document. When **false**, you haven't uploaded this defense document type. + /// + /// When **true**, you've successfully uploaded this type of defense document. When **false**, you haven't uploaded this defense document type. + [JsonPropertyName("available")] + public bool Available { get; set; } + + /// + /// The document type code of the defense document. + /// + /// The document type code of the defense document. + [JsonPropertyName("defenseDocumentTypeCode")] + public string DefenseDocumentTypeCode { get; set; } + + /// + /// Indicates to what extent the defense document is required in the defense process. Possible values: * **Required**: You must supply the document. * **OneOrMore**: You must supply at least one of the documents with this label. * **Optional**: You can choose to supply the document. * **AlternativeRequired**: You must supply a generic defense document. To enable this functionality, contact our Support Team. When enabled, you can supply a generic defense document for all schemes. + /// + /// Indicates to what extent the defense document is required in the defense process. Possible values: * **Required**: You must supply the document. * **OneOrMore**: You must supply at least one of the documents with this label. * **Optional**: You can choose to supply the document. * **AlternativeRequired**: You must supply a generic defense document. To enable this functionality, contact our Support Team. When enabled, you can supply a generic defense document for all schemes. + [JsonPropertyName("requirementLevel")] + public string RequirementLevel { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefenseDocumentType {\n"); + sb.Append(" Available: ").Append(Available).Append("\n"); + sb.Append(" DefenseDocumentTypeCode: ").Append(DefenseDocumentTypeCode).Append("\n"); + sb.Append(" RequirementLevel: ").Append(RequirementLevel).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefenseDocumentTypeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefenseDocumentType Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option available = default; + Option defenseDocumentTypeCode = default; + Option requirementLevel = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "available": + available = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "defenseDocumentTypeCode": + defenseDocumentTypeCode = new Option(utf8JsonReader.GetString()!); + break; + case "requirementLevel": + requirementLevel = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!available.IsSet) + throw new ArgumentException("Property is required for class DefenseDocumentType.", nameof(available)); + + if (!defenseDocumentTypeCode.IsSet) + throw new ArgumentException("Property is required for class DefenseDocumentType.", nameof(defenseDocumentTypeCode)); + + if (!requirementLevel.IsSet) + throw new ArgumentException("Property is required for class DefenseDocumentType.", nameof(requirementLevel)); + + return new DefenseDocumentType(available.Value!.Value!, defenseDocumentTypeCode.Value!, requirementLevel.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefenseDocumentType defenseDocumentType, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defenseDocumentType, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefenseDocumentType defenseDocumentType, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("available", defenseDocumentType.Available); + + if (defenseDocumentType.DefenseDocumentTypeCode != null) + writer.WriteString("defenseDocumentTypeCode", defenseDocumentType.DefenseDocumentTypeCode); + + if (defenseDocumentType.RequirementLevel != null) + writer.WriteString("requirementLevel", defenseDocumentType.RequirementLevel); + } + } +} diff --git a/Adyen/Disputes/Models/DefenseReason.cs b/Adyen/Disputes/Models/DefenseReason.cs new file mode 100644 index 000000000..681660cdd --- /dev/null +++ b/Adyen/Disputes/Models/DefenseReason.cs @@ -0,0 +1,217 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefenseReason. + /// + public partial class DefenseReason : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The defense reason code that was selected to defend this dispute. + /// Indicates if sufficient defense material has been supplied. + /// Array of defense document types for a specific defense reason. Indicates the document types that you can submit to the schemes to defend this dispute, and whether they are required. + [JsonConstructor] + public DefenseReason(string defenseReasonCode, bool satisfied, Option?> defenseDocumentTypes = default) + { + DefenseReasonCode = defenseReasonCode; + Satisfied = satisfied; + _DefenseDocumentTypesOption = defenseDocumentTypes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefenseReason() + { + } + + partial void OnCreated(); + + /// + /// The defense reason code that was selected to defend this dispute. + /// + /// The defense reason code that was selected to defend this dispute. + [JsonPropertyName("defenseReasonCode")] + public string DefenseReasonCode { get; set; } + + /// + /// Indicates if sufficient defense material has been supplied. + /// + /// Indicates if sufficient defense material has been supplied. + [JsonPropertyName("satisfied")] + public bool Satisfied { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DefenseDocumentTypesOption { get; private set; } + + /// + /// Array of defense document types for a specific defense reason. Indicates the document types that you can submit to the schemes to defend this dispute, and whether they are required. + /// + /// Array of defense document types for a specific defense reason. Indicates the document types that you can submit to the schemes to defend this dispute, and whether they are required. + [JsonPropertyName("defenseDocumentTypes")] + public List? DefenseDocumentTypes { get { return this._DefenseDocumentTypesOption; } set { this._DefenseDocumentTypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefenseReason {\n"); + sb.Append(" DefenseReasonCode: ").Append(DefenseReasonCode).Append("\n"); + sb.Append(" Satisfied: ").Append(Satisfied).Append("\n"); + sb.Append(" DefenseDocumentTypes: ").Append(DefenseDocumentTypes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefenseReasonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefenseReason Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option defenseReasonCode = default; + Option satisfied = default; + Option?> defenseDocumentTypes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "defenseReasonCode": + defenseReasonCode = new Option(utf8JsonReader.GetString()!); + break; + case "satisfied": + satisfied = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "defenseDocumentTypes": + defenseDocumentTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!defenseReasonCode.IsSet) + throw new ArgumentException("Property is required for class DefenseReason.", nameof(defenseReasonCode)); + + if (!satisfied.IsSet) + throw new ArgumentException("Property is required for class DefenseReason.", nameof(satisfied)); + + return new DefenseReason(defenseReasonCode.Value!, satisfied.Value!.Value!, defenseDocumentTypes); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefenseReason defenseReason, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defenseReason, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefenseReason defenseReason, JsonSerializerOptions jsonSerializerOptions) + { + + if (defenseReason.DefenseReasonCode != null) + writer.WriteString("defenseReasonCode", defenseReason.DefenseReasonCode); + + writer.WriteBoolean("satisfied", defenseReason.Satisfied); + + if (defenseReason._DefenseDocumentTypesOption.IsSet) + { + writer.WritePropertyName("defenseDocumentTypes"); + JsonSerializer.Serialize(writer, defenseReason.DefenseDocumentTypes, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Disputes/Models/DefenseReasonsRequest.cs b/Adyen/Disputes/Models/DefenseReasonsRequest.cs new file mode 100644 index 000000000..71dc31ae0 --- /dev/null +++ b/Adyen/Disputes/Models/DefenseReasonsRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefenseReasonsRequest. + /// + public partial class DefenseReasonsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The PSP reference assigned to the dispute. + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonConstructor] + public DefenseReasonsRequest(string disputePspReference, string merchantAccountCode) + { + DisputePspReference = disputePspReference; + MerchantAccountCode = merchantAccountCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefenseReasonsRequest() + { + } + + partial void OnCreated(); + + /// + /// The PSP reference assigned to the dispute. + /// + /// The PSP reference assigned to the dispute. + [JsonPropertyName("disputePspReference")] + public string DisputePspReference { get; set; } + + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefenseReasonsRequest {\n"); + sb.Append(" DisputePspReference: ").Append(DisputePspReference).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefenseReasonsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefenseReasonsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputePspReference = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputePspReference": + disputePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!disputePspReference.IsSet) + throw new ArgumentException("Property is required for class DefenseReasonsRequest.", nameof(disputePspReference)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class DefenseReasonsRequest.", nameof(merchantAccountCode)); + + return new DefenseReasonsRequest(disputePspReference.Value!, merchantAccountCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefenseReasonsRequest defenseReasonsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defenseReasonsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefenseReasonsRequest defenseReasonsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (defenseReasonsRequest.DisputePspReference != null) + writer.WriteString("disputePspReference", defenseReasonsRequest.DisputePspReference); + + if (defenseReasonsRequest.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", defenseReasonsRequest.MerchantAccountCode); + } + } +} diff --git a/Adyen/Disputes/Models/DefenseReasonsResponse.cs b/Adyen/Disputes/Models/DefenseReasonsResponse.cs new file mode 100644 index 000000000..08e375c33 --- /dev/null +++ b/Adyen/Disputes/Models/DefenseReasonsResponse.cs @@ -0,0 +1,196 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DefenseReasonsResponse. + /// + public partial class DefenseReasonsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// disputeServiceResult + /// The defense reasons that can be used to defend the dispute. + [JsonConstructor] + public DefenseReasonsResponse(DisputeServiceResult disputeServiceResult, Option?> defenseReasons = default) + { + DisputeServiceResult = disputeServiceResult; + _DefenseReasonsOption = defenseReasons; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefenseReasonsResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("disputeServiceResult")] + public DisputeServiceResult DisputeServiceResult { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DefenseReasonsOption { get; private set; } + + /// + /// The defense reasons that can be used to defend the dispute. + /// + /// The defense reasons that can be used to defend the dispute. + [JsonPropertyName("defenseReasons")] + public List? DefenseReasons { get { return this._DefenseReasonsOption; } set { this._DefenseReasonsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefenseReasonsResponse {\n"); + sb.Append(" DisputeServiceResult: ").Append(DisputeServiceResult).Append("\n"); + sb.Append(" DefenseReasons: ").Append(DefenseReasons).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefenseReasonsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefenseReasonsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeServiceResult = default; + Option?> defenseReasons = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeServiceResult": + disputeServiceResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "defenseReasons": + defenseReasons = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!disputeServiceResult.IsSet) + throw new ArgumentException("Property is required for class DefenseReasonsResponse.", nameof(disputeServiceResult)); + + return new DefenseReasonsResponse(disputeServiceResult.Value!, defenseReasons); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefenseReasonsResponse defenseReasonsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defenseReasonsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefenseReasonsResponse defenseReasonsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("disputeServiceResult"); + JsonSerializer.Serialize(writer, defenseReasonsResponse.DisputeServiceResult, jsonSerializerOptions); + if (defenseReasonsResponse._DefenseReasonsOption.IsSet) + { + writer.WritePropertyName("defenseReasons"); + JsonSerializer.Serialize(writer, defenseReasonsResponse.DefenseReasons, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Disputes/Models/DeleteDefenseDocumentRequest.cs b/Adyen/Disputes/Models/DeleteDefenseDocumentRequest.cs new file mode 100644 index 000000000..58051b64d --- /dev/null +++ b/Adyen/Disputes/Models/DeleteDefenseDocumentRequest.cs @@ -0,0 +1,211 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DeleteDefenseDocumentRequest. + /// + public partial class DeleteDefenseDocumentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The document type code of the defense document. + /// The PSP reference assigned to the dispute. + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonConstructor] + public DeleteDefenseDocumentRequest(string defenseDocumentType, string disputePspReference, string merchantAccountCode) + { + DefenseDocumentType = defenseDocumentType; + DisputePspReference = disputePspReference; + MerchantAccountCode = merchantAccountCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeleteDefenseDocumentRequest() + { + } + + partial void OnCreated(); + + /// + /// The document type code of the defense document. + /// + /// The document type code of the defense document. + [JsonPropertyName("defenseDocumentType")] + public string DefenseDocumentType { get; set; } + + /// + /// The PSP reference assigned to the dispute. + /// + /// The PSP reference assigned to the dispute. + [JsonPropertyName("disputePspReference")] + public string DisputePspReference { get; set; } + + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeleteDefenseDocumentRequest {\n"); + sb.Append(" DefenseDocumentType: ").Append(DefenseDocumentType).Append("\n"); + sb.Append(" DisputePspReference: ").Append(DisputePspReference).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeleteDefenseDocumentRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeleteDefenseDocumentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option defenseDocumentType = default; + Option disputePspReference = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "defenseDocumentType": + defenseDocumentType = new Option(utf8JsonReader.GetString()!); + break; + case "disputePspReference": + disputePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!defenseDocumentType.IsSet) + throw new ArgumentException("Property is required for class DeleteDefenseDocumentRequest.", nameof(defenseDocumentType)); + + if (!disputePspReference.IsSet) + throw new ArgumentException("Property is required for class DeleteDefenseDocumentRequest.", nameof(disputePspReference)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class DeleteDefenseDocumentRequest.", nameof(merchantAccountCode)); + + return new DeleteDefenseDocumentRequest(defenseDocumentType.Value!, disputePspReference.Value!, merchantAccountCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeleteDefenseDocumentRequest deleteDefenseDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deleteDefenseDocumentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeleteDefenseDocumentRequest deleteDefenseDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (deleteDefenseDocumentRequest.DefenseDocumentType != null) + writer.WriteString("defenseDocumentType", deleteDefenseDocumentRequest.DefenseDocumentType); + + if (deleteDefenseDocumentRequest.DisputePspReference != null) + writer.WriteString("disputePspReference", deleteDefenseDocumentRequest.DisputePspReference); + + if (deleteDefenseDocumentRequest.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", deleteDefenseDocumentRequest.MerchantAccountCode); + } + } +} diff --git a/Adyen/Disputes/Models/DeleteDefenseDocumentResponse.cs b/Adyen/Disputes/Models/DeleteDefenseDocumentResponse.cs new file mode 100644 index 000000000..4c291cbe9 --- /dev/null +++ b/Adyen/Disputes/Models/DeleteDefenseDocumentResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DeleteDefenseDocumentResponse. + /// + public partial class DeleteDefenseDocumentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// disputeServiceResult + [JsonConstructor] + public DeleteDefenseDocumentResponse(DisputeServiceResult disputeServiceResult) + { + DisputeServiceResult = disputeServiceResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeleteDefenseDocumentResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("disputeServiceResult")] + public DisputeServiceResult DisputeServiceResult { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeleteDefenseDocumentResponse {\n"); + sb.Append(" DisputeServiceResult: ").Append(DisputeServiceResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeleteDefenseDocumentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeleteDefenseDocumentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeServiceResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeServiceResult": + disputeServiceResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!disputeServiceResult.IsSet) + throw new ArgumentException("Property is required for class DeleteDefenseDocumentResponse.", nameof(disputeServiceResult)); + + return new DeleteDefenseDocumentResponse(disputeServiceResult.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeleteDefenseDocumentResponse deleteDefenseDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deleteDefenseDocumentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeleteDefenseDocumentResponse deleteDefenseDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("disputeServiceResult"); + JsonSerializer.Serialize(writer, deleteDefenseDocumentResponse.DisputeServiceResult, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Disputes/Models/DisputeServiceResult.cs b/Adyen/Disputes/Models/DisputeServiceResult.cs new file mode 100644 index 000000000..fe62daa12 --- /dev/null +++ b/Adyen/Disputes/Models/DisputeServiceResult.cs @@ -0,0 +1,195 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// DisputeServiceResult. + /// + public partial class DisputeServiceResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the request succeeded. + /// The general error message. + [JsonConstructor] + public DisputeServiceResult(bool success, Option errorMessage = default) + { + Success = success; + _ErrorMessageOption = errorMessage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisputeServiceResult() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether the request succeeded. + /// + /// Indicates whether the request succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorMessageOption { get; private set; } + + /// + /// The general error message. + /// + /// The general error message. + [JsonPropertyName("errorMessage")] + public string? ErrorMessage { get { return this._ErrorMessageOption; } set { this._ErrorMessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisputeServiceResult {\n"); + sb.Append(" Success: ").Append(Success).Append("\n"); + sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisputeServiceResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisputeServiceResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option success = default; + Option errorMessage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "success": + success = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "errorMessage": + errorMessage = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!success.IsSet) + throw new ArgumentException("Property is required for class DisputeServiceResult.", nameof(success)); + + return new DisputeServiceResult(success.Value!.Value!, errorMessage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisputeServiceResult disputeServiceResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disputeServiceResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisputeServiceResult disputeServiceResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("success", disputeServiceResult.Success); + + if (disputeServiceResult._ErrorMessageOption.IsSet) + if (disputeServiceResult.ErrorMessage != null) + writer.WriteString("errorMessage", disputeServiceResult.ErrorMessage); + } + } +} diff --git a/Adyen/Disputes/Models/ServiceError.cs b/Adyen/Disputes/Models/ServiceError.cs new file mode 100644 index 000000000..0095276e3 --- /dev/null +++ b/Adyen/Disputes/Models/ServiceError.cs @@ -0,0 +1,276 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Disputes/Models/SupplyDefenseDocumentRequest.cs b/Adyen/Disputes/Models/SupplyDefenseDocumentRequest.cs new file mode 100644 index 000000000..f2595b093 --- /dev/null +++ b/Adyen/Disputes/Models/SupplyDefenseDocumentRequest.cs @@ -0,0 +1,210 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// SupplyDefenseDocumentRequest. + /// + public partial class SupplyDefenseDocumentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An array containing a list of the defense documents. + /// The PSP reference assigned to the dispute. + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonConstructor] + public SupplyDefenseDocumentRequest(List defenseDocuments, string disputePspReference, string merchantAccountCode) + { + DefenseDocuments = defenseDocuments; + DisputePspReference = disputePspReference; + MerchantAccountCode = merchantAccountCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SupplyDefenseDocumentRequest() + { + } + + partial void OnCreated(); + + /// + /// An array containing a list of the defense documents. + /// + /// An array containing a list of the defense documents. + [JsonPropertyName("defenseDocuments")] + public List DefenseDocuments { get; set; } + + /// + /// The PSP reference assigned to the dispute. + /// + /// The PSP reference assigned to the dispute. + [JsonPropertyName("disputePspReference")] + public string DisputePspReference { get; set; } + + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + /// + /// The merchant account identifier, for which you want to process the dispute transaction. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SupplyDefenseDocumentRequest {\n"); + sb.Append(" DefenseDocuments: ").Append(DefenseDocuments).Append("\n"); + sb.Append(" DisputePspReference: ").Append(DisputePspReference).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SupplyDefenseDocumentRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SupplyDefenseDocumentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> defenseDocuments = default; + Option disputePspReference = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "defenseDocuments": + defenseDocuments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "disputePspReference": + disputePspReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!defenseDocuments.IsSet) + throw new ArgumentException("Property is required for class SupplyDefenseDocumentRequest.", nameof(defenseDocuments)); + + if (!disputePspReference.IsSet) + throw new ArgumentException("Property is required for class SupplyDefenseDocumentRequest.", nameof(disputePspReference)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class SupplyDefenseDocumentRequest.", nameof(merchantAccountCode)); + + return new SupplyDefenseDocumentRequest(defenseDocuments.Value!, disputePspReference.Value!, merchantAccountCode.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SupplyDefenseDocumentRequest supplyDefenseDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, supplyDefenseDocumentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SupplyDefenseDocumentRequest supplyDefenseDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("defenseDocuments"); + JsonSerializer.Serialize(writer, supplyDefenseDocumentRequest.DefenseDocuments, jsonSerializerOptions); + if (supplyDefenseDocumentRequest.DisputePspReference != null) + writer.WriteString("disputePspReference", supplyDefenseDocumentRequest.DisputePspReference); + + if (supplyDefenseDocumentRequest.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", supplyDefenseDocumentRequest.MerchantAccountCode); + } + } +} diff --git a/Adyen/Disputes/Models/SupplyDefenseDocumentResponse.cs b/Adyen/Disputes/Models/SupplyDefenseDocumentResponse.cs new file mode 100644 index 000000000..263bc0199 --- /dev/null +++ b/Adyen/Disputes/Models/SupplyDefenseDocumentResponse.cs @@ -0,0 +1,170 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Disputes.Client; + +namespace Adyen.Disputes.Models +{ + /// + /// SupplyDefenseDocumentResponse. + /// + public partial class SupplyDefenseDocumentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// disputeServiceResult + [JsonConstructor] + public SupplyDefenseDocumentResponse(DisputeServiceResult disputeServiceResult) + { + DisputeServiceResult = disputeServiceResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SupplyDefenseDocumentResponse() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("disputeServiceResult")] + public DisputeServiceResult DisputeServiceResult { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SupplyDefenseDocumentResponse {\n"); + sb.Append(" DisputeServiceResult: ").Append(DisputeServiceResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SupplyDefenseDocumentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SupplyDefenseDocumentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeServiceResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeServiceResult": + disputeServiceResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!disputeServiceResult.IsSet) + throw new ArgumentException("Property is required for class SupplyDefenseDocumentResponse.", nameof(disputeServiceResult)); + + return new SupplyDefenseDocumentResponse(disputeServiceResult.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SupplyDefenseDocumentResponse supplyDefenseDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, supplyDefenseDocumentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SupplyDefenseDocumentResponse supplyDefenseDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("disputeServiceResult"); + JsonSerializer.Serialize(writer, supplyDefenseDocumentResponse.DisputeServiceResult, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Disputes/Services/DisputesService.cs b/Adyen/Disputes/Services/DisputesService.cs new file mode 100644 index 000000000..fdcfc0892 --- /dev/null +++ b/Adyen/Disputes/Services/DisputesService.cs @@ -0,0 +1,2317 @@ +// +/* + * Disputes API + * + * You can use the [Disputes API](https://docs.adyen.com/risk-management/disputes-api) to automate the dispute handling process so that you can respond to disputes and chargebacks as soon as they are initiated. The Disputes API lets you retrieve defense reasons, supply and delete defense documents, and accept or defend disputes. ## Authentication Each request to the Disputes API must be signed with an API key. For this, obtain an API Key from your Customer Area, as described in [How to get the API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key). Then set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: Your_API_key\" \\ ... ``` Note that when going live, you need to generate new web service user credentials to access the [live endpoints](https://docs.adyen.com/development-resources/live-endpoints). ## Versioning Disputes API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://ca-test.adyen.com/ca/services/DisputeService/v30/defendDispute ``` + * + * The version of the OpenAPI document: 30 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Disputes.Client; +using Adyen.Disputes.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Disputes.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IDisputesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + DisputesServiceEvents Events { get; } + + /// + /// Accept a dispute + /// + /// + /// Accepts a specific dispute. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task AcceptDisputeAsync(AcceptDisputeRequest acceptDisputeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Defend a dispute + /// + /// + /// Defends a specific dispute. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task DefendDisputeAsync(DefendDisputeRequest defendDisputeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a defense document + /// + /// + /// Deletes a specific dispute defense document that was supplied earlier. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task DeleteDisputeDefenseDocumentAsync(DeleteDefenseDocumentRequest deleteDefenseDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get applicable defense reasons + /// + /// + /// Returns a list of all applicable defense reasons to defend a specific dispute. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task RetrieveApplicableDefenseReasonsAsync(DefenseReasonsRequest defenseReasonsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Supply a defense document + /// + /// + /// Supplies a specific dispute defense document. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task SupplyDefenseDocumentAsync(SupplyDefenseDocumentRequest supplyDefenseDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAcceptDisputeApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDefendDisputeApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteDisputeDefenseDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRetrieveApplicableDefenseReasonsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISupplyDefenseDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class DisputesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAcceptDispute; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAcceptDispute; + + internal void ExecuteOnAcceptDispute(DisputesService.AcceptDisputeApiResponse apiResponse) + { + OnAcceptDispute?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAcceptDispute(Exception exception) + { + OnErrorAcceptDispute?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDefendDispute; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDefendDispute; + + internal void ExecuteOnDefendDispute(DisputesService.DefendDisputeApiResponse apiResponse) + { + OnDefendDispute?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDefendDispute(Exception exception) + { + OnErrorDefendDispute?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteDisputeDefenseDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteDisputeDefenseDocument; + + internal void ExecuteOnDeleteDisputeDefenseDocument(DisputesService.DeleteDisputeDefenseDocumentApiResponse apiResponse) + { + OnDeleteDisputeDefenseDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteDisputeDefenseDocument(Exception exception) + { + OnErrorDeleteDisputeDefenseDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRetrieveApplicableDefenseReasons; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRetrieveApplicableDefenseReasons; + + internal void ExecuteOnRetrieveApplicableDefenseReasons(DisputesService.RetrieveApplicableDefenseReasonsApiResponse apiResponse) + { + OnRetrieveApplicableDefenseReasons?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRetrieveApplicableDefenseReasons(Exception exception) + { + OnErrorRetrieveApplicableDefenseReasons?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSupplyDefenseDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSupplyDefenseDocument; + + internal void ExecuteOnSupplyDefenseDocument(DisputesService.SupplyDefenseDocumentApiResponse apiResponse) + { + OnSupplyDefenseDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSupplyDefenseDocument(Exception exception) + { + OnErrorSupplyDefenseDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class DisputesService : IDisputesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public DisputesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public DisputesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DisputesServiceEvents disputesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = disputesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Accept a dispute Accepts a specific dispute. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AcceptDisputeAsync(AcceptDisputeRequest acceptDisputeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/acceptDispute" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/acceptDispute"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (acceptDisputeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(acceptDisputeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AcceptDisputeApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/acceptDispute", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAcceptDispute(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAcceptDispute(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AcceptDisputeApiResponse : Adyen.Core.Client.ApiResponse, IAcceptDisputeApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AcceptDisputeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AcceptDisputeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Disputes.Models.AcceptDisputeResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Disputes.Models.AcceptDisputeResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Disputes.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Disputes.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Disputes.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Disputes.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Disputes.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Defend a dispute Defends a specific dispute. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DefendDisputeAsync(DefendDisputeRequest defendDisputeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/defendDispute" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/defendDispute"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (defendDisputeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(defendDisputeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DefendDisputeApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/defendDispute", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDefendDispute(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDefendDispute(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DefendDisputeApiResponse : Adyen.Core.Client.ApiResponse, IDefendDisputeApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DefendDisputeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DefendDisputeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Disputes.Models.DefendDisputeResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Disputes.Models.DefendDisputeResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Disputes.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Disputes.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Disputes.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Disputes.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Disputes.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a defense document Deletes a specific dispute defense document that was supplied earlier. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteDisputeDefenseDocumentAsync(DeleteDefenseDocumentRequest deleteDefenseDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/deleteDisputeDefenseDocument" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/deleteDisputeDefenseDocument"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (deleteDefenseDocumentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(deleteDefenseDocumentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteDisputeDefenseDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/deleteDisputeDefenseDocument", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteDisputeDefenseDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteDisputeDefenseDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteDisputeDefenseDocumentApiResponse : Adyen.Core.Client.ApiResponse, IDeleteDisputeDefenseDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteDisputeDefenseDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteDisputeDefenseDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Disputes.Models.DeleteDefenseDocumentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Disputes.Models.DeleteDefenseDocumentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Disputes.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Disputes.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Disputes.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Disputes.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Disputes.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get applicable defense reasons Returns a list of all applicable defense reasons to defend a specific dispute. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RetrieveApplicableDefenseReasonsAsync(DefenseReasonsRequest defenseReasonsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/retrieveApplicableDefenseReasons" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/retrieveApplicableDefenseReasons"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (defenseReasonsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(defenseReasonsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RetrieveApplicableDefenseReasonsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/retrieveApplicableDefenseReasons", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRetrieveApplicableDefenseReasons(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRetrieveApplicableDefenseReasons(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RetrieveApplicableDefenseReasonsApiResponse : Adyen.Core.Client.ApiResponse, IRetrieveApplicableDefenseReasonsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RetrieveApplicableDefenseReasonsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RetrieveApplicableDefenseReasonsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Disputes.Models.DefenseReasonsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Disputes.Models.DefenseReasonsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Disputes.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Disputes.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Disputes.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Disputes.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Disputes.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Supply a defense document Supplies a specific dispute defense document. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SupplyDefenseDocumentAsync(SupplyDefenseDocumentRequest supplyDefenseDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/supplyDefenseDocument" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/supplyDefenseDocument"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (supplyDefenseDocumentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(supplyDefenseDocumentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SupplyDefenseDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/supplyDefenseDocument", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSupplyDefenseDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSupplyDefenseDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SupplyDefenseDocumentApiResponse : Adyen.Core.Client.ApiResponse, ISupplyDefenseDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SupplyDefenseDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SupplyDefenseDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Disputes.Models.SupplyDefenseDocumentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Disputes.Models.SupplyDefenseDocumentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Disputes.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Disputes.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Disputes.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Disputes.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Disputes.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Disputes.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Client/ApiKeyToken.cs b/Adyen/LegalEntityManagement/Client/ApiKeyToken.cs new file mode 100644 index 000000000..eceedd2d1 --- /dev/null +++ b/Adyen/LegalEntityManagement/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.LegalEntityManagement.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/LegalEntityManagement/Client/ClientUtils.cs b/Adyen/LegalEntityManagement/Client/ClientUtils.cs new file mode 100644 index 000000000..acd74f57c --- /dev/null +++ b/Adyen/LegalEntityManagement/Client/ClientUtils.cs @@ -0,0 +1,437 @@ +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Models; +using Models = Adyen.LegalEntityManagement.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.LegalEntityManagement.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AULocalAccountIdentification.TypeEnum aULocalAccountIdentificationTypeEnum) + return Models.AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentificationTypeEnum); + if (obj is Models.AcceptTermsOfServiceResponse.TypeEnum acceptTermsOfServiceResponseTypeEnum) + return Models.AcceptTermsOfServiceResponse.TypeEnum.ToJsonValue(acceptTermsOfServiceResponseTypeEnum); + if (obj is Models.AdditionalBankIdentification.TypeEnum additionalBankIdentificationTypeEnum) + return Models.AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentificationTypeEnum); + if (obj is Models.BusinessLine.ServiceEnum businessLineServiceEnum) + return Models.BusinessLine.ServiceEnum.ToJsonValue(businessLineServiceEnum); + if (obj is Models.BusinessLineInfo.ServiceEnum businessLineInfoServiceEnum) + return Models.BusinessLineInfo.ServiceEnum.ToJsonValue(businessLineInfoServiceEnum); + if (obj is Models.CALocalAccountIdentification.AccountTypeEnum cALocalAccountIdentificationAccountTypeEnum) + return Models.CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentificationAccountTypeEnum); + if (obj is Models.CALocalAccountIdentification.TypeEnum cALocalAccountIdentificationTypeEnum) + return Models.CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentificationTypeEnum); + if (obj is Models.CZLocalAccountIdentification.TypeEnum cZLocalAccountIdentificationTypeEnum) + return Models.CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentificationTypeEnum); + if (obj is Models.CalculatePciStatusRequest.AdditionalSalesChannelsEnum calculatePciStatusRequestAdditionalSalesChannelsEnum) + return CalculatePciStatusRequest.AdditionalSalesChannelsEnum.ToJsonValue(calculatePciStatusRequestAdditionalSalesChannelsEnum); + if (obj is Models.CalculateTermsOfServiceStatusResponse.TermsOfServiceTypesEnum calculateTermsOfServiceStatusResponseTermsOfServiceTypesEnum) + return CalculateTermsOfServiceStatusResponse.TermsOfServiceTypesEnum.ToJsonValue(calculateTermsOfServiceStatusResponseTermsOfServiceTypesEnum); + if (obj is Models.CapabilityProblemEntity.TypeEnum capabilityProblemEntityTypeEnum) + return Models.CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntityTypeEnum); + if (obj is Models.CapabilityProblemEntityRecursive.TypeEnum capabilityProblemEntityRecursiveTypeEnum) + return Models.CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursiveTypeEnum); + if (obj is Models.CapabilitySettings.FundingSourceEnum capabilitySettingsFundingSourceEnum) + return CapabilitySettings.FundingSourceEnum.ToJsonValue(capabilitySettingsFundingSourceEnum); + if (obj is Models.CapabilitySettings.IntervalEnum capabilitySettingsIntervalEnum) + return Models.CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettingsIntervalEnum); + if (obj is Models.DKLocalAccountIdentification.TypeEnum dKLocalAccountIdentificationTypeEnum) + return Models.DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentificationTypeEnum); + if (obj is Models.Document.TypeEnum documentTypeEnum) + return Models.Document.TypeEnum.ToJsonValue(documentTypeEnum); + if (obj is Models.DocumentPage.TypeEnum documentPageTypeEnum) + return Models.DocumentPage.TypeEnum.ToJsonValue(documentPageTypeEnum); + if (obj is Models.GeneratePciDescriptionRequest.AdditionalSalesChannelsEnum generatePciDescriptionRequestAdditionalSalesChannelsEnum) + return GeneratePciDescriptionRequest.AdditionalSalesChannelsEnum.ToJsonValue(generatePciDescriptionRequestAdditionalSalesChannelsEnum); + if (obj is Models.GetAcceptedTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormatEnum getAcceptedTermsOfServiceDocumentResponseTermsOfServiceDocumentFormatEnum) + return Models.GetAcceptedTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormatEnum.ToJsonValue(getAcceptedTermsOfServiceDocumentResponseTermsOfServiceDocumentFormatEnum); + if (obj is Models.GetTermsOfServiceDocumentRequest.TypeEnum getTermsOfServiceDocumentRequestTypeEnum) + return Models.GetTermsOfServiceDocumentRequest.TypeEnum.ToJsonValue(getTermsOfServiceDocumentRequestTypeEnum); + if (obj is Models.GetTermsOfServiceDocumentResponse.TypeEnum getTermsOfServiceDocumentResponseTypeEnum) + return Models.GetTermsOfServiceDocumentResponse.TypeEnum.ToJsonValue(getTermsOfServiceDocumentResponseTypeEnum); + if (obj is Models.HKLocalAccountIdentification.TypeEnum hKLocalAccountIdentificationTypeEnum) + return Models.HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentificationTypeEnum); + if (obj is Models.HULocalAccountIdentification.TypeEnum hULocalAccountIdentificationTypeEnum) + return Models.HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentificationTypeEnum); + if (obj is Models.IbanAccountIdentification.TypeEnum ibanAccountIdentificationTypeEnum) + return Models.IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentificationTypeEnum); + if (obj is Models.IdentificationData.TypeEnum identificationDataTypeEnum) + return Models.IdentificationData.TypeEnum.ToJsonValue(identificationDataTypeEnum); + if (obj is Models.LegalEntity.TypeEnum legalEntityTypeEnum) + return Models.LegalEntity.TypeEnum.ToJsonValue(legalEntityTypeEnum); + if (obj is Models.LegalEntityAssociation.TypeEnum legalEntityAssociationTypeEnum) + return Models.LegalEntityAssociation.TypeEnum.ToJsonValue(legalEntityAssociationTypeEnum); + if (obj is Models.LegalEntityCapability.AllowedLevelEnum legalEntityCapabilityAllowedLevelEnum) + return Models.LegalEntityCapability.AllowedLevelEnum.ToJsonValue(legalEntityCapabilityAllowedLevelEnum); + if (obj is Models.LegalEntityCapability.RequestedLevelEnum legalEntityCapabilityRequestedLevelEnum) + return Models.LegalEntityCapability.RequestedLevelEnum.ToJsonValue(legalEntityCapabilityRequestedLevelEnum); + if (obj is Models.LegalEntityInfo.TypeEnum legalEntityInfoTypeEnum) + return Models.LegalEntityInfo.TypeEnum.ToJsonValue(legalEntityInfoTypeEnum); + if (obj is Models.LegalEntityInfoRequiredType.TypeEnum legalEntityInfoRequiredTypeTypeEnum) + return Models.LegalEntityInfoRequiredType.TypeEnum.ToJsonValue(legalEntityInfoRequiredTypeTypeEnum); + if (obj is Models.NOLocalAccountIdentification.TypeEnum nOLocalAccountIdentificationTypeEnum) + return Models.NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentificationTypeEnum); + if (obj is Models.NZLocalAccountIdentification.TypeEnum nZLocalAccountIdentificationTypeEnum) + return Models.NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentificationTypeEnum); + if (obj is Models.NumberAndBicAccountIdentification.TypeEnum numberAndBicAccountIdentificationTypeEnum) + return Models.NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentificationTypeEnum); + if (obj is Models.Organization.InstitutionalSectorEnum organizationInstitutionalSectorEnum) + return Models.Organization.InstitutionalSectorEnum.ToJsonValue(organizationInstitutionalSectorEnum); + if (obj is Models.Organization.StatusOfLegalProceedingEnum organizationStatusOfLegalProceedingEnum) + return Models.Organization.StatusOfLegalProceedingEnum.ToJsonValue(organizationStatusOfLegalProceedingEnum); + if (obj is Models.Organization.TypeEnum organizationTypeEnum) + return Models.Organization.TypeEnum.ToJsonValue(organizationTypeEnum); + if (obj is Models.Organization.VatAbsenceReasonEnum organizationVatAbsenceReasonEnum) + return Models.Organization.VatAbsenceReasonEnum.ToJsonValue(organizationVatAbsenceReasonEnum); + if (obj is Models.PLLocalAccountIdentification.TypeEnum pLLocalAccountIdentificationTypeEnum) + return Models.PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentificationTypeEnum); + if (obj is Models.SELocalAccountIdentification.TypeEnum sELocalAccountIdentificationTypeEnum) + return Models.SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentificationTypeEnum); + if (obj is Models.SGLocalAccountIdentification.TypeEnum sGLocalAccountIdentificationTypeEnum) + return Models.SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentificationTypeEnum); + if (obj is Models.SoleProprietorship.VatAbsenceReasonEnum soleProprietorshipVatAbsenceReasonEnum) + return Models.SoleProprietorship.VatAbsenceReasonEnum.ToJsonValue(soleProprietorshipVatAbsenceReasonEnum); + if (obj is Models.SourceOfFunds.TypeEnum sourceOfFundsTypeEnum) + return Models.SourceOfFunds.TypeEnum.ToJsonValue(sourceOfFundsTypeEnum); + if (obj is Models.TaxReportingClassification.BusinessTypeEnum taxReportingClassificationBusinessTypeEnum) + return Models.TaxReportingClassification.BusinessTypeEnum.ToJsonValue(taxReportingClassificationBusinessTypeEnum); + if (obj is Models.TaxReportingClassification.MainSourceOfIncomeEnum taxReportingClassificationMainSourceOfIncomeEnum) + return Models.TaxReportingClassification.MainSourceOfIncomeEnum.ToJsonValue(taxReportingClassificationMainSourceOfIncomeEnum); + if (obj is Models.TaxReportingClassification.TypeEnum taxReportingClassificationTypeEnum) + return Models.TaxReportingClassification.TypeEnum.ToJsonValue(taxReportingClassificationTypeEnum); + if (obj is Models.TermsOfServiceAcceptanceInfo.TypeEnum termsOfServiceAcceptanceInfoTypeEnum) + return Models.TermsOfServiceAcceptanceInfo.TypeEnum.ToJsonValue(termsOfServiceAcceptanceInfoTypeEnum); + if (obj is Models.TransferInstrument.TypeEnum transferInstrumentTypeEnum) + return Models.TransferInstrument.TypeEnum.ToJsonValue(transferInstrumentTypeEnum); + if (obj is Models.TransferInstrumentInfo.TypeEnum transferInstrumentInfoTypeEnum) + return Models.TransferInstrumentInfo.TypeEnum.ToJsonValue(transferInstrumentInfoTypeEnum); + if (obj is Models.Trust.TypeEnum trustTypeEnum) + return Models.Trust.TypeEnum.ToJsonValue(trustTypeEnum); + if (obj is Models.Trust.VatAbsenceReasonEnum trustVatAbsenceReasonEnum) + return Models.Trust.VatAbsenceReasonEnum.ToJsonValue(trustVatAbsenceReasonEnum); + if (obj is Models.UKLocalAccountIdentification.TypeEnum uKLocalAccountIdentificationTypeEnum) + return Models.UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentificationTypeEnum); + if (obj is Models.USLocalAccountIdentification.AccountTypeEnum uSLocalAccountIdentificationAccountTypeEnum) + return Models.USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentificationAccountTypeEnum); + if (obj is Models.USLocalAccountIdentification.TypeEnum uSLocalAccountIdentificationTypeEnum) + return Models.USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentificationTypeEnum); + if (obj is Models.UnincorporatedPartnership.TypeEnum unincorporatedPartnershipTypeEnum) + return Models.UnincorporatedPartnership.TypeEnum.ToJsonValue(unincorporatedPartnershipTypeEnum); + if (obj is Models.UnincorporatedPartnership.VatAbsenceReasonEnum unincorporatedPartnershipVatAbsenceReasonEnum) + return Models.UnincorporatedPartnership.VatAbsenceReasonEnum.ToJsonValue(unincorporatedPartnershipVatAbsenceReasonEnum); + if (obj is Models.VerificationDeadline.CapabilitiesEnum verificationDeadlineCapabilitiesEnum) + return VerificationDeadline.CapabilitiesEnum.ToJsonValue(verificationDeadlineCapabilitiesEnum); + if (obj is Models.VerificationError.CapabilitiesEnum verificationErrorCapabilitiesEnum) + return VerificationError.CapabilitiesEnum.ToJsonValue(verificationErrorCapabilitiesEnum); + if (obj is Models.VerificationError.TypeEnum verificationErrorTypeEnum) + return Models.VerificationError.TypeEnum.ToJsonValue(verificationErrorTypeEnum); + if (obj is Models.VerificationErrorRecursive.CapabilitiesEnum verificationErrorRecursiveCapabilitiesEnum) + return VerificationErrorRecursive.CapabilitiesEnum.ToJsonValue(verificationErrorRecursiveCapabilitiesEnum); + if (obj is Models.VerificationErrorRecursive.TypeEnum verificationErrorRecursiveTypeEnum) + return Models.VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursiveTypeEnum); + if (obj is Models.WebDataExemption.ReasonEnum webDataExemptionReasonEnum) + return Models.WebDataExemption.ReasonEnum.ToJsonValue(webDataExemptionReasonEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/LegalEntityManagement/Client/HostConfiguration.cs b/Adyen/LegalEntityManagement/Client/HostConfiguration.cs new file mode 100644 index 000000000..e00c83021 --- /dev/null +++ b/Adyen/LegalEntityManagement/Client/HostConfiguration.cs @@ -0,0 +1,235 @@ +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.LegalEntityManagement.Services; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.LegalEntityManagement.Client +{ + /// + /// Provides hosting configuration for LegalEntityManagement + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://kyc-test.adyen.com/lem/v4"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AcceptTermsOfServiceRequestJsonConverter()); + _jsonOptions.Converters.Add(new AcceptTermsOfServiceResponseJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalBankIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AttachmentJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountInfoJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountInfoAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BirthDataJsonConverter()); + _jsonOptions.Converters.Add(new BusinessLineJsonConverter()); + _jsonOptions.Converters.Add(new BusinessLineInfoJsonConverter()); + _jsonOptions.Converters.Add(new BusinessLineInfoUpdateJsonConverter()); + _jsonOptions.Converters.Add(new BusinessLinesJsonConverter()); + _jsonOptions.Converters.Add(new CALocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CalculatePciStatusRequestJsonConverter()); + _jsonOptions.Converters.Add(new CalculatePciStatusResponseJsonConverter()); + _jsonOptions.Converters.Add(new CalculateTermsOfServiceStatusResponseJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new CapabilitySettingsJsonConverter()); + _jsonOptions.Converters.Add(new CheckTaxElectronicDeliveryConsentResponseJsonConverter()); + _jsonOptions.Converters.Add(new DKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new DataReviewConfirmationResponseJsonConverter()); + _jsonOptions.Converters.Add(new DocumentJsonConverter()); + _jsonOptions.Converters.Add(new DocumentPageJsonConverter()); + _jsonOptions.Converters.Add(new DocumentReferenceJsonConverter()); + _jsonOptions.Converters.Add(new EntityReferenceJsonConverter()); + _jsonOptions.Converters.Add(new FinancialReportJsonConverter()); + _jsonOptions.Converters.Add(new FinancierJsonConverter()); + _jsonOptions.Converters.Add(new GeneratePciDescriptionRequestJsonConverter()); + _jsonOptions.Converters.Add(new GeneratePciDescriptionResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetAcceptedTermsOfServiceDocumentResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetPciQuestionnaireInfosResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetPciQuestionnaireResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetTermsOfServiceAcceptanceInfosResponseJsonConverter()); + _jsonOptions.Converters.Add(new GetTermsOfServiceDocumentRequestJsonConverter()); + _jsonOptions.Converters.Add(new GetTermsOfServiceDocumentResponseJsonConverter()); + _jsonOptions.Converters.Add(new HKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new HULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new IdentificationDataJsonConverter()); + _jsonOptions.Converters.Add(new IndividualJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityAssociationJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityInfoJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityInfoRequiredTypeJsonConverter()); + _jsonOptions.Converters.Add(new NOLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new NumberAndBicAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new OnboardingLinkJsonConverter()); + _jsonOptions.Converters.Add(new OnboardingLinkInfoJsonConverter()); + _jsonOptions.Converters.Add(new OnboardingLinkSettingsJsonConverter()); + _jsonOptions.Converters.Add(new OnboardingThemeJsonConverter()); + _jsonOptions.Converters.Add(new OnboardingThemesJsonConverter()); + _jsonOptions.Converters.Add(new OrganizationJsonConverter()); + _jsonOptions.Converters.Add(new OwnerEntityJsonConverter()); + _jsonOptions.Converters.Add(new PLLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PciDocumentInfoJsonConverter()); + _jsonOptions.Converters.Add(new PciSigningRequestJsonConverter()); + _jsonOptions.Converters.Add(new PciSigningResponseJsonConverter()); + _jsonOptions.Converters.Add(new PhoneNumberJsonConverter()); + _jsonOptions.Converters.Add(new RemediatingActionJsonConverter()); + _jsonOptions.Converters.Add(new SELocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new SGLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new SetTaxElectronicDeliveryConsentRequestJsonConverter()); + _jsonOptions.Converters.Add(new SoleProprietorshipJsonConverter()); + _jsonOptions.Converters.Add(new SourceOfFundsJsonConverter()); + _jsonOptions.Converters.Add(new StockDataJsonConverter()); + _jsonOptions.Converters.Add(new SupportJsonConverter()); + _jsonOptions.Converters.Add(new SupportingEntityCapabilityJsonConverter()); + _jsonOptions.Converters.Add(new TaxInformationJsonConverter()); + _jsonOptions.Converters.Add(new TaxReportingClassificationJsonConverter()); + _jsonOptions.Converters.Add(new TermsOfServiceAcceptanceInfoJsonConverter()); + _jsonOptions.Converters.Add(new TransferInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new TransferInstrumentInfoJsonConverter()); + _jsonOptions.Converters.Add(new TransferInstrumentReferenceJsonConverter()); + _jsonOptions.Converters.Add(new TrustJsonConverter()); + _jsonOptions.Converters.Add(new UKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new USLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new UndefinedBeneficiaryJsonConverter()); + _jsonOptions.Converters.Add(new UnincorporatedPartnershipJsonConverter()); + _jsonOptions.Converters.Add(new VerificationDeadlineJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorsJsonConverter()); + _jsonOptions.Converters.Add(new WebDataJsonConverter()); + _jsonOptions.Converters.Add(new WebDataExemptionJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddLegalEntityManagementHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/LegalEntityManagement/Client/JsonSerializerOptionsProvider.cs b/Adyen/LegalEntityManagement/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..94dec5562 --- /dev/null +++ b/Adyen/LegalEntityManagement/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.LegalEntityManagement.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/LegalEntityManagement/Extensions/HostBuilderExtensions.cs b/Adyen/LegalEntityManagement/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..d609df042 --- /dev/null +++ b/Adyen/LegalEntityManagement/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.LegalEntityManagement; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the LegalEntityManagement API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureLegalEntityManagement(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddLegalEntityManagementHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/LegalEntityManagement/Extensions/ServiceCollectionExtensions.cs b/Adyen/LegalEntityManagement/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..e827b8b41 --- /dev/null +++ b/Adyen/LegalEntityManagement/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen LegalEntityManagement API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddLegalEntityManagementServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddLegalEntityManagementHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/AULocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/AULocalAccountIdentification.cs new file mode 100644 index 000000000..34fccb6f4 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/AULocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// AULocalAccountIdentification. + /// + public partial class AULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// **auLocal** (default to TypeEnum.AuLocal) + [JsonConstructor] + public AULocalAccountIdentification(string accountNumber, string bsbCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BsbCode = bsbCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuLocal - auLocal + /// + public static readonly TypeEnum AuLocal = new("auLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auLocal" => TypeEnum.AuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuLocal) + return "auLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + [JsonPropertyName("bsbCode")] + public string BsbCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BsbCode: ").Append(BsbCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 9.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // BsbCode (string) maxLength + if (this.BsbCode != null && this.BsbCode.Length > 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be less than 6.", new [] { "BsbCode" }); + } + + // BsbCode (string) minLength + if (this.BsbCode != null && this.BsbCode.Length < 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be greater than 6.", new [] { "BsbCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bsbCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bsbCode": + bsbCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(accountNumber)); + + if (!bsbCode.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(bsbCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(type)); + + return new AULocalAccountIdentification(accountNumber.Value!, bsbCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, aULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (aULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", aULocalAccountIdentification.AccountNumber); + + if (aULocalAccountIdentification.BsbCode != null) + writer.WriteString("bsbCode", aULocalAccountIdentification.BsbCode); + + if (aULocalAccountIdentification.Type != null) + { + string? typeRawValue = AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceRequest.cs b/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceRequest.cs new file mode 100644 index 000000000..cdb945871 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceRequest.cs @@ -0,0 +1,196 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// AcceptTermsOfServiceRequest. + /// + public partial class AcceptTermsOfServiceRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The legal entity ID of the user accepting the Terms of Service. For organizations, this must be the individual legal entity ID of an authorized signatory for the organization. For sole proprietorships, this must be the individual legal entity ID of the owner. For individuals, this must be the individual legal entity id of either the individual, parent, or guardian. + /// The IP address of the user accepting the Terms of Service. + [JsonConstructor] + public AcceptTermsOfServiceRequest(string acceptedBy, Option ipAddress = default) + { + AcceptedBy = acceptedBy; + _IpAddressOption = ipAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcceptTermsOfServiceRequest() + { + } + + partial void OnCreated(); + + /// + /// The legal entity ID of the user accepting the Terms of Service. For organizations, this must be the individual legal entity ID of an authorized signatory for the organization. For sole proprietorships, this must be the individual legal entity ID of the owner. For individuals, this must be the individual legal entity id of either the individual, parent, or guardian. + /// + /// The legal entity ID of the user accepting the Terms of Service. For organizations, this must be the individual legal entity ID of an authorized signatory for the organization. For sole proprietorships, this must be the individual legal entity ID of the owner. For individuals, this must be the individual legal entity id of either the individual, parent, or guardian. + [JsonPropertyName("acceptedBy")] + public string AcceptedBy { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IpAddressOption { get; private set; } + + /// + /// The IP address of the user accepting the Terms of Service. + /// + /// The IP address of the user accepting the Terms of Service. + [JsonPropertyName("ipAddress")] + public string? IpAddress { get { return this._IpAddressOption; } set { this._IpAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcceptTermsOfServiceRequest {\n"); + sb.Append(" AcceptedBy: ").Append(AcceptedBy).Append("\n"); + sb.Append(" IpAddress: ").Append(IpAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcceptTermsOfServiceRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcceptTermsOfServiceRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptedBy = default; + Option ipAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptedBy": + acceptedBy = new Option(utf8JsonReader.GetString()!); + break; + case "ipAddress": + ipAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!acceptedBy.IsSet) + throw new ArgumentException("Property is required for class AcceptTermsOfServiceRequest.", nameof(acceptedBy)); + + return new AcceptTermsOfServiceRequest(acceptedBy.Value!, ipAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcceptTermsOfServiceRequest acceptTermsOfServiceRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acceptTermsOfServiceRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcceptTermsOfServiceRequest acceptTermsOfServiceRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (acceptTermsOfServiceRequest.AcceptedBy != null) + writer.WriteString("acceptedBy", acceptTermsOfServiceRequest.AcceptedBy); + + if (acceptTermsOfServiceRequest._IpAddressOption.IsSet) + if (acceptTermsOfServiceRequest.IpAddress != null) + writer.WriteString("ipAddress", acceptTermsOfServiceRequest.IpAddress); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceResponse.cs b/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceResponse.cs new file mode 100644 index 000000000..290fc227c --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/AcceptTermsOfServiceResponse.cs @@ -0,0 +1,480 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// AcceptTermsOfServiceResponse. + /// + public partial class AcceptTermsOfServiceResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the user that accepted the Terms of Service. + /// The unique identifier of the Terms of Service acceptance. + /// The IP address of the user that accepted the Terms of Service. + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + /// The unique identifier of the Terms of Service document. + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConstructor] + public AcceptTermsOfServiceResponse(Option acceptedBy = default, Option id = default, Option ipAddress = default, Option language = default, Option termsOfServiceDocumentId = default, Option type = default) + { + _AcceptedByOption = acceptedBy; + _IdOption = id; + _IpAddressOption = ipAddress; + _LanguageOption = language; + _TermsOfServiceDocumentIdOption = termsOfServiceDocumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcceptTermsOfServiceResponse() + { + } + + partial void OnCreated(); + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AdyenAccount - adyenAccount + /// + public static readonly TypeEnum AdyenAccount = new("adyenAccount"); + + /// + /// TypeEnum.AdyenCapital - adyenCapital + /// + public static readonly TypeEnum AdyenCapital = new("adyenCapital"); + + /// + /// TypeEnum.AdyenCard - adyenCard + /// + public static readonly TypeEnum AdyenCard = new("adyenCard"); + + /// + /// TypeEnum.AdyenChargeCard - adyenChargeCard + /// + public static readonly TypeEnum AdyenChargeCard = new("adyenChargeCard"); + + /// + /// TypeEnum.AdyenForPlatformsAdvanced - adyenForPlatformsAdvanced + /// + public static readonly TypeEnum AdyenForPlatformsAdvanced = new("adyenForPlatformsAdvanced"); + + /// + /// TypeEnum.AdyenForPlatformsManage - adyenForPlatformsManage + /// + public static readonly TypeEnum AdyenForPlatformsManage = new("adyenForPlatformsManage"); + + /// + /// TypeEnum.AdyenFranchisee - adyenFranchisee + /// + public static readonly TypeEnum AdyenFranchisee = new("adyenFranchisee"); + + /// + /// TypeEnum.AdyenIssuing - adyenIssuing + /// + public static readonly TypeEnum AdyenIssuing = new("adyenIssuing"); + + /// + /// TypeEnum.AdyenPccr - adyenPccr + /// + public static readonly TypeEnum AdyenPccr = new("adyenPccr"); + + /// + /// TypeEnum.KycOnInvite - kycOnInvite + /// + public static readonly TypeEnum KycOnInvite = new("kycOnInvite"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "adyenAccount" => TypeEnum.AdyenAccount, + "adyenCapital" => TypeEnum.AdyenCapital, + "adyenCard" => TypeEnum.AdyenCard, + "adyenChargeCard" => TypeEnum.AdyenChargeCard, + "adyenForPlatformsAdvanced" => TypeEnum.AdyenForPlatformsAdvanced, + "adyenForPlatformsManage" => TypeEnum.AdyenForPlatformsManage, + "adyenFranchisee" => TypeEnum.AdyenFranchisee, + "adyenIssuing" => TypeEnum.AdyenIssuing, + "adyenPccr" => TypeEnum.AdyenPccr, + "kycOnInvite" => TypeEnum.KycOnInvite, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AdyenAccount) + return "adyenAccount"; + + if (value == TypeEnum.AdyenCapital) + return "adyenCapital"; + + if (value == TypeEnum.AdyenCard) + return "adyenCard"; + + if (value == TypeEnum.AdyenChargeCard) + return "adyenChargeCard"; + + if (value == TypeEnum.AdyenForPlatformsAdvanced) + return "adyenForPlatformsAdvanced"; + + if (value == TypeEnum.AdyenForPlatformsManage) + return "adyenForPlatformsManage"; + + if (value == TypeEnum.AdyenFranchisee) + return "adyenFranchisee"; + + if (value == TypeEnum.AdyenIssuing) + return "adyenIssuing"; + + if (value == TypeEnum.AdyenPccr) + return "adyenPccr"; + + if (value == TypeEnum.KycOnInvite) + return "kycOnInvite"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptedByOption { get; private set; } + + /// + /// The unique identifier of the user that accepted the Terms of Service. + /// + /// The unique identifier of the user that accepted the Terms of Service. + [JsonPropertyName("acceptedBy")] + public string? AcceptedBy { get { return this._AcceptedByOption; } set { this._AcceptedByOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the Terms of Service acceptance. + /// + /// The unique identifier of the Terms of Service acceptance. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IpAddressOption { get; private set; } + + /// + /// The IP address of the user that accepted the Terms of Service. + /// + /// The IP address of the user that accepted the Terms of Service. + [JsonPropertyName("ipAddress")] + public string? IpAddress { get { return this._IpAddressOption; } set { this._IpAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + /// + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceDocumentIdOption { get; private set; } + + /// + /// The unique identifier of the Terms of Service document. + /// + /// The unique identifier of the Terms of Service document. + [JsonPropertyName("termsOfServiceDocumentId")] + public string? TermsOfServiceDocumentId { get { return this._TermsOfServiceDocumentIdOption; } set { this._TermsOfServiceDocumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcceptTermsOfServiceResponse {\n"); + sb.Append(" AcceptedBy: ").Append(AcceptedBy).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IpAddress: ").Append(IpAddress).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" TermsOfServiceDocumentId: ").Append(TermsOfServiceDocumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcceptTermsOfServiceResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcceptTermsOfServiceResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptedBy = default; + Option id = default; + Option ipAddress = default; + Option language = default; + Option termsOfServiceDocumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptedBy": + acceptedBy = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "ipAddress": + ipAddress = new Option(utf8JsonReader.GetString()!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "termsOfServiceDocumentId": + termsOfServiceDocumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AcceptTermsOfServiceResponse.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AcceptTermsOfServiceResponse(acceptedBy, id, ipAddress, language, termsOfServiceDocumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcceptTermsOfServiceResponse acceptTermsOfServiceResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acceptTermsOfServiceResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcceptTermsOfServiceResponse acceptTermsOfServiceResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (acceptTermsOfServiceResponse._AcceptedByOption.IsSet) + if (acceptTermsOfServiceResponse.AcceptedBy != null) + writer.WriteString("acceptedBy", acceptTermsOfServiceResponse.AcceptedBy); + + if (acceptTermsOfServiceResponse._IdOption.IsSet) + if (acceptTermsOfServiceResponse.Id != null) + writer.WriteString("id", acceptTermsOfServiceResponse.Id); + + if (acceptTermsOfServiceResponse._IpAddressOption.IsSet) + if (acceptTermsOfServiceResponse.IpAddress != null) + writer.WriteString("ipAddress", acceptTermsOfServiceResponse.IpAddress); + + if (acceptTermsOfServiceResponse._LanguageOption.IsSet) + if (acceptTermsOfServiceResponse.Language != null) + writer.WriteString("language", acceptTermsOfServiceResponse.Language); + + if (acceptTermsOfServiceResponse._TermsOfServiceDocumentIdOption.IsSet) + if (acceptTermsOfServiceResponse.TermsOfServiceDocumentId != null) + writer.WriteString("termsOfServiceDocumentId", acceptTermsOfServiceResponse.TermsOfServiceDocumentId); + + if (acceptTermsOfServiceResponse._TypeOption.IsSet && acceptTermsOfServiceResponse.Type != null) + { + string? typeRawValue = AcceptTermsOfServiceResponse.TypeEnum.ToJsonValue(acceptTermsOfServiceResponse._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/AdditionalBankIdentification.cs b/Adyen/LegalEntityManagement/Models/AdditionalBankIdentification.cs new file mode 100644 index 000000000..2bf1dc60d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/AdditionalBankIdentification.cs @@ -0,0 +1,326 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// AdditionalBankIdentification. + /// + public partial class AdditionalBankIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the additional bank identification. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConstructor] + public AdditionalBankIdentification(Option code = default, Option type = default) + { + _CodeOption = code; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalBankIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuBsbCode - auBsbCode + /// + public static readonly TypeEnum AuBsbCode = new("auBsbCode"); + + /// + /// TypeEnum.CaRoutingNumber - caRoutingNumber + /// + public static readonly TypeEnum CaRoutingNumber = new("caRoutingNumber"); + + /// + /// TypeEnum.GbSortCode - gbSortCode + /// + public static readonly TypeEnum GbSortCode = new("gbSortCode"); + + /// + /// TypeEnum.UsRoutingNumber - usRoutingNumber + /// + public static readonly TypeEnum UsRoutingNumber = new("usRoutingNumber"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auBsbCode" => TypeEnum.AuBsbCode, + "caRoutingNumber" => TypeEnum.CaRoutingNumber, + "gbSortCode" => TypeEnum.GbSortCode, + "usRoutingNumber" => TypeEnum.UsRoutingNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuBsbCode) + return "auBsbCode"; + + if (value == TypeEnum.CaRoutingNumber) + return "caRoutingNumber"; + + if (value == TypeEnum.GbSortCode) + return "gbSortCode"; + + if (value == TypeEnum.UsRoutingNumber) + return "usRoutingNumber"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The value of the additional bank identification. + /// + /// The value of the additional bank identification. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalBankIdentification {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalBankIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalBankIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AdditionalBankIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AdditionalBankIdentification(code, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalBankIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalBankIdentification._CodeOption.IsSet) + if (additionalBankIdentification.Code != null) + writer.WriteString("code", additionalBankIdentification.Code); + + if (additionalBankIdentification._TypeOption.IsSet && additionalBankIdentification.Type != null) + { + string? typeRawValue = AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Address.cs b/Adyen/LegalEntityManagement/Models/Address.cs new file mode 100644 index 000000000..82c2a0dd6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Address.cs @@ -0,0 +1,296 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// The name of the city. Required if `stateOrProvince` is provided. If you specify the city, you must also send `postalCode` and `street`. + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA. + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US. Required for Australia and New Zealand. If you specify the state or province, you must also send `city`, `postalCode`, and `street`. + /// The name of the street, and the house or building number. Required if `stateOrProvince` and/or `city` is provided. + /// The apartment, unit, or suite number. + [JsonConstructor] + public Address(string country, Option city = default, Option postalCode = default, Option stateOrProvince = default, Option street = default, Option street2 = default) + { + Country = country; + _CityOption = city; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + _StreetOption = street; + _Street2Option = street2; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. Required if `stateOrProvince` is provided. If you specify the city, you must also send `postalCode` and `street`. + /// + /// The name of the city. Required if `stateOrProvince` is provided. If you specify the city, you must also send `postalCode` and `street`. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA. + /// + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US. Required for Australia and New Zealand. If you specify the state or province, you must also send `city`, `postalCode`, and `street`. + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US. Required for Australia and New Zealand. If you specify the state or province, you must also send `city`, `postalCode`, and `street`. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StreetOption { get; private set; } + + /// + /// The name of the street, and the house or building number. Required if `stateOrProvince` and/or `city` is provided. + /// + /// The name of the street, and the house or building number. Required if `stateOrProvince` and/or `city` is provided. + [JsonPropertyName("street")] + public string? Street { get { return this._StreetOption; } set { this._StreetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Street2Option { get; private set; } + + /// + /// The apartment, unit, or suite number. + /// + /// The apartment, unit, or suite number. + [JsonPropertyName("street2")] + public string? Street2 { get { return this._Street2Option; } set { this._Street2Option = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" Street2: ").Append(Street2).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option postalCode = default; + Option stateOrProvince = default; + Option street = default; + Option street2 = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "street2": + street2 = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + return new Address(country.Value!, city, postalCode, stateOrProvince, street, street2); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address._CityOption.IsSet) + if (address.City != null) + writer.WriteString("city", address.City); + + if (address._PostalCodeOption.IsSet) + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + + if (address._StreetOption.IsSet) + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._Street2Option.IsSet) + if (address.Street2 != null) + writer.WriteString("street2", address.Street2); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Amount.cs b/Adyen/LegalEntityManagement/Models/Amount.cs new file mode 100644 index 000000000..078ef32a0 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Amount.cs @@ -0,0 +1,201 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of currency. Must be EUR (or EUR equivalent) + /// Total value of amount. Must be >= 0 + [JsonConstructor] + public Amount(Option currency = default, Option value = default) + { + _CurrencyOption = currency; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The type of currency. Must be EUR (or EUR equivalent) + /// + /// The type of currency. Must be EUR (or EUR equivalent) + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// Total value of amount. Must be >= 0 + /// + /// Total value of amount. Must be >= 0 + [JsonPropertyName("value")] + public long? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new Amount(currency, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount._CurrencyOption.IsSet) + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + if (amount._ValueOption.IsSet) + writer.WriteNumber("value", amount._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Attachment.cs b/Adyen/LegalEntityManagement/Models/Attachment.cs new file mode 100644 index 000000000..bab57dbe6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Attachment.cs @@ -0,0 +1,272 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Attachment. + /// + public partial class Attachment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The document in Base64-encoded string format. + /// The file format. Possible values: **application/pdf**, **image/jpg**, **image/jpeg**, **image/png**. + /// The name of the file including the file extension. + /// The name of the file including the file extension. + /// Specifies which side of the ID card is uploaded. * If the `type` is **driversLicense** or **identityCard**, you must set this to **front** or **back** and include both sides in the same API request. * For any other types, when this is omitted, we infer the page number based on the order of attachments. + [JsonConstructor] + public Attachment(byte[] content, Option contentType = default, Option filename = default, Option pageName = default, Option pageType = default) + { + Content = content; + _ContentTypeOption = contentType; + _FilenameOption = filename; + _PageNameOption = pageName; + _PageTypeOption = pageType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Attachment() + { + } + + partial void OnCreated(); + + /// + /// The document in Base64-encoded string format. + /// + /// The document in Base64-encoded string format. + [JsonPropertyName("content")] + public byte[] Content { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContentTypeOption { get; private set; } + + /// + /// The file format. Possible values: **application/pdf**, **image/jpg**, **image/jpeg**, **image/png**. + /// + /// The file format. Possible values: **application/pdf**, **image/jpg**, **image/jpeg**, **image/png**. + [JsonPropertyName("contentType")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? ContentType { get { return this._ContentTypeOption; } set { this._ContentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FilenameOption { get; private set; } + + /// + /// The name of the file including the file extension. + /// + /// The name of the file including the file extension. + [JsonPropertyName("filename")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? Filename { get { return this._FilenameOption; } set { this._FilenameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PageNameOption { get; private set; } + + /// + /// The name of the file including the file extension. + /// + /// The name of the file including the file extension. + [JsonPropertyName("pageName")] + public string? PageName { get { return this._PageNameOption; } set { this._PageNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PageTypeOption { get; private set; } + + /// + /// Specifies which side of the ID card is uploaded. * If the `type` is **driversLicense** or **identityCard**, you must set this to **front** or **back** and include both sides in the same API request. * For any other types, when this is omitted, we infer the page number based on the order of attachments. + /// + /// Specifies which side of the ID card is uploaded. * If the `type` is **driversLicense** or **identityCard**, you must set this to **front** or **back** and include both sides in the same API request. * For any other types, when this is omitted, we infer the page number based on the order of attachments. + [JsonPropertyName("pageType")] + public string? PageType { get { return this._PageTypeOption; } set { this._PageTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Attachment {\n"); + sb.Append(" Content: ").Append(Content).Append("\n"); + sb.Append(" ContentType: ").Append(ContentType).Append("\n"); + sb.Append(" Filename: ").Append(Filename).Append("\n"); + sb.Append(" PageName: ").Append(PageName).Append("\n"); + sb.Append(" PageType: ").Append(PageType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AttachmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Attachment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option content = default; + Option contentType = default; + Option filename = default; + Option pageName = default; + Option pageType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "content": + content = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contentType": + contentType = new Option(utf8JsonReader.GetString()!); + break; + case "filename": + filename = new Option(utf8JsonReader.GetString()!); + break; + case "pageName": + pageName = new Option(utf8JsonReader.GetString()!); + break; + case "pageType": + pageType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!content.IsSet) + throw new ArgumentException("Property is required for class Attachment.", nameof(content)); + + return new Attachment(content.Value!, contentType, filename, pageName, pageType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Attachment attachment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, attachment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Attachment attachment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("content"); + JsonSerializer.Serialize(writer, attachment.Content, jsonSerializerOptions); + if (attachment._ContentTypeOption.IsSet) + if (attachment.ContentType != null) + writer.WriteString("contentType", attachment.ContentType); + + if (attachment._FilenameOption.IsSet) + if (attachment.Filename != null) + writer.WriteString("filename", attachment.Filename); + + if (attachment._PageNameOption.IsSet) + if (attachment.PageName != null) + writer.WriteString("pageName", attachment.PageName); + + if (attachment._PageTypeOption.IsSet) + if (attachment.PageType != null) + writer.WriteString("pageType", attachment.PageType); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BankAccountInfo.cs b/Adyen/LegalEntityManagement/Models/BankAccountInfo.cs new file mode 100644 index 000000000..b7d9c5885 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BankAccountInfo.cs @@ -0,0 +1,277 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BankAccountInfo. + /// + public partial class BankAccountInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountIdentification + /// The type of bank account. + /// The name of the banking institution where the bank account is held. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the bank account is registered. For example, **NL**. + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + [JsonConstructor] + public BankAccountInfo(Option accountIdentification = default, Option accountType = default, Option bankName = default, Option countryCode = default, Option trustedSource = default) + { + _AccountIdentificationOption = accountIdentification; + _AccountTypeOption = accountType; + _BankNameOption = bankName; + _CountryCodeOption = countryCode; + _TrustedSourceOption = trustedSource; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountIdentificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountIdentification")] + public BankAccountInfoAccountIdentification? AccountIdentification { get { return this._AccountIdentificationOption; } set { this._AccountIdentificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The type of bank account. + /// + /// The type of bank account. + [JsonPropertyName("accountType")] + [Obsolete("Deprecated since Legal Entity Management API v2.")] + public string? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankNameOption { get; private set; } + + /// + /// The name of the banking institution where the bank account is held. + /// + /// The name of the banking institution where the bank account is held. + [JsonPropertyName("bankName")] + public string? BankName { get { return this._BankNameOption; } set { this._BankNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the bank account is registered. For example, **NL**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the bank account is registered. For example, **NL**. + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedSourceOption { get; } + + /// + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + /// + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + [JsonPropertyName("trustedSource")] + public bool? TrustedSource { get { return this._TrustedSourceOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountInfo {\n"); + sb.Append(" AccountIdentification: ").Append(AccountIdentification).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BankName: ").Append(BankName).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" TrustedSource: ").Append(TrustedSource).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountIdentification = default; + Option accountType = default; + Option bankName = default; + Option countryCode = default; + Option trustedSource = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountIdentification": + accountIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountType": + accountType = new Option(utf8JsonReader.GetString()!); + break; + case "bankName": + bankName = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "trustedSource": + trustedSource = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new BankAccountInfo(accountIdentification, accountType, bankName, countryCode, trustedSource); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountInfo bankAccountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountInfo bankAccountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccountInfo._AccountIdentificationOption.IsSet) + { + writer.WritePropertyName("accountIdentification"); + JsonSerializer.Serialize(writer, bankAccountInfo.AccountIdentification, jsonSerializerOptions); + } + if (bankAccountInfo._AccountTypeOption.IsSet) + if (bankAccountInfo.AccountType != null) + writer.WriteString("accountType", bankAccountInfo.AccountType); + + if (bankAccountInfo._BankNameOption.IsSet) + if (bankAccountInfo.BankName != null) + writer.WriteString("bankName", bankAccountInfo.BankName); + + if (bankAccountInfo._CountryCodeOption.IsSet) + if (bankAccountInfo.CountryCode != null) + writer.WriteString("countryCode", bankAccountInfo.CountryCode); + + if (bankAccountInfo._TrustedSourceOption.IsSet) + writer.WriteBoolean("trustedSource", bankAccountInfo._TrustedSourceOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BankAccountInfoAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/BankAccountInfoAccountIdentification.cs new file mode 100644 index 000000000..e2fb86bb6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BankAccountInfoAccountIdentification.cs @@ -0,0 +1,539 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Identification of the bank account.. + /// + public partial class BankAccountInfoAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(AULocalAccountIdentification aULocalAccountIdentification) + { + AULocalAccountIdentification = aULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(CALocalAccountIdentification cALocalAccountIdentification) + { + CALocalAccountIdentification = cALocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(CZLocalAccountIdentification cZLocalAccountIdentification) + { + CZLocalAccountIdentification = cZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(DKLocalAccountIdentification dKLocalAccountIdentification) + { + DKLocalAccountIdentification = dKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(HKLocalAccountIdentification hKLocalAccountIdentification) + { + HKLocalAccountIdentification = hKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(HULocalAccountIdentification hULocalAccountIdentification) + { + HULocalAccountIdentification = hULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(NOLocalAccountIdentification nOLocalAccountIdentification) + { + NOLocalAccountIdentification = nOLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(NZLocalAccountIdentification nZLocalAccountIdentification) + { + NZLocalAccountIdentification = nZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(NumberAndBicAccountIdentification numberAndBicAccountIdentification) + { + NumberAndBicAccountIdentification = numberAndBicAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(PLLocalAccountIdentification pLLocalAccountIdentification) + { + PLLocalAccountIdentification = pLLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(SELocalAccountIdentification sELocalAccountIdentification) + { + SELocalAccountIdentification = sELocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(SGLocalAccountIdentification sGLocalAccountIdentification) + { + SGLocalAccountIdentification = sGLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(UKLocalAccountIdentification uKLocalAccountIdentification) + { + UKLocalAccountIdentification = uKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountInfoAccountIdentification(USLocalAccountIdentification uSLocalAccountIdentification) + { + USLocalAccountIdentification = uSLocalAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AULocalAccountIdentification? AULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CALocalAccountIdentification? CALocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CZLocalAccountIdentification? CZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public DKLocalAccountIdentification? DKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HKLocalAccountIdentification? HKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HULocalAccountIdentification? HULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// .. + /// + public NOLocalAccountIdentification? NOLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NZLocalAccountIdentification? NZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NumberAndBicAccountIdentification? NumberAndBicAccountIdentification { get; set; } + + /// + /// .. + /// + public PLLocalAccountIdentification? PLLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SELocalAccountIdentification? SELocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SGLocalAccountIdentification? SGLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public UKLocalAccountIdentification? UKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public USLocalAccountIdentification? USLocalAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountInfoAccountIdentification {\n"); + if (this.AULocalAccountIdentification != null) + sb.Append(AULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CALocalAccountIdentification != null) + sb.Append(CALocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CZLocalAccountIdentification != null) + sb.Append(CZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.DKLocalAccountIdentification != null) + sb.Append(DKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HKLocalAccountIdentification != null) + sb.Append(HKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HULocalAccountIdentification != null) + sb.Append(HULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NOLocalAccountIdentification != null) + sb.Append(NOLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NZLocalAccountIdentification != null) + sb.Append(NZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NumberAndBicAccountIdentification != null) + sb.Append(NumberAndBicAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.PLLocalAccountIdentification != null) + sb.Append(PLLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SELocalAccountIdentification != null) + sb.Append(SELocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SGLocalAccountIdentification != null) + sb.Append(SGLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.UKLocalAccountIdentification != null) + sb.Append(UKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.USLocalAccountIdentification != null) + sb.Append(USLocalAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountInfoAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountInfoAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AULocalAccountIdentification? aULocalAccountIdentification = default; + CALocalAccountIdentification? cALocalAccountIdentification = default; + CZLocalAccountIdentification? cZLocalAccountIdentification = default; + DKLocalAccountIdentification? dKLocalAccountIdentification = default; + HKLocalAccountIdentification? hKLocalAccountIdentification = default; + HULocalAccountIdentification? hULocalAccountIdentification = default; + IbanAccountIdentification? ibanAccountIdentification = default; + NOLocalAccountIdentification? nOLocalAccountIdentification = default; + NZLocalAccountIdentification? nZLocalAccountIdentification = default; + NumberAndBicAccountIdentification? numberAndBicAccountIdentification = default; + PLLocalAccountIdentification? pLLocalAccountIdentification = default; + SELocalAccountIdentification? sELocalAccountIdentification = default; + SGLocalAccountIdentification? sGLocalAccountIdentification = default; + UKLocalAccountIdentification? uKLocalAccountIdentification = default; + USLocalAccountIdentification? uSLocalAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAULocalAccountIdentification, jsonSerializerOptions, out aULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCALocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCALocalAccountIdentification, jsonSerializerOptions, out cALocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCZLocalAccountIdentification, jsonSerializerOptions, out cZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderDKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDKLocalAccountIdentification, jsonSerializerOptions, out dKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHKLocalAccountIdentification, jsonSerializerOptions, out hKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHULocalAccountIdentification, jsonSerializerOptions, out hULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + + Utf8JsonReader utf8JsonReaderNOLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNOLocalAccountIdentification, jsonSerializerOptions, out nOLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNZLocalAccountIdentification, jsonSerializerOptions, out nZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNumberAndBicAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumberAndBicAccountIdentification, jsonSerializerOptions, out numberAndBicAccountIdentification); + + Utf8JsonReader utf8JsonReaderPLLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPLLocalAccountIdentification, jsonSerializerOptions, out pLLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSELocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSELocalAccountIdentification, jsonSerializerOptions, out sELocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSGLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSGLocalAccountIdentification, jsonSerializerOptions, out sGLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUKLocalAccountIdentification, jsonSerializerOptions, out uKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUSLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSLocalAccountIdentification, jsonSerializerOptions, out uSLocalAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (aULocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(aULocalAccountIdentification); + + if (cALocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(cALocalAccountIdentification); + + if (cZLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(cZLocalAccountIdentification); + + if (dKLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(dKLocalAccountIdentification); + + if (hKLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(hKLocalAccountIdentification); + + if (hULocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(hULocalAccountIdentification); + + if (ibanAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(ibanAccountIdentification); + + if (nOLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(nOLocalAccountIdentification); + + if (nZLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(nZLocalAccountIdentification); + + if (numberAndBicAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(numberAndBicAccountIdentification); + + if (pLLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(pLLocalAccountIdentification); + + if (sELocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(sELocalAccountIdentification); + + if (sGLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(sGLocalAccountIdentification); + + if (uKLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(uKLocalAccountIdentification); + + if (uSLocalAccountIdentification?.Type != null) + return new BankAccountInfoAccountIdentification(uSLocalAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountInfoAccountIdentification bankAccountInfoAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + if (bankAccountInfoAccountIdentification.AULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.AULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.CALocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.CALocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.CZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.CZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.DKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.DKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.HKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.HKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.HULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.HULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.IbanAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.NOLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.NOLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.NZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.NZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.NumberAndBicAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.NumberAndBicAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.PLLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.PLLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.SELocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.SELocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.SGLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.SGLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.UKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.UKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountInfoAccountIdentification.USLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountInfoAccountIdentification.USLocalAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, bankAccountInfoAccountIdentification, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountInfoAccountIdentification bankAccountInfoAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BirthData.cs b/Adyen/LegalEntityManagement/Models/BirthData.cs new file mode 100644 index 000000000..690150d6b --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BirthData.cs @@ -0,0 +1,177 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BirthData. + /// + public partial class BirthData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The individual's date of birth, in YYYY-MM-DD format. + [JsonConstructor] + public BirthData(Option dateOfBirth = default) + { + _DateOfBirthOption = dateOfBirth; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BirthData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The individual's date of birth, in YYYY-MM-DD format. + /// + /// The individual's date of birth, in YYYY-MM-DD format. + [JsonPropertyName("dateOfBirth")] + public string? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BirthData {\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BirthDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BirthData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dateOfBirth = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dateOfBirth": + dateOfBirth = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BirthData(dateOfBirth); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BirthData birthData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, birthData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BirthData birthData, JsonSerializerOptions jsonSerializerOptions) + { + + if (birthData._DateOfBirthOption.IsSet) + if (birthData.DateOfBirth != null) + writer.WriteString("dateOfBirth", birthData.DateOfBirth); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BusinessLine.cs b/Adyen/LegalEntityManagement/Models/BusinessLine.cs new file mode 100644 index 000000000..80c5a7601 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BusinessLine.cs @@ -0,0 +1,476 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BusinessLine. + /// + public partial class BusinessLine : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the business line. + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// The verification errors related to capabilities for this supporting entity. + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// sourceOfFunds + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// webDataExemption + [JsonConstructor] + public BusinessLine(string id, string industryCode, string legalEntityId, ServiceEnum service, Option?> problems = default, Option?> salesChannels = default, Option sourceOfFunds = default, Option?> webData = default, Option webDataExemption = default) + { + Id = id; + IndustryCode = industryCode; + LegalEntityId = legalEntityId; + Service = service; + _ProblemsOption = problems; + _SalesChannelsOption = salesChannels; + _SourceOfFundsOption = sourceOfFunds; + _WebDataOption = webData; + _WebDataExemptionOption = webDataExemption; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BusinessLine() + { + } + + partial void OnCreated(); + + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + [JsonConverter(typeof(ServiceEnumJsonConverter))] + public class ServiceEnum : IEnum + { + /// + /// Returns the value of the ServiceEnum. + /// + public string? Value { get; set; } + + /// + /// ServiceEnum.PaymentProcessing - paymentProcessing + /// + public static readonly ServiceEnum PaymentProcessing = new("paymentProcessing"); + + /// + /// ServiceEnum.Issuing - issuing + /// + public static readonly ServiceEnum Issuing = new("issuing"); + + /// + /// ServiceEnum.Banking - banking + /// + public static readonly ServiceEnum Banking = new("banking"); + + private ServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ServiceEnum?(string? value) => value == null ? null : new ServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ServiceEnum? option) => option?.Value; + + public static bool operator ==(ServiceEnum? left, ServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ServiceEnum? left, ServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentProcessing" => ServiceEnum.PaymentProcessing, + "issuing" => ServiceEnum.Issuing, + "banking" => ServiceEnum.Banking, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ServiceEnum? value) + { + if (value == null) + return null; + + if (value == ServiceEnum.PaymentProcessing) + return "paymentProcessing"; + + if (value == ServiceEnum.Issuing) + return "issuing"; + + if (value == ServiceEnum.Banking) + return "banking"; + + return null; + } + + /// + /// JsonConverter for writing ServiceEnum. + /// + public class ServiceEnumJsonConverter : JsonConverter + { + public override ServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ServiceEnum.FromStringOrDefault(value) ?? new ServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + [JsonPropertyName("service")] + public ServiceEnum Service { get; set; } + + /// + /// The unique identifier of the business line. + /// + /// The unique identifier of the business line. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + /// + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + [JsonPropertyName("industryCode")] + public string IndustryCode { get; set; } + + /// + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + /// + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// The verification errors related to capabilities for this supporting entity. + /// + /// The verification errors related to capabilities for this supporting entity. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SalesChannelsOption { get; private set; } + + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + [JsonPropertyName("salesChannels")] + public List? SalesChannels { get { return this._SalesChannelsOption; } set { this._SalesChannelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceOfFundsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sourceOfFunds")] + public SourceOfFunds? SourceOfFunds { get { return this._SourceOfFundsOption; } set { this._SourceOfFundsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _WebDataOption { get; private set; } + + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + [JsonPropertyName("webData")] + public List? WebData { get { return this._WebDataOption; } set { this._WebDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebDataExemptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webDataExemption")] + public WebDataExemption? WebDataExemption { get { return this._WebDataExemptionOption; } set { this._WebDataExemptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BusinessLine {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IndustryCode: ").Append(IndustryCode).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" Service: ").Append(Service).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append(" SalesChannels: ").Append(SalesChannels).Append("\n"); + sb.Append(" SourceOfFunds: ").Append(SourceOfFunds).Append("\n"); + sb.Append(" WebData: ").Append(WebData).Append("\n"); + sb.Append(" WebDataExemption: ").Append(WebDataExemption).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BusinessLineJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BusinessLine Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option industryCode = default; + Option legalEntityId = default; + Option service = default; + Option?> problems = default; + Option?> salesChannels = default; + Option sourceOfFunds = default; + Option?> webData = default; + Option webDataExemption = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "industryCode": + industryCode = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "service": + string? serviceRawValue = utf8JsonReader.GetString(); + service = new Option(BusinessLine.ServiceEnum.FromStringOrDefault(serviceRawValue)); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "salesChannels": + salesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sourceOfFunds": + sourceOfFunds = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webData": + webData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webDataExemption": + webDataExemption = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class BusinessLine.", nameof(id)); + + if (!industryCode.IsSet) + throw new ArgumentException("Property is required for class BusinessLine.", nameof(industryCode)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class BusinessLine.", nameof(legalEntityId)); + + if (!service.IsSet) + throw new ArgumentException("Property is required for class BusinessLine.", nameof(service)); + + return new BusinessLine(id.Value!, industryCode.Value!, legalEntityId.Value!, service.Value!.Value!, problems, salesChannels, sourceOfFunds, webData, webDataExemption); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BusinessLine businessLine, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, businessLine, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BusinessLine businessLine, JsonSerializerOptions jsonSerializerOptions) + { + + if (businessLine.Id != null) + writer.WriteString("id", businessLine.Id); + + if (businessLine.IndustryCode != null) + writer.WriteString("industryCode", businessLine.IndustryCode); + + if (businessLine.LegalEntityId != null) + writer.WriteString("legalEntityId", businessLine.LegalEntityId); + + if (businessLine.Service != null) + { + string? serviceRawValue = BusinessLine.ServiceEnum.ToJsonValue(businessLine.Service); + writer.WriteString("service", serviceRawValue); + } + + if (businessLine._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, businessLine.Problems, jsonSerializerOptions); + } + if (businessLine._SalesChannelsOption.IsSet) + { + writer.WritePropertyName("salesChannels"); + JsonSerializer.Serialize(writer, businessLine.SalesChannels, jsonSerializerOptions); + } + if (businessLine._SourceOfFundsOption.IsSet) + { + writer.WritePropertyName("sourceOfFunds"); + JsonSerializer.Serialize(writer, businessLine.SourceOfFunds, jsonSerializerOptions); + } + if (businessLine._WebDataOption.IsSet) + { + writer.WritePropertyName("webData"); + JsonSerializer.Serialize(writer, businessLine.WebData, jsonSerializerOptions); + } + if (businessLine._WebDataExemptionOption.IsSet) + { + writer.WritePropertyName("webDataExemption"); + JsonSerializer.Serialize(writer, businessLine.WebDataExemption, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BusinessLineInfo.cs b/Adyen/LegalEntityManagement/Models/BusinessLineInfo.cs new file mode 100644 index 000000000..6b2cec46c --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BusinessLineInfo.cs @@ -0,0 +1,430 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BusinessLineInfo. + /// + public partial class BusinessLineInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// sourceOfFunds + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// webDataExemption + [JsonConstructor] + public BusinessLineInfo(string industryCode, string legalEntityId, ServiceEnum service, Option?> salesChannels = default, Option sourceOfFunds = default, Option?> webData = default, Option webDataExemption = default) + { + IndustryCode = industryCode; + LegalEntityId = legalEntityId; + Service = service; + _SalesChannelsOption = salesChannels; + _SourceOfFundsOption = sourceOfFunds; + _WebDataOption = webData; + _WebDataExemptionOption = webDataExemption; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BusinessLineInfo() + { + } + + partial void OnCreated(); + + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + [JsonConverter(typeof(ServiceEnumJsonConverter))] + public class ServiceEnum : IEnum + { + /// + /// Returns the value of the ServiceEnum. + /// + public string? Value { get; set; } + + /// + /// ServiceEnum.PaymentProcessing - paymentProcessing + /// + public static readonly ServiceEnum PaymentProcessing = new("paymentProcessing"); + + /// + /// ServiceEnum.Issuing - issuing + /// + public static readonly ServiceEnum Issuing = new("issuing"); + + /// + /// ServiceEnum.Banking - banking + /// + public static readonly ServiceEnum Banking = new("banking"); + + private ServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ServiceEnum?(string? value) => value == null ? null : new ServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ServiceEnum? option) => option?.Value; + + public static bool operator ==(ServiceEnum? left, ServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ServiceEnum? left, ServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentProcessing" => ServiceEnum.PaymentProcessing, + "issuing" => ServiceEnum.Issuing, + "banking" => ServiceEnum.Banking, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ServiceEnum? value) + { + if (value == null) + return null; + + if (value == ServiceEnum.PaymentProcessing) + return "paymentProcessing"; + + if (value == ServiceEnum.Issuing) + return "issuing"; + + if (value == ServiceEnum.Banking) + return "banking"; + + return null; + } + + /// + /// JsonConverter for writing ServiceEnum. + /// + public class ServiceEnumJsonConverter : JsonConverter + { + public override ServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ServiceEnum.FromStringOrDefault(value) ?? new ServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + /// + /// The service for which you are creating the business line. Possible values: * **paymentProcessing** * **issuing** * **banking** + [JsonPropertyName("service")] + public ServiceEnum Service { get; set; } + + /// + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + /// + /// A code that represents the industry of the legal entity for [marketplaces](https://docs.adyen.com/marketplaces/verification-requirements/reference-additional-products/#list-industry-codes) or [platforms](https://docs.adyen.com/platforms/verification-requirements/reference-additional-products/#list-industry-codes). For example, **4431A** for computer software stores. + [JsonPropertyName("industryCode")] + public string IndustryCode { get; set; } + + /// + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + /// + /// Unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) that owns the business line. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SalesChannelsOption { get; private set; } + + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + [JsonPropertyName("salesChannels")] + public List? SalesChannels { get { return this._SalesChannelsOption; } set { this._SalesChannelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceOfFundsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sourceOfFunds")] + public SourceOfFunds? SourceOfFunds { get { return this._SourceOfFundsOption; } set { this._SourceOfFundsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _WebDataOption { get; private set; } + + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + [JsonPropertyName("webData")] + public List? WebData { get { return this._WebDataOption; } set { this._WebDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebDataExemptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webDataExemption")] + public WebDataExemption? WebDataExemption { get { return this._WebDataExemptionOption; } set { this._WebDataExemptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BusinessLineInfo {\n"); + sb.Append(" IndustryCode: ").Append(IndustryCode).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" Service: ").Append(Service).Append("\n"); + sb.Append(" SalesChannels: ").Append(SalesChannels).Append("\n"); + sb.Append(" SourceOfFunds: ").Append(SourceOfFunds).Append("\n"); + sb.Append(" WebData: ").Append(WebData).Append("\n"); + sb.Append(" WebDataExemption: ").Append(WebDataExemption).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BusinessLineInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BusinessLineInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option industryCode = default; + Option legalEntityId = default; + Option service = default; + Option?> salesChannels = default; + Option sourceOfFunds = default; + Option?> webData = default; + Option webDataExemption = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "industryCode": + industryCode = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "service": + string? serviceRawValue = utf8JsonReader.GetString(); + service = new Option(BusinessLineInfo.ServiceEnum.FromStringOrDefault(serviceRawValue)); + break; + case "salesChannels": + salesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sourceOfFunds": + sourceOfFunds = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webData": + webData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webDataExemption": + webDataExemption = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!industryCode.IsSet) + throw new ArgumentException("Property is required for class BusinessLineInfo.", nameof(industryCode)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class BusinessLineInfo.", nameof(legalEntityId)); + + if (!service.IsSet) + throw new ArgumentException("Property is required for class BusinessLineInfo.", nameof(service)); + + return new BusinessLineInfo(industryCode.Value!, legalEntityId.Value!, service.Value!.Value!, salesChannels, sourceOfFunds, webData, webDataExemption); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BusinessLineInfo businessLineInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, businessLineInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BusinessLineInfo businessLineInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (businessLineInfo.IndustryCode != null) + writer.WriteString("industryCode", businessLineInfo.IndustryCode); + + if (businessLineInfo.LegalEntityId != null) + writer.WriteString("legalEntityId", businessLineInfo.LegalEntityId); + + if (businessLineInfo.Service != null) + { + string? serviceRawValue = BusinessLineInfo.ServiceEnum.ToJsonValue(businessLineInfo.Service); + writer.WriteString("service", serviceRawValue); + } + + if (businessLineInfo._SalesChannelsOption.IsSet) + { + writer.WritePropertyName("salesChannels"); + JsonSerializer.Serialize(writer, businessLineInfo.SalesChannels, jsonSerializerOptions); + } + if (businessLineInfo._SourceOfFundsOption.IsSet) + { + writer.WritePropertyName("sourceOfFunds"); + JsonSerializer.Serialize(writer, businessLineInfo.SourceOfFunds, jsonSerializerOptions); + } + if (businessLineInfo._WebDataOption.IsSet) + { + writer.WritePropertyName("webData"); + JsonSerializer.Serialize(writer, businessLineInfo.WebData, jsonSerializerOptions); + } + if (businessLineInfo._WebDataExemptionOption.IsSet) + { + writer.WritePropertyName("webDataExemption"); + JsonSerializer.Serialize(writer, businessLineInfo.WebDataExemption, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BusinessLineInfoUpdate.cs b/Adyen/LegalEntityManagement/Models/BusinessLineInfoUpdate.cs new file mode 100644 index 000000000..2b4df9aca --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BusinessLineInfoUpdate.cs @@ -0,0 +1,280 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BusinessLineInfoUpdate. + /// + public partial class BusinessLineInfoUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A code that represents the industry of your legal entity. For example, **4431A** for computer software stores. + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// sourceOfFunds + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// webDataExemption + [JsonConstructor] + public BusinessLineInfoUpdate(Option industryCode = default, Option?> salesChannels = default, Option sourceOfFunds = default, Option?> webData = default, Option webDataExemption = default) + { + _IndustryCodeOption = industryCode; + _SalesChannelsOption = salesChannels; + _SourceOfFundsOption = sourceOfFunds; + _WebDataOption = webData; + _WebDataExemptionOption = webDataExemption; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BusinessLineInfoUpdate() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryCodeOption { get; private set; } + + /// + /// A code that represents the industry of your legal entity. For example, **4431A** for computer software stores. + /// + /// A code that represents the industry of your legal entity. For example, **4431A** for computer software stores. + [JsonPropertyName("industryCode")] + public string? IndustryCode { get { return this._IndustryCodeOption; } set { this._IndustryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SalesChannelsOption { get; private set; } + + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + /// + /// A list of channels where goods or services are sold. Possible values: **pos**, **posMoto**, **eCommerce**, **ecomMoto**, **payByLink**. Required only in combination with the `service` **paymentProcessing**. + [JsonPropertyName("salesChannels")] + public List? SalesChannels { get { return this._SalesChannelsOption; } set { this._SalesChannelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceOfFundsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sourceOfFunds")] + public SourceOfFunds? SourceOfFunds { get { return this._SourceOfFundsOption; } set { this._SourceOfFundsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _WebDataOption { get; private set; } + + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + /// + /// List of website URLs where your user's goods or services are sold. When this is required for a service but your user does not have an online presence, provide the reason in the `webDataExemption` object. + [JsonPropertyName("webData")] + public List? WebData { get { return this._WebDataOption; } set { this._WebDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebDataExemptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webDataExemption")] + public WebDataExemption? WebDataExemption { get { return this._WebDataExemptionOption; } set { this._WebDataExemptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BusinessLineInfoUpdate {\n"); + sb.Append(" IndustryCode: ").Append(IndustryCode).Append("\n"); + sb.Append(" SalesChannels: ").Append(SalesChannels).Append("\n"); + sb.Append(" SourceOfFunds: ").Append(SourceOfFunds).Append("\n"); + sb.Append(" WebData: ").Append(WebData).Append("\n"); + sb.Append(" WebDataExemption: ").Append(WebDataExemption).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BusinessLineInfoUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BusinessLineInfoUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option industryCode = default; + Option?> salesChannels = default; + Option sourceOfFunds = default; + Option?> webData = default; + Option webDataExemption = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "industryCode": + industryCode = new Option(utf8JsonReader.GetString()!); + break; + case "salesChannels": + salesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sourceOfFunds": + sourceOfFunds = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webData": + webData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webDataExemption": + webDataExemption = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new BusinessLineInfoUpdate(industryCode, salesChannels, sourceOfFunds, webData, webDataExemption); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BusinessLineInfoUpdate businessLineInfoUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, businessLineInfoUpdate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BusinessLineInfoUpdate businessLineInfoUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + if (businessLineInfoUpdate._IndustryCodeOption.IsSet) + if (businessLineInfoUpdate.IndustryCode != null) + writer.WriteString("industryCode", businessLineInfoUpdate.IndustryCode); + + if (businessLineInfoUpdate._SalesChannelsOption.IsSet) + { + writer.WritePropertyName("salesChannels"); + JsonSerializer.Serialize(writer, businessLineInfoUpdate.SalesChannels, jsonSerializerOptions); + } + if (businessLineInfoUpdate._SourceOfFundsOption.IsSet) + { + writer.WritePropertyName("sourceOfFunds"); + JsonSerializer.Serialize(writer, businessLineInfoUpdate.SourceOfFunds, jsonSerializerOptions); + } + if (businessLineInfoUpdate._WebDataOption.IsSet) + { + writer.WritePropertyName("webData"); + JsonSerializer.Serialize(writer, businessLineInfoUpdate.WebData, jsonSerializerOptions); + } + if (businessLineInfoUpdate._WebDataExemptionOption.IsSet) + { + writer.WritePropertyName("webDataExemption"); + JsonSerializer.Serialize(writer, businessLineInfoUpdate.WebDataExemption, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/BusinessLines.cs b/Adyen/LegalEntityManagement/Models/BusinessLines.cs new file mode 100644 index 000000000..625f82e9f --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/BusinessLines.cs @@ -0,0 +1,171 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// BusinessLines. + /// + public partial class BusinessLines : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of business lines. + [JsonConstructor] + public BusinessLines(List varBusinessLines) + { + VarBusinessLines = varBusinessLines; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BusinessLines() + { + } + + partial void OnCreated(); + + /// + /// List of business lines. + /// + /// List of business lines. + [JsonPropertyName("businessLines")] + public List VarBusinessLines { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BusinessLines {\n"); + sb.Append(" VarBusinessLines: ").Append(VarBusinessLines).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BusinessLinesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BusinessLines Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> varBusinessLines = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "businessLines": + varBusinessLines = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!varBusinessLines.IsSet) + throw new ArgumentException("Property is required for class BusinessLines.", nameof(varBusinessLines)); + + return new BusinessLines(varBusinessLines.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BusinessLines businessLines, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, businessLines, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BusinessLines businessLines, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("businessLines"); + JsonSerializer.Serialize(writer, businessLines.VarBusinessLines, jsonSerializerOptions); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CALocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/CALocalAccountIdentification.cs new file mode 100644 index 000000000..720f33481 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CALocalAccountIdentification.cs @@ -0,0 +1,496 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CALocalAccountIdentification. + /// + public partial class CALocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// The 3-digit institution number, without separators or whitespace. + /// The 5-digit transit number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **caLocal** (default to TypeEnum.CaLocal) + [JsonConstructor] + public CALocalAccountIdentification(string accountNumber, string institutionNumber, string transitNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + InstitutionNumber = institutionNumber; + TransitNumber = transitNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CALocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CaLocal - caLocal + /// + public static readonly TypeEnum CaLocal = new("caLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "caLocal" => TypeEnum.CaLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CaLocal) + return "caLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit institution number, without separators or whitespace. + /// + /// The 3-digit institution number, without separators or whitespace. + [JsonPropertyName("institutionNumber")] + public string InstitutionNumber { get; set; } + + /// + /// The 5-digit transit number, without separators or whitespace. + /// + /// The 5-digit transit number, without separators or whitespace. + [JsonPropertyName("transitNumber")] + public string TransitNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CALocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" InstitutionNumber: ").Append(InstitutionNumber).Append("\n"); + sb.Append(" TransitNumber: ").Append(TransitNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 12) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 12.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // InstitutionNumber (string) maxLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length > 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be less than 3.", new [] { "InstitutionNumber" }); + } + + // InstitutionNumber (string) minLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length < 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be greater than 3.", new [] { "InstitutionNumber" }); + } + + // TransitNumber (string) maxLength + if (this.TransitNumber != null && this.TransitNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be less than 5.", new [] { "TransitNumber" }); + } + + // TransitNumber (string) minLength + if (this.TransitNumber != null && this.TransitNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be greater than 5.", new [] { "TransitNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CALocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CALocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option institutionNumber = default; + Option transitNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "institutionNumber": + institutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "transitNumber": + transitNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(CALocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CALocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(accountNumber)); + + if (!institutionNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(institutionNumber)); + + if (!transitNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(transitNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(type)); + + return new CALocalAccountIdentification(accountNumber.Value!, institutionNumber.Value!, transitNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cALocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cALocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cALocalAccountIdentification.AccountNumber); + + if (cALocalAccountIdentification.InstitutionNumber != null) + writer.WriteString("institutionNumber", cALocalAccountIdentification.InstitutionNumber); + + if (cALocalAccountIdentification.TransitNumber != null) + writer.WriteString("transitNumber", cALocalAccountIdentification.TransitNumber); + + if (cALocalAccountIdentification._AccountTypeOption.IsSet && cALocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (cALocalAccountIdentification.Type != null) + { + string? typeRawValue = CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CZLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/CZLocalAccountIdentification.cs new file mode 100644 index 000000000..bdf7595ff --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CZLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CZLocalAccountIdentification. + /// + public partial class CZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// **czLocal** (default to TypeEnum.CzLocal) + [JsonConstructor] + public CZLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CzLocal - czLocal + /// + public static readonly TypeEnum CzLocal = new("czLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "czLocal" => TypeEnum.CzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CzLocal) + return "czLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(type)); + + return new CZLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cZLocalAccountIdentification.AccountNumber); + + if (cZLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", cZLocalAccountIdentification.BankCode); + + if (cZLocalAccountIdentification.Type != null) + { + string? typeRawValue = CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CalculatePciStatusRequest.cs b/Adyen/LegalEntityManagement/Models/CalculatePciStatusRequest.cs new file mode 100644 index 000000000..3bf56067e --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CalculatePciStatusRequest.cs @@ -0,0 +1,299 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CalculatePciStatusRequest. + /// + public partial class CalculatePciStatusRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + [JsonConstructor] + public CalculatePciStatusRequest(Option?> additionalSalesChannels = default) + { + _AdditionalSalesChannelsOption = additionalSalesChannels; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CalculatePciStatusRequest() + { + } + + partial void OnCreated(); + + /// + /// Defines AdditionalSalesChannels. + /// + [JsonConverter(typeof(AdditionalSalesChannelsEnumJsonConverter))] + public class AdditionalSalesChannelsEnum : IEnum + { + /// + /// Returns the value of the AdditionalSalesChannelsEnum. + /// + public string? Value { get; set; } + + /// + /// AdditionalSalesChannelsEnum.ECommerce - eCommerce + /// + public static readonly AdditionalSalesChannelsEnum ECommerce = new("eCommerce"); + + /// + /// AdditionalSalesChannelsEnum.EcomMoto - ecomMoto + /// + public static readonly AdditionalSalesChannelsEnum EcomMoto = new("ecomMoto"); + + /// + /// AdditionalSalesChannelsEnum.Pos - pos + /// + public static readonly AdditionalSalesChannelsEnum Pos = new("pos"); + + /// + /// AdditionalSalesChannelsEnum.PosMoto - posMoto + /// + public static readonly AdditionalSalesChannelsEnum PosMoto = new("posMoto"); + + private AdditionalSalesChannelsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdditionalSalesChannelsEnum?(string? value) => value == null ? null : new AdditionalSalesChannelsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdditionalSalesChannelsEnum? option) => option?.Value; + + public static bool operator ==(AdditionalSalesChannelsEnum? left, AdditionalSalesChannelsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdditionalSalesChannelsEnum? left, AdditionalSalesChannelsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdditionalSalesChannelsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdditionalSalesChannelsEnum? FromStringOrDefault(string value) + { + return value switch { + "eCommerce" => AdditionalSalesChannelsEnum.ECommerce, + "ecomMoto" => AdditionalSalesChannelsEnum.EcomMoto, + "pos" => AdditionalSalesChannelsEnum.Pos, + "posMoto" => AdditionalSalesChannelsEnum.PosMoto, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdditionalSalesChannelsEnum? value) + { + if (value == null) + return null; + + if (value == AdditionalSalesChannelsEnum.ECommerce) + return "eCommerce"; + + if (value == AdditionalSalesChannelsEnum.EcomMoto) + return "ecomMoto"; + + if (value == AdditionalSalesChannelsEnum.Pos) + return "pos"; + + if (value == AdditionalSalesChannelsEnum.PosMoto) + return "posMoto"; + + return null; + } + + /// + /// JsonConverter for writing AdditionalSalesChannelsEnum. + /// + public class AdditionalSalesChannelsEnumJsonConverter : JsonConverter + { + public override AdditionalSalesChannelsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdditionalSalesChannelsEnum.FromStringOrDefault(value) ?? new AdditionalSalesChannelsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdditionalSalesChannelsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdditionalSalesChannelsEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalSalesChannelsOption { get; private set; } + + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + [JsonPropertyName("additionalSalesChannels")] + public List? AdditionalSalesChannels { get { return this._AdditionalSalesChannelsOption; } set { this._AdditionalSalesChannelsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CalculatePciStatusRequest {\n"); + sb.Append(" AdditionalSalesChannels: ").Append(AdditionalSalesChannels).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CalculatePciStatusRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CalculatePciStatusRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalSalesChannels = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalSalesChannels": + additionalSalesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CalculatePciStatusRequest(additionalSalesChannels); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CalculatePciStatusRequest calculatePciStatusRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, calculatePciStatusRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CalculatePciStatusRequest calculatePciStatusRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (calculatePciStatusRequest._AdditionalSalesChannelsOption.IsSet) + { + writer.WritePropertyName("additionalSalesChannels"); + JsonSerializer.Serialize(writer, calculatePciStatusRequest.AdditionalSalesChannels, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CalculatePciStatusResponse.cs b/Adyen/LegalEntityManagement/Models/CalculatePciStatusResponse.cs new file mode 100644 index 000000000..c6b4dd297 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CalculatePciStatusResponse.cs @@ -0,0 +1,176 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CalculatePciStatusResponse. + /// + public partial class CalculatePciStatusResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the user is required to sign PCI questionnaires. If **false**, they do not need to sign any questionnaires. + [JsonConstructor] + public CalculatePciStatusResponse(Option signingRequired = default) + { + _SigningRequiredOption = signingRequired; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CalculatePciStatusResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SigningRequiredOption { get; private set; } + + /// + /// Indicates if the user is required to sign PCI questionnaires. If **false**, they do not need to sign any questionnaires. + /// + /// Indicates if the user is required to sign PCI questionnaires. If **false**, they do not need to sign any questionnaires. + [JsonPropertyName("signingRequired")] + public bool? SigningRequired { get { return this._SigningRequiredOption; } set { this._SigningRequiredOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CalculatePciStatusResponse {\n"); + sb.Append(" SigningRequired: ").Append(SigningRequired).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CalculatePciStatusResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CalculatePciStatusResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option signingRequired = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "signingRequired": + signingRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new CalculatePciStatusResponse(signingRequired); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CalculatePciStatusResponse calculatePciStatusResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, calculatePciStatusResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CalculatePciStatusResponse calculatePciStatusResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (calculatePciStatusResponse._SigningRequiredOption.IsSet) + writer.WriteBoolean("signingRequired", calculatePciStatusResponse._SigningRequiredOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CalculateTermsOfServiceStatusResponse.cs b/Adyen/LegalEntityManagement/Models/CalculateTermsOfServiceStatusResponse.cs new file mode 100644 index 000000000..f6d72c5c7 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CalculateTermsOfServiceStatusResponse.cs @@ -0,0 +1,353 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CalculateTermsOfServiceStatusResponse. + /// + public partial class CalculateTermsOfServiceStatusResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of Terms of Service that the legal entity needs to accept. If empty, no Terms of Service needs to be accepted. + [JsonConstructor] + public CalculateTermsOfServiceStatusResponse(Option?> termsOfServiceTypes = default) + { + _TermsOfServiceTypesOption = termsOfServiceTypes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CalculateTermsOfServiceStatusResponse() + { + } + + partial void OnCreated(); + + /// + /// Defines TermsOfServiceTypes. + /// + [JsonConverter(typeof(TermsOfServiceTypesEnumJsonConverter))] + public class TermsOfServiceTypesEnum : IEnum + { + /// + /// Returns the value of the TermsOfServiceTypesEnum. + /// + public string? Value { get; set; } + + /// + /// TermsOfServiceTypesEnum.AdyenAccount - adyenAccount + /// + public static readonly TermsOfServiceTypesEnum AdyenAccount = new("adyenAccount"); + + /// + /// TermsOfServiceTypesEnum.AdyenCapital - adyenCapital + /// + public static readonly TermsOfServiceTypesEnum AdyenCapital = new("adyenCapital"); + + /// + /// TermsOfServiceTypesEnum.AdyenCard - adyenCard + /// + public static readonly TermsOfServiceTypesEnum AdyenCard = new("adyenCard"); + + /// + /// TermsOfServiceTypesEnum.AdyenChargeCard - adyenChargeCard + /// + public static readonly TermsOfServiceTypesEnum AdyenChargeCard = new("adyenChargeCard"); + + /// + /// TermsOfServiceTypesEnum.AdyenForPlatformsAdvanced - adyenForPlatformsAdvanced + /// + public static readonly TermsOfServiceTypesEnum AdyenForPlatformsAdvanced = new("adyenForPlatformsAdvanced"); + + /// + /// TermsOfServiceTypesEnum.AdyenForPlatformsManage - adyenForPlatformsManage + /// + public static readonly TermsOfServiceTypesEnum AdyenForPlatformsManage = new("adyenForPlatformsManage"); + + /// + /// TermsOfServiceTypesEnum.AdyenFranchisee - adyenFranchisee + /// + public static readonly TermsOfServiceTypesEnum AdyenFranchisee = new("adyenFranchisee"); + + /// + /// TermsOfServiceTypesEnum.AdyenIssuing - adyenIssuing + /// + public static readonly TermsOfServiceTypesEnum AdyenIssuing = new("adyenIssuing"); + + /// + /// TermsOfServiceTypesEnum.AdyenPccr - adyenPccr + /// + public static readonly TermsOfServiceTypesEnum AdyenPccr = new("adyenPccr"); + + /// + /// TermsOfServiceTypesEnum.KycOnInvite - kycOnInvite + /// + public static readonly TermsOfServiceTypesEnum KycOnInvite = new("kycOnInvite"); + + private TermsOfServiceTypesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TermsOfServiceTypesEnum?(string? value) => value == null ? null : new TermsOfServiceTypesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TermsOfServiceTypesEnum? option) => option?.Value; + + public static bool operator ==(TermsOfServiceTypesEnum? left, TermsOfServiceTypesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TermsOfServiceTypesEnum? left, TermsOfServiceTypesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TermsOfServiceTypesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TermsOfServiceTypesEnum? FromStringOrDefault(string value) + { + return value switch { + "adyenAccount" => TermsOfServiceTypesEnum.AdyenAccount, + "adyenCapital" => TermsOfServiceTypesEnum.AdyenCapital, + "adyenCard" => TermsOfServiceTypesEnum.AdyenCard, + "adyenChargeCard" => TermsOfServiceTypesEnum.AdyenChargeCard, + "adyenForPlatformsAdvanced" => TermsOfServiceTypesEnum.AdyenForPlatformsAdvanced, + "adyenForPlatformsManage" => TermsOfServiceTypesEnum.AdyenForPlatformsManage, + "adyenFranchisee" => TermsOfServiceTypesEnum.AdyenFranchisee, + "adyenIssuing" => TermsOfServiceTypesEnum.AdyenIssuing, + "adyenPccr" => TermsOfServiceTypesEnum.AdyenPccr, + "kycOnInvite" => TermsOfServiceTypesEnum.KycOnInvite, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TermsOfServiceTypesEnum? value) + { + if (value == null) + return null; + + if (value == TermsOfServiceTypesEnum.AdyenAccount) + return "adyenAccount"; + + if (value == TermsOfServiceTypesEnum.AdyenCapital) + return "adyenCapital"; + + if (value == TermsOfServiceTypesEnum.AdyenCard) + return "adyenCard"; + + if (value == TermsOfServiceTypesEnum.AdyenChargeCard) + return "adyenChargeCard"; + + if (value == TermsOfServiceTypesEnum.AdyenForPlatformsAdvanced) + return "adyenForPlatformsAdvanced"; + + if (value == TermsOfServiceTypesEnum.AdyenForPlatformsManage) + return "adyenForPlatformsManage"; + + if (value == TermsOfServiceTypesEnum.AdyenFranchisee) + return "adyenFranchisee"; + + if (value == TermsOfServiceTypesEnum.AdyenIssuing) + return "adyenIssuing"; + + if (value == TermsOfServiceTypesEnum.AdyenPccr) + return "adyenPccr"; + + if (value == TermsOfServiceTypesEnum.KycOnInvite) + return "kycOnInvite"; + + return null; + } + + /// + /// JsonConverter for writing TermsOfServiceTypesEnum. + /// + public class TermsOfServiceTypesEnumJsonConverter : JsonConverter + { + public override TermsOfServiceTypesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TermsOfServiceTypesEnum.FromStringOrDefault(value) ?? new TermsOfServiceTypesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TermsOfServiceTypesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TermsOfServiceTypesEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TermsOfServiceTypesOption { get; private set; } + + /// + /// The type of Terms of Service that the legal entity needs to accept. If empty, no Terms of Service needs to be accepted. + /// + /// The type of Terms of Service that the legal entity needs to accept. If empty, no Terms of Service needs to be accepted. + [JsonPropertyName("termsOfServiceTypes")] + public List? TermsOfServiceTypes { get { return this._TermsOfServiceTypesOption; } set { this._TermsOfServiceTypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CalculateTermsOfServiceStatusResponse {\n"); + sb.Append(" TermsOfServiceTypes: ").Append(TermsOfServiceTypes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CalculateTermsOfServiceStatusResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CalculateTermsOfServiceStatusResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> termsOfServiceTypes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "termsOfServiceTypes": + termsOfServiceTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CalculateTermsOfServiceStatusResponse(termsOfServiceTypes); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CalculateTermsOfServiceStatusResponse calculateTermsOfServiceStatusResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, calculateTermsOfServiceStatusResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CalculateTermsOfServiceStatusResponse calculateTermsOfServiceStatusResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (calculateTermsOfServiceStatusResponse._TermsOfServiceTypesOption.IsSet) + { + writer.WritePropertyName("termsOfServiceTypes"); + JsonSerializer.Serialize(writer, calculateTermsOfServiceStatusResponse.TermsOfServiceTypes, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CapabilityProblem.cs b/Adyen/LegalEntityManagement/Models/CapabilityProblem.cs new file mode 100644 index 000000000..7a9209290 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CapabilityProblem.cs @@ -0,0 +1,203 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CapabilityProblem. + /// + public partial class CapabilityProblem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// entity + /// verificationErrors + [JsonConstructor] + public CapabilityProblem(Option entity = default, Option?> verificationErrors = default) + { + _EntityOption = entity; + _VerificationErrorsOption = verificationErrors; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("entity")] + public CapabilityProblemEntity? Entity { get { return this._EntityOption; } set { this._EntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationErrorsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("verificationErrors")] + public List? VerificationErrors { get { return this._VerificationErrorsOption; } set { this._VerificationErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblem {\n"); + sb.Append(" Entity: ").Append(Entity).Append("\n"); + sb.Append(" VerificationErrors: ").Append(VerificationErrors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entity = default; + Option?> verificationErrors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entity": + entity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationErrors": + verificationErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilityProblem(entity, verificationErrors); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblem._EntityOption.IsSet) + { + writer.WritePropertyName("entity"); + JsonSerializer.Serialize(writer, capabilityProblem.Entity, jsonSerializerOptions); + } + if (capabilityProblem._VerificationErrorsOption.IsSet) + { + writer.WritePropertyName("verificationErrors"); + JsonSerializer.Serialize(writer, capabilityProblem.VerificationErrors, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CapabilityProblemEntity.cs b/Adyen/LegalEntityManagement/Models/CapabilityProblemEntity.cs new file mode 100644 index 000000000..1a3b0b8e4 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CapabilityProblemEntity.cs @@ -0,0 +1,374 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CapabilityProblemEntity. + /// + public partial class CapabilityProblemEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs corresponding to the verification errors from capabilities. + /// id + /// owner + /// type + [JsonConstructor] + public CapabilityProblemEntity(Option?> documents = default, Option id = default, Option owner = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _OwnerOption = owner; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntity() + { + } + + partial void OnCreated(); + + /// + /// Defines Type. + /// + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + /// + /// TypeEnum.Product - product + /// + public static readonly TypeEnum Product = new("product"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + "product" => TypeEnum.Product, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + if (value == TypeEnum.Product) + return "product"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs corresponding to the verification errors from capabilities. + /// + /// List of document IDs corresponding to the verification errors from capabilities. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("owner")] + public CapabilityProblemEntityRecursive? Owner { get { return this._OwnerOption; } set { this._OwnerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntity {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Owner: ").Append(Owner).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option owner = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "owner": + owner = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntity.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntity(documents, id, owner, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntity._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntity._IdOption.IsSet) + if (capabilityProblemEntity.Id != null) + writer.WriteString("id", capabilityProblemEntity.Id); + + if (capabilityProblemEntity._OwnerOption.IsSet) + { + writer.WritePropertyName("owner"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Owner, jsonSerializerOptions); + } + if (capabilityProblemEntity._TypeOption.IsSet && capabilityProblemEntity.Type != null) + { + string? typeRawValue = CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntity._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CapabilityProblemEntityRecursive.cs b/Adyen/LegalEntityManagement/Models/CapabilityProblemEntityRecursive.cs new file mode 100644 index 000000000..b065d6874 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CapabilityProblemEntityRecursive.cs @@ -0,0 +1,349 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CapabilityProblemEntityRecursive. + /// + public partial class CapabilityProblemEntityRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs corresponding to the verification errors from capabilities. + /// id + /// type + [JsonConstructor] + public CapabilityProblemEntityRecursive(Option?> documents = default, Option id = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntityRecursive() + { + } + + partial void OnCreated(); + + /// + /// Defines Type. + /// + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + /// + /// TypeEnum.Product - product + /// + public static readonly TypeEnum Product = new("product"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + "product" => TypeEnum.Product, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + if (value == TypeEnum.Product) + return "product"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs corresponding to the verification errors from capabilities. + /// + /// List of document IDs corresponding to the verification errors from capabilities. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntityRecursive {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntityRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntityRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntityRecursive(documents, id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntityRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntityRecursive._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntityRecursive.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntityRecursive._IdOption.IsSet) + if (capabilityProblemEntityRecursive.Id != null) + writer.WriteString("id", capabilityProblemEntityRecursive.Id); + + if (capabilityProblemEntityRecursive._TypeOption.IsSet && capabilityProblemEntityRecursive.Type != null) + { + string? typeRawValue = CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CapabilitySettings.cs b/Adyen/LegalEntityManagement/Models/CapabilitySettings.cs new file mode 100644 index 000000000..d41fc1142 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CapabilitySettings.cs @@ -0,0 +1,505 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CapabilitySettings. + /// + public partial class CapabilitySettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The maximum amount a card holder can spend per industry. + /// The number of card holders who can use the card. + /// The funding source of the card, for example **debit**. + /// The period when the rule conditions apply. + /// maxAmount + [JsonConstructor] + public CapabilitySettings(Option?> amountPerIndustry = default, Option authorizedCardUsers = default, Option?> fundingSource = default, Option interval = default, Option maxAmount = default) + { + _AmountPerIndustryOption = amountPerIndustry; + _AuthorizedCardUsersOption = authorizedCardUsers; + _FundingSourceOption = fundingSource; + _IntervalOption = interval; + _MaxAmountOption = maxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilitySettings() + { + } + + partial void OnCreated(); + + /// + /// Defines FundingSource. + /// + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + /// + /// FundingSourceEnum.Prepaid - prepaid + /// + public static readonly FundingSourceEnum Prepaid = new("prepaid"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + "prepaid" => FundingSourceEnum.Prepaid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + if (value == FundingSourceEnum.Prepaid) + return "prepaid"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// The period when the rule conditions apply. + /// + /// The period when the rule conditions apply. + [JsonConverter(typeof(IntervalEnumJsonConverter))] + public class IntervalEnum : IEnum + { + /// + /// Returns the value of the IntervalEnum. + /// + public string? Value { get; set; } + + /// + /// IntervalEnum.Daily - daily + /// + public static readonly IntervalEnum Daily = new("daily"); + + /// + /// IntervalEnum.Monthly - monthly + /// + public static readonly IntervalEnum Monthly = new("monthly"); + + /// + /// IntervalEnum.Weekly - weekly + /// + public static readonly IntervalEnum Weekly = new("weekly"); + + private IntervalEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IntervalEnum?(string? value) => value == null ? null : new IntervalEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IntervalEnum? option) => option?.Value; + + public static bool operator ==(IntervalEnum? left, IntervalEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IntervalEnum? left, IntervalEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IntervalEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IntervalEnum? FromStringOrDefault(string value) + { + return value switch { + "daily" => IntervalEnum.Daily, + "monthly" => IntervalEnum.Monthly, + "weekly" => IntervalEnum.Weekly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IntervalEnum? value) + { + if (value == null) + return null; + + if (value == IntervalEnum.Daily) + return "daily"; + + if (value == IntervalEnum.Monthly) + return "monthly"; + + if (value == IntervalEnum.Weekly) + return "weekly"; + + return null; + } + + /// + /// JsonConverter for writing IntervalEnum. + /// + public class IntervalEnumJsonConverter : JsonConverter + { + public override IntervalEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IntervalEnum.FromStringOrDefault(value) ?? new IntervalEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IntervalEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IntervalEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IntervalOption { get; private set; } + + /// + /// The period when the rule conditions apply. + /// + /// The period when the rule conditions apply. + [JsonPropertyName("interval")] + public IntervalEnum? Interval { get { return this._IntervalOption; } set { this._IntervalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AmountPerIndustryOption { get; private set; } + + /// + /// The maximum amount a card holder can spend per industry. + /// + /// The maximum amount a card holder can spend per industry. + [JsonPropertyName("amountPerIndustry")] + public Dictionary? AmountPerIndustry { get { return this._AmountPerIndustryOption; } set { this._AmountPerIndustryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorizedCardUsersOption { get; private set; } + + /// + /// The number of card holders who can use the card. + /// + /// The number of card holders who can use the card. + [JsonPropertyName("authorizedCardUsers")] + public bool? AuthorizedCardUsers { get { return this._AuthorizedCardUsersOption; } set { this._AuthorizedCardUsersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FundingSourceOption { get; private set; } + + /// + /// The funding source of the card, for example **debit**. + /// + /// The funding source of the card, for example **debit**. + [JsonPropertyName("fundingSource")] + public List? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maxAmount")] + public Amount? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilitySettings {\n"); + sb.Append(" AmountPerIndustry: ").Append(AmountPerIndustry).Append("\n"); + sb.Append(" AuthorizedCardUsers: ").Append(AuthorizedCardUsers).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Interval: ").Append(Interval).Append("\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilitySettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilitySettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> amountPerIndustry = default; + Option authorizedCardUsers = default; + Option?> fundingSource = default; + Option interval = default; + Option maxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amountPerIndustry": + amountPerIndustry = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authorizedCardUsers": + authorizedCardUsers = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "fundingSource": + fundingSource = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interval": + string? intervalRawValue = utf8JsonReader.GetString(); + interval = new Option(CapabilitySettings.IntervalEnum.FromStringOrDefault(intervalRawValue)); + break; + case "maxAmount": + maxAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilitySettings(amountPerIndustry, authorizedCardUsers, fundingSource, interval, maxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilitySettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilitySettings capabilitySettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilitySettings._AmountPerIndustryOption.IsSet) + { + writer.WritePropertyName("amountPerIndustry"); + JsonSerializer.Serialize(writer, capabilitySettings.AmountPerIndustry, jsonSerializerOptions); + } + if (capabilitySettings._AuthorizedCardUsersOption.IsSet) + writer.WriteBoolean("authorizedCardUsers", capabilitySettings._AuthorizedCardUsersOption.Value!.Value); + + if (capabilitySettings._FundingSourceOption.IsSet) + { + writer.WritePropertyName("fundingSource"); + JsonSerializer.Serialize(writer, capabilitySettings.FundingSource, jsonSerializerOptions); + } + if (capabilitySettings._IntervalOption.IsSet && capabilitySettings.Interval != null) + { + string? intervalRawValue = CapabilitySettings.IntervalEnum.ToJsonValue(capabilitySettings._IntervalOption.Value!.Value); + writer.WriteString("interval", intervalRawValue); + } + + if (capabilitySettings._MaxAmountOption.IsSet) + { + writer.WritePropertyName("maxAmount"); + JsonSerializer.Serialize(writer, capabilitySettings.MaxAmount, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/CheckTaxElectronicDeliveryConsentResponse.cs b/Adyen/LegalEntityManagement/Models/CheckTaxElectronicDeliveryConsentResponse.cs new file mode 100644 index 000000000..49d59c6d6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/CheckTaxElectronicDeliveryConsentResponse.cs @@ -0,0 +1,176 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// CheckTaxElectronicDeliveryConsentResponse. + /// + public partial class CheckTaxElectronicDeliveryConsentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Consent to electronically deliver tax form US1099-K. + [JsonConstructor] + public CheckTaxElectronicDeliveryConsentResponse(Option uS1099k = default) + { + _US1099kOption = uS1099k; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CheckTaxElectronicDeliveryConsentResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _US1099kOption { get; private set; } + + /// + /// Consent to electronically deliver tax form US1099-K. + /// + /// Consent to electronically deliver tax form US1099-K. + [JsonPropertyName("US1099k")] + public bool? US1099k { get { return this._US1099kOption; } set { this._US1099kOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CheckTaxElectronicDeliveryConsentResponse {\n"); + sb.Append(" US1099k: ").Append(US1099k).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CheckTaxElectronicDeliveryConsentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CheckTaxElectronicDeliveryConsentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option uS1099k = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "US1099k": + uS1099k = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new CheckTaxElectronicDeliveryConsentResponse(uS1099k); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CheckTaxElectronicDeliveryConsentResponse checkTaxElectronicDeliveryConsentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, checkTaxElectronicDeliveryConsentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CheckTaxElectronicDeliveryConsentResponse checkTaxElectronicDeliveryConsentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (checkTaxElectronicDeliveryConsentResponse._US1099kOption.IsSet) + writer.WriteBoolean("US1099k", checkTaxElectronicDeliveryConsentResponse._US1099kOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/DKLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/DKLocalAccountIdentification.cs new file mode 100644 index 000000000..5a10057b4 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/DKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// DKLocalAccountIdentification. + /// + public partial class DKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// **dkLocal** (default to TypeEnum.DkLocal) + [JsonConstructor] + public DKLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DkLocal - dkLocal + /// + public static readonly TypeEnum DkLocal = new("dkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dkLocal" => TypeEnum.DkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DkLocal) + return "dkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(type)); + + return new DKLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (dKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", dKLocalAccountIdentification.AccountNumber); + + if (dKLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", dKLocalAccountIdentification.BankCode); + + if (dKLocalAccountIdentification.Type != null) + { + string? typeRawValue = DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/DataReviewConfirmationResponse.cs b/Adyen/LegalEntityManagement/Models/DataReviewConfirmationResponse.cs new file mode 100644 index 000000000..3c6b9788a --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/DataReviewConfirmationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// DataReviewConfirmationResponse. + /// + public partial class DataReviewConfirmationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Date when data review was confirmed. + [JsonConstructor] + public DataReviewConfirmationResponse(Option dataReviewedAt = default) + { + _DataReviewedAtOption = dataReviewedAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DataReviewConfirmationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DataReviewedAtOption { get; private set; } + + /// + /// Date when data review was confirmed. + /// + /// Date when data review was confirmed. + [JsonPropertyName("dataReviewedAt")] + public string? DataReviewedAt { get { return this._DataReviewedAtOption; } set { this._DataReviewedAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DataReviewConfirmationResponse {\n"); + sb.Append(" DataReviewedAt: ").Append(DataReviewedAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DataReviewConfirmationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DataReviewConfirmationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dataReviewedAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dataReviewedAt": + dataReviewedAt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DataReviewConfirmationResponse(dataReviewedAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DataReviewConfirmationResponse dataReviewConfirmationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dataReviewConfirmationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DataReviewConfirmationResponse dataReviewConfirmationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (dataReviewConfirmationResponse._DataReviewedAtOption.IsSet) + if (dataReviewConfirmationResponse.DataReviewedAt != null) + writer.WriteString("dataReviewedAt", dataReviewConfirmationResponse.DataReviewedAt); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Document.cs b/Adyen/LegalEntityManagement/Models/Document.cs new file mode 100644 index 000000000..4010d2e2a --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Document.cs @@ -0,0 +1,748 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Document. + /// + public partial class Document : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your description for the document. + /// Type of document, used when providing an ID number or uploading a document. The possible values depend on the legal entity type. * For **organization**, the `type` values can be **proofOfAddress**, **registrationDocument**, **vatDocument**, **proofOfOrganizationTaxInfo**, **proofOfOwnership**, **proofOfIndustry**, **proofOfSignatory**, **proofOfDirector**, or **proofOfFundingOrWealthSource**. * For **individual**, the `type` values can be **identityCard**, **driversLicense**, **passport**, **liveSelfie**, **proofOfNationalIdNumber**, **proofOfResidency**, **proofOfIndustry**, **proofOfIndividualTaxId**, **proofOfFundingOrWealthSource** or **proofOfRelationship**. * For **soleProprietorship**, the `type` values can be **constitutionalDocument**, **proofOfAddress**, or **proofOfIndustry**. * For **trust**, the `type` value is **constitutionalDocument**. * For **unincorporatedPartnership**, the `type` value is **constitutionalDocument**. * Use **bankStatement** to upload documents for a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + /// attachment + /// Array that contains the document. The array supports multiple attachments for uploading different sides or pages of a document. + /// The creation date of the document. + /// The expiry date of the document, in YYYY-MM-DD format. + /// The filename of the document. + /// The unique identifier of the document. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + /// The state or province where the document was issued (AU only). + /// The modification date of the document. + /// The number in the document. + /// owner + [JsonConstructor] + public Document(string description, TypeEnum type, Option attachment = default, Option?> attachments = default, Option creationDate = default, Option expiryDate = default, Option fileName = default, Option id = default, Option issuerCountry = default, Option issuerState = default, Option modificationDate = default, Option number = default, Option owner = default) + { + Description = description; + Type = type; + _AttachmentOption = attachment; + _AttachmentsOption = attachments; + _CreationDateOption = creationDate; + _ExpiryDateOption = expiryDate; + _FileNameOption = fileName; + _IdOption = id; + _IssuerCountryOption = issuerCountry; + _IssuerStateOption = issuerState; + _ModificationDateOption = modificationDate; + _NumberOption = number; + _OwnerOption = owner; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Document() + { + } + + partial void OnCreated(); + + /// + /// Type of document, used when providing an ID number or uploading a document. The possible values depend on the legal entity type. * For **organization**, the `type` values can be **proofOfAddress**, **registrationDocument**, **vatDocument**, **proofOfOrganizationTaxInfo**, **proofOfOwnership**, **proofOfIndustry**, **proofOfSignatory**, **proofOfDirector**, or **proofOfFundingOrWealthSource**. * For **individual**, the `type` values can be **identityCard**, **driversLicense**, **passport**, **liveSelfie**, **proofOfNationalIdNumber**, **proofOfResidency**, **proofOfIndustry**, **proofOfIndividualTaxId**, **proofOfFundingOrWealthSource** or **proofOfRelationship**. * For **soleProprietorship**, the `type` values can be **constitutionalDocument**, **proofOfAddress**, or **proofOfIndustry**. * For **trust**, the `type` value is **constitutionalDocument**. * For **unincorporatedPartnership**, the `type` value is **constitutionalDocument**. * Use **bankStatement** to upload documents for a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + /// + /// Type of document, used when providing an ID number or uploading a document. The possible values depend on the legal entity type. * For **organization**, the `type` values can be **proofOfAddress**, **registrationDocument**, **vatDocument**, **proofOfOrganizationTaxInfo**, **proofOfOwnership**, **proofOfIndustry**, **proofOfSignatory**, **proofOfDirector**, or **proofOfFundingOrWealthSource**. * For **individual**, the `type` values can be **identityCard**, **driversLicense**, **passport**, **liveSelfie**, **proofOfNationalIdNumber**, **proofOfResidency**, **proofOfIndustry**, **proofOfIndividualTaxId**, **proofOfFundingOrWealthSource** or **proofOfRelationship**. * For **soleProprietorship**, the `type` values can be **constitutionalDocument**, **proofOfAddress**, or **proofOfIndustry**. * For **trust**, the `type` value is **constitutionalDocument**. * For **unincorporatedPartnership**, the `type` value is **constitutionalDocument**. * Use **bankStatement** to upload documents for a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankStatement - bankStatement + /// + public static readonly TypeEnum BankStatement = new("bankStatement"); + + /// + /// TypeEnum.DriversLicense - driversLicense + /// + public static readonly TypeEnum DriversLicense = new("driversLicense"); + + /// + /// TypeEnum.IdentityCard - identityCard + /// + public static readonly TypeEnum IdentityCard = new("identityCard"); + + /// + /// TypeEnum.NationalIdNumber - nationalIdNumber + /// + public static readonly TypeEnum NationalIdNumber = new("nationalIdNumber"); + + /// + /// TypeEnum.Passport - passport + /// + public static readonly TypeEnum Passport = new("passport"); + + /// + /// TypeEnum.ProofOfAddress - proofOfAddress + /// + public static readonly TypeEnum ProofOfAddress = new("proofOfAddress"); + + /// + /// TypeEnum.ProofOfNationalIdNumber - proofOfNationalIdNumber + /// + public static readonly TypeEnum ProofOfNationalIdNumber = new("proofOfNationalIdNumber"); + + /// + /// TypeEnum.ProofOfResidency - proofOfResidency + /// + public static readonly TypeEnum ProofOfResidency = new("proofOfResidency"); + + /// + /// TypeEnum.RegistrationDocument - registrationDocument + /// + public static readonly TypeEnum RegistrationDocument = new("registrationDocument"); + + /// + /// TypeEnum.VatDocument - vatDocument + /// + public static readonly TypeEnum VatDocument = new("vatDocument"); + + /// + /// TypeEnum.ProofOfOrganizationTaxInfo - proofOfOrganizationTaxInfo + /// + public static readonly TypeEnum ProofOfOrganizationTaxInfo = new("proofOfOrganizationTaxInfo"); + + /// + /// TypeEnum.ProofOfIndividualTaxId - proofOfIndividualTaxId + /// + public static readonly TypeEnum ProofOfIndividualTaxId = new("proofOfIndividualTaxId"); + + /// + /// TypeEnum.ProofOfOwnership - proofOfOwnership + /// + public static readonly TypeEnum ProofOfOwnership = new("proofOfOwnership"); + + /// + /// TypeEnum.ProofOfSignatory - proofOfSignatory + /// + public static readonly TypeEnum ProofOfSignatory = new("proofOfSignatory"); + + /// + /// TypeEnum.LiveSelfie - liveSelfie + /// + public static readonly TypeEnum LiveSelfie = new("liveSelfie"); + + /// + /// TypeEnum.ProofOfIndustry - proofOfIndustry + /// + public static readonly TypeEnum ProofOfIndustry = new("proofOfIndustry"); + + /// + /// TypeEnum.ConstitutionalDocument - constitutionalDocument + /// + public static readonly TypeEnum ConstitutionalDocument = new("constitutionalDocument"); + + /// + /// TypeEnum.ProofOfFundingOrWealthSource - proofOfFundingOrWealthSource + /// + public static readonly TypeEnum ProofOfFundingOrWealthSource = new("proofOfFundingOrWealthSource"); + + /// + /// TypeEnum.ProofOfRelationship - proofOfRelationship + /// + public static readonly TypeEnum ProofOfRelationship = new("proofOfRelationship"); + + /// + /// TypeEnum.ProofOfDirector - proofOfDirector + /// + public static readonly TypeEnum ProofOfDirector = new("proofOfDirector"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankStatement" => TypeEnum.BankStatement, + "driversLicense" => TypeEnum.DriversLicense, + "identityCard" => TypeEnum.IdentityCard, + "nationalIdNumber" => TypeEnum.NationalIdNumber, + "passport" => TypeEnum.Passport, + "proofOfAddress" => TypeEnum.ProofOfAddress, + "proofOfNationalIdNumber" => TypeEnum.ProofOfNationalIdNumber, + "proofOfResidency" => TypeEnum.ProofOfResidency, + "registrationDocument" => TypeEnum.RegistrationDocument, + "vatDocument" => TypeEnum.VatDocument, + "proofOfOrganizationTaxInfo" => TypeEnum.ProofOfOrganizationTaxInfo, + "proofOfIndividualTaxId" => TypeEnum.ProofOfIndividualTaxId, + "proofOfOwnership" => TypeEnum.ProofOfOwnership, + "proofOfSignatory" => TypeEnum.ProofOfSignatory, + "liveSelfie" => TypeEnum.LiveSelfie, + "proofOfIndustry" => TypeEnum.ProofOfIndustry, + "constitutionalDocument" => TypeEnum.ConstitutionalDocument, + "proofOfFundingOrWealthSource" => TypeEnum.ProofOfFundingOrWealthSource, + "proofOfRelationship" => TypeEnum.ProofOfRelationship, + "proofOfDirector" => TypeEnum.ProofOfDirector, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankStatement) + return "bankStatement"; + + if (value == TypeEnum.DriversLicense) + return "driversLicense"; + + if (value == TypeEnum.IdentityCard) + return "identityCard"; + + if (value == TypeEnum.NationalIdNumber) + return "nationalIdNumber"; + + if (value == TypeEnum.Passport) + return "passport"; + + if (value == TypeEnum.ProofOfAddress) + return "proofOfAddress"; + + if (value == TypeEnum.ProofOfNationalIdNumber) + return "proofOfNationalIdNumber"; + + if (value == TypeEnum.ProofOfResidency) + return "proofOfResidency"; + + if (value == TypeEnum.RegistrationDocument) + return "registrationDocument"; + + if (value == TypeEnum.VatDocument) + return "vatDocument"; + + if (value == TypeEnum.ProofOfOrganizationTaxInfo) + return "proofOfOrganizationTaxInfo"; + + if (value == TypeEnum.ProofOfIndividualTaxId) + return "proofOfIndividualTaxId"; + + if (value == TypeEnum.ProofOfOwnership) + return "proofOfOwnership"; + + if (value == TypeEnum.ProofOfSignatory) + return "proofOfSignatory"; + + if (value == TypeEnum.LiveSelfie) + return "liveSelfie"; + + if (value == TypeEnum.ProofOfIndustry) + return "proofOfIndustry"; + + if (value == TypeEnum.ConstitutionalDocument) + return "constitutionalDocument"; + + if (value == TypeEnum.ProofOfFundingOrWealthSource) + return "proofOfFundingOrWealthSource"; + + if (value == TypeEnum.ProofOfRelationship) + return "proofOfRelationship"; + + if (value == TypeEnum.ProofOfDirector) + return "proofOfDirector"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of document, used when providing an ID number or uploading a document. The possible values depend on the legal entity type. * For **organization**, the `type` values can be **proofOfAddress**, **registrationDocument**, **vatDocument**, **proofOfOrganizationTaxInfo**, **proofOfOwnership**, **proofOfIndustry**, **proofOfSignatory**, **proofOfDirector**, or **proofOfFundingOrWealthSource**. * For **individual**, the `type` values can be **identityCard**, **driversLicense**, **passport**, **liveSelfie**, **proofOfNationalIdNumber**, **proofOfResidency**, **proofOfIndustry**, **proofOfIndividualTaxId**, **proofOfFundingOrWealthSource** or **proofOfRelationship**. * For **soleProprietorship**, the `type` values can be **constitutionalDocument**, **proofOfAddress**, or **proofOfIndustry**. * For **trust**, the `type` value is **constitutionalDocument**. * For **unincorporatedPartnership**, the `type` value is **constitutionalDocument**. * Use **bankStatement** to upload documents for a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + /// + /// Type of document, used when providing an ID number or uploading a document. The possible values depend on the legal entity type. * For **organization**, the `type` values can be **proofOfAddress**, **registrationDocument**, **vatDocument**, **proofOfOrganizationTaxInfo**, **proofOfOwnership**, **proofOfIndustry**, **proofOfSignatory**, **proofOfDirector**, or **proofOfFundingOrWealthSource**. * For **individual**, the `type` values can be **identityCard**, **driversLicense**, **passport**, **liveSelfie**, **proofOfNationalIdNumber**, **proofOfResidency**, **proofOfIndustry**, **proofOfIndividualTaxId**, **proofOfFundingOrWealthSource** or **proofOfRelationship**. * For **soleProprietorship**, the `type` values can be **constitutionalDocument**, **proofOfAddress**, or **proofOfIndustry**. * For **trust**, the `type` value is **constitutionalDocument**. * For **unincorporatedPartnership**, the `type` value is **constitutionalDocument**. * Use **bankStatement** to upload documents for a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id). + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Your description for the document. + /// + /// Your description for the document. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AttachmentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("attachment")] + public Attachment? Attachment { get { return this._AttachmentOption; } set { this._AttachmentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AttachmentsOption { get; private set; } + + /// + /// Array that contains the document. The array supports multiple attachments for uploading different sides or pages of a document. + /// + /// Array that contains the document. The array supports multiple attachments for uploading different sides or pages of a document. + [JsonPropertyName("attachments")] + public List? Attachments { get { return this._AttachmentsOption; } set { this._AttachmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; } + + /// + /// The creation date of the document. + /// + /// The creation date of the document. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryDateOption { get; private set; } + + /// + /// The expiry date of the document, in YYYY-MM-DD format. + /// + /// The expiry date of the document, in YYYY-MM-DD format. + [JsonPropertyName("expiryDate")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? ExpiryDate { get { return this._ExpiryDateOption; } set { this._ExpiryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FileNameOption { get; private set; } + + /// + /// The filename of the document. + /// + /// The filename of the document. + [JsonPropertyName("fileName")] + public string? FileName { get { return this._FileNameOption; } set { this._FileNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// The unique identifier of the document. + /// + /// The unique identifier of the document. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + [JsonPropertyName("issuerCountry")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerStateOption { get; private set; } + + /// + /// The state or province where the document was issued (AU only). + /// + /// The state or province where the document was issued (AU only). + [JsonPropertyName("issuerState")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? IssuerState { get { return this._IssuerStateOption; } set { this._IssuerStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationDateOption { get; } + + /// + /// The modification date of the document. + /// + /// The modification date of the document. + [JsonPropertyName("modificationDate")] + public DateTimeOffset? ModificationDate { get { return this._ModificationDateOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The number in the document. + /// + /// The number in the document. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("owner")] + public OwnerEntity? Owner { get { return this._OwnerOption; } set { this._OwnerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Document {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Attachment: ").Append(Attachment).Append("\n"); + sb.Append(" Attachments: ").Append(Attachments).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" ExpiryDate: ").Append(ExpiryDate).Append("\n"); + sb.Append(" FileName: ").Append(FileName).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append(" IssuerState: ").Append(IssuerState).Append("\n"); + sb.Append(" ModificationDate: ").Append(ModificationDate).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Owner: ").Append(Owner).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DocumentJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ModificationDate. + /// + public static string ModificationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Document Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option type = default; + Option attachment = default; + Option?> attachments = default; + Option creationDate = default; + Option expiryDate = default; + Option fileName = default; + Option id = default; + Option issuerCountry = default; + Option issuerState = default; + Option modificationDate = default; + Option number = default; + Option owner = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Document.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "attachment": + attachment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "attachments": + attachments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "expiryDate": + expiryDate = new Option(utf8JsonReader.GetString()!); + break; + case "fileName": + fileName = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + case "issuerState": + issuerState = new Option(utf8JsonReader.GetString()!); + break; + case "modificationDate": + modificationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "owner": + owner = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!description.IsSet) + throw new ArgumentException("Property is required for class Document.", nameof(description)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Document.", nameof(type)); + + return new Document(description.Value!, type.Value!.Value!, attachment, attachments, creationDate, expiryDate, fileName, id, issuerCountry, issuerState, modificationDate, number, owner); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Document document, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, document, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Document document, JsonSerializerOptions jsonSerializerOptions) + { + + if (document.Description != null) + writer.WriteString("description", document.Description); + + if (document.Type != null) + { + string? typeRawValue = Document.TypeEnum.ToJsonValue(document.Type); + writer.WriteString("type", typeRawValue); + } + + if (document._AttachmentOption.IsSet) + { + writer.WritePropertyName("attachment"); + JsonSerializer.Serialize(writer, document.Attachment, jsonSerializerOptions); + } + if (document._AttachmentsOption.IsSet) + { + writer.WritePropertyName("attachments"); + JsonSerializer.Serialize(writer, document.Attachments, jsonSerializerOptions); + } + if (document._CreationDateOption.IsSet) + writer.WriteString("creationDate", document._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (document._ExpiryDateOption.IsSet) + if (document.ExpiryDate != null) + writer.WriteString("expiryDate", document.ExpiryDate); + + if (document._FileNameOption.IsSet) + if (document.FileName != null) + writer.WriteString("fileName", document.FileName); + + if (document._IdOption.IsSet) + if (document.Id != null) + writer.WriteString("id", document.Id); + + if (document._IssuerCountryOption.IsSet) + if (document.IssuerCountry != null) + writer.WriteString("issuerCountry", document.IssuerCountry); + + if (document._IssuerStateOption.IsSet) + if (document.IssuerState != null) + writer.WriteString("issuerState", document.IssuerState); + + if (document._ModificationDateOption.IsSet) + writer.WriteString("modificationDate", document._ModificationDateOption.Value!.Value.ToString(ModificationDateFormat)); + + if (document._NumberOption.IsSet) + if (document.Number != null) + writer.WriteString("number", document.Number); + + if (document._OwnerOption.IsSet) + { + writer.WritePropertyName("owner"); + JsonSerializer.Serialize(writer, document.Owner, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/DocumentPage.cs b/Adyen/LegalEntityManagement/Models/DocumentPage.cs new file mode 100644 index 000000000..7405b06df --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/DocumentPage.cs @@ -0,0 +1,337 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// DocumentPage. + /// + public partial class DocumentPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// pageName + /// pageNumber + /// type + [JsonConstructor] + public DocumentPage(Option pageName = default, Option pageNumber = default, Option type = default) + { + _PageNameOption = pageName; + _PageNumberOption = pageNumber; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DocumentPage() + { + } + + partial void OnCreated(); + + /// + /// Defines Type. + /// + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BACK - BACK + /// + public static readonly TypeEnum BACK = new("BACK"); + + /// + /// TypeEnum.FRONT - FRONT + /// + public static readonly TypeEnum FRONT = new("FRONT"); + + /// + /// TypeEnum.UNDEFINED - UNDEFINED + /// + public static readonly TypeEnum UNDEFINED = new("UNDEFINED"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BACK" => TypeEnum.BACK, + "FRONT" => TypeEnum.FRONT, + "UNDEFINED" => TypeEnum.UNDEFINED, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BACK) + return "BACK"; + + if (value == TypeEnum.FRONT) + return "FRONT"; + + if (value == TypeEnum.UNDEFINED) + return "UNDEFINED"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PageNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pageName")] + public string? PageName { get { return this._PageNameOption; } set { this._PageNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PageNumberOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pageNumber")] + public int? PageNumber { get { return this._PageNumberOption; } set { this._PageNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DocumentPage {\n"); + sb.Append(" PageName: ").Append(PageName).Append("\n"); + sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DocumentPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DocumentPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pageName = default; + Option pageNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pageName": + pageName = new Option(utf8JsonReader.GetString()!); + break; + case "pageNumber": + pageNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DocumentPage.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new DocumentPage(pageName, pageNumber, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DocumentPage documentPage, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, documentPage, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DocumentPage documentPage, JsonSerializerOptions jsonSerializerOptions) + { + + if (documentPage._PageNameOption.IsSet) + if (documentPage.PageName != null) + writer.WriteString("pageName", documentPage.PageName); + + if (documentPage._PageNumberOption.IsSet) + writer.WriteNumber("pageNumber", documentPage._PageNumberOption.Value!.Value); + + if (documentPage._TypeOption.IsSet && documentPage.Type != null) + { + string? typeRawValue = DocumentPage.TypeEnum.ToJsonValue(documentPage._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/DocumentReference.cs b/Adyen/LegalEntityManagement/Models/DocumentReference.cs new file mode 100644 index 000000000..552345b6b --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/DocumentReference.cs @@ -0,0 +1,331 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// DocumentReference. + /// + public partial class DocumentReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Identifies whether the document is active and used for checks. + /// Your description for the document. + /// Document name. + /// The unique identifier of the resource. + /// The modification date of the document. + /// List of document pages + /// Type of document, used when providing an ID number or uploading a document. + [JsonConstructor] + public DocumentReference(Option active = default, Option description = default, Option fileName = default, Option id = default, Option modificationDate = default, Option?> pages = default, Option type = default) + { + _ActiveOption = active; + _DescriptionOption = description; + _FileNameOption = fileName; + _IdOption = id; + _ModificationDateOption = modificationDate; + _PagesOption = pages; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DocumentReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Identifies whether the document is active and used for checks. + /// + /// Identifies whether the document is active and used for checks. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the document. + /// + /// Your description for the document. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FileNameOption { get; private set; } + + /// + /// Document name. + /// + /// Document name. + [JsonPropertyName("fileName")] + public string? FileName { get { return this._FileNameOption; } set { this._FileNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationDateOption { get; private set; } + + /// + /// The modification date of the document. + /// + /// The modification date of the document. + [JsonPropertyName("modificationDate")] + public DateTimeOffset? ModificationDate { get { return this._ModificationDateOption; } set { this._ModificationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PagesOption { get; private set; } + + /// + /// List of document pages + /// + /// List of document pages + [JsonPropertyName("pages")] + public List? Pages { get { return this._PagesOption; } set { this._PagesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of document, used when providing an ID number or uploading a document. + /// + /// Type of document, used when providing an ID number or uploading a document. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DocumentReference {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" FileName: ").Append(FileName).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" ModificationDate: ").Append(ModificationDate).Append("\n"); + sb.Append(" Pages: ").Append(Pages).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DocumentReferenceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ModificationDate. + /// + public static string ModificationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DocumentReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option description = default; + Option fileName = default; + Option id = default; + Option modificationDate = default; + Option?> pages = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "fileName": + fileName = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "modificationDate": + modificationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "pages": + pages = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DocumentReference(active, description, fileName, id, modificationDate, pages, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DocumentReference documentReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, documentReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DocumentReference documentReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (documentReference._ActiveOption.IsSet) + writer.WriteBoolean("active", documentReference._ActiveOption.Value!.Value); + + if (documentReference._DescriptionOption.IsSet) + if (documentReference.Description != null) + writer.WriteString("description", documentReference.Description); + + if (documentReference._FileNameOption.IsSet) + if (documentReference.FileName != null) + writer.WriteString("fileName", documentReference.FileName); + + if (documentReference._IdOption.IsSet) + if (documentReference.Id != null) + writer.WriteString("id", documentReference.Id); + + if (documentReference._ModificationDateOption.IsSet) + writer.WriteString("modificationDate", documentReference._ModificationDateOption.Value!.Value.ToString(ModificationDateFormat)); + + if (documentReference._PagesOption.IsSet) + { + writer.WritePropertyName("pages"); + JsonSerializer.Serialize(writer, documentReference.Pages, jsonSerializerOptions); + } + if (documentReference._TypeOption.IsSet) + if (documentReference.Type != null) + writer.WriteString("type", documentReference.Type); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/EntityReference.cs b/Adyen/LegalEntityManagement/Models/EntityReference.cs new file mode 100644 index 000000000..495cbd301 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/EntityReference.cs @@ -0,0 +1,177 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// EntityReference. + /// + public partial class EntityReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource. + [JsonConstructor] + public EntityReference(Option id = default) + { + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EntityReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EntityReference {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EntityReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EntityReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new EntityReference(id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EntityReference entityReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, entityReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EntityReference entityReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (entityReference._IdOption.IsSet) + if (entityReference.Id != null) + writer.WriteString("id", entityReference.Id); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/FinancialReport.cs b/Adyen/LegalEntityManagement/Models/FinancialReport.cs new file mode 100644 index 000000000..caa1179f5 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/FinancialReport.cs @@ -0,0 +1,302 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// FinancialReport. + /// + public partial class FinancialReport : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The annual turnover of the business. + /// The balance sheet total of the business. + /// The currency used for the annual turnover, balance sheet total, and net assets. + /// The date the financial data were provided, in YYYY-MM-DD format. + /// The number of employees of the business. + /// The net assets of the business. + [JsonConstructor] + public FinancialReport(Option annualTurnover = default, Option balanceSheetTotal = default, Option currencyOfFinancialData = default, Option dateOfFinancialData = default, Option employeeCount = default, Option netAssets = default) + { + _AnnualTurnoverOption = annualTurnover; + _BalanceSheetTotalOption = balanceSheetTotal; + _CurrencyOfFinancialDataOption = currencyOfFinancialData; + _DateOfFinancialDataOption = dateOfFinancialData; + _EmployeeCountOption = employeeCount; + _NetAssetsOption = netAssets; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FinancialReport() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AnnualTurnoverOption { get; private set; } + + /// + /// The annual turnover of the business. + /// + /// The annual turnover of the business. + [JsonPropertyName("annualTurnover")] + public string? AnnualTurnover { get { return this._AnnualTurnoverOption; } set { this._AnnualTurnoverOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceSheetTotalOption { get; private set; } + + /// + /// The balance sheet total of the business. + /// + /// The balance sheet total of the business. + [JsonPropertyName("balanceSheetTotal")] + public string? BalanceSheetTotal { get { return this._BalanceSheetTotalOption; } set { this._BalanceSheetTotalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOfFinancialDataOption { get; private set; } + + /// + /// The currency used for the annual turnover, balance sheet total, and net assets. + /// + /// The currency used for the annual turnover, balance sheet total, and net assets. + [JsonPropertyName("currencyOfFinancialData")] + public string? CurrencyOfFinancialData { get { return this._CurrencyOfFinancialDataOption; } set { this._CurrencyOfFinancialDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfFinancialDataOption { get; private set; } + + /// + /// The date the financial data were provided, in YYYY-MM-DD format. + /// + /// The date the financial data were provided, in YYYY-MM-DD format. + [JsonPropertyName("dateOfFinancialData")] + public string? DateOfFinancialData { get { return this._DateOfFinancialDataOption; } set { this._DateOfFinancialDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmployeeCountOption { get; private set; } + + /// + /// The number of employees of the business. + /// + /// The number of employees of the business. + [JsonPropertyName("employeeCount")] + public string? EmployeeCount { get { return this._EmployeeCountOption; } set { this._EmployeeCountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetAssetsOption { get; private set; } + + /// + /// The net assets of the business. + /// + /// The net assets of the business. + [JsonPropertyName("netAssets")] + public string? NetAssets { get { return this._NetAssetsOption; } set { this._NetAssetsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FinancialReport {\n"); + sb.Append(" AnnualTurnover: ").Append(AnnualTurnover).Append("\n"); + sb.Append(" BalanceSheetTotal: ").Append(BalanceSheetTotal).Append("\n"); + sb.Append(" CurrencyOfFinancialData: ").Append(CurrencyOfFinancialData).Append("\n"); + sb.Append(" DateOfFinancialData: ").Append(DateOfFinancialData).Append("\n"); + sb.Append(" EmployeeCount: ").Append(EmployeeCount).Append("\n"); + sb.Append(" NetAssets: ").Append(NetAssets).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FinancialReportJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FinancialReport Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option annualTurnover = default; + Option balanceSheetTotal = default; + Option currencyOfFinancialData = default; + Option dateOfFinancialData = default; + Option employeeCount = default; + Option netAssets = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "annualTurnover": + annualTurnover = new Option(utf8JsonReader.GetString()!); + break; + case "balanceSheetTotal": + balanceSheetTotal = new Option(utf8JsonReader.GetString()!); + break; + case "currencyOfFinancialData": + currencyOfFinancialData = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfFinancialData": + dateOfFinancialData = new Option(utf8JsonReader.GetString()!); + break; + case "employeeCount": + employeeCount = new Option(utf8JsonReader.GetString()!); + break; + case "netAssets": + netAssets = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new FinancialReport(annualTurnover, balanceSheetTotal, currencyOfFinancialData, dateOfFinancialData, employeeCount, netAssets); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FinancialReport financialReport, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, financialReport, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FinancialReport financialReport, JsonSerializerOptions jsonSerializerOptions) + { + + if (financialReport._AnnualTurnoverOption.IsSet) + if (financialReport.AnnualTurnover != null) + writer.WriteString("annualTurnover", financialReport.AnnualTurnover); + + if (financialReport._BalanceSheetTotalOption.IsSet) + if (financialReport.BalanceSheetTotal != null) + writer.WriteString("balanceSheetTotal", financialReport.BalanceSheetTotal); + + if (financialReport._CurrencyOfFinancialDataOption.IsSet) + if (financialReport.CurrencyOfFinancialData != null) + writer.WriteString("currencyOfFinancialData", financialReport.CurrencyOfFinancialData); + + if (financialReport._DateOfFinancialDataOption.IsSet) + if (financialReport.DateOfFinancialData != null) + writer.WriteString("dateOfFinancialData", financialReport.DateOfFinancialData); + + if (financialReport._EmployeeCountOption.IsSet) + if (financialReport.EmployeeCount != null) + writer.WriteString("employeeCount", financialReport.EmployeeCount); + + if (financialReport._NetAssetsOption.IsSet) + if (financialReport.NetAssets != null) + writer.WriteString("netAssets", financialReport.NetAssets); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Financier.cs b/Adyen/LegalEntityManagement/Models/Financier.cs new file mode 100644 index 000000000..3bacd53c2 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Financier.cs @@ -0,0 +1,229 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Financier. + /// + public partial class Financier : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The financier's first name. + /// The financier's last name. + /// The city and country/region where the financier is currently located. For example: Chicago, USA + [JsonConstructor] + public Financier(Amount amount, string firstName, string lastName, string location) + { + Amount = amount; + FirstName = firstName; + LastName = lastName; + Location = location; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Financier() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The financier's first name. + /// + /// The financier's first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The financier's last name. + /// + /// The financier's last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// The city and country/region where the financier is currently located. For example: Chicago, USA + /// + /// The city and country/region where the financier is currently located. For example: Chicago, USA + [JsonPropertyName("location")] + public string Location { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Financier {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FinancierJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Financier Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option firstName = default; + Option lastName = default; + Option location = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "location": + location = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Financier.", nameof(amount)); + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Financier.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Financier.", nameof(lastName)); + + if (!location.IsSet) + throw new ArgumentException("Property is required for class Financier.", nameof(location)); + + return new Financier(amount.Value!, firstName.Value!, lastName.Value!, location.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Financier financier, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, financier, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Financier financier, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, financier.Amount, jsonSerializerOptions); + if (financier.FirstName != null) + writer.WriteString("firstName", financier.FirstName); + + if (financier.LastName != null) + writer.WriteString("lastName", financier.LastName); + + if (financier.Location != null) + writer.WriteString("location", financier.Location); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionRequest.cs b/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionRequest.cs new file mode 100644 index 000000000..cd6e19cc2 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionRequest.cs @@ -0,0 +1,323 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GeneratePciDescriptionRequest. + /// + public partial class GeneratePciDescriptionRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + /// Sets the language of the PCI questionnaire. Its value is a two-character [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) language code, for example, **en**. + [JsonConstructor] + public GeneratePciDescriptionRequest(Option?> additionalSalesChannels = default, Option language = default) + { + _AdditionalSalesChannelsOption = additionalSalesChannels; + _LanguageOption = language; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GeneratePciDescriptionRequest() + { + } + + partial void OnCreated(); + + /// + /// Defines AdditionalSalesChannels. + /// + [JsonConverter(typeof(AdditionalSalesChannelsEnumJsonConverter))] + public class AdditionalSalesChannelsEnum : IEnum + { + /// + /// Returns the value of the AdditionalSalesChannelsEnum. + /// + public string? Value { get; set; } + + /// + /// AdditionalSalesChannelsEnum.ECommerce - eCommerce + /// + public static readonly AdditionalSalesChannelsEnum ECommerce = new("eCommerce"); + + /// + /// AdditionalSalesChannelsEnum.EcomMoto - ecomMoto + /// + public static readonly AdditionalSalesChannelsEnum EcomMoto = new("ecomMoto"); + + /// + /// AdditionalSalesChannelsEnum.Pos - pos + /// + public static readonly AdditionalSalesChannelsEnum Pos = new("pos"); + + /// + /// AdditionalSalesChannelsEnum.PosMoto - posMoto + /// + public static readonly AdditionalSalesChannelsEnum PosMoto = new("posMoto"); + + private AdditionalSalesChannelsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdditionalSalesChannelsEnum?(string? value) => value == null ? null : new AdditionalSalesChannelsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdditionalSalesChannelsEnum? option) => option?.Value; + + public static bool operator ==(AdditionalSalesChannelsEnum? left, AdditionalSalesChannelsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdditionalSalesChannelsEnum? left, AdditionalSalesChannelsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdditionalSalesChannelsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdditionalSalesChannelsEnum? FromStringOrDefault(string value) + { + return value switch { + "eCommerce" => AdditionalSalesChannelsEnum.ECommerce, + "ecomMoto" => AdditionalSalesChannelsEnum.EcomMoto, + "pos" => AdditionalSalesChannelsEnum.Pos, + "posMoto" => AdditionalSalesChannelsEnum.PosMoto, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdditionalSalesChannelsEnum? value) + { + if (value == null) + return null; + + if (value == AdditionalSalesChannelsEnum.ECommerce) + return "eCommerce"; + + if (value == AdditionalSalesChannelsEnum.EcomMoto) + return "ecomMoto"; + + if (value == AdditionalSalesChannelsEnum.Pos) + return "pos"; + + if (value == AdditionalSalesChannelsEnum.PosMoto) + return "posMoto"; + + return null; + } + + /// + /// JsonConverter for writing AdditionalSalesChannelsEnum. + /// + public class AdditionalSalesChannelsEnumJsonConverter : JsonConverter + { + public override AdditionalSalesChannelsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdditionalSalesChannelsEnum.FromStringOrDefault(value) ?? new AdditionalSalesChannelsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdditionalSalesChannelsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdditionalSalesChannelsEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalSalesChannelsOption { get; private set; } + + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + /// + /// An array of additional sales channels to generate PCI questionnaires. Include the relevant sales channels if you need your user to sign PCI questionnaires. Not required if you [create stores](https://docs.adyen.com/platforms) and [add payment methods](https://docs.adyen.com/adyen-for-platforms-model) before you generate the questionnaires. Possible values: * **eCommerce** * **pos** * **ecomMoto** * **posMoto** + [JsonPropertyName("additionalSalesChannels")] + public List? AdditionalSalesChannels { get { return this._AdditionalSalesChannelsOption; } set { this._AdditionalSalesChannelsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// Sets the language of the PCI questionnaire. Its value is a two-character [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) language code, for example, **en**. + /// + /// Sets the language of the PCI questionnaire. Its value is a two-character [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) language code, for example, **en**. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GeneratePciDescriptionRequest {\n"); + sb.Append(" AdditionalSalesChannels: ").Append(AdditionalSalesChannels).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GeneratePciDescriptionRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GeneratePciDescriptionRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalSalesChannels = default; + Option language = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalSalesChannels": + additionalSalesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new GeneratePciDescriptionRequest(additionalSalesChannels, language); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GeneratePciDescriptionRequest generatePciDescriptionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, generatePciDescriptionRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GeneratePciDescriptionRequest generatePciDescriptionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (generatePciDescriptionRequest._AdditionalSalesChannelsOption.IsSet) + { + writer.WritePropertyName("additionalSalesChannels"); + JsonSerializer.Serialize(writer, generatePciDescriptionRequest.AdditionalSalesChannels, jsonSerializerOptions); + } + if (generatePciDescriptionRequest._LanguageOption.IsSet) + if (generatePciDescriptionRequest.Language != null) + writer.WriteString("language", generatePciDescriptionRequest.Language); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionResponse.cs b/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionResponse.cs new file mode 100644 index 000000000..e1e4b0e07 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GeneratePciDescriptionResponse.cs @@ -0,0 +1,230 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GeneratePciDescriptionResponse. + /// + public partial class GeneratePciDescriptionResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The generated questionnaires in a base64 encoded format. + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code for the questionnaire. For example, **en**. + /// The array of Adyen-generated unique identifiers for the questionnaires. If empty, the user is not required to sign questionnaires. + [JsonConstructor] + public GeneratePciDescriptionResponse(Option content = default, Option language = default, Option?> pciTemplateReferences = default) + { + _ContentOption = content; + _LanguageOption = language; + _PciTemplateReferencesOption = pciTemplateReferences; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GeneratePciDescriptionResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContentOption { get; private set; } + + /// + /// The generated questionnaires in a base64 encoded format. + /// + /// The generated questionnaires in a base64 encoded format. + [JsonPropertyName("content")] + public byte[]? Content { get { return this._ContentOption; } set { this._ContentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code for the questionnaire. For example, **en**. + /// + /// The two-letter [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code for the questionnaire. For example, **en**. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PciTemplateReferencesOption { get; private set; } + + /// + /// The array of Adyen-generated unique identifiers for the questionnaires. If empty, the user is not required to sign questionnaires. + /// + /// The array of Adyen-generated unique identifiers for the questionnaires. If empty, the user is not required to sign questionnaires. + [JsonPropertyName("pciTemplateReferences")] + public List? PciTemplateReferences { get { return this._PciTemplateReferencesOption; } set { this._PciTemplateReferencesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GeneratePciDescriptionResponse {\n"); + sb.Append(" Content: ").Append(Content).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" PciTemplateReferences: ").Append(PciTemplateReferences).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GeneratePciDescriptionResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GeneratePciDescriptionResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option content = default; + Option language = default; + Option?> pciTemplateReferences = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "content": + content = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "pciTemplateReferences": + pciTemplateReferences = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new GeneratePciDescriptionResponse(content, language, pciTemplateReferences); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GeneratePciDescriptionResponse generatePciDescriptionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, generatePciDescriptionResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GeneratePciDescriptionResponse generatePciDescriptionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (generatePciDescriptionResponse._ContentOption.IsSet) + { + writer.WritePropertyName("content"); + JsonSerializer.Serialize(writer, generatePciDescriptionResponse.Content, jsonSerializerOptions); + } + if (generatePciDescriptionResponse._LanguageOption.IsSet) + if (generatePciDescriptionResponse.Language != null) + writer.WriteString("language", generatePciDescriptionResponse.Language); + + if (generatePciDescriptionResponse._PciTemplateReferencesOption.IsSet) + { + writer.WritePropertyName("pciTemplateReferences"); + JsonSerializer.Serialize(writer, generatePciDescriptionResponse.PciTemplateReferences, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetAcceptedTermsOfServiceDocumentResponse.cs b/Adyen/LegalEntityManagement/Models/GetAcceptedTermsOfServiceDocumentResponse.cs new file mode 100644 index 000000000..cb6e140fd --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetAcceptedTermsOfServiceDocumentResponse.cs @@ -0,0 +1,368 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetAcceptedTermsOfServiceDocumentResponse. + /// + public partial class GetAcceptedTermsOfServiceDocumentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The accepted Terms of Service document in the requested format represented as a Base64-encoded bytes array. + /// The unique identifier of the legal entity. + /// An Adyen-generated reference for the accepted Terms of Service. + /// The format of the Terms of Service document. + [JsonConstructor] + public GetAcceptedTermsOfServiceDocumentResponse(Option document = default, Option id = default, Option termsOfServiceAcceptanceReference = default, Option termsOfServiceDocumentFormat = default) + { + _DocumentOption = document; + _IdOption = id; + _TermsOfServiceAcceptanceReferenceOption = termsOfServiceAcceptanceReference; + _TermsOfServiceDocumentFormatOption = termsOfServiceDocumentFormat; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetAcceptedTermsOfServiceDocumentResponse() + { + } + + partial void OnCreated(); + + /// + /// The format of the Terms of Service document. + /// + /// The format of the Terms of Service document. + [JsonConverter(typeof(TermsOfServiceDocumentFormatEnumJsonConverter))] + public class TermsOfServiceDocumentFormatEnum : IEnum + { + /// + /// Returns the value of the TermsOfServiceDocumentFormatEnum. + /// + public string? Value { get; set; } + + /// + /// TermsOfServiceDocumentFormatEnum.JSON - JSON + /// + public static readonly TermsOfServiceDocumentFormatEnum JSON = new("JSON"); + + /// + /// TermsOfServiceDocumentFormatEnum.PDF - PDF + /// + public static readonly TermsOfServiceDocumentFormatEnum PDF = new("PDF"); + + /// + /// TermsOfServiceDocumentFormatEnum.TXT - TXT + /// + public static readonly TermsOfServiceDocumentFormatEnum TXT = new("TXT"); + + private TermsOfServiceDocumentFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TermsOfServiceDocumentFormatEnum?(string? value) => value == null ? null : new TermsOfServiceDocumentFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TermsOfServiceDocumentFormatEnum? option) => option?.Value; + + public static bool operator ==(TermsOfServiceDocumentFormatEnum? left, TermsOfServiceDocumentFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TermsOfServiceDocumentFormatEnum? left, TermsOfServiceDocumentFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TermsOfServiceDocumentFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TermsOfServiceDocumentFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "JSON" => TermsOfServiceDocumentFormatEnum.JSON, + "PDF" => TermsOfServiceDocumentFormatEnum.PDF, + "TXT" => TermsOfServiceDocumentFormatEnum.TXT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TermsOfServiceDocumentFormatEnum? value) + { + if (value == null) + return null; + + if (value == TermsOfServiceDocumentFormatEnum.JSON) + return "JSON"; + + if (value == TermsOfServiceDocumentFormatEnum.PDF) + return "PDF"; + + if (value == TermsOfServiceDocumentFormatEnum.TXT) + return "TXT"; + + return null; + } + + /// + /// JsonConverter for writing TermsOfServiceDocumentFormatEnum. + /// + public class TermsOfServiceDocumentFormatEnumJsonConverter : JsonConverter + { + public override TermsOfServiceDocumentFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TermsOfServiceDocumentFormatEnum.FromStringOrDefault(value) ?? new TermsOfServiceDocumentFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TermsOfServiceDocumentFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TermsOfServiceDocumentFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceDocumentFormatOption { get; private set; } + + /// + /// The format of the Terms of Service document. + /// + /// The format of the Terms of Service document. + [JsonPropertyName("termsOfServiceDocumentFormat")] + public TermsOfServiceDocumentFormatEnum? TermsOfServiceDocumentFormat { get { return this._TermsOfServiceDocumentFormatOption; } set { this._TermsOfServiceDocumentFormatOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DocumentOption { get; private set; } + + /// + /// The accepted Terms of Service document in the requested format represented as a Base64-encoded bytes array. + /// + /// The accepted Terms of Service document in the requested format represented as a Base64-encoded bytes array. + [JsonPropertyName("document")] + public byte[]? Document { get { return this._DocumentOption; } set { this._DocumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the legal entity. + /// + /// The unique identifier of the legal entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceAcceptanceReferenceOption { get; private set; } + + /// + /// An Adyen-generated reference for the accepted Terms of Service. + /// + /// An Adyen-generated reference for the accepted Terms of Service. + [JsonPropertyName("termsOfServiceAcceptanceReference")] + public string? TermsOfServiceAcceptanceReference { get { return this._TermsOfServiceAcceptanceReferenceOption; } set { this._TermsOfServiceAcceptanceReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetAcceptedTermsOfServiceDocumentResponse {\n"); + sb.Append(" Document: ").Append(Document).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" TermsOfServiceAcceptanceReference: ").Append(TermsOfServiceAcceptanceReference).Append("\n"); + sb.Append(" TermsOfServiceDocumentFormat: ").Append(TermsOfServiceDocumentFormat).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetAcceptedTermsOfServiceDocumentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetAcceptedTermsOfServiceDocumentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option document = default; + Option id = default; + Option termsOfServiceAcceptanceReference = default; + Option termsOfServiceDocumentFormat = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "document": + document = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "termsOfServiceAcceptanceReference": + termsOfServiceAcceptanceReference = new Option(utf8JsonReader.GetString()!); + break; + case "termsOfServiceDocumentFormat": + string? termsOfServiceDocumentFormatRawValue = utf8JsonReader.GetString(); + termsOfServiceDocumentFormat = new Option(GetAcceptedTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormatEnum.FromStringOrDefault(termsOfServiceDocumentFormatRawValue)); + break; + default: + break; + } + } + } + + + return new GetAcceptedTermsOfServiceDocumentResponse(document, id, termsOfServiceAcceptanceReference, termsOfServiceDocumentFormat); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetAcceptedTermsOfServiceDocumentResponse getAcceptedTermsOfServiceDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getAcceptedTermsOfServiceDocumentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetAcceptedTermsOfServiceDocumentResponse getAcceptedTermsOfServiceDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (getAcceptedTermsOfServiceDocumentResponse._DocumentOption.IsSet) + { + writer.WritePropertyName("document"); + JsonSerializer.Serialize(writer, getAcceptedTermsOfServiceDocumentResponse.Document, jsonSerializerOptions); + } + if (getAcceptedTermsOfServiceDocumentResponse._IdOption.IsSet) + if (getAcceptedTermsOfServiceDocumentResponse.Id != null) + writer.WriteString("id", getAcceptedTermsOfServiceDocumentResponse.Id); + + if (getAcceptedTermsOfServiceDocumentResponse._TermsOfServiceAcceptanceReferenceOption.IsSet) + if (getAcceptedTermsOfServiceDocumentResponse.TermsOfServiceAcceptanceReference != null) + writer.WriteString("termsOfServiceAcceptanceReference", getAcceptedTermsOfServiceDocumentResponse.TermsOfServiceAcceptanceReference); + + if (getAcceptedTermsOfServiceDocumentResponse._TermsOfServiceDocumentFormatOption.IsSet && getAcceptedTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormat != null) + { + string? termsOfServiceDocumentFormatRawValue = GetAcceptedTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormatEnum.ToJsonValue(getAcceptedTermsOfServiceDocumentResponse._TermsOfServiceDocumentFormatOption.Value!.Value); + writer.WriteString("termsOfServiceDocumentFormat", termsOfServiceDocumentFormatRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireInfosResponse.cs b/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireInfosResponse.cs new file mode 100644 index 000000000..f966f75f8 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireInfosResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetPciQuestionnaireInfosResponse. + /// + public partial class GetPciQuestionnaireInfosResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Information about the signed PCI questionnaires. + [JsonConstructor] + public GetPciQuestionnaireInfosResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetPciQuestionnaireInfosResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Information about the signed PCI questionnaires. + /// + /// Information about the signed PCI questionnaires. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetPciQuestionnaireInfosResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetPciQuestionnaireInfosResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetPciQuestionnaireInfosResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new GetPciQuestionnaireInfosResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetPciQuestionnaireInfosResponse getPciQuestionnaireInfosResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getPciQuestionnaireInfosResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetPciQuestionnaireInfosResponse getPciQuestionnaireInfosResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (getPciQuestionnaireInfosResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, getPciQuestionnaireInfosResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireResponse.cs b/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireResponse.cs new file mode 100644 index 000000000..490afdc61 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetPciQuestionnaireResponse.cs @@ -0,0 +1,261 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetPciQuestionnaireResponse. + /// + public partial class GetPciQuestionnaireResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The generated questionnaire in a base64 encoded format. + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// The unique identifier of the signed questionnaire. + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonConstructor] + public GetPciQuestionnaireResponse(Option content = default, Option createdAt = default, Option id = default, Option validUntil = default) + { + _ContentOption = content; + _CreatedAtOption = createdAt; + _IdOption = id; + _ValidUntilOption = validUntil; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetPciQuestionnaireResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContentOption { get; private set; } + + /// + /// The generated questionnaire in a base64 encoded format. + /// + /// The generated questionnaire in a base64 encoded format. + [JsonPropertyName("content")] + public byte[]? Content { get { return this._ContentOption; } set { this._ContentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the signed questionnaire. + /// + /// The unique identifier of the signed questionnaire. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValidUntilOption { get; private set; } + + /// + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonPropertyName("validUntil")] + public DateTimeOffset? ValidUntil { get { return this._ValidUntilOption; } set { this._ValidUntilOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetPciQuestionnaireResponse {\n"); + sb.Append(" Content: ").Append(Content).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" ValidUntil: ").Append(ValidUntil).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetPciQuestionnaireResponseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValidUntil. + /// + public static string ValidUntilFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetPciQuestionnaireResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option content = default; + Option createdAt = default; + Option id = default; + Option validUntil = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "content": + content = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "validUntil": + validUntil = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new GetPciQuestionnaireResponse(content, createdAt, id, validUntil); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetPciQuestionnaireResponse getPciQuestionnaireResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getPciQuestionnaireResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetPciQuestionnaireResponse getPciQuestionnaireResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (getPciQuestionnaireResponse._ContentOption.IsSet) + { + writer.WritePropertyName("content"); + JsonSerializer.Serialize(writer, getPciQuestionnaireResponse.Content, jsonSerializerOptions); + } + if (getPciQuestionnaireResponse._CreatedAtOption.IsSet) + writer.WriteString("createdAt", getPciQuestionnaireResponse._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (getPciQuestionnaireResponse._IdOption.IsSet) + if (getPciQuestionnaireResponse.Id != null) + writer.WriteString("id", getPciQuestionnaireResponse.Id); + + if (getPciQuestionnaireResponse._ValidUntilOption.IsSet) + writer.WriteString("validUntil", getPciQuestionnaireResponse._ValidUntilOption.Value!.Value.ToString(ValidUntilFormat)); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetTermsOfServiceAcceptanceInfosResponse.cs b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceAcceptanceInfosResponse.cs new file mode 100644 index 000000000..825467a40 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceAcceptanceInfosResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetTermsOfServiceAcceptanceInfosResponse. + /// + public partial class GetTermsOfServiceAcceptanceInfosResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Terms of Service acceptance information. + [JsonConstructor] + public GetTermsOfServiceAcceptanceInfosResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetTermsOfServiceAcceptanceInfosResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The Terms of Service acceptance information. + /// + /// The Terms of Service acceptance information. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetTermsOfServiceAcceptanceInfosResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetTermsOfServiceAcceptanceInfosResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetTermsOfServiceAcceptanceInfosResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new GetTermsOfServiceAcceptanceInfosResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetTermsOfServiceAcceptanceInfosResponse getTermsOfServiceAcceptanceInfosResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getTermsOfServiceAcceptanceInfosResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetTermsOfServiceAcceptanceInfosResponse getTermsOfServiceAcceptanceInfosResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (getTermsOfServiceAcceptanceInfosResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, getTermsOfServiceAcceptanceInfosResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentRequest.cs b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentRequest.cs new file mode 100644 index 000000000..a9e0a5634 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentRequest.cs @@ -0,0 +1,395 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetTermsOfServiceDocumentRequest. + /// + public partial class GetTermsOfServiceDocumentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The language to be used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English. + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// The requested format for the Terms of Service document. Default value: JSON. Possible values: **JSON**, **PDF**, or **TXT**. + [JsonConstructor] + public GetTermsOfServiceDocumentRequest(string language, TypeEnum type, Option termsOfServiceDocumentFormat = default) + { + Language = language; + Type = type; + _TermsOfServiceDocumentFormatOption = termsOfServiceDocumentFormat; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetTermsOfServiceDocumentRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AdyenAccount - adyenAccount + /// + public static readonly TypeEnum AdyenAccount = new("adyenAccount"); + + /// + /// TypeEnum.AdyenCapital - adyenCapital + /// + public static readonly TypeEnum AdyenCapital = new("adyenCapital"); + + /// + /// TypeEnum.AdyenCard - adyenCard + /// + public static readonly TypeEnum AdyenCard = new("adyenCard"); + + /// + /// TypeEnum.AdyenChargeCard - adyenChargeCard + /// + public static readonly TypeEnum AdyenChargeCard = new("adyenChargeCard"); + + /// + /// TypeEnum.AdyenForPlatformsAdvanced - adyenForPlatformsAdvanced + /// + public static readonly TypeEnum AdyenForPlatformsAdvanced = new("adyenForPlatformsAdvanced"); + + /// + /// TypeEnum.AdyenForPlatformsManage - adyenForPlatformsManage + /// + public static readonly TypeEnum AdyenForPlatformsManage = new("adyenForPlatformsManage"); + + /// + /// TypeEnum.AdyenFranchisee - adyenFranchisee + /// + public static readonly TypeEnum AdyenFranchisee = new("adyenFranchisee"); + + /// + /// TypeEnum.AdyenIssuing - adyenIssuing + /// + public static readonly TypeEnum AdyenIssuing = new("adyenIssuing"); + + /// + /// TypeEnum.AdyenPccr - adyenPccr + /// + public static readonly TypeEnum AdyenPccr = new("adyenPccr"); + + /// + /// TypeEnum.KycOnInvite - kycOnInvite + /// + public static readonly TypeEnum KycOnInvite = new("kycOnInvite"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "adyenAccount" => TypeEnum.AdyenAccount, + "adyenCapital" => TypeEnum.AdyenCapital, + "adyenCard" => TypeEnum.AdyenCard, + "adyenChargeCard" => TypeEnum.AdyenChargeCard, + "adyenForPlatformsAdvanced" => TypeEnum.AdyenForPlatformsAdvanced, + "adyenForPlatformsManage" => TypeEnum.AdyenForPlatformsManage, + "adyenFranchisee" => TypeEnum.AdyenFranchisee, + "adyenIssuing" => TypeEnum.AdyenIssuing, + "adyenPccr" => TypeEnum.AdyenPccr, + "kycOnInvite" => TypeEnum.KycOnInvite, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AdyenAccount) + return "adyenAccount"; + + if (value == TypeEnum.AdyenCapital) + return "adyenCapital"; + + if (value == TypeEnum.AdyenCard) + return "adyenCard"; + + if (value == TypeEnum.AdyenChargeCard) + return "adyenChargeCard"; + + if (value == TypeEnum.AdyenForPlatformsAdvanced) + return "adyenForPlatformsAdvanced"; + + if (value == TypeEnum.AdyenForPlatformsManage) + return "adyenForPlatformsManage"; + + if (value == TypeEnum.AdyenFranchisee) + return "adyenFranchisee"; + + if (value == TypeEnum.AdyenIssuing) + return "adyenIssuing"; + + if (value == TypeEnum.AdyenPccr) + return "adyenPccr"; + + if (value == TypeEnum.KycOnInvite) + return "kycOnInvite"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The language to be used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English. + /// + /// The language to be used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English. + [JsonPropertyName("language")] + public string Language { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceDocumentFormatOption { get; private set; } + + /// + /// The requested format for the Terms of Service document. Default value: JSON. Possible values: **JSON**, **PDF**, or **TXT**. + /// + /// The requested format for the Terms of Service document. Default value: JSON. Possible values: **JSON**, **PDF**, or **TXT**. + [JsonPropertyName("termsOfServiceDocumentFormat")] + public string? TermsOfServiceDocumentFormat { get { return this._TermsOfServiceDocumentFormatOption; } set { this._TermsOfServiceDocumentFormatOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetTermsOfServiceDocumentRequest {\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" TermsOfServiceDocumentFormat: ").Append(TermsOfServiceDocumentFormat).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetTermsOfServiceDocumentRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetTermsOfServiceDocumentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option language = default; + Option type = default; + Option termsOfServiceDocumentFormat = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(GetTermsOfServiceDocumentRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "termsOfServiceDocumentFormat": + termsOfServiceDocumentFormat = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!language.IsSet) + throw new ArgumentException("Property is required for class GetTermsOfServiceDocumentRequest.", nameof(language)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class GetTermsOfServiceDocumentRequest.", nameof(type)); + + return new GetTermsOfServiceDocumentRequest(language.Value!, type.Value!.Value!, termsOfServiceDocumentFormat); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetTermsOfServiceDocumentRequest getTermsOfServiceDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getTermsOfServiceDocumentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetTermsOfServiceDocumentRequest getTermsOfServiceDocumentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (getTermsOfServiceDocumentRequest.Language != null) + writer.WriteString("language", getTermsOfServiceDocumentRequest.Language); + + if (getTermsOfServiceDocumentRequest.Type != null) + { + string? typeRawValue = GetTermsOfServiceDocumentRequest.TypeEnum.ToJsonValue(getTermsOfServiceDocumentRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (getTermsOfServiceDocumentRequest._TermsOfServiceDocumentFormatOption.IsSet) + if (getTermsOfServiceDocumentRequest.TermsOfServiceDocumentFormat != null) + writer.WriteString("termsOfServiceDocumentFormat", getTermsOfServiceDocumentRequest.TermsOfServiceDocumentFormat); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentResponse.cs b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentResponse.cs new file mode 100644 index 000000000..b6a2a3a60 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/GetTermsOfServiceDocumentResponse.cs @@ -0,0 +1,481 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// GetTermsOfServiceDocumentResponse. + /// + public partial class GetTermsOfServiceDocumentResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Terms of Service document in Base64-encoded format. + /// The unique identifier of the legal entity. + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + /// The format of the Terms of Service document. + /// The unique identifier of the Terms of Service document. + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConstructor] + public GetTermsOfServiceDocumentResponse(Option document = default, Option id = default, Option language = default, Option termsOfServiceDocumentFormat = default, Option termsOfServiceDocumentId = default, Option type = default) + { + _DocumentOption = document; + _IdOption = id; + _LanguageOption = language; + _TermsOfServiceDocumentFormatOption = termsOfServiceDocumentFormat; + _TermsOfServiceDocumentIdOption = termsOfServiceDocumentId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GetTermsOfServiceDocumentResponse() + { + } + + partial void OnCreated(); + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AdyenAccount - adyenAccount + /// + public static readonly TypeEnum AdyenAccount = new("adyenAccount"); + + /// + /// TypeEnum.AdyenCapital - adyenCapital + /// + public static readonly TypeEnum AdyenCapital = new("adyenCapital"); + + /// + /// TypeEnum.AdyenCard - adyenCard + /// + public static readonly TypeEnum AdyenCard = new("adyenCard"); + + /// + /// TypeEnum.AdyenChargeCard - adyenChargeCard + /// + public static readonly TypeEnum AdyenChargeCard = new("adyenChargeCard"); + + /// + /// TypeEnum.AdyenForPlatformsAdvanced - adyenForPlatformsAdvanced + /// + public static readonly TypeEnum AdyenForPlatformsAdvanced = new("adyenForPlatformsAdvanced"); + + /// + /// TypeEnum.AdyenForPlatformsManage - adyenForPlatformsManage + /// + public static readonly TypeEnum AdyenForPlatformsManage = new("adyenForPlatformsManage"); + + /// + /// TypeEnum.AdyenFranchisee - adyenFranchisee + /// + public static readonly TypeEnum AdyenFranchisee = new("adyenFranchisee"); + + /// + /// TypeEnum.AdyenIssuing - adyenIssuing + /// + public static readonly TypeEnum AdyenIssuing = new("adyenIssuing"); + + /// + /// TypeEnum.AdyenPccr - adyenPccr + /// + public static readonly TypeEnum AdyenPccr = new("adyenPccr"); + + /// + /// TypeEnum.KycOnInvite - kycOnInvite + /// + public static readonly TypeEnum KycOnInvite = new("kycOnInvite"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "adyenAccount" => TypeEnum.AdyenAccount, + "adyenCapital" => TypeEnum.AdyenCapital, + "adyenCard" => TypeEnum.AdyenCard, + "adyenChargeCard" => TypeEnum.AdyenChargeCard, + "adyenForPlatformsAdvanced" => TypeEnum.AdyenForPlatformsAdvanced, + "adyenForPlatformsManage" => TypeEnum.AdyenForPlatformsManage, + "adyenFranchisee" => TypeEnum.AdyenFranchisee, + "adyenIssuing" => TypeEnum.AdyenIssuing, + "adyenPccr" => TypeEnum.AdyenPccr, + "kycOnInvite" => TypeEnum.KycOnInvite, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AdyenAccount) + return "adyenAccount"; + + if (value == TypeEnum.AdyenCapital) + return "adyenCapital"; + + if (value == TypeEnum.AdyenCard) + return "adyenCard"; + + if (value == TypeEnum.AdyenChargeCard) + return "adyenChargeCard"; + + if (value == TypeEnum.AdyenForPlatformsAdvanced) + return "adyenForPlatformsAdvanced"; + + if (value == TypeEnum.AdyenForPlatformsManage) + return "adyenForPlatformsManage"; + + if (value == TypeEnum.AdyenFranchisee) + return "adyenFranchisee"; + + if (value == TypeEnum.AdyenIssuing) + return "adyenIssuing"; + + if (value == TypeEnum.AdyenPccr) + return "adyenPccr"; + + if (value == TypeEnum.KycOnInvite) + return "kycOnInvite"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DocumentOption { get; private set; } + + /// + /// The Terms of Service document in Base64-encoded format. + /// + /// The Terms of Service document in Base64-encoded format. + [JsonPropertyName("document")] + public byte[]? Document { get { return this._DocumentOption; } set { this._DocumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the legal entity. + /// + /// The unique identifier of the legal entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + /// + /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English or **fr** for French. Note that French is only available for some integration types in certain countries/regions. Reach out to your Adyen contact for more information. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceDocumentFormatOption { get; private set; } + + /// + /// The format of the Terms of Service document. + /// + /// The format of the Terms of Service document. + [JsonPropertyName("termsOfServiceDocumentFormat")] + public string? TermsOfServiceDocumentFormat { get { return this._TermsOfServiceDocumentFormatOption; } set { this._TermsOfServiceDocumentFormatOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermsOfServiceDocumentIdOption { get; private set; } + + /// + /// The unique identifier of the Terms of Service document. + /// + /// The unique identifier of the Terms of Service document. + [JsonPropertyName("termsOfServiceDocumentId")] + public string? TermsOfServiceDocumentId { get { return this._TermsOfServiceDocumentIdOption; } set { this._TermsOfServiceDocumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GetTermsOfServiceDocumentResponse {\n"); + sb.Append(" Document: ").Append(Document).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" TermsOfServiceDocumentFormat: ").Append(TermsOfServiceDocumentFormat).Append("\n"); + sb.Append(" TermsOfServiceDocumentId: ").Append(TermsOfServiceDocumentId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GetTermsOfServiceDocumentResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GetTermsOfServiceDocumentResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option document = default; + Option id = default; + Option language = default; + Option termsOfServiceDocumentFormat = default; + Option termsOfServiceDocumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "document": + document = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "termsOfServiceDocumentFormat": + termsOfServiceDocumentFormat = new Option(utf8JsonReader.GetString()!); + break; + case "termsOfServiceDocumentId": + termsOfServiceDocumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(GetTermsOfServiceDocumentResponse.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new GetTermsOfServiceDocumentResponse(document, id, language, termsOfServiceDocumentFormat, termsOfServiceDocumentId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GetTermsOfServiceDocumentResponse getTermsOfServiceDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, getTermsOfServiceDocumentResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GetTermsOfServiceDocumentResponse getTermsOfServiceDocumentResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (getTermsOfServiceDocumentResponse._DocumentOption.IsSet) + { + writer.WritePropertyName("document"); + JsonSerializer.Serialize(writer, getTermsOfServiceDocumentResponse.Document, jsonSerializerOptions); + } + if (getTermsOfServiceDocumentResponse._IdOption.IsSet) + if (getTermsOfServiceDocumentResponse.Id != null) + writer.WriteString("id", getTermsOfServiceDocumentResponse.Id); + + if (getTermsOfServiceDocumentResponse._LanguageOption.IsSet) + if (getTermsOfServiceDocumentResponse.Language != null) + writer.WriteString("language", getTermsOfServiceDocumentResponse.Language); + + if (getTermsOfServiceDocumentResponse._TermsOfServiceDocumentFormatOption.IsSet) + if (getTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormat != null) + writer.WriteString("termsOfServiceDocumentFormat", getTermsOfServiceDocumentResponse.TermsOfServiceDocumentFormat); + + if (getTermsOfServiceDocumentResponse._TermsOfServiceDocumentIdOption.IsSet) + if (getTermsOfServiceDocumentResponse.TermsOfServiceDocumentId != null) + writer.WriteString("termsOfServiceDocumentId", getTermsOfServiceDocumentResponse.TermsOfServiceDocumentId); + + if (getTermsOfServiceDocumentResponse._TypeOption.IsSet && getTermsOfServiceDocumentResponse.Type != null) + { + string? typeRawValue = GetTermsOfServiceDocumentResponse.TypeEnum.ToJsonValue(getTermsOfServiceDocumentResponse._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/HKLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/HKLocalAccountIdentification.cs new file mode 100644 index 000000000..8508c39ea --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/HKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// HKLocalAccountIdentification. + /// + public partial class HKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// The 3-digit clearing code, without separators or whitespace. + /// **hkLocal** (default to TypeEnum.HkLocal) + [JsonConstructor] + public HKLocalAccountIdentification(string accountNumber, string clearingCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingCode = clearingCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HkLocal - hkLocal + /// + public static readonly TypeEnum HkLocal = new("hkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "hkLocal" => TypeEnum.HkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HkLocal) + return "hkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit clearing code, without separators or whitespace. + /// + /// The 3-digit clearing code, without separators or whitespace. + [JsonPropertyName("clearingCode")] + public string ClearingCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingCode: ").Append(ClearingCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 9.", new [] { "AccountNumber" }); + } + + // ClearingCode (string) maxLength + if (this.ClearingCode != null && this.ClearingCode.Length > 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be less than 3.", new [] { "ClearingCode" }); + } + + // ClearingCode (string) minLength + if (this.ClearingCode != null && this.ClearingCode.Length < 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be greater than 3.", new [] { "ClearingCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingCode": + clearingCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingCode.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(clearingCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(type)); + + return new HKLocalAccountIdentification(accountNumber.Value!, clearingCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hKLocalAccountIdentification.AccountNumber); + + if (hKLocalAccountIdentification.ClearingCode != null) + writer.WriteString("clearingCode", hKLocalAccountIdentification.ClearingCode); + + if (hKLocalAccountIdentification.Type != null) + { + string? typeRawValue = HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/HULocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/HULocalAccountIdentification.cs new file mode 100644 index 000000000..636e3081e --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/HULocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// HULocalAccountIdentification. + /// + public partial class HULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 24-digit bank account number, without separators or whitespace. + /// **huLocal** (default to TypeEnum.HuLocal) + [JsonConstructor] + public HULocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HuLocal - huLocal + /// + public static readonly TypeEnum HuLocal = new("huLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "huLocal" => TypeEnum.HuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HuLocal) + return "huLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 24-digit bank account number, without separators or whitespace. + /// + /// The 24-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 24.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 24.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(type)); + + return new HULocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hULocalAccountIdentification.AccountNumber); + + if (hULocalAccountIdentification.Type != null) + { + string? typeRawValue = HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/IbanAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/IbanAccountIdentification.cs new file mode 100644 index 000000000..40ae1ac74 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/IbanAccountIdentification.cs @@ -0,0 +1,289 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// IbanAccountIdentification. + /// + public partial class IbanAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// **iban** (default to TypeEnum.Iban) + [JsonConstructor] + public IbanAccountIdentification(string iban, TypeEnum type = default) + { + Iban = iban; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **iban** + /// + /// **iban** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Iban - iban + /// + public static readonly TypeEnum Iban = new("iban"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "iban" => TypeEnum.Iban, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Iban) + return "iban"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **iban** + /// + /// **iban** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentification {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(iban)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(type)); + + return new IbanAccountIdentification(iban.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentification.Iban != null) + writer.WriteString("iban", ibanAccountIdentification.Iban); + + if (ibanAccountIdentification.Type != null) + { + string? typeRawValue = IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/IdentificationData.cs b/Adyen/LegalEntityManagement/Models/IdentificationData.cs new file mode 100644 index 000000000..f3b56d13e --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/IdentificationData.cs @@ -0,0 +1,446 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// IdentificationData. + /// + public partial class IdentificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Type of identity data. For individuals, the following types are supported. See our [onboarding guide](https://docs.adyen.com/platforms/onboard-users/onboarding-steps/?onboarding_type=custom) for other supported countries. - Australia: **driversLicense**, **passport** - Hong Kong: **driversLicense**, **nationalIdNumber**, **passport** - New Zealand: **driversLicense**, **passport** - Singapore: **driversLicense**, **nationalIdNumber**, **passport** - All other supported countries: **nationalIdNumber** + /// The card number of the document that was issued (AU only). + /// The expiry date of the document, in YYYY-MM-DD format. + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + /// The state or province where the document was issued (AU only). + /// Applies only to individuals in the US. Set to **true** if the individual does not have an SSN. To verify their identity, Adyen will require them to upload an ID document. + /// The number in the document. + [JsonConstructor] + public IdentificationData(TypeEnum type, Option cardNumber = default, Option expiryDate = default, Option issuerCountry = default, Option issuerState = default, Option nationalIdExempt = default, Option number = default) + { + Type = type; + _CardNumberOption = cardNumber; + _ExpiryDateOption = expiryDate; + _IssuerCountryOption = issuerCountry; + _IssuerStateOption = issuerState; + _NationalIdExemptOption = nationalIdExempt; + _NumberOption = number; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IdentificationData() + { + } + + partial void OnCreated(); + + /// + /// Type of identity data. For individuals, the following types are supported. See our [onboarding guide](https://docs.adyen.com/platforms/onboard-users/onboarding-steps/?onboarding_type=custom) for other supported countries. - Australia: **driversLicense**, **passport** - Hong Kong: **driversLicense**, **nationalIdNumber**, **passport** - New Zealand: **driversLicense**, **passport** - Singapore: **driversLicense**, **nationalIdNumber**, **passport** - All other supported countries: **nationalIdNumber** + /// + /// Type of identity data. For individuals, the following types are supported. See our [onboarding guide](https://docs.adyen.com/platforms/onboard-users/onboarding-steps/?onboarding_type=custom) for other supported countries. - Australia: **driversLicense**, **passport** - Hong Kong: **driversLicense**, **nationalIdNumber**, **passport** - New Zealand: **driversLicense**, **passport** - Singapore: **driversLicense**, **nationalIdNumber**, **passport** - All other supported countries: **nationalIdNumber** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NationalIdNumber - nationalIdNumber + /// + public static readonly TypeEnum NationalIdNumber = new("nationalIdNumber"); + + /// + /// TypeEnum.Passport - passport + /// + public static readonly TypeEnum Passport = new("passport"); + + /// + /// TypeEnum.DriversLicense - driversLicense + /// + public static readonly TypeEnum DriversLicense = new("driversLicense"); + + /// + /// TypeEnum.IdentityCard - identityCard + /// + public static readonly TypeEnum IdentityCard = new("identityCard"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nationalIdNumber" => TypeEnum.NationalIdNumber, + "passport" => TypeEnum.Passport, + "driversLicense" => TypeEnum.DriversLicense, + "identityCard" => TypeEnum.IdentityCard, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NationalIdNumber) + return "nationalIdNumber"; + + if (value == TypeEnum.Passport) + return "passport"; + + if (value == TypeEnum.DriversLicense) + return "driversLicense"; + + if (value == TypeEnum.IdentityCard) + return "identityCard"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of identity data. For individuals, the following types are supported. See our [onboarding guide](https://docs.adyen.com/platforms/onboard-users/onboarding-steps/?onboarding_type=custom) for other supported countries. - Australia: **driversLicense**, **passport** - Hong Kong: **driversLicense**, **nationalIdNumber**, **passport** - New Zealand: **driversLicense**, **passport** - Singapore: **driversLicense**, **nationalIdNumber**, **passport** - All other supported countries: **nationalIdNumber** + /// + /// Type of identity data. For individuals, the following types are supported. See our [onboarding guide](https://docs.adyen.com/platforms/onboard-users/onboarding-steps/?onboarding_type=custom) for other supported countries. - Australia: **driversLicense**, **passport** - Hong Kong: **driversLicense**, **nationalIdNumber**, **passport** - New Zealand: **driversLicense**, **passport** - Singapore: **driversLicense**, **nationalIdNumber**, **passport** - All other supported countries: **nationalIdNumber** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardNumberOption { get; private set; } + + /// + /// The card number of the document that was issued (AU only). + /// + /// The card number of the document that was issued (AU only). + [JsonPropertyName("cardNumber")] + public string? CardNumber { get { return this._CardNumberOption; } set { this._CardNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryDateOption { get; private set; } + + /// + /// The expiry date of the document, in YYYY-MM-DD format. + /// + /// The expiry date of the document, in YYYY-MM-DD format. + [JsonPropertyName("expiryDate")] + public string? ExpiryDate { get { return this._ExpiryDateOption; } set { this._ExpiryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code where the document was issued. For example, **US**. + [JsonPropertyName("issuerCountry")] + [Obsolete("Deprecated since Legal Entity Management API v1.")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerStateOption { get; private set; } + + /// + /// The state or province where the document was issued (AU only). + /// + /// The state or province where the document was issued (AU only). + [JsonPropertyName("issuerState")] + public string? IssuerState { get { return this._IssuerStateOption; } set { this._IssuerStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NationalIdExemptOption { get; private set; } + + /// + /// Applies only to individuals in the US. Set to **true** if the individual does not have an SSN. To verify their identity, Adyen will require them to upload an ID document. + /// + /// Applies only to individuals in the US. Set to **true** if the individual does not have an SSN. To verify their identity, Adyen will require them to upload an ID document. + [JsonPropertyName("nationalIdExempt")] + public bool? NationalIdExempt { get { return this._NationalIdExemptOption; } set { this._NationalIdExemptOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The number in the document. + /// + /// The number in the document. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IdentificationData {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); + sb.Append(" ExpiryDate: ").Append(ExpiryDate).Append("\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append(" IssuerState: ").Append(IssuerState).Append("\n"); + sb.Append(" NationalIdExempt: ").Append(NationalIdExempt).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IdentificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IdentificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option cardNumber = default; + Option expiryDate = default; + Option issuerCountry = default; + Option issuerState = default; + Option nationalIdExempt = default; + Option number = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IdentificationData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "cardNumber": + cardNumber = new Option(utf8JsonReader.GetString()!); + break; + case "expiryDate": + expiryDate = new Option(utf8JsonReader.GetString()!); + break; + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + case "issuerState": + issuerState = new Option(utf8JsonReader.GetString()!); + break; + case "nationalIdExempt": + nationalIdExempt = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IdentificationData.", nameof(type)); + + return new IdentificationData(type.Value!.Value!, cardNumber, expiryDate, issuerCountry, issuerState, nationalIdExempt, number); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IdentificationData identificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, identificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IdentificationData identificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (identificationData.Type != null) + { + string? typeRawValue = IdentificationData.TypeEnum.ToJsonValue(identificationData.Type); + writer.WriteString("type", typeRawValue); + } + + if (identificationData._CardNumberOption.IsSet) + if (identificationData.CardNumber != null) + writer.WriteString("cardNumber", identificationData.CardNumber); + + if (identificationData._ExpiryDateOption.IsSet) + if (identificationData.ExpiryDate != null) + writer.WriteString("expiryDate", identificationData.ExpiryDate); + + if (identificationData._IssuerCountryOption.IsSet) + if (identificationData.IssuerCountry != null) + writer.WriteString("issuerCountry", identificationData.IssuerCountry); + + if (identificationData._IssuerStateOption.IsSet) + if (identificationData.IssuerState != null) + writer.WriteString("issuerState", identificationData.IssuerState); + + if (identificationData._NationalIdExemptOption.IsSet) + writer.WriteBoolean("nationalIdExempt", identificationData._NationalIdExemptOption.Value!.Value); + + if (identificationData._NumberOption.IsSet) + if (identificationData.Number != null) + writer.WriteString("number", identificationData.Number); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Individual.cs b/Adyen/LegalEntityManagement/Models/Individual.cs new file mode 100644 index 000000000..aa307fe75 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Individual.cs @@ -0,0 +1,389 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Individual. + /// + public partial class Individual : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// residentialAddress + /// birthData + /// The email address of the legal entity. + /// identificationData + /// The individual's nationality. + /// phone + /// support + /// The tax information of the individual. + /// webData + [JsonConstructor] + public Individual(Name name, Address residentialAddress, Option birthData = default, Option email = default, Option identificationData = default, Option nationality = default, Option phone = default, Option support = default, Option?> taxInformation = default, Option webData = default) + { + Name = name; + ResidentialAddress = residentialAddress; + _BirthDataOption = birthData; + _EmailOption = email; + _IdentificationDataOption = identificationData; + _NationalityOption = nationality; + _PhoneOption = phone; + _SupportOption = support; + _TaxInformationOption = taxInformation; + _WebDataOption = webData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Individual() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("name")] + public Name Name { get; set; } + + /// + /// . + /// + [JsonPropertyName("residentialAddress")] + public Address ResidentialAddress { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BirthDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("birthData")] + public BirthData? BirthData { get { return this._BirthDataOption; } set { this._BirthDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the legal entity. + /// + /// The email address of the legal entity. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdentificationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("identificationData")] + public IdentificationData? IdentificationData { get { return this._IdentificationDataOption; } set { this._IdentificationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NationalityOption { get; private set; } + + /// + /// The individual's nationality. + /// + /// The individual's nationality. + [JsonPropertyName("nationality")] + public string? Nationality { get { return this._NationalityOption; } set { this._NationalityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public PhoneNumber? Phone { get { return this._PhoneOption; } set { this._PhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SupportOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("support")] + public Support? Support { get { return this._SupportOption; } set { this._SupportOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TaxInformationOption { get; private set; } + + /// + /// The tax information of the individual. + /// + /// The tax information of the individual. + [JsonPropertyName("taxInformation")] + public List? TaxInformation { get { return this._TaxInformationOption; } set { this._TaxInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webData")] + public WebData? WebData { get { return this._WebDataOption; } set { this._WebDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Individual {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" ResidentialAddress: ").Append(ResidentialAddress).Append("\n"); + sb.Append(" BirthData: ").Append(BirthData).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" IdentificationData: ").Append(IdentificationData).Append("\n"); + sb.Append(" Nationality: ").Append(Nationality).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" Support: ").Append(Support).Append("\n"); + sb.Append(" TaxInformation: ").Append(TaxInformation).Append("\n"); + sb.Append(" WebData: ").Append(WebData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IndividualJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Individual Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option residentialAddress = default; + Option birthData = default; + Option email = default; + Option identificationData = default; + Option nationality = default; + Option phone = default; + Option support = default; + Option?> taxInformation = default; + Option webData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "residentialAddress": + residentialAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "birthData": + birthData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "identificationData": + identificationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nationality": + nationality = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "support": + support = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "taxInformation": + taxInformation = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webData": + webData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class Individual.", nameof(name)); + + if (!residentialAddress.IsSet) + throw new ArgumentException("Property is required for class Individual.", nameof(residentialAddress)); + + return new Individual(name.Value!, residentialAddress.Value!, birthData, email, identificationData, nationality, phone, support, taxInformation, webData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Individual individual, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, individual, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Individual individual, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, individual.Name, jsonSerializerOptions); + writer.WritePropertyName("residentialAddress"); + JsonSerializer.Serialize(writer, individual.ResidentialAddress, jsonSerializerOptions); + if (individual._BirthDataOption.IsSet) + { + writer.WritePropertyName("birthData"); + JsonSerializer.Serialize(writer, individual.BirthData, jsonSerializerOptions); + } + if (individual._EmailOption.IsSet) + if (individual.Email != null) + writer.WriteString("email", individual.Email); + + if (individual._IdentificationDataOption.IsSet) + { + writer.WritePropertyName("identificationData"); + JsonSerializer.Serialize(writer, individual.IdentificationData, jsonSerializerOptions); + } + if (individual._NationalityOption.IsSet) + if (individual.Nationality != null) + writer.WriteString("nationality", individual.Nationality); + + if (individual._PhoneOption.IsSet) + { + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, individual.Phone, jsonSerializerOptions); + } + if (individual._SupportOption.IsSet) + { + writer.WritePropertyName("support"); + JsonSerializer.Serialize(writer, individual.Support, jsonSerializerOptions); + } + if (individual._TaxInformationOption.IsSet) + { + writer.WritePropertyName("taxInformation"); + JsonSerializer.Serialize(writer, individual.TaxInformation, jsonSerializerOptions); + } + if (individual._WebDataOption.IsSet) + { + writer.WritePropertyName("webData"); + JsonSerializer.Serialize(writer, individual.WebData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/LegalEntity.cs b/Adyen/LegalEntityManagement/Models/LegalEntity.cs new file mode 100644 index 000000000..4b52a2e09 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/LegalEntity.cs @@ -0,0 +1,693 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// LegalEntity. + /// + public partial class LegalEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the legal entity. + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// List of documents uploaded for the legal entity. + /// List of documents uploaded for the legal entity. + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// individual + /// organization + /// List of verification errors related to capabilities for the legal entity. + /// Your reference for the legal entity, maximum 150 characters. + /// soleProprietorship + /// List of transfer instruments that the legal entity owns. + /// trust + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// unincorporatedPartnership + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonConstructor] + public LegalEntity(string id, Option?> capabilities = default, Option?> documentDetails = default, Option?> documents = default, Option?> entityAssociations = default, Option individual = default, Option organization = default, Option?> problems = default, Option reference = default, Option soleProprietorship = default, Option?> transferInstruments = default, Option trust = default, Option type = default, Option unincorporatedPartnership = default, Option?> verificationDeadlines = default, Option verificationPlan = default) + { + Id = id; + _CapabilitiesOption = capabilities; + _DocumentDetailsOption = documentDetails; + _DocumentsOption = documents; + _EntityAssociationsOption = entityAssociations; + _IndividualOption = individual; + _OrganizationOption = organization; + _ProblemsOption = problems; + _ReferenceOption = reference; + _SoleProprietorshipOption = soleProprietorship; + _TransferInstrumentsOption = transferInstruments; + _TrustOption = trust; + _TypeOption = type; + _UnincorporatedPartnershipOption = unincorporatedPartnership; + _VerificationDeadlinesOption = verificationDeadlines; + _VerificationPlanOption = verificationPlan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntity() + { + } + + partial void OnCreated(); + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.SoleProprietorship - soleProprietorship + /// + public static readonly TypeEnum SoleProprietorship = new("soleProprietorship"); + + /// + /// TypeEnum.Trust - trust + /// + public static readonly TypeEnum Trust = new("trust"); + + /// + /// TypeEnum.UnincorporatedPartnership - unincorporatedPartnership + /// + public static readonly TypeEnum UnincorporatedPartnership = new("unincorporatedPartnership"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "soleProprietorship" => TypeEnum.SoleProprietorship, + "trust" => TypeEnum.Trust, + "unincorporatedPartnership" => TypeEnum.UnincorporatedPartnership, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.SoleProprietorship) + return "soleProprietorship"; + + if (value == TypeEnum.Trust) + return "trust"; + + if (value == TypeEnum.UnincorporatedPartnership) + return "unincorporatedPartnership"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The unique identifier of the legal entity. + /// + /// The unique identifier of the legal entity. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentDetailsOption { get; private set; } + + /// + /// List of documents uploaded for the legal entity. + /// + /// List of documents uploaded for the legal entity. + [JsonPropertyName("documentDetails")] + public List? DocumentDetails { get { return this._DocumentDetailsOption; } set { this._DocumentDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of documents uploaded for the legal entity. + /// + /// List of documents uploaded for the legal entity. + [JsonPropertyName("documents")] + [Obsolete("Deprecated since Legal Entity Management API v1. Use the `documentDetails` array instead.")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityAssociationsOption { get; private set; } + + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + [JsonPropertyName("entityAssociations")] + public List? EntityAssociations { get { return this._EntityAssociationsOption; } set { this._EntityAssociationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndividualOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("individual")] + public Individual? Individual { get { return this._IndividualOption; } set { this._IndividualOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrganizationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("organization")] + public Organization? Organization { get { return this._OrganizationOption; } set { this._OrganizationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// List of verification errors related to capabilities for the legal entity. + /// + /// List of verification errors related to capabilities for the legal entity. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the legal entity, maximum 150 characters. + /// + /// Your reference for the legal entity, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SoleProprietorshipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("soleProprietorship")] + public SoleProprietorship? SoleProprietorship { get { return this._SoleProprietorshipOption; } set { this._SoleProprietorshipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferInstrumentsOption { get; } + + /// + /// List of transfer instruments that the legal entity owns. + /// + /// List of transfer instruments that the legal entity owns. + [JsonPropertyName("transferInstruments")] + public List? TransferInstruments { get { return this._TransferInstrumentsOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("trust")] + public Trust? Trust { get { return this._TrustOption; } set { this._TrustOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnincorporatedPartnershipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("unincorporatedPartnership")] + public UnincorporatedPartnership? UnincorporatedPartnership { get { return this._UnincorporatedPartnershipOption; } set { this._UnincorporatedPartnershipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationDeadlinesOption { get; } + + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + /// + /// List of verification deadlines and the capabilities that will be disallowed if verification errors are not resolved. + [JsonPropertyName("verificationDeadlines")] + public List? VerificationDeadlines { get { return this._VerificationDeadlinesOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationPlanOption { get; private set; } + + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonPropertyName("verificationPlan")] + public string? VerificationPlan { get { return this._VerificationPlanOption; } set { this._VerificationPlanOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntity {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" DocumentDetails: ").Append(DocumentDetails).Append("\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" EntityAssociations: ").Append(EntityAssociations).Append("\n"); + sb.Append(" Individual: ").Append(Individual).Append("\n"); + sb.Append(" Organization: ").Append(Organization).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SoleProprietorship: ").Append(SoleProprietorship).Append("\n"); + sb.Append(" TransferInstruments: ").Append(TransferInstruments).Append("\n"); + sb.Append(" Trust: ").Append(Trust).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UnincorporatedPartnership: ").Append(UnincorporatedPartnership).Append("\n"); + sb.Append(" VerificationDeadlines: ").Append(VerificationDeadlines).Append("\n"); + sb.Append(" VerificationPlan: ").Append(VerificationPlan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option?> capabilities = default; + Option?> documentDetails = default; + Option?> documents = default; + Option?> entityAssociations = default; + Option individual = default; + Option organization = default; + Option?> problems = default; + Option reference = default; + Option soleProprietorship = default; + Option?> transferInstruments = default; + Option trust = default; + Option type = default; + Option unincorporatedPartnership = default; + Option?> verificationDeadlines = default; + Option verificationPlan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "documentDetails": + documentDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "entityAssociations": + entityAssociations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "individual": + individual = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "organization": + organization = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "soleProprietorship": + soleProprietorship = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstruments": + transferInstruments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "trust": + trust = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(LegalEntity.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "unincorporatedPartnership": + unincorporatedPartnership = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationDeadlines": + verificationDeadlines = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationPlan": + verificationPlan = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class LegalEntity.", nameof(id)); + + return new LegalEntity(id.Value!, capabilities, documentDetails, documents, entityAssociations, individual, organization, problems, reference, soleProprietorship, transferInstruments, trust, type, unincorporatedPartnership, verificationDeadlines, verificationPlan); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntity legalEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntity legalEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntity.Id != null) + writer.WriteString("id", legalEntity.Id); + + if (legalEntity._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, legalEntity.Capabilities, jsonSerializerOptions); + } + if (legalEntity._DocumentDetailsOption.IsSet) + { + writer.WritePropertyName("documentDetails"); + JsonSerializer.Serialize(writer, legalEntity.DocumentDetails, jsonSerializerOptions); + } + if (legalEntity._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, legalEntity.Documents, jsonSerializerOptions); + } + if (legalEntity._EntityAssociationsOption.IsSet) + { + writer.WritePropertyName("entityAssociations"); + JsonSerializer.Serialize(writer, legalEntity.EntityAssociations, jsonSerializerOptions); + } + if (legalEntity._IndividualOption.IsSet) + { + writer.WritePropertyName("individual"); + JsonSerializer.Serialize(writer, legalEntity.Individual, jsonSerializerOptions); + } + if (legalEntity._OrganizationOption.IsSet) + { + writer.WritePropertyName("organization"); + JsonSerializer.Serialize(writer, legalEntity.Organization, jsonSerializerOptions); + } + if (legalEntity._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, legalEntity.Problems, jsonSerializerOptions); + } + if (legalEntity._ReferenceOption.IsSet) + if (legalEntity.Reference != null) + writer.WriteString("reference", legalEntity.Reference); + + if (legalEntity._SoleProprietorshipOption.IsSet) + { + writer.WritePropertyName("soleProprietorship"); + JsonSerializer.Serialize(writer, legalEntity.SoleProprietorship, jsonSerializerOptions); + } + if (legalEntity._TransferInstrumentsOption.IsSet) + { + writer.WritePropertyName("transferInstruments"); + JsonSerializer.Serialize(writer, legalEntity.TransferInstruments, jsonSerializerOptions); + } + if (legalEntity._TrustOption.IsSet) + { + writer.WritePropertyName("trust"); + JsonSerializer.Serialize(writer, legalEntity.Trust, jsonSerializerOptions); + } + if (legalEntity._TypeOption.IsSet && legalEntity.Type != null) + { + string? typeRawValue = LegalEntity.TypeEnum.ToJsonValue(legalEntity._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (legalEntity._UnincorporatedPartnershipOption.IsSet) + { + writer.WritePropertyName("unincorporatedPartnership"); + JsonSerializer.Serialize(writer, legalEntity.UnincorporatedPartnership, jsonSerializerOptions); + } + if (legalEntity._VerificationDeadlinesOption.IsSet) + { + writer.WritePropertyName("verificationDeadlines"); + JsonSerializer.Serialize(writer, legalEntity.VerificationDeadlines, jsonSerializerOptions); + } + if (legalEntity._VerificationPlanOption.IsSet) + if (legalEntity.VerificationPlan != null) + writer.WriteString("verificationPlan", legalEntity.VerificationPlan); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/LegalEntityAssociation.cs b/Adyen/LegalEntityManagement/Models/LegalEntityAssociation.cs new file mode 100644 index 000000000..d28138bd3 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/LegalEntityAssociation.cs @@ -0,0 +1,618 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// LegalEntityAssociation. + /// + public partial class LegalEntityAssociation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + /// Defines the relationship of the legal entity to the current legal entity. Possible value for individuals: **legalRepresentative**. Possible values for organizations: **director**, **signatory**, **trustOwnership**, **uboThroughOwnership**, **uboThroughControl**, or **ultimateParentCompany**. Possible values for sole proprietorships: **soleProprietorship**. Possible value for trusts: **trust**. Possible values for trust members: **definedBeneficiary**, **protector**, **secondaryTrustee**, **settlor**, **uboThroughControl**, or **uboThroughOwnership**. Possible value for unincorporated partnership: **unincorporatedPartnership**. Possible values for unincorporated partnership members: **secondaryPartner**, **uboThroughControl**, **uboThroughOwnership** + /// The unique identifier of another legal entity with which the `legalEntityId` is associated. When the `legalEntityId` is associated to legal entities other than the current one, the response returns all the associations. + /// The legal entity type of associated legal entity. For example, **organization**, **soleProprietorship** or **individual**. + /// The individual's job title if the `type` is **uboThroughControl** or **signatory**. + /// The name of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). - For **individual**, `name.firstName` and `name.lastName`. - For **organization**, `legalName`. - For **soleProprietorship**, `name`. + /// Default value: **false** Set to **true** if the entity association `type` **director**, **secondaryPartner** or **shareholder** is also a nominee. Only applicable to New Zealand. + /// The individual's relationship to a legal representative if the `type` is **legalRepresentative**. Possible values: **parent**, **guardian**. + /// Defines the KYC exemption reason for a settlor associated with a trust. Only applicable to trusts in Australia. For example, **professionalServiceProvider**, **deceased**, or **contributionBelowThreshold**. + [JsonConstructor] + public LegalEntityAssociation(string legalEntityId, TypeEnum type, Option associatorId = default, Option entityType = default, Option jobTitle = default, Option name = default, Option nominee = default, Option relationship = default, Option?> settlorExemptionReason = default) + { + LegalEntityId = legalEntityId; + Type = type; + _AssociatorIdOption = associatorId; + _EntityTypeOption = entityType; + _JobTitleOption = jobTitle; + _NameOption = name; + _NomineeOption = nominee; + _RelationshipOption = relationship; + _SettlorExemptionReasonOption = settlorExemptionReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntityAssociation() + { + } + + partial void OnCreated(); + + /// + /// Defines the relationship of the legal entity to the current legal entity. Possible value for individuals: **legalRepresentative**. Possible values for organizations: **director**, **signatory**, **trustOwnership**, **uboThroughOwnership**, **uboThroughControl**, or **ultimateParentCompany**. Possible values for sole proprietorships: **soleProprietorship**. Possible value for trusts: **trust**. Possible values for trust members: **definedBeneficiary**, **protector**, **secondaryTrustee**, **settlor**, **uboThroughControl**, or **uboThroughOwnership**. Possible value for unincorporated partnership: **unincorporatedPartnership**. Possible values for unincorporated partnership members: **secondaryPartner**, **uboThroughControl**, **uboThroughOwnership** + /// + /// Defines the relationship of the legal entity to the current legal entity. Possible value for individuals: **legalRepresentative**. Possible values for organizations: **director**, **signatory**, **trustOwnership**, **uboThroughOwnership**, **uboThroughControl**, or **ultimateParentCompany**. Possible values for sole proprietorships: **soleProprietorship**. Possible value for trusts: **trust**. Possible values for trust members: **definedBeneficiary**, **protector**, **secondaryTrustee**, **settlor**, **uboThroughControl**, or **uboThroughOwnership**. Possible value for unincorporated partnership: **unincorporatedPartnership**. Possible values for unincorporated partnership members: **secondaryPartner**, **uboThroughControl**, **uboThroughOwnership** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DefinedBeneficiary - definedBeneficiary + /// + public static readonly TypeEnum DefinedBeneficiary = new("definedBeneficiary"); + + /// + /// TypeEnum.Director - director + /// + public static readonly TypeEnum Director = new("director"); + + /// + /// TypeEnum.ImmediateParentCompany - immediateParentCompany + /// + public static readonly TypeEnum ImmediateParentCompany = new("immediateParentCompany"); + + /// + /// TypeEnum.LegalRepresentative - legalRepresentative + /// + public static readonly TypeEnum LegalRepresentative = new("legalRepresentative"); + + /// + /// TypeEnum.PciSignatory - pciSignatory + /// + public static readonly TypeEnum PciSignatory = new("pciSignatory"); + + /// + /// TypeEnum.Protector - protector + /// + public static readonly TypeEnum Protector = new("protector"); + + /// + /// TypeEnum.SecondaryPartner - secondaryPartner + /// + public static readonly TypeEnum SecondaryPartner = new("secondaryPartner"); + + /// + /// TypeEnum.SecondaryTrustee - secondaryTrustee + /// + public static readonly TypeEnum SecondaryTrustee = new("secondaryTrustee"); + + /// + /// TypeEnum.Settlor - settlor + /// + public static readonly TypeEnum Settlor = new("settlor"); + + /// + /// TypeEnum.Signatory - signatory + /// + public static readonly TypeEnum Signatory = new("signatory"); + + /// + /// TypeEnum.SoleProprietorship - soleProprietorship + /// + public static readonly TypeEnum SoleProprietorship = new("soleProprietorship"); + + /// + /// TypeEnum.Trust - trust + /// + public static readonly TypeEnum Trust = new("trust"); + + /// + /// TypeEnum.TrustOwnership - trustOwnership + /// + public static readonly TypeEnum TrustOwnership = new("trustOwnership"); + + /// + /// TypeEnum.UboThroughControl - uboThroughControl + /// + public static readonly TypeEnum UboThroughControl = new("uboThroughControl"); + + /// + /// TypeEnum.UboThroughOwnership - uboThroughOwnership + /// + public static readonly TypeEnum UboThroughOwnership = new("uboThroughOwnership"); + + /// + /// TypeEnum.UltimateParentCompany - ultimateParentCompany + /// + public static readonly TypeEnum UltimateParentCompany = new("ultimateParentCompany"); + + /// + /// TypeEnum.UndefinedBeneficiary - undefinedBeneficiary + /// + public static readonly TypeEnum UndefinedBeneficiary = new("undefinedBeneficiary"); + + /// + /// TypeEnum.UnincorporatedPartnership - unincorporatedPartnership + /// + public static readonly TypeEnum UnincorporatedPartnership = new("unincorporatedPartnership"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "definedBeneficiary" => TypeEnum.DefinedBeneficiary, + "director" => TypeEnum.Director, + "immediateParentCompany" => TypeEnum.ImmediateParentCompany, + "legalRepresentative" => TypeEnum.LegalRepresentative, + "pciSignatory" => TypeEnum.PciSignatory, + "protector" => TypeEnum.Protector, + "secondaryPartner" => TypeEnum.SecondaryPartner, + "secondaryTrustee" => TypeEnum.SecondaryTrustee, + "settlor" => TypeEnum.Settlor, + "signatory" => TypeEnum.Signatory, + "soleProprietorship" => TypeEnum.SoleProprietorship, + "trust" => TypeEnum.Trust, + "trustOwnership" => TypeEnum.TrustOwnership, + "uboThroughControl" => TypeEnum.UboThroughControl, + "uboThroughOwnership" => TypeEnum.UboThroughOwnership, + "ultimateParentCompany" => TypeEnum.UltimateParentCompany, + "undefinedBeneficiary" => TypeEnum.UndefinedBeneficiary, + "unincorporatedPartnership" => TypeEnum.UnincorporatedPartnership, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DefinedBeneficiary) + return "definedBeneficiary"; + + if (value == TypeEnum.Director) + return "director"; + + if (value == TypeEnum.ImmediateParentCompany) + return "immediateParentCompany"; + + if (value == TypeEnum.LegalRepresentative) + return "legalRepresentative"; + + if (value == TypeEnum.PciSignatory) + return "pciSignatory"; + + if (value == TypeEnum.Protector) + return "protector"; + + if (value == TypeEnum.SecondaryPartner) + return "secondaryPartner"; + + if (value == TypeEnum.SecondaryTrustee) + return "secondaryTrustee"; + + if (value == TypeEnum.Settlor) + return "settlor"; + + if (value == TypeEnum.Signatory) + return "signatory"; + + if (value == TypeEnum.SoleProprietorship) + return "soleProprietorship"; + + if (value == TypeEnum.Trust) + return "trust"; + + if (value == TypeEnum.TrustOwnership) + return "trustOwnership"; + + if (value == TypeEnum.UboThroughControl) + return "uboThroughControl"; + + if (value == TypeEnum.UboThroughOwnership) + return "uboThroughOwnership"; + + if (value == TypeEnum.UltimateParentCompany) + return "ultimateParentCompany"; + + if (value == TypeEnum.UndefinedBeneficiary) + return "undefinedBeneficiary"; + + if (value == TypeEnum.UnincorporatedPartnership) + return "unincorporatedPartnership"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Defines the relationship of the legal entity to the current legal entity. Possible value for individuals: **legalRepresentative**. Possible values for organizations: **director**, **signatory**, **trustOwnership**, **uboThroughOwnership**, **uboThroughControl**, or **ultimateParentCompany**. Possible values for sole proprietorships: **soleProprietorship**. Possible value for trusts: **trust**. Possible values for trust members: **definedBeneficiary**, **protector**, **secondaryTrustee**, **settlor**, **uboThroughControl**, or **uboThroughOwnership**. Possible value for unincorporated partnership: **unincorporatedPartnership**. Possible values for unincorporated partnership members: **secondaryPartner**, **uboThroughControl**, **uboThroughOwnership** + /// + /// Defines the relationship of the legal entity to the current legal entity. Possible value for individuals: **legalRepresentative**. Possible values for organizations: **director**, **signatory**, **trustOwnership**, **uboThroughOwnership**, **uboThroughControl**, or **ultimateParentCompany**. Possible values for sole proprietorships: **soleProprietorship**. Possible value for trusts: **trust**. Possible values for trust members: **definedBeneficiary**, **protector**, **secondaryTrustee**, **settlor**, **uboThroughControl**, or **uboThroughOwnership**. Possible value for unincorporated partnership: **unincorporatedPartnership**. Possible values for unincorporated partnership members: **secondaryPartner**, **uboThroughControl**, **uboThroughOwnership** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The unique identifier of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + /// + /// The unique identifier of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssociatorIdOption { get; } + + /// + /// The unique identifier of another legal entity with which the `legalEntityId` is associated. When the `legalEntityId` is associated to legal entities other than the current one, the response returns all the associations. + /// + /// The unique identifier of another legal entity with which the `legalEntityId` is associated. When the `legalEntityId` is associated to legal entities other than the current one, the response returns all the associations. + [JsonPropertyName("associatorId")] + public string? AssociatorId { get { return this._AssociatorIdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityTypeOption { get; } + + /// + /// The legal entity type of associated legal entity. For example, **organization**, **soleProprietorship** or **individual**. + /// + /// The legal entity type of associated legal entity. For example, **organization**, **soleProprietorship** or **individual**. + [JsonPropertyName("entityType")] + public string? EntityType { get { return this._EntityTypeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JobTitleOption { get; private set; } + + /// + /// The individual's job title if the `type` is **uboThroughControl** or **signatory**. + /// + /// The individual's job title if the `type` is **uboThroughControl** or **signatory**. + [JsonPropertyName("jobTitle")] + public string? JobTitle { get { return this._JobTitleOption; } set { this._JobTitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; } + + /// + /// The name of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). - For **individual**, `name.firstName` and `name.lastName`. - For **organization**, `legalName`. - For **soleProprietorship**, `name`. + /// + /// The name of the associated [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). - For **individual**, `name.firstName` and `name.lastName`. - For **organization**, `legalName`. - For **soleProprietorship**, `name`. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NomineeOption { get; private set; } + + /// + /// Default value: **false** Set to **true** if the entity association `type` **director**, **secondaryPartner** or **shareholder** is also a nominee. Only applicable to New Zealand. + /// + /// Default value: **false** Set to **true** if the entity association `type` **director**, **secondaryPartner** or **shareholder** is also a nominee. Only applicable to New Zealand. + [JsonPropertyName("nominee")] + public bool? Nominee { get { return this._NomineeOption; } set { this._NomineeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RelationshipOption { get; private set; } + + /// + /// The individual's relationship to a legal representative if the `type` is **legalRepresentative**. Possible values: **parent**, **guardian**. + /// + /// The individual's relationship to a legal representative if the `type` is **legalRepresentative**. Possible values: **parent**, **guardian**. + [JsonPropertyName("relationship")] + public string? Relationship { get { return this._RelationshipOption; } set { this._RelationshipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SettlorExemptionReasonOption { get; private set; } + + /// + /// Defines the KYC exemption reason for a settlor associated with a trust. Only applicable to trusts in Australia. For example, **professionalServiceProvider**, **deceased**, or **contributionBelowThreshold**. + /// + /// Defines the KYC exemption reason for a settlor associated with a trust. Only applicable to trusts in Australia. For example, **professionalServiceProvider**, **deceased**, or **contributionBelowThreshold**. + [JsonPropertyName("settlorExemptionReason")] + public List? SettlorExemptionReason { get { return this._SettlorExemptionReasonOption; } set { this._SettlorExemptionReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntityAssociation {\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" AssociatorId: ").Append(AssociatorId).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" JobTitle: ").Append(JobTitle).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Nominee: ").Append(Nominee).Append("\n"); + sb.Append(" Relationship: ").Append(Relationship).Append("\n"); + sb.Append(" SettlorExemptionReason: ").Append(SettlorExemptionReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityAssociationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntityAssociation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option legalEntityId = default; + Option type = default; + Option associatorId = default; + Option entityType = default; + Option jobTitle = default; + Option name = default; + Option nominee = default; + Option relationship = default; + Option?> settlorExemptionReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(LegalEntityAssociation.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "associatorId": + associatorId = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + entityType = new Option(utf8JsonReader.GetString()!); + break; + case "jobTitle": + jobTitle = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "nominee": + nominee = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "relationship": + relationship = new Option(utf8JsonReader.GetString()!); + break; + case "settlorExemptionReason": + settlorExemptionReason = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class LegalEntityAssociation.", nameof(legalEntityId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class LegalEntityAssociation.", nameof(type)); + + return new LegalEntityAssociation(legalEntityId.Value!, type.Value!.Value!, associatorId, entityType, jobTitle, name, nominee, relationship, settlorExemptionReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntityAssociation legalEntityAssociation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntityAssociation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntityAssociation legalEntityAssociation, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntityAssociation.LegalEntityId != null) + writer.WriteString("legalEntityId", legalEntityAssociation.LegalEntityId); + + if (legalEntityAssociation.Type != null) + { + string? typeRawValue = LegalEntityAssociation.TypeEnum.ToJsonValue(legalEntityAssociation.Type); + writer.WriteString("type", typeRawValue); + } + + if (legalEntityAssociation._AssociatorIdOption.IsSet) + if (legalEntityAssociation.AssociatorId != null) + writer.WriteString("associatorId", legalEntityAssociation.AssociatorId); + + if (legalEntityAssociation._EntityTypeOption.IsSet) + if (legalEntityAssociation.EntityType != null) + writer.WriteString("entityType", legalEntityAssociation.EntityType); + + if (legalEntityAssociation._JobTitleOption.IsSet) + if (legalEntityAssociation.JobTitle != null) + writer.WriteString("jobTitle", legalEntityAssociation.JobTitle); + + if (legalEntityAssociation._NameOption.IsSet) + if (legalEntityAssociation.Name != null) + writer.WriteString("name", legalEntityAssociation.Name); + + if (legalEntityAssociation._NomineeOption.IsSet) + writer.WriteBoolean("nominee", legalEntityAssociation._NomineeOption.Value!.Value); + + if (legalEntityAssociation._RelationshipOption.IsSet) + if (legalEntityAssociation.Relationship != null) + writer.WriteString("relationship", legalEntityAssociation.Relationship); + + if (legalEntityAssociation._SettlorExemptionReasonOption.IsSet) + { + writer.WritePropertyName("settlorExemptionReason"); + JsonSerializer.Serialize(writer, legalEntityAssociation.SettlorExemptionReason, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/LegalEntityCapability.cs b/Adyen/LegalEntityManagement/Models/LegalEntityCapability.cs new file mode 100644 index 000000000..373daeef4 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/LegalEntityCapability.cs @@ -0,0 +1,599 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// LegalEntityCapability. + /// + public partial class LegalEntityCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + /// The capability level that is allowed for the legal entity. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// allowedSettings + /// Indicates whether the capability is requested. To check whether the legal entity is permitted to use the capability, refer to the `allowed` field. + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// requestedSettings + /// The capability status of transfer instruments associated with the legal entity. + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + public LegalEntityCapability(Option allowed = default, Option allowedLevel = default, Option allowedSettings = default, Option requested = default, Option requestedLevel = default, Option requestedSettings = default, Option?> transferInstruments = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _AllowedSettingsOption = allowedSettings; + _RequestedOption = requested; + _RequestedLevelOption = requestedLevel; + _RequestedSettingsOption = requestedSettings; + _TransferInstrumentsOption = transferInstruments; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntityCapability() + { + } + + partial void OnCreated(); + + /// + /// The capability level that is allowed for the legal entity. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the legal entity. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(AllowedLevelEnumJsonConverter))] + public class AllowedLevelEnum : IEnum + { + /// + /// Returns the value of the AllowedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// AllowedLevelEnum.High - high + /// + public static readonly AllowedLevelEnum High = new("high"); + + /// + /// AllowedLevelEnum.Low - low + /// + public static readonly AllowedLevelEnum Low = new("low"); + + /// + /// AllowedLevelEnum.Medium - medium + /// + public static readonly AllowedLevelEnum Medium = new("medium"); + + /// + /// AllowedLevelEnum.NotApplicable - notApplicable + /// + public static readonly AllowedLevelEnum NotApplicable = new("notApplicable"); + + private AllowedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AllowedLevelEnum?(string? value) => value == null ? null : new AllowedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AllowedLevelEnum? option) => option?.Value; + + public static bool operator ==(AllowedLevelEnum? left, AllowedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AllowedLevelEnum? left, AllowedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AllowedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AllowedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => AllowedLevelEnum.High, + "low" => AllowedLevelEnum.Low, + "medium" => AllowedLevelEnum.Medium, + "notApplicable" => AllowedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AllowedLevelEnum? value) + { + if (value == null) + return null; + + if (value == AllowedLevelEnum.High) + return "high"; + + if (value == AllowedLevelEnum.Low) + return "low"; + + if (value == AllowedLevelEnum.Medium) + return "medium"; + + if (value == AllowedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing AllowedLevelEnum. + /// + public class AllowedLevelEnumJsonConverter : JsonConverter + { + public override AllowedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AllowedLevelEnum.FromStringOrDefault(value) ?? new AllowedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AllowedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AllowedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; } + + /// + /// The capability level that is allowed for the legal entity. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The capability level that is allowed for the legal entity. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public AllowedLevelEnum? AllowedLevel { get { return this._AllowedLevelOption; } } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonConverter(typeof(RequestedLevelEnumJsonConverter))] + public class RequestedLevelEnum : IEnum + { + /// + /// Returns the value of the RequestedLevelEnum. + /// + public string? Value { get; set; } + + /// + /// RequestedLevelEnum.High - high + /// + public static readonly RequestedLevelEnum High = new("high"); + + /// + /// RequestedLevelEnum.Low - low + /// + public static readonly RequestedLevelEnum Low = new("low"); + + /// + /// RequestedLevelEnum.Medium - medium + /// + public static readonly RequestedLevelEnum Medium = new("medium"); + + /// + /// RequestedLevelEnum.NotApplicable - notApplicable + /// + public static readonly RequestedLevelEnum NotApplicable = new("notApplicable"); + + private RequestedLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RequestedLevelEnum?(string? value) => value == null ? null : new RequestedLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RequestedLevelEnum? option) => option?.Value; + + public static bool operator ==(RequestedLevelEnum? left, RequestedLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RequestedLevelEnum? left, RequestedLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RequestedLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RequestedLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "high" => RequestedLevelEnum.High, + "low" => RequestedLevelEnum.Low, + "medium" => RequestedLevelEnum.Medium, + "notApplicable" => RequestedLevelEnum.NotApplicable, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RequestedLevelEnum? value) + { + if (value == null) + return null; + + if (value == RequestedLevelEnum.High) + return "high"; + + if (value == RequestedLevelEnum.Low) + return "low"; + + if (value == RequestedLevelEnum.Medium) + return "medium"; + + if (value == RequestedLevelEnum.NotApplicable) + return "notApplicable"; + + return null; + } + + /// + /// JsonConverter for writing RequestedLevelEnum. + /// + public class RequestedLevelEnumJsonConverter : JsonConverter + { + public override RequestedLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RequestedLevelEnum.FromStringOrDefault(value) ?? new RequestedLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RequestedLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RequestedLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedLevelOption { get; } + + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The requested level of the capability. Some capabilities, such as those used in [card issuing](https://docs.adyen.com/issuing/add-capabilities#capability-levels), have different levels. Levels increase the capability, but also require additional checks and increased monitoring. Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public RequestedLevelEnum? RequestedLevel { get { return this._RequestedLevelOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; } + + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("allowedSettings")] + public CapabilitySettings? AllowedSettings { get { return this._AllowedSettingsOption; } set { this._AllowedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; } + + /// + /// Indicates whether the capability is requested. To check whether the legal entity is permitted to use the capability, refer to the `allowed` field. + /// + /// Indicates whether the capability is requested. To check whether the legal entity is permitted to use the capability, refer to the `allowed` field. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("requestedSettings")] + public CapabilitySettings? RequestedSettings { get { return this._RequestedSettingsOption; } set { this._RequestedSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferInstrumentsOption { get; } + + /// + /// The capability status of transfer instruments associated with the legal entity. + /// + /// The capability status of transfer instruments associated with the legal entity. + [JsonPropertyName("transferInstruments")] + public List? TransferInstruments { get { return this._TransferInstrumentsOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public string? VerificationStatus { get { return this._VerificationStatusOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntityCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" AllowedSettings: ").Append(AllowedSettings).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" RequestedSettings: ").Append(RequestedSettings).Append("\n"); + sb.Append(" TransferInstruments: ").Append(TransferInstruments).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntityCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option allowedLevel = default; + Option allowedSettings = default; + Option requested = default; + Option requestedLevel = default; + Option requestedSettings = default; + Option?> transferInstruments = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + string? allowedLevelRawValue = utf8JsonReader.GetString(); + allowedLevel = new Option(LegalEntityCapability.AllowedLevelEnum.FromStringOrDefault(allowedLevelRawValue)); + break; + case "allowedSettings": + allowedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + string? requestedLevelRawValue = utf8JsonReader.GetString(); + requestedLevel = new Option(LegalEntityCapability.RequestedLevelEnum.FromStringOrDefault(requestedLevelRawValue)); + break; + case "requestedSettings": + requestedSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstruments": + transferInstruments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationStatus": + verificationStatus = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new LegalEntityCapability(allowed, allowedLevel, allowedSettings, requested, requestedLevel, requestedSettings, transferInstruments, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntityCapability legalEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntityCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntityCapability legalEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntityCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", legalEntityCapability._AllowedOption.Value!.Value); + + if (legalEntityCapability._AllowedLevelOption.IsSet && legalEntityCapability.AllowedLevel != null) + { + string? allowedLevelRawValue = LegalEntityCapability.AllowedLevelEnum.ToJsonValue(legalEntityCapability._AllowedLevelOption.Value!.Value); + writer.WriteString("allowedLevel", allowedLevelRawValue); + } + + if (legalEntityCapability._AllowedSettingsOption.IsSet) + { + writer.WritePropertyName("allowedSettings"); + JsonSerializer.Serialize(writer, legalEntityCapability.AllowedSettings, jsonSerializerOptions); + } + if (legalEntityCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", legalEntityCapability._RequestedOption.Value!.Value); + + if (legalEntityCapability._RequestedLevelOption.IsSet && legalEntityCapability.RequestedLevel != null) + { + string? requestedLevelRawValue = LegalEntityCapability.RequestedLevelEnum.ToJsonValue(legalEntityCapability._RequestedLevelOption.Value!.Value); + writer.WriteString("requestedLevel", requestedLevelRawValue); + } + + if (legalEntityCapability._RequestedSettingsOption.IsSet) + { + writer.WritePropertyName("requestedSettings"); + JsonSerializer.Serialize(writer, legalEntityCapability.RequestedSettings, jsonSerializerOptions); + } + if (legalEntityCapability._TransferInstrumentsOption.IsSet) + { + writer.WritePropertyName("transferInstruments"); + JsonSerializer.Serialize(writer, legalEntityCapability.TransferInstruments, jsonSerializerOptions); + } + if (legalEntityCapability._VerificationStatusOption.IsSet) + if (legalEntityCapability.VerificationStatus != null) + writer.WriteString("verificationStatus", legalEntityCapability.VerificationStatus); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/LegalEntityInfo.cs b/Adyen/LegalEntityManagement/Models/LegalEntityInfo.cs new file mode 100644 index 000000000..6b700c136 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/LegalEntityInfo.cs @@ -0,0 +1,543 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// LegalEntityInfo. + /// + public partial class LegalEntityInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// individual + /// organization + /// Your reference for the legal entity, maximum 150 characters. + /// soleProprietorship + /// trust + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// unincorporatedPartnership + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonConstructor] + public LegalEntityInfo(Option?> capabilities = default, Option?> entityAssociations = default, Option individual = default, Option organization = default, Option reference = default, Option soleProprietorship = default, Option trust = default, Option type = default, Option unincorporatedPartnership = default, Option verificationPlan = default) + { + _CapabilitiesOption = capabilities; + _EntityAssociationsOption = entityAssociations; + _IndividualOption = individual; + _OrganizationOption = organization; + _ReferenceOption = reference; + _SoleProprietorshipOption = soleProprietorship; + _TrustOption = trust; + _TypeOption = type; + _UnincorporatedPartnershipOption = unincorporatedPartnership; + _VerificationPlanOption = verificationPlan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntityInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.SoleProprietorship - soleProprietorship + /// + public static readonly TypeEnum SoleProprietorship = new("soleProprietorship"); + + /// + /// TypeEnum.Trust - trust + /// + public static readonly TypeEnum Trust = new("trust"); + + /// + /// TypeEnum.UnincorporatedPartnership - unincorporatedPartnership + /// + public static readonly TypeEnum UnincorporatedPartnership = new("unincorporatedPartnership"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "soleProprietorship" => TypeEnum.SoleProprietorship, + "trust" => TypeEnum.Trust, + "unincorporatedPartnership" => TypeEnum.UnincorporatedPartnership, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.SoleProprietorship) + return "soleProprietorship"; + + if (value == TypeEnum.Trust) + return "trust"; + + if (value == TypeEnum.UnincorporatedPartnership) + return "unincorporatedPartnership"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityAssociationsOption { get; private set; } + + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + [JsonPropertyName("entityAssociations")] + public List? EntityAssociations { get { return this._EntityAssociationsOption; } set { this._EntityAssociationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndividualOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("individual")] + public Individual? Individual { get { return this._IndividualOption; } set { this._IndividualOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrganizationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("organization")] + public Organization? Organization { get { return this._OrganizationOption; } set { this._OrganizationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the legal entity, maximum 150 characters. + /// + /// Your reference for the legal entity, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SoleProprietorshipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("soleProprietorship")] + public SoleProprietorship? SoleProprietorship { get { return this._SoleProprietorshipOption; } set { this._SoleProprietorshipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("trust")] + public Trust? Trust { get { return this._TrustOption; } set { this._TrustOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnincorporatedPartnershipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("unincorporatedPartnership")] + public UnincorporatedPartnership? UnincorporatedPartnership { get { return this._UnincorporatedPartnershipOption; } set { this._UnincorporatedPartnershipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationPlanOption { get; private set; } + + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonPropertyName("verificationPlan")] + public string? VerificationPlan { get { return this._VerificationPlanOption; } set { this._VerificationPlanOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntityInfo {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" EntityAssociations: ").Append(EntityAssociations).Append("\n"); + sb.Append(" Individual: ").Append(Individual).Append("\n"); + sb.Append(" Organization: ").Append(Organization).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SoleProprietorship: ").Append(SoleProprietorship).Append("\n"); + sb.Append(" Trust: ").Append(Trust).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UnincorporatedPartnership: ").Append(UnincorporatedPartnership).Append("\n"); + sb.Append(" VerificationPlan: ").Append(VerificationPlan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntityInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option?> entityAssociations = default; + Option individual = default; + Option organization = default; + Option reference = default; + Option soleProprietorship = default; + Option trust = default; + Option type = default; + Option unincorporatedPartnership = default; + Option verificationPlan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "entityAssociations": + entityAssociations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "individual": + individual = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "organization": + organization = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "soleProprietorship": + soleProprietorship = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "trust": + trust = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(LegalEntityInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "unincorporatedPartnership": + unincorporatedPartnership = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationPlan": + verificationPlan = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new LegalEntityInfo(capabilities, entityAssociations, individual, organization, reference, soleProprietorship, trust, type, unincorporatedPartnership, verificationPlan); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntityInfo legalEntityInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntityInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntityInfo legalEntityInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntityInfo._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, legalEntityInfo.Capabilities, jsonSerializerOptions); + } + if (legalEntityInfo._EntityAssociationsOption.IsSet) + { + writer.WritePropertyName("entityAssociations"); + JsonSerializer.Serialize(writer, legalEntityInfo.EntityAssociations, jsonSerializerOptions); + } + if (legalEntityInfo._IndividualOption.IsSet) + { + writer.WritePropertyName("individual"); + JsonSerializer.Serialize(writer, legalEntityInfo.Individual, jsonSerializerOptions); + } + if (legalEntityInfo._OrganizationOption.IsSet) + { + writer.WritePropertyName("organization"); + JsonSerializer.Serialize(writer, legalEntityInfo.Organization, jsonSerializerOptions); + } + if (legalEntityInfo._ReferenceOption.IsSet) + if (legalEntityInfo.Reference != null) + writer.WriteString("reference", legalEntityInfo.Reference); + + if (legalEntityInfo._SoleProprietorshipOption.IsSet) + { + writer.WritePropertyName("soleProprietorship"); + JsonSerializer.Serialize(writer, legalEntityInfo.SoleProprietorship, jsonSerializerOptions); + } + if (legalEntityInfo._TrustOption.IsSet) + { + writer.WritePropertyName("trust"); + JsonSerializer.Serialize(writer, legalEntityInfo.Trust, jsonSerializerOptions); + } + if (legalEntityInfo._TypeOption.IsSet && legalEntityInfo.Type != null) + { + string? typeRawValue = LegalEntityInfo.TypeEnum.ToJsonValue(legalEntityInfo._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (legalEntityInfo._UnincorporatedPartnershipOption.IsSet) + { + writer.WritePropertyName("unincorporatedPartnership"); + JsonSerializer.Serialize(writer, legalEntityInfo.UnincorporatedPartnership, jsonSerializerOptions); + } + if (legalEntityInfo._VerificationPlanOption.IsSet) + if (legalEntityInfo.VerificationPlan != null) + writer.WriteString("verificationPlan", legalEntityInfo.VerificationPlan); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/LegalEntityInfoRequiredType.cs b/Adyen/LegalEntityManagement/Models/LegalEntityInfoRequiredType.cs new file mode 100644 index 000000000..df4d71a90 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/LegalEntityInfoRequiredType.cs @@ -0,0 +1,538 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// LegalEntityInfoRequiredType. + /// + public partial class LegalEntityInfoRequiredType : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// individual + /// organization + /// Your reference for the legal entity, maximum 150 characters. + /// soleProprietorship + /// trust + /// unincorporatedPartnership + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonConstructor] + public LegalEntityInfoRequiredType(TypeEnum type, Option?> capabilities = default, Option?> entityAssociations = default, Option individual = default, Option organization = default, Option reference = default, Option soleProprietorship = default, Option trust = default, Option unincorporatedPartnership = default, Option verificationPlan = default) + { + Type = type; + _CapabilitiesOption = capabilities; + _EntityAssociationsOption = entityAssociations; + _IndividualOption = individual; + _OrganizationOption = organization; + _ReferenceOption = reference; + _SoleProprietorshipOption = soleProprietorship; + _TrustOption = trust; + _UnincorporatedPartnershipOption = unincorporatedPartnership; + _VerificationPlanOption = verificationPlan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntityInfoRequiredType() + { + } + + partial void OnCreated(); + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.SoleProprietorship - soleProprietorship + /// + public static readonly TypeEnum SoleProprietorship = new("soleProprietorship"); + + /// + /// TypeEnum.Trust - trust + /// + public static readonly TypeEnum Trust = new("trust"); + + /// + /// TypeEnum.UnincorporatedPartnership - unincorporatedPartnership + /// + public static readonly TypeEnum UnincorporatedPartnership = new("unincorporatedPartnership"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "soleProprietorship" => TypeEnum.SoleProprietorship, + "trust" => TypeEnum.Trust, + "unincorporatedPartnership" => TypeEnum.UnincorporatedPartnership, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.SoleProprietorship) + return "soleProprietorship"; + + if (value == TypeEnum.Trust) + return "trust"; + + if (value == TypeEnum.UnincorporatedPartnership) + return "unincorporatedPartnership"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + /// + /// The type of legal entity. Possible values: **individual**, **organization**, **soleProprietorship**, or **trust**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform.The key is a capability required for your integration. For example, **issueCard** for Issuing. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityAssociationsOption { get; private set; } + + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + /// + /// List of legal entities associated with the current legal entity. For example, ultimate beneficial owners associated with an organization through ownership or control, or as signatories. + [JsonPropertyName("entityAssociations")] + public List? EntityAssociations { get { return this._EntityAssociationsOption; } set { this._EntityAssociationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndividualOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("individual")] + public Individual? Individual { get { return this._IndividualOption; } set { this._IndividualOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrganizationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("organization")] + public Organization? Organization { get { return this._OrganizationOption; } set { this._OrganizationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the legal entity, maximum 150 characters. + /// + /// Your reference for the legal entity, maximum 150 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SoleProprietorshipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("soleProprietorship")] + public SoleProprietorship? SoleProprietorship { get { return this._SoleProprietorshipOption; } set { this._SoleProprietorshipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("trust")] + public Trust? Trust { get { return this._TrustOption; } set { this._TrustOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnincorporatedPartnershipOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("unincorporatedPartnership")] + public UnincorporatedPartnership? UnincorporatedPartnership { get { return this._UnincorporatedPartnershipOption; } set { this._UnincorporatedPartnershipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationPlanOption { get; private set; } + + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + /// + /// A key-value pair that specifies the verification process for a legal entity. Set to **upfront** for upfront verification for [marketplaces](https://docs.adyen.com/marketplaces/verification-overview/verification-types/#upfront-verification). + [JsonPropertyName("verificationPlan")] + public string? VerificationPlan { get { return this._VerificationPlanOption; } set { this._VerificationPlanOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntityInfoRequiredType {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" EntityAssociations: ").Append(EntityAssociations).Append("\n"); + sb.Append(" Individual: ").Append(Individual).Append("\n"); + sb.Append(" Organization: ").Append(Organization).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SoleProprietorship: ").Append(SoleProprietorship).Append("\n"); + sb.Append(" Trust: ").Append(Trust).Append("\n"); + sb.Append(" UnincorporatedPartnership: ").Append(UnincorporatedPartnership).Append("\n"); + sb.Append(" VerificationPlan: ").Append(VerificationPlan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityInfoRequiredTypeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntityInfoRequiredType Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option?> capabilities = default; + Option?> entityAssociations = default; + Option individual = default; + Option organization = default; + Option reference = default; + Option soleProprietorship = default; + Option trust = default; + Option unincorporatedPartnership = default; + Option verificationPlan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(LegalEntityInfoRequiredType.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "entityAssociations": + entityAssociations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "individual": + individual = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "organization": + organization = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "soleProprietorship": + soleProprietorship = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "trust": + trust = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "unincorporatedPartnership": + unincorporatedPartnership = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationPlan": + verificationPlan = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class LegalEntityInfoRequiredType.", nameof(type)); + + return new LegalEntityInfoRequiredType(type.Value!.Value!, capabilities, entityAssociations, individual, organization, reference, soleProprietorship, trust, unincorporatedPartnership, verificationPlan); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntityInfoRequiredType legalEntityInfoRequiredType, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntityInfoRequiredType, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntityInfoRequiredType legalEntityInfoRequiredType, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntityInfoRequiredType.Type != null) + { + string? typeRawValue = LegalEntityInfoRequiredType.TypeEnum.ToJsonValue(legalEntityInfoRequiredType.Type); + writer.WriteString("type", typeRawValue); + } + + if (legalEntityInfoRequiredType._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.Capabilities, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._EntityAssociationsOption.IsSet) + { + writer.WritePropertyName("entityAssociations"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.EntityAssociations, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._IndividualOption.IsSet) + { + writer.WritePropertyName("individual"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.Individual, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._OrganizationOption.IsSet) + { + writer.WritePropertyName("organization"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.Organization, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._ReferenceOption.IsSet) + if (legalEntityInfoRequiredType.Reference != null) + writer.WriteString("reference", legalEntityInfoRequiredType.Reference); + + if (legalEntityInfoRequiredType._SoleProprietorshipOption.IsSet) + { + writer.WritePropertyName("soleProprietorship"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.SoleProprietorship, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._TrustOption.IsSet) + { + writer.WritePropertyName("trust"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.Trust, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._UnincorporatedPartnershipOption.IsSet) + { + writer.WritePropertyName("unincorporatedPartnership"); + JsonSerializer.Serialize(writer, legalEntityInfoRequiredType.UnincorporatedPartnership, jsonSerializerOptions); + } + if (legalEntityInfoRequiredType._VerificationPlanOption.IsSet) + if (legalEntityInfoRequiredType.VerificationPlan != null) + writer.WriteString("verificationPlan", legalEntityInfoRequiredType.VerificationPlan); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/NOLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/NOLocalAccountIdentification.cs new file mode 100644 index 000000000..1517429da --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/NOLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// NOLocalAccountIdentification. + /// + public partial class NOLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 11-digit bank account number, without separators or whitespace. + /// **noLocal** (default to TypeEnum.NoLocal) + [JsonConstructor] + public NOLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NOLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NoLocal - noLocal + /// + public static readonly TypeEnum NoLocal = new("noLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "noLocal" => TypeEnum.NoLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NoLocal) + return "noLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 11-digit bank account number, without separators or whitespace. + /// + /// The 11-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NOLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 11.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 11.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NOLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NOLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NOLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(type)); + + return new NOLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nOLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nOLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nOLocalAccountIdentification.AccountNumber); + + if (nOLocalAccountIdentification.Type != null) + { + string? typeRawValue = NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/NZLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/NZLocalAccountIdentification.cs new file mode 100644 index 000000000..45b21213c --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/NZLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// NZLocalAccountIdentification. + /// + public partial class NZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// **nzLocal** (default to TypeEnum.NzLocal) + [JsonConstructor] + public NZLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NzLocal - nzLocal + /// + public static readonly TypeEnum NzLocal = new("nzLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nzLocal" => TypeEnum.NzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NzLocal) + return "nzLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 16) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 16.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 15) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 15.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(type)); + + return new NZLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nZLocalAccountIdentification.AccountNumber); + + if (nZLocalAccountIdentification.Type != null) + { + string? typeRawValue = NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Name.cs b/Adyen/LegalEntityManagement/Models/Name.cs new file mode 100644 index 000000000..c7bc3241d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Name.cs @@ -0,0 +1,216 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The individual's first name. Must not be blank. + /// The individual's last name. Must not be blank. + /// The infix in the individual's name, if any. + [JsonConstructor] + public Name(string firstName, string lastName, Option infix = default) + { + FirstName = firstName; + LastName = lastName; + _InfixOption = infix; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The individual's first name. Must not be blank. + /// + /// The individual's first name. Must not be blank. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The individual's last name. Must not be blank. + /// + /// The individual's last name. Must not be blank. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InfixOption { get; private set; } + + /// + /// The infix in the individual's name, if any. + /// + /// The infix in the individual's name, if any. + [JsonPropertyName("infix")] + public string? Infix { get { return this._InfixOption; } set { this._InfixOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Infix: ").Append(Infix).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + Option infix = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "infix": + infix = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!, infix); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + + if (name._InfixOption.IsSet) + if (name.Infix != null) + writer.WriteString("infix", name.Infix); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/NumberAndBicAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/NumberAndBicAccountIdentification.cs new file mode 100644 index 000000000..7efed200b --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/NumberAndBicAccountIdentification.cs @@ -0,0 +1,352 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// NumberAndBicAccountIdentification. + /// + public partial class NumberAndBicAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// additionalBankIdentification + /// **numberAndBic** (default to TypeEnum.NumberAndBic) + [JsonConstructor] + public NumberAndBicAccountIdentification(string accountNumber, string bic, Option additionalBankIdentification = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _AdditionalBankIdentificationOption = additionalBankIdentification; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NumberAndBicAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NumberAndBic - numberAndBic + /// + public static readonly TypeEnum NumberAndBic = new("numberAndBic"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "numberAndBic" => TypeEnum.NumberAndBic, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NumberAndBic) + return "numberAndBic"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalBankIdentificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalBankIdentification")] + public AdditionalBankIdentification? AdditionalBankIdentification { get { return this._AdditionalBankIdentificationOption; } set { this._AdditionalBankIdentificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberAndBicAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" AdditionalBankIdentification: ").Append(AdditionalBankIdentification).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 34) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 34.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NumberAndBicAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NumberAndBicAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option additionalBankIdentification = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "additionalBankIdentification": + additionalBankIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NumberAndBicAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(bic)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(type)); + + return new NumberAndBicAccountIdentification(accountNumber.Value!, bic.Value!, additionalBankIdentification, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, numberAndBicAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (numberAndBicAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", numberAndBicAccountIdentification.AccountNumber); + + if (numberAndBicAccountIdentification.Bic != null) + writer.WriteString("bic", numberAndBicAccountIdentification.Bic); + + if (numberAndBicAccountIdentification._AdditionalBankIdentificationOption.IsSet) + { + writer.WritePropertyName("additionalBankIdentification"); + JsonSerializer.Serialize(writer, numberAndBicAccountIdentification.AdditionalBankIdentification, jsonSerializerOptions); + } + if (numberAndBicAccountIdentification.Type != null) + { + string? typeRawValue = NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OnboardingLink.cs b/Adyen/LegalEntityManagement/Models/OnboardingLink.cs new file mode 100644 index 000000000..8d562f236 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OnboardingLink.cs @@ -0,0 +1,177 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OnboardingLink. + /// + public partial class OnboardingLink : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The URL of the hosted onboarding page where you need to redirect your user. This URL: - Expires after 4 minutes. - Can only be used once. - Can only be clicked once by the user. If the link expires, you need to create a new link. + [JsonConstructor] + public OnboardingLink(Option url = default) + { + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OnboardingLink() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// The URL of the hosted onboarding page where you need to redirect your user. This URL: - Expires after 4 minutes. - Can only be used once. - Can only be clicked once by the user. If the link expires, you need to create a new link. + /// + /// The URL of the hosted onboarding page where you need to redirect your user. This URL: - Expires after 4 minutes. - Can only be used once. - Can only be clicked once by the user. If the link expires, you need to create a new link. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OnboardingLink {\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OnboardingLinkJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OnboardingLink Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new OnboardingLink(url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OnboardingLink onboardingLink, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, onboardingLink, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OnboardingLink onboardingLink, JsonSerializerOptions jsonSerializerOptions) + { + + if (onboardingLink._UrlOption.IsSet) + if (onboardingLink.Url != null) + writer.WriteString("url", onboardingLink.Url); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OnboardingLinkInfo.cs b/Adyen/LegalEntityManagement/Models/OnboardingLinkInfo.cs new file mode 100644 index 000000000..548a9c496 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OnboardingLinkInfo.cs @@ -0,0 +1,252 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OnboardingLinkInfo. + /// + public partial class OnboardingLinkInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The language that will be used for the page, specified by a combination of two letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language and [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. See possible valuesfor [marketplaces](https://docs.adyen.com/marketplaces/onboard-users/hosted#supported-languages) or [platforms](https://docs.adyen.com/platforms/onboard-users/hosted#supported-languages). If not specified in the request or if the language is not supported, the page uses the browser language. If the browser language is not supported, the page uses **en-US** by default. + /// The URL where the user is redirected after they complete hosted onboarding. + /// settings + /// The unique identifier of the hosted onboarding theme. + [JsonConstructor] + public OnboardingLinkInfo(Option locale = default, Option redirectUrl = default, Option settings = default, Option themeId = default) + { + _LocaleOption = locale; + _RedirectUrlOption = redirectUrl; + _SettingsOption = settings; + _ThemeIdOption = themeId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OnboardingLinkInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LocaleOption { get; private set; } + + /// + /// The language that will be used for the page, specified by a combination of two letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language and [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. See possible valuesfor [marketplaces](https://docs.adyen.com/marketplaces/onboard-users/hosted#supported-languages) or [platforms](https://docs.adyen.com/platforms/onboard-users/hosted#supported-languages). If not specified in the request or if the language is not supported, the page uses the browser language. If the browser language is not supported, the page uses **en-US** by default. + /// + /// The language that will be used for the page, specified by a combination of two letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language and [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes. See possible valuesfor [marketplaces](https://docs.adyen.com/marketplaces/onboard-users/hosted#supported-languages) or [platforms](https://docs.adyen.com/platforms/onboard-users/hosted#supported-languages). If not specified in the request or if the language is not supported, the page uses the browser language. If the browser language is not supported, the page uses **en-US** by default. + [JsonPropertyName("locale")] + public string? Locale { get { return this._LocaleOption; } set { this._LocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RedirectUrlOption { get; private set; } + + /// + /// The URL where the user is redirected after they complete hosted onboarding. + /// + /// The URL where the user is redirected after they complete hosted onboarding. + [JsonPropertyName("redirectUrl")] + public string? RedirectUrl { get { return this._RedirectUrlOption; } set { this._RedirectUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("settings")] + public OnboardingLinkSettings? Settings { get { return this._SettingsOption; } set { this._SettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThemeIdOption { get; private set; } + + /// + /// The unique identifier of the hosted onboarding theme. + /// + /// The unique identifier of the hosted onboarding theme. + [JsonPropertyName("themeId")] + public string? ThemeId { get { return this._ThemeIdOption; } set { this._ThemeIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OnboardingLinkInfo {\n"); + sb.Append(" Locale: ").Append(Locale).Append("\n"); + sb.Append(" RedirectUrl: ").Append(RedirectUrl).Append("\n"); + sb.Append(" Settings: ").Append(Settings).Append("\n"); + sb.Append(" ThemeId: ").Append(ThemeId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OnboardingLinkInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OnboardingLinkInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option locale = default; + Option redirectUrl = default; + Option settings = default; + Option themeId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "locale": + locale = new Option(utf8JsonReader.GetString()!); + break; + case "redirectUrl": + redirectUrl = new Option(utf8JsonReader.GetString()!); + break; + case "settings": + settings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "themeId": + themeId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new OnboardingLinkInfo(locale, redirectUrl, settings, themeId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OnboardingLinkInfo onboardingLinkInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, onboardingLinkInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OnboardingLinkInfo onboardingLinkInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (onboardingLinkInfo._LocaleOption.IsSet) + if (onboardingLinkInfo.Locale != null) + writer.WriteString("locale", onboardingLinkInfo.Locale); + + if (onboardingLinkInfo._RedirectUrlOption.IsSet) + if (onboardingLinkInfo.RedirectUrl != null) + writer.WriteString("redirectUrl", onboardingLinkInfo.RedirectUrl); + + if (onboardingLinkInfo._SettingsOption.IsSet) + { + writer.WritePropertyName("settings"); + JsonSerializer.Serialize(writer, onboardingLinkInfo.Settings, jsonSerializerOptions); + } + if (onboardingLinkInfo._ThemeIdOption.IsSet) + if (onboardingLinkInfo.ThemeId != null) + writer.WriteString("themeId", onboardingLinkInfo.ThemeId); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OnboardingLinkSettings.cs b/Adyen/LegalEntityManagement/Models/OnboardingLinkSettings.cs new file mode 100644 index 000000000..62aedd2d1 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OnboardingLinkSettings.cs @@ -0,0 +1,562 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OnboardingLinkSettings. + /// + public partial class OnboardingLinkSettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of countries the user can choose from in hosted onboarding when `editPrefilledCountry` is allowed. The value must be in the two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code format. The array is empty by default, allowing all [countries and regions supported by hosted onboarding](https://docs.adyen.com/platforms/onboard-users/#hosted-onboarding). + /// Default value: **false** Indicates if the user can select the format for their payout account (if applicable). + /// Default value: **true** Indicates whether the debug user interface (UI) is enabled. The debug UI provides information for your support staff to diagnose and resolve user issues during onboarding. It can be accessed using a keyboard shortcut. + /// Default value: **false** Indicates if the user can select a payout account in a different EU/EEA location (including Switzerland and the UK) than the location of their legal entity. + /// Default value: **true** Indicates if the user can change their legal entity type. + /// Default value: **true** Indicates if the user can change the country of their legal entity's address, for example the registered address of an organization. + /// Default value: **false** Indicates if only users above the age of 18 can be onboarded. + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the individual legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the organization legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the sole proprietorship legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the trust legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// Default value: **true** Indicates if the user can initiate the verification process through open banking providers, like Plaid or Tink. + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **ecomMoto** sales channel type. + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **eCommerce** sales channel type. + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **pos** sales channel type. + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **posMoto** sales channel type. + /// The maximum number of transfer instruments the user can create. + [JsonConstructor] + public OnboardingLinkSettings(Option?> acceptedCountries = default, Option allowBankAccountFormatSelection = default, Option allowDebugUi = default, Option allowIntraRegionCrossBorderPayout = default, Option changeLegalEntityType = default, Option editPrefilledCountry = default, Option enforceLegalAge = default, Option hideOnboardingIntroductionIndividual = default, Option hideOnboardingIntroductionOrganization = default, Option hideOnboardingIntroductionSoleProprietor = default, Option hideOnboardingIntroductionTrust = default, Option instantBankVerification = default, Option requirePciSignEcomMoto = default, Option requirePciSignEcommerce = default, Option requirePciSignPos = default, Option requirePciSignPosMoto = default, Option transferInstrumentLimit = default) + { + _AcceptedCountriesOption = acceptedCountries; + _AllowBankAccountFormatSelectionOption = allowBankAccountFormatSelection; + _AllowDebugUiOption = allowDebugUi; + _AllowIntraRegionCrossBorderPayoutOption = allowIntraRegionCrossBorderPayout; + _ChangeLegalEntityTypeOption = changeLegalEntityType; + _EditPrefilledCountryOption = editPrefilledCountry; + _EnforceLegalAgeOption = enforceLegalAge; + _HideOnboardingIntroductionIndividualOption = hideOnboardingIntroductionIndividual; + _HideOnboardingIntroductionOrganizationOption = hideOnboardingIntroductionOrganization; + _HideOnboardingIntroductionSoleProprietorOption = hideOnboardingIntroductionSoleProprietor; + _HideOnboardingIntroductionTrustOption = hideOnboardingIntroductionTrust; + _InstantBankVerificationOption = instantBankVerification; + _RequirePciSignEcomMotoOption = requirePciSignEcomMoto; + _RequirePciSignEcommerceOption = requirePciSignEcommerce; + _RequirePciSignPosOption = requirePciSignPos; + _RequirePciSignPosMotoOption = requirePciSignPosMoto; + _TransferInstrumentLimitOption = transferInstrumentLimit; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OnboardingLinkSettings() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AcceptedCountriesOption { get; private set; } + + /// + /// The list of countries the user can choose from in hosted onboarding when `editPrefilledCountry` is allowed. The value must be in the two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code format. The array is empty by default, allowing all [countries and regions supported by hosted onboarding](https://docs.adyen.com/platforms/onboard-users/#hosted-onboarding). + /// + /// The list of countries the user can choose from in hosted onboarding when `editPrefilledCountry` is allowed. The value must be in the two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code format. The array is empty by default, allowing all [countries and regions supported by hosted onboarding](https://docs.adyen.com/platforms/onboard-users/#hosted-onboarding). + [JsonPropertyName("acceptedCountries")] + public List? AcceptedCountries { get { return this._AcceptedCountriesOption; } set { this._AcceptedCountriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowBankAccountFormatSelectionOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user can select the format for their payout account (if applicable). + /// + /// Default value: **false** Indicates if the user can select the format for their payout account (if applicable). + [JsonPropertyName("allowBankAccountFormatSelection")] + public bool? AllowBankAccountFormatSelection { get { return this._AllowBankAccountFormatSelectionOption; } set { this._AllowBankAccountFormatSelectionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowDebugUiOption { get; private set; } + + /// + /// Default value: **true** Indicates whether the debug user interface (UI) is enabled. The debug UI provides information for your support staff to diagnose and resolve user issues during onboarding. It can be accessed using a keyboard shortcut. + /// + /// Default value: **true** Indicates whether the debug user interface (UI) is enabled. The debug UI provides information for your support staff to diagnose and resolve user issues during onboarding. It can be accessed using a keyboard shortcut. + [JsonPropertyName("allowDebugUi")] + public bool? AllowDebugUi { get { return this._AllowDebugUiOption; } set { this._AllowDebugUiOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowIntraRegionCrossBorderPayoutOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user can select a payout account in a different EU/EEA location (including Switzerland and the UK) than the location of their legal entity. + /// + /// Default value: **false** Indicates if the user can select a payout account in a different EU/EEA location (including Switzerland and the UK) than the location of their legal entity. + [JsonPropertyName("allowIntraRegionCrossBorderPayout")] + public bool? AllowIntraRegionCrossBorderPayout { get { return this._AllowIntraRegionCrossBorderPayoutOption; } set { this._AllowIntraRegionCrossBorderPayoutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChangeLegalEntityTypeOption { get; private set; } + + /// + /// Default value: **true** Indicates if the user can change their legal entity type. + /// + /// Default value: **true** Indicates if the user can change their legal entity type. + [JsonPropertyName("changeLegalEntityType")] + public bool? ChangeLegalEntityType { get { return this._ChangeLegalEntityTypeOption; } set { this._ChangeLegalEntityTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EditPrefilledCountryOption { get; private set; } + + /// + /// Default value: **true** Indicates if the user can change the country of their legal entity's address, for example the registered address of an organization. + /// + /// Default value: **true** Indicates if the user can change the country of their legal entity's address, for example the registered address of an organization. + [JsonPropertyName("editPrefilledCountry")] + public bool? EditPrefilledCountry { get { return this._EditPrefilledCountryOption; } set { this._EditPrefilledCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnforceLegalAgeOption { get; private set; } + + /// + /// Default value: **false** Indicates if only users above the age of 18 can be onboarded. + /// + /// Default value: **false** Indicates if only users above the age of 18 can be onboarded. + [JsonPropertyName("enforceLegalAge")] + public bool? EnforceLegalAge { get { return this._EnforceLegalAgeOption; } set { this._EnforceLegalAgeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HideOnboardingIntroductionIndividualOption { get; private set; } + + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the individual legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the individual legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + [JsonPropertyName("hideOnboardingIntroductionIndividual")] + public bool? HideOnboardingIntroductionIndividual { get { return this._HideOnboardingIntroductionIndividualOption; } set { this._HideOnboardingIntroductionIndividualOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HideOnboardingIntroductionOrganizationOption { get; private set; } + + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the organization legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the organization legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + [JsonPropertyName("hideOnboardingIntroductionOrganization")] + public bool? HideOnboardingIntroductionOrganization { get { return this._HideOnboardingIntroductionOrganizationOption; } set { this._HideOnboardingIntroductionOrganizationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HideOnboardingIntroductionSoleProprietorOption { get; private set; } + + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the sole proprietorship legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the sole proprietorship legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + [JsonPropertyName("hideOnboardingIntroductionSoleProprietor")] + public bool? HideOnboardingIntroductionSoleProprietor { get { return this._HideOnboardingIntroductionSoleProprietorOption; } set { this._HideOnboardingIntroductionSoleProprietorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HideOnboardingIntroductionTrustOption { get; private set; } + + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the trust legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + /// + /// Default value: **true** Indicates whether the introduction screen is hidden for the user of the trust legal entity type. The introduction screen provides brief instructions for the subsequent steps in the hosted onboarding process. + [JsonPropertyName("hideOnboardingIntroductionTrust")] + public bool? HideOnboardingIntroductionTrust { get { return this._HideOnboardingIntroductionTrustOption; } set { this._HideOnboardingIntroductionTrustOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstantBankVerificationOption { get; private set; } + + /// + /// Default value: **true** Indicates if the user can initiate the verification process through open banking providers, like Plaid or Tink. + /// + /// Default value: **true** Indicates if the user can initiate the verification process through open banking providers, like Plaid or Tink. + [JsonPropertyName("instantBankVerification")] + public bool? InstantBankVerification { get { return this._InstantBankVerificationOption; } set { this._InstantBankVerificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequirePciSignEcomMotoOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **ecomMoto** sales channel type. + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **ecomMoto** sales channel type. + [JsonPropertyName("requirePciSignEcomMoto")] + public bool? RequirePciSignEcomMoto { get { return this._RequirePciSignEcomMotoOption; } set { this._RequirePciSignEcomMotoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequirePciSignEcommerceOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **eCommerce** sales channel type. + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **eCommerce** sales channel type. + [JsonPropertyName("requirePciSignEcommerce")] + public bool? RequirePciSignEcommerce { get { return this._RequirePciSignEcommerceOption; } set { this._RequirePciSignEcommerceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequirePciSignPosOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **pos** sales channel type. + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **pos** sales channel type. + [JsonPropertyName("requirePciSignPos")] + public bool? RequirePciSignPos { get { return this._RequirePciSignPosOption; } set { this._RequirePciSignPosOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequirePciSignPosMotoOption { get; private set; } + + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **posMoto** sales channel type. + /// + /// Default value: **false** Indicates if the user is required to sign a PCI questionnaires for the **posMoto** sales channel type. + [JsonPropertyName("requirePciSignPosMoto")] + public bool? RequirePciSignPosMoto { get { return this._RequirePciSignPosMotoOption; } set { this._RequirePciSignPosMotoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentLimitOption { get; private set; } + + /// + /// The maximum number of transfer instruments the user can create. + /// + /// The maximum number of transfer instruments the user can create. + [JsonPropertyName("transferInstrumentLimit")] + public int? TransferInstrumentLimit { get { return this._TransferInstrumentLimitOption; } set { this._TransferInstrumentLimitOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OnboardingLinkSettings {\n"); + sb.Append(" AcceptedCountries: ").Append(AcceptedCountries).Append("\n"); + sb.Append(" AllowBankAccountFormatSelection: ").Append(AllowBankAccountFormatSelection).Append("\n"); + sb.Append(" AllowDebugUi: ").Append(AllowDebugUi).Append("\n"); + sb.Append(" AllowIntraRegionCrossBorderPayout: ").Append(AllowIntraRegionCrossBorderPayout).Append("\n"); + sb.Append(" ChangeLegalEntityType: ").Append(ChangeLegalEntityType).Append("\n"); + sb.Append(" EditPrefilledCountry: ").Append(EditPrefilledCountry).Append("\n"); + sb.Append(" EnforceLegalAge: ").Append(EnforceLegalAge).Append("\n"); + sb.Append(" HideOnboardingIntroductionIndividual: ").Append(HideOnboardingIntroductionIndividual).Append("\n"); + sb.Append(" HideOnboardingIntroductionOrganization: ").Append(HideOnboardingIntroductionOrganization).Append("\n"); + sb.Append(" HideOnboardingIntroductionSoleProprietor: ").Append(HideOnboardingIntroductionSoleProprietor).Append("\n"); + sb.Append(" HideOnboardingIntroductionTrust: ").Append(HideOnboardingIntroductionTrust).Append("\n"); + sb.Append(" InstantBankVerification: ").Append(InstantBankVerification).Append("\n"); + sb.Append(" RequirePciSignEcomMoto: ").Append(RequirePciSignEcomMoto).Append("\n"); + sb.Append(" RequirePciSignEcommerce: ").Append(RequirePciSignEcommerce).Append("\n"); + sb.Append(" RequirePciSignPos: ").Append(RequirePciSignPos).Append("\n"); + sb.Append(" RequirePciSignPosMoto: ").Append(RequirePciSignPosMoto).Append("\n"); + sb.Append(" TransferInstrumentLimit: ").Append(TransferInstrumentLimit).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OnboardingLinkSettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OnboardingLinkSettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> acceptedCountries = default; + Option allowBankAccountFormatSelection = default; + Option allowDebugUi = default; + Option allowIntraRegionCrossBorderPayout = default; + Option changeLegalEntityType = default; + Option editPrefilledCountry = default; + Option enforceLegalAge = default; + Option hideOnboardingIntroductionIndividual = default; + Option hideOnboardingIntroductionOrganization = default; + Option hideOnboardingIntroductionSoleProprietor = default; + Option hideOnboardingIntroductionTrust = default; + Option instantBankVerification = default; + Option requirePciSignEcomMoto = default; + Option requirePciSignEcommerce = default; + Option requirePciSignPos = default; + Option requirePciSignPosMoto = default; + Option transferInstrumentLimit = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptedCountries": + acceptedCountries = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowBankAccountFormatSelection": + allowBankAccountFormatSelection = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowDebugUi": + allowDebugUi = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowIntraRegionCrossBorderPayout": + allowIntraRegionCrossBorderPayout = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "changeLegalEntityType": + changeLegalEntityType = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "editPrefilledCountry": + editPrefilledCountry = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enforceLegalAge": + enforceLegalAge = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hideOnboardingIntroductionIndividual": + hideOnboardingIntroductionIndividual = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hideOnboardingIntroductionOrganization": + hideOnboardingIntroductionOrganization = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hideOnboardingIntroductionSoleProprietor": + hideOnboardingIntroductionSoleProprietor = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hideOnboardingIntroductionTrust": + hideOnboardingIntroductionTrust = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "instantBankVerification": + instantBankVerification = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requirePciSignEcomMoto": + requirePciSignEcomMoto = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requirePciSignEcommerce": + requirePciSignEcommerce = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requirePciSignPos": + requirePciSignPos = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requirePciSignPosMoto": + requirePciSignPosMoto = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "transferInstrumentLimit": + transferInstrumentLimit = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new OnboardingLinkSettings(acceptedCountries, allowBankAccountFormatSelection, allowDebugUi, allowIntraRegionCrossBorderPayout, changeLegalEntityType, editPrefilledCountry, enforceLegalAge, hideOnboardingIntroductionIndividual, hideOnboardingIntroductionOrganization, hideOnboardingIntroductionSoleProprietor, hideOnboardingIntroductionTrust, instantBankVerification, requirePciSignEcomMoto, requirePciSignEcommerce, requirePciSignPos, requirePciSignPosMoto, transferInstrumentLimit); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OnboardingLinkSettings onboardingLinkSettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, onboardingLinkSettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OnboardingLinkSettings onboardingLinkSettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (onboardingLinkSettings._AcceptedCountriesOption.IsSet) + { + writer.WritePropertyName("acceptedCountries"); + JsonSerializer.Serialize(writer, onboardingLinkSettings.AcceptedCountries, jsonSerializerOptions); + } + if (onboardingLinkSettings._AllowBankAccountFormatSelectionOption.IsSet) + writer.WriteBoolean("allowBankAccountFormatSelection", onboardingLinkSettings._AllowBankAccountFormatSelectionOption.Value!.Value); + + if (onboardingLinkSettings._AllowDebugUiOption.IsSet) + writer.WriteBoolean("allowDebugUi", onboardingLinkSettings._AllowDebugUiOption.Value!.Value); + + if (onboardingLinkSettings._AllowIntraRegionCrossBorderPayoutOption.IsSet) + writer.WriteBoolean("allowIntraRegionCrossBorderPayout", onboardingLinkSettings._AllowIntraRegionCrossBorderPayoutOption.Value!.Value); + + if (onboardingLinkSettings._ChangeLegalEntityTypeOption.IsSet) + writer.WriteBoolean("changeLegalEntityType", onboardingLinkSettings._ChangeLegalEntityTypeOption.Value!.Value); + + if (onboardingLinkSettings._EditPrefilledCountryOption.IsSet) + writer.WriteBoolean("editPrefilledCountry", onboardingLinkSettings._EditPrefilledCountryOption.Value!.Value); + + if (onboardingLinkSettings._EnforceLegalAgeOption.IsSet) + writer.WriteBoolean("enforceLegalAge", onboardingLinkSettings._EnforceLegalAgeOption.Value!.Value); + + if (onboardingLinkSettings._HideOnboardingIntroductionIndividualOption.IsSet) + writer.WriteBoolean("hideOnboardingIntroductionIndividual", onboardingLinkSettings._HideOnboardingIntroductionIndividualOption.Value!.Value); + + if (onboardingLinkSettings._HideOnboardingIntroductionOrganizationOption.IsSet) + writer.WriteBoolean("hideOnboardingIntroductionOrganization", onboardingLinkSettings._HideOnboardingIntroductionOrganizationOption.Value!.Value); + + if (onboardingLinkSettings._HideOnboardingIntroductionSoleProprietorOption.IsSet) + writer.WriteBoolean("hideOnboardingIntroductionSoleProprietor", onboardingLinkSettings._HideOnboardingIntroductionSoleProprietorOption.Value!.Value); + + if (onboardingLinkSettings._HideOnboardingIntroductionTrustOption.IsSet) + writer.WriteBoolean("hideOnboardingIntroductionTrust", onboardingLinkSettings._HideOnboardingIntroductionTrustOption.Value!.Value); + + if (onboardingLinkSettings._InstantBankVerificationOption.IsSet) + writer.WriteBoolean("instantBankVerification", onboardingLinkSettings._InstantBankVerificationOption.Value!.Value); + + if (onboardingLinkSettings._RequirePciSignEcomMotoOption.IsSet) + writer.WriteBoolean("requirePciSignEcomMoto", onboardingLinkSettings._RequirePciSignEcomMotoOption.Value!.Value); + + if (onboardingLinkSettings._RequirePciSignEcommerceOption.IsSet) + writer.WriteBoolean("requirePciSignEcommerce", onboardingLinkSettings._RequirePciSignEcommerceOption.Value!.Value); + + if (onboardingLinkSettings._RequirePciSignPosOption.IsSet) + writer.WriteBoolean("requirePciSignPos", onboardingLinkSettings._RequirePciSignPosOption.Value!.Value); + + if (onboardingLinkSettings._RequirePciSignPosMotoOption.IsSet) + writer.WriteBoolean("requirePciSignPosMoto", onboardingLinkSettings._RequirePciSignPosMotoOption.Value!.Value); + + if (onboardingLinkSettings._TransferInstrumentLimitOption.IsSet) + writer.WriteNumber("transferInstrumentLimit", onboardingLinkSettings._TransferInstrumentLimitOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OnboardingTheme.cs b/Adyen/LegalEntityManagement/Models/OnboardingTheme.cs new file mode 100644 index 000000000..28e42bf55 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OnboardingTheme.cs @@ -0,0 +1,268 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OnboardingTheme. + /// + public partial class OnboardingTheme : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The creation date of the theme. + /// The unique identifier of the theme. + /// The properties of the theme. + /// The description of the theme. + /// The date when the theme was last updated. + [JsonConstructor] + public OnboardingTheme(DateTimeOffset createdAt, string id, Dictionary properties, Option description = default, Option updatedAt = default) + { + CreatedAt = createdAt; + Id = id; + Properties = properties; + _DescriptionOption = description; + _UpdatedAtOption = updatedAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OnboardingTheme() + { + } + + partial void OnCreated(); + + /// + /// The creation date of the theme. + /// + /// The creation date of the theme. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// The unique identifier of the theme. + /// + /// The unique identifier of the theme. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The properties of the theme. + /// + /// The properties of the theme. + [JsonPropertyName("properties")] + public Dictionary Properties { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the theme. + /// + /// The description of the theme. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdatedAtOption { get; private set; } + + /// + /// The date when the theme was last updated. + /// + /// The date when the theme was last updated. + [JsonPropertyName("updatedAt")] + public DateTimeOffset? UpdatedAt { get { return this._UpdatedAtOption; } set { this._UpdatedAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OnboardingTheme {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Properties: ").Append(Properties).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OnboardingThemeJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdatedAt. + /// + public static string UpdatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OnboardingTheme Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option id = default; + Option?> properties = default; + Option description = default; + Option updatedAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "properties": + properties = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "updatedAt": + updatedAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class OnboardingTheme.", nameof(createdAt)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class OnboardingTheme.", nameof(id)); + + if (!properties.IsSet) + throw new ArgumentException("Property is required for class OnboardingTheme.", nameof(properties)); + + return new OnboardingTheme(createdAt.Value!.Value!, id.Value!, properties.Value!, description, updatedAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OnboardingTheme onboardingTheme, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, onboardingTheme, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OnboardingTheme onboardingTheme, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", onboardingTheme.CreatedAt.ToString(CreatedAtFormat)); + + if (onboardingTheme.Id != null) + writer.WriteString("id", onboardingTheme.Id); + + writer.WritePropertyName("properties"); + JsonSerializer.Serialize(writer, onboardingTheme.Properties, jsonSerializerOptions); + if (onboardingTheme._DescriptionOption.IsSet) + if (onboardingTheme.Description != null) + writer.WriteString("description", onboardingTheme.Description); + + if (onboardingTheme._UpdatedAtOption.IsSet) + writer.WriteString("updatedAt", onboardingTheme._UpdatedAtOption.Value!.Value.ToString(UpdatedAtFormat)); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OnboardingThemes.cs b/Adyen/LegalEntityManagement/Models/OnboardingThemes.cs new file mode 100644 index 000000000..57e403484 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OnboardingThemes.cs @@ -0,0 +1,220 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OnboardingThemes. + /// + public partial class OnboardingThemes : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of onboarding themes. + /// The next page. Only present if there is a next page. + /// The previous page. Only present if there is a previous page. + [JsonConstructor] + public OnboardingThemes(List themes, Option next = default, Option previous = default) + { + Themes = themes; + _NextOption = next; + _PreviousOption = previous; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OnboardingThemes() + { + } + + partial void OnCreated(); + + /// + /// List of onboarding themes. + /// + /// List of onboarding themes. + [JsonPropertyName("themes")] + public List Themes { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NextOption { get; private set; } + + /// + /// The next page. Only present if there is a next page. + /// + /// The next page. Only present if there is a next page. + [JsonPropertyName("next")] + public string? Next { get { return this._NextOption; } set { this._NextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreviousOption { get; private set; } + + /// + /// The previous page. Only present if there is a previous page. + /// + /// The previous page. Only present if there is a previous page. + [JsonPropertyName("previous")] + public string? Previous { get { return this._PreviousOption; } set { this._PreviousOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OnboardingThemes {\n"); + sb.Append(" Themes: ").Append(Themes).Append("\n"); + sb.Append(" Next: ").Append(Next).Append("\n"); + sb.Append(" Previous: ").Append(Previous).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OnboardingThemesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OnboardingThemes Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> themes = default; + Option next = default; + Option previous = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "themes": + themes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next": + next = new Option(utf8JsonReader.GetString()!); + break; + case "previous": + previous = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!themes.IsSet) + throw new ArgumentException("Property is required for class OnboardingThemes.", nameof(themes)); + + return new OnboardingThemes(themes.Value!, next, previous); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OnboardingThemes onboardingThemes, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, onboardingThemes, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OnboardingThemes onboardingThemes, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("themes"); + JsonSerializer.Serialize(writer, onboardingThemes.Themes, jsonSerializerOptions); + if (onboardingThemes._NextOption.IsSet) + if (onboardingThemes.Next != null) + writer.WriteString("next", onboardingThemes.Next); + + if (onboardingThemes._PreviousOption.IsSet) + if (onboardingThemes.Previous != null) + writer.WriteString("previous", onboardingThemes.Previous); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Organization.cs b/Adyen/LegalEntityManagement/Models/Organization.cs new file mode 100644 index 000000000..22a4e7057 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Organization.cs @@ -0,0 +1,1458 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Organization. + /// + public partial class Organization : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The organization's legal name. + /// registeredAddress + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// The date when the organization was incorporated in YYYY-MM-DD format. + /// Required if the value of `statusOfLegalProceeding` is one of the following: **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** The date at which a legal proceeding was initiated, in **YYYY-MM-DD** format. Example: **2000-02-12** + /// Your description for the organization. + /// The organization's trading name, if different from the registered legal name. + /// Set this to **true** if the organization or legal arrangement does not have a `Doing business as` name. + /// The sector of the economy the legal entity operates within, represented by a 2-4 digit code that may include a \".\". Example: 45.11 You can locate economic sector codes for your area by referencing codes defined by the NACE (Nomenclature of Economic Activities) used in the European Union. + /// The email address of the legal entity. + /// The financial report information of the organization. + /// The global legal entity identifier for the organization. + /// Indicates that the registered business address is also the company's headquarters. + /// The institutional sector the organization operates within. + /// The type of business entity as defined in the national legal system. Use a legal form listed within the accepted legal forms compiled by the Central Bank of Europe. + /// phone + /// principalPlaceOfBusiness + /// The organization's registration number. + /// Set this to **true** if the organization does not have a registration number available. Only applicable for organizations in New Zealand, and incorporated partnerships and government organizations in Australia. + /// The status of any current or past legal action taken against the legal entity. Possible values: **noLegalActionsTaken**, **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** If the value of this field is **noLegalActionsTaken**, then `dateOfInitiationOfLegalProceeding` is not required. Otherwise, it is required. + /// stockData + /// support + /// The tax information of the organization. + /// taxReportingClassification + /// Type of organization. Possible values: **associationIncorporated**, **governmentalOrganization**, **listedPublicCompany**, **nonProfit**, **partnershipIncorporated**, **privateCompany**. + /// The reason the organization has not provided a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// The organization's VAT number. + /// webData + [JsonConstructor] + public Organization(string legalName, Address registeredAddress, Option countryOfGoverningLaw = default, Option dateOfIncorporation = default, Option dateOfInitiationOfLegalProceeding = default, Option description = default, Option doingBusinessAs = default, Option doingBusinessAsAbsent = default, Option economicSector = default, Option email = default, Option?> financialReports = default, Option globalLegalEntityIdentifier = default, Option headOfficeIndicator = default, Option institutionalSector = default, Option legalForm = default, Option phone = default, Option principalPlaceOfBusiness = default, Option registrationNumber = default, Option registrationNumberAbsent = default, Option statusOfLegalProceeding = default, Option stockData = default, Option support = default, Option?> taxInformation = default, Option taxReportingClassification = default, Option type = default, Option vatAbsenceReason = default, Option vatNumber = default, Option webData = default) + { + LegalName = legalName; + RegisteredAddress = registeredAddress; + _CountryOfGoverningLawOption = countryOfGoverningLaw; + _DateOfIncorporationOption = dateOfIncorporation; + _DateOfInitiationOfLegalProceedingOption = dateOfInitiationOfLegalProceeding; + _DescriptionOption = description; + _DoingBusinessAsOption = doingBusinessAs; + _DoingBusinessAsAbsentOption = doingBusinessAsAbsent; + _EconomicSectorOption = economicSector; + _EmailOption = email; + _FinancialReportsOption = financialReports; + _GlobalLegalEntityIdentifierOption = globalLegalEntityIdentifier; + _HeadOfficeIndicatorOption = headOfficeIndicator; + _InstitutionalSectorOption = institutionalSector; + _LegalFormOption = legalForm; + _PhoneOption = phone; + _PrincipalPlaceOfBusinessOption = principalPlaceOfBusiness; + _RegistrationNumberOption = registrationNumber; + _RegistrationNumberAbsentOption = registrationNumberAbsent; + _StatusOfLegalProceedingOption = statusOfLegalProceeding; + _StockDataOption = stockData; + _SupportOption = support; + _TaxInformationOption = taxInformation; + _TaxReportingClassificationOption = taxReportingClassification; + _TypeOption = type; + _VatAbsenceReasonOption = vatAbsenceReason; + _VatNumberOption = vatNumber; + _WebDataOption = webData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Organization() + { + } + + partial void OnCreated(); + + /// + /// The institutional sector the organization operates within. + /// + /// The institutional sector the organization operates within. + [JsonConverter(typeof(InstitutionalSectorEnumJsonConverter))] + public class InstitutionalSectorEnum : IEnum + { + /// + /// Returns the value of the InstitutionalSectorEnum. + /// + public string? Value { get; set; } + + /// + /// InstitutionalSectorEnum.NonFinancialCorporation - nonFinancialCorporation + /// + public static readonly InstitutionalSectorEnum NonFinancialCorporation = new("nonFinancialCorporation"); + + /// + /// InstitutionalSectorEnum.CentralBank - centralBank + /// + public static readonly InstitutionalSectorEnum CentralBank = new("centralBank"); + + /// + /// InstitutionalSectorEnum.CreditInstitutions - creditInstitutions + /// + public static readonly InstitutionalSectorEnum CreditInstitutions = new("creditInstitutions"); + + /// + /// InstitutionalSectorEnum.DepositTakingCorporations - depositTakingCorporations + /// + public static readonly InstitutionalSectorEnum DepositTakingCorporations = new("depositTakingCorporations"); + + /// + /// InstitutionalSectorEnum.MoneyMarketFunds - moneyMarketFunds + /// + public static readonly InstitutionalSectorEnum MoneyMarketFunds = new("moneyMarketFunds"); + + /// + /// InstitutionalSectorEnum.NonMMFInvestmentFunds - nonMMFInvestmentFunds + /// + public static readonly InstitutionalSectorEnum NonMMFInvestmentFunds = new("nonMMFInvestmentFunds"); + + /// + /// InstitutionalSectorEnum.FinancialVehicleCorporation - financialVehicleCorporation + /// + public static readonly InstitutionalSectorEnum FinancialVehicleCorporation = new("financialVehicleCorporation"); + + /// + /// InstitutionalSectorEnum.OtherFinancialIntermediaries - otherFinancialIntermediaries + /// + public static readonly InstitutionalSectorEnum OtherFinancialIntermediaries = new("otherFinancialIntermediaries"); + + /// + /// InstitutionalSectorEnum.FinancialAuxiliaries - financialAuxiliaries + /// + public static readonly InstitutionalSectorEnum FinancialAuxiliaries = new("financialAuxiliaries"); + + /// + /// InstitutionalSectorEnum.CaptiveFinancialInstitutionsAndMoneyLenders - captiveFinancialInstitutionsAndMoneyLenders + /// + public static readonly InstitutionalSectorEnum CaptiveFinancialInstitutionsAndMoneyLenders = new("captiveFinancialInstitutionsAndMoneyLenders"); + + /// + /// InstitutionalSectorEnum.InsuranceCorporations - insuranceCorporations + /// + public static readonly InstitutionalSectorEnum InsuranceCorporations = new("insuranceCorporations"); + + /// + /// InstitutionalSectorEnum.PensionFunds - pensionFunds + /// + public static readonly InstitutionalSectorEnum PensionFunds = new("pensionFunds"); + + /// + /// InstitutionalSectorEnum.CentralGovernment - centralGovernment + /// + public static readonly InstitutionalSectorEnum CentralGovernment = new("centralGovernment"); + + /// + /// InstitutionalSectorEnum.StateGovernment - stateGovernment + /// + public static readonly InstitutionalSectorEnum StateGovernment = new("stateGovernment"); + + /// + /// InstitutionalSectorEnum.LocalGovernment - localGovernment + /// + public static readonly InstitutionalSectorEnum LocalGovernment = new("localGovernment"); + + /// + /// InstitutionalSectorEnum.SocialSecurityFunds - socialSecurityFunds + /// + public static readonly InstitutionalSectorEnum SocialSecurityFunds = new("socialSecurityFunds"); + + /// + /// InstitutionalSectorEnum.NonProfitInstitutionsServingHouseholds - nonProfitInstitutionsServingHouseholds + /// + public static readonly InstitutionalSectorEnum NonProfitInstitutionsServingHouseholds = new("nonProfitInstitutionsServingHouseholds"); + + private InstitutionalSectorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator InstitutionalSectorEnum?(string? value) => value == null ? null : new InstitutionalSectorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(InstitutionalSectorEnum? option) => option?.Value; + + public static bool operator ==(InstitutionalSectorEnum? left, InstitutionalSectorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(InstitutionalSectorEnum? left, InstitutionalSectorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is InstitutionalSectorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static InstitutionalSectorEnum? FromStringOrDefault(string value) + { + return value switch { + "nonFinancialCorporation" => InstitutionalSectorEnum.NonFinancialCorporation, + "centralBank" => InstitutionalSectorEnum.CentralBank, + "creditInstitutions" => InstitutionalSectorEnum.CreditInstitutions, + "depositTakingCorporations" => InstitutionalSectorEnum.DepositTakingCorporations, + "moneyMarketFunds" => InstitutionalSectorEnum.MoneyMarketFunds, + "nonMMFInvestmentFunds" => InstitutionalSectorEnum.NonMMFInvestmentFunds, + "financialVehicleCorporation" => InstitutionalSectorEnum.FinancialVehicleCorporation, + "otherFinancialIntermediaries" => InstitutionalSectorEnum.OtherFinancialIntermediaries, + "financialAuxiliaries" => InstitutionalSectorEnum.FinancialAuxiliaries, + "captiveFinancialInstitutionsAndMoneyLenders" => InstitutionalSectorEnum.CaptiveFinancialInstitutionsAndMoneyLenders, + "insuranceCorporations" => InstitutionalSectorEnum.InsuranceCorporations, + "pensionFunds" => InstitutionalSectorEnum.PensionFunds, + "centralGovernment" => InstitutionalSectorEnum.CentralGovernment, + "stateGovernment" => InstitutionalSectorEnum.StateGovernment, + "localGovernment" => InstitutionalSectorEnum.LocalGovernment, + "socialSecurityFunds" => InstitutionalSectorEnum.SocialSecurityFunds, + "nonProfitInstitutionsServingHouseholds" => InstitutionalSectorEnum.NonProfitInstitutionsServingHouseholds, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(InstitutionalSectorEnum? value) + { + if (value == null) + return null; + + if (value == InstitutionalSectorEnum.NonFinancialCorporation) + return "nonFinancialCorporation"; + + if (value == InstitutionalSectorEnum.CentralBank) + return "centralBank"; + + if (value == InstitutionalSectorEnum.CreditInstitutions) + return "creditInstitutions"; + + if (value == InstitutionalSectorEnum.DepositTakingCorporations) + return "depositTakingCorporations"; + + if (value == InstitutionalSectorEnum.MoneyMarketFunds) + return "moneyMarketFunds"; + + if (value == InstitutionalSectorEnum.NonMMFInvestmentFunds) + return "nonMMFInvestmentFunds"; + + if (value == InstitutionalSectorEnum.FinancialVehicleCorporation) + return "financialVehicleCorporation"; + + if (value == InstitutionalSectorEnum.OtherFinancialIntermediaries) + return "otherFinancialIntermediaries"; + + if (value == InstitutionalSectorEnum.FinancialAuxiliaries) + return "financialAuxiliaries"; + + if (value == InstitutionalSectorEnum.CaptiveFinancialInstitutionsAndMoneyLenders) + return "captiveFinancialInstitutionsAndMoneyLenders"; + + if (value == InstitutionalSectorEnum.InsuranceCorporations) + return "insuranceCorporations"; + + if (value == InstitutionalSectorEnum.PensionFunds) + return "pensionFunds"; + + if (value == InstitutionalSectorEnum.CentralGovernment) + return "centralGovernment"; + + if (value == InstitutionalSectorEnum.StateGovernment) + return "stateGovernment"; + + if (value == InstitutionalSectorEnum.LocalGovernment) + return "localGovernment"; + + if (value == InstitutionalSectorEnum.SocialSecurityFunds) + return "socialSecurityFunds"; + + if (value == InstitutionalSectorEnum.NonProfitInstitutionsServingHouseholds) + return "nonProfitInstitutionsServingHouseholds"; + + return null; + } + + /// + /// JsonConverter for writing InstitutionalSectorEnum. + /// + public class InstitutionalSectorEnumJsonConverter : JsonConverter + { + public override InstitutionalSectorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : InstitutionalSectorEnum.FromStringOrDefault(value) ?? new InstitutionalSectorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, InstitutionalSectorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(InstitutionalSectorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstitutionalSectorOption { get; private set; } + + /// + /// The institutional sector the organization operates within. + /// + /// The institutional sector the organization operates within. + [JsonPropertyName("institutionalSector")] + public InstitutionalSectorEnum? InstitutionalSector { get { return this._InstitutionalSectorOption; } set { this._InstitutionalSectorOption = new(value); } } + + /// + /// The status of any current or past legal action taken against the legal entity. Possible values: **noLegalActionsTaken**, **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** If the value of this field is **noLegalActionsTaken**, then `dateOfInitiationOfLegalProceeding` is not required. Otherwise, it is required. + /// + /// The status of any current or past legal action taken against the legal entity. Possible values: **noLegalActionsTaken**, **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** If the value of this field is **noLegalActionsTaken**, then `dateOfInitiationOfLegalProceeding` is not required. Otherwise, it is required. + [JsonConverter(typeof(StatusOfLegalProceedingEnumJsonConverter))] + public class StatusOfLegalProceedingEnum : IEnum + { + /// + /// Returns the value of the StatusOfLegalProceedingEnum. + /// + public string? Value { get; set; } + + /// + /// StatusOfLegalProceedingEnum.NoLegalActionsTaken - noLegalActionsTaken + /// + public static readonly StatusOfLegalProceedingEnum NoLegalActionsTaken = new("noLegalActionsTaken"); + + /// + /// StatusOfLegalProceedingEnum.UnderJudicialAdministration - underJudicialAdministration + /// + public static readonly StatusOfLegalProceedingEnum UnderJudicialAdministration = new("underJudicialAdministration"); + + /// + /// StatusOfLegalProceedingEnum.BankruptcyInsolvency - bankruptcyInsolvency + /// + public static readonly StatusOfLegalProceedingEnum BankruptcyInsolvency = new("bankruptcyInsolvency"); + + /// + /// StatusOfLegalProceedingEnum.OtherLegalMeasures - otherLegalMeasures + /// + public static readonly StatusOfLegalProceedingEnum OtherLegalMeasures = new("otherLegalMeasures"); + + private StatusOfLegalProceedingEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusOfLegalProceedingEnum?(string? value) => value == null ? null : new StatusOfLegalProceedingEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusOfLegalProceedingEnum? option) => option?.Value; + + public static bool operator ==(StatusOfLegalProceedingEnum? left, StatusOfLegalProceedingEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusOfLegalProceedingEnum? left, StatusOfLegalProceedingEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusOfLegalProceedingEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusOfLegalProceedingEnum? FromStringOrDefault(string value) + { + return value switch { + "noLegalActionsTaken" => StatusOfLegalProceedingEnum.NoLegalActionsTaken, + "underJudicialAdministration" => StatusOfLegalProceedingEnum.UnderJudicialAdministration, + "bankruptcyInsolvency" => StatusOfLegalProceedingEnum.BankruptcyInsolvency, + "otherLegalMeasures" => StatusOfLegalProceedingEnum.OtherLegalMeasures, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusOfLegalProceedingEnum? value) + { + if (value == null) + return null; + + if (value == StatusOfLegalProceedingEnum.NoLegalActionsTaken) + return "noLegalActionsTaken"; + + if (value == StatusOfLegalProceedingEnum.UnderJudicialAdministration) + return "underJudicialAdministration"; + + if (value == StatusOfLegalProceedingEnum.BankruptcyInsolvency) + return "bankruptcyInsolvency"; + + if (value == StatusOfLegalProceedingEnum.OtherLegalMeasures) + return "otherLegalMeasures"; + + return null; + } + + /// + /// JsonConverter for writing StatusOfLegalProceedingEnum. + /// + public class StatusOfLegalProceedingEnumJsonConverter : JsonConverter + { + public override StatusOfLegalProceedingEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusOfLegalProceedingEnum.FromStringOrDefault(value) ?? new StatusOfLegalProceedingEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusOfLegalProceedingEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusOfLegalProceedingEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOfLegalProceedingOption { get; private set; } + + /// + /// The status of any current or past legal action taken against the legal entity. Possible values: **noLegalActionsTaken**, **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** If the value of this field is **noLegalActionsTaken**, then `dateOfInitiationOfLegalProceeding` is not required. Otherwise, it is required. + /// + /// The status of any current or past legal action taken against the legal entity. Possible values: **noLegalActionsTaken**, **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** If the value of this field is **noLegalActionsTaken**, then `dateOfInitiationOfLegalProceeding` is not required. Otherwise, it is required. + [JsonPropertyName("statusOfLegalProceeding")] + public StatusOfLegalProceedingEnum? StatusOfLegalProceeding { get { return this._StatusOfLegalProceedingOption; } set { this._StatusOfLegalProceedingOption = new(value); } } + + /// + /// Type of organization. Possible values: **associationIncorporated**, **governmentalOrganization**, **listedPublicCompany**, **nonProfit**, **partnershipIncorporated**, **privateCompany**. + /// + /// Type of organization. Possible values: **associationIncorporated**, **governmentalOrganization**, **listedPublicCompany**, **nonProfit**, **partnershipIncorporated**, **privateCompany**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AssociationIncorporated - associationIncorporated + /// + public static readonly TypeEnum AssociationIncorporated = new("associationIncorporated"); + + /// + /// TypeEnum.GovernmentalOrganization - governmentalOrganization + /// + public static readonly TypeEnum GovernmentalOrganization = new("governmentalOrganization"); + + /// + /// TypeEnum.ListedPublicCompany - listedPublicCompany + /// + public static readonly TypeEnum ListedPublicCompany = new("listedPublicCompany"); + + /// + /// TypeEnum.NonProfit - nonProfit + /// + public static readonly TypeEnum NonProfit = new("nonProfit"); + + /// + /// TypeEnum.PartnershipIncorporated - partnershipIncorporated + /// + public static readonly TypeEnum PartnershipIncorporated = new("partnershipIncorporated"); + + /// + /// TypeEnum.PrivateCompany - privateCompany + /// + public static readonly TypeEnum PrivateCompany = new("privateCompany"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "associationIncorporated" => TypeEnum.AssociationIncorporated, + "governmentalOrganization" => TypeEnum.GovernmentalOrganization, + "listedPublicCompany" => TypeEnum.ListedPublicCompany, + "nonProfit" => TypeEnum.NonProfit, + "partnershipIncorporated" => TypeEnum.PartnershipIncorporated, + "privateCompany" => TypeEnum.PrivateCompany, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AssociationIncorporated) + return "associationIncorporated"; + + if (value == TypeEnum.GovernmentalOrganization) + return "governmentalOrganization"; + + if (value == TypeEnum.ListedPublicCompany) + return "listedPublicCompany"; + + if (value == TypeEnum.NonProfit) + return "nonProfit"; + + if (value == TypeEnum.PartnershipIncorporated) + return "partnershipIncorporated"; + + if (value == TypeEnum.PrivateCompany) + return "privateCompany"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of organization. Possible values: **associationIncorporated**, **governmentalOrganization**, **listedPublicCompany**, **nonProfit**, **partnershipIncorporated**, **privateCompany**. + /// + /// Type of organization. Possible values: **associationIncorporated**, **governmentalOrganization**, **listedPublicCompany**, **nonProfit**, **partnershipIncorporated**, **privateCompany**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The reason the organization has not provided a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason the organization has not provided a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonConverter(typeof(VatAbsenceReasonEnumJsonConverter))] + public class VatAbsenceReasonEnum : IEnum + { + /// + /// Returns the value of the VatAbsenceReasonEnum. + /// + public string? Value { get; set; } + + /// + /// VatAbsenceReasonEnum.IndustryExemption - industryExemption + /// + public static readonly VatAbsenceReasonEnum IndustryExemption = new("industryExemption"); + + /// + /// VatAbsenceReasonEnum.BelowTaxThreshold - belowTaxThreshold + /// + public static readonly VatAbsenceReasonEnum BelowTaxThreshold = new("belowTaxThreshold"); + + private VatAbsenceReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VatAbsenceReasonEnum?(string? value) => value == null ? null : new VatAbsenceReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VatAbsenceReasonEnum? option) => option?.Value; + + public static bool operator ==(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VatAbsenceReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VatAbsenceReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "industryExemption" => VatAbsenceReasonEnum.IndustryExemption, + "belowTaxThreshold" => VatAbsenceReasonEnum.BelowTaxThreshold, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VatAbsenceReasonEnum? value) + { + if (value == null) + return null; + + if (value == VatAbsenceReasonEnum.IndustryExemption) + return "industryExemption"; + + if (value == VatAbsenceReasonEnum.BelowTaxThreshold) + return "belowTaxThreshold"; + + return null; + } + + /// + /// JsonConverter for writing VatAbsenceReasonEnum. + /// + public class VatAbsenceReasonEnumJsonConverter : JsonConverter + { + public override VatAbsenceReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VatAbsenceReasonEnum.FromStringOrDefault(value) ?? new VatAbsenceReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VatAbsenceReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VatAbsenceReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatAbsenceReasonOption { get; private set; } + + /// + /// The reason the organization has not provided a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason the organization has not provided a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonPropertyName("vatAbsenceReason")] + public VatAbsenceReasonEnum? VatAbsenceReason { get { return this._VatAbsenceReasonOption; } set { this._VatAbsenceReasonOption = new(value); } } + + /// + /// The organization's legal name. + /// + /// The organization's legal name. + [JsonPropertyName("legalName")] + public string LegalName { get; set; } + + /// + /// . + /// + [JsonPropertyName("registeredAddress")] + public Address RegisteredAddress { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOfGoverningLawOption { get; private set; } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + [JsonPropertyName("countryOfGoverningLaw")] + public string? CountryOfGoverningLaw { get { return this._CountryOfGoverningLawOption; } set { this._CountryOfGoverningLawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfIncorporationOption { get; private set; } + + /// + /// The date when the organization was incorporated in YYYY-MM-DD format. + /// + /// The date when the organization was incorporated in YYYY-MM-DD format. + [JsonPropertyName("dateOfIncorporation")] + public string? DateOfIncorporation { get { return this._DateOfIncorporationOption; } set { this._DateOfIncorporationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfInitiationOfLegalProceedingOption { get; private set; } + + /// + /// Required if the value of `statusOfLegalProceeding` is one of the following: **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** The date at which a legal proceeding was initiated, in **YYYY-MM-DD** format. Example: **2000-02-12** + /// + /// Required if the value of `statusOfLegalProceeding` is one of the following: **underJudicialAdministration**, **bankruptcyInsolvency**, **otherLegalMeasures** The date at which a legal proceeding was initiated, in **YYYY-MM-DD** format. Example: **2000-02-12** + [JsonPropertyName("dateOfInitiationOfLegalProceeding")] + public string? DateOfInitiationOfLegalProceeding { get { return this._DateOfInitiationOfLegalProceedingOption; } set { this._DateOfInitiationOfLegalProceedingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the organization. + /// + /// Your description for the organization. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsOption { get; private set; } + + /// + /// The organization's trading name, if different from the registered legal name. + /// + /// The organization's trading name, if different from the registered legal name. + [JsonPropertyName("doingBusinessAs")] + public string? DoingBusinessAs { get { return this._DoingBusinessAsOption; } set { this._DoingBusinessAsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsAbsentOption { get; private set; } + + /// + /// Set this to **true** if the organization or legal arrangement does not have a `Doing business as` name. + /// + /// Set this to **true** if the organization or legal arrangement does not have a `Doing business as` name. + [JsonPropertyName("doingBusinessAsAbsent")] + public bool? DoingBusinessAsAbsent { get { return this._DoingBusinessAsAbsentOption; } set { this._DoingBusinessAsAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EconomicSectorOption { get; private set; } + + /// + /// The sector of the economy the legal entity operates within, represented by a 2-4 digit code that may include a \".\". Example: 45.11 You can locate economic sector codes for your area by referencing codes defined by the NACE (Nomenclature of Economic Activities) used in the European Union. + /// + /// The sector of the economy the legal entity operates within, represented by a 2-4 digit code that may include a \".\". Example: 45.11 You can locate economic sector codes for your area by referencing codes defined by the NACE (Nomenclature of Economic Activities) used in the European Union. + [JsonPropertyName("economicSector")] + public string? EconomicSector { get { return this._EconomicSectorOption; } set { this._EconomicSectorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the legal entity. + /// + /// The email address of the legal entity. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FinancialReportsOption { get; private set; } + + /// + /// The financial report information of the organization. + /// + /// The financial report information of the organization. + [JsonPropertyName("financialReports")] + public List? FinancialReports { get { return this._FinancialReportsOption; } set { this._FinancialReportsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GlobalLegalEntityIdentifierOption { get; private set; } + + /// + /// The global legal entity identifier for the organization. + /// + /// The global legal entity identifier for the organization. + [JsonPropertyName("globalLegalEntityIdentifier")] + public string? GlobalLegalEntityIdentifier { get { return this._GlobalLegalEntityIdentifierOption; } set { this._GlobalLegalEntityIdentifierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HeadOfficeIndicatorOption { get; private set; } + + /// + /// Indicates that the registered business address is also the company's headquarters. + /// + /// Indicates that the registered business address is also the company's headquarters. + [JsonPropertyName("headOfficeIndicator")] + public bool? HeadOfficeIndicator { get { return this._HeadOfficeIndicatorOption; } set { this._HeadOfficeIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LegalFormOption { get; private set; } + + /// + /// The type of business entity as defined in the national legal system. Use a legal form listed within the accepted legal forms compiled by the Central Bank of Europe. + /// + /// The type of business entity as defined in the national legal system. Use a legal form listed within the accepted legal forms compiled by the Central Bank of Europe. + [JsonPropertyName("legalForm")] + public string? LegalForm { get { return this._LegalFormOption; } set { this._LegalFormOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public PhoneNumber? Phone { get { return this._PhoneOption; } set { this._PhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrincipalPlaceOfBusinessOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("principalPlaceOfBusiness")] + public Address? PrincipalPlaceOfBusiness { get { return this._PrincipalPlaceOfBusinessOption; } set { this._PrincipalPlaceOfBusinessOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberOption { get; private set; } + + /// + /// The organization's registration number. + /// + /// The organization's registration number. + [JsonPropertyName("registrationNumber")] + public string? RegistrationNumber { get { return this._RegistrationNumberOption; } set { this._RegistrationNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberAbsentOption { get; private set; } + + /// + /// Set this to **true** if the organization does not have a registration number available. Only applicable for organizations in New Zealand, and incorporated partnerships and government organizations in Australia. + /// + /// Set this to **true** if the organization does not have a registration number available. Only applicable for organizations in New Zealand, and incorporated partnerships and government organizations in Australia. + [JsonPropertyName("registrationNumberAbsent")] + public bool? RegistrationNumberAbsent { get { return this._RegistrationNumberAbsentOption; } set { this._RegistrationNumberAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StockDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("stockData")] + public StockData? StockData { get { return this._StockDataOption; } set { this._StockDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SupportOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("support")] + public Support? Support { get { return this._SupportOption; } set { this._SupportOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TaxInformationOption { get; private set; } + + /// + /// The tax information of the organization. + /// + /// The tax information of the organization. + [JsonPropertyName("taxInformation")] + public List? TaxInformation { get { return this._TaxInformationOption; } set { this._TaxInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxReportingClassificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("taxReportingClassification")] + public TaxReportingClassification? TaxReportingClassification { get { return this._TaxReportingClassificationOption; } set { this._TaxReportingClassificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatNumberOption { get; private set; } + + /// + /// The organization's VAT number. + /// + /// The organization's VAT number. + [JsonPropertyName("vatNumber")] + public string? VatNumber { get { return this._VatNumberOption; } set { this._VatNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webData")] + public WebData? WebData { get { return this._WebDataOption; } set { this._WebDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Organization {\n"); + sb.Append(" LegalName: ").Append(LegalName).Append("\n"); + sb.Append(" RegisteredAddress: ").Append(RegisteredAddress).Append("\n"); + sb.Append(" CountryOfGoverningLaw: ").Append(CountryOfGoverningLaw).Append("\n"); + sb.Append(" DateOfIncorporation: ").Append(DateOfIncorporation).Append("\n"); + sb.Append(" DateOfInitiationOfLegalProceeding: ").Append(DateOfInitiationOfLegalProceeding).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DoingBusinessAs: ").Append(DoingBusinessAs).Append("\n"); + sb.Append(" DoingBusinessAsAbsent: ").Append(DoingBusinessAsAbsent).Append("\n"); + sb.Append(" EconomicSector: ").Append(EconomicSector).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FinancialReports: ").Append(FinancialReports).Append("\n"); + sb.Append(" GlobalLegalEntityIdentifier: ").Append(GlobalLegalEntityIdentifier).Append("\n"); + sb.Append(" HeadOfficeIndicator: ").Append(HeadOfficeIndicator).Append("\n"); + sb.Append(" InstitutionalSector: ").Append(InstitutionalSector).Append("\n"); + sb.Append(" LegalForm: ").Append(LegalForm).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" PrincipalPlaceOfBusiness: ").Append(PrincipalPlaceOfBusiness).Append("\n"); + sb.Append(" RegistrationNumber: ").Append(RegistrationNumber).Append("\n"); + sb.Append(" RegistrationNumberAbsent: ").Append(RegistrationNumberAbsent).Append("\n"); + sb.Append(" StatusOfLegalProceeding: ").Append(StatusOfLegalProceeding).Append("\n"); + sb.Append(" StockData: ").Append(StockData).Append("\n"); + sb.Append(" Support: ").Append(Support).Append("\n"); + sb.Append(" TaxInformation: ").Append(TaxInformation).Append("\n"); + sb.Append(" TaxReportingClassification: ").Append(TaxReportingClassification).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" VatAbsenceReason: ").Append(VatAbsenceReason).Append("\n"); + sb.Append(" VatNumber: ").Append(VatNumber).Append("\n"); + sb.Append(" WebData: ").Append(WebData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OrganizationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Organization Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option legalName = default; + Option registeredAddress = default; + Option countryOfGoverningLaw = default; + Option dateOfIncorporation = default; + Option dateOfInitiationOfLegalProceeding = default; + Option description = default; + Option doingBusinessAs = default; + Option doingBusinessAsAbsent = default; + Option economicSector = default; + Option email = default; + Option?> financialReports = default; + Option globalLegalEntityIdentifier = default; + Option headOfficeIndicator = default; + Option institutionalSector = default; + Option legalForm = default; + Option phone = default; + Option principalPlaceOfBusiness = default; + Option registrationNumber = default; + Option registrationNumberAbsent = default; + Option statusOfLegalProceeding = default; + Option stockData = default; + Option support = default; + Option?> taxInformation = default; + Option taxReportingClassification = default; + Option type = default; + Option vatAbsenceReason = default; + Option vatNumber = default; + Option webData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legalName": + legalName = new Option(utf8JsonReader.GetString()!); + break; + case "registeredAddress": + registeredAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countryOfGoverningLaw": + countryOfGoverningLaw = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfIncorporation": + dateOfIncorporation = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfInitiationOfLegalProceeding": + dateOfInitiationOfLegalProceeding = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAs": + doingBusinessAs = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAsAbsent": + doingBusinessAsAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "economicSector": + economicSector = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "financialReports": + financialReports = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "globalLegalEntityIdentifier": + globalLegalEntityIdentifier = new Option(utf8JsonReader.GetString()!); + break; + case "headOfficeIndicator": + headOfficeIndicator = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "institutionalSector": + string? institutionalSectorRawValue = utf8JsonReader.GetString(); + institutionalSector = new Option(Organization.InstitutionalSectorEnum.FromStringOrDefault(institutionalSectorRawValue)); + break; + case "legalForm": + legalForm = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "principalPlaceOfBusiness": + principalPlaceOfBusiness = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "registrationNumber": + registrationNumber = new Option(utf8JsonReader.GetString()!); + break; + case "registrationNumberAbsent": + registrationNumberAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "statusOfLegalProceeding": + string? statusOfLegalProceedingRawValue = utf8JsonReader.GetString(); + statusOfLegalProceeding = new Option(Organization.StatusOfLegalProceedingEnum.FromStringOrDefault(statusOfLegalProceedingRawValue)); + break; + case "stockData": + stockData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "support": + support = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "taxInformation": + taxInformation = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "taxReportingClassification": + taxReportingClassification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Organization.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "vatAbsenceReason": + string? vatAbsenceReasonRawValue = utf8JsonReader.GetString(); + vatAbsenceReason = new Option(Organization.VatAbsenceReasonEnum.FromStringOrDefault(vatAbsenceReasonRawValue)); + break; + case "vatNumber": + vatNumber = new Option(utf8JsonReader.GetString()!); + break; + case "webData": + webData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!legalName.IsSet) + throw new ArgumentException("Property is required for class Organization.", nameof(legalName)); + + if (!registeredAddress.IsSet) + throw new ArgumentException("Property is required for class Organization.", nameof(registeredAddress)); + + return new Organization(legalName.Value!, registeredAddress.Value!, countryOfGoverningLaw, dateOfIncorporation, dateOfInitiationOfLegalProceeding, description, doingBusinessAs, doingBusinessAsAbsent, economicSector, email, financialReports, globalLegalEntityIdentifier, headOfficeIndicator, institutionalSector, legalForm, phone, principalPlaceOfBusiness, registrationNumber, registrationNumberAbsent, statusOfLegalProceeding, stockData, support, taxInformation, taxReportingClassification, type, vatAbsenceReason, vatNumber, webData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Organization organization, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, organization, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Organization organization, JsonSerializerOptions jsonSerializerOptions) + { + + if (organization.LegalName != null) + writer.WriteString("legalName", organization.LegalName); + + writer.WritePropertyName("registeredAddress"); + JsonSerializer.Serialize(writer, organization.RegisteredAddress, jsonSerializerOptions); + if (organization._CountryOfGoverningLawOption.IsSet) + if (organization.CountryOfGoverningLaw != null) + writer.WriteString("countryOfGoverningLaw", organization.CountryOfGoverningLaw); + + if (organization._DateOfIncorporationOption.IsSet) + if (organization.DateOfIncorporation != null) + writer.WriteString("dateOfIncorporation", organization.DateOfIncorporation); + + if (organization._DateOfInitiationOfLegalProceedingOption.IsSet) + if (organization.DateOfInitiationOfLegalProceeding != null) + writer.WriteString("dateOfInitiationOfLegalProceeding", organization.DateOfInitiationOfLegalProceeding); + + if (organization._DescriptionOption.IsSet) + if (organization.Description != null) + writer.WriteString("description", organization.Description); + + if (organization._DoingBusinessAsOption.IsSet) + if (organization.DoingBusinessAs != null) + writer.WriteString("doingBusinessAs", organization.DoingBusinessAs); + + if (organization._DoingBusinessAsAbsentOption.IsSet) + if (organization._DoingBusinessAsAbsentOption.Value != null) + writer.WriteBoolean("doingBusinessAsAbsent", organization._DoingBusinessAsAbsentOption.Value!.Value); + else + writer.WriteNull("doingBusinessAsAbsent"); + + if (organization._EconomicSectorOption.IsSet) + if (organization.EconomicSector != null) + writer.WriteString("economicSector", organization.EconomicSector); + + if (organization._EmailOption.IsSet) + if (organization.Email != null) + writer.WriteString("email", organization.Email); + + if (organization._FinancialReportsOption.IsSet) + { + writer.WritePropertyName("financialReports"); + JsonSerializer.Serialize(writer, organization.FinancialReports, jsonSerializerOptions); + } + if (organization._GlobalLegalEntityIdentifierOption.IsSet) + if (organization.GlobalLegalEntityIdentifier != null) + writer.WriteString("globalLegalEntityIdentifier", organization.GlobalLegalEntityIdentifier); + + if (organization._HeadOfficeIndicatorOption.IsSet) + writer.WriteBoolean("headOfficeIndicator", organization._HeadOfficeIndicatorOption.Value!.Value); + + if (organization._InstitutionalSectorOption.IsSet && organization.InstitutionalSector != null) + { + string? institutionalSectorRawValue = Organization.InstitutionalSectorEnum.ToJsonValue(organization._InstitutionalSectorOption.Value!.Value); + writer.WriteString("institutionalSector", institutionalSectorRawValue); + } + + if (organization._LegalFormOption.IsSet) + if (organization.LegalForm != null) + writer.WriteString("legalForm", organization.LegalForm); + + if (organization._PhoneOption.IsSet) + { + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, organization.Phone, jsonSerializerOptions); + } + if (organization._PrincipalPlaceOfBusinessOption.IsSet) + { + writer.WritePropertyName("principalPlaceOfBusiness"); + JsonSerializer.Serialize(writer, organization.PrincipalPlaceOfBusiness, jsonSerializerOptions); + } + if (organization._RegistrationNumberOption.IsSet) + if (organization.RegistrationNumber != null) + writer.WriteString("registrationNumber", organization.RegistrationNumber); + + if (organization._RegistrationNumberAbsentOption.IsSet) + if (organization._RegistrationNumberAbsentOption.Value != null) + writer.WriteBoolean("registrationNumberAbsent", organization._RegistrationNumberAbsentOption.Value!.Value); + else + writer.WriteNull("registrationNumberAbsent"); + + if (organization._StatusOfLegalProceedingOption.IsSet && organization.StatusOfLegalProceeding != null) + { + string? statusOfLegalProceedingRawValue = Organization.StatusOfLegalProceedingEnum.ToJsonValue(organization._StatusOfLegalProceedingOption.Value!.Value); + writer.WriteString("statusOfLegalProceeding", statusOfLegalProceedingRawValue); + } + + if (organization._StockDataOption.IsSet) + { + writer.WritePropertyName("stockData"); + JsonSerializer.Serialize(writer, organization.StockData, jsonSerializerOptions); + } + if (organization._SupportOption.IsSet) + { + writer.WritePropertyName("support"); + JsonSerializer.Serialize(writer, organization.Support, jsonSerializerOptions); + } + if (organization._TaxInformationOption.IsSet) + { + writer.WritePropertyName("taxInformation"); + JsonSerializer.Serialize(writer, organization.TaxInformation, jsonSerializerOptions); + } + if (organization._TaxReportingClassificationOption.IsSet) + { + writer.WritePropertyName("taxReportingClassification"); + JsonSerializer.Serialize(writer, organization.TaxReportingClassification, jsonSerializerOptions); + } + if (organization._TypeOption.IsSet && organization.Type != null) + { + string? typeRawValue = Organization.TypeEnum.ToJsonValue(organization._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (organization._VatAbsenceReasonOption.IsSet && organization.VatAbsenceReason != null) + { + string? vatAbsenceReasonRawValue = Organization.VatAbsenceReasonEnum.ToJsonValue(organization._VatAbsenceReasonOption.Value!.Value); + writer.WriteString("vatAbsenceReason", vatAbsenceReasonRawValue); + } + + if (organization._VatNumberOption.IsSet) + if (organization.VatNumber != null) + writer.WriteString("vatNumber", organization.VatNumber); + + if (organization._WebDataOption.IsSet) + { + writer.WritePropertyName("webData"); + JsonSerializer.Serialize(writer, organization.WebData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/OwnerEntity.cs b/Adyen/LegalEntityManagement/Models/OwnerEntity.cs new file mode 100644 index 000000000..d6503cda7 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/OwnerEntity.cs @@ -0,0 +1,191 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// OwnerEntity. + /// + public partial class OwnerEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier of the resource that owns the document. For `type` **legalEntity**, this value is the unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). For `type` **bankAccount**, this value is the unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// Type of resource that owns the document. Possible values: **legalEntity**, **bankAccount**. + [JsonConstructor] + public OwnerEntity(string id, string type) + { + Id = id; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OwnerEntity() + { + } + + partial void OnCreated(); + + /// + /// Unique identifier of the resource that owns the document. For `type` **legalEntity**, this value is the unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). For `type` **bankAccount**, this value is the unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// Unique identifier of the resource that owns the document. For `type` **legalEntity**, this value is the unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). For `type` **bankAccount**, this value is the unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Type of resource that owns the document. Possible values: **legalEntity**, **bankAccount**. + /// + /// Type of resource that owns the document. Possible values: **legalEntity**, **bankAccount**. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OwnerEntity {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OwnerEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OwnerEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class OwnerEntity.", nameof(id)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class OwnerEntity.", nameof(type)); + + return new OwnerEntity(id.Value!, type.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OwnerEntity ownerEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ownerEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OwnerEntity ownerEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (ownerEntity.Id != null) + writer.WriteString("id", ownerEntity.Id); + + if (ownerEntity.Type != null) + writer.WriteString("type", ownerEntity.Type); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/PLLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/PLLocalAccountIdentification.cs new file mode 100644 index 000000000..11a1c02f1 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/PLLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// PLLocalAccountIdentification. + /// + public partial class PLLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// **plLocal** (default to TypeEnum.PlLocal) + [JsonConstructor] + public PLLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PLLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlLocal - plLocal + /// + public static readonly TypeEnum PlLocal = new("plLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "plLocal" => TypeEnum.PlLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlLocal) + return "plLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PLLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 26.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 26.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PLLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PLLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PLLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(type)); + + return new PLLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pLLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (pLLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", pLLocalAccountIdentification.AccountNumber); + + if (pLLocalAccountIdentification.Type != null) + { + string? typeRawValue = PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/PciDocumentInfo.cs b/Adyen/LegalEntityManagement/Models/PciDocumentInfo.cs new file mode 100644 index 000000000..422c9f062 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/PciDocumentInfo.cs @@ -0,0 +1,235 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// PciDocumentInfo. + /// + public partial class PciDocumentInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// The unique identifier of the signed questionnaire. + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonConstructor] + public PciDocumentInfo(Option createdAt = default, Option id = default, Option validUntil = default) + { + _CreatedAtOption = createdAt; + _IdOption = id; + _ValidUntilOption = validUntil; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PciDocumentInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// + /// The date the questionnaire was created, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the signed questionnaire. + /// + /// The unique identifier of the signed questionnaire. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValidUntilOption { get; private set; } + + /// + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + /// + /// The expiration date of the questionnaire, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00 + [JsonPropertyName("validUntil")] + public DateTimeOffset? ValidUntil { get { return this._ValidUntilOption; } set { this._ValidUntilOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PciDocumentInfo {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" ValidUntil: ").Append(ValidUntil).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PciDocumentInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValidUntil. + /// + public static string ValidUntilFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PciDocumentInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option id = default; + Option validUntil = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "validUntil": + validUntil = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new PciDocumentInfo(createdAt, id, validUntil); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PciDocumentInfo pciDocumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pciDocumentInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PciDocumentInfo pciDocumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (pciDocumentInfo._CreatedAtOption.IsSet) + writer.WriteString("createdAt", pciDocumentInfo._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (pciDocumentInfo._IdOption.IsSet) + if (pciDocumentInfo.Id != null) + writer.WriteString("id", pciDocumentInfo.Id); + + if (pciDocumentInfo._ValidUntilOption.IsSet) + writer.WriteString("validUntil", pciDocumentInfo._ValidUntilOption.Value!.Value.ToString(ValidUntilFormat)); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/PciSigningRequest.cs b/Adyen/LegalEntityManagement/Models/PciSigningRequest.cs new file mode 100644 index 000000000..39a986ec4 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/PciSigningRequest.cs @@ -0,0 +1,190 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// PciSigningRequest. + /// + public partial class PciSigningRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The array of Adyen-generated unique identifiers for the questionnaires. + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signs the PCI questionnaire. + [JsonConstructor] + public PciSigningRequest(List pciTemplateReferences, string signedBy) + { + PciTemplateReferences = pciTemplateReferences; + SignedBy = signedBy; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PciSigningRequest() + { + } + + partial void OnCreated(); + + /// + /// The array of Adyen-generated unique identifiers for the questionnaires. + /// + /// The array of Adyen-generated unique identifiers for the questionnaires. + [JsonPropertyName("pciTemplateReferences")] + public List PciTemplateReferences { get; set; } + + /// + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signs the PCI questionnaire. + /// + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signs the PCI questionnaire. + [JsonPropertyName("signedBy")] + public string SignedBy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PciSigningRequest {\n"); + sb.Append(" PciTemplateReferences: ").Append(PciTemplateReferences).Append("\n"); + sb.Append(" SignedBy: ").Append(SignedBy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PciSigningRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PciSigningRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> pciTemplateReferences = default; + Option signedBy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pciTemplateReferences": + pciTemplateReferences = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signedBy": + signedBy = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!pciTemplateReferences.IsSet) + throw new ArgumentException("Property is required for class PciSigningRequest.", nameof(pciTemplateReferences)); + + if (!signedBy.IsSet) + throw new ArgumentException("Property is required for class PciSigningRequest.", nameof(signedBy)); + + return new PciSigningRequest(pciTemplateReferences.Value!, signedBy.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PciSigningRequest pciSigningRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pciSigningRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PciSigningRequest pciSigningRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("pciTemplateReferences"); + JsonSerializer.Serialize(writer, pciSigningRequest.PciTemplateReferences, jsonSerializerOptions); + if (pciSigningRequest.SignedBy != null) + writer.WriteString("signedBy", pciSigningRequest.SignedBy); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/PciSigningResponse.cs b/Adyen/LegalEntityManagement/Models/PciSigningResponse.cs new file mode 100644 index 000000000..17595555d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/PciSigningResponse.cs @@ -0,0 +1,203 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// PciSigningResponse. + /// + public partial class PciSigningResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifiers of the signed PCI documents. + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signed the PCI questionnaire. + [JsonConstructor] + public PciSigningResponse(Option?> pciQuestionnaireIds = default, Option signedBy = default) + { + _PciQuestionnaireIdsOption = pciQuestionnaireIds; + _SignedByOption = signedBy; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PciSigningResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PciQuestionnaireIdsOption { get; private set; } + + /// + /// The unique identifiers of the signed PCI documents. + /// + /// The unique identifiers of the signed PCI documents. + [JsonPropertyName("pciQuestionnaireIds")] + public List? PciQuestionnaireIds { get { return this._PciQuestionnaireIdsOption; } set { this._PciQuestionnaireIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SignedByOption { get; private set; } + + /// + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signed the PCI questionnaire. + /// + /// The [legal entity ID](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities__resParam_id) of the individual who signed the PCI questionnaire. + [JsonPropertyName("signedBy")] + public string? SignedBy { get { return this._SignedByOption; } set { this._SignedByOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PciSigningResponse {\n"); + sb.Append(" PciQuestionnaireIds: ").Append(PciQuestionnaireIds).Append("\n"); + sb.Append(" SignedBy: ").Append(SignedBy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PciSigningResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PciSigningResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> pciQuestionnaireIds = default; + Option signedBy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pciQuestionnaireIds": + pciQuestionnaireIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signedBy": + signedBy = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PciSigningResponse(pciQuestionnaireIds, signedBy); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PciSigningResponse pciSigningResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pciSigningResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PciSigningResponse pciSigningResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (pciSigningResponse._PciQuestionnaireIdsOption.IsSet) + { + writer.WritePropertyName("pciQuestionnaireIds"); + JsonSerializer.Serialize(writer, pciSigningResponse.PciQuestionnaireIds, jsonSerializerOptions); + } + if (pciSigningResponse._SignedByOption.IsSet) + if (pciSigningResponse.SignedBy != null) + writer.WriteString("signedBy", pciSigningResponse.SignedBy); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/PhoneNumber.cs b/Adyen/LegalEntityManagement/Models/PhoneNumber.cs new file mode 100644 index 000000000..3e19330e6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/PhoneNumber.cs @@ -0,0 +1,221 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// PhoneNumber. + /// + public partial class PhoneNumber : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The full phone number, including the country code. For example, **+3112345678**. + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code prefix of the phone number. For example, **US** or **NL**. The value of the `phoneCountryCode` is determined by the country code digit(s) of `phone.number` + /// The type of phone number. Possible values: **mobile**, **landline**, **sip**, **fax.** + [JsonConstructor] + public PhoneNumber(string number, Option phoneCountryCode = default, Option type = default) + { + Number = number; + _PhoneCountryCodeOption = phoneCountryCode; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PhoneNumber() + { + } + + partial void OnCreated(); + + /// + /// The full phone number, including the country code. For example, **+3112345678**. + /// + /// The full phone number, including the country code. For example, **+3112345678**. + [JsonPropertyName("number")] + public string Number { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneCountryCodeOption { get; } + + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code prefix of the phone number. For example, **US** or **NL**. The value of the `phoneCountryCode` is determined by the country code digit(s) of `phone.number` + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code prefix of the phone number. For example, **US** or **NL**. The value of the `phoneCountryCode` is determined by the country code digit(s) of `phone.number` + [JsonPropertyName("phoneCountryCode")] + public string? PhoneCountryCode { get { return this._PhoneCountryCodeOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of phone number. Possible values: **mobile**, **landline**, **sip**, **fax.** + /// + /// The type of phone number. Possible values: **mobile**, **landline**, **sip**, **fax.** + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PhoneNumber {\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" PhoneCountryCode: ").Append(PhoneCountryCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneNumberJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PhoneNumber Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option number = default; + Option phoneCountryCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "phoneCountryCode": + phoneCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!number.IsSet) + throw new ArgumentException("Property is required for class PhoneNumber.", nameof(number)); + + return new PhoneNumber(number.Value!, phoneCountryCode, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phoneNumber, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PhoneNumber phoneNumber, JsonSerializerOptions jsonSerializerOptions) + { + + if (phoneNumber.Number != null) + writer.WriteString("number", phoneNumber.Number); + + if (phoneNumber._PhoneCountryCodeOption.IsSet) + if (phoneNumber.PhoneCountryCode != null) + writer.WriteString("phoneCountryCode", phoneNumber.PhoneCountryCode); + + if (phoneNumber._TypeOption.IsSet) + if (phoneNumber.Type != null) + writer.WriteString("type", phoneNumber.Type); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/RemediatingAction.cs b/Adyen/LegalEntityManagement/Models/RemediatingAction.cs new file mode 100644 index 000000000..dd565cf95 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/RemediatingAction.cs @@ -0,0 +1,200 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// RemediatingAction. + /// + public partial class RemediatingAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// code + /// message + [JsonConstructor] + public RemediatingAction(Option code = default, Option message = default) + { + _CodeOption = code; + _MessageOption = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RemediatingAction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RemediatingAction {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RemediatingActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RemediatingAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RemediatingAction(code, message); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, remediatingAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (remediatingAction._CodeOption.IsSet) + if (remediatingAction.Code != null) + writer.WriteString("code", remediatingAction.Code); + + if (remediatingAction._MessageOption.IsSet) + if (remediatingAction.Message != null) + writer.WriteString("message", remediatingAction.Message); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SELocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/SELocalAccountIdentification.cs new file mode 100644 index 000000000..063eeee59 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SELocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SELocalAccountIdentification. + /// + public partial class SELocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// **seLocal** (default to TypeEnum.SeLocal) + [JsonConstructor] + public SELocalAccountIdentification(string accountNumber, string clearingNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingNumber = clearingNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SELocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SeLocal - seLocal + /// + public static readonly TypeEnum SeLocal = new("seLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "seLocal" => TypeEnum.SeLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SeLocal) + return "seLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + [JsonPropertyName("clearingNumber")] + public string ClearingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SELocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingNumber: ").Append(ClearingNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 7) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 7.", new [] { "AccountNumber" }); + } + + // ClearingNumber (string) maxLength + if (this.ClearingNumber != null && this.ClearingNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be less than 5.", new [] { "ClearingNumber" }); + } + + // ClearingNumber (string) minLength + if (this.ClearingNumber != null && this.ClearingNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be greater than 4.", new [] { "ClearingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SELocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SELocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingNumber": + clearingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SELocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(clearingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(type)); + + return new SELocalAccountIdentification(accountNumber.Value!, clearingNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sELocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sELocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sELocalAccountIdentification.AccountNumber); + + if (sELocalAccountIdentification.ClearingNumber != null) + writer.WriteString("clearingNumber", sELocalAccountIdentification.ClearingNumber); + + if (sELocalAccountIdentification.Type != null) + { + string? typeRawValue = SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SGLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/SGLocalAccountIdentification.cs new file mode 100644 index 000000000..71fbc50a0 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SGLocalAccountIdentification.cs @@ -0,0 +1,337 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SGLocalAccountIdentification. + /// + public partial class SGLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// **sgLocal** (default to TypeEnum.SgLocal) + [JsonConstructor] + public SGLocalAccountIdentification(string accountNumber, string bic, Option type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SGLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SgLocal - sgLocal + /// + public static readonly TypeEnum SgLocal = new("sgLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sgLocal" => TypeEnum.SgLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SgLocal) + return "sgLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SGLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 19) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 19.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SGLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SGLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SGLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(bic)); + + return new SGLocalAccountIdentification(accountNumber.Value!, bic.Value!, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sGLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sGLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sGLocalAccountIdentification.AccountNumber); + + if (sGLocalAccountIdentification.Bic != null) + writer.WriteString("bic", sGLocalAccountIdentification.Bic); + + if (sGLocalAccountIdentification._TypeOption.IsSet && sGLocalAccountIdentification.Type != null) + { + string? typeRawValue = SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/ServiceError.cs b/Adyen/LegalEntityManagement/Models/ServiceError.cs new file mode 100644 index 000000000..0c1e56c0d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/ServiceError.cs @@ -0,0 +1,276 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SetTaxElectronicDeliveryConsentRequest.cs b/Adyen/LegalEntityManagement/Models/SetTaxElectronicDeliveryConsentRequest.cs new file mode 100644 index 000000000..551f83b20 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SetTaxElectronicDeliveryConsentRequest.cs @@ -0,0 +1,176 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SetTaxElectronicDeliveryConsentRequest. + /// + public partial class SetTaxElectronicDeliveryConsentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Consent to electronically deliver tax form US1099-K. + [JsonConstructor] + public SetTaxElectronicDeliveryConsentRequest(Option uS1099k = default) + { + _US1099kOption = uS1099k; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SetTaxElectronicDeliveryConsentRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _US1099kOption { get; private set; } + + /// + /// Consent to electronically deliver tax form US1099-K. + /// + /// Consent to electronically deliver tax form US1099-K. + [JsonPropertyName("US1099k")] + public bool? US1099k { get { return this._US1099kOption; } set { this._US1099kOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SetTaxElectronicDeliveryConsentRequest {\n"); + sb.Append(" US1099k: ").Append(US1099k).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SetTaxElectronicDeliveryConsentRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SetTaxElectronicDeliveryConsentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option uS1099k = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "US1099k": + uS1099k = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new SetTaxElectronicDeliveryConsentRequest(uS1099k); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SetTaxElectronicDeliveryConsentRequest setTaxElectronicDeliveryConsentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, setTaxElectronicDeliveryConsentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SetTaxElectronicDeliveryConsentRequest setTaxElectronicDeliveryConsentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (setTaxElectronicDeliveryConsentRequest._US1099kOption.IsSet) + writer.WriteBoolean("US1099k", setTaxElectronicDeliveryConsentRequest._US1099kOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SoleProprietorship.cs b/Adyen/LegalEntityManagement/Models/SoleProprietorship.cs new file mode 100644 index 000000000..0233b0320 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SoleProprietorship.cs @@ -0,0 +1,571 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SoleProprietorship. + /// + public partial class SoleProprietorship : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// The legal name. + /// registeredAddress + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// The registered name, if different from the `name`. + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// The information from the financial report of the sole proprietorship. + /// principalPlaceOfBusiness + /// The registration number. + /// The tax information is absent. + /// The tax information of the entity. + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// The VAT number. + [JsonConstructor] + public SoleProprietorship(string countryOfGoverningLaw, string name, Address registeredAddress, Option dateOfIncorporation = default, Option doingBusinessAs = default, Option doingBusinessAsAbsent = default, Option?> financialReports = default, Option principalPlaceOfBusiness = default, Option registrationNumber = default, Option taxAbsent = default, Option?> taxInformation = default, Option vatAbsenceReason = default, Option vatNumber = default) + { + CountryOfGoverningLaw = countryOfGoverningLaw; + Name = name; + RegisteredAddress = registeredAddress; + _DateOfIncorporationOption = dateOfIncorporation; + _DoingBusinessAsOption = doingBusinessAs; + _DoingBusinessAsAbsentOption = doingBusinessAsAbsent; + _FinancialReportsOption = financialReports; + _PrincipalPlaceOfBusinessOption = principalPlaceOfBusiness; + _RegistrationNumberOption = registrationNumber; + _TaxAbsentOption = taxAbsent; + _TaxInformationOption = taxInformation; + _VatAbsenceReasonOption = vatAbsenceReason; + _VatNumberOption = vatNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SoleProprietorship() + { + } + + partial void OnCreated(); + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonConverter(typeof(VatAbsenceReasonEnumJsonConverter))] + public class VatAbsenceReasonEnum : IEnum + { + /// + /// Returns the value of the VatAbsenceReasonEnum. + /// + public string? Value { get; set; } + + /// + /// VatAbsenceReasonEnum.IndustryExemption - industryExemption + /// + public static readonly VatAbsenceReasonEnum IndustryExemption = new("industryExemption"); + + /// + /// VatAbsenceReasonEnum.BelowTaxThreshold - belowTaxThreshold + /// + public static readonly VatAbsenceReasonEnum BelowTaxThreshold = new("belowTaxThreshold"); + + private VatAbsenceReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VatAbsenceReasonEnum?(string? value) => value == null ? null : new VatAbsenceReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VatAbsenceReasonEnum? option) => option?.Value; + + public static bool operator ==(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VatAbsenceReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VatAbsenceReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "industryExemption" => VatAbsenceReasonEnum.IndustryExemption, + "belowTaxThreshold" => VatAbsenceReasonEnum.BelowTaxThreshold, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VatAbsenceReasonEnum? value) + { + if (value == null) + return null; + + if (value == VatAbsenceReasonEnum.IndustryExemption) + return "industryExemption"; + + if (value == VatAbsenceReasonEnum.BelowTaxThreshold) + return "belowTaxThreshold"; + + return null; + } + + /// + /// JsonConverter for writing VatAbsenceReasonEnum. + /// + public class VatAbsenceReasonEnumJsonConverter : JsonConverter + { + public override VatAbsenceReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VatAbsenceReasonEnum.FromStringOrDefault(value) ?? new VatAbsenceReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VatAbsenceReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VatAbsenceReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatAbsenceReasonOption { get; private set; } + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonPropertyName("vatAbsenceReason")] + public VatAbsenceReasonEnum? VatAbsenceReason { get { return this._VatAbsenceReasonOption; } set { this._VatAbsenceReasonOption = new(value); } } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + [JsonPropertyName("countryOfGoverningLaw")] + public string CountryOfGoverningLaw { get; set; } + + /// + /// The legal name. + /// + /// The legal name. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// . + /// + [JsonPropertyName("registeredAddress")] + public Address RegisteredAddress { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfIncorporationOption { get; private set; } + + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + [JsonPropertyName("dateOfIncorporation")] + public string? DateOfIncorporation { get { return this._DateOfIncorporationOption; } set { this._DateOfIncorporationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsOption { get; private set; } + + /// + /// The registered name, if different from the `name`. + /// + /// The registered name, if different from the `name`. + [JsonPropertyName("doingBusinessAs")] + public string? DoingBusinessAs { get { return this._DoingBusinessAsOption; } set { this._DoingBusinessAsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsAbsentOption { get; private set; } + + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + [JsonPropertyName("doingBusinessAsAbsent")] + public bool? DoingBusinessAsAbsent { get { return this._DoingBusinessAsAbsentOption; } set { this._DoingBusinessAsAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FinancialReportsOption { get; private set; } + + /// + /// The information from the financial report of the sole proprietorship. + /// + /// The information from the financial report of the sole proprietorship. + [JsonPropertyName("financialReports")] + public List? FinancialReports { get { return this._FinancialReportsOption; } set { this._FinancialReportsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrincipalPlaceOfBusinessOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("principalPlaceOfBusiness")] + public Address? PrincipalPlaceOfBusiness { get { return this._PrincipalPlaceOfBusinessOption; } set { this._PrincipalPlaceOfBusinessOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberOption { get; private set; } + + /// + /// The registration number. + /// + /// The registration number. + [JsonPropertyName("registrationNumber")] + public string? RegistrationNumber { get { return this._RegistrationNumberOption; } set { this._RegistrationNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxAbsentOption { get; private set; } + + /// + /// The tax information is absent. + /// + /// The tax information is absent. + [JsonPropertyName("taxAbsent")] + public bool? TaxAbsent { get { return this._TaxAbsentOption; } set { this._TaxAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TaxInformationOption { get; private set; } + + /// + /// The tax information of the entity. + /// + /// The tax information of the entity. + [JsonPropertyName("taxInformation")] + public List? TaxInformation { get { return this._TaxInformationOption; } set { this._TaxInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatNumberOption { get; private set; } + + /// + /// The VAT number. + /// + /// The VAT number. + [JsonPropertyName("vatNumber")] + public string? VatNumber { get { return this._VatNumberOption; } set { this._VatNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SoleProprietorship {\n"); + sb.Append(" CountryOfGoverningLaw: ").Append(CountryOfGoverningLaw).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RegisteredAddress: ").Append(RegisteredAddress).Append("\n"); + sb.Append(" DateOfIncorporation: ").Append(DateOfIncorporation).Append("\n"); + sb.Append(" DoingBusinessAs: ").Append(DoingBusinessAs).Append("\n"); + sb.Append(" DoingBusinessAsAbsent: ").Append(DoingBusinessAsAbsent).Append("\n"); + sb.Append(" FinancialReports: ").Append(FinancialReports).Append("\n"); + sb.Append(" PrincipalPlaceOfBusiness: ").Append(PrincipalPlaceOfBusiness).Append("\n"); + sb.Append(" RegistrationNumber: ").Append(RegistrationNumber).Append("\n"); + sb.Append(" TaxAbsent: ").Append(TaxAbsent).Append("\n"); + sb.Append(" TaxInformation: ").Append(TaxInformation).Append("\n"); + sb.Append(" VatAbsenceReason: ").Append(VatAbsenceReason).Append("\n"); + sb.Append(" VatNumber: ").Append(VatNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SoleProprietorshipJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SoleProprietorship Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option countryOfGoverningLaw = default; + Option name = default; + Option registeredAddress = default; + Option dateOfIncorporation = default; + Option doingBusinessAs = default; + Option doingBusinessAsAbsent = default; + Option?> financialReports = default; + Option principalPlaceOfBusiness = default; + Option registrationNumber = default; + Option taxAbsent = default; + Option?> taxInformation = default; + Option vatAbsenceReason = default; + Option vatNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "countryOfGoverningLaw": + countryOfGoverningLaw = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "registeredAddress": + registeredAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfIncorporation": + dateOfIncorporation = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAs": + doingBusinessAs = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAsAbsent": + doingBusinessAsAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "financialReports": + financialReports = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "principalPlaceOfBusiness": + principalPlaceOfBusiness = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "registrationNumber": + registrationNumber = new Option(utf8JsonReader.GetString()!); + break; + case "taxAbsent": + taxAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "taxInformation": + taxInformation = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "vatAbsenceReason": + string? vatAbsenceReasonRawValue = utf8JsonReader.GetString(); + vatAbsenceReason = new Option(SoleProprietorship.VatAbsenceReasonEnum.FromStringOrDefault(vatAbsenceReasonRawValue)); + break; + case "vatNumber": + vatNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!countryOfGoverningLaw.IsSet) + throw new ArgumentException("Property is required for class SoleProprietorship.", nameof(countryOfGoverningLaw)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class SoleProprietorship.", nameof(name)); + + if (!registeredAddress.IsSet) + throw new ArgumentException("Property is required for class SoleProprietorship.", nameof(registeredAddress)); + + return new SoleProprietorship(countryOfGoverningLaw.Value!, name.Value!, registeredAddress.Value!, dateOfIncorporation, doingBusinessAs, doingBusinessAsAbsent, financialReports, principalPlaceOfBusiness, registrationNumber, taxAbsent, taxInformation, vatAbsenceReason, vatNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SoleProprietorship soleProprietorship, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, soleProprietorship, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SoleProprietorship soleProprietorship, JsonSerializerOptions jsonSerializerOptions) + { + + if (soleProprietorship.CountryOfGoverningLaw != null) + writer.WriteString("countryOfGoverningLaw", soleProprietorship.CountryOfGoverningLaw); + + if (soleProprietorship.Name != null) + writer.WriteString("name", soleProprietorship.Name); + + writer.WritePropertyName("registeredAddress"); + JsonSerializer.Serialize(writer, soleProprietorship.RegisteredAddress, jsonSerializerOptions); + if (soleProprietorship._DateOfIncorporationOption.IsSet) + if (soleProprietorship.DateOfIncorporation != null) + writer.WriteString("dateOfIncorporation", soleProprietorship.DateOfIncorporation); + + if (soleProprietorship._DoingBusinessAsOption.IsSet) + if (soleProprietorship.DoingBusinessAs != null) + writer.WriteString("doingBusinessAs", soleProprietorship.DoingBusinessAs); + + if (soleProprietorship._DoingBusinessAsAbsentOption.IsSet) + if (soleProprietorship._DoingBusinessAsAbsentOption.Value != null) + writer.WriteBoolean("doingBusinessAsAbsent", soleProprietorship._DoingBusinessAsAbsentOption.Value!.Value); + else + writer.WriteNull("doingBusinessAsAbsent"); + + if (soleProprietorship._FinancialReportsOption.IsSet) + { + writer.WritePropertyName("financialReports"); + JsonSerializer.Serialize(writer, soleProprietorship.FinancialReports, jsonSerializerOptions); + } + if (soleProprietorship._PrincipalPlaceOfBusinessOption.IsSet) + { + writer.WritePropertyName("principalPlaceOfBusiness"); + JsonSerializer.Serialize(writer, soleProprietorship.PrincipalPlaceOfBusiness, jsonSerializerOptions); + } + if (soleProprietorship._RegistrationNumberOption.IsSet) + if (soleProprietorship.RegistrationNumber != null) + writer.WriteString("registrationNumber", soleProprietorship.RegistrationNumber); + + if (soleProprietorship._TaxAbsentOption.IsSet) + if (soleProprietorship._TaxAbsentOption.Value != null) + writer.WriteBoolean("taxAbsent", soleProprietorship._TaxAbsentOption.Value!.Value); + else + writer.WriteNull("taxAbsent"); + + if (soleProprietorship._TaxInformationOption.IsSet) + { + writer.WritePropertyName("taxInformation"); + JsonSerializer.Serialize(writer, soleProprietorship.TaxInformation, jsonSerializerOptions); + } + if (soleProprietorship._VatAbsenceReasonOption.IsSet && soleProprietorship.VatAbsenceReason != null) + { + string? vatAbsenceReasonRawValue = SoleProprietorship.VatAbsenceReasonEnum.ToJsonValue(soleProprietorship._VatAbsenceReasonOption.Value!.Value); + writer.WriteString("vatAbsenceReason", vatAbsenceReasonRawValue); + } + + if (soleProprietorship._VatNumberOption.IsSet) + if (soleProprietorship.VatNumber != null) + writer.WriteString("vatNumber", soleProprietorship.VatNumber); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SourceOfFunds.cs b/Adyen/LegalEntityManagement/Models/SourceOfFunds.cs new file mode 100644 index 000000000..775f9fe63 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SourceOfFunds.cs @@ -0,0 +1,701 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SourceOfFunds. + /// + public partial class SourceOfFunds : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the funds are coming from transactions processed by Adyen. If **false**, the `type` is required. + /// amount + /// The number of months that the asset has been in possession of the user. For example, if the source of funds is of type **cryptocurrencyIncome** then `assetMonthsHeld` is the number of months the user has owned the cryptocurrency. + /// Required if `type` is **cryptocurrencyIncome**. The cryptocurrency exchange where the funds were acquired. + /// Required if `type` is **donations** or **inheritance**. The date the funds were received, in YYYY-MM-DD format. + /// Required if `type` is **assetSale** or **gamblingWinnings**. The date the funds were received, in YYYY-MM-DD format. For example, if the source of funds is of type **assetSale**, the dateOfSourceEvent is the date of the sale. If the source of funds is of type **gamblingWinnings**, the dateOfSourceEvent is the date of winnings. + /// Required if `type` is **business** or **assetSale**. A description for the source of funds. For example, for `type` **business**, provide a description of where the business transactions come from, such as payments through bank transfer. For `type` **assetSale**, provide a description of the asset. For example, the address of a residential property if it is a property sale. + /// Required if `type` is **thirdPartyFunding**. Information about the financiers. + /// Required if `type` is **donations** or **inheritance**. The legal entity ID representing the originator of the source of funds. For example, if the source of funds is **inheritance**, then `originatorOfFundsReference` should be the legal entity reference of the benefactor. + /// Required if `type` is **donations**. The reason for receiving the funds. + /// Required if `type` is **donations** or **inheritance**. The relationship of the originator of the funds to the recipient. + /// The type of the source of funds. Possible values: * **business** * **employment** * **donations** * **inheritance** * **financialAid** * **rentalIncome** * **dividendIncome** * **royaltyIncome** * **thirdPartyFunding** * **pensionIncome** * **insuranceSettlement** * **cryptocurrencyIncome** * **assetSale** * **loans** * **gamblingWinnings** + /// Required if `type` is **gamblingWinnings**. The location of the gambling site for the winnings. For example, if the source of funds is online gambling, provide the website of the gambling company. + [JsonConstructor] + public SourceOfFunds(bool adyenProcessedFunds, Option amount = default, Option assetMonthsHeld = default, Option cryptocurrencyExchange = default, Option dateOfFundsReceived = default, Option dateOfSourceEvent = default, Option description = default, Option?> financiers = default, Option originatorLegalEntityId = default, Option purpose = default, Option relationship = default, Option type = default, Option website = default) + { + AdyenProcessedFunds = adyenProcessedFunds; + _AmountOption = amount; + _AssetMonthsHeldOption = assetMonthsHeld; + _CryptocurrencyExchangeOption = cryptocurrencyExchange; + _DateOfFundsReceivedOption = dateOfFundsReceived; + _DateOfSourceEventOption = dateOfSourceEvent; + _DescriptionOption = description; + _FinanciersOption = financiers; + _OriginatorLegalEntityIdOption = originatorLegalEntityId; + _PurposeOption = purpose; + _RelationshipOption = relationship; + _TypeOption = type; + _WebsiteOption = website; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SourceOfFunds() + { + } + + partial void OnCreated(); + + /// + /// The type of the source of funds. Possible values: * **business** * **employment** * **donations** * **inheritance** * **financialAid** * **rentalIncome** * **dividendIncome** * **royaltyIncome** * **thirdPartyFunding** * **pensionIncome** * **insuranceSettlement** * **cryptocurrencyIncome** * **assetSale** * **loans** * **gamblingWinnings** + /// + /// The type of the source of funds. Possible values: * **business** * **employment** * **donations** * **inheritance** * **financialAid** * **rentalIncome** * **dividendIncome** * **royaltyIncome** * **thirdPartyFunding** * **pensionIncome** * **insuranceSettlement** * **cryptocurrencyIncome** * **assetSale** * **loans** * **gamblingWinnings** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Business - business + /// + public static readonly TypeEnum Business = new("business"); + + /// + /// TypeEnum.Employment - employment + /// + public static readonly TypeEnum Employment = new("employment"); + + /// + /// TypeEnum.Donations - donations + /// + public static readonly TypeEnum Donations = new("donations"); + + /// + /// TypeEnum.Inheritance - inheritance + /// + public static readonly TypeEnum Inheritance = new("inheritance"); + + /// + /// TypeEnum.FinancialAid - financialAid + /// + public static readonly TypeEnum FinancialAid = new("financialAid"); + + /// + /// TypeEnum.RentalIncome - rentalIncome + /// + public static readonly TypeEnum RentalIncome = new("rentalIncome"); + + /// + /// TypeEnum.DividendIncome - dividendIncome + /// + public static readonly TypeEnum DividendIncome = new("dividendIncome"); + + /// + /// TypeEnum.RoyaltyIncome - royaltyIncome + /// + public static readonly TypeEnum RoyaltyIncome = new("royaltyIncome"); + + /// + /// TypeEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly TypeEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// TypeEnum.PensionIncome - pensionIncome + /// + public static readonly TypeEnum PensionIncome = new("pensionIncome"); + + /// + /// TypeEnum.InsuranceSettlement - insuranceSettlement + /// + public static readonly TypeEnum InsuranceSettlement = new("insuranceSettlement"); + + /// + /// TypeEnum.CryptocurrencyIncome - cryptocurrencyIncome + /// + public static readonly TypeEnum CryptocurrencyIncome = new("cryptocurrencyIncome"); + + /// + /// TypeEnum.AssetSale - assetSale + /// + public static readonly TypeEnum AssetSale = new("assetSale"); + + /// + /// TypeEnum.Loans - loans + /// + public static readonly TypeEnum Loans = new("loans"); + + /// + /// TypeEnum.GamblingWinnings - gamblingWinnings + /// + public static readonly TypeEnum GamblingWinnings = new("gamblingWinnings"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "business" => TypeEnum.Business, + "employment" => TypeEnum.Employment, + "donations" => TypeEnum.Donations, + "inheritance" => TypeEnum.Inheritance, + "financialAid" => TypeEnum.FinancialAid, + "rentalIncome" => TypeEnum.RentalIncome, + "dividendIncome" => TypeEnum.DividendIncome, + "royaltyIncome" => TypeEnum.RoyaltyIncome, + "thirdPartyFunding" => TypeEnum.ThirdPartyFunding, + "pensionIncome" => TypeEnum.PensionIncome, + "insuranceSettlement" => TypeEnum.InsuranceSettlement, + "cryptocurrencyIncome" => TypeEnum.CryptocurrencyIncome, + "assetSale" => TypeEnum.AssetSale, + "loans" => TypeEnum.Loans, + "gamblingWinnings" => TypeEnum.GamblingWinnings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Business) + return "business"; + + if (value == TypeEnum.Employment) + return "employment"; + + if (value == TypeEnum.Donations) + return "donations"; + + if (value == TypeEnum.Inheritance) + return "inheritance"; + + if (value == TypeEnum.FinancialAid) + return "financialAid"; + + if (value == TypeEnum.RentalIncome) + return "rentalIncome"; + + if (value == TypeEnum.DividendIncome) + return "dividendIncome"; + + if (value == TypeEnum.RoyaltyIncome) + return "royaltyIncome"; + + if (value == TypeEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == TypeEnum.PensionIncome) + return "pensionIncome"; + + if (value == TypeEnum.InsuranceSettlement) + return "insuranceSettlement"; + + if (value == TypeEnum.CryptocurrencyIncome) + return "cryptocurrencyIncome"; + + if (value == TypeEnum.AssetSale) + return "assetSale"; + + if (value == TypeEnum.Loans) + return "loans"; + + if (value == TypeEnum.GamblingWinnings) + return "gamblingWinnings"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the source of funds. Possible values: * **business** * **employment** * **donations** * **inheritance** * **financialAid** * **rentalIncome** * **dividendIncome** * **royaltyIncome** * **thirdPartyFunding** * **pensionIncome** * **insuranceSettlement** * **cryptocurrencyIncome** * **assetSale** * **loans** * **gamblingWinnings** + /// + /// The type of the source of funds. Possible values: * **business** * **employment** * **donations** * **inheritance** * **financialAid** * **rentalIncome** * **dividendIncome** * **royaltyIncome** * **thirdPartyFunding** * **pensionIncome** * **insuranceSettlement** * **cryptocurrencyIncome** * **assetSale** * **loans** * **gamblingWinnings** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Indicates whether the funds are coming from transactions processed by Adyen. If **false**, the `type` is required. + /// + /// Indicates whether the funds are coming from transactions processed by Adyen. If **false**, the `type` is required. + [JsonPropertyName("adyenProcessedFunds")] + public bool AdyenProcessedFunds { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssetMonthsHeldOption { get; private set; } + + /// + /// The number of months that the asset has been in possession of the user. For example, if the source of funds is of type **cryptocurrencyIncome** then `assetMonthsHeld` is the number of months the user has owned the cryptocurrency. + /// + /// The number of months that the asset has been in possession of the user. For example, if the source of funds is of type **cryptocurrencyIncome** then `assetMonthsHeld` is the number of months the user has owned the cryptocurrency. + [JsonPropertyName("assetMonthsHeld")] + public int? AssetMonthsHeld { get { return this._AssetMonthsHeldOption; } set { this._AssetMonthsHeldOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CryptocurrencyExchangeOption { get; private set; } + + /// + /// Required if `type` is **cryptocurrencyIncome**. The cryptocurrency exchange where the funds were acquired. + /// + /// Required if `type` is **cryptocurrencyIncome**. The cryptocurrency exchange where the funds were acquired. + [JsonPropertyName("cryptocurrencyExchange")] + public string? CryptocurrencyExchange { get { return this._CryptocurrencyExchangeOption; } set { this._CryptocurrencyExchangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfFundsReceivedOption { get; private set; } + + /// + /// Required if `type` is **donations** or **inheritance**. The date the funds were received, in YYYY-MM-DD format. + /// + /// Required if `type` is **donations** or **inheritance**. The date the funds were received, in YYYY-MM-DD format. + [JsonPropertyName("dateOfFundsReceived")] + public DateOnly? DateOfFundsReceived { get { return this._DateOfFundsReceivedOption; } set { this._DateOfFundsReceivedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfSourceEventOption { get; private set; } + + /// + /// Required if `type` is **assetSale** or **gamblingWinnings**. The date the funds were received, in YYYY-MM-DD format. For example, if the source of funds is of type **assetSale**, the dateOfSourceEvent is the date of the sale. If the source of funds is of type **gamblingWinnings**, the dateOfSourceEvent is the date of winnings. + /// + /// Required if `type` is **assetSale** or **gamblingWinnings**. The date the funds were received, in YYYY-MM-DD format. For example, if the source of funds is of type **assetSale**, the dateOfSourceEvent is the date of the sale. If the source of funds is of type **gamblingWinnings**, the dateOfSourceEvent is the date of winnings. + [JsonPropertyName("dateOfSourceEvent")] + public DateOnly? DateOfSourceEvent { get { return this._DateOfSourceEventOption; } set { this._DateOfSourceEventOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Required if `type` is **business** or **assetSale**. A description for the source of funds. For example, for `type` **business**, provide a description of where the business transactions come from, such as payments through bank transfer. For `type` **assetSale**, provide a description of the asset. For example, the address of a residential property if it is a property sale. + /// + /// Required if `type` is **business** or **assetSale**. A description for the source of funds. For example, for `type` **business**, provide a description of where the business transactions come from, such as payments through bank transfer. For `type` **assetSale**, provide a description of the asset. For example, the address of a residential property if it is a property sale. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FinanciersOption { get; private set; } + + /// + /// Required if `type` is **thirdPartyFunding**. Information about the financiers. + /// + /// Required if `type` is **thirdPartyFunding**. Information about the financiers. + [JsonPropertyName("financiers")] + public List? Financiers { get { return this._FinanciersOption; } set { this._FinanciersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginatorLegalEntityIdOption { get; private set; } + + /// + /// Required if `type` is **donations** or **inheritance**. The legal entity ID representing the originator of the source of funds. For example, if the source of funds is **inheritance**, then `originatorOfFundsReference` should be the legal entity reference of the benefactor. + /// + /// Required if `type` is **donations** or **inheritance**. The legal entity ID representing the originator of the source of funds. For example, if the source of funds is **inheritance**, then `originatorOfFundsReference` should be the legal entity reference of the benefactor. + [JsonPropertyName("originatorLegalEntityId")] + public string? OriginatorLegalEntityId { get { return this._OriginatorLegalEntityIdOption; } set { this._OriginatorLegalEntityIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurposeOption { get; private set; } + + /// + /// Required if `type` is **donations**. The reason for receiving the funds. + /// + /// Required if `type` is **donations**. The reason for receiving the funds. + [JsonPropertyName("purpose")] + public string? Purpose { get { return this._PurposeOption; } set { this._PurposeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RelationshipOption { get; private set; } + + /// + /// Required if `type` is **donations** or **inheritance**. The relationship of the originator of the funds to the recipient. + /// + /// Required if `type` is **donations** or **inheritance**. The relationship of the originator of the funds to the recipient. + [JsonPropertyName("relationship")] + public string? Relationship { get { return this._RelationshipOption; } set { this._RelationshipOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebsiteOption { get; private set; } + + /// + /// Required if `type` is **gamblingWinnings**. The location of the gambling site for the winnings. For example, if the source of funds is online gambling, provide the website of the gambling company. + /// + /// Required if `type` is **gamblingWinnings**. The location of the gambling site for the winnings. For example, if the source of funds is online gambling, provide the website of the gambling company. + [JsonPropertyName("website")] + public string? Website { get { return this._WebsiteOption; } set { this._WebsiteOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SourceOfFunds {\n"); + sb.Append(" AdyenProcessedFunds: ").Append(AdyenProcessedFunds).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" AssetMonthsHeld: ").Append(AssetMonthsHeld).Append("\n"); + sb.Append(" CryptocurrencyExchange: ").Append(CryptocurrencyExchange).Append("\n"); + sb.Append(" DateOfFundsReceived: ").Append(DateOfFundsReceived).Append("\n"); + sb.Append(" DateOfSourceEvent: ").Append(DateOfSourceEvent).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Financiers: ").Append(Financiers).Append("\n"); + sb.Append(" OriginatorLegalEntityId: ").Append(OriginatorLegalEntityId).Append("\n"); + sb.Append(" Purpose: ").Append(Purpose).Append("\n"); + sb.Append(" Relationship: ").Append(Relationship).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Website: ").Append(Website).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SourceOfFundsJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfFundsReceived. + /// + public static string DateOfFundsReceivedFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DateOfSourceEvent. + /// + public static string DateOfSourceEventFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SourceOfFunds Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option adyenProcessedFunds = default; + Option amount = default; + Option assetMonthsHeld = default; + Option cryptocurrencyExchange = default; + Option dateOfFundsReceived = default; + Option dateOfSourceEvent = default; + Option description = default; + Option?> financiers = default; + Option originatorLegalEntityId = default; + Option purpose = default; + Option relationship = default; + Option type = default; + Option website = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "adyenProcessedFunds": + adyenProcessedFunds = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "assetMonthsHeld": + assetMonthsHeld = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "cryptocurrencyExchange": + cryptocurrencyExchange = new Option(utf8JsonReader.GetString()!); + break; + case "dateOfFundsReceived": + dateOfFundsReceived = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dateOfSourceEvent": + dateOfSourceEvent = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "financiers": + financiers = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originatorLegalEntityId": + originatorLegalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "purpose": + purpose = new Option(utf8JsonReader.GetString()!); + break; + case "relationship": + relationship = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SourceOfFunds.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "website": + website = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!adyenProcessedFunds.IsSet) + throw new ArgumentException("Property is required for class SourceOfFunds.", nameof(adyenProcessedFunds)); + + return new SourceOfFunds(adyenProcessedFunds.Value!.Value!, amount, assetMonthsHeld, cryptocurrencyExchange, dateOfFundsReceived, dateOfSourceEvent, description, financiers, originatorLegalEntityId, purpose, relationship, type, website); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SourceOfFunds sourceOfFunds, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sourceOfFunds, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SourceOfFunds sourceOfFunds, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("adyenProcessedFunds", sourceOfFunds.AdyenProcessedFunds); + + if (sourceOfFunds._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, sourceOfFunds.Amount, jsonSerializerOptions); + } + if (sourceOfFunds._AssetMonthsHeldOption.IsSet) + writer.WriteNumber("assetMonthsHeld", sourceOfFunds._AssetMonthsHeldOption.Value!.Value); + + if (sourceOfFunds._CryptocurrencyExchangeOption.IsSet) + if (sourceOfFunds.CryptocurrencyExchange != null) + writer.WriteString("cryptocurrencyExchange", sourceOfFunds.CryptocurrencyExchange); + + if (sourceOfFunds._DateOfFundsReceivedOption.IsSet) + writer.WriteString("dateOfFundsReceived", sourceOfFunds._DateOfFundsReceivedOption.Value!.Value.ToString(DateOfFundsReceivedFormat)); + + if (sourceOfFunds._DateOfSourceEventOption.IsSet) + writer.WriteString("dateOfSourceEvent", sourceOfFunds._DateOfSourceEventOption.Value!.Value.ToString(DateOfSourceEventFormat)); + + if (sourceOfFunds._DescriptionOption.IsSet) + if (sourceOfFunds.Description != null) + writer.WriteString("description", sourceOfFunds.Description); + + if (sourceOfFunds._FinanciersOption.IsSet) + { + writer.WritePropertyName("financiers"); + JsonSerializer.Serialize(writer, sourceOfFunds.Financiers, jsonSerializerOptions); + } + if (sourceOfFunds._OriginatorLegalEntityIdOption.IsSet) + if (sourceOfFunds.OriginatorLegalEntityId != null) + writer.WriteString("originatorLegalEntityId", sourceOfFunds.OriginatorLegalEntityId); + + if (sourceOfFunds._PurposeOption.IsSet) + if (sourceOfFunds.Purpose != null) + writer.WriteString("purpose", sourceOfFunds.Purpose); + + if (sourceOfFunds._RelationshipOption.IsSet) + if (sourceOfFunds.Relationship != null) + writer.WriteString("relationship", sourceOfFunds.Relationship); + + if (sourceOfFunds._TypeOption.IsSet && sourceOfFunds.Type != null) + { + string? typeRawValue = SourceOfFunds.TypeEnum.ToJsonValue(sourceOfFunds._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (sourceOfFunds._WebsiteOption.IsSet) + if (sourceOfFunds.Website != null) + writer.WriteString("website", sourceOfFunds.Website); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/StockData.cs b/Adyen/LegalEntityManagement/Models/StockData.cs new file mode 100644 index 000000000..495f79467 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/StockData.cs @@ -0,0 +1,227 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// StockData. + /// + public partial class StockData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The four-digit [Market Identifier Code](https://en.wikipedia.org/wiki/Market_Identifier_Code) of the stock market where the organization's stocks are traded. + /// The 12-digit International Securities Identification Number (ISIN) of the company, without dashes (-). + /// The stock ticker symbol. + [JsonConstructor] + public StockData(Option marketIdentifier = default, Option stockNumber = default, Option tickerSymbol = default) + { + _MarketIdentifierOption = marketIdentifier; + _StockNumberOption = stockNumber; + _TickerSymbolOption = tickerSymbol; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StockData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MarketIdentifierOption { get; private set; } + + /// + /// The four-digit [Market Identifier Code](https://en.wikipedia.org/wiki/Market_Identifier_Code) of the stock market where the organization's stocks are traded. + /// + /// The four-digit [Market Identifier Code](https://en.wikipedia.org/wiki/Market_Identifier_Code) of the stock market where the organization's stocks are traded. + [JsonPropertyName("marketIdentifier")] + public string? MarketIdentifier { get { return this._MarketIdentifierOption; } set { this._MarketIdentifierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StockNumberOption { get; private set; } + + /// + /// The 12-digit International Securities Identification Number (ISIN) of the company, without dashes (-). + /// + /// The 12-digit International Securities Identification Number (ISIN) of the company, without dashes (-). + [JsonPropertyName("stockNumber")] + public string? StockNumber { get { return this._StockNumberOption; } set { this._StockNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TickerSymbolOption { get; private set; } + + /// + /// The stock ticker symbol. + /// + /// The stock ticker symbol. + [JsonPropertyName("tickerSymbol")] + public string? TickerSymbol { get { return this._TickerSymbolOption; } set { this._TickerSymbolOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StockData {\n"); + sb.Append(" MarketIdentifier: ").Append(MarketIdentifier).Append("\n"); + sb.Append(" StockNumber: ").Append(StockNumber).Append("\n"); + sb.Append(" TickerSymbol: ").Append(TickerSymbol).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StockDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StockData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option marketIdentifier = default; + Option stockNumber = default; + Option tickerSymbol = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "marketIdentifier": + marketIdentifier = new Option(utf8JsonReader.GetString()!); + break; + case "stockNumber": + stockNumber = new Option(utf8JsonReader.GetString()!); + break; + case "tickerSymbol": + tickerSymbol = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StockData(marketIdentifier, stockNumber, tickerSymbol); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StockData stockData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, stockData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StockData stockData, JsonSerializerOptions jsonSerializerOptions) + { + + if (stockData._MarketIdentifierOption.IsSet) + if (stockData.MarketIdentifier != null) + writer.WriteString("marketIdentifier", stockData.MarketIdentifier); + + if (stockData._StockNumberOption.IsSet) + if (stockData.StockNumber != null) + writer.WriteString("stockNumber", stockData.StockNumber); + + if (stockData._TickerSymbolOption.IsSet) + if (stockData.TickerSymbol != null) + writer.WriteString("tickerSymbol", stockData.TickerSymbol); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Support.cs b/Adyen/LegalEntityManagement/Models/Support.cs new file mode 100644 index 000000000..231df00e0 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Support.cs @@ -0,0 +1,203 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Support. + /// + public partial class Support : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The support email address of the legal entity. + /// phone + [JsonConstructor] + public Support(Option email = default, Option phone = default) + { + _EmailOption = email; + _PhoneOption = phone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Support() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The support email address of the legal entity. + /// + /// The support email address of the legal entity. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("phone")] + public PhoneNumber? Phone { get { return this._PhoneOption; } set { this._PhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Support {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SupportJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Support Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option phone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "phone": + phone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Support(email, phone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Support support, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, support, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Support support, JsonSerializerOptions jsonSerializerOptions) + { + + if (support._EmailOption.IsSet) + if (support.Email != null) + writer.WriteString("email", support.Email); + + if (support._PhoneOption.IsSet) + { + writer.WritePropertyName("phone"); + JsonSerializer.Serialize(writer, support.Phone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/SupportingEntityCapability.cs b/Adyen/LegalEntityManagement/Models/SupportingEntityCapability.cs new file mode 100644 index 000000000..4d9589574 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/SupportingEntityCapability.cs @@ -0,0 +1,250 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// SupportingEntityCapability. + /// + public partial class SupportingEntityCapability : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the capability is allowed for the supporting entity. If a capability is allowed for a supporting entity but not for the parent legal entity, this means the legal entity has other supporting entities that failed verification. **You can use the allowed supporting entity** regardless of the verification status of other supporting entities. + /// Supporting entity reference + /// Indicates whether the supporting entity capability is requested. + /// The status of the verification checks for the capability of the supporting entity. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonConstructor] + internal SupportingEntityCapability(Option allowed = default, Option id = default, Option requested = default, Option verificationStatus = default) + { + _AllowedOption = allowed; + _IdOption = id; + _RequestedOption = requested; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + internal SupportingEntityCapability() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; } + + /// + /// Indicates whether the capability is allowed for the supporting entity. If a capability is allowed for a supporting entity but not for the parent legal entity, this means the legal entity has other supporting entities that failed verification. **You can use the allowed supporting entity** regardless of the verification status of other supporting entities. + /// + /// Indicates whether the capability is allowed for the supporting entity. If a capability is allowed for a supporting entity but not for the parent legal entity, this means the legal entity has other supporting entities that failed verification. **You can use the allowed supporting entity** regardless of the verification status of other supporting entities. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; } + + /// + /// Supporting entity reference + /// + /// Supporting entity reference + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedOption { get; } + + /// + /// Indicates whether the supporting entity capability is requested. + /// + /// Indicates whether the supporting entity capability is requested. + [JsonPropertyName("requested")] + public bool? Requested { get { return this._RequestedOption; } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; } + + /// + /// The status of the verification checks for the capability of the supporting entity. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability of the supporting entity. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification has been successfully completed. * **rejected**: Adyen has verified the information, but found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public string? VerificationStatus { get { return this._VerificationStatusOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SupportingEntityCapability {\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SupportingEntityCapabilityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SupportingEntityCapability Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowed = default; + Option id = default; + Option requested = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "verificationStatus": + verificationStatus = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SupportingEntityCapability(allowed, id, requested, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SupportingEntityCapability supportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, supportingEntityCapability, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SupportingEntityCapability supportingEntityCapability, JsonSerializerOptions jsonSerializerOptions) + { + + if (supportingEntityCapability._AllowedOption.IsSet) + writer.WriteBoolean("allowed", supportingEntityCapability._AllowedOption.Value!.Value); + + if (supportingEntityCapability._IdOption.IsSet) + if (supportingEntityCapability.Id != null) + writer.WriteString("id", supportingEntityCapability.Id); + + if (supportingEntityCapability._RequestedOption.IsSet) + writer.WriteBoolean("requested", supportingEntityCapability._RequestedOption.Value!.Value); + + if (supportingEntityCapability._VerificationStatusOption.IsSet) + if (supportingEntityCapability.VerificationStatus != null) + writer.WriteString("verificationStatus", supportingEntityCapability.VerificationStatus); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TaxInformation.cs b/Adyen/LegalEntityManagement/Models/TaxInformation.cs new file mode 100644 index 000000000..f8097b8a2 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TaxInformation.cs @@ -0,0 +1,263 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TaxInformation. + /// + public partial class TaxInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// The tax ID number (TIN) of the organization or individual. + /// Set this to **true** if the legal entity or legal arrangement does not have a tax ID number (TIN). Only applicable in Australia. + /// The TIN type depending on the country where it was issued. Only provide if the country has multiple tax IDs: Singapore, Sweden, the UK, or the US. For example, provide **SSN**, **EIN**, or **ITIN** for the US. + [JsonConstructor] + public TaxInformation(Option country = default, Option number = default, Option numberAbsent = default, Option type = default) + { + _CountryOption = country; + _NumberOption = number; + _NumberAbsentOption = numberAbsent; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TaxInformation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + /// + /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The tax ID number (TIN) of the organization or individual. + /// + /// The tax ID number (TIN) of the organization or individual. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberAbsentOption { get; private set; } + + /// + /// Set this to **true** if the legal entity or legal arrangement does not have a tax ID number (TIN). Only applicable in Australia. + /// + /// Set this to **true** if the legal entity or legal arrangement does not have a tax ID number (TIN). Only applicable in Australia. + [JsonPropertyName("numberAbsent")] + public bool? NumberAbsent { get { return this._NumberAbsentOption; } set { this._NumberAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The TIN type depending on the country where it was issued. Only provide if the country has multiple tax IDs: Singapore, Sweden, the UK, or the US. For example, provide **SSN**, **EIN**, or **ITIN** for the US. + /// + /// The TIN type depending on the country where it was issued. Only provide if the country has multiple tax IDs: Singapore, Sweden, the UK, or the US. For example, provide **SSN**, **EIN**, or **ITIN** for the US. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaxInformation {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" NumberAbsent: ").Append(NumberAbsent).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Country (string) maxLength + if (this.Country != null && this.Country.Length > 2) + { + yield return new ValidationResult("Invalid value for Country, length must be less than 2.", new [] { "Country" }); + } + + // Country (string) minLength + if (this.Country != null && this.Country.Length < 2) + { + yield return new ValidationResult("Invalid value for Country, length must be greater than 2.", new [] { "Country" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaxInformationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TaxInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option number = default; + Option numberAbsent = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "numberAbsent": + numberAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TaxInformation(country, number, numberAbsent, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaxInformation taxInformation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, taxInformation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaxInformation taxInformation, JsonSerializerOptions jsonSerializerOptions) + { + + if (taxInformation._CountryOption.IsSet) + if (taxInformation.Country != null) + writer.WriteString("country", taxInformation.Country); + + if (taxInformation._NumberOption.IsSet) + if (taxInformation.Number != null) + writer.WriteString("number", taxInformation.Number); + + if (taxInformation._NumberAbsentOption.IsSet) + writer.WriteBoolean("numberAbsent", taxInformation._NumberAbsentOption.Value!.Value); + + if (taxInformation._TypeOption.IsSet) + if (taxInformation.Type != null) + writer.WriteString("type", taxInformation.Type); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TaxReportingClassification.cs b/Adyen/LegalEntityManagement/Models/TaxReportingClassification.cs new file mode 100644 index 000000000..dd1493ecc --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TaxReportingClassification.cs @@ -0,0 +1,651 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TaxReportingClassification. + /// + public partial class TaxReportingClassification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The organization's business type. Possible values: **other**, **listedPublicCompany**, **subsidiaryOfListedPublicCompany**, **governmentalOrganization**, **internationalOrganization**, **financialInstitution**. + /// The Global Intermediary Identification Number (GIIN) required for FATCA. Only required if the organization is a US financial institution and the `businessType` is **financialInstitution**. + /// The organization's main source of income. Only required if `businessType` is **other**. Possible values: **businessOperation**, **realEstateSales**, **investmentInterestOrRoyalty**, **propertyRental**, **other**. + /// The tax reporting classification type. Possible values: **nonFinancialNonReportable**, **financialNonReportable**, **nonFinancialActive**, **nonFinancialPassive**. + [JsonConstructor] + public TaxReportingClassification(Option businessType = default, Option financialInstitutionNumber = default, Option mainSourceOfIncome = default, Option type = default) + { + _BusinessTypeOption = businessType; + _FinancialInstitutionNumberOption = financialInstitutionNumber; + _MainSourceOfIncomeOption = mainSourceOfIncome; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TaxReportingClassification() + { + } + + partial void OnCreated(); + + /// + /// The organization's business type. Possible values: **other**, **listedPublicCompany**, **subsidiaryOfListedPublicCompany**, **governmentalOrganization**, **internationalOrganization**, **financialInstitution**. + /// + /// The organization's business type. Possible values: **other**, **listedPublicCompany**, **subsidiaryOfListedPublicCompany**, **governmentalOrganization**, **internationalOrganization**, **financialInstitution**. + [JsonConverter(typeof(BusinessTypeEnumJsonConverter))] + public class BusinessTypeEnum : IEnum + { + /// + /// Returns the value of the BusinessTypeEnum. + /// + public string? Value { get; set; } + + /// + /// BusinessTypeEnum.Other - other + /// + public static readonly BusinessTypeEnum Other = new("other"); + + /// + /// BusinessTypeEnum.ListedPublicCompany - listedPublicCompany + /// + public static readonly BusinessTypeEnum ListedPublicCompany = new("listedPublicCompany"); + + /// + /// BusinessTypeEnum.SubsidiaryOfListedPublicCompany - subsidiaryOfListedPublicCompany + /// + public static readonly BusinessTypeEnum SubsidiaryOfListedPublicCompany = new("subsidiaryOfListedPublicCompany"); + + /// + /// BusinessTypeEnum.GovernmentalOrganization - governmentalOrganization + /// + public static readonly BusinessTypeEnum GovernmentalOrganization = new("governmentalOrganization"); + + /// + /// BusinessTypeEnum.InternationalOrganization - internationalOrganization + /// + public static readonly BusinessTypeEnum InternationalOrganization = new("internationalOrganization"); + + /// + /// BusinessTypeEnum.FinancialInstitution - financialInstitution + /// + public static readonly BusinessTypeEnum FinancialInstitution = new("financialInstitution"); + + private BusinessTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BusinessTypeEnum?(string? value) => value == null ? null : new BusinessTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BusinessTypeEnum? option) => option?.Value; + + public static bool operator ==(BusinessTypeEnum? left, BusinessTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BusinessTypeEnum? left, BusinessTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BusinessTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BusinessTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "other" => BusinessTypeEnum.Other, + "listedPublicCompany" => BusinessTypeEnum.ListedPublicCompany, + "subsidiaryOfListedPublicCompany" => BusinessTypeEnum.SubsidiaryOfListedPublicCompany, + "governmentalOrganization" => BusinessTypeEnum.GovernmentalOrganization, + "internationalOrganization" => BusinessTypeEnum.InternationalOrganization, + "financialInstitution" => BusinessTypeEnum.FinancialInstitution, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BusinessTypeEnum? value) + { + if (value == null) + return null; + + if (value == BusinessTypeEnum.Other) + return "other"; + + if (value == BusinessTypeEnum.ListedPublicCompany) + return "listedPublicCompany"; + + if (value == BusinessTypeEnum.SubsidiaryOfListedPublicCompany) + return "subsidiaryOfListedPublicCompany"; + + if (value == BusinessTypeEnum.GovernmentalOrganization) + return "governmentalOrganization"; + + if (value == BusinessTypeEnum.InternationalOrganization) + return "internationalOrganization"; + + if (value == BusinessTypeEnum.FinancialInstitution) + return "financialInstitution"; + + return null; + } + + /// + /// JsonConverter for writing BusinessTypeEnum. + /// + public class BusinessTypeEnumJsonConverter : JsonConverter + { + public override BusinessTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BusinessTypeEnum.FromStringOrDefault(value) ?? new BusinessTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BusinessTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BusinessTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessTypeOption { get; private set; } + + /// + /// The organization's business type. Possible values: **other**, **listedPublicCompany**, **subsidiaryOfListedPublicCompany**, **governmentalOrganization**, **internationalOrganization**, **financialInstitution**. + /// + /// The organization's business type. Possible values: **other**, **listedPublicCompany**, **subsidiaryOfListedPublicCompany**, **governmentalOrganization**, **internationalOrganization**, **financialInstitution**. + [JsonPropertyName("businessType")] + public BusinessTypeEnum? BusinessType { get { return this._BusinessTypeOption; } set { this._BusinessTypeOption = new(value); } } + + /// + /// The organization's main source of income. Only required if `businessType` is **other**. Possible values: **businessOperation**, **realEstateSales**, **investmentInterestOrRoyalty**, **propertyRental**, **other**. + /// + /// The organization's main source of income. Only required if `businessType` is **other**. Possible values: **businessOperation**, **realEstateSales**, **investmentInterestOrRoyalty**, **propertyRental**, **other**. + [JsonConverter(typeof(MainSourceOfIncomeEnumJsonConverter))] + public class MainSourceOfIncomeEnum : IEnum + { + /// + /// Returns the value of the MainSourceOfIncomeEnum. + /// + public string? Value { get; set; } + + /// + /// MainSourceOfIncomeEnum.BusinessOperation - businessOperation + /// + public static readonly MainSourceOfIncomeEnum BusinessOperation = new("businessOperation"); + + /// + /// MainSourceOfIncomeEnum.RealEstateSales - realEstateSales + /// + public static readonly MainSourceOfIncomeEnum RealEstateSales = new("realEstateSales"); + + /// + /// MainSourceOfIncomeEnum.InvestmentInterestOrRoyalty - investmentInterestOrRoyalty + /// + public static readonly MainSourceOfIncomeEnum InvestmentInterestOrRoyalty = new("investmentInterestOrRoyalty"); + + /// + /// MainSourceOfIncomeEnum.PropertyRental - propertyRental + /// + public static readonly MainSourceOfIncomeEnum PropertyRental = new("propertyRental"); + + /// + /// MainSourceOfIncomeEnum.Other - other + /// + public static readonly MainSourceOfIncomeEnum Other = new("other"); + + private MainSourceOfIncomeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator MainSourceOfIncomeEnum?(string? value) => value == null ? null : new MainSourceOfIncomeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(MainSourceOfIncomeEnum? option) => option?.Value; + + public static bool operator ==(MainSourceOfIncomeEnum? left, MainSourceOfIncomeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(MainSourceOfIncomeEnum? left, MainSourceOfIncomeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is MainSourceOfIncomeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static MainSourceOfIncomeEnum? FromStringOrDefault(string value) + { + return value switch { + "businessOperation" => MainSourceOfIncomeEnum.BusinessOperation, + "realEstateSales" => MainSourceOfIncomeEnum.RealEstateSales, + "investmentInterestOrRoyalty" => MainSourceOfIncomeEnum.InvestmentInterestOrRoyalty, + "propertyRental" => MainSourceOfIncomeEnum.PropertyRental, + "other" => MainSourceOfIncomeEnum.Other, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(MainSourceOfIncomeEnum? value) + { + if (value == null) + return null; + + if (value == MainSourceOfIncomeEnum.BusinessOperation) + return "businessOperation"; + + if (value == MainSourceOfIncomeEnum.RealEstateSales) + return "realEstateSales"; + + if (value == MainSourceOfIncomeEnum.InvestmentInterestOrRoyalty) + return "investmentInterestOrRoyalty"; + + if (value == MainSourceOfIncomeEnum.PropertyRental) + return "propertyRental"; + + if (value == MainSourceOfIncomeEnum.Other) + return "other"; + + return null; + } + + /// + /// JsonConverter for writing MainSourceOfIncomeEnum. + /// + public class MainSourceOfIncomeEnumJsonConverter : JsonConverter + { + public override MainSourceOfIncomeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : MainSourceOfIncomeEnum.FromStringOrDefault(value) ?? new MainSourceOfIncomeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, MainSourceOfIncomeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(MainSourceOfIncomeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MainSourceOfIncomeOption { get; private set; } + + /// + /// The organization's main source of income. Only required if `businessType` is **other**. Possible values: **businessOperation**, **realEstateSales**, **investmentInterestOrRoyalty**, **propertyRental**, **other**. + /// + /// The organization's main source of income. Only required if `businessType` is **other**. Possible values: **businessOperation**, **realEstateSales**, **investmentInterestOrRoyalty**, **propertyRental**, **other**. + [JsonPropertyName("mainSourceOfIncome")] + public MainSourceOfIncomeEnum? MainSourceOfIncome { get { return this._MainSourceOfIncomeOption; } set { this._MainSourceOfIncomeOption = new(value); } } + + /// + /// The tax reporting classification type. Possible values: **nonFinancialNonReportable**, **financialNonReportable**, **nonFinancialActive**, **nonFinancialPassive**. + /// + /// The tax reporting classification type. Possible values: **nonFinancialNonReportable**, **financialNonReportable**, **nonFinancialActive**, **nonFinancialPassive**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NonFinancialNonReportable - nonFinancialNonReportable + /// + public static readonly TypeEnum NonFinancialNonReportable = new("nonFinancialNonReportable"); + + /// + /// TypeEnum.FinancialNonReportable - financialNonReportable + /// + public static readonly TypeEnum FinancialNonReportable = new("financialNonReportable"); + + /// + /// TypeEnum.NonFinancialActive - nonFinancialActive + /// + public static readonly TypeEnum NonFinancialActive = new("nonFinancialActive"); + + /// + /// TypeEnum.NonFinancialPassive - nonFinancialPassive + /// + public static readonly TypeEnum NonFinancialPassive = new("nonFinancialPassive"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nonFinancialNonReportable" => TypeEnum.NonFinancialNonReportable, + "financialNonReportable" => TypeEnum.FinancialNonReportable, + "nonFinancialActive" => TypeEnum.NonFinancialActive, + "nonFinancialPassive" => TypeEnum.NonFinancialPassive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NonFinancialNonReportable) + return "nonFinancialNonReportable"; + + if (value == TypeEnum.FinancialNonReportable) + return "financialNonReportable"; + + if (value == TypeEnum.NonFinancialActive) + return "nonFinancialActive"; + + if (value == TypeEnum.NonFinancialPassive) + return "nonFinancialPassive"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The tax reporting classification type. Possible values: **nonFinancialNonReportable**, **financialNonReportable**, **nonFinancialActive**, **nonFinancialPassive**. + /// + /// The tax reporting classification type. Possible values: **nonFinancialNonReportable**, **financialNonReportable**, **nonFinancialActive**, **nonFinancialPassive**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FinancialInstitutionNumberOption { get; private set; } + + /// + /// The Global Intermediary Identification Number (GIIN) required for FATCA. Only required if the organization is a US financial institution and the `businessType` is **financialInstitution**. + /// + /// The Global Intermediary Identification Number (GIIN) required for FATCA. Only required if the organization is a US financial institution and the `businessType` is **financialInstitution**. + [JsonPropertyName("financialInstitutionNumber")] + public string? FinancialInstitutionNumber { get { return this._FinancialInstitutionNumberOption; } set { this._FinancialInstitutionNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaxReportingClassification {\n"); + sb.Append(" BusinessType: ").Append(BusinessType).Append("\n"); + sb.Append(" FinancialInstitutionNumber: ").Append(FinancialInstitutionNumber).Append("\n"); + sb.Append(" MainSourceOfIncome: ").Append(MainSourceOfIncome).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaxReportingClassificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TaxReportingClassification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option businessType = default; + Option financialInstitutionNumber = default; + Option mainSourceOfIncome = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "businessType": + string? businessTypeRawValue = utf8JsonReader.GetString(); + businessType = new Option(TaxReportingClassification.BusinessTypeEnum.FromStringOrDefault(businessTypeRawValue)); + break; + case "financialInstitutionNumber": + financialInstitutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "mainSourceOfIncome": + string? mainSourceOfIncomeRawValue = utf8JsonReader.GetString(); + mainSourceOfIncome = new Option(TaxReportingClassification.MainSourceOfIncomeEnum.FromStringOrDefault(mainSourceOfIncomeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TaxReportingClassification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new TaxReportingClassification(businessType, financialInstitutionNumber, mainSourceOfIncome, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaxReportingClassification taxReportingClassification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, taxReportingClassification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaxReportingClassification taxReportingClassification, JsonSerializerOptions jsonSerializerOptions) + { + + if (taxReportingClassification._BusinessTypeOption.IsSet && taxReportingClassification.BusinessType != null) + { + string? businessTypeRawValue = TaxReportingClassification.BusinessTypeEnum.ToJsonValue(taxReportingClassification._BusinessTypeOption.Value!.Value); + writer.WriteString("businessType", businessTypeRawValue); + } + + if (taxReportingClassification._FinancialInstitutionNumberOption.IsSet) + if (taxReportingClassification.FinancialInstitutionNumber != null) + writer.WriteString("financialInstitutionNumber", taxReportingClassification.FinancialInstitutionNumber); + + if (taxReportingClassification._MainSourceOfIncomeOption.IsSet && taxReportingClassification.MainSourceOfIncome != null) + { + string? mainSourceOfIncomeRawValue = TaxReportingClassification.MainSourceOfIncomeEnum.ToJsonValue(taxReportingClassification._MainSourceOfIncomeOption.Value!.Value); + writer.WriteString("mainSourceOfIncome", mainSourceOfIncomeRawValue); + } + + if (taxReportingClassification._TypeOption.IsSet && taxReportingClassification.Type != null) + { + string? typeRawValue = TaxReportingClassification.TypeEnum.ToJsonValue(taxReportingClassification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TermsOfServiceAcceptanceInfo.cs b/Adyen/LegalEntityManagement/Models/TermsOfServiceAcceptanceInfo.cs new file mode 100644 index 000000000..9c6290c3e --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TermsOfServiceAcceptanceInfo.cs @@ -0,0 +1,488 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TermsOfServiceAcceptanceInfo. + /// + public partial class TermsOfServiceAcceptanceInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the user that accepted the Terms of Service. + /// The unique identifier of the legal entity for which the Terms of Service are accepted. + /// The date when the Terms of Service were accepted, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00. + /// An Adyen-generated reference for the accepted Terms of Service. + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// The expiration date for the Terms of Service acceptance, in ISO 8601 extended format. For example, 2022-12-18T00:00:00+01:00. + [JsonConstructor] + public TermsOfServiceAcceptanceInfo(Option acceptedBy = default, Option acceptedFor = default, Option createdAt = default, Option id = default, Option type = default, Option validTo = default) + { + _AcceptedByOption = acceptedBy; + _AcceptedForOption = acceptedFor; + _CreatedAtOption = createdAt; + _IdOption = id; + _TypeOption = type; + _ValidToOption = validTo; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TermsOfServiceAcceptanceInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AdyenAccount - adyenAccount + /// + public static readonly TypeEnum AdyenAccount = new("adyenAccount"); + + /// + /// TypeEnum.AdyenCapital - adyenCapital + /// + public static readonly TypeEnum AdyenCapital = new("adyenCapital"); + + /// + /// TypeEnum.AdyenCard - adyenCard + /// + public static readonly TypeEnum AdyenCard = new("adyenCard"); + + /// + /// TypeEnum.AdyenChargeCard - adyenChargeCard + /// + public static readonly TypeEnum AdyenChargeCard = new("adyenChargeCard"); + + /// + /// TypeEnum.AdyenForPlatformsAdvanced - adyenForPlatformsAdvanced + /// + public static readonly TypeEnum AdyenForPlatformsAdvanced = new("adyenForPlatformsAdvanced"); + + /// + /// TypeEnum.AdyenForPlatformsManage - adyenForPlatformsManage + /// + public static readonly TypeEnum AdyenForPlatformsManage = new("adyenForPlatformsManage"); + + /// + /// TypeEnum.AdyenFranchisee - adyenFranchisee + /// + public static readonly TypeEnum AdyenFranchisee = new("adyenFranchisee"); + + /// + /// TypeEnum.AdyenIssuing - adyenIssuing + /// + public static readonly TypeEnum AdyenIssuing = new("adyenIssuing"); + + /// + /// TypeEnum.AdyenPccr - adyenPccr + /// + public static readonly TypeEnum AdyenPccr = new("adyenPccr"); + + /// + /// TypeEnum.KycOnInvite - kycOnInvite + /// + public static readonly TypeEnum KycOnInvite = new("kycOnInvite"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "adyenAccount" => TypeEnum.AdyenAccount, + "adyenCapital" => TypeEnum.AdyenCapital, + "adyenCard" => TypeEnum.AdyenCard, + "adyenChargeCard" => TypeEnum.AdyenChargeCard, + "adyenForPlatformsAdvanced" => TypeEnum.AdyenForPlatformsAdvanced, + "adyenForPlatformsManage" => TypeEnum.AdyenForPlatformsManage, + "adyenFranchisee" => TypeEnum.AdyenFranchisee, + "adyenIssuing" => TypeEnum.AdyenIssuing, + "adyenPccr" => TypeEnum.AdyenPccr, + "kycOnInvite" => TypeEnum.KycOnInvite, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AdyenAccount) + return "adyenAccount"; + + if (value == TypeEnum.AdyenCapital) + return "adyenCapital"; + + if (value == TypeEnum.AdyenCard) + return "adyenCard"; + + if (value == TypeEnum.AdyenChargeCard) + return "adyenChargeCard"; + + if (value == TypeEnum.AdyenForPlatformsAdvanced) + return "adyenForPlatformsAdvanced"; + + if (value == TypeEnum.AdyenForPlatformsManage) + return "adyenForPlatformsManage"; + + if (value == TypeEnum.AdyenFranchisee) + return "adyenFranchisee"; + + if (value == TypeEnum.AdyenIssuing) + return "adyenIssuing"; + + if (value == TypeEnum.AdyenPccr) + return "adyenPccr"; + + if (value == TypeEnum.KycOnInvite) + return "kycOnInvite"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + /// + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptedByOption { get; private set; } + + /// + /// The unique identifier of the user that accepted the Terms of Service. + /// + /// The unique identifier of the user that accepted the Terms of Service. + [JsonPropertyName("acceptedBy")] + public string? AcceptedBy { get { return this._AcceptedByOption; } set { this._AcceptedByOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptedForOption { get; private set; } + + /// + /// The unique identifier of the legal entity for which the Terms of Service are accepted. + /// + /// The unique identifier of the legal entity for which the Terms of Service are accepted. + [JsonPropertyName("acceptedFor")] + public string? AcceptedFor { get { return this._AcceptedForOption; } set { this._AcceptedForOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date when the Terms of Service were accepted, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00. + /// + /// The date when the Terms of Service were accepted, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00. + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// An Adyen-generated reference for the accepted Terms of Service. + /// + /// An Adyen-generated reference for the accepted Terms of Service. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValidToOption { get; private set; } + + /// + /// The expiration date for the Terms of Service acceptance, in ISO 8601 extended format. For example, 2022-12-18T00:00:00+01:00. + /// + /// The expiration date for the Terms of Service acceptance, in ISO 8601 extended format. For example, 2022-12-18T00:00:00+01:00. + [JsonPropertyName("validTo")] + public DateTimeOffset? ValidTo { get { return this._ValidToOption; } set { this._ValidToOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TermsOfServiceAcceptanceInfo {\n"); + sb.Append(" AcceptedBy: ").Append(AcceptedBy).Append("\n"); + sb.Append(" AcceptedFor: ").Append(AcceptedFor).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidTo: ").Append(ValidTo).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TermsOfServiceAcceptanceInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValidTo. + /// + public static string ValidToFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TermsOfServiceAcceptanceInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptedBy = default; + Option acceptedFor = default; + Option createdAt = default; + Option id = default; + Option type = default; + Option validTo = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptedBy": + acceptedBy = new Option(utf8JsonReader.GetString()!); + break; + case "acceptedFor": + acceptedFor = new Option(utf8JsonReader.GetString()!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TermsOfServiceAcceptanceInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "validTo": + validTo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new TermsOfServiceAcceptanceInfo(acceptedBy, acceptedFor, createdAt, id, type, validTo); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TermsOfServiceAcceptanceInfo termsOfServiceAcceptanceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, termsOfServiceAcceptanceInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TermsOfServiceAcceptanceInfo termsOfServiceAcceptanceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (termsOfServiceAcceptanceInfo._AcceptedByOption.IsSet) + if (termsOfServiceAcceptanceInfo.AcceptedBy != null) + writer.WriteString("acceptedBy", termsOfServiceAcceptanceInfo.AcceptedBy); + + if (termsOfServiceAcceptanceInfo._AcceptedForOption.IsSet) + if (termsOfServiceAcceptanceInfo.AcceptedFor != null) + writer.WriteString("acceptedFor", termsOfServiceAcceptanceInfo.AcceptedFor); + + if (termsOfServiceAcceptanceInfo._CreatedAtOption.IsSet) + writer.WriteString("createdAt", termsOfServiceAcceptanceInfo._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (termsOfServiceAcceptanceInfo._IdOption.IsSet) + if (termsOfServiceAcceptanceInfo.Id != null) + writer.WriteString("id", termsOfServiceAcceptanceInfo.Id); + + if (termsOfServiceAcceptanceInfo._TypeOption.IsSet && termsOfServiceAcceptanceInfo.Type != null) + { + string? typeRawValue = TermsOfServiceAcceptanceInfo.TypeEnum.ToJsonValue(termsOfServiceAcceptanceInfo._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (termsOfServiceAcceptanceInfo._ValidToOption.IsSet) + writer.WriteString("validTo", termsOfServiceAcceptanceInfo._ValidToOption.Value!.Value.ToString(ValidToFormat)); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TransferInstrument.cs b/Adyen/LegalEntityManagement/Models/TransferInstrument.cs new file mode 100644 index 000000000..75635854d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TransferInstrument.cs @@ -0,0 +1,415 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TransferInstrument. + /// + public partial class TransferInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bankAccount + /// The unique identifier of the transfer instrument. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + /// The type of transfer instrument. Possible value: **bankAccount**. + /// List of capabilities for this transfer instrument. + /// List of documents uploaded for the transfer instrument. + /// The verification errors related to capabilities for this transfer instrument. + [JsonConstructor] + public TransferInstrument(BankAccountInfo bankAccount, string id, string legalEntityId, TypeEnum type, Option?> capabilities = default, Option?> documentDetails = default, Option?> problems = default) + { + BankAccount = bankAccount; + Id = id; + LegalEntityId = legalEntityId; + Type = type; + _CapabilitiesOption = capabilities; + _DocumentDetailsOption = documentDetails; + _ProblemsOption = problems; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferInstrument() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.RecurringDetail - recurringDetail + /// + public static readonly TypeEnum RecurringDetail = new("recurringDetail"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "recurringDetail" => TypeEnum.RecurringDetail, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.RecurringDetail) + return "recurringDetail"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountInfo BankAccount { get; set; } + + /// + /// The unique identifier of the transfer instrument. + /// + /// The unique identifier of the transfer instrument. + [JsonPropertyName("id")] + public string Id { get; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// List of capabilities for this transfer instrument. + /// + /// List of capabilities for this transfer instrument. + [JsonPropertyName("capabilities")] + public Dictionary? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentDetailsOption { get; private set; } + + /// + /// List of documents uploaded for the transfer instrument. + /// + /// List of documents uploaded for the transfer instrument. + [JsonPropertyName("documentDetails")] + public List? DocumentDetails { get { return this._DocumentDetailsOption; } set { this._DocumentDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// The verification errors related to capabilities for this transfer instrument. + /// + /// The verification errors related to capabilities for this transfer instrument. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferInstrument {\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" DocumentDetails: ").Append(DocumentDetails).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccount = default; + Option id = default; + Option legalEntityId = default; + Option type = default; + Option?> capabilities = default; + Option?> documentDetails = default; + Option?> problems = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferInstrument.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "documentDetails": + documentDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!bankAccount.IsSet) + throw new ArgumentException("Property is required for class TransferInstrument.", nameof(bankAccount)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TransferInstrument.", nameof(id)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class TransferInstrument.", nameof(legalEntityId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransferInstrument.", nameof(type)); + + return new TransferInstrument(bankAccount.Value!, id.Value!, legalEntityId.Value!, type.Value!.Value!, capabilities, documentDetails, problems); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferInstrument transferInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferInstrument transferInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, transferInstrument.BankAccount, jsonSerializerOptions); + if (transferInstrument.Id != null) + writer.WriteString("id", transferInstrument.Id); + + if (transferInstrument.LegalEntityId != null) + writer.WriteString("legalEntityId", transferInstrument.LegalEntityId); + + if (transferInstrument.Type != null) + { + string? typeRawValue = TransferInstrument.TypeEnum.ToJsonValue(transferInstrument.Type); + writer.WriteString("type", typeRawValue); + } + + if (transferInstrument._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, transferInstrument.Capabilities, jsonSerializerOptions); + } + if (transferInstrument._DocumentDetailsOption.IsSet) + { + writer.WritePropertyName("documentDetails"); + JsonSerializer.Serialize(writer, transferInstrument.DocumentDetails, jsonSerializerOptions); + } + if (transferInstrument._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, transferInstrument.Problems, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TransferInstrumentInfo.cs b/Adyen/LegalEntityManagement/Models/TransferInstrumentInfo.cs new file mode 100644 index 000000000..396919d00 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TransferInstrumentInfo.cs @@ -0,0 +1,316 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TransferInstrumentInfo. + /// + public partial class TransferInstrumentInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bankAccount + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + /// The type of transfer instrument. Possible value: **bankAccount**. + [JsonConstructor] + public TransferInstrumentInfo(BankAccountInfo bankAccount, string legalEntityId, TypeEnum type) + { + BankAccount = bankAccount; + LegalEntityId = legalEntityId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferInstrumentInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - bankAccount + /// + public static readonly TypeEnum BankAccount = new("bankAccount"); + + /// + /// TypeEnum.RecurringDetail - recurringDetail + /// + public static readonly TypeEnum RecurringDetail = new("recurringDetail"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankAccount" => TypeEnum.BankAccount, + "recurringDetail" => TypeEnum.RecurringDetail, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "bankAccount"; + + if (value == TypeEnum.RecurringDetail) + return "recurringDetail"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + /// + /// The type of transfer instrument. Possible value: **bankAccount**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountInfo BankAccount { get; set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id) that owns the transfer instrument. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferInstrumentInfo {\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferInstrumentInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferInstrumentInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccount = default; + Option legalEntityId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferInstrumentInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!bankAccount.IsSet) + throw new ArgumentException("Property is required for class TransferInstrumentInfo.", nameof(bankAccount)); + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class TransferInstrumentInfo.", nameof(legalEntityId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransferInstrumentInfo.", nameof(type)); + + return new TransferInstrumentInfo(bankAccount.Value!, legalEntityId.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferInstrumentInfo transferInstrumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferInstrumentInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferInstrumentInfo transferInstrumentInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, transferInstrumentInfo.BankAccount, jsonSerializerOptions); + if (transferInstrumentInfo.LegalEntityId != null) + writer.WriteString("legalEntityId", transferInstrumentInfo.LegalEntityId); + + if (transferInstrumentInfo.Type != null) + { + string? typeRawValue = TransferInstrumentInfo.TypeEnum.ToJsonValue(transferInstrumentInfo.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/TransferInstrumentReference.cs b/Adyen/LegalEntityManagement/Models/TransferInstrumentReference.cs new file mode 100644 index 000000000..815ee29f1 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/TransferInstrumentReference.cs @@ -0,0 +1,240 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// TransferInstrumentReference. + /// + public partial class TransferInstrumentReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The masked IBAN or bank account number. + /// The unique identifier of the resource. + /// Four last digits of the bank account number. If the transfer instrument is created using [instant bank account verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding), and it is a virtual bank account, these digits may be different from the last four digits of the masked account number. + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + [JsonConstructor] + public TransferInstrumentReference(string accountIdentifier, string id, Option realLastFour = default, Option trustedSource = default) + { + AccountIdentifier = accountIdentifier; + Id = id; + _RealLastFourOption = realLastFour; + _TrustedSourceOption = trustedSource; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferInstrumentReference() + { + } + + partial void OnCreated(); + + /// + /// The masked IBAN or bank account number. + /// + /// The masked IBAN or bank account number. + [JsonPropertyName("accountIdentifier")] + public string AccountIdentifier { get; set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RealLastFourOption { get; private set; } + + /// + /// Four last digits of the bank account number. If the transfer instrument is created using [instant bank account verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding), and it is a virtual bank account, these digits may be different from the last four digits of the masked account number. + /// + /// Four last digits of the bank account number. If the transfer instrument is created using [instant bank account verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding), and it is a virtual bank account, these digits may be different from the last four digits of the masked account number. + [JsonPropertyName("realLastFour")] + public string? RealLastFour { get { return this._RealLastFourOption; } set { this._RealLastFourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedSourceOption { get; } + + /// + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + /// + /// Identifies if the bank account was created through [instant bank verification](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-08-hosted-onboarding). + [JsonPropertyName("trustedSource")] + public bool? TrustedSource { get { return this._TrustedSourceOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferInstrumentReference {\n"); + sb.Append(" AccountIdentifier: ").Append(AccountIdentifier).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" RealLastFour: ").Append(RealLastFour).Append("\n"); + sb.Append(" TrustedSource: ").Append(TrustedSource).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferInstrumentReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferInstrumentReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountIdentifier = default; + Option id = default; + Option realLastFour = default; + Option trustedSource = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountIdentifier": + accountIdentifier = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "realLastFour": + realLastFour = new Option(utf8JsonReader.GetString()!); + break; + case "trustedSource": + trustedSource = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!accountIdentifier.IsSet) + throw new ArgumentException("Property is required for class TransferInstrumentReference.", nameof(accountIdentifier)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TransferInstrumentReference.", nameof(id)); + + return new TransferInstrumentReference(accountIdentifier.Value!, id.Value!, realLastFour, trustedSource); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferInstrumentReference transferInstrumentReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferInstrumentReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferInstrumentReference transferInstrumentReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferInstrumentReference.AccountIdentifier != null) + writer.WriteString("accountIdentifier", transferInstrumentReference.AccountIdentifier); + + if (transferInstrumentReference.Id != null) + writer.WriteString("id", transferInstrumentReference.Id); + + if (transferInstrumentReference._RealLastFourOption.IsSet) + if (transferInstrumentReference.RealLastFour != null) + writer.WriteString("realLastFour", transferInstrumentReference.RealLastFour); + + if (transferInstrumentReference._TrustedSourceOption.IsSet) + writer.WriteBoolean("trustedSource", transferInstrumentReference._TrustedSourceOption.Value!.Value); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/Trust.cs b/Adyen/LegalEntityManagement/Models/Trust.cs new file mode 100644 index 000000000..ae31225d8 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/Trust.cs @@ -0,0 +1,849 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// Trust. + /// + public partial class Trust : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// The legal name. + /// registeredAddress + /// Type of trust. See possible values for trusts in [Australia](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-australia) and [New Zealand](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-new-zealand). + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// A short description about the trust. Only applicable for charitable trusts in New Zealand. + /// The registered name, if different from the `name`. + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// principalPlaceOfBusiness + /// The registration number. + /// The tax information of the entity. + /// The undefined beneficiary information of the entity. + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// The VAT number. + [JsonConstructor] + public Trust(string countryOfGoverningLaw, string name, Address registeredAddress, TypeEnum type, Option dateOfIncorporation = default, Option description = default, Option doingBusinessAs = default, Option doingBusinessAsAbsent = default, Option principalPlaceOfBusiness = default, Option registrationNumber = default, Option?> taxInformation = default, Option?> undefinedBeneficiaryInfo = default, Option vatAbsenceReason = default, Option vatNumber = default) + { + CountryOfGoverningLaw = countryOfGoverningLaw; + Name = name; + RegisteredAddress = registeredAddress; + Type = type; + _DateOfIncorporationOption = dateOfIncorporation; + _DescriptionOption = description; + _DoingBusinessAsOption = doingBusinessAs; + _DoingBusinessAsAbsentOption = doingBusinessAsAbsent; + _PrincipalPlaceOfBusinessOption = principalPlaceOfBusiness; + _RegistrationNumberOption = registrationNumber; + _TaxInformationOption = taxInformation; + _UndefinedBeneficiaryInfoOption = undefinedBeneficiaryInfo; + _VatAbsenceReasonOption = vatAbsenceReason; + _VatNumberOption = vatNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Trust() + { + } + + partial void OnCreated(); + + /// + /// Type of trust. See possible values for trusts in [Australia](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-australia) and [New Zealand](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-new-zealand). + /// + /// Type of trust. See possible values for trusts in [Australia](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-australia) and [New Zealand](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-new-zealand). + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BusinessTrust - businessTrust + /// + public static readonly TypeEnum BusinessTrust = new("businessTrust"); + + /// + /// TypeEnum.CashManagementTrust - cashManagementTrust + /// + public static readonly TypeEnum CashManagementTrust = new("cashManagementTrust"); + + /// + /// TypeEnum.CharitableTrust - charitableTrust + /// + public static readonly TypeEnum CharitableTrust = new("charitableTrust"); + + /// + /// TypeEnum.CorporateUnitTrust - corporateUnitTrust + /// + public static readonly TypeEnum CorporateUnitTrust = new("corporateUnitTrust"); + + /// + /// TypeEnum.DeceasedEstate - deceasedEstate + /// + public static readonly TypeEnum DeceasedEstate = new("deceasedEstate"); + + /// + /// TypeEnum.DiscretionaryTrust - discretionaryTrust + /// + public static readonly TypeEnum DiscretionaryTrust = new("discretionaryTrust"); + + /// + /// TypeEnum.DiscretionaryInvestmentTrust - discretionaryInvestmentTrust + /// + public static readonly TypeEnum DiscretionaryInvestmentTrust = new("discretionaryInvestmentTrust"); + + /// + /// TypeEnum.DiscretionaryServicesManagementTrust - discretionaryServicesManagementTrust + /// + public static readonly TypeEnum DiscretionaryServicesManagementTrust = new("discretionaryServicesManagementTrust"); + + /// + /// TypeEnum.DiscretionaryTradingTrust - discretionaryTradingTrust + /// + public static readonly TypeEnum DiscretionaryTradingTrust = new("discretionaryTradingTrust"); + + /// + /// TypeEnum.FamilyTrust - familyTrust + /// + public static readonly TypeEnum FamilyTrust = new("familyTrust"); + + /// + /// TypeEnum.FirstHomeSaverAccountsTrust - firstHomeSaverAccountsTrust + /// + public static readonly TypeEnum FirstHomeSaverAccountsTrust = new("firstHomeSaverAccountsTrust"); + + /// + /// TypeEnum.FixedTrust - fixedTrust + /// + public static readonly TypeEnum FixedTrust = new("fixedTrust"); + + /// + /// TypeEnum.FixedUnitTrust - fixedUnitTrust + /// + public static readonly TypeEnum FixedUnitTrust = new("fixedUnitTrust"); + + /// + /// TypeEnum.HybridTrust - hybridTrust + /// + public static readonly TypeEnum HybridTrust = new("hybridTrust"); + + /// + /// TypeEnum.ListedPublicUnitTrust - listedPublicUnitTrust + /// + public static readonly TypeEnum ListedPublicUnitTrust = new("listedPublicUnitTrust"); + + /// + /// TypeEnum.OtherTrust - otherTrust + /// + public static readonly TypeEnum OtherTrust = new("otherTrust"); + + /// + /// TypeEnum.PooledSuperannuationTrust - pooledSuperannuationTrust + /// + public static readonly TypeEnum PooledSuperannuationTrust = new("pooledSuperannuationTrust"); + + /// + /// TypeEnum.PublicTradingTrust - publicTradingTrust + /// + public static readonly TypeEnum PublicTradingTrust = new("publicTradingTrust"); + + /// + /// TypeEnum.UnlistedPublicUnitTrust - unlistedPublicUnitTrust + /// + public static readonly TypeEnum UnlistedPublicUnitTrust = new("unlistedPublicUnitTrust"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "businessTrust" => TypeEnum.BusinessTrust, + "cashManagementTrust" => TypeEnum.CashManagementTrust, + "charitableTrust" => TypeEnum.CharitableTrust, + "corporateUnitTrust" => TypeEnum.CorporateUnitTrust, + "deceasedEstate" => TypeEnum.DeceasedEstate, + "discretionaryTrust" => TypeEnum.DiscretionaryTrust, + "discretionaryInvestmentTrust" => TypeEnum.DiscretionaryInvestmentTrust, + "discretionaryServicesManagementTrust" => TypeEnum.DiscretionaryServicesManagementTrust, + "discretionaryTradingTrust" => TypeEnum.DiscretionaryTradingTrust, + "familyTrust" => TypeEnum.FamilyTrust, + "firstHomeSaverAccountsTrust" => TypeEnum.FirstHomeSaverAccountsTrust, + "fixedTrust" => TypeEnum.FixedTrust, + "fixedUnitTrust" => TypeEnum.FixedUnitTrust, + "hybridTrust" => TypeEnum.HybridTrust, + "listedPublicUnitTrust" => TypeEnum.ListedPublicUnitTrust, + "otherTrust" => TypeEnum.OtherTrust, + "pooledSuperannuationTrust" => TypeEnum.PooledSuperannuationTrust, + "publicTradingTrust" => TypeEnum.PublicTradingTrust, + "unlistedPublicUnitTrust" => TypeEnum.UnlistedPublicUnitTrust, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BusinessTrust) + return "businessTrust"; + + if (value == TypeEnum.CashManagementTrust) + return "cashManagementTrust"; + + if (value == TypeEnum.CharitableTrust) + return "charitableTrust"; + + if (value == TypeEnum.CorporateUnitTrust) + return "corporateUnitTrust"; + + if (value == TypeEnum.DeceasedEstate) + return "deceasedEstate"; + + if (value == TypeEnum.DiscretionaryTrust) + return "discretionaryTrust"; + + if (value == TypeEnum.DiscretionaryInvestmentTrust) + return "discretionaryInvestmentTrust"; + + if (value == TypeEnum.DiscretionaryServicesManagementTrust) + return "discretionaryServicesManagementTrust"; + + if (value == TypeEnum.DiscretionaryTradingTrust) + return "discretionaryTradingTrust"; + + if (value == TypeEnum.FamilyTrust) + return "familyTrust"; + + if (value == TypeEnum.FirstHomeSaverAccountsTrust) + return "firstHomeSaverAccountsTrust"; + + if (value == TypeEnum.FixedTrust) + return "fixedTrust"; + + if (value == TypeEnum.FixedUnitTrust) + return "fixedUnitTrust"; + + if (value == TypeEnum.HybridTrust) + return "hybridTrust"; + + if (value == TypeEnum.ListedPublicUnitTrust) + return "listedPublicUnitTrust"; + + if (value == TypeEnum.OtherTrust) + return "otherTrust"; + + if (value == TypeEnum.PooledSuperannuationTrust) + return "pooledSuperannuationTrust"; + + if (value == TypeEnum.PublicTradingTrust) + return "publicTradingTrust"; + + if (value == TypeEnum.UnlistedPublicUnitTrust) + return "unlistedPublicUnitTrust"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of trust. See possible values for trusts in [Australia](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-australia) and [New Zealand](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-new-zealand). + /// + /// Type of trust. See possible values for trusts in [Australia](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-australia) and [New Zealand](https://docs.adyen.com/platforms/verification-requirements/?tab=trust_3_4#trust-types-in-new-zealand). + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonConverter(typeof(VatAbsenceReasonEnumJsonConverter))] + public class VatAbsenceReasonEnum : IEnum + { + /// + /// Returns the value of the VatAbsenceReasonEnum. + /// + public string? Value { get; set; } + + /// + /// VatAbsenceReasonEnum.IndustryExemption - industryExemption + /// + public static readonly VatAbsenceReasonEnum IndustryExemption = new("industryExemption"); + + /// + /// VatAbsenceReasonEnum.BelowTaxThreshold - belowTaxThreshold + /// + public static readonly VatAbsenceReasonEnum BelowTaxThreshold = new("belowTaxThreshold"); + + private VatAbsenceReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VatAbsenceReasonEnum?(string? value) => value == null ? null : new VatAbsenceReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VatAbsenceReasonEnum? option) => option?.Value; + + public static bool operator ==(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VatAbsenceReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VatAbsenceReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "industryExemption" => VatAbsenceReasonEnum.IndustryExemption, + "belowTaxThreshold" => VatAbsenceReasonEnum.BelowTaxThreshold, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VatAbsenceReasonEnum? value) + { + if (value == null) + return null; + + if (value == VatAbsenceReasonEnum.IndustryExemption) + return "industryExemption"; + + if (value == VatAbsenceReasonEnum.BelowTaxThreshold) + return "belowTaxThreshold"; + + return null; + } + + /// + /// JsonConverter for writing VatAbsenceReasonEnum. + /// + public class VatAbsenceReasonEnumJsonConverter : JsonConverter + { + public override VatAbsenceReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VatAbsenceReasonEnum.FromStringOrDefault(value) ?? new VatAbsenceReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VatAbsenceReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VatAbsenceReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatAbsenceReasonOption { get; private set; } + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonPropertyName("vatAbsenceReason")] + public VatAbsenceReasonEnum? VatAbsenceReason { get { return this._VatAbsenceReasonOption; } set { this._VatAbsenceReasonOption = new(value); } } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + [JsonPropertyName("countryOfGoverningLaw")] + public string CountryOfGoverningLaw { get; set; } + + /// + /// The legal name. + /// + /// The legal name. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// . + /// + [JsonPropertyName("registeredAddress")] + public Address RegisteredAddress { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfIncorporationOption { get; private set; } + + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + [JsonPropertyName("dateOfIncorporation")] + public string? DateOfIncorporation { get { return this._DateOfIncorporationOption; } set { this._DateOfIncorporationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// A short description about the trust. Only applicable for charitable trusts in New Zealand. + /// + /// A short description about the trust. Only applicable for charitable trusts in New Zealand. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsOption { get; private set; } + + /// + /// The registered name, if different from the `name`. + /// + /// The registered name, if different from the `name`. + [JsonPropertyName("doingBusinessAs")] + public string? DoingBusinessAs { get { return this._DoingBusinessAsOption; } set { this._DoingBusinessAsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsAbsentOption { get; private set; } + + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + [JsonPropertyName("doingBusinessAsAbsent")] + public bool? DoingBusinessAsAbsent { get { return this._DoingBusinessAsAbsentOption; } set { this._DoingBusinessAsAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrincipalPlaceOfBusinessOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("principalPlaceOfBusiness")] + public Address? PrincipalPlaceOfBusiness { get { return this._PrincipalPlaceOfBusinessOption; } set { this._PrincipalPlaceOfBusinessOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberOption { get; private set; } + + /// + /// The registration number. + /// + /// The registration number. + [JsonPropertyName("registrationNumber")] + public string? RegistrationNumber { get { return this._RegistrationNumberOption; } set { this._RegistrationNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TaxInformationOption { get; private set; } + + /// + /// The tax information of the entity. + /// + /// The tax information of the entity. + [JsonPropertyName("taxInformation")] + public List? TaxInformation { get { return this._TaxInformationOption; } set { this._TaxInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _UndefinedBeneficiaryInfoOption { get; private set; } + + /// + /// The undefined beneficiary information of the entity. + /// + /// The undefined beneficiary information of the entity. + [JsonPropertyName("undefinedBeneficiaryInfo")] + public List? UndefinedBeneficiaryInfo { get { return this._UndefinedBeneficiaryInfoOption; } set { this._UndefinedBeneficiaryInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatNumberOption { get; private set; } + + /// + /// The VAT number. + /// + /// The VAT number. + [JsonPropertyName("vatNumber")] + public string? VatNumber { get { return this._VatNumberOption; } set { this._VatNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Trust {\n"); + sb.Append(" CountryOfGoverningLaw: ").Append(CountryOfGoverningLaw).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RegisteredAddress: ").Append(RegisteredAddress).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" DateOfIncorporation: ").Append(DateOfIncorporation).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DoingBusinessAs: ").Append(DoingBusinessAs).Append("\n"); + sb.Append(" DoingBusinessAsAbsent: ").Append(DoingBusinessAsAbsent).Append("\n"); + sb.Append(" PrincipalPlaceOfBusiness: ").Append(PrincipalPlaceOfBusiness).Append("\n"); + sb.Append(" RegistrationNumber: ").Append(RegistrationNumber).Append("\n"); + sb.Append(" TaxInformation: ").Append(TaxInformation).Append("\n"); + sb.Append(" UndefinedBeneficiaryInfo: ").Append(UndefinedBeneficiaryInfo).Append("\n"); + sb.Append(" VatAbsenceReason: ").Append(VatAbsenceReason).Append("\n"); + sb.Append(" VatNumber: ").Append(VatNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TrustJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Trust Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option countryOfGoverningLaw = default; + Option name = default; + Option registeredAddress = default; + Option type = default; + Option dateOfIncorporation = default; + Option description = default; + Option doingBusinessAs = default; + Option doingBusinessAsAbsent = default; + Option principalPlaceOfBusiness = default; + Option registrationNumber = default; + Option?> taxInformation = default; + Option?> undefinedBeneficiaryInfo = default; + Option vatAbsenceReason = default; + Option vatNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "countryOfGoverningLaw": + countryOfGoverningLaw = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "registeredAddress": + registeredAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Trust.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "dateOfIncorporation": + dateOfIncorporation = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAs": + doingBusinessAs = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAsAbsent": + doingBusinessAsAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "principalPlaceOfBusiness": + principalPlaceOfBusiness = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "registrationNumber": + registrationNumber = new Option(utf8JsonReader.GetString()!); + break; + case "taxInformation": + taxInformation = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "undefinedBeneficiaryInfo": + undefinedBeneficiaryInfo = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "vatAbsenceReason": + string? vatAbsenceReasonRawValue = utf8JsonReader.GetString(); + vatAbsenceReason = new Option(Trust.VatAbsenceReasonEnum.FromStringOrDefault(vatAbsenceReasonRawValue)); + break; + case "vatNumber": + vatNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!countryOfGoverningLaw.IsSet) + throw new ArgumentException("Property is required for class Trust.", nameof(countryOfGoverningLaw)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class Trust.", nameof(name)); + + if (!registeredAddress.IsSet) + throw new ArgumentException("Property is required for class Trust.", nameof(registeredAddress)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Trust.", nameof(type)); + + return new Trust(countryOfGoverningLaw.Value!, name.Value!, registeredAddress.Value!, type.Value!.Value!, dateOfIncorporation, description, doingBusinessAs, doingBusinessAsAbsent, principalPlaceOfBusiness, registrationNumber, taxInformation, undefinedBeneficiaryInfo, vatAbsenceReason, vatNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Trust trust, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, trust, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Trust trust, JsonSerializerOptions jsonSerializerOptions) + { + + if (trust.CountryOfGoverningLaw != null) + writer.WriteString("countryOfGoverningLaw", trust.CountryOfGoverningLaw); + + if (trust.Name != null) + writer.WriteString("name", trust.Name); + + writer.WritePropertyName("registeredAddress"); + JsonSerializer.Serialize(writer, trust.RegisteredAddress, jsonSerializerOptions); + if (trust.Type != null) + { + string? typeRawValue = Trust.TypeEnum.ToJsonValue(trust.Type); + writer.WriteString("type", typeRawValue); + } + + if (trust._DateOfIncorporationOption.IsSet) + if (trust.DateOfIncorporation != null) + writer.WriteString("dateOfIncorporation", trust.DateOfIncorporation); + + if (trust._DescriptionOption.IsSet) + if (trust.Description != null) + writer.WriteString("description", trust.Description); + + if (trust._DoingBusinessAsOption.IsSet) + if (trust.DoingBusinessAs != null) + writer.WriteString("doingBusinessAs", trust.DoingBusinessAs); + + if (trust._DoingBusinessAsAbsentOption.IsSet) + if (trust._DoingBusinessAsAbsentOption.Value != null) + writer.WriteBoolean("doingBusinessAsAbsent", trust._DoingBusinessAsAbsentOption.Value!.Value); + else + writer.WriteNull("doingBusinessAsAbsent"); + + if (trust._PrincipalPlaceOfBusinessOption.IsSet) + { + writer.WritePropertyName("principalPlaceOfBusiness"); + JsonSerializer.Serialize(writer, trust.PrincipalPlaceOfBusiness, jsonSerializerOptions); + } + if (trust._RegistrationNumberOption.IsSet) + if (trust.RegistrationNumber != null) + writer.WriteString("registrationNumber", trust.RegistrationNumber); + + if (trust._TaxInformationOption.IsSet) + { + writer.WritePropertyName("taxInformation"); + JsonSerializer.Serialize(writer, trust.TaxInformation, jsonSerializerOptions); + } + if (trust._UndefinedBeneficiaryInfoOption.IsSet) + { + writer.WritePropertyName("undefinedBeneficiaryInfo"); + JsonSerializer.Serialize(writer, trust.UndefinedBeneficiaryInfo, jsonSerializerOptions); + } + if (trust._VatAbsenceReasonOption.IsSet && trust.VatAbsenceReason != null) + { + string? vatAbsenceReasonRawValue = Trust.VatAbsenceReasonEnum.ToJsonValue(trust._VatAbsenceReasonOption.Value!.Value); + writer.WriteString("vatAbsenceReason", vatAbsenceReasonRawValue); + } + + if (trust._VatNumberOption.IsSet) + if (trust.VatNumber != null) + writer.WriteString("vatNumber", trust.VatNumber); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/UKLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/UKLocalAccountIdentification.cs new file mode 100644 index 000000000..671f0ec2b --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/UKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// UKLocalAccountIdentification. + /// + public partial class UKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 8-digit bank account number, without separators or whitespace. + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **ukLocal** (default to TypeEnum.UkLocal) + [JsonConstructor] + public UKLocalAccountIdentification(string accountNumber, string sortCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + SortCode = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UkLocal - ukLocal + /// + public static readonly TypeEnum UkLocal = new("ukLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ukLocal" => TypeEnum.UkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UkLocal) + return "ukLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 8-digit bank account number, without separators or whitespace. + /// + /// The 8-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string SortCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 8.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 8.", new [] { "AccountNumber" }); + } + + // SortCode (string) maxLength + if (this.SortCode != null && this.SortCode.Length > 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be less than 6.", new [] { "SortCode" }); + } + + // SortCode (string) minLength + if (this.SortCode != null && this.SortCode.Length < 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be greater than 6.", new [] { "SortCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(accountNumber)); + + if (!sortCode.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(sortCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(type)); + + return new UKLocalAccountIdentification(accountNumber.Value!, sortCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uKLocalAccountIdentification.AccountNumber); + + if (uKLocalAccountIdentification.SortCode != null) + writer.WriteString("sortCode", uKLocalAccountIdentification.SortCode); + + if (uKLocalAccountIdentification.Type != null) + { + string? typeRawValue = UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/USLocalAccountIdentification.cs b/Adyen/LegalEntityManagement/Models/USLocalAccountIdentification.cs new file mode 100644 index 000000000..f4c9d2310 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/USLocalAccountIdentification.cs @@ -0,0 +1,464 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// USLocalAccountIdentification. + /// + public partial class USLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **usLocal** (default to TypeEnum.UsLocal) + [JsonConstructor] + public USLocalAccountIdentification(string accountNumber, string routingNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + RoutingNumber = routingNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsLocal - usLocal + /// + public static readonly TypeEnum UsLocal = new("usLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usLocal" => TypeEnum.UsLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsLocal) + return "usLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string RoutingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 18) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 18.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // RoutingNumber (string) maxLength + if (this.RoutingNumber != null && this.RoutingNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be less than 9.", new [] { "RoutingNumber" }); + } + + // RoutingNumber (string) minLength + if (this.RoutingNumber != null && this.RoutingNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be greater than 9.", new [] { "RoutingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option routingNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(USLocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(accountNumber)); + + if (!routingNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(routingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(type)); + + return new USLocalAccountIdentification(accountNumber.Value!, routingNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uSLocalAccountIdentification.AccountNumber); + + if (uSLocalAccountIdentification.RoutingNumber != null) + writer.WriteString("routingNumber", uSLocalAccountIdentification.RoutingNumber); + + if (uSLocalAccountIdentification._AccountTypeOption.IsSet && uSLocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (uSLocalAccountIdentification.Type != null) + { + string? typeRawValue = USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/UndefinedBeneficiary.cs b/Adyen/LegalEntityManagement/Models/UndefinedBeneficiary.cs new file mode 100644 index 000000000..53f8b8140 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/UndefinedBeneficiary.cs @@ -0,0 +1,202 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// UndefinedBeneficiary. + /// + public partial class UndefinedBeneficiary : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The details of the undefined beneficiary. + /// The reference of the undefined beneficiary. + [JsonConstructor] + public UndefinedBeneficiary(Option description = default, Option reference = default) + { + _DescriptionOption = description; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UndefinedBeneficiary() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The details of the undefined beneficiary. + /// + /// The details of the undefined beneficiary. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; } + + /// + /// The reference of the undefined beneficiary. + /// + /// The reference of the undefined beneficiary. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UndefinedBeneficiary {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UndefinedBeneficiaryJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UndefinedBeneficiary Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UndefinedBeneficiary(description, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UndefinedBeneficiary undefinedBeneficiary, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, undefinedBeneficiary, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UndefinedBeneficiary undefinedBeneficiary, JsonSerializerOptions jsonSerializerOptions) + { + + if (undefinedBeneficiary._DescriptionOption.IsSet) + if (undefinedBeneficiary.Description != null) + writer.WriteString("description", undefinedBeneficiary.Description); + + if (undefinedBeneficiary._ReferenceOption.IsSet) + if (undefinedBeneficiary.Reference != null) + writer.WriteString("reference", undefinedBeneficiary.Reference); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/UnincorporatedPartnership.cs b/Adyen/LegalEntityManagement/Models/UnincorporatedPartnership.cs new file mode 100644 index 000000000..6326d4f5f --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/UnincorporatedPartnership.cs @@ -0,0 +1,908 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// UnincorporatedPartnership. + /// + public partial class UnincorporatedPartnership : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// The legal name. + /// registeredAddress + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// Short description about the Legal Arrangement. + /// The registered name, if different from the `name`. + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// principalPlaceOfBusiness + /// The registration number. + /// The tax information of the entity. + /// Type of Partnership. Possible values: * **limitedPartnership** * **generalPartnership** * **familyPartnership** * **commercialPartnership** * **publicPartnership** * **otherPartnership** * **gbr** * **gmbh** * **kgaa** * **cv** * **vof** * **maatschap** * **privateFundLimitedPartnership** * **businessTrustEntity** * **businessPartnership** * **limitedLiabilityPartnership** * **eg** * **cooperative** * **vos** * **comunidadDeBienes** * **herenciaYacente** * **comunidadDePropietarios** * **sep** * **sca** * **bt** * **kkt** * **scs** * **snc** + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// The VAT number. + [JsonConstructor] + public UnincorporatedPartnership(string countryOfGoverningLaw, string name, Address registeredAddress, Option dateOfIncorporation = default, Option description = default, Option doingBusinessAs = default, Option doingBusinessAsAbsent = default, Option principalPlaceOfBusiness = default, Option registrationNumber = default, Option?> taxInformation = default, Option type = default, Option vatAbsenceReason = default, Option vatNumber = default) + { + CountryOfGoverningLaw = countryOfGoverningLaw; + Name = name; + RegisteredAddress = registeredAddress; + _DateOfIncorporationOption = dateOfIncorporation; + _DescriptionOption = description; + _DoingBusinessAsOption = doingBusinessAs; + _DoingBusinessAsAbsentOption = doingBusinessAsAbsent; + _PrincipalPlaceOfBusinessOption = principalPlaceOfBusiness; + _RegistrationNumberOption = registrationNumber; + _TaxInformationOption = taxInformation; + _TypeOption = type; + _VatAbsenceReasonOption = vatAbsenceReason; + _VatNumberOption = vatNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UnincorporatedPartnership() + { + } + + partial void OnCreated(); + + /// + /// Type of Partnership. Possible values: * **limitedPartnership** * **generalPartnership** * **familyPartnership** * **commercialPartnership** * **publicPartnership** * **otherPartnership** * **gbr** * **gmbh** * **kgaa** * **cv** * **vof** * **maatschap** * **privateFundLimitedPartnership** * **businessTrustEntity** * **businessPartnership** * **limitedLiabilityPartnership** * **eg** * **cooperative** * **vos** * **comunidadDeBienes** * **herenciaYacente** * **comunidadDePropietarios** * **sep** * **sca** * **bt** * **kkt** * **scs** * **snc** + /// + /// Type of Partnership. Possible values: * **limitedPartnership** * **generalPartnership** * **familyPartnership** * **commercialPartnership** * **publicPartnership** * **otherPartnership** * **gbr** * **gmbh** * **kgaa** * **cv** * **vof** * **maatschap** * **privateFundLimitedPartnership** * **businessTrustEntity** * **businessPartnership** * **limitedLiabilityPartnership** * **eg** * **cooperative** * **vos** * **comunidadDeBienes** * **herenciaYacente** * **comunidadDePropietarios** * **sep** * **sca** * **bt** * **kkt** * **scs** * **snc** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.LimitedPartnership - limitedPartnership + /// + public static readonly TypeEnum LimitedPartnership = new("limitedPartnership"); + + /// + /// TypeEnum.GeneralPartnership - generalPartnership + /// + public static readonly TypeEnum GeneralPartnership = new("generalPartnership"); + + /// + /// TypeEnum.FamilyPartnership - familyPartnership + /// + public static readonly TypeEnum FamilyPartnership = new("familyPartnership"); + + /// + /// TypeEnum.CommercialPartnership - commercialPartnership + /// + public static readonly TypeEnum CommercialPartnership = new("commercialPartnership"); + + /// + /// TypeEnum.PublicPartnership - publicPartnership + /// + public static readonly TypeEnum PublicPartnership = new("publicPartnership"); + + /// + /// TypeEnum.OtherPartnership - otherPartnership + /// + public static readonly TypeEnum OtherPartnership = new("otherPartnership"); + + /// + /// TypeEnum.Gbr - gbr + /// + public static readonly TypeEnum Gbr = new("gbr"); + + /// + /// TypeEnum.Gmbh - gmbh + /// + public static readonly TypeEnum Gmbh = new("gmbh"); + + /// + /// TypeEnum.Kgaa - kgaa + /// + public static readonly TypeEnum Kgaa = new("kgaa"); + + /// + /// TypeEnum.Cv - cv + /// + public static readonly TypeEnum Cv = new("cv"); + + /// + /// TypeEnum.Vof - vof + /// + public static readonly TypeEnum Vof = new("vof"); + + /// + /// TypeEnum.Maatschap - maatschap + /// + public static readonly TypeEnum Maatschap = new("maatschap"); + + /// + /// TypeEnum.PrivateFundLimitedPartnership - privateFundLimitedPartnership + /// + public static readonly TypeEnum PrivateFundLimitedPartnership = new("privateFundLimitedPartnership"); + + /// + /// TypeEnum.BusinessTrustEntity - businessTrustEntity + /// + public static readonly TypeEnum BusinessTrustEntity = new("businessTrustEntity"); + + /// + /// TypeEnum.BusinessPartnership - businessPartnership + /// + public static readonly TypeEnum BusinessPartnership = new("businessPartnership"); + + /// + /// TypeEnum.LimitedLiabilityPartnership - limitedLiabilityPartnership + /// + public static readonly TypeEnum LimitedLiabilityPartnership = new("limitedLiabilityPartnership"); + + /// + /// TypeEnum.Eg - eg + /// + public static readonly TypeEnum Eg = new("eg"); + + /// + /// TypeEnum.Cooperative - cooperative + /// + public static readonly TypeEnum Cooperative = new("cooperative"); + + /// + /// TypeEnum.Vos - vos + /// + public static readonly TypeEnum Vos = new("vos"); + + /// + /// TypeEnum.ComunidadDeBienes - comunidadDeBienes + /// + public static readonly TypeEnum ComunidadDeBienes = new("comunidadDeBienes"); + + /// + /// TypeEnum.HerenciaYacente - herenciaYacente + /// + public static readonly TypeEnum HerenciaYacente = new("herenciaYacente"); + + /// + /// TypeEnum.ComunidadDePropietarios - comunidadDePropietarios + /// + public static readonly TypeEnum ComunidadDePropietarios = new("comunidadDePropietarios"); + + /// + /// TypeEnum.Sep - sep + /// + public static readonly TypeEnum Sep = new("sep"); + + /// + /// TypeEnum.Sca - sca + /// + public static readonly TypeEnum Sca = new("sca"); + + /// + /// TypeEnum.Bt - bt + /// + public static readonly TypeEnum Bt = new("bt"); + + /// + /// TypeEnum.Kkt - kkt + /// + public static readonly TypeEnum Kkt = new("kkt"); + + /// + /// TypeEnum.Scs - scs + /// + public static readonly TypeEnum Scs = new("scs"); + + /// + /// TypeEnum.Snc - snc + /// + public static readonly TypeEnum Snc = new("snc"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "limitedPartnership" => TypeEnum.LimitedPartnership, + "generalPartnership" => TypeEnum.GeneralPartnership, + "familyPartnership" => TypeEnum.FamilyPartnership, + "commercialPartnership" => TypeEnum.CommercialPartnership, + "publicPartnership" => TypeEnum.PublicPartnership, + "otherPartnership" => TypeEnum.OtherPartnership, + "gbr" => TypeEnum.Gbr, + "gmbh" => TypeEnum.Gmbh, + "kgaa" => TypeEnum.Kgaa, + "cv" => TypeEnum.Cv, + "vof" => TypeEnum.Vof, + "maatschap" => TypeEnum.Maatschap, + "privateFundLimitedPartnership" => TypeEnum.PrivateFundLimitedPartnership, + "businessTrustEntity" => TypeEnum.BusinessTrustEntity, + "businessPartnership" => TypeEnum.BusinessPartnership, + "limitedLiabilityPartnership" => TypeEnum.LimitedLiabilityPartnership, + "eg" => TypeEnum.Eg, + "cooperative" => TypeEnum.Cooperative, + "vos" => TypeEnum.Vos, + "comunidadDeBienes" => TypeEnum.ComunidadDeBienes, + "herenciaYacente" => TypeEnum.HerenciaYacente, + "comunidadDePropietarios" => TypeEnum.ComunidadDePropietarios, + "sep" => TypeEnum.Sep, + "sca" => TypeEnum.Sca, + "bt" => TypeEnum.Bt, + "kkt" => TypeEnum.Kkt, + "scs" => TypeEnum.Scs, + "snc" => TypeEnum.Snc, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.LimitedPartnership) + return "limitedPartnership"; + + if (value == TypeEnum.GeneralPartnership) + return "generalPartnership"; + + if (value == TypeEnum.FamilyPartnership) + return "familyPartnership"; + + if (value == TypeEnum.CommercialPartnership) + return "commercialPartnership"; + + if (value == TypeEnum.PublicPartnership) + return "publicPartnership"; + + if (value == TypeEnum.OtherPartnership) + return "otherPartnership"; + + if (value == TypeEnum.Gbr) + return "gbr"; + + if (value == TypeEnum.Gmbh) + return "gmbh"; + + if (value == TypeEnum.Kgaa) + return "kgaa"; + + if (value == TypeEnum.Cv) + return "cv"; + + if (value == TypeEnum.Vof) + return "vof"; + + if (value == TypeEnum.Maatschap) + return "maatschap"; + + if (value == TypeEnum.PrivateFundLimitedPartnership) + return "privateFundLimitedPartnership"; + + if (value == TypeEnum.BusinessTrustEntity) + return "businessTrustEntity"; + + if (value == TypeEnum.BusinessPartnership) + return "businessPartnership"; + + if (value == TypeEnum.LimitedLiabilityPartnership) + return "limitedLiabilityPartnership"; + + if (value == TypeEnum.Eg) + return "eg"; + + if (value == TypeEnum.Cooperative) + return "cooperative"; + + if (value == TypeEnum.Vos) + return "vos"; + + if (value == TypeEnum.ComunidadDeBienes) + return "comunidadDeBienes"; + + if (value == TypeEnum.HerenciaYacente) + return "herenciaYacente"; + + if (value == TypeEnum.ComunidadDePropietarios) + return "comunidadDePropietarios"; + + if (value == TypeEnum.Sep) + return "sep"; + + if (value == TypeEnum.Sca) + return "sca"; + + if (value == TypeEnum.Bt) + return "bt"; + + if (value == TypeEnum.Kkt) + return "kkt"; + + if (value == TypeEnum.Scs) + return "scs"; + + if (value == TypeEnum.Snc) + return "snc"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; } + + /// + /// Type of Partnership. Possible values: * **limitedPartnership** * **generalPartnership** * **familyPartnership** * **commercialPartnership** * **publicPartnership** * **otherPartnership** * **gbr** * **gmbh** * **kgaa** * **cv** * **vof** * **maatschap** * **privateFundLimitedPartnership** * **businessTrustEntity** * **businessPartnership** * **limitedLiabilityPartnership** * **eg** * **cooperative** * **vos** * **comunidadDeBienes** * **herenciaYacente** * **comunidadDePropietarios** * **sep** * **sca** * **bt** * **kkt** * **scs** * **snc** + /// + /// Type of Partnership. Possible values: * **limitedPartnership** * **generalPartnership** * **familyPartnership** * **commercialPartnership** * **publicPartnership** * **otherPartnership** * **gbr** * **gmbh** * **kgaa** * **cv** * **vof** * **maatschap** * **privateFundLimitedPartnership** * **businessTrustEntity** * **businessPartnership** * **limitedLiabilityPartnership** * **eg** * **cooperative** * **vos** * **comunidadDeBienes** * **herenciaYacente** * **comunidadDePropietarios** * **sep** * **sca** * **bt** * **kkt** * **scs** * **snc** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } } + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonConverter(typeof(VatAbsenceReasonEnumJsonConverter))] + public class VatAbsenceReasonEnum : IEnum + { + /// + /// Returns the value of the VatAbsenceReasonEnum. + /// + public string? Value { get; set; } + + /// + /// VatAbsenceReasonEnum.IndustryExemption - industryExemption + /// + public static readonly VatAbsenceReasonEnum IndustryExemption = new("industryExemption"); + + /// + /// VatAbsenceReasonEnum.BelowTaxThreshold - belowTaxThreshold + /// + public static readonly VatAbsenceReasonEnum BelowTaxThreshold = new("belowTaxThreshold"); + + private VatAbsenceReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VatAbsenceReasonEnum?(string? value) => value == null ? null : new VatAbsenceReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VatAbsenceReasonEnum? option) => option?.Value; + + public static bool operator ==(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VatAbsenceReasonEnum? left, VatAbsenceReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VatAbsenceReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VatAbsenceReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "industryExemption" => VatAbsenceReasonEnum.IndustryExemption, + "belowTaxThreshold" => VatAbsenceReasonEnum.BelowTaxThreshold, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VatAbsenceReasonEnum? value) + { + if (value == null) + return null; + + if (value == VatAbsenceReasonEnum.IndustryExemption) + return "industryExemption"; + + if (value == VatAbsenceReasonEnum.BelowTaxThreshold) + return "belowTaxThreshold"; + + return null; + } + + /// + /// JsonConverter for writing VatAbsenceReasonEnum. + /// + public class VatAbsenceReasonEnumJsonConverter : JsonConverter + { + public override VatAbsenceReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VatAbsenceReasonEnum.FromStringOrDefault(value) ?? new VatAbsenceReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VatAbsenceReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VatAbsenceReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatAbsenceReasonOption { get; private set; } + + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + /// + /// The reason for not providing a VAT number. Possible values: **industryExemption**, **belowTaxThreshold**. + [JsonPropertyName("vatAbsenceReason")] + public VatAbsenceReasonEnum? VatAbsenceReason { get { return this._VatAbsenceReasonOption; } set { this._VatAbsenceReasonOption = new(value); } } + + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + /// + /// The two-character [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the governing country. + [JsonPropertyName("countryOfGoverningLaw")] + public string CountryOfGoverningLaw { get; set; } + + /// + /// The legal name. + /// + /// The legal name. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// . + /// + [JsonPropertyName("registeredAddress")] + public Address RegisteredAddress { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfIncorporationOption { get; private set; } + + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + /// + /// The date when the legal arrangement was incorporated in YYYY-MM-DD format. + [JsonPropertyName("dateOfIncorporation")] + public string? DateOfIncorporation { get { return this._DateOfIncorporationOption; } set { this._DateOfIncorporationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Short description about the Legal Arrangement. + /// + /// Short description about the Legal Arrangement. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsOption { get; private set; } + + /// + /// The registered name, if different from the `name`. + /// + /// The registered name, if different from the `name`. + [JsonPropertyName("doingBusinessAs")] + public string? DoingBusinessAs { get { return this._DoingBusinessAsOption; } set { this._DoingBusinessAsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsAbsentOption { get; private set; } + + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + /// + /// Set this to **true** if the legal arrangement does not have a `Doing business as` name. + [JsonPropertyName("doingBusinessAsAbsent")] + public bool? DoingBusinessAsAbsent { get { return this._DoingBusinessAsAbsentOption; } set { this._DoingBusinessAsAbsentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrincipalPlaceOfBusinessOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("principalPlaceOfBusiness")] + public Address? PrincipalPlaceOfBusiness { get { return this._PrincipalPlaceOfBusinessOption; } set { this._PrincipalPlaceOfBusinessOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RegistrationNumberOption { get; private set; } + + /// + /// The registration number. + /// + /// The registration number. + [JsonPropertyName("registrationNumber")] + public string? RegistrationNumber { get { return this._RegistrationNumberOption; } set { this._RegistrationNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TaxInformationOption { get; private set; } + + /// + /// The tax information of the entity. + /// + /// The tax information of the entity. + [JsonPropertyName("taxInformation")] + public List? TaxInformation { get { return this._TaxInformationOption; } set { this._TaxInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VatNumberOption { get; private set; } + + /// + /// The VAT number. + /// + /// The VAT number. + [JsonPropertyName("vatNumber")] + public string? VatNumber { get { return this._VatNumberOption; } set { this._VatNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UnincorporatedPartnership {\n"); + sb.Append(" CountryOfGoverningLaw: ").Append(CountryOfGoverningLaw).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RegisteredAddress: ").Append(RegisteredAddress).Append("\n"); + sb.Append(" DateOfIncorporation: ").Append(DateOfIncorporation).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DoingBusinessAs: ").Append(DoingBusinessAs).Append("\n"); + sb.Append(" DoingBusinessAsAbsent: ").Append(DoingBusinessAsAbsent).Append("\n"); + sb.Append(" PrincipalPlaceOfBusiness: ").Append(PrincipalPlaceOfBusiness).Append("\n"); + sb.Append(" RegistrationNumber: ").Append(RegistrationNumber).Append("\n"); + sb.Append(" TaxInformation: ").Append(TaxInformation).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" VatAbsenceReason: ").Append(VatAbsenceReason).Append("\n"); + sb.Append(" VatNumber: ").Append(VatNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UnincorporatedPartnershipJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UnincorporatedPartnership Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option countryOfGoverningLaw = default; + Option name = default; + Option registeredAddress = default; + Option dateOfIncorporation = default; + Option description = default; + Option doingBusinessAs = default; + Option doingBusinessAsAbsent = default; + Option principalPlaceOfBusiness = default; + Option registrationNumber = default; + Option?> taxInformation = default; + Option type = default; + Option vatAbsenceReason = default; + Option vatNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "countryOfGoverningLaw": + countryOfGoverningLaw = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "registeredAddress": + registeredAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfIncorporation": + dateOfIncorporation = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAs": + doingBusinessAs = new Option(utf8JsonReader.GetString()!); + break; + case "doingBusinessAsAbsent": + doingBusinessAsAbsent = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "principalPlaceOfBusiness": + principalPlaceOfBusiness = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "registrationNumber": + registrationNumber = new Option(utf8JsonReader.GetString()!); + break; + case "taxInformation": + taxInformation = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UnincorporatedPartnership.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "vatAbsenceReason": + string? vatAbsenceReasonRawValue = utf8JsonReader.GetString(); + vatAbsenceReason = new Option(UnincorporatedPartnership.VatAbsenceReasonEnum.FromStringOrDefault(vatAbsenceReasonRawValue)); + break; + case "vatNumber": + vatNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!countryOfGoverningLaw.IsSet) + throw new ArgumentException("Property is required for class UnincorporatedPartnership.", nameof(countryOfGoverningLaw)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class UnincorporatedPartnership.", nameof(name)); + + if (!registeredAddress.IsSet) + throw new ArgumentException("Property is required for class UnincorporatedPartnership.", nameof(registeredAddress)); + + return new UnincorporatedPartnership(countryOfGoverningLaw.Value!, name.Value!, registeredAddress.Value!, dateOfIncorporation, description, doingBusinessAs, doingBusinessAsAbsent, principalPlaceOfBusiness, registrationNumber, taxInformation, type, vatAbsenceReason, vatNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UnincorporatedPartnership unincorporatedPartnership, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, unincorporatedPartnership, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UnincorporatedPartnership unincorporatedPartnership, JsonSerializerOptions jsonSerializerOptions) + { + + if (unincorporatedPartnership.CountryOfGoverningLaw != null) + writer.WriteString("countryOfGoverningLaw", unincorporatedPartnership.CountryOfGoverningLaw); + + if (unincorporatedPartnership.Name != null) + writer.WriteString("name", unincorporatedPartnership.Name); + + writer.WritePropertyName("registeredAddress"); + JsonSerializer.Serialize(writer, unincorporatedPartnership.RegisteredAddress, jsonSerializerOptions); + if (unincorporatedPartnership._DateOfIncorporationOption.IsSet) + if (unincorporatedPartnership.DateOfIncorporation != null) + writer.WriteString("dateOfIncorporation", unincorporatedPartnership.DateOfIncorporation); + + if (unincorporatedPartnership._DescriptionOption.IsSet) + if (unincorporatedPartnership.Description != null) + writer.WriteString("description", unincorporatedPartnership.Description); + + if (unincorporatedPartnership._DoingBusinessAsOption.IsSet) + if (unincorporatedPartnership.DoingBusinessAs != null) + writer.WriteString("doingBusinessAs", unincorporatedPartnership.DoingBusinessAs); + + if (unincorporatedPartnership._DoingBusinessAsAbsentOption.IsSet) + if (unincorporatedPartnership._DoingBusinessAsAbsentOption.Value != null) + writer.WriteBoolean("doingBusinessAsAbsent", unincorporatedPartnership._DoingBusinessAsAbsentOption.Value!.Value); + else + writer.WriteNull("doingBusinessAsAbsent"); + + if (unincorporatedPartnership._PrincipalPlaceOfBusinessOption.IsSet) + { + writer.WritePropertyName("principalPlaceOfBusiness"); + JsonSerializer.Serialize(writer, unincorporatedPartnership.PrincipalPlaceOfBusiness, jsonSerializerOptions); + } + if (unincorporatedPartnership._RegistrationNumberOption.IsSet) + if (unincorporatedPartnership.RegistrationNumber != null) + writer.WriteString("registrationNumber", unincorporatedPartnership.RegistrationNumber); + + if (unincorporatedPartnership._TaxInformationOption.IsSet) + { + writer.WritePropertyName("taxInformation"); + JsonSerializer.Serialize(writer, unincorporatedPartnership.TaxInformation, jsonSerializerOptions); + } + if (unincorporatedPartnership._TypeOption.IsSet && unincorporatedPartnership.Type != null) + { + string? typeRawValue = UnincorporatedPartnership.TypeEnum.ToJsonValue(unincorporatedPartnership._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (unincorporatedPartnership._VatAbsenceReasonOption.IsSet && unincorporatedPartnership.VatAbsenceReason != null) + { + string? vatAbsenceReasonRawValue = UnincorporatedPartnership.VatAbsenceReasonEnum.ToJsonValue(unincorporatedPartnership._VatAbsenceReasonOption.Value!.Value); + writer.WriteString("vatAbsenceReason", vatAbsenceReasonRawValue); + } + + if (unincorporatedPartnership._VatNumberOption.IsSet) + if (unincorporatedPartnership.VatNumber != null) + writer.WriteString("vatNumber", unincorporatedPartnership.VatNumber); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/VerificationDeadline.cs b/Adyen/LegalEntityManagement/Models/VerificationDeadline.cs new file mode 100644 index 000000000..09584a6a6 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/VerificationDeadline.cs @@ -0,0 +1,800 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// VerificationDeadline. + /// + public partial class VerificationDeadline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of capabilities that will be disallowed if information is not reviewed by the time of the deadline + /// The date that verification is due by before capabilities are disallowed. + /// The unique identifiers of the legal entity or supporting entities that the deadline applies to + [JsonConstructor] + internal VerificationDeadline(List capabilities, DateTimeOffset expiresAt, Option?> entityIds = default) + { + Capabilities = capabilities; + ExpiresAt = expiresAt; + _EntityIdsOption = entityIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + internal VerificationDeadline() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The list of capabilities that will be disallowed if information is not reviewed by the time of the deadline + /// + /// The list of capabilities that will be disallowed if information is not reviewed by the time of the deadline + [JsonPropertyName("capabilities")] + public List Capabilities { get; } + + /// + /// The date that verification is due by before capabilities are disallowed. + /// + /// The date that verification is due by before capabilities are disallowed. + [JsonPropertyName("expiresAt")] + public DateTimeOffset ExpiresAt { get; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EntityIdsOption { get; } + + /// + /// The unique identifiers of the legal entity or supporting entities that the deadline applies to + /// + /// The unique identifiers of the legal entity or supporting entities that the deadline applies to + [JsonPropertyName("entityIds")] + public List? EntityIds { get { return this._EntityIdsOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationDeadline {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); + sb.Append(" EntityIds: ").Append(EntityIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationDeadlineJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ExpiresAt. + /// + public static string ExpiresAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationDeadline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option expiresAt = default; + Option?> entityIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "expiresAt": + expiresAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityIds": + entityIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!capabilities.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(capabilities)); + + if (!expiresAt.IsSet) + throw new ArgumentException("Property is required for class VerificationDeadline.", nameof(expiresAt)); + + return new VerificationDeadline(capabilities.Value!, expiresAt.Value!.Value!, entityIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationDeadline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationDeadline verificationDeadline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationDeadline.Capabilities, jsonSerializerOptions); + writer.WriteString("expiresAt", verificationDeadline.ExpiresAt.ToString(ExpiresAtFormat)); + + if (verificationDeadline._EntityIdsOption.IsSet) + { + writer.WritePropertyName("entityIds"); + JsonSerializer.Serialize(writer, verificationDeadline.EntityIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/VerificationError.cs b/Adyen/LegalEntityManagement/Models/VerificationError.cs new file mode 100644 index 000000000..435933a4d --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/VerificationError.cs @@ -0,0 +1,1017 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// VerificationError. + /// + public partial class VerificationError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + /// The general error code. + /// The general error message. + /// An object containing possible solutions to fix a verification error. + /// An array containing more granular information about the cause of the verification error. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + [JsonConstructor] + public VerificationError(Option?> capabilities = default, Option code = default, Option message = default, Option?> remediatingActions = default, Option?> subErrors = default, Option type = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _RemediatingActionsOption = remediatingActions; + _SubErrorsOption = subErrors; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationError() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + /// + /// TypeEnum.Rejected - rejected + /// + public static readonly TypeEnum Rejected = new("rejected"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + "rejected" => TypeEnum.Rejected, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + if (value == TypeEnum.Rejected) + return "rejected"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The general error code. + /// + /// The general error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// The general error message. + /// + /// The general error message. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// An object containing possible solutions to fix a verification error. + /// + /// An object containing possible solutions to fix a verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubErrorsOption { get; private set; } + + /// + /// An array containing more granular information about the cause of the verification error. + /// + /// An array containing more granular information about the cause of the verification error. + [JsonPropertyName("subErrors")] + public List? SubErrors { get { return this._SubErrorsOption; } set { this._SubErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationError {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append(" SubErrors: ").Append(SubErrors).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option?> remediatingActions = default; + Option?> subErrors = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subErrors": + subErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationError.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new VerificationError(capabilities, code, message, remediatingActions, subErrors, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationError._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationError.Capabilities, jsonSerializerOptions); + } + if (verificationError._CodeOption.IsSet) + if (verificationError.Code != null) + writer.WriteString("code", verificationError.Code); + + if (verificationError._MessageOption.IsSet) + if (verificationError.Message != null) + writer.WriteString("message", verificationError.Message); + + if (verificationError._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationError.RemediatingActions, jsonSerializerOptions); + } + if (verificationError._SubErrorsOption.IsSet) + { + writer.WritePropertyName("subErrors"); + JsonSerializer.Serialize(writer, verificationError.SubErrors, jsonSerializerOptions); + } + if (verificationError._TypeOption.IsSet && verificationError.Type != null) + { + string? typeRawValue = VerificationError.TypeEnum.ToJsonValue(verificationError._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/VerificationErrorRecursive.cs b/Adyen/LegalEntityManagement/Models/VerificationErrorRecursive.cs new file mode 100644 index 000000000..4ed82b4e0 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/VerificationErrorRecursive.cs @@ -0,0 +1,992 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// VerificationErrorRecursive. + /// + public partial class VerificationErrorRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + /// The general error code. + /// The general error message. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + /// An object containing possible solutions to fix a verification error. + [JsonConstructor] + public VerificationErrorRecursive(Option?> capabilities = default, Option code = default, Option message = default, Option type = default, Option?> remediatingActions = default) + { + _CapabilitiesOption = capabilities; + _CodeOption = code; + _MessageOption = message; + _TypeOption = type; + _RemediatingActionsOption = remediatingActions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationErrorRecursive() + { + } + + partial void OnCreated(); + + /// + /// Defines Capabilities. + /// + [JsonConverter(typeof(CapabilitiesEnumJsonConverter))] + public class CapabilitiesEnum : IEnum + { + /// + /// Returns the value of the CapabilitiesEnum. + /// + public string? Value { get; set; } + + /// + /// CapabilitiesEnum.AcceptExternalFunding - acceptExternalFunding + /// + public static readonly CapabilitiesEnum AcceptExternalFunding = new("acceptExternalFunding"); + + /// + /// CapabilitiesEnum.AcceptPspFunding - acceptPspFunding + /// + public static readonly CapabilitiesEnum AcceptPspFunding = new("acceptPspFunding"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountries - acceptTransactionInRestrictedCountries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountries = new("acceptTransactionInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial - acceptTransactionInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesCommercial = new("acceptTransactionInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer - acceptTransactionInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedCountriesConsumer = new("acceptTransactionInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustries - acceptTransactionInRestrictedIndustries + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustries = new("acceptTransactionInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial - acceptTransactionInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesCommercial = new("acceptTransactionInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer - acceptTransactionInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum AcceptTransactionInRestrictedIndustriesConsumer = new("acceptTransactionInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.Acquiring - acquiring + /// + public static readonly CapabilitiesEnum Acquiring = new("acquiring"); + + /// + /// CapabilitiesEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly CapabilitiesEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// CapabilitiesEnum.AtmWithdrawalCommercial - atmWithdrawalCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalCommercial = new("atmWithdrawalCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalConsumer - atmWithdrawalConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalConsumer = new("atmWithdrawalConsumer"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountries - atmWithdrawalInRestrictedCountries + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountries = new("atmWithdrawalInRestrictedCountries"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial - atmWithdrawalInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesCommercial = new("atmWithdrawalInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer - atmWithdrawalInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum AtmWithdrawalInRestrictedCountriesConsumer = new("atmWithdrawalInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.AuthorisedPaymentInstrumentUser - authorisedPaymentInstrumentUser + /// + public static readonly CapabilitiesEnum AuthorisedPaymentInstrumentUser = new("authorisedPaymentInstrumentUser"); + + /// + /// CapabilitiesEnum.GetGrantOffers - getGrantOffers + /// + public static readonly CapabilitiesEnum GetGrantOffers = new("getGrantOffers"); + + /// + /// CapabilitiesEnum.IssueBankAccount - issueBankAccount + /// + public static readonly CapabilitiesEnum IssueBankAccount = new("issueBankAccount"); + + /// + /// CapabilitiesEnum.IssueCard - issueCard + /// + public static readonly CapabilitiesEnum IssueCard = new("issueCard"); + + /// + /// CapabilitiesEnum.IssueCardCommercial - issueCardCommercial + /// + public static readonly CapabilitiesEnum IssueCardCommercial = new("issueCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCardConsumer - issueCardConsumer + /// + public static readonly CapabilitiesEnum IssueCardConsumer = new("issueCardConsumer"); + + /// + /// CapabilitiesEnum.IssueChargeCard - issueChargeCard + /// + public static readonly CapabilitiesEnum IssueChargeCard = new("issueChargeCard"); + + /// + /// CapabilitiesEnum.IssueChargeCardCommercial - issueChargeCardCommercial + /// + public static readonly CapabilitiesEnum IssueChargeCardCommercial = new("issueChargeCardCommercial"); + + /// + /// CapabilitiesEnum.IssueCreditLimit - issueCreditLimit + /// + public static readonly CapabilitiesEnum IssueCreditLimit = new("issueCreditLimit"); + + /// + /// CapabilitiesEnum.LocalAcceptance - localAcceptance + /// + public static readonly CapabilitiesEnum LocalAcceptance = new("localAcceptance"); + + /// + /// CapabilitiesEnum.Payout - payout + /// + public static readonly CapabilitiesEnum Payout = new("payout"); + + /// + /// CapabilitiesEnum.PayoutToTransferInstrument - payoutToTransferInstrument + /// + public static readonly CapabilitiesEnum PayoutToTransferInstrument = new("payoutToTransferInstrument"); + + /// + /// CapabilitiesEnum.Processing - processing + /// + public static readonly CapabilitiesEnum Processing = new("processing"); + + /// + /// CapabilitiesEnum.ReceiveFromBalanceAccount - receiveFromBalanceAccount + /// + public static readonly CapabilitiesEnum ReceiveFromBalanceAccount = new("receiveFromBalanceAccount"); + + /// + /// CapabilitiesEnum.ReceiveFromPlatformPayments - receiveFromPlatformPayments + /// + public static readonly CapabilitiesEnum ReceiveFromPlatformPayments = new("receiveFromPlatformPayments"); + + /// + /// CapabilitiesEnum.ReceiveFromThirdParty - receiveFromThirdParty + /// + public static readonly CapabilitiesEnum ReceiveFromThirdParty = new("receiveFromThirdParty"); + + /// + /// CapabilitiesEnum.ReceiveFromTransferInstrument - receiveFromTransferInstrument + /// + public static readonly CapabilitiesEnum ReceiveFromTransferInstrument = new("receiveFromTransferInstrument"); + + /// + /// CapabilitiesEnum.ReceiveGrants - receiveGrants + /// + public static readonly CapabilitiesEnum ReceiveGrants = new("receiveGrants"); + + /// + /// CapabilitiesEnum.ReceivePayments - receivePayments + /// + public static readonly CapabilitiesEnum ReceivePayments = new("receivePayments"); + + /// + /// CapabilitiesEnum.SendToBalanceAccount - sendToBalanceAccount + /// + public static readonly CapabilitiesEnum SendToBalanceAccount = new("sendToBalanceAccount"); + + /// + /// CapabilitiesEnum.SendToThirdParty - sendToThirdParty + /// + public static readonly CapabilitiesEnum SendToThirdParty = new("sendToThirdParty"); + + /// + /// CapabilitiesEnum.SendToTransferInstrument - sendToTransferInstrument + /// + public static readonly CapabilitiesEnum SendToTransferInstrument = new("sendToTransferInstrument"); + + /// + /// CapabilitiesEnum.ThirdPartyFunding - thirdPartyFunding + /// + public static readonly CapabilitiesEnum ThirdPartyFunding = new("thirdPartyFunding"); + + /// + /// CapabilitiesEnum.UseCard - useCard + /// + public static readonly CapabilitiesEnum UseCard = new("useCard"); + + /// + /// CapabilitiesEnum.UseCardCommercial - useCardCommercial + /// + public static readonly CapabilitiesEnum UseCardCommercial = new("useCardCommercial"); + + /// + /// CapabilitiesEnum.UseCardConsumer - useCardConsumer + /// + public static readonly CapabilitiesEnum UseCardConsumer = new("useCardConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountries - useCardInRestrictedCountries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountries = new("useCardInRestrictedCountries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesCommercial - useCardInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesCommercial = new("useCardInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedCountriesConsumer - useCardInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedCountriesConsumer = new("useCardInRestrictedCountriesConsumer"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustries - useCardInRestrictedIndustries + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustries = new("useCardInRestrictedIndustries"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial - useCardInRestrictedIndustriesCommercial + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesCommercial = new("useCardInRestrictedIndustriesCommercial"); + + /// + /// CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer - useCardInRestrictedIndustriesConsumer + /// + public static readonly CapabilitiesEnum UseCardInRestrictedIndustriesConsumer = new("useCardInRestrictedIndustriesConsumer"); + + /// + /// CapabilitiesEnum.UseChargeCard - useChargeCard + /// + public static readonly CapabilitiesEnum UseChargeCard = new("useChargeCard"); + + /// + /// CapabilitiesEnum.UseChargeCardCommercial - useChargeCardCommercial + /// + public static readonly CapabilitiesEnum UseChargeCardCommercial = new("useChargeCardCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtm - withdrawFromAtm + /// + public static readonly CapabilitiesEnum WithdrawFromAtm = new("withdrawFromAtm"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmCommercial - withdrawFromAtmCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmCommercial = new("withdrawFromAtmCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmConsumer - withdrawFromAtmConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmConsumer = new("withdrawFromAtmConsumer"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries - withdrawFromAtmInRestrictedCountries + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountries = new("withdrawFromAtmInRestrictedCountries"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial - withdrawFromAtmInRestrictedCountriesCommercial + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesCommercial = new("withdrawFromAtmInRestrictedCountriesCommercial"); + + /// + /// CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer - withdrawFromAtmInRestrictedCountriesConsumer + /// + public static readonly CapabilitiesEnum WithdrawFromAtmInRestrictedCountriesConsumer = new("withdrawFromAtmInRestrictedCountriesConsumer"); + + private CapabilitiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CapabilitiesEnum?(string? value) => value == null ? null : new CapabilitiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CapabilitiesEnum? option) => option?.Value; + + public static bool operator ==(CapabilitiesEnum? left, CapabilitiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CapabilitiesEnum? left, CapabilitiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CapabilitiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CapabilitiesEnum? FromStringOrDefault(string value) + { + return value switch { + "acceptExternalFunding" => CapabilitiesEnum.AcceptExternalFunding, + "acceptPspFunding" => CapabilitiesEnum.AcceptPspFunding, + "acceptTransactionInRestrictedCountries" => CapabilitiesEnum.AcceptTransactionInRestrictedCountries, + "acceptTransactionInRestrictedCountriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial, + "acceptTransactionInRestrictedCountriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer, + "acceptTransactionInRestrictedIndustries" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustries, + "acceptTransactionInRestrictedIndustriesCommercial" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial, + "acceptTransactionInRestrictedIndustriesConsumer" => CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer, + "acquiring" => CapabilitiesEnum.Acquiring, + "atmWithdrawal" => CapabilitiesEnum.AtmWithdrawal, + "atmWithdrawalCommercial" => CapabilitiesEnum.AtmWithdrawalCommercial, + "atmWithdrawalConsumer" => CapabilitiesEnum.AtmWithdrawalConsumer, + "atmWithdrawalInRestrictedCountries" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountries, + "atmWithdrawalInRestrictedCountriesCommercial" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial, + "atmWithdrawalInRestrictedCountriesConsumer" => CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer, + "authorisedPaymentInstrumentUser" => CapabilitiesEnum.AuthorisedPaymentInstrumentUser, + "getGrantOffers" => CapabilitiesEnum.GetGrantOffers, + "issueBankAccount" => CapabilitiesEnum.IssueBankAccount, + "issueCard" => CapabilitiesEnum.IssueCard, + "issueCardCommercial" => CapabilitiesEnum.IssueCardCommercial, + "issueCardConsumer" => CapabilitiesEnum.IssueCardConsumer, + "issueChargeCard" => CapabilitiesEnum.IssueChargeCard, + "issueChargeCardCommercial" => CapabilitiesEnum.IssueChargeCardCommercial, + "issueCreditLimit" => CapabilitiesEnum.IssueCreditLimit, + "localAcceptance" => CapabilitiesEnum.LocalAcceptance, + "payout" => CapabilitiesEnum.Payout, + "payoutToTransferInstrument" => CapabilitiesEnum.PayoutToTransferInstrument, + "processing" => CapabilitiesEnum.Processing, + "receiveFromBalanceAccount" => CapabilitiesEnum.ReceiveFromBalanceAccount, + "receiveFromPlatformPayments" => CapabilitiesEnum.ReceiveFromPlatformPayments, + "receiveFromThirdParty" => CapabilitiesEnum.ReceiveFromThirdParty, + "receiveFromTransferInstrument" => CapabilitiesEnum.ReceiveFromTransferInstrument, + "receiveGrants" => CapabilitiesEnum.ReceiveGrants, + "receivePayments" => CapabilitiesEnum.ReceivePayments, + "sendToBalanceAccount" => CapabilitiesEnum.SendToBalanceAccount, + "sendToThirdParty" => CapabilitiesEnum.SendToThirdParty, + "sendToTransferInstrument" => CapabilitiesEnum.SendToTransferInstrument, + "thirdPartyFunding" => CapabilitiesEnum.ThirdPartyFunding, + "useCard" => CapabilitiesEnum.UseCard, + "useCardCommercial" => CapabilitiesEnum.UseCardCommercial, + "useCardConsumer" => CapabilitiesEnum.UseCardConsumer, + "useCardInRestrictedCountries" => CapabilitiesEnum.UseCardInRestrictedCountries, + "useCardInRestrictedCountriesCommercial" => CapabilitiesEnum.UseCardInRestrictedCountriesCommercial, + "useCardInRestrictedCountriesConsumer" => CapabilitiesEnum.UseCardInRestrictedCountriesConsumer, + "useCardInRestrictedIndustries" => CapabilitiesEnum.UseCardInRestrictedIndustries, + "useCardInRestrictedIndustriesCommercial" => CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial, + "useCardInRestrictedIndustriesConsumer" => CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer, + "useChargeCard" => CapabilitiesEnum.UseChargeCard, + "useChargeCardCommercial" => CapabilitiesEnum.UseChargeCardCommercial, + "withdrawFromAtm" => CapabilitiesEnum.WithdrawFromAtm, + "withdrawFromAtmCommercial" => CapabilitiesEnum.WithdrawFromAtmCommercial, + "withdrawFromAtmConsumer" => CapabilitiesEnum.WithdrawFromAtmConsumer, + "withdrawFromAtmInRestrictedCountries" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries, + "withdrawFromAtmInRestrictedCountriesCommercial" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial, + "withdrawFromAtmInRestrictedCountriesConsumer" => CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CapabilitiesEnum? value) + { + if (value == null) + return null; + + if (value == CapabilitiesEnum.AcceptExternalFunding) + return "acceptExternalFunding"; + + if (value == CapabilitiesEnum.AcceptPspFunding) + return "acceptPspFunding"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountries) + return "acceptTransactionInRestrictedCountries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesCommercial) + return "acceptTransactionInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedCountriesConsumer) + return "acceptTransactionInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustries) + return "acceptTransactionInRestrictedIndustries"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesCommercial) + return "acceptTransactionInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.AcceptTransactionInRestrictedIndustriesConsumer) + return "acceptTransactionInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.Acquiring) + return "acquiring"; + + if (value == CapabilitiesEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == CapabilitiesEnum.AtmWithdrawalCommercial) + return "atmWithdrawalCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalConsumer) + return "atmWithdrawalConsumer"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountries) + return "atmWithdrawalInRestrictedCountries"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesCommercial) + return "atmWithdrawalInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.AtmWithdrawalInRestrictedCountriesConsumer) + return "atmWithdrawalInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.AuthorisedPaymentInstrumentUser) + return "authorisedPaymentInstrumentUser"; + + if (value == CapabilitiesEnum.GetGrantOffers) + return "getGrantOffers"; + + if (value == CapabilitiesEnum.IssueBankAccount) + return "issueBankAccount"; + + if (value == CapabilitiesEnum.IssueCard) + return "issueCard"; + + if (value == CapabilitiesEnum.IssueCardCommercial) + return "issueCardCommercial"; + + if (value == CapabilitiesEnum.IssueCardConsumer) + return "issueCardConsumer"; + + if (value == CapabilitiesEnum.IssueChargeCard) + return "issueChargeCard"; + + if (value == CapabilitiesEnum.IssueChargeCardCommercial) + return "issueChargeCardCommercial"; + + if (value == CapabilitiesEnum.IssueCreditLimit) + return "issueCreditLimit"; + + if (value == CapabilitiesEnum.LocalAcceptance) + return "localAcceptance"; + + if (value == CapabilitiesEnum.Payout) + return "payout"; + + if (value == CapabilitiesEnum.PayoutToTransferInstrument) + return "payoutToTransferInstrument"; + + if (value == CapabilitiesEnum.Processing) + return "processing"; + + if (value == CapabilitiesEnum.ReceiveFromBalanceAccount) + return "receiveFromBalanceAccount"; + + if (value == CapabilitiesEnum.ReceiveFromPlatformPayments) + return "receiveFromPlatformPayments"; + + if (value == CapabilitiesEnum.ReceiveFromThirdParty) + return "receiveFromThirdParty"; + + if (value == CapabilitiesEnum.ReceiveFromTransferInstrument) + return "receiveFromTransferInstrument"; + + if (value == CapabilitiesEnum.ReceiveGrants) + return "receiveGrants"; + + if (value == CapabilitiesEnum.ReceivePayments) + return "receivePayments"; + + if (value == CapabilitiesEnum.SendToBalanceAccount) + return "sendToBalanceAccount"; + + if (value == CapabilitiesEnum.SendToThirdParty) + return "sendToThirdParty"; + + if (value == CapabilitiesEnum.SendToTransferInstrument) + return "sendToTransferInstrument"; + + if (value == CapabilitiesEnum.ThirdPartyFunding) + return "thirdPartyFunding"; + + if (value == CapabilitiesEnum.UseCard) + return "useCard"; + + if (value == CapabilitiesEnum.UseCardCommercial) + return "useCardCommercial"; + + if (value == CapabilitiesEnum.UseCardConsumer) + return "useCardConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountries) + return "useCardInRestrictedCountries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesCommercial) + return "useCardInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedCountriesConsumer) + return "useCardInRestrictedCountriesConsumer"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustries) + return "useCardInRestrictedIndustries"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesCommercial) + return "useCardInRestrictedIndustriesCommercial"; + + if (value == CapabilitiesEnum.UseCardInRestrictedIndustriesConsumer) + return "useCardInRestrictedIndustriesConsumer"; + + if (value == CapabilitiesEnum.UseChargeCard) + return "useChargeCard"; + + if (value == CapabilitiesEnum.UseChargeCardCommercial) + return "useChargeCardCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtm) + return "withdrawFromAtm"; + + if (value == CapabilitiesEnum.WithdrawFromAtmCommercial) + return "withdrawFromAtmCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmConsumer) + return "withdrawFromAtmConsumer"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountries) + return "withdrawFromAtmInRestrictedCountries"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesCommercial) + return "withdrawFromAtmInRestrictedCountriesCommercial"; + + if (value == CapabilitiesEnum.WithdrawFromAtmInRestrictedCountriesConsumer) + return "withdrawFromAtmInRestrictedCountriesConsumer"; + + return null; + } + + /// + /// JsonConverter for writing CapabilitiesEnum. + /// + public class CapabilitiesEnumJsonConverter : JsonConverter + { + public override CapabilitiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CapabilitiesEnum.FromStringOrDefault(value) ?? new CapabilitiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CapabilitiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CapabilitiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + /// + /// TypeEnum.Rejected - rejected + /// + public static readonly TypeEnum Rejected = new("rejected"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + "rejected" => TypeEnum.Rejected, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + if (value == TypeEnum.Rejected) + return "rejected"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + /// + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **rejected** * **dataReview** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CapabilitiesOption { get; private set; } + + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + /// + /// Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public List? Capabilities { get { return this._CapabilitiesOption; } set { this._CapabilitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The general error code. + /// + /// The general error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// The general error message. + /// + /// The general error message. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// An object containing possible solutions to fix a verification error. + /// + /// An object containing possible solutions to fix a verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationErrorRecursive {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationErrorRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option code = default; + Option message = default; + Option type = default; + Option?> remediatingActions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationErrorRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new VerificationErrorRecursive(capabilities, code, message, type, remediatingActions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationErrorRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationErrorRecursive._CapabilitiesOption.IsSet) + { + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.Capabilities, jsonSerializerOptions); + } + if (verificationErrorRecursive._CodeOption.IsSet) + if (verificationErrorRecursive.Code != null) + writer.WriteString("code", verificationErrorRecursive.Code); + + if (verificationErrorRecursive._MessageOption.IsSet) + if (verificationErrorRecursive.Message != null) + writer.WriteString("message", verificationErrorRecursive.Message); + + if (verificationErrorRecursive._TypeOption.IsSet && verificationErrorRecursive.Type != null) + { + string? typeRawValue = VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (verificationErrorRecursive._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.RemediatingActions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/VerificationErrors.cs b/Adyen/LegalEntityManagement/Models/VerificationErrors.cs new file mode 100644 index 000000000..f65efeb46 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/VerificationErrors.cs @@ -0,0 +1,179 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// VerificationErrors. + /// + public partial class VerificationErrors : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of the verification errors. + [JsonConstructor] + public VerificationErrors(Option?> problems = default) + { + _ProblemsOption = problems; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationErrors() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// List of the verification errors. + /// + /// List of the verification errors. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationErrors {\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationErrors Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> problems = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new VerificationErrors(problems); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationErrors verificationErrors, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationErrors, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationErrors verificationErrors, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationErrors._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, verificationErrors.Problems, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/WebData.cs b/Adyen/LegalEntityManagement/Models/WebData.cs new file mode 100644 index 000000000..ad7790242 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/WebData.cs @@ -0,0 +1,202 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// WebData. + /// + public partial class WebData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The URL of the website or the app store URL. + /// The unique identifier of the web address. + [JsonConstructor] + public WebData(Option webAddress = default, Option webAddressId = default) + { + _WebAddressOption = webAddress; + _WebAddressIdOption = webAddressId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WebData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressOption { get; private set; } + + /// + /// The URL of the website or the app store URL. + /// + /// The URL of the website or the app store URL. + [JsonPropertyName("webAddress")] + public string? WebAddress { get { return this._WebAddressOption; } set { this._WebAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebAddressIdOption { get; } + + /// + /// The unique identifier of the web address. + /// + /// The unique identifier of the web address. + [JsonPropertyName("webAddressId")] + public string? WebAddressId { get { return this._WebAddressIdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WebData {\n"); + sb.Append(" WebAddress: ").Append(WebAddress).Append("\n"); + sb.Append(" WebAddressId: ").Append(WebAddressId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WebData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option webAddress = default; + Option webAddressId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "webAddress": + webAddress = new Option(utf8JsonReader.GetString()!); + break; + case "webAddressId": + webAddressId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new WebData(webAddress, webAddressId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WebData webData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, webData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WebData webData, JsonSerializerOptions jsonSerializerOptions) + { + + if (webData._WebAddressOption.IsSet) + if (webData.WebAddress != null) + writer.WriteString("webAddress", webData.WebAddress); + + if (webData._WebAddressIdOption.IsSet) + if (webData.WebAddressId != null) + writer.WriteString("webAddressId", webData.WebAddressId); + } + } +} diff --git a/Adyen/LegalEntityManagement/Models/WebDataExemption.cs b/Adyen/LegalEntityManagement/Models/WebDataExemption.cs new file mode 100644 index 000000000..544a58fb1 --- /dev/null +++ b/Adyen/LegalEntityManagement/Models/WebDataExemption.cs @@ -0,0 +1,283 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.LegalEntityManagement.Client; + +namespace Adyen.LegalEntityManagement.Models +{ + /// + /// WebDataExemption. + /// + public partial class WebDataExemption : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason why the web data was not provided. Possible value: **noOnlinePresence**. + [JsonConstructor] + public WebDataExemption(Option reason = default) + { + _ReasonOption = reason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WebDataExemption() + { + } + + partial void OnCreated(); + + /// + /// The reason why the web data was not provided. Possible value: **noOnlinePresence**. + /// + /// The reason why the web data was not provided. Possible value: **noOnlinePresence**. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.NoOnlinePresence - noOnlinePresence + /// + public static readonly ReasonEnum NoOnlinePresence = new("noOnlinePresence"); + + /// + /// ReasonEnum.NotCollectedDuringOnboarding - notCollectedDuringOnboarding + /// + public static readonly ReasonEnum NotCollectedDuringOnboarding = new("notCollectedDuringOnboarding"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "noOnlinePresence" => ReasonEnum.NoOnlinePresence, + "notCollectedDuringOnboarding" => ReasonEnum.NotCollectedDuringOnboarding, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.NoOnlinePresence) + return "noOnlinePresence"; + + if (value == ReasonEnum.NotCollectedDuringOnboarding) + return "notCollectedDuringOnboarding"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason why the web data was not provided. Possible value: **noOnlinePresence**. + /// + /// The reason why the web data was not provided. Possible value: **noOnlinePresence**. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WebDataExemption {\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebDataExemptionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WebDataExemption Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(WebDataExemption.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + default: + break; + } + } + } + + + return new WebDataExemption(reason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WebDataExemption webDataExemption, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, webDataExemption, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WebDataExemption webDataExemption, JsonSerializerOptions jsonSerializerOptions) + { + + if (webDataExemption._ReasonOption.IsSet && webDataExemption.Reason != null) + { + string? reasonRawValue = WebDataExemption.ReasonEnum.ToJsonValue(webDataExemption._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + } + } +} diff --git a/Adyen/LegalEntityManagement/Services/BusinessLinesService.cs b/Adyen/LegalEntityManagement/Services/BusinessLinesService.cs new file mode 100644 index 000000000..c5b144130 --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/BusinessLinesService.cs @@ -0,0 +1,1814 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IBusinessLinesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + BusinessLinesServiceEvents Events { get; } + + /// + /// Create a business line + /// + /// + /// Creates a business line. This resource contains information about your user's line of business, including their industry and their source of funds. Adyen uses this information to verify your users as required by payment industry regulations.Adyen informs you of the verification results through webhooks or API responses. You can create a maximum of 200 business lines per legal entity for payment processing. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateBusinessLineAsync(BusinessLineInfo businessLineInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a business line + /// + /// + /// Deletes a business line. >If you delete a business line linked to a [payment method](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api), it can affect your merchant account's ability to use the [payment method](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/_merchantId_/paymentMethodSettings). The business line is removed from all linked merchant accounts. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line to be deleted. + /// . + /// . + /// of . + Task DeleteBusinessLineAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a business line + /// + /// + /// Returns the detail of a business line. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line. + /// . + /// . + /// of . + Task GetBusinessLineAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a business line + /// + /// + /// Updates a business line. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line. + /// + /// . + /// . + /// of . + Task UpdateBusinessLineAsync(string id, BusinessLineInfoUpdate businessLineInfoUpdate, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateBusinessLineApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteBusinessLineApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetBusinessLineApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateBusinessLineApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class BusinessLinesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateBusinessLine; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateBusinessLine; + + internal void ExecuteOnCreateBusinessLine(BusinessLinesService.CreateBusinessLineApiResponse apiResponse) + { + OnCreateBusinessLine?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateBusinessLine(Exception exception) + { + OnErrorCreateBusinessLine?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteBusinessLine; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteBusinessLine; + + internal void ExecuteOnDeleteBusinessLine(BusinessLinesService.DeleteBusinessLineApiResponse apiResponse) + { + OnDeleteBusinessLine?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteBusinessLine(Exception exception) + { + OnErrorDeleteBusinessLine?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetBusinessLine; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetBusinessLine; + + internal void ExecuteOnGetBusinessLine(BusinessLinesService.GetBusinessLineApiResponse apiResponse) + { + OnGetBusinessLine?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetBusinessLine(Exception exception) + { + OnErrorGetBusinessLine?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateBusinessLine; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateBusinessLine; + + internal void ExecuteOnUpdateBusinessLine(BusinessLinesService.UpdateBusinessLineApiResponse apiResponse) + { + OnUpdateBusinessLine?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateBusinessLine(Exception exception) + { + OnErrorUpdateBusinessLine?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class BusinessLinesService : IBusinessLinesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public BusinessLinesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public BusinessLinesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, BusinessLinesServiceEvents businessLinesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = businessLinesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a business line Creates a business line. This resource contains information about your user's line of business, including their industry and their source of funds. Adyen uses this information to verify your users as required by payment industry regulations.Adyen informs you of the verification results through webhooks or API responses. You can create a maximum of 200 business lines per legal entity for payment processing. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateBusinessLineAsync(BusinessLineInfo businessLineInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/businessLines" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/businessLines"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (businessLineInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(businessLineInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateBusinessLineApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/businessLines", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateBusinessLine(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateBusinessLine(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateBusinessLineApiResponse : Adyen.Core.Client.ApiResponse, ICreateBusinessLineApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.BusinessLine? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.BusinessLine? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a business line Deletes a business line. >If you delete a business line linked to a [payment method](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api), it can affect your merchant account's ability to use the [payment method](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/_merchantId_/paymentMethodSettings). The business line is removed from all linked merchant accounts. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line to be deleted. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteBusinessLineAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/businessLines/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/businessLines/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteBusinessLineApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/businessLines/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteBusinessLine(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteBusinessLine(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteBusinessLineApiResponse : Adyen.Core.Client.ApiResponse, IDeleteBusinessLineApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a business line Returns the detail of a business line. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetBusinessLineAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/businessLines/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/businessLines/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetBusinessLineApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/businessLines/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetBusinessLine(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetBusinessLine(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetBusinessLineApiResponse : Adyen.Core.Client.ApiResponse, IGetBusinessLineApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.BusinessLine? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.BusinessLine? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a business line Updates a business line. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the business line. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateBusinessLineAsync(string id, BusinessLineInfoUpdate businessLineInfoUpdate, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/businessLines/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/businessLines/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (businessLineInfoUpdate as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(businessLineInfoUpdate, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateBusinessLineApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/businessLines/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateBusinessLine(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateBusinessLine(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateBusinessLineApiResponse : Adyen.Core.Client.ApiResponse, IUpdateBusinessLineApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateBusinessLineApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.BusinessLine? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.BusinessLine? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/DocumentsService.cs b/Adyen/LegalEntityManagement/Services/DocumentsService.cs new file mode 100644 index 000000000..0f8f24c34 --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/DocumentsService.cs @@ -0,0 +1,1827 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IDocumentsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + DocumentsServiceEvents Events { get; } + + /// + /// Delete a document + /// + /// + /// Deletes a document. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document to be deleted. + /// . + /// . + /// of . + Task DeleteDocumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a document + /// + /// + /// Returns a document. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document. + /// Do not load document content while fetching the document. + /// . + /// . + /// of . + Task GetDocumentAsync(string id, Option skipContent = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a document + /// + /// + /// Updates a document. >You can upload a maximum of 15 pages for photo IDs. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document to be updated. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the document. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UpdateDocumentAsync(string id, Document document, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Upload a document for verification checks + /// + /// + /// Uploads a document for verification checks. Adyen uses the information from the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities) to run automated verification checks. If these checks fail, you will be notified to provide additional documents. You should only upload documents when Adyen requests additional information for the legal entity. >You can upload a maximum of 15 pages for photo IDs. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UploadDocumentForVerificationChecksAsync(Document document, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IDeleteDocumentApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUploadDocumentForVerificationChecksApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class DocumentsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteDocument; + + internal void ExecuteOnDeleteDocument(DocumentsService.DeleteDocumentApiResponse apiResponse) + { + OnDeleteDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteDocument(Exception exception) + { + OnErrorDeleteDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetDocument; + + internal void ExecuteOnGetDocument(DocumentsService.GetDocumentApiResponse apiResponse) + { + OnGetDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetDocument(Exception exception) + { + OnErrorGetDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateDocument; + + internal void ExecuteOnUpdateDocument(DocumentsService.UpdateDocumentApiResponse apiResponse) + { + OnUpdateDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateDocument(Exception exception) + { + OnErrorUpdateDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUploadDocumentForVerificationChecks; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUploadDocumentForVerificationChecks; + + internal void ExecuteOnUploadDocumentForVerificationChecks(DocumentsService.UploadDocumentForVerificationChecksApiResponse apiResponse) + { + OnUploadDocumentForVerificationChecks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUploadDocumentForVerificationChecks(Exception exception) + { + OnErrorUploadDocumentForVerificationChecks?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class DocumentsService : IDocumentsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public DocumentsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public DocumentsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DocumentsServiceEvents documentsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = documentsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Delete a document Deletes a document. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document to be deleted. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteDocumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/documents/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/documents/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/documents/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteDocumentApiResponse : Adyen.Core.Client.ApiResponse, IDeleteDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a document Returns a document. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document. + /// Do not load document content while fetching the document. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetDocumentAsync(string id, Option skipContent = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/documents/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/documents/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (skipContent.IsSet) + parseQueryString["skipContent"] = ClientUtils.ParameterToString(skipContent.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/documents/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetDocumentApiResponse : Adyen.Core.Client.ApiResponse, IGetDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.Document? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.Document? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a document Updates a document. >You can upload a maximum of 15 pages for photo IDs. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the document to be updated. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the document. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateDocumentAsync(string id, Document document, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/documents/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/documents/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (document as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(document, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/documents/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateDocumentApiResponse : Adyen.Core.Client.ApiResponse, IUpdateDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.Document? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.Document? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Upload a document for verification checks Uploads a document for verification checks. Adyen uses the information from the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities) to run automated verification checks. If these checks fail, you will be notified to provide additional documents. You should only upload documents when Adyen requests additional information for the legal entity. >You can upload a maximum of 15 pages for photo IDs. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UploadDocumentForVerificationChecksAsync(Document document, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/documents" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/documents"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (document as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(document, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UploadDocumentForVerificationChecksApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/documents", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUploadDocumentForVerificationChecks(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUploadDocumentForVerificationChecks(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UploadDocumentForVerificationChecksApiResponse : Adyen.Core.Client.ApiResponse, IUploadDocumentForVerificationChecksApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadDocumentForVerificationChecksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadDocumentForVerificationChecksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.Document? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.Document? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/HostedOnboardingService.cs b/Adyen/LegalEntityManagement/Services/HostedOnboardingService.cs new file mode 100644 index 000000000..97e72e8ba --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/HostedOnboardingService.cs @@ -0,0 +1,1399 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IHostedOnboardingService : IAdyenApiService + { + /// + /// The class containing the events. + /// + HostedOnboardingServiceEvents Events { get; } + + /// + /// Get a link to an Adyen-hosted onboarding page + /// + /// + /// Returns a link to an Adyen-hosted onboarding page where you need to redirect your user. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity + /// + /// . + /// . + /// of . + Task GetLinkToAdyenhostedOnboardingPageAsync(string id, OnboardingLinkInfo onboardingLinkInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an onboarding link theme + /// + /// + /// Returns the details of the theme identified in the path. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the theme + /// . + /// . + /// of . + Task GetOnboardingLinkThemeAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of hosted onboarding page themes + /// + /// + /// Returns a list of hosted onboarding page themes. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of . + Task ListHostedOnboardingPageThemesAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetLinkToAdyenhostedOnboardingPageApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetOnboardingLinkThemeApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListHostedOnboardingPageThemesApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class HostedOnboardingServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetLinkToAdyenhostedOnboardingPage; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetLinkToAdyenhostedOnboardingPage; + + internal void ExecuteOnGetLinkToAdyenhostedOnboardingPage(HostedOnboardingService.GetLinkToAdyenhostedOnboardingPageApiResponse apiResponse) + { + OnGetLinkToAdyenhostedOnboardingPage?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetLinkToAdyenhostedOnboardingPage(Exception exception) + { + OnErrorGetLinkToAdyenhostedOnboardingPage?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetOnboardingLinkTheme; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetOnboardingLinkTheme; + + internal void ExecuteOnGetOnboardingLinkTheme(HostedOnboardingService.GetOnboardingLinkThemeApiResponse apiResponse) + { + OnGetOnboardingLinkTheme?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetOnboardingLinkTheme(Exception exception) + { + OnErrorGetOnboardingLinkTheme?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListHostedOnboardingPageThemes; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListHostedOnboardingPageThemes; + + internal void ExecuteOnListHostedOnboardingPageThemes(HostedOnboardingService.ListHostedOnboardingPageThemesApiResponse apiResponse) + { + OnListHostedOnboardingPageThemes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListHostedOnboardingPageThemes(Exception exception) + { + OnErrorListHostedOnboardingPageThemes?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class HostedOnboardingService : IHostedOnboardingService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public HostedOnboardingServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public HostedOnboardingService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, HostedOnboardingServiceEvents hostedOnboardingServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = hostedOnboardingServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a link to an Adyen-hosted onboarding page Returns a link to an Adyen-hosted onboarding page where you need to redirect your user. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetLinkToAdyenhostedOnboardingPageAsync(string id, OnboardingLinkInfo onboardingLinkInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/onboardingLinks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/onboardingLinks"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (onboardingLinkInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(onboardingLinkInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetLinkToAdyenhostedOnboardingPageApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/onboardingLinks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetLinkToAdyenhostedOnboardingPage(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetLinkToAdyenhostedOnboardingPage(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetLinkToAdyenhostedOnboardingPageApiResponse : Adyen.Core.Client.ApiResponse, IGetLinkToAdyenhostedOnboardingPageApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetLinkToAdyenhostedOnboardingPageApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetLinkToAdyenhostedOnboardingPageApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.OnboardingLink? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.OnboardingLink? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an onboarding link theme Returns the details of the theme identified in the path. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the theme + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetOnboardingLinkThemeAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/themes/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/themes/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetOnboardingLinkThemeApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/themes/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetOnboardingLinkTheme(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetOnboardingLinkTheme(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetOnboardingLinkThemeApiResponse : Adyen.Core.Client.ApiResponse, IGetOnboardingLinkThemeApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetOnboardingLinkThemeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetOnboardingLinkThemeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.OnboardingTheme? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.OnboardingTheme? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of hosted onboarding page themes Returns a list of hosted onboarding page themes. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListHostedOnboardingPageThemesAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/themes" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/themes"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListHostedOnboardingPageThemesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/themes", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListHostedOnboardingPageThemes(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListHostedOnboardingPageThemes(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListHostedOnboardingPageThemesApiResponse : Adyen.Core.Client.ApiResponse, IListHostedOnboardingPageThemesApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListHostedOnboardingPageThemesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListHostedOnboardingPageThemesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.OnboardingThemes? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.OnboardingThemes? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/LegalEntitiesService.cs b/Adyen/LegalEntityManagement/Services/LegalEntitiesService.cs new file mode 100644 index 000000000..c09332136 --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/LegalEntitiesService.cs @@ -0,0 +1,2708 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ILegalEntitiesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + LegalEntitiesServiceEvents Events { get; } + + /// + /// Check a legal entity's verification errors + /// + /// + /// Returns the verification errors for a legal entity and its supporting entities. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of . + Task CheckLegalEntitysVerificationErrorsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Confirm data review + /// + /// + /// Confirms that your user has reviewed the data for the legal entity specified in the path. Call this endpoint to inform Adyen that your user reviewed and verified that the data is up-to-date. The endpoint returns the timestamp of when Adyen received the request. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of . + Task ConfirmDataReviewAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a legal entity + /// + /// + /// Creates a legal entity. This resource contains information about the user that will be onboarded in your platform. Adyen uses this information to perform verification checks as required by payment industry regulations. Adyen informs you of the verification results through webhooks or API responses. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CreateLegalEntityAsync(LegalEntityInfoRequiredType legalEntityInfoRequiredType, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all business lines under a legal entity + /// + /// + /// Returns the business lines owned by a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of . + Task GetAllBusinessLinesUnderLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a legal entity + /// + /// + /// Returns a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of . + Task GetLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a legal entity + /// + /// + /// Updates a legal entity. >To change the legal entity type, include only the new `type` in your request. If you need to update information for the legal entity, make a separate request. To update the `entityAssociations` array, you need to replace the entire array.For example, if the array has 3 entries and you want to remove 1 entry, you need to PATCH the resource with the remaining 2 entries. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the legal entity. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UpdateLegalEntityAsync(string id, LegalEntityInfo legalEntityInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICheckLegalEntitysVerificationErrorsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IConfirmDataReviewApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllBusinessLinesUnderLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class LegalEntitiesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCheckLegalEntitysVerificationErrors; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCheckLegalEntitysVerificationErrors; + + internal void ExecuteOnCheckLegalEntitysVerificationErrors(LegalEntitiesService.CheckLegalEntitysVerificationErrorsApiResponse apiResponse) + { + OnCheckLegalEntitysVerificationErrors?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCheckLegalEntitysVerificationErrors(Exception exception) + { + OnErrorCheckLegalEntitysVerificationErrors?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnConfirmDataReview; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorConfirmDataReview; + + internal void ExecuteOnConfirmDataReview(LegalEntitiesService.ConfirmDataReviewApiResponse apiResponse) + { + OnConfirmDataReview?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorConfirmDataReview(Exception exception) + { + OnErrorConfirmDataReview?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateLegalEntity; + + internal void ExecuteOnCreateLegalEntity(LegalEntitiesService.CreateLegalEntityApiResponse apiResponse) + { + OnCreateLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateLegalEntity(Exception exception) + { + OnErrorCreateLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllBusinessLinesUnderLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllBusinessLinesUnderLegalEntity; + + internal void ExecuteOnGetAllBusinessLinesUnderLegalEntity(LegalEntitiesService.GetAllBusinessLinesUnderLegalEntityApiResponse apiResponse) + { + OnGetAllBusinessLinesUnderLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllBusinessLinesUnderLegalEntity(Exception exception) + { + OnErrorGetAllBusinessLinesUnderLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetLegalEntity; + + internal void ExecuteOnGetLegalEntity(LegalEntitiesService.GetLegalEntityApiResponse apiResponse) + { + OnGetLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetLegalEntity(Exception exception) + { + OnErrorGetLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateLegalEntity; + + internal void ExecuteOnUpdateLegalEntity(LegalEntitiesService.UpdateLegalEntityApiResponse apiResponse) + { + OnUpdateLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateLegalEntity(Exception exception) + { + OnErrorUpdateLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class LegalEntitiesService : ILegalEntitiesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public LegalEntitiesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public LegalEntitiesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, LegalEntitiesServiceEvents legalEntitiesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = legalEntitiesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Check a legal entity's verification errors Returns the verification errors for a legal entity and its supporting entities. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CheckLegalEntitysVerificationErrorsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/checkVerificationErrors" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/checkVerificationErrors"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CheckLegalEntitysVerificationErrorsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/checkVerificationErrors", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCheckLegalEntitysVerificationErrors(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCheckLegalEntitysVerificationErrors(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CheckLegalEntitysVerificationErrorsApiResponse : Adyen.Core.Client.ApiResponse, ICheckLegalEntitysVerificationErrorsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckLegalEntitysVerificationErrorsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckLegalEntitysVerificationErrorsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.VerificationErrors? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.VerificationErrors? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Confirm data review Confirms that your user has reviewed the data for the legal entity specified in the path. Call this endpoint to inform Adyen that your user reviewed and verified that the data is up-to-date. The endpoint returns the timestamp of when Adyen received the request. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ConfirmDataReviewAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/confirmDataReview" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/confirmDataReview"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ConfirmDataReviewApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/confirmDataReview", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnConfirmDataReview(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorConfirmDataReview(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ConfirmDataReviewApiResponse : Adyen.Core.Client.ApiResponse, IConfirmDataReviewApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ConfirmDataReviewApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ConfirmDataReviewApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.DataReviewConfirmationResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.DataReviewConfirmationResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a legal entity Creates a legal entity. This resource contains information about the user that will be onboarded in your platform. Adyen uses this information to perform verification checks as required by payment industry regulations. Adyen informs you of the verification results through webhooks or API responses. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateLegalEntityAsync(LegalEntityInfoRequiredType legalEntityInfoRequiredType, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (legalEntityInfoRequiredType as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(legalEntityInfoRequiredType, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, ICreateLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.LegalEntity? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.LegalEntity? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all business lines under a legal entity Returns the business lines owned by a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllBusinessLinesUnderLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/businessLines" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/businessLines"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllBusinessLinesUnderLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/businessLines", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllBusinessLinesUnderLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllBusinessLinesUnderLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllBusinessLinesUnderLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, IGetAllBusinessLinesUnderLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllBusinessLinesUnderLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllBusinessLinesUnderLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.BusinessLines? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.BusinessLines? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a legal entity Returns a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, IGetLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.LegalEntity? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.LegalEntity? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a legal entity Updates a legal entity. >To change the legal entity type, include only the new `type` in your request. If you need to update information for the legal entity, make a separate request. To update the `entityAssociations` array, you need to replace the entire array.For example, if the array has 3 entries and you want to remove 1 entry, you need to PATCH the resource with the remaining 2 entries. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the legal entity. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateLegalEntityAsync(string id, LegalEntityInfo legalEntityInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (legalEntityInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(legalEntityInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, IUpdateLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.LegalEntity? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.LegalEntity? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/PCIQuestionnairesService.cs b/Adyen/LegalEntityManagement/Services/PCIQuestionnairesService.cs new file mode 100644 index 000000000..e97c2e3af --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/PCIQuestionnairesService.cs @@ -0,0 +1,2299 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPCIQuestionnairesService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PCIQuestionnairesServiceEvents Events { get; } + + /// + /// Calculate PCI status of a legal entity + /// + /// + /// Calculate PCI status of a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to calculate PCI status. + /// + /// . + /// . + /// of . + Task CalculatePciStatusOfLegalEntityAsync(string id, CalculatePciStatusRequest calculatePciStatusRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Generate PCI questionnaire + /// + /// + /// Generates the required PCI questionnaires based on the user's [salesChannel](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines__reqParam_salesChannels). Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to get PCI questionnaire information. + /// + /// . + /// . + /// of . + Task GeneratePciQuestionnaireAsync(string id, GeneratePciDescriptionRequest generatePciDescriptionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get PCI questionnaire + /// + /// + /// Returns the signed PCI questionnaire. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The legal entity ID of the individual who signed the PCI questionnaire. + /// The unique identifier of the signed PCI questionnaire. + /// . + /// . + /// of . + Task GetPciQuestionnaireAsync(string id, string pciid, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get PCI questionnaire details + /// + /// + /// Get a list of signed PCI questionnaires. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to get PCI questionnaire information. + /// . + /// . + /// of . + Task GetPciQuestionnaireDetailsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Sign PCI questionnaire + /// + /// + /// Signs the required PCI questionnaire. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The legal entity ID of the user that has a contractual relationship with your platform. + /// + /// . + /// . + /// of . + Task SignPciQuestionnaireAsync(string id, PciSigningRequest pciSigningRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICalculatePciStatusOfLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGeneratePciQuestionnaireApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPciQuestionnaireApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPciQuestionnaireDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISignPciQuestionnaireApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PCIQuestionnairesServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCalculatePciStatusOfLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCalculatePciStatusOfLegalEntity; + + internal void ExecuteOnCalculatePciStatusOfLegalEntity(PCIQuestionnairesService.CalculatePciStatusOfLegalEntityApiResponse apiResponse) + { + OnCalculatePciStatusOfLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCalculatePciStatusOfLegalEntity(Exception exception) + { + OnErrorCalculatePciStatusOfLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGeneratePciQuestionnaire; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGeneratePciQuestionnaire; + + internal void ExecuteOnGeneratePciQuestionnaire(PCIQuestionnairesService.GeneratePciQuestionnaireApiResponse apiResponse) + { + OnGeneratePciQuestionnaire?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGeneratePciQuestionnaire(Exception exception) + { + OnErrorGeneratePciQuestionnaire?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPciQuestionnaire; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPciQuestionnaire; + + internal void ExecuteOnGetPciQuestionnaire(PCIQuestionnairesService.GetPciQuestionnaireApiResponse apiResponse) + { + OnGetPciQuestionnaire?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPciQuestionnaire(Exception exception) + { + OnErrorGetPciQuestionnaire?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPciQuestionnaireDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPciQuestionnaireDetails; + + internal void ExecuteOnGetPciQuestionnaireDetails(PCIQuestionnairesService.GetPciQuestionnaireDetailsApiResponse apiResponse) + { + OnGetPciQuestionnaireDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPciQuestionnaireDetails(Exception exception) + { + OnErrorGetPciQuestionnaireDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSignPciQuestionnaire; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSignPciQuestionnaire; + + internal void ExecuteOnSignPciQuestionnaire(PCIQuestionnairesService.SignPciQuestionnaireApiResponse apiResponse) + { + OnSignPciQuestionnaire?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSignPciQuestionnaire(Exception exception) + { + OnErrorSignPciQuestionnaire?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PCIQuestionnairesService : IPCIQuestionnairesService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PCIQuestionnairesServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PCIQuestionnairesService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PCIQuestionnairesServiceEvents pCIQuestionnairesServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = pCIQuestionnairesServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Calculate PCI status of a legal entity Calculate PCI status of a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to calculate PCI status. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CalculatePciStatusOfLegalEntityAsync(string id, CalculatePciStatusRequest calculatePciStatusRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/pciQuestionnaires/signingRequired" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/pciQuestionnaires/signingRequired"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (calculatePciStatusRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(calculatePciStatusRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CalculatePciStatusOfLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/pciQuestionnaires/signingRequired", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCalculatePciStatusOfLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCalculatePciStatusOfLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CalculatePciStatusOfLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, ICalculatePciStatusOfLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CalculatePciStatusOfLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CalculatePciStatusOfLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.CalculatePciStatusResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.CalculatePciStatusResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Generate PCI questionnaire Generates the required PCI questionnaires based on the user's [salesChannel](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines__reqParam_salesChannels). Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to get PCI questionnaire information. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GeneratePciQuestionnaireAsync(string id, GeneratePciDescriptionRequest generatePciDescriptionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/pciQuestionnaires/generatePciTemplates" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/pciQuestionnaires/generatePciTemplates"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (generatePciDescriptionRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(generatePciDescriptionRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GeneratePciQuestionnaireApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/pciQuestionnaires/generatePciTemplates", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGeneratePciQuestionnaire(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGeneratePciQuestionnaire(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GeneratePciQuestionnaireApiResponse : Adyen.Core.Client.ApiResponse, IGeneratePciQuestionnaireApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GeneratePciDescriptionResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GeneratePciDescriptionResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get PCI questionnaire Returns the signed PCI questionnaire. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The legal entity ID of the individual who signed the PCI questionnaire. + /// The unique identifier of the signed PCI questionnaire. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPciQuestionnaireAsync(string id, string pciid, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/pciQuestionnaires/{pciid}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/pciQuestionnaires/{pciid}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bpciid%7D", Uri.EscapeDataString(pciid.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPciQuestionnaireApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/pciQuestionnaires/{pciid}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPciQuestionnaire(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPciQuestionnaire(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPciQuestionnaireApiResponse : Adyen.Core.Client.ApiResponse, IGetPciQuestionnaireApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GetPciQuestionnaireResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GetPciQuestionnaireResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get PCI questionnaire details Get a list of signed PCI questionnaires. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity to get PCI questionnaire information. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPciQuestionnaireDetailsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/pciQuestionnaires" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/pciQuestionnaires"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPciQuestionnaireDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/pciQuestionnaires", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPciQuestionnaireDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPciQuestionnaireDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPciQuestionnaireDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetPciQuestionnaireDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPciQuestionnaireDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPciQuestionnaireDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GetPciQuestionnaireInfosResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GetPciQuestionnaireInfosResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Sign PCI questionnaire Signs the required PCI questionnaire. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The legal entity ID of the user that has a contractual relationship with your platform. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SignPciQuestionnaireAsync(string id, PciSigningRequest pciSigningRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/pciQuestionnaires/signPciTemplates" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/pciQuestionnaires/signPciTemplates"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (pciSigningRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(pciSigningRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SignPciQuestionnaireApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/pciQuestionnaires/signPciTemplates", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSignPciQuestionnaire(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSignPciQuestionnaire(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SignPciQuestionnaireApiResponse : Adyen.Core.Client.ApiResponse, ISignPciQuestionnaireApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SignPciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SignPciQuestionnaireApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.PciSigningResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.PciSigningResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/TaxEDeliveryConsentService.cs b/Adyen/LegalEntityManagement/Services/TaxEDeliveryConsentService.cs new file mode 100644 index 000000000..dbd5ea8c5 --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/TaxEDeliveryConsentService.cs @@ -0,0 +1,941 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITaxEDeliveryConsentService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TaxEDeliveryConsentServiceEvents Events { get; } + + /// + /// Check the status of consent for electronic delivery of tax forms + /// + /// + /// Returns the consent status for electronic delivery of tax forms. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of . + Task CheckStatusOfConsentForElectronicDeliveryOfTaxFormsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Set the consent status for electronic delivery of tax forms + /// + /// + /// Set the consent status for electronic delivery of tax forms. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// + /// . + /// . + /// of . + Task SetConsentStatusForElectronicDeliveryOfTaxFormsAsync(string id, SetTaxElectronicDeliveryConsentRequest setTaxElectronicDeliveryConsentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TaxEDeliveryConsentServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCheckStatusOfConsentForElectronicDeliveryOfTaxForms; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCheckStatusOfConsentForElectronicDeliveryOfTaxForms; + + internal void ExecuteOnCheckStatusOfConsentForElectronicDeliveryOfTaxForms(TaxEDeliveryConsentService.CheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse apiResponse) + { + OnCheckStatusOfConsentForElectronicDeliveryOfTaxForms?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCheckStatusOfConsentForElectronicDeliveryOfTaxForms(Exception exception) + { + OnErrorCheckStatusOfConsentForElectronicDeliveryOfTaxForms?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSetConsentStatusForElectronicDeliveryOfTaxForms; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSetConsentStatusForElectronicDeliveryOfTaxForms; + + internal void ExecuteOnSetConsentStatusForElectronicDeliveryOfTaxForms(TaxEDeliveryConsentService.SetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse apiResponse) + { + OnSetConsentStatusForElectronicDeliveryOfTaxForms?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSetConsentStatusForElectronicDeliveryOfTaxForms(Exception exception) + { + OnErrorSetConsentStatusForElectronicDeliveryOfTaxForms?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TaxEDeliveryConsentService : ITaxEDeliveryConsentService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TaxEDeliveryConsentServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TaxEDeliveryConsentService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TaxEDeliveryConsentServiceEvents taxEDeliveryConsentServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = taxEDeliveryConsentServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Check the status of consent for electronic delivery of tax forms Returns the consent status for electronic delivery of tax forms. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CheckStatusOfConsentForElectronicDeliveryOfTaxFormsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/checkTaxElectronicDeliveryConsent" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/checkTaxElectronicDeliveryConsent"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/checkTaxElectronicDeliveryConsent", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCheckStatusOfConsentForElectronicDeliveryOfTaxForms(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCheckStatusOfConsentForElectronicDeliveryOfTaxForms(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse : Adyen.Core.Client.ApiResponse, ICheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckStatusOfConsentForElectronicDeliveryOfTaxFormsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.CheckTaxElectronicDeliveryConsentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.CheckTaxElectronicDeliveryConsentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Set the consent status for electronic delivery of tax forms Set the consent status for electronic delivery of tax forms. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SetConsentStatusForElectronicDeliveryOfTaxFormsAsync(string id, SetTaxElectronicDeliveryConsentRequest setTaxElectronicDeliveryConsentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/setTaxElectronicDeliveryConsent" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/setTaxElectronicDeliveryConsent"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (setTaxElectronicDeliveryConsentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(setTaxElectronicDeliveryConsentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/setTaxElectronicDeliveryConsent", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSetConsentStatusForElectronicDeliveryOfTaxForms(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSetConsentStatusForElectronicDeliveryOfTaxForms(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse : Adyen.Core.Client.ApiResponse, ISetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SetConsentStatusForElectronicDeliveryOfTaxFormsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/TermsOfServiceService.cs b/Adyen/LegalEntityManagement/Services/TermsOfServiceService.cs new file mode 100644 index 000000000..6bbca110e --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/TermsOfServiceService.cs @@ -0,0 +1,2293 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITermsOfServiceService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TermsOfServiceServiceEvents Events { get; } + + /// + /// Accept Terms of Service + /// + /// + /// Accepts Terms of Service. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. For legal representatives of individuals, this is the ID of the individual. + /// The unique identifier of the Terms of Service document. + /// + /// . + /// . + /// of . + Task AcceptTermsOfServiceAsync(string id, string termsofservicedocumentid, AcceptTermsOfServiceRequest acceptTermsOfServiceRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get accepted Terms of Service document + /// + /// + /// Returns the accepted Terms of Service document for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorship, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// An Adyen-generated reference for the accepted Terms of Service. + /// The format of the Terms of Service document. Possible values: **JSON**, **PDF**, or **TXT** + /// . + /// . + /// of . + Task GetAcceptedTermsOfServiceDocumentAsync(string id, string termsofserviceacceptancereference, Option termsOfServiceDocumentFormat = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get Terms of Service document + /// + /// + /// Returns the Terms of Service document for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// + /// . + /// . + /// of . + Task GetTermsOfServiceDocumentAsync(string id, GetTermsOfServiceDocumentRequest getTermsOfServiceDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get Terms of Service information for a legal entity + /// + /// + /// Returns Terms of Service information for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of . + Task GetTermsOfServiceInformationForLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get Terms of Service status + /// + /// + /// Returns the required types of Terms of Service that need to be accepted by a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of . + Task GetTermsOfServiceStatusAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAcceptTermsOfServiceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAcceptedTermsOfServiceDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTermsOfServiceDocumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTermsOfServiceInformationForLegalEntityApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTermsOfServiceStatusApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TermsOfServiceServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAcceptTermsOfService; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAcceptTermsOfService; + + internal void ExecuteOnAcceptTermsOfService(TermsOfServiceService.AcceptTermsOfServiceApiResponse apiResponse) + { + OnAcceptTermsOfService?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAcceptTermsOfService(Exception exception) + { + OnErrorAcceptTermsOfService?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAcceptedTermsOfServiceDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAcceptedTermsOfServiceDocument; + + internal void ExecuteOnGetAcceptedTermsOfServiceDocument(TermsOfServiceService.GetAcceptedTermsOfServiceDocumentApiResponse apiResponse) + { + OnGetAcceptedTermsOfServiceDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAcceptedTermsOfServiceDocument(Exception exception) + { + OnErrorGetAcceptedTermsOfServiceDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTermsOfServiceDocument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTermsOfServiceDocument; + + internal void ExecuteOnGetTermsOfServiceDocument(TermsOfServiceService.GetTermsOfServiceDocumentApiResponse apiResponse) + { + OnGetTermsOfServiceDocument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTermsOfServiceDocument(Exception exception) + { + OnErrorGetTermsOfServiceDocument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTermsOfServiceInformationForLegalEntity; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTermsOfServiceInformationForLegalEntity; + + internal void ExecuteOnGetTermsOfServiceInformationForLegalEntity(TermsOfServiceService.GetTermsOfServiceInformationForLegalEntityApiResponse apiResponse) + { + OnGetTermsOfServiceInformationForLegalEntity?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTermsOfServiceInformationForLegalEntity(Exception exception) + { + OnErrorGetTermsOfServiceInformationForLegalEntity?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTermsOfServiceStatus; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTermsOfServiceStatus; + + internal void ExecuteOnGetTermsOfServiceStatus(TermsOfServiceService.GetTermsOfServiceStatusApiResponse apiResponse) + { + OnGetTermsOfServiceStatus?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTermsOfServiceStatus(Exception exception) + { + OnErrorGetTermsOfServiceStatus?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TermsOfServiceService : ITermsOfServiceService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TermsOfServiceServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TermsOfServiceService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TermsOfServiceServiceEvents termsOfServiceServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = termsOfServiceServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Accept Terms of Service Accepts Terms of Service. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. For legal representatives of individuals, this is the ID of the individual. + /// The unique identifier of the Terms of Service document. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AcceptTermsOfServiceAsync(string id, string termsofservicedocumentid, AcceptTermsOfServiceRequest acceptTermsOfServiceRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/termsOfService/{termsofservicedocumentid}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/termsOfService/{termsofservicedocumentid}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Btermsofservicedocumentid%7D", Uri.EscapeDataString(termsofservicedocumentid.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (acceptTermsOfServiceRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(acceptTermsOfServiceRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AcceptTermsOfServiceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/termsOfService/{termsofservicedocumentid}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAcceptTermsOfService(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAcceptTermsOfService(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AcceptTermsOfServiceApiResponse : Adyen.Core.Client.ApiResponse, IAcceptTermsOfServiceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AcceptTermsOfServiceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AcceptTermsOfServiceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.AcceptTermsOfServiceResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.AcceptTermsOfServiceResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get accepted Terms of Service document Returns the accepted Terms of Service document for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorship, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// An Adyen-generated reference for the accepted Terms of Service. + /// The format of the Terms of Service document. Possible values: **JSON**, **PDF**, or **TXT** () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAcceptedTermsOfServiceDocumentAsync(string id, string termsofserviceacceptancereference, Option termsOfServiceDocumentFormat = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/acceptedTermsOfServiceDocument/{termsofserviceacceptancereference}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/acceptedTermsOfServiceDocument/{termsofserviceacceptancereference}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Btermsofserviceacceptancereference%7D", Uri.EscapeDataString(termsofserviceacceptancereference.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (termsOfServiceDocumentFormat.IsSet) + parseQueryString["termsOfServiceDocumentFormat"] = ClientUtils.ParameterToString(termsOfServiceDocumentFormat.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAcceptedTermsOfServiceDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/acceptedTermsOfServiceDocument/{termsofserviceacceptancereference}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAcceptedTermsOfServiceDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAcceptedTermsOfServiceDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAcceptedTermsOfServiceDocumentApiResponse : Adyen.Core.Client.ApiResponse, IGetAcceptedTermsOfServiceDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAcceptedTermsOfServiceDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAcceptedTermsOfServiceDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GetAcceptedTermsOfServiceDocumentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GetAcceptedTermsOfServiceDocumentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get Terms of Service document Returns the Terms of Service document for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTermsOfServiceDocumentAsync(string id, GetTermsOfServiceDocumentRequest getTermsOfServiceDocumentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/termsOfService" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/termsOfService"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (getTermsOfServiceDocumentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(getTermsOfServiceDocumentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTermsOfServiceDocumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/termsOfService", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTermsOfServiceDocument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTermsOfServiceDocument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTermsOfServiceDocumentApiResponse : Adyen.Core.Client.ApiResponse, IGetTermsOfServiceDocumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceDocumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GetTermsOfServiceDocumentResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GetTermsOfServiceDocumentResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get Terms of Service information for a legal entity Returns Terms of Service information for a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTermsOfServiceInformationForLegalEntityAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/termsOfServiceAcceptanceInfos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/termsOfServiceAcceptanceInfos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTermsOfServiceInformationForLegalEntityApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/termsOfServiceAcceptanceInfos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTermsOfServiceInformationForLegalEntity(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTermsOfServiceInformationForLegalEntity(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTermsOfServiceInformationForLegalEntityApiResponse : Adyen.Core.Client.ApiResponse, IGetTermsOfServiceInformationForLegalEntityApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceInformationForLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceInformationForLegalEntityApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.GetTermsOfServiceAcceptanceInfosResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.GetTermsOfServiceAcceptanceInfosResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get Terms of Service status Returns the required types of Terms of Service that need to be accepted by a legal entity. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTermsOfServiceStatusAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/legalEntities/{id}/termsOfServiceStatus" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/legalEntities/{id}/termsOfServiceStatus"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTermsOfServiceStatusApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/legalEntities/{id}/termsOfServiceStatus", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTermsOfServiceStatus(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTermsOfServiceStatus(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTermsOfServiceStatusApiResponse : Adyen.Core.Client.ApiResponse, IGetTermsOfServiceStatusApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceStatusApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTermsOfServiceStatusApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.CalculateTermsOfServiceStatusResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.CalculateTermsOfServiceStatusResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/LegalEntityManagement/Services/TransferInstrumentsService.cs b/Adyen/LegalEntityManagement/Services/TransferInstrumentsService.cs new file mode 100644 index 000000000..b0d93a5ac --- /dev/null +++ b/Adyen/LegalEntityManagement/Services/TransferInstrumentsService.cs @@ -0,0 +1,1818 @@ +// +/* + * Legal Entity Management API + * + * The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Each request to the Legal Entity Management API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v4/legalEntities ``` ## Rate limits We enforce rate limits on Legal Entity Management API endpoints. When the number of requests you send exceeds a threshold within a time frame, additional requests are blocked until the time frame ends. Current limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration.You can then use the API key to send requests to `https://kyc-live.adyen.com/lem/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.LegalEntityManagement.Client; +using Adyen.LegalEntityManagement.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.LegalEntityManagement.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransferInstrumentsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransferInstrumentsServiceEvents Events { get; } + + /// + /// Create a transfer instrument + /// + /// + /// Creates a transfer instrument. A transfer instrument is a bank account that a legal entity owns. Adyen performs verification checks on the transfer instrument as required by payment industry regulations. We inform you of the verification results through webhooks or API responses. When the transfer instrument passes the verification checks, you can start sending funds from the balance platform to the transfer instrument (such as payouts). Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CreateTransferInstrumentAsync(TransferInstrumentInfo transferInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a transfer instrument + /// + /// + /// Deletes a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument to be deleted. + /// . + /// . + /// of . + Task DeleteTransferInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a transfer instrument + /// + /// + /// Returns the details of a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument. + /// . + /// . + /// of . + Task GetTransferInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a transfer instrument + /// + /// + /// Updates a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the transfer instrument. Requested verification codes can only be used in your test environment. - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task UpdateTransferInstrumentAsync(string id, TransferInstrumentInfo transferInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateTransferInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteTransferInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTransferInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTransferInstrumentApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransferInstrumentsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateTransferInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateTransferInstrument; + + internal void ExecuteOnCreateTransferInstrument(TransferInstrumentsService.CreateTransferInstrumentApiResponse apiResponse) + { + OnCreateTransferInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTransferInstrument(Exception exception) + { + OnErrorCreateTransferInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteTransferInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteTransferInstrument; + + internal void ExecuteOnDeleteTransferInstrument(TransferInstrumentsService.DeleteTransferInstrumentApiResponse apiResponse) + { + OnDeleteTransferInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTransferInstrument(Exception exception) + { + OnErrorDeleteTransferInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransferInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransferInstrument; + + internal void ExecuteOnGetTransferInstrument(TransferInstrumentsService.GetTransferInstrumentApiResponse apiResponse) + { + OnGetTransferInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransferInstrument(Exception exception) + { + OnErrorGetTransferInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTransferInstrument; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTransferInstrument; + + internal void ExecuteOnUpdateTransferInstrument(TransferInstrumentsService.UpdateTransferInstrumentApiResponse apiResponse) + { + OnUpdateTransferInstrument?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTransferInstrument(Exception exception) + { + OnErrorUpdateTransferInstrument?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransferInstrumentsService : ITransferInstrumentsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransferInstrumentsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransferInstrumentsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransferInstrumentsServiceEvents transferInstrumentsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transferInstrumentsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a transfer instrument Creates a transfer instrument. A transfer instrument is a bank account that a legal entity owns. Adyen performs verification checks on the transfer instrument as required by payment industry regulations. We inform you of the verification results through webhooks or API responses. When the transfer instrument passes the verification checks, you can start sending funds from the balance platform to the transfer instrument (such as payouts). Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateTransferInstrumentAsync(TransferInstrumentInfo transferInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transferInstruments" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transferInstruments"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transferInstrumentInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transferInstrumentInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateTransferInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transferInstruments", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateTransferInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateTransferInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateTransferInstrumentApiResponse : Adyen.Core.Client.ApiResponse, ICreateTransferInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.TransferInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.TransferInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a transfer instrument Deletes a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument to be deleted. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteTransferInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transferInstruments/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transferInstruments/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteTransferInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transferInstruments/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteTransferInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteTransferInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteTransferInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IDeleteTransferInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a transfer instrument Returns the details of a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransferInstrumentAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transferInstruments/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transferInstruments/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTransferInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transferInstruments/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransferInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransferInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTransferInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IGetTransferInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.TransferInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.TransferInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a transfer instrument Updates a transfer instrument. Requests to this endpoint are subject to rate limits: - Live environments: 700 requests per 5 seconds. - Test environments: 200 requests per 5 seconds. - Failed requests are subject to a limit of 5 failures per 10 seconds. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer instrument. + /// Use the requested verification code 0_0001 to resolve any suberrors associated with the transfer instrument. Requested verification codes can only be used in your test environment. () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTransferInstrumentAsync(string id, TransferInstrumentInfo transferInstrumentInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transferInstruments/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transferInstruments/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transferInstrumentInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transferInstrumentInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTransferInstrumentApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transferInstruments/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTransferInstrument(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTransferInstrument(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTransferInstrumentApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTransferInstrumentApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTransferInstrumentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.LegalEntityManagement.Models.TransferInstrument? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.TransferInstrument? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.LegalEntityManagement.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.LegalEntityManagement.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Client/ApiKeyToken.cs b/Adyen/Management/Client/ApiKeyToken.cs new file mode 100644 index 000000000..a608fb932 --- /dev/null +++ b/Adyen/Management/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Management.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Management/Client/ClientUtils.cs b/Adyen/Management/Client/ClientUtils.cs new file mode 100644 index 000000000..e57e800f0 --- /dev/null +++ b/Adyen/Management/Client/ClientUtils.cs @@ -0,0 +1,469 @@ +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Management.Models; +using Models = Adyen.Management.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Management.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AccelInfo.ProcessingTypeEnum accelInfoProcessingTypeEnum) + return Models.AccelInfo.ProcessingTypeEnum.ToJsonValue(accelInfoProcessingTypeEnum); + if (obj is Models.AmexInfo.ServiceLevelEnum amexInfoServiceLevelEnum) + return Models.AmexInfo.ServiceLevelEnum.ToJsonValue(amexInfoServiceLevelEnum); + if (obj is Models.AndroidApp.StatusEnum androidAppStatusEnum) + return Models.AndroidApp.StatusEnum.ToJsonValue(androidAppStatusEnum); + if (obj is Models.Connectivity.SimcardStatusEnum connectivitySimcardStatusEnum) + return Models.Connectivity.SimcardStatusEnum.ToJsonValue(connectivitySimcardStatusEnum); + if (obj is Models.CreateCompanyWebhookRequest.CommunicationFormatEnum createCompanyWebhookRequestCommunicationFormatEnum) + return Models.CreateCompanyWebhookRequest.CommunicationFormatEnum.ToJsonValue(createCompanyWebhookRequestCommunicationFormatEnum); + if (obj is Models.CreateCompanyWebhookRequest.FilterMerchantAccountTypeEnum createCompanyWebhookRequestFilterMerchantAccountTypeEnum) + return Models.CreateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.ToJsonValue(createCompanyWebhookRequestFilterMerchantAccountTypeEnum); + if (obj is Models.CreateCompanyWebhookRequest.EncryptionProtocolEnum createCompanyWebhookRequestEncryptionProtocolEnum) + return Models.CreateCompanyWebhookRequest.EncryptionProtocolEnum.ToJsonValue(createCompanyWebhookRequestEncryptionProtocolEnum); + if (obj is Models.CreateCompanyWebhookRequest.NetworkTypeEnum createCompanyWebhookRequestNetworkTypeEnum) + return Models.CreateCompanyWebhookRequest.NetworkTypeEnum.ToJsonValue(createCompanyWebhookRequestNetworkTypeEnum); + if (obj is Models.CreateMerchantWebhookRequest.CommunicationFormatEnum createMerchantWebhookRequestCommunicationFormatEnum) + return Models.CreateMerchantWebhookRequest.CommunicationFormatEnum.ToJsonValue(createMerchantWebhookRequestCommunicationFormatEnum); + if (obj is Models.CreateMerchantWebhookRequest.EncryptionProtocolEnum createMerchantWebhookRequestEncryptionProtocolEnum) + return Models.CreateMerchantWebhookRequest.EncryptionProtocolEnum.ToJsonValue(createMerchantWebhookRequestEncryptionProtocolEnum); + if (obj is Models.CreateMerchantWebhookRequest.NetworkTypeEnum createMerchantWebhookRequestNetworkTypeEnum) + return Models.CreateMerchantWebhookRequest.NetworkTypeEnum.ToJsonValue(createMerchantWebhookRequestNetworkTypeEnum); + if (obj is Models.DinersInfo.ServiceLevelEnum dinersInfoServiceLevelEnum) + return Models.DinersInfo.ServiceLevelEnum.ToJsonValue(dinersInfoServiceLevelEnum); + if (obj is Models.InstallAndroidAppDetails.TypeEnum installAndroidAppDetailsTypeEnum) + return Models.InstallAndroidAppDetails.TypeEnum.ToJsonValue(installAndroidAppDetailsTypeEnum); + if (obj is Models.InstallAndroidCertificateDetails.TypeEnum installAndroidCertificateDetailsTypeEnum) + return Models.InstallAndroidCertificateDetails.TypeEnum.ToJsonValue(installAndroidCertificateDetailsTypeEnum); + if (obj is Models.JCBInfo.ServiceLevelEnum jCBInfoServiceLevelEnum) + return Models.JCBInfo.ServiceLevelEnum.ToJsonValue(jCBInfoServiceLevelEnum); + if (obj is Models.KlarnaInfo.RegionEnum klarnaInfoRegionEnum) + return Models.KlarnaInfo.RegionEnum.ToJsonValue(klarnaInfoRegionEnum); + if (obj is Models.Notification.CategoryEnum notificationCategoryEnum) + return Models.Notification.CategoryEnum.ToJsonValue(notificationCategoryEnum); + if (obj is Models.NyceInfo.ProcessingTypeEnum nyceInfoProcessingTypeEnum) + return Models.NyceInfo.ProcessingTypeEnum.ToJsonValue(nyceInfoProcessingTypeEnum); + if (obj is Models.PayAtTable.AuthenticationMethodEnum payAtTableAuthenticationMethodEnum) + return Models.PayAtTable.AuthenticationMethodEnum.ToJsonValue(payAtTableAuthenticationMethodEnum); + if (obj is Models.PayAtTable.PaymentInstrumentEnum payAtTablePaymentInstrumentEnum) + return Models.PayAtTable.PaymentInstrumentEnum.ToJsonValue(payAtTablePaymentInstrumentEnum); + if (obj is Models.PaymentMethod.VerificationStatusEnum paymentMethodVerificationStatusEnum) + return Models.PaymentMethod.VerificationStatusEnum.ToJsonValue(paymentMethodVerificationStatusEnum); + if (obj is Models.PaymentMethodResponse.TypesWithErrorsEnum paymentMethodResponseTypesWithErrorsEnum) + return PaymentMethodResponse.TypesWithErrorsEnum.ToJsonValue(paymentMethodResponseTypesWithErrorsEnum); + if (obj is Models.PaymentMethodSetupInfo.TypeEnum paymentMethodSetupInfoTypeEnum) + return Models.PaymentMethodSetupInfo.TypeEnum.ToJsonValue(paymentMethodSetupInfoTypeEnum); + if (obj is Models.PaymentMethodSetupInfo.ShopperInteractionEnum paymentMethodSetupInfoShopperInteractionEnum) + return Models.PaymentMethodSetupInfo.ShopperInteractionEnum.ToJsonValue(paymentMethodSetupInfoShopperInteractionEnum); + if (obj is Models.PayoutSettings.PriorityEnum payoutSettingsPriorityEnum) + return Models.PayoutSettings.PriorityEnum.ToJsonValue(payoutSettingsPriorityEnum); + if (obj is Models.PayoutSettings.VerificationStatusEnum payoutSettingsVerificationStatusEnum) + return Models.PayoutSettings.VerificationStatusEnum.ToJsonValue(payoutSettingsVerificationStatusEnum); + if (obj is Models.PulseInfo.ProcessingTypeEnum pulseInfoProcessingTypeEnum) + return Models.PulseInfo.ProcessingTypeEnum.ToJsonValue(pulseInfoProcessingTypeEnum); + if (obj is Models.ReleaseUpdateDetails.TypeEnum releaseUpdateDetailsTypeEnum) + return Models.ReleaseUpdateDetails.TypeEnum.ToJsonValue(releaseUpdateDetailsTypeEnum); + if (obj is Models.SplitConfigurationLogic.AcquiringFeesEnum splitConfigurationLogicAcquiringFeesEnum) + return Models.SplitConfigurationLogic.AcquiringFeesEnum.ToJsonValue(splitConfigurationLogicAcquiringFeesEnum); + if (obj is Models.SplitConfigurationLogic.AdyenCommissionEnum splitConfigurationLogicAdyenCommissionEnum) + return Models.SplitConfigurationLogic.AdyenCommissionEnum.ToJsonValue(splitConfigurationLogicAdyenCommissionEnum); + if (obj is Models.SplitConfigurationLogic.AdyenFeesEnum splitConfigurationLogicAdyenFeesEnum) + return Models.SplitConfigurationLogic.AdyenFeesEnum.ToJsonValue(splitConfigurationLogicAdyenFeesEnum); + if (obj is Models.SplitConfigurationLogic.AdyenMarkupEnum splitConfigurationLogicAdyenMarkupEnum) + return Models.SplitConfigurationLogic.AdyenMarkupEnum.ToJsonValue(splitConfigurationLogicAdyenMarkupEnum); + if (obj is Models.SplitConfigurationLogic.ChargebackEnum splitConfigurationLogicChargebackEnum) + return Models.SplitConfigurationLogic.ChargebackEnum.ToJsonValue(splitConfigurationLogicChargebackEnum); + if (obj is Models.SplitConfigurationLogic.ChargebackCostAllocationEnum splitConfigurationLogicChargebackCostAllocationEnum) + return Models.SplitConfigurationLogic.ChargebackCostAllocationEnum.ToJsonValue(splitConfigurationLogicChargebackCostAllocationEnum); + if (obj is Models.SplitConfigurationLogic.InterchangeEnum splitConfigurationLogicInterchangeEnum) + return Models.SplitConfigurationLogic.InterchangeEnum.ToJsonValue(splitConfigurationLogicInterchangeEnum); + if (obj is Models.SplitConfigurationLogic.PaymentFeeEnum splitConfigurationLogicPaymentFeeEnum) + return Models.SplitConfigurationLogic.PaymentFeeEnum.ToJsonValue(splitConfigurationLogicPaymentFeeEnum); + if (obj is Models.SplitConfigurationLogic.RefundEnum splitConfigurationLogicRefundEnum) + return Models.SplitConfigurationLogic.RefundEnum.ToJsonValue(splitConfigurationLogicRefundEnum); + if (obj is Models.SplitConfigurationLogic.RefundCostAllocationEnum splitConfigurationLogicRefundCostAllocationEnum) + return Models.SplitConfigurationLogic.RefundCostAllocationEnum.ToJsonValue(splitConfigurationLogicRefundCostAllocationEnum); + if (obj is Models.SplitConfigurationLogic.RemainderEnum splitConfigurationLogicRemainderEnum) + return Models.SplitConfigurationLogic.RemainderEnum.ToJsonValue(splitConfigurationLogicRemainderEnum); + if (obj is Models.SplitConfigurationLogic.SchemeFeeEnum splitConfigurationLogicSchemeFeeEnum) + return Models.SplitConfigurationLogic.SchemeFeeEnum.ToJsonValue(splitConfigurationLogicSchemeFeeEnum); + if (obj is Models.SplitConfigurationLogic.SurchargeEnum splitConfigurationLogicSurchargeEnum) + return Models.SplitConfigurationLogic.SurchargeEnum.ToJsonValue(splitConfigurationLogicSurchargeEnum); + if (obj is Models.SplitConfigurationLogic.TipEnum splitConfigurationLogicTipEnum) + return Models.SplitConfigurationLogic.TipEnum.ToJsonValue(splitConfigurationLogicTipEnum); + if (obj is Models.SplitConfigurationRule.FundingSourceEnum splitConfigurationRuleFundingSourceEnum) + return Models.SplitConfigurationRule.FundingSourceEnum.ToJsonValue(splitConfigurationRuleFundingSourceEnum); + if (obj is Models.SplitConfigurationRule.ShopperInteractionEnum splitConfigurationRuleShopperInteractionEnum) + return Models.SplitConfigurationRule.ShopperInteractionEnum.ToJsonValue(splitConfigurationRuleShopperInteractionEnum); + if (obj is Models.SplitConfigurationRule.CardRegionEnum splitConfigurationRuleCardRegionEnum) + return Models.SplitConfigurationRule.CardRegionEnum.ToJsonValue(splitConfigurationRuleCardRegionEnum); + if (obj is Models.StarInfo.ProcessingTypeEnum starInfoProcessingTypeEnum) + return Models.StarInfo.ProcessingTypeEnum.ToJsonValue(starInfoProcessingTypeEnum); + if (obj is Models.Store.StatusEnum storeStatusEnum) + return Models.Store.StatusEnum.ToJsonValue(storeStatusEnum); + if (obj is Models.TerminalAssignment.StatusEnum terminalAssignmentStatusEnum) + return Models.TerminalAssignment.StatusEnum.ToJsonValue(terminalAssignmentStatusEnum); + if (obj is Models.TerminalConnectivityCellular.StatusEnum terminalConnectivityCellularStatusEnum) + return Models.TerminalConnectivityCellular.StatusEnum.ToJsonValue(terminalConnectivityCellularStatusEnum); + if (obj is Models.TransactionDescriptionInfo.TypeEnum transactionDescriptionInfoTypeEnum) + return Models.TransactionDescriptionInfo.TypeEnum.ToJsonValue(transactionDescriptionInfoTypeEnum); + if (obj is Models.UninstallAndroidAppDetails.TypeEnum uninstallAndroidAppDetailsTypeEnum) + return Models.UninstallAndroidAppDetails.TypeEnum.ToJsonValue(uninstallAndroidAppDetailsTypeEnum); + if (obj is Models.UninstallAndroidCertificateDetails.TypeEnum uninstallAndroidCertificateDetailsTypeEnum) + return Models.UninstallAndroidCertificateDetails.TypeEnum.ToJsonValue(uninstallAndroidCertificateDetailsTypeEnum); + if (obj is Models.UpdateCompanyWebhookRequest.CommunicationFormatEnum updateCompanyWebhookRequestCommunicationFormatEnum) + return Models.UpdateCompanyWebhookRequest.CommunicationFormatEnum.ToJsonValue(updateCompanyWebhookRequestCommunicationFormatEnum); + if (obj is Models.UpdateCompanyWebhookRequest.EncryptionProtocolEnum updateCompanyWebhookRequestEncryptionProtocolEnum) + return Models.UpdateCompanyWebhookRequest.EncryptionProtocolEnum.ToJsonValue(updateCompanyWebhookRequestEncryptionProtocolEnum); + if (obj is Models.UpdateCompanyWebhookRequest.FilterMerchantAccountTypeEnum updateCompanyWebhookRequestFilterMerchantAccountTypeEnum) + return Models.UpdateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.ToJsonValue(updateCompanyWebhookRequestFilterMerchantAccountTypeEnum); + if (obj is Models.UpdateCompanyWebhookRequest.NetworkTypeEnum updateCompanyWebhookRequestNetworkTypeEnum) + return Models.UpdateCompanyWebhookRequest.NetworkTypeEnum.ToJsonValue(updateCompanyWebhookRequestNetworkTypeEnum); + if (obj is Models.UpdateMerchantWebhookRequest.CommunicationFormatEnum updateMerchantWebhookRequestCommunicationFormatEnum) + return Models.UpdateMerchantWebhookRequest.CommunicationFormatEnum.ToJsonValue(updateMerchantWebhookRequestCommunicationFormatEnum); + if (obj is Models.UpdateMerchantWebhookRequest.EncryptionProtocolEnum updateMerchantWebhookRequestEncryptionProtocolEnum) + return Models.UpdateMerchantWebhookRequest.EncryptionProtocolEnum.ToJsonValue(updateMerchantWebhookRequestEncryptionProtocolEnum); + if (obj is Models.UpdateMerchantWebhookRequest.NetworkTypeEnum updateMerchantWebhookRequestNetworkTypeEnum) + return Models.UpdateMerchantWebhookRequest.NetworkTypeEnum.ToJsonValue(updateMerchantWebhookRequestNetworkTypeEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.AcquiringFeesEnum updateSplitConfigurationLogicRequestAcquiringFeesEnum) + return Models.UpdateSplitConfigurationLogicRequest.AcquiringFeesEnum.ToJsonValue(updateSplitConfigurationLogicRequestAcquiringFeesEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.AdyenCommissionEnum updateSplitConfigurationLogicRequestAdyenCommissionEnum) + return Models.UpdateSplitConfigurationLogicRequest.AdyenCommissionEnum.ToJsonValue(updateSplitConfigurationLogicRequestAdyenCommissionEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.AdyenFeesEnum updateSplitConfigurationLogicRequestAdyenFeesEnum) + return Models.UpdateSplitConfigurationLogicRequest.AdyenFeesEnum.ToJsonValue(updateSplitConfigurationLogicRequestAdyenFeesEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.AdyenMarkupEnum updateSplitConfigurationLogicRequestAdyenMarkupEnum) + return Models.UpdateSplitConfigurationLogicRequest.AdyenMarkupEnum.ToJsonValue(updateSplitConfigurationLogicRequestAdyenMarkupEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.ChargebackEnum updateSplitConfigurationLogicRequestChargebackEnum) + return Models.UpdateSplitConfigurationLogicRequest.ChargebackEnum.ToJsonValue(updateSplitConfigurationLogicRequestChargebackEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.ChargebackCostAllocationEnum updateSplitConfigurationLogicRequestChargebackCostAllocationEnum) + return Models.UpdateSplitConfigurationLogicRequest.ChargebackCostAllocationEnum.ToJsonValue(updateSplitConfigurationLogicRequestChargebackCostAllocationEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.InterchangeEnum updateSplitConfigurationLogicRequestInterchangeEnum) + return Models.UpdateSplitConfigurationLogicRequest.InterchangeEnum.ToJsonValue(updateSplitConfigurationLogicRequestInterchangeEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.PaymentFeeEnum updateSplitConfigurationLogicRequestPaymentFeeEnum) + return Models.UpdateSplitConfigurationLogicRequest.PaymentFeeEnum.ToJsonValue(updateSplitConfigurationLogicRequestPaymentFeeEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.RefundEnum updateSplitConfigurationLogicRequestRefundEnum) + return Models.UpdateSplitConfigurationLogicRequest.RefundEnum.ToJsonValue(updateSplitConfigurationLogicRequestRefundEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.RefundCostAllocationEnum updateSplitConfigurationLogicRequestRefundCostAllocationEnum) + return Models.UpdateSplitConfigurationLogicRequest.RefundCostAllocationEnum.ToJsonValue(updateSplitConfigurationLogicRequestRefundCostAllocationEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.RemainderEnum updateSplitConfigurationLogicRequestRemainderEnum) + return Models.UpdateSplitConfigurationLogicRequest.RemainderEnum.ToJsonValue(updateSplitConfigurationLogicRequestRemainderEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.SchemeFeeEnum updateSplitConfigurationLogicRequestSchemeFeeEnum) + return Models.UpdateSplitConfigurationLogicRequest.SchemeFeeEnum.ToJsonValue(updateSplitConfigurationLogicRequestSchemeFeeEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.SurchargeEnum updateSplitConfigurationLogicRequestSurchargeEnum) + return Models.UpdateSplitConfigurationLogicRequest.SurchargeEnum.ToJsonValue(updateSplitConfigurationLogicRequestSurchargeEnum); + if (obj is Models.UpdateSplitConfigurationLogicRequest.TipEnum updateSplitConfigurationLogicRequestTipEnum) + return Models.UpdateSplitConfigurationLogicRequest.TipEnum.ToJsonValue(updateSplitConfigurationLogicRequestTipEnum); + if (obj is Models.UpdateStoreRequest.StatusEnum updateStoreRequestStatusEnum) + return Models.UpdateStoreRequest.StatusEnum.ToJsonValue(updateStoreRequestStatusEnum); + if (obj is Models.Webhook.CommunicationFormatEnum webhookCommunicationFormatEnum) + return Models.Webhook.CommunicationFormatEnum.ToJsonValue(webhookCommunicationFormatEnum); + if (obj is Models.Webhook.EncryptionProtocolEnum webhookEncryptionProtocolEnum) + return Models.Webhook.EncryptionProtocolEnum.ToJsonValue(webhookEncryptionProtocolEnum); + if (obj is Models.Webhook.FilterMerchantAccountTypeEnum webhookFilterMerchantAccountTypeEnum) + return Models.Webhook.FilterMerchantAccountTypeEnum.ToJsonValue(webhookFilterMerchantAccountTypeEnum); + if (obj is Models.Webhook.NetworkTypeEnum webhookNetworkTypeEnum) + return Models.Webhook.NetworkTypeEnum.ToJsonValue(webhookNetworkTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Management/Client/HostConfiguration.cs b/Adyen/Management/Client/HostConfiguration.cs new file mode 100644 index 000000000..29c1193c4 --- /dev/null +++ b/Adyen/Management/Client/HostConfiguration.cs @@ -0,0 +1,384 @@ +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Management.Services; +using Adyen.Management.Client; +using Adyen.Management.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Management.Client +{ + /// + /// Provides hosting configuration for Management + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://management-test.adyen.com/v3"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccelInfoJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalCommissionJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalSettingsJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalSettingsResponseJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AffirmInfoJsonConverter()); + _jsonOptions.Converters.Add(new AfterpayTouchInfoJsonConverter()); + _jsonOptions.Converters.Add(new AlipayPlusInfoJsonConverter()); + _jsonOptions.Converters.Add(new AllowedOriginJsonConverter()); + _jsonOptions.Converters.Add(new AllowedOriginsResponseJsonConverter()); + _jsonOptions.Converters.Add(new AmexInfoJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AndroidAppJsonConverter()); + _jsonOptions.Converters.Add(new AndroidAppErrorJsonConverter()); + _jsonOptions.Converters.Add(new AndroidAppsResponseJsonConverter()); + _jsonOptions.Converters.Add(new AndroidCertificateJsonConverter()); + _jsonOptions.Converters.Add(new AndroidCertificatesResponseJsonConverter()); + _jsonOptions.Converters.Add(new ApiCredentialJsonConverter()); + _jsonOptions.Converters.Add(new ApiCredentialLinksJsonConverter()); + _jsonOptions.Converters.Add(new ApplePayInfoJsonConverter()); + _jsonOptions.Converters.Add(new BcmcInfoJsonConverter()); + _jsonOptions.Converters.Add(new BillingEntitiesResponseJsonConverter()); + _jsonOptions.Converters.Add(new BillingEntityJsonConverter()); + _jsonOptions.Converters.Add(new CardholderReceiptJsonConverter()); + _jsonOptions.Converters.Add(new CartesBancairesInfoJsonConverter()); + _jsonOptions.Converters.Add(new ClearpayInfoJsonConverter()); + _jsonOptions.Converters.Add(new CommissionJsonConverter()); + _jsonOptions.Converters.Add(new CompanyJsonConverter()); + _jsonOptions.Converters.Add(new CompanyApiCredentialJsonConverter()); + _jsonOptions.Converters.Add(new CompanyLinksJsonConverter()); + _jsonOptions.Converters.Add(new CompanyUserJsonConverter()); + _jsonOptions.Converters.Add(new ConnectivityJsonConverter()); + _jsonOptions.Converters.Add(new ContactJsonConverter()); + _jsonOptions.Converters.Add(new CreateAllowedOriginRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateApiCredentialResponseJsonConverter()); + _jsonOptions.Converters.Add(new CreateCompanyApiCredentialRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateCompanyApiCredentialResponseJsonConverter()); + _jsonOptions.Converters.Add(new CreateCompanyUserRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateCompanyUserResponseJsonConverter()); + _jsonOptions.Converters.Add(new CreateCompanyWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateMerchantApiCredentialRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateMerchantRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateMerchantResponseJsonConverter()); + _jsonOptions.Converters.Add(new CreateMerchantUserRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateMerchantWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateUserResponseJsonConverter()); + _jsonOptions.Converters.Add(new CurrencyJsonConverter()); + _jsonOptions.Converters.Add(new CustomNotificationJsonConverter()); + _jsonOptions.Converters.Add(new DataCenterJsonConverter()); + _jsonOptions.Converters.Add(new DinersInfoJsonConverter()); + _jsonOptions.Converters.Add(new EventUrlJsonConverter()); + _jsonOptions.Converters.Add(new ExternalTerminalActionJsonConverter()); + _jsonOptions.Converters.Add(new FileJsonConverter()); + _jsonOptions.Converters.Add(new GenerateApiKeyResponseJsonConverter()); + _jsonOptions.Converters.Add(new GenerateClientKeyResponseJsonConverter()); + _jsonOptions.Converters.Add(new GenerateHmacKeyResponseJsonConverter()); + _jsonOptions.Converters.Add(new GenericPmWithTdiInfoJsonConverter()); + _jsonOptions.Converters.Add(new GooglePayInfoJsonConverter()); + _jsonOptions.Converters.Add(new GratuityJsonConverter()); + _jsonOptions.Converters.Add(new HardwareJsonConverter()); + _jsonOptions.Converters.Add(new IdNameJsonConverter()); + _jsonOptions.Converters.Add(new InstallAndroidAppDetailsJsonConverter()); + _jsonOptions.Converters.Add(new InstallAndroidCertificateDetailsJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new JCBInfoJsonConverter()); + _jsonOptions.Converters.Add(new KeyJsonConverter()); + _jsonOptions.Converters.Add(new KlarnaInfoJsonConverter()); + _jsonOptions.Converters.Add(new LinksJsonConverter()); + _jsonOptions.Converters.Add(new LinksElementJsonConverter()); + _jsonOptions.Converters.Add(new ListCompanyApiCredentialsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListCompanyResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListCompanyUsersResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListExternalTerminalActionsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListMerchantApiCredentialsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListMerchantResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListMerchantUsersResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListStoresResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListTerminalsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ListWebhooksResponseJsonConverter()); + _jsonOptions.Converters.Add(new LocalizationJsonConverter()); + _jsonOptions.Converters.Add(new LogoJsonConverter()); + _jsonOptions.Converters.Add(new MeApiCredentialJsonConverter()); + _jsonOptions.Converters.Add(new MealVoucherFRInfoJsonConverter()); + _jsonOptions.Converters.Add(new MerchantJsonConverter()); + _jsonOptions.Converters.Add(new MerchantLinksJsonConverter()); + _jsonOptions.Converters.Add(new MinorUnitsMonetaryValueJsonConverter()); + _jsonOptions.Converters.Add(new ModelConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new Name2JsonConverter()); + _jsonOptions.Converters.Add(new NexoJsonConverter()); + _jsonOptions.Converters.Add(new NotificationJsonConverter()); + _jsonOptions.Converters.Add(new NotificationUrlJsonConverter()); + _jsonOptions.Converters.Add(new NyceInfoJsonConverter()); + _jsonOptions.Converters.Add(new OfflineProcessingJsonConverter()); + _jsonOptions.Converters.Add(new OpiJsonConverter()); + _jsonOptions.Converters.Add(new OrderItemJsonConverter()); + _jsonOptions.Converters.Add(new PaginationLinksJsonConverter()); + _jsonOptions.Converters.Add(new PasscodesJsonConverter()); + _jsonOptions.Converters.Add(new PayAtTableJsonConverter()); + _jsonOptions.Converters.Add(new PayByBankPlaidInfoJsonConverter()); + _jsonOptions.Converters.Add(new PayMeInfoJsonConverter()); + _jsonOptions.Converters.Add(new PayPalInfoJsonConverter()); + _jsonOptions.Converters.Add(new PayToInfoJsonConverter()); + _jsonOptions.Converters.Add(new PaymentJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodSetupInfoJsonConverter()); + _jsonOptions.Converters.Add(new PayoutSettingsJsonConverter()); + _jsonOptions.Converters.Add(new PayoutSettingsRequestJsonConverter()); + _jsonOptions.Converters.Add(new PayoutSettingsResponseJsonConverter()); + _jsonOptions.Converters.Add(new ProfileJsonConverter()); + _jsonOptions.Converters.Add(new PulseInfoJsonConverter()); + _jsonOptions.Converters.Add(new ReceiptOptionsJsonConverter()); + _jsonOptions.Converters.Add(new ReceiptPrintingJsonConverter()); + _jsonOptions.Converters.Add(new ReferencedJsonConverter()); + _jsonOptions.Converters.Add(new RefundsJsonConverter()); + _jsonOptions.Converters.Add(new ReleaseUpdateDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ReprocessAndroidAppResponseJsonConverter()); + _jsonOptions.Converters.Add(new RequestActivationResponseJsonConverter()); + _jsonOptions.Converters.Add(new RestServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new ScheduleTerminalActionsRequestJsonConverter()); + _jsonOptions.Converters.Add(new ScheduleTerminalActionsRequestActionDetailsJsonConverter()); + _jsonOptions.Converters.Add(new ScheduleTerminalActionsResponseJsonConverter()); + _jsonOptions.Converters.Add(new SepaDirectDebitInfoJsonConverter()); + _jsonOptions.Converters.Add(new SettingsJsonConverter()); + _jsonOptions.Converters.Add(new ShippingLocationJsonConverter()); + _jsonOptions.Converters.Add(new ShippingLocationsResponseJsonConverter()); + _jsonOptions.Converters.Add(new SignatureJsonConverter()); + _jsonOptions.Converters.Add(new SodexoInfoJsonConverter()); + _jsonOptions.Converters.Add(new SofortInfoJsonConverter()); + _jsonOptions.Converters.Add(new SplitConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new SplitConfigurationListJsonConverter()); + _jsonOptions.Converters.Add(new SplitConfigurationLogicJsonConverter()); + _jsonOptions.Converters.Add(new SplitConfigurationRuleJsonConverter()); + _jsonOptions.Converters.Add(new StandaloneJsonConverter()); + _jsonOptions.Converters.Add(new StarInfoJsonConverter()); + _jsonOptions.Converters.Add(new StoreJsonConverter()); + _jsonOptions.Converters.Add(new StoreAndForwardJsonConverter()); + _jsonOptions.Converters.Add(new StoreCreationRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoreCreationWithMerchantCodeRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoreLocationJsonConverter()); + _jsonOptions.Converters.Add(new StoreSplitConfigurationJsonConverter()); + _jsonOptions.Converters.Add(new SubMerchantDataJsonConverter()); + _jsonOptions.Converters.Add(new SupportedCardTypesJsonConverter()); + _jsonOptions.Converters.Add(new SurchargeJsonConverter()); + _jsonOptions.Converters.Add(new SwishInfoJsonConverter()); + _jsonOptions.Converters.Add(new TapToPayJsonConverter()); + _jsonOptions.Converters.Add(new TerminalJsonConverter()); + _jsonOptions.Converters.Add(new TerminalActionScheduleDetailJsonConverter()); + _jsonOptions.Converters.Add(new TerminalAssignmentJsonConverter()); + _jsonOptions.Converters.Add(new TerminalConnectivityJsonConverter()); + _jsonOptions.Converters.Add(new TerminalConnectivityBluetoothJsonConverter()); + _jsonOptions.Converters.Add(new TerminalConnectivityCellularJsonConverter()); + _jsonOptions.Converters.Add(new TerminalConnectivityEthernetJsonConverter()); + _jsonOptions.Converters.Add(new TerminalConnectivityWifiJsonConverter()); + _jsonOptions.Converters.Add(new TerminalInstructionsJsonConverter()); + _jsonOptions.Converters.Add(new TerminalModelsResponseJsonConverter()); + _jsonOptions.Converters.Add(new TerminalOrderJsonConverter()); + _jsonOptions.Converters.Add(new TerminalOrderRequestJsonConverter()); + _jsonOptions.Converters.Add(new TerminalOrdersResponseJsonConverter()); + _jsonOptions.Converters.Add(new TerminalProductJsonConverter()); + _jsonOptions.Converters.Add(new TerminalProductPriceJsonConverter()); + _jsonOptions.Converters.Add(new TerminalProductsResponseJsonConverter()); + _jsonOptions.Converters.Add(new TerminalReassignmentRequestJsonConverter()); + _jsonOptions.Converters.Add(new TerminalReassignmentTargetJsonConverter()); + _jsonOptions.Converters.Add(new TerminalSettingsJsonConverter()); + _jsonOptions.Converters.Add(new TestCompanyWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new TestOutputJsonConverter()); + _jsonOptions.Converters.Add(new TestWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new TestWebhookResponseJsonConverter()); + _jsonOptions.Converters.Add(new TicketInfoJsonConverter()); + _jsonOptions.Converters.Add(new TimeoutsJsonConverter()); + _jsonOptions.Converters.Add(new TransactionDescriptionInfoJsonConverter()); + _jsonOptions.Converters.Add(new TwintInfoJsonConverter()); + _jsonOptions.Converters.Add(new UninstallAndroidAppDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UninstallAndroidCertificateDetailsJsonConverter()); + _jsonOptions.Converters.Add(new UnreferencedJsonConverter()); + _jsonOptions.Converters.Add(new UpdatableAddressJsonConverter()); + _jsonOptions.Converters.Add(new UpdateCompanyApiCredentialRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateCompanyUserRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateCompanyWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateMerchantApiCredentialRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateMerchantUserRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateMerchantWebhookRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdatePaymentMethodInfoJsonConverter()); + _jsonOptions.Converters.Add(new UpdatePayoutSettingsRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateSplitConfigurationLogicRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateSplitConfigurationRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateSplitConfigurationRuleRequestJsonConverter()); + _jsonOptions.Converters.Add(new UpdateStoreRequestJsonConverter()); + _jsonOptions.Converters.Add(new UploadAndroidAppResponseJsonConverter()); + _jsonOptions.Converters.Add(new UploadAndroidCertificateResponseJsonConverter()); + _jsonOptions.Converters.Add(new UrlJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new VippsInfoJsonConverter()); + _jsonOptions.Converters.Add(new WeChatPayInfoJsonConverter()); + _jsonOptions.Converters.Add(new WeChatPayPosInfoJsonConverter()); + _jsonOptions.Converters.Add(new WebhookJsonConverter()); + _jsonOptions.Converters.Add(new WebhookLinksJsonConverter()); + _jsonOptions.Converters.Add(new WifiProfilesJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddManagementHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Management/Client/JsonSerializerOptionsProvider.cs b/Adyen/Management/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..a23dc0f32 --- /dev/null +++ b/Adyen/Management/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Management.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Management/Extensions/HostBuilderExtensions.cs b/Adyen/Management/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..3a902f050 --- /dev/null +++ b/Adyen/Management/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Management; +using Adyen.Management.Client; + +namespace Adyen.Management.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Management API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureManagement(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddManagementHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Management/Extensions/ServiceCollectionExtensions.cs b/Adyen/Management/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..ff9bc97b8 --- /dev/null +++ b/Adyen/Management/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Management.Client; + +namespace Adyen.Management.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Management API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddManagementServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddManagementHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Management/Models/AccelInfo.cs b/Adyen/Management/Models/AccelInfo.cs new file mode 100644 index 000000000..4afad9d15 --- /dev/null +++ b/Adyen/Management/Models/AccelInfo.cs @@ -0,0 +1,313 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AccelInfo. + /// + public partial class AccelInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// transactionDescription + [JsonConstructor] + public AccelInfo(ProcessingTypeEnum processingType, Option transactionDescription = default) + { + ProcessingType = processingType; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccelInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.Billpay - billpay + /// + public static readonly ProcessingTypeEnum Billpay = new("billpay"); + + /// + /// ProcessingTypeEnum.Ecom - ecom + /// + public static readonly ProcessingTypeEnum Ecom = new("ecom"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "billpay" => ProcessingTypeEnum.Billpay, + "ecom" => ProcessingTypeEnum.Ecom, + "pos" => ProcessingTypeEnum.Pos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.Billpay) + return "billpay"; + + if (value == ProcessingTypeEnum.Ecom) + return "ecom"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum ProcessingType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccelInfo {\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccelInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccelInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option processingType = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(AccelInfo.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!processingType.IsSet) + throw new ArgumentException("Property is required for class AccelInfo.", nameof(processingType)); + + return new AccelInfo(processingType.Value!.Value!, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccelInfo accelInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accelInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccelInfo accelInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (accelInfo.ProcessingType != null) + { + string? processingTypeRawValue = AccelInfo.ProcessingTypeEnum.ToJsonValue(accelInfo.ProcessingType); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (accelInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, accelInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/AdditionalCommission.cs b/Adyen/Management/Models/AdditionalCommission.cs new file mode 100644 index 000000000..653370bba --- /dev/null +++ b/Adyen/Management/Models/AdditionalCommission.cs @@ -0,0 +1,225 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AdditionalCommission. + /// + public partial class AdditionalCommission : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier of the balance account to which the additional commission is booked. + /// A fixed commission fee, in minor units. + /// A variable commission fee, in basis points. + [JsonConstructor] + public AdditionalCommission(Option balanceAccountId = default, Option fixedAmount = default, Option variablePercentage = default) + { + _BalanceAccountIdOption = balanceAccountId; + _FixedAmountOption = fixedAmount; + _VariablePercentageOption = variablePercentage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalCommission() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// Unique identifier of the balance account to which the additional commission is booked. + /// + /// Unique identifier of the balance account to which the additional commission is booked. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FixedAmountOption { get; private set; } + + /// + /// A fixed commission fee, in minor units. + /// + /// A fixed commission fee, in minor units. + [JsonPropertyName("fixedAmount")] + public long? FixedAmount { get { return this._FixedAmountOption; } set { this._FixedAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VariablePercentageOption { get; private set; } + + /// + /// A variable commission fee, in basis points. + /// + /// A variable commission fee, in basis points. + [JsonPropertyName("variablePercentage")] + public long? VariablePercentage { get { return this._VariablePercentageOption; } set { this._VariablePercentageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalCommission {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" FixedAmount: ").Append(FixedAmount).Append("\n"); + sb.Append(" VariablePercentage: ").Append(VariablePercentage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalCommissionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalCommission Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option fixedAmount = default; + Option variablePercentage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "fixedAmount": + fixedAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "variablePercentage": + variablePercentage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new AdditionalCommission(balanceAccountId, fixedAmount, variablePercentage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalCommission additionalCommission, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalCommission, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalCommission additionalCommission, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalCommission._BalanceAccountIdOption.IsSet) + if (additionalCommission.BalanceAccountId != null) + writer.WriteString("balanceAccountId", additionalCommission.BalanceAccountId); + + if (additionalCommission._FixedAmountOption.IsSet) + writer.WriteNumber("fixedAmount", additionalCommission._FixedAmountOption.Value!.Value); + + if (additionalCommission._VariablePercentageOption.IsSet) + writer.WriteNumber("variablePercentage", additionalCommission._VariablePercentageOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/AdditionalSettings.cs b/Adyen/Management/Models/AdditionalSettings.cs new file mode 100644 index 000000000..99ea035f7 --- /dev/null +++ b/Adyen/Management/Models/AdditionalSettings.cs @@ -0,0 +1,205 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AdditionalSettings. + /// + public partial class AdditionalSettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Object containing list of event codes for which the notification will be sent. + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + [JsonConstructor] + public AdditionalSettings(Option?> includeEventCodes = default, Option?> properties = default) + { + _IncludeEventCodesOption = includeEventCodes; + _PropertiesOption = properties; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalSettings() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IncludeEventCodesOption { get; private set; } + + /// + /// Object containing list of event codes for which the notification will be sent. + /// + /// Object containing list of event codes for which the notification will be sent. + [JsonPropertyName("includeEventCodes")] + public List? IncludeEventCodes { get { return this._IncludeEventCodesOption; } set { this._IncludeEventCodesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PropertiesOption { get; private set; } + + /// + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + /// + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + [JsonPropertyName("properties")] + public Dictionary? Properties { get { return this._PropertiesOption; } set { this._PropertiesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalSettings {\n"); + sb.Append(" IncludeEventCodes: ").Append(IncludeEventCodes).Append("\n"); + sb.Append(" Properties: ").Append(Properties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalSettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalSettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> includeEventCodes = default; + Option?> properties = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "includeEventCodes": + includeEventCodes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "properties": + properties = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AdditionalSettings(includeEventCodes, properties); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalSettings additionalSettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalSettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalSettings additionalSettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalSettings._IncludeEventCodesOption.IsSet) + { + writer.WritePropertyName("includeEventCodes"); + JsonSerializer.Serialize(writer, additionalSettings.IncludeEventCodes, jsonSerializerOptions); + } + if (additionalSettings._PropertiesOption.IsSet) + { + writer.WritePropertyName("properties"); + JsonSerializer.Serialize(writer, additionalSettings.Properties, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/AdditionalSettingsResponse.cs b/Adyen/Management/Models/AdditionalSettingsResponse.cs new file mode 100644 index 000000000..73791cab3 --- /dev/null +++ b/Adyen/Management/Models/AdditionalSettingsResponse.cs @@ -0,0 +1,231 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AdditionalSettingsResponse. + /// + public partial class AdditionalSettingsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Object containing list of event codes for which the notification will not be sent. + /// Object containing list of event codes for which the notification will be sent. + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + [JsonConstructor] + public AdditionalSettingsResponse(Option?> excludeEventCodes = default, Option?> includeEventCodes = default, Option?> properties = default) + { + _ExcludeEventCodesOption = excludeEventCodes; + _IncludeEventCodesOption = includeEventCodes; + _PropertiesOption = properties; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalSettingsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ExcludeEventCodesOption { get; private set; } + + /// + /// Object containing list of event codes for which the notification will not be sent. + /// + /// Object containing list of event codes for which the notification will not be sent. + [JsonPropertyName("excludeEventCodes")] + public List? ExcludeEventCodes { get { return this._ExcludeEventCodesOption; } set { this._ExcludeEventCodesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _IncludeEventCodesOption { get; private set; } + + /// + /// Object containing list of event codes for which the notification will be sent. + /// + /// Object containing list of event codes for which the notification will be sent. + [JsonPropertyName("includeEventCodes")] + public List? IncludeEventCodes { get { return this._IncludeEventCodesOption; } set { this._IncludeEventCodesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PropertiesOption { get; private set; } + + /// + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + /// + /// Object containing boolean key-value pairs. The key can be any [standard webhook additional setting](https://docs.adyen.com/development-resources/webhooks/additional-settings), and the value indicates if the setting is enabled. For example, `includeCaptureDelayHours`: **true** means the standard notifications you get will contain the number of hours remaining until the payment will be captured. + [JsonPropertyName("properties")] + public Dictionary? Properties { get { return this._PropertiesOption; } set { this._PropertiesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalSettingsResponse {\n"); + sb.Append(" ExcludeEventCodes: ").Append(ExcludeEventCodes).Append("\n"); + sb.Append(" IncludeEventCodes: ").Append(IncludeEventCodes).Append("\n"); + sb.Append(" Properties: ").Append(Properties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalSettingsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalSettingsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> excludeEventCodes = default; + Option?> includeEventCodes = default; + Option?> properties = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "excludeEventCodes": + excludeEventCodes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "includeEventCodes": + includeEventCodes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "properties": + properties = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AdditionalSettingsResponse(excludeEventCodes, includeEventCodes, properties); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalSettingsResponse additionalSettingsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalSettingsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalSettingsResponse additionalSettingsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalSettingsResponse._ExcludeEventCodesOption.IsSet) + { + writer.WritePropertyName("excludeEventCodes"); + JsonSerializer.Serialize(writer, additionalSettingsResponse.ExcludeEventCodes, jsonSerializerOptions); + } + if (additionalSettingsResponse._IncludeEventCodesOption.IsSet) + { + writer.WritePropertyName("includeEventCodes"); + JsonSerializer.Serialize(writer, additionalSettingsResponse.IncludeEventCodes, jsonSerializerOptions); + } + if (additionalSettingsResponse._PropertiesOption.IsSet) + { + writer.WritePropertyName("properties"); + JsonSerializer.Serialize(writer, additionalSettingsResponse.Properties, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Address.cs b/Adyen/Management/Models/Address.cs new file mode 100644 index 000000000..9959e70fd --- /dev/null +++ b/Adyen/Management/Models/Address.cs @@ -0,0 +1,327 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. + /// The name of the company. + /// The two-letter country code, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + /// The postal code. + /// The state or province as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Applicable for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + /// The name of the street, and the house or building number. + /// Additional address details, if any. + [JsonConstructor] + public Address(Option city = default, Option companyName = default, Option country = default, Option postalCode = default, Option stateOrProvince = default, Option streetAddress = default, Option streetAddress2 = default) + { + _CityOption = city; + _CompanyNameOption = companyName; + _CountryOption = country; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + _StreetAddressOption = streetAddress; + _StreetAddress2Option = streetAddress2; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyNameOption { get; private set; } + + /// + /// The name of the company. + /// + /// The name of the company. + [JsonPropertyName("companyName")] + public string? CompanyName { get { return this._CompanyNameOption; } set { this._CompanyNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The two-letter country code, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + /// + /// The two-letter country code, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. + /// + /// The postal code. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The state or province as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Applicable for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + /// + /// The state or province as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Applicable for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StreetAddressOption { get; private set; } + + /// + /// The name of the street, and the house or building number. + /// + /// The name of the street, and the house or building number. + [JsonPropertyName("streetAddress")] + public string? StreetAddress { get { return this._StreetAddressOption; } set { this._StreetAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StreetAddress2Option { get; private set; } + + /// + /// Additional address details, if any. + /// + /// Additional address details, if any. + [JsonPropertyName("streetAddress2")] + public string? StreetAddress2 { get { return this._StreetAddress2Option; } set { this._StreetAddress2Option = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" CompanyName: ").Append(CompanyName).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append(" StreetAddress: ").Append(StreetAddress).Append("\n"); + sb.Append(" StreetAddress2: ").Append(StreetAddress2).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option companyName = default; + Option country = default; + Option postalCode = default; + Option stateOrProvince = default; + Option streetAddress = default; + Option streetAddress2 = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "companyName": + companyName = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "streetAddress": + streetAddress = new Option(utf8JsonReader.GetString()!); + break; + case "streetAddress2": + streetAddress2 = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Address(city, companyName, country, postalCode, stateOrProvince, streetAddress, streetAddress2); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address._CityOption.IsSet) + if (address.City != null) + writer.WriteString("city", address.City); + + if (address._CompanyNameOption.IsSet) + if (address.CompanyName != null) + writer.WriteString("companyName", address.CompanyName); + + if (address._CountryOption.IsSet) + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address._PostalCodeOption.IsSet) + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + + if (address._StreetAddressOption.IsSet) + if (address.StreetAddress != null) + writer.WriteString("streetAddress", address.StreetAddress); + + if (address._StreetAddress2Option.IsSet) + if (address.StreetAddress2 != null) + writer.WriteString("streetAddress2", address.StreetAddress2); + } + } +} diff --git a/Adyen/Management/Models/AffirmInfo.cs b/Adyen/Management/Models/AffirmInfo.cs new file mode 100644 index 000000000..263283ca5 --- /dev/null +++ b/Adyen/Management/Models/AffirmInfo.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AffirmInfo. + /// + public partial class AffirmInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Merchant support email + [JsonConstructor] + public AffirmInfo(string supportEmail) + { + SupportEmail = supportEmail; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AffirmInfo() + { + } + + partial void OnCreated(); + + /// + /// Merchant support email + /// + /// Merchant support email + [JsonPropertyName("supportEmail")] + public string SupportEmail { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AffirmInfo {\n"); + sb.Append(" SupportEmail: ").Append(SupportEmail).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AffirmInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AffirmInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option supportEmail = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "supportEmail": + supportEmail = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!supportEmail.IsSet) + throw new ArgumentException("Property is required for class AffirmInfo.", nameof(supportEmail)); + + return new AffirmInfo(supportEmail.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AffirmInfo affirmInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, affirmInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AffirmInfo affirmInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (affirmInfo.SupportEmail != null) + writer.WriteString("supportEmail", affirmInfo.SupportEmail); + } + } +} diff --git a/Adyen/Management/Models/AfterpayTouchInfo.cs b/Adyen/Management/Models/AfterpayTouchInfo.cs new file mode 100644 index 000000000..5f037bf1c --- /dev/null +++ b/Adyen/Management/Models/AfterpayTouchInfo.cs @@ -0,0 +1,196 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AfterpayTouchInfo. + /// + public partial class AfterpayTouchInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Support Url + /// Support Email + [JsonConstructor] + public AfterpayTouchInfo(string supportUrl, Option supportEmail = default) + { + SupportUrl = supportUrl; + _SupportEmailOption = supportEmail; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AfterpayTouchInfo() + { + } + + partial void OnCreated(); + + /// + /// Support Url + /// + /// Support Url + [JsonPropertyName("supportUrl")] + public string SupportUrl { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SupportEmailOption { get; private set; } + + /// + /// Support Email + /// + /// Support Email + [JsonPropertyName("supportEmail")] + public string? SupportEmail { get { return this._SupportEmailOption; } set { this._SupportEmailOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AfterpayTouchInfo {\n"); + sb.Append(" SupportUrl: ").Append(SupportUrl).Append("\n"); + sb.Append(" SupportEmail: ").Append(SupportEmail).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AfterpayTouchInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AfterpayTouchInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option supportUrl = default; + Option supportEmail = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "supportUrl": + supportUrl = new Option(utf8JsonReader.GetString()!); + break; + case "supportEmail": + supportEmail = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!supportUrl.IsSet) + throw new ArgumentException("Property is required for class AfterpayTouchInfo.", nameof(supportUrl)); + + return new AfterpayTouchInfo(supportUrl.Value!, supportEmail); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AfterpayTouchInfo afterpayTouchInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, afterpayTouchInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AfterpayTouchInfo afterpayTouchInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (afterpayTouchInfo.SupportUrl != null) + writer.WriteString("supportUrl", afterpayTouchInfo.SupportUrl); + + if (afterpayTouchInfo._SupportEmailOption.IsSet) + if (afterpayTouchInfo.SupportEmail != null) + writer.WriteString("supportEmail", afterpayTouchInfo.SupportEmail); + } + } +} diff --git a/Adyen/Management/Models/AlipayPlusInfo.cs b/Adyen/Management/Models/AlipayPlusInfo.cs new file mode 100644 index 000000000..cb7dea1b7 --- /dev/null +++ b/Adyen/Management/Models/AlipayPlusInfo.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AlipayPlusInfo. + /// + public partial class AlipayPlusInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The currency used for settlement. Defaults to USD. + [JsonConstructor] + public AlipayPlusInfo(Option settlementCurrencyCode = default) + { + _SettlementCurrencyCodeOption = settlementCurrencyCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AlipayPlusInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SettlementCurrencyCodeOption { get; private set; } + + /// + /// The currency used for settlement. Defaults to USD. + /// + /// The currency used for settlement. Defaults to USD. + [JsonPropertyName("settlementCurrencyCode")] + public string? SettlementCurrencyCode { get { return this._SettlementCurrencyCodeOption; } set { this._SettlementCurrencyCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AlipayPlusInfo {\n"); + sb.Append(" SettlementCurrencyCode: ").Append(SettlementCurrencyCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AlipayPlusInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AlipayPlusInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option settlementCurrencyCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "settlementCurrencyCode": + settlementCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AlipayPlusInfo(settlementCurrencyCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AlipayPlusInfo alipayPlusInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, alipayPlusInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AlipayPlusInfo alipayPlusInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (alipayPlusInfo._SettlementCurrencyCodeOption.IsSet) + if (alipayPlusInfo.SettlementCurrencyCode != null) + writer.WriteString("settlementCurrencyCode", alipayPlusInfo.SettlementCurrencyCode); + } + } +} diff --git a/Adyen/Management/Models/AllowedOrigin.cs b/Adyen/Management/Models/AllowedOrigin.cs new file mode 100644 index 000000000..bb03052e6 --- /dev/null +++ b/Adyen/Management/Models/AllowedOrigin.cs @@ -0,0 +1,222 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AllowedOrigin. + /// + public partial class AllowedOrigin : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Domain of the allowed origin. + /// links + /// Unique identifier of the allowed origin. + [JsonConstructor] + public AllowedOrigin(string domain, Option links = default, Option id = default) + { + Domain = domain; + _LinksOption = links; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AllowedOrigin() + { + } + + partial void OnCreated(); + + /// + /// Domain of the allowed origin. + /// + /// Domain of the allowed origin. + /* https://adyen.com */ + [JsonPropertyName("domain")] + public string Domain { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Unique identifier of the allowed origin. + /// + /// Unique identifier of the allowed origin. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AllowedOrigin {\n"); + sb.Append(" Domain: ").Append(Domain).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AllowedOriginJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AllowedOrigin Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option domain = default; + Option links = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domain": + domain = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!domain.IsSet) + throw new ArgumentException("Property is required for class AllowedOrigin.", nameof(domain)); + + return new AllowedOrigin(domain.Value!, links, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AllowedOrigin allowedOrigin, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, allowedOrigin, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AllowedOrigin allowedOrigin, JsonSerializerOptions jsonSerializerOptions) + { + + if (allowedOrigin.Domain != null) + writer.WriteString("domain", allowedOrigin.Domain); + + if (allowedOrigin._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, allowedOrigin.Links, jsonSerializerOptions); + } + if (allowedOrigin._IdOption.IsSet) + if (allowedOrigin.Id != null) + writer.WriteString("id", allowedOrigin.Id); + } + } +} diff --git a/Adyen/Management/Models/AllowedOriginsResponse.cs b/Adyen/Management/Models/AllowedOriginsResponse.cs new file mode 100644 index 000000000..bec543153 --- /dev/null +++ b/Adyen/Management/Models/AllowedOriginsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AllowedOriginsResponse. + /// + public partial class AllowedOriginsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of allowed origins. + [JsonConstructor] + public AllowedOriginsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AllowedOriginsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List of allowed origins. + /// + /// List of allowed origins. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AllowedOriginsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AllowedOriginsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AllowedOriginsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AllowedOriginsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AllowedOriginsResponse allowedOriginsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, allowedOriginsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AllowedOriginsResponse allowedOriginsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (allowedOriginsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, allowedOriginsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/AmexInfo.cs b/Adyen/Management/Models/AmexInfo.cs new file mode 100644 index 000000000..ad030b6ed --- /dev/null +++ b/Adyen/Management/Models/AmexInfo.cs @@ -0,0 +1,342 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AmexInfo. + /// + public partial class AmexInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the service level (settlement type) of this payment method. Possible values: * **noContract**: Adyen holds the contract with American Express. * **gatewayContract**: American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Adyen receives the settlement, and handles disputes and payouts. + /// Merchant ID (MID) number. Format: 10 numeric characters. You must provide this field when you request `gatewayContract` or `paymentDesignatorContract` service levels. + /// Indicates whether the Amex Merchant ID is reused from a previously setup Amex payment method. This is only applicable for `gatewayContract` and `paymentDesignatorContract` service levels. The default value is **false**. (default to false) + [JsonConstructor] + public AmexInfo(ServiceLevelEnum serviceLevel, Option midNumber = default, Option reuseMidNumber = default) + { + ServiceLevel = serviceLevel; + _MidNumberOption = midNumber; + _ReuseMidNumberOption = reuseMidNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmexInfo() + { + } + + partial void OnCreated(); + + /// + /// Specifies the service level (settlement type) of this payment method. Possible values: * **noContract**: Adyen holds the contract with American Express. * **gatewayContract**: American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Adyen receives the settlement, and handles disputes and payouts. + /// + /// Specifies the service level (settlement type) of this payment method. Possible values: * **noContract**: Adyen holds the contract with American Express. * **gatewayContract**: American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Adyen receives the settlement, and handles disputes and payouts. + [JsonConverter(typeof(ServiceLevelEnumJsonConverter))] + public class ServiceLevelEnum : IEnum + { + /// + /// Returns the value of the ServiceLevelEnum. + /// + public string? Value { get; set; } + + /// + /// ServiceLevelEnum.NoContract - noContract + /// + public static readonly ServiceLevelEnum NoContract = new("noContract"); + + /// + /// ServiceLevelEnum.GatewayContract - gatewayContract + /// + public static readonly ServiceLevelEnum GatewayContract = new("gatewayContract"); + + /// + /// ServiceLevelEnum.PaymentDesignatorContract - paymentDesignatorContract + /// + public static readonly ServiceLevelEnum PaymentDesignatorContract = new("paymentDesignatorContract"); + + private ServiceLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ServiceLevelEnum?(string? value) => value == null ? null : new ServiceLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ServiceLevelEnum? option) => option?.Value; + + public static bool operator ==(ServiceLevelEnum? left, ServiceLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ServiceLevelEnum? left, ServiceLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ServiceLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ServiceLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "noContract" => ServiceLevelEnum.NoContract, + "gatewayContract" => ServiceLevelEnum.GatewayContract, + "paymentDesignatorContract" => ServiceLevelEnum.PaymentDesignatorContract, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ServiceLevelEnum? value) + { + if (value == null) + return null; + + if (value == ServiceLevelEnum.NoContract) + return "noContract"; + + if (value == ServiceLevelEnum.GatewayContract) + return "gatewayContract"; + + if (value == ServiceLevelEnum.PaymentDesignatorContract) + return "paymentDesignatorContract"; + + return null; + } + + /// + /// JsonConverter for writing ServiceLevelEnum. + /// + public class ServiceLevelEnumJsonConverter : JsonConverter + { + public override ServiceLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ServiceLevelEnum.FromStringOrDefault(value) ?? new ServiceLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ServiceLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ServiceLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// Specifies the service level (settlement type) of this payment method. Possible values: * **noContract**: Adyen holds the contract with American Express. * **gatewayContract**: American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Adyen receives the settlement, and handles disputes and payouts. + /// + /// Specifies the service level (settlement type) of this payment method. Possible values: * **noContract**: Adyen holds the contract with American Express. * **gatewayContract**: American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Adyen receives the settlement, and handles disputes and payouts. + [JsonPropertyName("serviceLevel")] + public ServiceLevelEnum ServiceLevel { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MidNumberOption { get; private set; } + + /// + /// Merchant ID (MID) number. Format: 10 numeric characters. You must provide this field when you request `gatewayContract` or `paymentDesignatorContract` service levels. + /// + /// Merchant ID (MID) number. Format: 10 numeric characters. You must provide this field when you request `gatewayContract` or `paymentDesignatorContract` service levels. + [JsonPropertyName("midNumber")] + public string? MidNumber { get { return this._MidNumberOption; } set { this._MidNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReuseMidNumberOption { get; private set; } + + /// + /// Indicates whether the Amex Merchant ID is reused from a previously setup Amex payment method. This is only applicable for `gatewayContract` and `paymentDesignatorContract` service levels. The default value is **false**. + /// + /// Indicates whether the Amex Merchant ID is reused from a previously setup Amex payment method. This is only applicable for `gatewayContract` and `paymentDesignatorContract` service levels. The default value is **false**. + [JsonPropertyName("reuseMidNumber")] + public bool? ReuseMidNumber { get { return this._ReuseMidNumberOption; } set { this._ReuseMidNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmexInfo {\n"); + sb.Append(" ServiceLevel: ").Append(ServiceLevel).Append("\n"); + sb.Append(" MidNumber: ").Append(MidNumber).Append("\n"); + sb.Append(" ReuseMidNumber: ").Append(ReuseMidNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MidNumber (string) maxLength + if (this.MidNumber != null && this.MidNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for MidNumber, length must be less than 10.", new [] { "MidNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmexInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmexInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option serviceLevel = default; + Option midNumber = default; + Option reuseMidNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "serviceLevel": + string? serviceLevelRawValue = utf8JsonReader.GetString(); + serviceLevel = new Option(AmexInfo.ServiceLevelEnum.FromStringOrDefault(serviceLevelRawValue)); + break; + case "midNumber": + midNumber = new Option(utf8JsonReader.GetString()!); + break; + case "reuseMidNumber": + reuseMidNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!serviceLevel.IsSet) + throw new ArgumentException("Property is required for class AmexInfo.", nameof(serviceLevel)); + + return new AmexInfo(serviceLevel.Value!.Value!, midNumber, reuseMidNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmexInfo amexInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amexInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmexInfo amexInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (amexInfo.ServiceLevel != null) + { + string? serviceLevelRawValue = AmexInfo.ServiceLevelEnum.ToJsonValue(amexInfo.ServiceLevel); + writer.WriteString("serviceLevel", serviceLevelRawValue); + } + + if (amexInfo._MidNumberOption.IsSet) + if (amexInfo.MidNumber != null) + writer.WriteString("midNumber", amexInfo.MidNumber); + + if (amexInfo._ReuseMidNumberOption.IsSet) + writer.WriteBoolean("reuseMidNumber", amexInfo._ReuseMidNumberOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Amount.cs b/Adyen/Management/Models/Amount.cs new file mode 100644 index 000000000..80ea3643f --- /dev/null +++ b/Adyen/Management/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Management/Models/AndroidApp.cs b/Adyen/Management/Models/AndroidApp.cs new file mode 100644 index 000000000..1e464f324 --- /dev/null +++ b/Adyen/Management/Models/AndroidApp.cs @@ -0,0 +1,501 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AndroidApp. + /// + public partial class AndroidApp : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the app. + /// The status of the app. Possible values: * `processing`: the app is being signed and converted to a format that the terminal can handle. * `error`: something went wrong. Check that the app matches the [requirements](https://docs.adyen.com/point-of-sale/android-terminals/app-requirements). * `invalid`: there is something wrong with the APK file of the app. * `ready`: the app has been signed and converted. * `archived`: the app is no longer available. + /// The description that was provided when uploading the app. The description is not shown on the terminal. + /// The error code of the Android app with the `status` of either **error** or **invalid**. + /// The list of errors of the Android app. + /// The app name that is shown on the terminal. + /// The package name that uniquely identifies the Android app. + /// The version number of the app. + /// The app version number that is shown on the terminal. + [JsonConstructor] + public AndroidApp(string id, StatusEnum status, Option description = default, Option errorCode = default, Option?> errors = default, Option label = default, Option packageName = default, Option versionCode = default, Option versionName = default) + { + Id = id; + Status = status; + _DescriptionOption = description; + _ErrorCodeOption = errorCode; + _ErrorsOption = errors; + _LabelOption = label; + _PackageNameOption = packageName; + _VersionCodeOption = versionCode; + _VersionNameOption = versionName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidApp() + { + } + + partial void OnCreated(); + + /// + /// The status of the app. Possible values: * `processing`: the app is being signed and converted to a format that the terminal can handle. * `error`: something went wrong. Check that the app matches the [requirements](https://docs.adyen.com/point-of-sale/android-terminals/app-requirements). * `invalid`: there is something wrong with the APK file of the app. * `ready`: the app has been signed and converted. * `archived`: the app is no longer available. + /// + /// The status of the app. Possible values: * `processing`: the app is being signed and converted to a format that the terminal can handle. * `error`: something went wrong. Check that the app matches the [requirements](https://docs.adyen.com/point-of-sale/android-terminals/app-requirements). * `invalid`: there is something wrong with the APK file of the app. * `ready`: the app has been signed and converted. * `archived`: the app is no longer available. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Archived - archived + /// + public static readonly StatusEnum Archived = new("archived"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Invalid - invalid + /// + public static readonly StatusEnum Invalid = new("invalid"); + + /// + /// StatusEnum.Processing - processing + /// + public static readonly StatusEnum Processing = new("processing"); + + /// + /// StatusEnum.Ready - ready + /// + public static readonly StatusEnum Ready = new("ready"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "archived" => StatusEnum.Archived, + "error" => StatusEnum.Error, + "invalid" => StatusEnum.Invalid, + "processing" => StatusEnum.Processing, + "ready" => StatusEnum.Ready, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Archived) + return "archived"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Invalid) + return "invalid"; + + if (value == StatusEnum.Processing) + return "processing"; + + if (value == StatusEnum.Ready) + return "ready"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the app. Possible values: * `processing`: the app is being signed and converted to a format that the terminal can handle. * `error`: something went wrong. Check that the app matches the [requirements](https://docs.adyen.com/point-of-sale/android-terminals/app-requirements). * `invalid`: there is something wrong with the APK file of the app. * `ready`: the app has been signed and converted. * `archived`: the app is no longer available. + /// + /// The status of the app. Possible values: * `processing`: the app is being signed and converted to a format that the terminal can handle. * `error`: something went wrong. Check that the app matches the [requirements](https://docs.adyen.com/point-of-sale/android-terminals/app-requirements). * `invalid`: there is something wrong with the APK file of the app. * `ready`: the app has been signed and converted. * `archived`: the app is no longer available. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The unique identifier of the app. + /// + /// The unique identifier of the app. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description that was provided when uploading the app. The description is not shown on the terminal. + /// + /// The description that was provided when uploading the app. The description is not shown on the terminal. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code of the Android app with the `status` of either **error** or **invalid**. + /// + /// The error code of the Android app with the `status` of either **error** or **invalid**. + [JsonPropertyName("errorCode")] + [Obsolete("Deprecated since Management API v3. Use `errors` instead.")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ErrorsOption { get; private set; } + + /// + /// The list of errors of the Android app. + /// + /// The list of errors of the Android app. + [JsonPropertyName("errors")] + public List? Errors { get { return this._ErrorsOption; } set { this._ErrorsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LabelOption { get; private set; } + + /// + /// The app name that is shown on the terminal. + /// + /// The app name that is shown on the terminal. + [JsonPropertyName("label")] + public string? Label { get { return this._LabelOption; } set { this._LabelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PackageNameOption { get; private set; } + + /// + /// The package name that uniquely identifies the Android app. + /// + /// The package name that uniquely identifies the Android app. + [JsonPropertyName("packageName")] + public string? PackageName { get { return this._PackageNameOption; } set { this._PackageNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionCodeOption { get; private set; } + + /// + /// The version number of the app. + /// + /// The version number of the app. + [JsonPropertyName("versionCode")] + public int? VersionCode { get { return this._VersionCodeOption; } set { this._VersionCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionNameOption { get; private set; } + + /// + /// The app version number that is shown on the terminal. + /// + /// The app version number that is shown on the terminal. + [JsonPropertyName("versionName")] + public string? VersionName { get { return this._VersionNameOption; } set { this._VersionNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidApp {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Errors: ").Append(Errors).Append("\n"); + sb.Append(" Label: ").Append(Label).Append("\n"); + sb.Append(" PackageName: ").Append(PackageName).Append("\n"); + sb.Append(" VersionCode: ").Append(VersionCode).Append("\n"); + sb.Append(" VersionName: ").Append(VersionName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidAppJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidApp Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option status = default; + Option description = default; + Option errorCode = default; + Option?> errors = default; + Option label = default; + Option packageName = default; + Option versionCode = default; + Option versionName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(AndroidApp.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errors": + errors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "label": + label = new Option(utf8JsonReader.GetString()!); + break; + case "packageName": + packageName = new Option(utf8JsonReader.GetString()!); + break; + case "versionCode": + versionCode = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "versionName": + versionName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class AndroidApp.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AndroidApp.", nameof(status)); + + return new AndroidApp(id.Value!, status.Value!.Value!, description, errorCode, errors, label, packageName, versionCode, versionName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidApp androidApp, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidApp, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidApp androidApp, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidApp.Id != null) + writer.WriteString("id", androidApp.Id); + + if (androidApp.Status != null) + { + string? statusRawValue = AndroidApp.StatusEnum.ToJsonValue(androidApp.Status); + writer.WriteString("status", statusRawValue); + } + + if (androidApp._DescriptionOption.IsSet) + if (androidApp.Description != null) + writer.WriteString("description", androidApp.Description); + + if (androidApp._ErrorCodeOption.IsSet) + if (androidApp.ErrorCode != null) + writer.WriteString("errorCode", androidApp.ErrorCode); + + if (androidApp._ErrorsOption.IsSet) + { + writer.WritePropertyName("errors"); + JsonSerializer.Serialize(writer, androidApp.Errors, jsonSerializerOptions); + } + if (androidApp._LabelOption.IsSet) + if (androidApp.Label != null) + writer.WriteString("label", androidApp.Label); + + if (androidApp._PackageNameOption.IsSet) + if (androidApp.PackageName != null) + writer.WriteString("packageName", androidApp.PackageName); + + if (androidApp._VersionCodeOption.IsSet) + writer.WriteNumber("versionCode", androidApp._VersionCodeOption.Value!.Value); + + if (androidApp._VersionNameOption.IsSet) + if (androidApp.VersionName != null) + writer.WriteString("versionName", androidApp.VersionName); + } + } +} diff --git a/Adyen/Management/Models/AndroidAppError.cs b/Adyen/Management/Models/AndroidAppError.cs new file mode 100644 index 000000000..2663be02b --- /dev/null +++ b/Adyen/Management/Models/AndroidAppError.cs @@ -0,0 +1,204 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AndroidAppError. + /// + public partial class AndroidAppError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code of the Android app with the `status` of either **error** or **invalid**. + /// The list of payment terminal models to which the returned `errorCode` applies. + [JsonConstructor] + public AndroidAppError(Option errorCode = default, Option?> terminalModels = default) + { + _ErrorCodeOption = errorCode; + _TerminalModelsOption = terminalModels; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidAppError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code of the Android app with the `status` of either **error** or **invalid**. + /// + /// The error code of the Android app with the `status` of either **error** or **invalid**. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TerminalModelsOption { get; private set; } + + /// + /// The list of payment terminal models to which the returned `errorCode` applies. + /// + /// The list of payment terminal models to which the returned `errorCode` applies. + [JsonPropertyName("terminalModels")] + public List? TerminalModels { get { return this._TerminalModelsOption; } set { this._TerminalModelsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidAppError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" TerminalModels: ").Append(TerminalModels).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidAppErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidAppError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option?> terminalModels = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "terminalModels": + terminalModels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AndroidAppError(errorCode, terminalModels); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidAppError androidAppError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidAppError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidAppError androidAppError, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidAppError._ErrorCodeOption.IsSet) + if (androidAppError.ErrorCode != null) + writer.WriteString("errorCode", androidAppError.ErrorCode); + + if (androidAppError._TerminalModelsOption.IsSet) + { + writer.WritePropertyName("terminalModels"); + JsonSerializer.Serialize(writer, androidAppError.TerminalModels, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/AndroidAppsResponse.cs b/Adyen/Management/Models/AndroidAppsResponse.cs new file mode 100644 index 000000000..6da9cba86 --- /dev/null +++ b/Adyen/Management/Models/AndroidAppsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AndroidAppsResponse. + /// + public partial class AndroidAppsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Apps uploaded for Android payment terminals. + [JsonConstructor] + public AndroidAppsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidAppsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Apps uploaded for Android payment terminals. + /// + /// Apps uploaded for Android payment terminals. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidAppsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidAppsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidAppsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AndroidAppsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidAppsResponse androidAppsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidAppsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidAppsResponse androidAppsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidAppsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, androidAppsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/AndroidCertificate.cs b/Adyen/Management/Models/AndroidCertificate.cs new file mode 100644 index 000000000..63b9c86f0 --- /dev/null +++ b/Adyen/Management/Models/AndroidCertificate.cs @@ -0,0 +1,329 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AndroidCertificate. + /// + public partial class AndroidCertificate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the certificate. + /// The description that was provided when uploading the certificate. + /// The file format of the certificate, as indicated by the file extension. For example, **.cert** or **.pem**. + /// The file name of the certificate. For example, **mycert**. + /// The date when the certificate stops to be valid. + /// The date when the certificate starts to be valid. + /// The status of the certificate. + [JsonConstructor] + public AndroidCertificate(string id, Option description = default, Option extension = default, Option name = default, Option notAfter = default, Option notBefore = default, Option status = default) + { + Id = id; + _DescriptionOption = description; + _ExtensionOption = extension; + _NameOption = name; + _NotAfterOption = notAfter; + _NotBeforeOption = notBefore; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidCertificate() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the certificate. + /// + /// The unique identifier of the certificate. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description that was provided when uploading the certificate. + /// + /// The description that was provided when uploading the certificate. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtensionOption { get; private set; } + + /// + /// The file format of the certificate, as indicated by the file extension. For example, **.cert** or **.pem**. + /// + /// The file format of the certificate, as indicated by the file extension. For example, **.cert** or **.pem**. + [JsonPropertyName("extension")] + public string? Extension { get { return this._ExtensionOption; } set { this._ExtensionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The file name of the certificate. For example, **mycert**. + /// + /// The file name of the certificate. For example, **mycert**. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotAfterOption { get; private set; } + + /// + /// The date when the certificate stops to be valid. + /// + /// The date when the certificate stops to be valid. + [JsonPropertyName("notAfter")] + public DateTimeOffset? NotAfter { get { return this._NotAfterOption; } set { this._NotAfterOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotBeforeOption { get; private set; } + + /// + /// The date when the certificate starts to be valid. + /// + /// The date when the certificate starts to be valid. + [JsonPropertyName("notBefore")] + public DateTimeOffset? NotBefore { get { return this._NotBeforeOption; } set { this._NotBeforeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the certificate. + /// + /// The status of the certificate. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidCertificate {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Extension: ").Append(Extension).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" NotAfter: ").Append(NotAfter).Append("\n"); + sb.Append(" NotBefore: ").Append(NotBefore).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidCertificateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize NotAfter. + /// + public static string NotAfterFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotBefore. + /// + public static string NotBeforeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidCertificate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option description = default; + Option extension = default; + Option name = default; + Option notAfter = default; + Option notBefore = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "extension": + extension = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "notAfter": + notAfter = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notBefore": + notBefore = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class AndroidCertificate.", nameof(id)); + + return new AndroidCertificate(id.Value!, description, extension, name, notAfter, notBefore, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidCertificate androidCertificate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidCertificate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidCertificate androidCertificate, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidCertificate.Id != null) + writer.WriteString("id", androidCertificate.Id); + + if (androidCertificate._DescriptionOption.IsSet) + if (androidCertificate.Description != null) + writer.WriteString("description", androidCertificate.Description); + + if (androidCertificate._ExtensionOption.IsSet) + if (androidCertificate.Extension != null) + writer.WriteString("extension", androidCertificate.Extension); + + if (androidCertificate._NameOption.IsSet) + if (androidCertificate.Name != null) + writer.WriteString("name", androidCertificate.Name); + + if (androidCertificate._NotAfterOption.IsSet) + writer.WriteString("notAfter", androidCertificate._NotAfterOption.Value!.Value.ToString(NotAfterFormat)); + + if (androidCertificate._NotBeforeOption.IsSet) + writer.WriteString("notBefore", androidCertificate._NotBeforeOption.Value!.Value.ToString(NotBeforeFormat)); + + if (androidCertificate._StatusOption.IsSet) + if (androidCertificate.Status != null) + writer.WriteString("status", androidCertificate.Status); + } + } +} diff --git a/Adyen/Management/Models/AndroidCertificatesResponse.cs b/Adyen/Management/Models/AndroidCertificatesResponse.cs new file mode 100644 index 000000000..f964a76b6 --- /dev/null +++ b/Adyen/Management/Models/AndroidCertificatesResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// AndroidCertificatesResponse. + /// + public partial class AndroidCertificatesResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Uploaded Android certificates for Android payment terminals. + [JsonConstructor] + public AndroidCertificatesResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AndroidCertificatesResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Uploaded Android certificates for Android payment terminals. + /// + /// Uploaded Android certificates for Android payment terminals. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AndroidCertificatesResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AndroidCertificatesResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AndroidCertificatesResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AndroidCertificatesResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AndroidCertificatesResponse androidCertificatesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, androidCertificatesResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AndroidCertificatesResponse androidCertificatesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (androidCertificatesResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, androidCertificatesResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ApiCredential.cs b/Adyen/Management/Models/ApiCredential.cs new file mode 100644 index 000000000..d7ebfe175 --- /dev/null +++ b/Adyen/Management/Models/ApiCredential.cs @@ -0,0 +1,350 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ApiCredential. + /// + public partial class ApiCredential : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// Unique identifier of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// links + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// Description of the API credential. + [JsonConstructor] + public ApiCredential(bool active, List allowedIpAddresses, string clientKey, string id, List roles, string username, Option links = default, Option?> allowedOrigins = default, Option description = default) + { + Active = active; + AllowedIpAddresses = allowedIpAddresses; + ClientKey = clientKey; + Id = id; + Roles = roles; + Username = username; + _LinksOption = links; + _AllowedOriginsOption = allowedOrigins; + _DescriptionOption = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApiCredential() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + [JsonPropertyName("allowedIpAddresses")] + public List AllowedIpAddresses { get; set; } + + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Unique identifier of the API credential. + /// + /// Unique identifier of the API credential. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public ApiCredentialLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApiCredential {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedIpAddresses: ").Append(AllowedIpAddresses).Append("\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 50) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 50.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApiCredentialJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApiCredential Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedIpAddresses = default; + Option clientKey = default; + Option id = default; + Option?> roles = default; + Option username = default; + Option links = default; + Option?> allowedOrigins = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedIpAddresses": + allowedIpAddresses = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(active)); + + if (!allowedIpAddresses.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(allowedIpAddresses)); + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(clientKey)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(roles)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class ApiCredential.", nameof(username)); + + return new ApiCredential(active.Value!.Value!, allowedIpAddresses.Value!, clientKey.Value!, id.Value!, roles.Value!, username.Value!, links, allowedOrigins, description); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiCredential apiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, apiCredential, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApiCredential apiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", apiCredential.Active); + + writer.WritePropertyName("allowedIpAddresses"); + JsonSerializer.Serialize(writer, apiCredential.AllowedIpAddresses, jsonSerializerOptions); + if (apiCredential.ClientKey != null) + writer.WriteString("clientKey", apiCredential.ClientKey); + + if (apiCredential.Id != null) + writer.WriteString("id", apiCredential.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, apiCredential.Roles, jsonSerializerOptions); + if (apiCredential.Username != null) + writer.WriteString("username", apiCredential.Username); + + if (apiCredential._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, apiCredential.Links, jsonSerializerOptions); + } + if (apiCredential._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, apiCredential.AllowedOrigins, jsonSerializerOptions); + } + if (apiCredential._DescriptionOption.IsSet) + if (apiCredential.Description != null) + writer.WriteString("description", apiCredential.Description); + } + } +} diff --git a/Adyen/Management/Models/ApiCredentialLinks.cs b/Adyen/Management/Models/ApiCredentialLinks.cs new file mode 100644 index 000000000..7c3e45ea2 --- /dev/null +++ b/Adyen/Management/Models/ApiCredentialLinks.cs @@ -0,0 +1,295 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ApiCredentialLinks. + /// + public partial class ApiCredentialLinks : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// self + /// allowedOrigins + /// company + /// generateApiKey + /// generateClientKey + /// merchant + [JsonConstructor] + public ApiCredentialLinks(LinksElement self, Option allowedOrigins = default, Option company = default, Option generateApiKey = default, Option generateClientKey = default, Option merchant = default) + { + Self = self; + _AllowedOriginsOption = allowedOrigins; + _CompanyOption = company; + _GenerateApiKeyOption = generateApiKey; + _GenerateClientKeyOption = generateClientKey; + _MerchantOption = merchant; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApiCredentialLinks() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOriginsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("allowedOrigins")] + public LinksElement? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("company")] + public LinksElement? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GenerateApiKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("generateApiKey")] + public LinksElement? GenerateApiKey { get { return this._GenerateApiKeyOption; } set { this._GenerateApiKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GenerateClientKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("generateClientKey")] + public LinksElement? GenerateClientKey { get { return this._GenerateClientKeyOption; } set { this._GenerateClientKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public LinksElement? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApiCredentialLinks {\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" GenerateApiKey: ").Append(GenerateApiKey).Append("\n"); + sb.Append(" GenerateClientKey: ").Append(GenerateClientKey).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApiCredentialLinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApiCredentialLinks Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option self = default; + Option allowedOrigins = default; + Option company = default; + Option generateApiKey = default; + Option generateClientKey = default; + Option merchant = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "company": + company = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "generateApiKey": + generateApiKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "generateClientKey": + generateClientKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!self.IsSet) + throw new ArgumentException("Property is required for class ApiCredentialLinks.", nameof(self)); + + return new ApiCredentialLinks(self.Value!, allowedOrigins, company, generateApiKey, generateClientKey, merchant); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApiCredentialLinks apiCredentialLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, apiCredentialLinks, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApiCredentialLinks apiCredentialLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, apiCredentialLinks.Self, jsonSerializerOptions); + if (apiCredentialLinks._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, apiCredentialLinks.AllowedOrigins, jsonSerializerOptions); + } + if (apiCredentialLinks._CompanyOption.IsSet) + { + writer.WritePropertyName("company"); + JsonSerializer.Serialize(writer, apiCredentialLinks.Company, jsonSerializerOptions); + } + if (apiCredentialLinks._GenerateApiKeyOption.IsSet) + { + writer.WritePropertyName("generateApiKey"); + JsonSerializer.Serialize(writer, apiCredentialLinks.GenerateApiKey, jsonSerializerOptions); + } + if (apiCredentialLinks._GenerateClientKeyOption.IsSet) + { + writer.WritePropertyName("generateClientKey"); + JsonSerializer.Serialize(writer, apiCredentialLinks.GenerateClientKey, jsonSerializerOptions); + } + if (apiCredentialLinks._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, apiCredentialLinks.Merchant, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ApplePayInfo.cs b/Adyen/Management/Models/ApplePayInfo.cs new file mode 100644 index 000000000..45fa851e0 --- /dev/null +++ b/Adyen/Management/Models/ApplePayInfo.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ApplePayInfo. + /// + public partial class ApplePayInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of merchant domains. Maximum: 99 domains per request. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/web-drop-in?tab=adyen-certificate-live_1#going-live). + [JsonConstructor] + public ApplePayInfo(List domains) + { + Domains = domains; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplePayInfo() + { + } + + partial void OnCreated(); + + /// + /// The list of merchant domains. Maximum: 99 domains per request. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/web-drop-in?tab=adyen-certificate-live_1#going-live). + /// + /// The list of merchant domains. Maximum: 99 domains per request. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/web-drop-in?tab=adyen-certificate-live_1#going-live). + [JsonPropertyName("domains")] + public List Domains { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplePayInfo {\n"); + sb.Append(" Domains: ").Append(Domains).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplePayInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplePayInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> domains = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domains": + domains = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!domains.IsSet) + throw new ArgumentException("Property is required for class ApplePayInfo.", nameof(domains)); + + return new ApplePayInfo(domains.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplePayInfo applePayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applePayInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplePayInfo applePayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("domains"); + JsonSerializer.Serialize(writer, applePayInfo.Domains, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Management/Models/BcmcInfo.cs b/Adyen/Management/Models/BcmcInfo.cs new file mode 100644 index 000000000..071e5e565 --- /dev/null +++ b/Adyen/Management/Models/BcmcInfo.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// BcmcInfo. + /// + public partial class BcmcInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if [Bancontact mobile](https://docs.adyen.com/payment-methods/bancontact/bancontact-mobile) is enabled. + [JsonConstructor] + public BcmcInfo(Option enableBcmcMobile = default) + { + _EnableBcmcMobileOption = enableBcmcMobile; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BcmcInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableBcmcMobileOption { get; private set; } + + /// + /// Indicates if [Bancontact mobile](https://docs.adyen.com/payment-methods/bancontact/bancontact-mobile) is enabled. + /// + /// Indicates if [Bancontact mobile](https://docs.adyen.com/payment-methods/bancontact/bancontact-mobile) is enabled. + [JsonPropertyName("enableBcmcMobile")] + public bool? EnableBcmcMobile { get { return this._EnableBcmcMobileOption; } set { this._EnableBcmcMobileOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BcmcInfo {\n"); + sb.Append(" EnableBcmcMobile: ").Append(EnableBcmcMobile).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BcmcInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BcmcInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enableBcmcMobile = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enableBcmcMobile": + enableBcmcMobile = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new BcmcInfo(enableBcmcMobile); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BcmcInfo bcmcInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bcmcInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BcmcInfo bcmcInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (bcmcInfo._EnableBcmcMobileOption.IsSet) + writer.WriteBoolean("enableBcmcMobile", bcmcInfo._EnableBcmcMobileOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/BillingEntitiesResponse.cs b/Adyen/Management/Models/BillingEntitiesResponse.cs new file mode 100644 index 000000000..1b3964ac2 --- /dev/null +++ b/Adyen/Management/Models/BillingEntitiesResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// BillingEntitiesResponse. + /// + public partial class BillingEntitiesResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of legal entities that can be used for the billing of orders. + [JsonConstructor] + public BillingEntitiesResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BillingEntitiesResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List of legal entities that can be used for the billing of orders. + /// + /// List of legal entities that can be used for the billing of orders. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BillingEntitiesResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BillingEntitiesResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BillingEntitiesResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new BillingEntitiesResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BillingEntitiesResponse billingEntitiesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, billingEntitiesResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BillingEntitiesResponse billingEntitiesResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (billingEntitiesResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, billingEntitiesResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/BillingEntity.cs b/Adyen/Management/Models/BillingEntity.cs new file mode 100644 index 000000000..8323f61ef --- /dev/null +++ b/Adyen/Management/Models/BillingEntity.cs @@ -0,0 +1,277 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// BillingEntity. + /// + public partial class BillingEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The email address of the billing entity. + /// The unique identifier of the billing entity, for use as `billingEntityId` when creating an order. + /// The unique name of the billing entity. + /// The tax number of the billing entity. + [JsonConstructor] + public BillingEntity(Option address = default, Option email = default, Option id = default, Option name = default, Option taxId = default) + { + _AddressOption = address; + _EmailOption = email; + _IdOption = id; + _NameOption = name; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BillingEntity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public Address? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the billing entity. + /// + /// The email address of the billing entity. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the billing entity, for use as `billingEntityId` when creating an order. + /// + /// The unique identifier of the billing entity, for use as `billingEntityId` when creating an order. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The unique name of the billing entity. + /// + /// The unique name of the billing entity. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The tax number of the billing entity. + /// + /// The tax number of the billing entity. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BillingEntity {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BillingEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BillingEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option email = default; + Option id = default; + Option name = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BillingEntity(address, email, id, name, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BillingEntity billingEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, billingEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BillingEntity billingEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (billingEntity._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, billingEntity.Address, jsonSerializerOptions); + } + if (billingEntity._EmailOption.IsSet) + if (billingEntity.Email != null) + writer.WriteString("email", billingEntity.Email); + + if (billingEntity._IdOption.IsSet) + if (billingEntity.Id != null) + writer.WriteString("id", billingEntity.Id); + + if (billingEntity._NameOption.IsSet) + if (billingEntity.Name != null) + writer.WriteString("name", billingEntity.Name); + + if (billingEntity._TaxIdOption.IsSet) + if (billingEntity.TaxId != null) + writer.WriteString("taxId", billingEntity.TaxId); + } + } +} diff --git a/Adyen/Management/Models/CardholderReceipt.cs b/Adyen/Management/Models/CardholderReceipt.cs new file mode 100644 index 000000000..f3878cd08 --- /dev/null +++ b/Adyen/Management/Models/CardholderReceipt.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CardholderReceipt. + /// + public partial class CardholderReceipt : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A custom header to show on the shopper receipt for an authorised transaction. Allows one or two comma-separated header lines, and blank lines. For example, `header,header,filler` + [JsonConstructor] + public CardholderReceipt(Option headerForAuthorizedReceipt = default) + { + _HeaderForAuthorizedReceiptOption = headerForAuthorizedReceipt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardholderReceipt() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HeaderForAuthorizedReceiptOption { get; private set; } + + /// + /// A custom header to show on the shopper receipt for an authorised transaction. Allows one or two comma-separated header lines, and blank lines. For example, `header,header,filler` + /// + /// A custom header to show on the shopper receipt for an authorised transaction. Allows one or two comma-separated header lines, and blank lines. For example, `header,header,filler` + [JsonPropertyName("headerForAuthorizedReceipt")] + public string? HeaderForAuthorizedReceipt { get { return this._HeaderForAuthorizedReceiptOption; } set { this._HeaderForAuthorizedReceiptOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardholderReceipt {\n"); + sb.Append(" HeaderForAuthorizedReceipt: ").Append(HeaderForAuthorizedReceipt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardholderReceiptJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardholderReceipt Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option headerForAuthorizedReceipt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "headerForAuthorizedReceipt": + headerForAuthorizedReceipt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardholderReceipt(headerForAuthorizedReceipt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardholderReceipt cardholderReceipt, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardholderReceipt, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardholderReceipt cardholderReceipt, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardholderReceipt._HeaderForAuthorizedReceiptOption.IsSet) + if (cardholderReceipt.HeaderForAuthorizedReceipt != null) + writer.WriteString("headerForAuthorizedReceipt", cardholderReceipt.HeaderForAuthorizedReceipt); + } + } +} diff --git a/Adyen/Management/Models/CartesBancairesInfo.cs b/Adyen/Management/Models/CartesBancairesInfo.cs new file mode 100644 index 000000000..10ecccc58 --- /dev/null +++ b/Adyen/Management/Models/CartesBancairesInfo.cs @@ -0,0 +1,197 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CartesBancairesInfo. + /// + public partial class CartesBancairesInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Cartes Bancaires SIRET. Format: 14 digits. + /// transactionDescription + [JsonConstructor] + public CartesBancairesInfo(string siret, Option transactionDescription = default) + { + Siret = siret; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CartesBancairesInfo() + { + } + + partial void OnCreated(); + + /// + /// Cartes Bancaires SIRET. Format: 14 digits. + /// + /// Cartes Bancaires SIRET. Format: 14 digits. + [JsonPropertyName("siret")] + public string Siret { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CartesBancairesInfo {\n"); + sb.Append(" Siret: ").Append(Siret).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CartesBancairesInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CartesBancairesInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option siret = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "siret": + siret = new Option(utf8JsonReader.GetString()!); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!siret.IsSet) + throw new ArgumentException("Property is required for class CartesBancairesInfo.", nameof(siret)); + + return new CartesBancairesInfo(siret.Value!, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CartesBancairesInfo cartesBancairesInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cartesBancairesInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CartesBancairesInfo cartesBancairesInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (cartesBancairesInfo.Siret != null) + writer.WriteString("siret", cartesBancairesInfo.Siret); + + if (cartesBancairesInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, cartesBancairesInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ClearpayInfo.cs b/Adyen/Management/Models/ClearpayInfo.cs new file mode 100644 index 000000000..cb438b623 --- /dev/null +++ b/Adyen/Management/Models/ClearpayInfo.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ClearpayInfo. + /// + public partial class ClearpayInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Support Url + [JsonConstructor] + public ClearpayInfo(string supportUrl) + { + SupportUrl = supportUrl; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ClearpayInfo() + { + } + + partial void OnCreated(); + + /// + /// Support Url + /// + /// Support Url + [JsonPropertyName("supportUrl")] + public string SupportUrl { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ClearpayInfo {\n"); + sb.Append(" SupportUrl: ").Append(SupportUrl).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ClearpayInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ClearpayInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option supportUrl = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "supportUrl": + supportUrl = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!supportUrl.IsSet) + throw new ArgumentException("Property is required for class ClearpayInfo.", nameof(supportUrl)); + + return new ClearpayInfo(supportUrl.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ClearpayInfo clearpayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, clearpayInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ClearpayInfo clearpayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (clearpayInfo.SupportUrl != null) + writer.WriteString("supportUrl", clearpayInfo.SupportUrl); + } + } +} diff --git a/Adyen/Management/Models/Commission.cs b/Adyen/Management/Models/Commission.cs new file mode 100644 index 000000000..74443b489 --- /dev/null +++ b/Adyen/Management/Models/Commission.cs @@ -0,0 +1,200 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Commission. + /// + public partial class Commission : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A fixed commission fee, in minor units. + /// A variable commission fee, in basis points. + [JsonConstructor] + public Commission(Option fixedAmount = default, Option variablePercentage = default) + { + _FixedAmountOption = fixedAmount; + _VariablePercentageOption = variablePercentage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Commission() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FixedAmountOption { get; private set; } + + /// + /// A fixed commission fee, in minor units. + /// + /// A fixed commission fee, in minor units. + [JsonPropertyName("fixedAmount")] + public long? FixedAmount { get { return this._FixedAmountOption; } set { this._FixedAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VariablePercentageOption { get; private set; } + + /// + /// A variable commission fee, in basis points. + /// + /// A variable commission fee, in basis points. + [JsonPropertyName("variablePercentage")] + public long? VariablePercentage { get { return this._VariablePercentageOption; } set { this._VariablePercentageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Commission {\n"); + sb.Append(" FixedAmount: ").Append(FixedAmount).Append("\n"); + sb.Append(" VariablePercentage: ").Append(VariablePercentage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CommissionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Commission Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option fixedAmount = default; + Option variablePercentage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "fixedAmount": + fixedAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "variablePercentage": + variablePercentage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new Commission(fixedAmount, variablePercentage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Commission commission, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, commission, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Commission commission, JsonSerializerOptions jsonSerializerOptions) + { + + if (commission._FixedAmountOption.IsSet) + writer.WriteNumber("fixedAmount", commission._FixedAmountOption.Value!.Value); + + if (commission._VariablePercentageOption.IsSet) + writer.WriteNumber("variablePercentage", commission._VariablePercentageOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Company.cs b/Adyen/Management/Models/Company.cs new file mode 100644 index 000000000..9c1ab9e8e --- /dev/null +++ b/Adyen/Management/Models/Company.cs @@ -0,0 +1,328 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Company. + /// + public partial class Company : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + /// Your description for the company account, maximum 300 characters + /// The unique identifier of the company account. + /// The legal or trading name of the company. + /// Your reference to the account + /// The status of the company account. Possible values: * **Active**: Users can log in. Processing and payout capabilities depend on the status of the merchant account. * **Inactive**: Users can log in. Payment processing and payouts are disabled. * **Closed**: The company account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonConstructor] + public Company(Option links = default, Option?> dataCenters = default, Option description = default, Option id = default, Option name = default, Option reference = default, Option status = default) + { + _LinksOption = links; + _DataCentersOption = dataCenters; + _DescriptionOption = description; + _IdOption = id; + _NameOption = name; + _ReferenceOption = reference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Company() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public CompanyLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataCentersOption { get; private set; } + + /// + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + /// + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + [JsonPropertyName("dataCenters")] + public List? DataCenters { get { return this._DataCentersOption; } set { this._DataCentersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the company account, maximum 300 characters + /// + /// Your description for the company account, maximum 300 characters + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The legal or trading name of the company. + /// + /// The legal or trading name of the company. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference to the account + /// + /// Your reference to the account + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the company account. Possible values: * **Active**: Users can log in. Processing and payout capabilities depend on the status of the merchant account. * **Inactive**: Users can log in. Payment processing and payouts are disabled. * **Closed**: The company account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// + /// The status of the company account. Possible values: * **Active**: Users can log in. Processing and payout capabilities depend on the status of the merchant account. * **Inactive**: Users can log in. Payment processing and payouts are disabled. * **Closed**: The company account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Company {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" DataCenters: ").Append(DataCenters).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CompanyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Company Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option?> dataCenters = default; + Option description = default; + Option id = default; + Option name = default; + Option reference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dataCenters": + dataCenters = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Company(links, dataCenters, description, id, name, reference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Company company, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, company, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Company company, JsonSerializerOptions jsonSerializerOptions) + { + + if (company._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, company.Links, jsonSerializerOptions); + } + if (company._DataCentersOption.IsSet) + { + writer.WritePropertyName("dataCenters"); + JsonSerializer.Serialize(writer, company.DataCenters, jsonSerializerOptions); + } + if (company._DescriptionOption.IsSet) + if (company.Description != null) + writer.WriteString("description", company.Description); + + if (company._IdOption.IsSet) + if (company.Id != null) + writer.WriteString("id", company.Id); + + if (company._NameOption.IsSet) + if (company.Name != null) + writer.WriteString("name", company.Name); + + if (company._ReferenceOption.IsSet) + if (company.Reference != null) + writer.WriteString("reference", company.Reference); + + if (company._StatusOption.IsSet) + if (company.Status != null) + writer.WriteString("status", company.Status); + } + } +} diff --git a/Adyen/Management/Models/CompanyApiCredential.cs b/Adyen/Management/Models/CompanyApiCredential.cs new file mode 100644 index 000000000..7d31cec7e --- /dev/null +++ b/Adyen/Management/Models/CompanyApiCredential.cs @@ -0,0 +1,376 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CompanyApiCredential. + /// + public partial class CompanyApiCredential : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// Unique identifier of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// links + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// List of merchant accounts that the API credential has explicit access to. If the credential has access to a company, this implies access to all merchant accounts and no merchants for that company will be included. + /// Description of the API credential. + [JsonConstructor] + public CompanyApiCredential(bool active, List allowedIpAddresses, string clientKey, string id, List roles, string username, Option links = default, Option?> allowedOrigins = default, Option?> associatedMerchantAccounts = default, Option description = default) + { + Active = active; + AllowedIpAddresses = allowedIpAddresses; + ClientKey = clientKey; + Id = id; + Roles = roles; + Username = username; + _LinksOption = links; + _AllowedOriginsOption = allowedOrigins; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _DescriptionOption = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CompanyApiCredential() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + [JsonPropertyName("allowedIpAddresses")] + public List AllowedIpAddresses { get; set; } + + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Unique identifier of the API credential. + /// + /// Unique identifier of the API credential. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public ApiCredentialLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// List of merchant accounts that the API credential has explicit access to. If the credential has access to a company, this implies access to all merchant accounts and no merchants for that company will be included. + /// + /// List of merchant accounts that the API credential has explicit access to. If the credential has access to a company, this implies access to all merchant accounts and no merchants for that company will be included. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CompanyApiCredential {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedIpAddresses: ").Append(AllowedIpAddresses).Append("\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 50) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 50.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CompanyApiCredentialJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CompanyApiCredential Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedIpAddresses = default; + Option clientKey = default; + Option id = default; + Option?> roles = default; + Option username = default; + Option links = default; + Option?> allowedOrigins = default; + Option?> associatedMerchantAccounts = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedIpAddresses": + allowedIpAddresses = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(active)); + + if (!allowedIpAddresses.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(allowedIpAddresses)); + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(clientKey)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(roles)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CompanyApiCredential.", nameof(username)); + + return new CompanyApiCredential(active.Value!.Value!, allowedIpAddresses.Value!, clientKey.Value!, id.Value!, roles.Value!, username.Value!, links, allowedOrigins, associatedMerchantAccounts, description); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CompanyApiCredential companyApiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, companyApiCredential, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CompanyApiCredential companyApiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", companyApiCredential.Active); + + writer.WritePropertyName("allowedIpAddresses"); + JsonSerializer.Serialize(writer, companyApiCredential.AllowedIpAddresses, jsonSerializerOptions); + if (companyApiCredential.ClientKey != null) + writer.WriteString("clientKey", companyApiCredential.ClientKey); + + if (companyApiCredential.Id != null) + writer.WriteString("id", companyApiCredential.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, companyApiCredential.Roles, jsonSerializerOptions); + if (companyApiCredential.Username != null) + writer.WriteString("username", companyApiCredential.Username); + + if (companyApiCredential._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, companyApiCredential.Links, jsonSerializerOptions); + } + if (companyApiCredential._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, companyApiCredential.AllowedOrigins, jsonSerializerOptions); + } + if (companyApiCredential._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, companyApiCredential.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (companyApiCredential._DescriptionOption.IsSet) + if (companyApiCredential.Description != null) + writer.WriteString("description", companyApiCredential.Description); + } + } +} diff --git a/Adyen/Management/Models/CompanyLinks.cs b/Adyen/Management/Models/CompanyLinks.cs new file mode 100644 index 000000000..ece6b4528 --- /dev/null +++ b/Adyen/Management/Models/CompanyLinks.cs @@ -0,0 +1,245 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CompanyLinks. + /// + public partial class CompanyLinks : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// self + /// apiCredentials + /// users + /// webhooks + [JsonConstructor] + public CompanyLinks(LinksElement self, Option apiCredentials = default, Option users = default, Option webhooks = default) + { + Self = self; + _ApiCredentialsOption = apiCredentials; + _UsersOption = users; + _WebhooksOption = webhooks; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CompanyLinks() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApiCredentialsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("apiCredentials")] + public LinksElement? ApiCredentials { get { return this._ApiCredentialsOption; } set { this._ApiCredentialsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("users")] + public LinksElement? Users { get { return this._UsersOption; } set { this._UsersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebhooksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webhooks")] + public LinksElement? Webhooks { get { return this._WebhooksOption; } set { this._WebhooksOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CompanyLinks {\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append(" ApiCredentials: ").Append(ApiCredentials).Append("\n"); + sb.Append(" Users: ").Append(Users).Append("\n"); + sb.Append(" Webhooks: ").Append(Webhooks).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CompanyLinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CompanyLinks Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option self = default; + Option apiCredentials = default; + Option users = default; + Option webhooks = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "apiCredentials": + apiCredentials = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "users": + users = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webhooks": + webhooks = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!self.IsSet) + throw new ArgumentException("Property is required for class CompanyLinks.", nameof(self)); + + return new CompanyLinks(self.Value!, apiCredentials, users, webhooks); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CompanyLinks companyLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, companyLinks, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CompanyLinks companyLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, companyLinks.Self, jsonSerializerOptions); + if (companyLinks._ApiCredentialsOption.IsSet) + { + writer.WritePropertyName("apiCredentials"); + JsonSerializer.Serialize(writer, companyLinks.ApiCredentials, jsonSerializerOptions); + } + if (companyLinks._UsersOption.IsSet) + { + writer.WritePropertyName("users"); + JsonSerializer.Serialize(writer, companyLinks.Users, jsonSerializerOptions); + } + if (companyLinks._WebhooksOption.IsSet) + { + writer.WritePropertyName("webhooks"); + JsonSerializer.Serialize(writer, companyLinks.Webhooks, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/CompanyUser.cs b/Adyen/Management/Models/CompanyUser.cs new file mode 100644 index 000000000..e9784d510 --- /dev/null +++ b/Adyen/Management/Models/CompanyUser.cs @@ -0,0 +1,415 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CompanyUser. + /// + public partial class CompanyUser : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// The unique identifier of the user. + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// The username for this user. + /// links + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Indicates whether this user is active. + /// Set of apps available to this user + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// name + [JsonConstructor] + public CompanyUser(string email, string id, List roles, string timeZoneCode, string username, Option links = default, Option?> accountGroups = default, Option active = default, Option?> apps = default, Option?> associatedMerchantAccounts = default, Option name = default) + { + Email = email; + Id = id; + Roles = roles; + TimeZoneCode = timeZoneCode; + Username = username; + _LinksOption = links; + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _AppsOption = apps; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CompanyUser() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// The unique identifier of the user. + /// + /// The unique identifier of the user. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string TimeZoneCode { get; set; } + + /// + /// The username for this user. + /// + /// The username for this user. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates whether this user is active. + /// + /// Indicates whether this user is active. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AppsOption { get; private set; } + + /// + /// Set of apps available to this user + /// + /// Set of apps available to this user + [JsonPropertyName("apps")] + public List? Apps { get { return this._AppsOption; } set { this._AppsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CompanyUser {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Apps: ").Append(Apps).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CompanyUserJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CompanyUser Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option id = default; + Option?> roles = default; + Option timeZoneCode = default; + Option username = default; + Option links = default; + Option?> accountGroups = default; + Option active = default; + Option?> apps = default; + Option?> associatedMerchantAccounts = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "apps": + apps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class CompanyUser.", nameof(email)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CompanyUser.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CompanyUser.", nameof(roles)); + + if (!timeZoneCode.IsSet) + throw new ArgumentException("Property is required for class CompanyUser.", nameof(timeZoneCode)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CompanyUser.", nameof(username)); + + return new CompanyUser(email.Value!, id.Value!, roles.Value!, timeZoneCode.Value!, username.Value!, links, accountGroups, active, apps, associatedMerchantAccounts, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CompanyUser companyUser, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, companyUser, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CompanyUser companyUser, JsonSerializerOptions jsonSerializerOptions) + { + + if (companyUser.Email != null) + writer.WriteString("email", companyUser.Email); + + if (companyUser.Id != null) + writer.WriteString("id", companyUser.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, companyUser.Roles, jsonSerializerOptions); + if (companyUser.TimeZoneCode != null) + writer.WriteString("timeZoneCode", companyUser.TimeZoneCode); + + if (companyUser.Username != null) + writer.WriteString("username", companyUser.Username); + + if (companyUser._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, companyUser.Links, jsonSerializerOptions); + } + if (companyUser._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, companyUser.AccountGroups, jsonSerializerOptions); + } + if (companyUser._ActiveOption.IsSet) + writer.WriteBoolean("active", companyUser._ActiveOption.Value!.Value); + + if (companyUser._AppsOption.IsSet) + { + writer.WritePropertyName("apps"); + JsonSerializer.Serialize(writer, companyUser.Apps, jsonSerializerOptions); + } + if (companyUser._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, companyUser.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (companyUser._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, companyUser.Name, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Connectivity.cs b/Adyen/Management/Models/Connectivity.cs new file mode 100644 index 000000000..bcd348d37 --- /dev/null +++ b/Adyen/Management/Models/Connectivity.cs @@ -0,0 +1,309 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Connectivity. + /// + public partial class Connectivity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates the status of the SIM card in the payment terminal. Can be updated and received only at terminal level, and only for models that support cellular connectivity. Possible values: * **ACTIVATED**: the SIM card is activated. Cellular connectivity may still need to be enabled on the terminal itself, in the **Network** settings. * **INVENTORY**: the SIM card is not activated. The terminal can't use cellular connectivity. + /// terminalIPAddressURL + [JsonConstructor] + public Connectivity(Option simcardStatus = default, Option terminalIPAddressURL = default) + { + _SimcardStatusOption = simcardStatus; + _TerminalIPAddressURLOption = terminalIPAddressURL; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Connectivity() + { + } + + partial void OnCreated(); + + /// + /// Indicates the status of the SIM card in the payment terminal. Can be updated and received only at terminal level, and only for models that support cellular connectivity. Possible values: * **ACTIVATED**: the SIM card is activated. Cellular connectivity may still need to be enabled on the terminal itself, in the **Network** settings. * **INVENTORY**: the SIM card is not activated. The terminal can't use cellular connectivity. + /// + /// Indicates the status of the SIM card in the payment terminal. Can be updated and received only at terminal level, and only for models that support cellular connectivity. Possible values: * **ACTIVATED**: the SIM card is activated. Cellular connectivity may still need to be enabled on the terminal itself, in the **Network** settings. * **INVENTORY**: the SIM card is not activated. The terminal can't use cellular connectivity. + [JsonConverter(typeof(SimcardStatusEnumJsonConverter))] + public class SimcardStatusEnum : IEnum + { + /// + /// Returns the value of the SimcardStatusEnum. + /// + public string? Value { get; set; } + + /// + /// SimcardStatusEnum.ACTIVATED - ACTIVATED + /// + public static readonly SimcardStatusEnum ACTIVATED = new("ACTIVATED"); + + /// + /// SimcardStatusEnum.INVENTORY - INVENTORY + /// + public static readonly SimcardStatusEnum INVENTORY = new("INVENTORY"); + + private SimcardStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SimcardStatusEnum?(string? value) => value == null ? null : new SimcardStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SimcardStatusEnum? option) => option?.Value; + + public static bool operator ==(SimcardStatusEnum? left, SimcardStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SimcardStatusEnum? left, SimcardStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SimcardStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SimcardStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "ACTIVATED" => SimcardStatusEnum.ACTIVATED, + "INVENTORY" => SimcardStatusEnum.INVENTORY, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SimcardStatusEnum? value) + { + if (value == null) + return null; + + if (value == SimcardStatusEnum.ACTIVATED) + return "ACTIVATED"; + + if (value == SimcardStatusEnum.INVENTORY) + return "INVENTORY"; + + return null; + } + + /// + /// JsonConverter for writing SimcardStatusEnum. + /// + public class SimcardStatusEnumJsonConverter : JsonConverter + { + public override SimcardStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SimcardStatusEnum.FromStringOrDefault(value) ?? new SimcardStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SimcardStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SimcardStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SimcardStatusOption { get; private set; } + + /// + /// Indicates the status of the SIM card in the payment terminal. Can be updated and received only at terminal level, and only for models that support cellular connectivity. Possible values: * **ACTIVATED**: the SIM card is activated. Cellular connectivity may still need to be enabled on the terminal itself, in the **Network** settings. * **INVENTORY**: the SIM card is not activated. The terminal can't use cellular connectivity. + /// + /// Indicates the status of the SIM card in the payment terminal. Can be updated and received only at terminal level, and only for models that support cellular connectivity. Possible values: * **ACTIVATED**: the SIM card is activated. Cellular connectivity may still need to be enabled on the terminal itself, in the **Network** settings. * **INVENTORY**: the SIM card is not activated. The terminal can't use cellular connectivity. + [JsonPropertyName("simcardStatus")] + public SimcardStatusEnum? SimcardStatus { get { return this._SimcardStatusOption; } set { this._SimcardStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIPAddressURLOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("terminalIPAddressURL")] + public EventUrl? TerminalIPAddressURL { get { return this._TerminalIPAddressURLOption; } set { this._TerminalIPAddressURLOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Connectivity {\n"); + sb.Append(" SimcardStatus: ").Append(SimcardStatus).Append("\n"); + sb.Append(" TerminalIPAddressURL: ").Append(TerminalIPAddressURL).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ConnectivityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Connectivity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option simcardStatus = default; + Option terminalIPAddressURL = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "simcardStatus": + string? simcardStatusRawValue = utf8JsonReader.GetString(); + simcardStatus = new Option(Connectivity.SimcardStatusEnum.FromStringOrDefault(simcardStatusRawValue)); + break; + case "terminalIPAddressURL": + terminalIPAddressURL = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Connectivity(simcardStatus, terminalIPAddressURL); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Connectivity connectivity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, connectivity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Connectivity connectivity, JsonSerializerOptions jsonSerializerOptions) + { + + if (connectivity._SimcardStatusOption.IsSet && connectivity.SimcardStatus != null) + { + string? simcardStatusRawValue = Connectivity.SimcardStatusEnum.ToJsonValue(connectivity._SimcardStatusOption.Value!.Value); + writer.WriteString("simcardStatus", simcardStatusRawValue); + } + + if (connectivity._TerminalIPAddressURLOption.IsSet) + { + writer.WritePropertyName("terminalIPAddressURL"); + JsonSerializer.Serialize(writer, connectivity.TerminalIPAddressURL, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Contact.cs b/Adyen/Management/Models/Contact.cs new file mode 100644 index 000000000..c3c8f1bed --- /dev/null +++ b/Adyen/Management/Models/Contact.cs @@ -0,0 +1,277 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Contact. + /// + public partial class Contact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The individual's email address. + /// The individual's first name. + /// The infix in the individual's name, if any. + /// The individual's last name. + /// The individual's phone number, specified as 10-14 digits with an optional `+` prefix. + [JsonConstructor] + public Contact(Option email = default, Option firstName = default, Option infix = default, Option lastName = default, Option phoneNumber = default) + { + _EmailOption = email; + _FirstNameOption = firstName; + _InfixOption = infix; + _LastNameOption = lastName; + _PhoneNumberOption = phoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Contact() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The individual's email address. + /// + /// The individual's email address. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The individual's first name. + /// + /// The individual's first name. + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InfixOption { get; private set; } + + /// + /// The infix in the individual's name, if any. + /// + /// The infix in the individual's name, if any. + [JsonPropertyName("infix")] + public string? Infix { get { return this._InfixOption; } set { this._InfixOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The individual's last name. + /// + /// The individual's last name. + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// The individual's phone number, specified as 10-14 digits with an optional `+` prefix. + /// + /// The individual's phone number, specified as 10-14 digits with an optional `+` prefix. + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Contact {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" Infix: ").Append(Infix).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ContactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Contact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option firstName = default; + Option infix = default; + Option lastName = default; + Option phoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "infix": + infix = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Contact(email, firstName, infix, lastName, phoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Contact contact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, contact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Contact contact, JsonSerializerOptions jsonSerializerOptions) + { + + if (contact._EmailOption.IsSet) + if (contact.Email != null) + writer.WriteString("email", contact.Email); + + if (contact._FirstNameOption.IsSet) + if (contact.FirstName != null) + writer.WriteString("firstName", contact.FirstName); + + if (contact._InfixOption.IsSet) + if (contact.Infix != null) + writer.WriteString("infix", contact.Infix); + + if (contact._LastNameOption.IsSet) + if (contact.LastName != null) + writer.WriteString("lastName", contact.LastName); + + if (contact._PhoneNumberOption.IsSet) + if (contact.PhoneNumber != null) + writer.WriteString("phoneNumber", contact.PhoneNumber); + } + } +} diff --git a/Adyen/Management/Models/CreateAllowedOriginRequest.cs b/Adyen/Management/Models/CreateAllowedOriginRequest.cs new file mode 100644 index 000000000..31c9cfb43 --- /dev/null +++ b/Adyen/Management/Models/CreateAllowedOriginRequest.cs @@ -0,0 +1,222 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateAllowedOriginRequest. + /// + public partial class CreateAllowedOriginRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Domain of the allowed origin. + /// links + /// Unique identifier of the allowed origin. + [JsonConstructor] + public CreateAllowedOriginRequest(string domain, Option links = default, Option id = default) + { + Domain = domain; + _LinksOption = links; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateAllowedOriginRequest() + { + } + + partial void OnCreated(); + + /// + /// Domain of the allowed origin. + /// + /// Domain of the allowed origin. + /* https://adyen.com */ + [JsonPropertyName("domain")] + public string Domain { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Unique identifier of the allowed origin. + /// + /// Unique identifier of the allowed origin. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateAllowedOriginRequest {\n"); + sb.Append(" Domain: ").Append(Domain).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateAllowedOriginRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateAllowedOriginRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option domain = default; + Option links = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domain": + domain = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!domain.IsSet) + throw new ArgumentException("Property is required for class CreateAllowedOriginRequest.", nameof(domain)); + + return new CreateAllowedOriginRequest(domain.Value!, links, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateAllowedOriginRequest createAllowedOriginRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createAllowedOriginRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateAllowedOriginRequest createAllowedOriginRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createAllowedOriginRequest.Domain != null) + writer.WriteString("domain", createAllowedOriginRequest.Domain); + + if (createAllowedOriginRequest._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, createAllowedOriginRequest.Links, jsonSerializerOptions); + } + if (createAllowedOriginRequest._IdOption.IsSet) + if (createAllowedOriginRequest.Id != null) + writer.WriteString("id", createAllowedOriginRequest.Id); + } + } +} diff --git a/Adyen/Management/Models/CreateApiCredentialResponse.cs b/Adyen/Management/Models/CreateApiCredentialResponse.cs new file mode 100644 index 000000000..4072b1760 --- /dev/null +++ b/Adyen/Management/Models/CreateApiCredentialResponse.cs @@ -0,0 +1,390 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateApiCredentialResponse. + /// + public partial class CreateApiCredentialResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// The API key for the API credential that was created. + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// Unique identifier of the API credential. + /// The password for the API credential that was created. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// links + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// Description of the API credential. + [JsonConstructor] + public CreateApiCredentialResponse(bool active, List allowedIpAddresses, string apiKey, string clientKey, string id, string password, List roles, string username, Option links = default, Option?> allowedOrigins = default, Option description = default) + { + Active = active; + AllowedIpAddresses = allowedIpAddresses; + ApiKey = apiKey; + ClientKey = clientKey; + Id = id; + Password = password; + Roles = roles; + Username = username; + _LinksOption = links; + _AllowedOriginsOption = allowedOrigins; + _DescriptionOption = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateApiCredentialResponse() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + [JsonPropertyName("allowedIpAddresses")] + public List AllowedIpAddresses { get; set; } + + /// + /// The API key for the API credential that was created. + /// + /// The API key for the API credential that was created. + [JsonPropertyName("apiKey")] + public string ApiKey { get; set; } + + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Unique identifier of the API credential. + /// + /// Unique identifier of the API credential. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The password for the API credential that was created. + /// + /// The password for the API credential that was created. + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public ApiCredentialLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateApiCredentialResponse {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedIpAddresses: ").Append(AllowedIpAddresses).Append("\n"); + sb.Append(" ApiKey: ").Append(ApiKey).Append("\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 50) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 50.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateApiCredentialResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateApiCredentialResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedIpAddresses = default; + Option apiKey = default; + Option clientKey = default; + Option id = default; + Option password = default; + Option?> roles = default; + Option username = default; + Option links = default; + Option?> allowedOrigins = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedIpAddresses": + allowedIpAddresses = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "apiKey": + apiKey = new Option(utf8JsonReader.GetString()!); + break; + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(active)); + + if (!allowedIpAddresses.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(allowedIpAddresses)); + + if (!apiKey.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(apiKey)); + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(clientKey)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(id)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(password)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(roles)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateApiCredentialResponse.", nameof(username)); + + return new CreateApiCredentialResponse(active.Value!.Value!, allowedIpAddresses.Value!, apiKey.Value!, clientKey.Value!, id.Value!, password.Value!, roles.Value!, username.Value!, links, allowedOrigins, description); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateApiCredentialResponse createApiCredentialResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createApiCredentialResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateApiCredentialResponse createApiCredentialResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", createApiCredentialResponse.Active); + + writer.WritePropertyName("allowedIpAddresses"); + JsonSerializer.Serialize(writer, createApiCredentialResponse.AllowedIpAddresses, jsonSerializerOptions); + if (createApiCredentialResponse.ApiKey != null) + writer.WriteString("apiKey", createApiCredentialResponse.ApiKey); + + if (createApiCredentialResponse.ClientKey != null) + writer.WriteString("clientKey", createApiCredentialResponse.ClientKey); + + if (createApiCredentialResponse.Id != null) + writer.WriteString("id", createApiCredentialResponse.Id); + + if (createApiCredentialResponse.Password != null) + writer.WriteString("password", createApiCredentialResponse.Password); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createApiCredentialResponse.Roles, jsonSerializerOptions); + if (createApiCredentialResponse.Username != null) + writer.WriteString("username", createApiCredentialResponse.Username); + + if (createApiCredentialResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, createApiCredentialResponse.Links, jsonSerializerOptions); + } + if (createApiCredentialResponse._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, createApiCredentialResponse.AllowedOrigins, jsonSerializerOptions); + } + if (createApiCredentialResponse._DescriptionOption.IsSet) + if (createApiCredentialResponse.Description != null) + writer.WriteString("description", createApiCredentialResponse.Description); + } + } +} diff --git a/Adyen/Management/Models/CreateCompanyApiCredentialRequest.cs b/Adyen/Management/Models/CreateCompanyApiCredentialRequest.cs new file mode 100644 index 000000000..0bad7c095 --- /dev/null +++ b/Adyen/Management/Models/CreateCompanyApiCredentialRequest.cs @@ -0,0 +1,256 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateCompanyApiCredentialRequest. + /// + public partial class CreateCompanyApiCredentialRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + /// List of merchant accounts that the API credential has access to. + /// Description of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + [JsonConstructor] + public CreateCompanyApiCredentialRequest(Option?> allowedOrigins = default, Option?> associatedMerchantAccounts = default, Option description = default, Option?> roles = default) + { + _AllowedOriginsOption = allowedOrigins; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _DescriptionOption = description; + _RolesOption = roles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCompanyApiCredentialRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + /// + /// List of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// List of merchant accounts that the API credential has access to. + /// + /// List of merchant accounts that the API credential has access to. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.' can be assigned to other API credentials. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCompanyApiCredentialRequest {\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCompanyApiCredentialRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCompanyApiCredentialRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> allowedOrigins = default; + Option?> associatedMerchantAccounts = default; + Option description = default; + Option?> roles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CreateCompanyApiCredentialRequest(allowedOrigins, associatedMerchantAccounts, description, roles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCompanyApiCredentialRequest createCompanyApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCompanyApiCredentialRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCompanyApiCredentialRequest createCompanyApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createCompanyApiCredentialRequest._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialRequest.AllowedOrigins, jsonSerializerOptions); + } + if (createCompanyApiCredentialRequest._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialRequest.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (createCompanyApiCredentialRequest._DescriptionOption.IsSet) + if (createCompanyApiCredentialRequest.Description != null) + writer.WriteString("description", createCompanyApiCredentialRequest.Description); + + if (createCompanyApiCredentialRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialRequest.Roles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/CreateCompanyApiCredentialResponse.cs b/Adyen/Management/Models/CreateCompanyApiCredentialResponse.cs new file mode 100644 index 000000000..cd5de20f2 --- /dev/null +++ b/Adyen/Management/Models/CreateCompanyApiCredentialResponse.cs @@ -0,0 +1,409 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateCompanyApiCredentialResponse. + /// + public partial class CreateCompanyApiCredentialResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// The API key for the API credential that was created. + /// List of merchant accounts that the API credential has access to. + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// Unique identifier of the API credential. + /// The password for the API credential that was created. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// links + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// Description of the API credential. + [JsonConstructor] + public CreateCompanyApiCredentialResponse(bool active, List allowedIpAddresses, string apiKey, List associatedMerchantAccounts, string clientKey, string id, string password, List roles, string username, Option links = default, Option?> allowedOrigins = default, Option description = default) + { + Active = active; + AllowedIpAddresses = allowedIpAddresses; + ApiKey = apiKey; + AssociatedMerchantAccounts = associatedMerchantAccounts; + ClientKey = clientKey; + Id = id; + Password = password; + Roles = roles; + Username = username; + _LinksOption = links; + _AllowedOriginsOption = allowedOrigins; + _DescriptionOption = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCompanyApiCredentialResponse() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + [JsonPropertyName("allowedIpAddresses")] + public List AllowedIpAddresses { get; set; } + + /// + /// The API key for the API credential that was created. + /// + /// The API key for the API credential that was created. + [JsonPropertyName("apiKey")] + public string ApiKey { get; set; } + + /// + /// List of merchant accounts that the API credential has access to. + /// + /// List of merchant accounts that the API credential has access to. + [JsonPropertyName("associatedMerchantAccounts")] + public List AssociatedMerchantAccounts { get; set; } + + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Unique identifier of the API credential. + /// + /// Unique identifier of the API credential. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The password for the API credential that was created. + /// + /// The password for the API credential that was created. + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public ApiCredentialLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCompanyApiCredentialResponse {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedIpAddresses: ").Append(AllowedIpAddresses).Append("\n"); + sb.Append(" ApiKey: ").Append(ApiKey).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 50) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 50.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCompanyApiCredentialResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCompanyApiCredentialResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedIpAddresses = default; + Option apiKey = default; + Option?> associatedMerchantAccounts = default; + Option clientKey = default; + Option id = default; + Option password = default; + Option?> roles = default; + Option username = default; + Option links = default; + Option?> allowedOrigins = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedIpAddresses": + allowedIpAddresses = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "apiKey": + apiKey = new Option(utf8JsonReader.GetString()!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(active)); + + if (!allowedIpAddresses.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(allowedIpAddresses)); + + if (!apiKey.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(apiKey)); + + if (!associatedMerchantAccounts.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(associatedMerchantAccounts)); + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(clientKey)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(id)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(password)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(roles)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyApiCredentialResponse.", nameof(username)); + + return new CreateCompanyApiCredentialResponse(active.Value!.Value!, allowedIpAddresses.Value!, apiKey.Value!, associatedMerchantAccounts.Value!, clientKey.Value!, id.Value!, password.Value!, roles.Value!, username.Value!, links, allowedOrigins, description); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCompanyApiCredentialResponse createCompanyApiCredentialResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCompanyApiCredentialResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCompanyApiCredentialResponse createCompanyApiCredentialResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", createCompanyApiCredentialResponse.Active); + + writer.WritePropertyName("allowedIpAddresses"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialResponse.AllowedIpAddresses, jsonSerializerOptions); + if (createCompanyApiCredentialResponse.ApiKey != null) + writer.WriteString("apiKey", createCompanyApiCredentialResponse.ApiKey); + + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialResponse.AssociatedMerchantAccounts, jsonSerializerOptions); + if (createCompanyApiCredentialResponse.ClientKey != null) + writer.WriteString("clientKey", createCompanyApiCredentialResponse.ClientKey); + + if (createCompanyApiCredentialResponse.Id != null) + writer.WriteString("id", createCompanyApiCredentialResponse.Id); + + if (createCompanyApiCredentialResponse.Password != null) + writer.WriteString("password", createCompanyApiCredentialResponse.Password); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialResponse.Roles, jsonSerializerOptions); + if (createCompanyApiCredentialResponse.Username != null) + writer.WriteString("username", createCompanyApiCredentialResponse.Username); + + if (createCompanyApiCredentialResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialResponse.Links, jsonSerializerOptions); + } + if (createCompanyApiCredentialResponse._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, createCompanyApiCredentialResponse.AllowedOrigins, jsonSerializerOptions); + } + if (createCompanyApiCredentialResponse._DescriptionOption.IsSet) + if (createCompanyApiCredentialResponse.Description != null) + writer.WriteString("description", createCompanyApiCredentialResponse.Description); + } + } +} diff --git a/Adyen/Management/Models/CreateCompanyUserRequest.cs b/Adyen/Management/Models/CreateCompanyUserRequest.cs new file mode 100644 index 000000000..13154ffe0 --- /dev/null +++ b/Adyen/Management/Models/CreateCompanyUserRequest.cs @@ -0,0 +1,349 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateCompanyUserRequest. + /// + public partial class CreateCompanyUserRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// name + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonConstructor] + public CreateCompanyUserRequest(string email, Name name, string username, Option?> accountGroups = default, Option?> associatedMerchantAccounts = default, Option loginMethod = default, Option?> roles = default, Option timeZoneCode = default) + { + Email = email; + Name = name; + Username = username; + _AccountGroupsOption = accountGroups; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _LoginMethodOption = loginMethod; + _RolesOption = roles; + _TimeZoneCodeOption = timeZoneCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCompanyUserRequest() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name Name { get; set; } + + /// + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + /// + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LoginMethodOption { get; private set; } + + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + [JsonPropertyName("loginMethod")] + public string? LoginMethod { get { return this._LoginMethodOption; } set { this._LoginMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneCodeOption { get; private set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string? TimeZoneCode { get { return this._TimeZoneCodeOption; } set { this._TimeZoneCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCompanyUserRequest {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" LoginMethod: ").Append(LoginMethod).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCompanyUserRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCompanyUserRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option name = default; + Option username = default; + Option?> accountGroups = default; + Option?> associatedMerchantAccounts = default; + Option loginMethod = default; + Option?> roles = default; + Option timeZoneCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "loginMethod": + loginMethod = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserRequest.", nameof(email)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserRequest.", nameof(name)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserRequest.", nameof(username)); + + return new CreateCompanyUserRequest(email.Value!, name.Value!, username.Value!, accountGroups, associatedMerchantAccounts, loginMethod, roles, timeZoneCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCompanyUserRequest createCompanyUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCompanyUserRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCompanyUserRequest createCompanyUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createCompanyUserRequest.Email != null) + writer.WriteString("email", createCompanyUserRequest.Email); + + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, createCompanyUserRequest.Name, jsonSerializerOptions); + if (createCompanyUserRequest.Username != null) + writer.WriteString("username", createCompanyUserRequest.Username); + + if (createCompanyUserRequest._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, createCompanyUserRequest.AccountGroups, jsonSerializerOptions); + } + if (createCompanyUserRequest._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, createCompanyUserRequest.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (createCompanyUserRequest._LoginMethodOption.IsSet) + if (createCompanyUserRequest.LoginMethod != null) + writer.WriteString("loginMethod", createCompanyUserRequest.LoginMethod); + + if (createCompanyUserRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createCompanyUserRequest.Roles, jsonSerializerOptions); + } + if (createCompanyUserRequest._TimeZoneCodeOption.IsSet) + if (createCompanyUserRequest.TimeZoneCode != null) + writer.WriteString("timeZoneCode", createCompanyUserRequest.TimeZoneCode); + } + } +} diff --git a/Adyen/Management/Models/CreateCompanyUserResponse.cs b/Adyen/Management/Models/CreateCompanyUserResponse.cs new file mode 100644 index 000000000..24083c3a6 --- /dev/null +++ b/Adyen/Management/Models/CreateCompanyUserResponse.cs @@ -0,0 +1,415 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateCompanyUserResponse. + /// + public partial class CreateCompanyUserResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// The unique identifier of the user. + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// The username for this user. + /// links + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Indicates whether this user is active. + /// Set of apps available to this user + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// name + [JsonConstructor] + public CreateCompanyUserResponse(string email, string id, List roles, string timeZoneCode, string username, Option links = default, Option?> accountGroups = default, Option active = default, Option?> apps = default, Option?> associatedMerchantAccounts = default, Option name = default) + { + Email = email; + Id = id; + Roles = roles; + TimeZoneCode = timeZoneCode; + Username = username; + _LinksOption = links; + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _AppsOption = apps; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCompanyUserResponse() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// The unique identifier of the user. + /// + /// The unique identifier of the user. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string TimeZoneCode { get; set; } + + /// + /// The username for this user. + /// + /// The username for this user. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates whether this user is active. + /// + /// Indicates whether this user is active. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AppsOption { get; private set; } + + /// + /// Set of apps available to this user + /// + /// Set of apps available to this user + [JsonPropertyName("apps")] + public List? Apps { get { return this._AppsOption; } set { this._AppsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) associated with this user. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCompanyUserResponse {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Apps: ").Append(Apps).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCompanyUserResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCompanyUserResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option id = default; + Option?> roles = default; + Option timeZoneCode = default; + Option username = default; + Option links = default; + Option?> accountGroups = default; + Option active = default; + Option?> apps = default; + Option?> associatedMerchantAccounts = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "apps": + apps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserResponse.", nameof(email)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserResponse.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserResponse.", nameof(roles)); + + if (!timeZoneCode.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserResponse.", nameof(timeZoneCode)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyUserResponse.", nameof(username)); + + return new CreateCompanyUserResponse(email.Value!, id.Value!, roles.Value!, timeZoneCode.Value!, username.Value!, links, accountGroups, active, apps, associatedMerchantAccounts, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCompanyUserResponse createCompanyUserResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCompanyUserResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCompanyUserResponse createCompanyUserResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (createCompanyUserResponse.Email != null) + writer.WriteString("email", createCompanyUserResponse.Email); + + if (createCompanyUserResponse.Id != null) + writer.WriteString("id", createCompanyUserResponse.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.Roles, jsonSerializerOptions); + if (createCompanyUserResponse.TimeZoneCode != null) + writer.WriteString("timeZoneCode", createCompanyUserResponse.TimeZoneCode); + + if (createCompanyUserResponse.Username != null) + writer.WriteString("username", createCompanyUserResponse.Username); + + if (createCompanyUserResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.Links, jsonSerializerOptions); + } + if (createCompanyUserResponse._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.AccountGroups, jsonSerializerOptions); + } + if (createCompanyUserResponse._ActiveOption.IsSet) + writer.WriteBoolean("active", createCompanyUserResponse._ActiveOption.Value!.Value); + + if (createCompanyUserResponse._AppsOption.IsSet) + { + writer.WritePropertyName("apps"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.Apps, jsonSerializerOptions); + } + if (createCompanyUserResponse._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (createCompanyUserResponse._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, createCompanyUserResponse.Name, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/CreateCompanyWebhookRequest.cs b/Adyen/Management/Models/CreateCompanyWebhookRequest.cs new file mode 100644 index 000000000..d9a719d3f --- /dev/null +++ b/Adyen/Management/Models/CreateCompanyWebhookRequest.cs @@ -0,0 +1,977 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateCompanyWebhookRequest. + /// + public partial class CreateCompanyWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **allAccounts** : Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. * **includeAccounts** : The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts** : The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// additionalSettings + /// Your description for this webhook configuration. + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// Password to access the webhook URL. + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// Username to access the webhook URL. + [JsonConstructor] + public CreateCompanyWebhookRequest(bool active, CommunicationFormatEnum communicationFormat, FilterMerchantAccountTypeEnum filterMerchantAccountType, List filterMerchantAccounts, string type, string url, Option acceptsExpiredCertificate = default, Option acceptsSelfSignedCertificate = default, Option acceptsUntrustedRootCertificate = default, Option additionalSettings = default, Option description = default, Option encryptionProtocol = default, Option networkType = default, Option password = default, Option populateSoapActionHeader = default, Option username = default) + { + Active = active; + CommunicationFormat = communicationFormat; + FilterMerchantAccountType = filterMerchantAccountType; + FilterMerchantAccounts = filterMerchantAccounts; + Type = type; + Url = url; + _AcceptsExpiredCertificateOption = acceptsExpiredCertificate; + _AcceptsSelfSignedCertificateOption = acceptsSelfSignedCertificate; + _AcceptsUntrustedRootCertificateOption = acceptsUntrustedRootCertificate; + _AdditionalSettingsOption = additionalSettings; + _DescriptionOption = description; + _EncryptionProtocolOption = encryptionProtocol; + _NetworkTypeOption = networkType; + _PasswordOption = password; + _PopulateSoapActionHeaderOption = populateSoapActionHeader; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateCompanyWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + [JsonConverter(typeof(CommunicationFormatEnumJsonConverter))] + public class CommunicationFormatEnum : IEnum + { + /// + /// Returns the value of the CommunicationFormatEnum. + /// + public string? Value { get; set; } + + /// + /// CommunicationFormatEnum.Http - http + /// + public static readonly CommunicationFormatEnum Http = new("http"); + + /// + /// CommunicationFormatEnum.Json - json + /// + public static readonly CommunicationFormatEnum Json = new("json"); + + /// + /// CommunicationFormatEnum.Soap - soap + /// + public static readonly CommunicationFormatEnum Soap = new("soap"); + + private CommunicationFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CommunicationFormatEnum?(string? value) => value == null ? null : new CommunicationFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CommunicationFormatEnum? option) => option?.Value; + + public static bool operator ==(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CommunicationFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CommunicationFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "http" => CommunicationFormatEnum.Http, + "json" => CommunicationFormatEnum.Json, + "soap" => CommunicationFormatEnum.Soap, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CommunicationFormatEnum? value) + { + if (value == null) + return null; + + if (value == CommunicationFormatEnum.Http) + return "http"; + + if (value == CommunicationFormatEnum.Json) + return "json"; + + if (value == CommunicationFormatEnum.Soap) + return "soap"; + + return null; + } + + /// + /// JsonConverter for writing CommunicationFormatEnum. + /// + public class CommunicationFormatEnumJsonConverter : JsonConverter + { + public override CommunicationFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CommunicationFormatEnum.FromStringOrDefault(value) ?? new CommunicationFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CommunicationFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CommunicationFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /* soap */ + [JsonPropertyName("communicationFormat")] + public CommunicationFormatEnum CommunicationFormat { get; set; } + + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **allAccounts** : Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. * **includeAccounts** : The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts** : The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **allAccounts** : Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. * **includeAccounts** : The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts** : The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. + [JsonConverter(typeof(FilterMerchantAccountTypeEnumJsonConverter))] + public class FilterMerchantAccountTypeEnum : IEnum + { + /// + /// Returns the value of the FilterMerchantAccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FilterMerchantAccountTypeEnum.AllAccounts - allAccounts + /// + public static readonly FilterMerchantAccountTypeEnum AllAccounts = new("allAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.ExcludeAccounts - excludeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum ExcludeAccounts = new("excludeAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.IncludeAccounts - includeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum IncludeAccounts = new("includeAccounts"); + + private FilterMerchantAccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FilterMerchantAccountTypeEnum?(string? value) => value == null ? null : new FilterMerchantAccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FilterMerchantAccountTypeEnum? option) => option?.Value; + + public static bool operator ==(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FilterMerchantAccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FilterMerchantAccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "allAccounts" => FilterMerchantAccountTypeEnum.AllAccounts, + "excludeAccounts" => FilterMerchantAccountTypeEnum.ExcludeAccounts, + "includeAccounts" => FilterMerchantAccountTypeEnum.IncludeAccounts, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FilterMerchantAccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == FilterMerchantAccountTypeEnum.AllAccounts) + return "allAccounts"; + + if (value == FilterMerchantAccountTypeEnum.ExcludeAccounts) + return "excludeAccounts"; + + if (value == FilterMerchantAccountTypeEnum.IncludeAccounts) + return "includeAccounts"; + + return null; + } + + /// + /// JsonConverter for writing FilterMerchantAccountTypeEnum. + /// + public class FilterMerchantAccountTypeEnumJsonConverter : JsonConverter + { + public override FilterMerchantAccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FilterMerchantAccountTypeEnum.FromStringOrDefault(value) ?? new FilterMerchantAccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FilterMerchantAccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FilterMerchantAccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **allAccounts** : Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. * **includeAccounts** : The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts** : The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **allAccounts** : Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. * **includeAccounts** : The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts** : The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. + [JsonPropertyName("filterMerchantAccountType")] + public FilterMerchantAccountTypeEnum FilterMerchantAccountType { get; set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + [JsonConverter(typeof(EncryptionProtocolEnumJsonConverter))] + public class EncryptionProtocolEnum : IEnum + { + /// + /// Returns the value of the EncryptionProtocolEnum. + /// + public string? Value { get; set; } + + /// + /// EncryptionProtocolEnum.HTTP - HTTP + /// + public static readonly EncryptionProtocolEnum HTTP = new("HTTP"); + + /// + /// EncryptionProtocolEnum.TLSv12 - TLSv1.2 + /// + public static readonly EncryptionProtocolEnum TLSv12 = new("TLSv1.2"); + + /// + /// EncryptionProtocolEnum.TLSv13 - TLSv1.3 + /// + public static readonly EncryptionProtocolEnum TLSv13 = new("TLSv1.3"); + + private EncryptionProtocolEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EncryptionProtocolEnum?(string? value) => value == null ? null : new EncryptionProtocolEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EncryptionProtocolEnum? option) => option?.Value; + + public static bool operator ==(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EncryptionProtocolEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EncryptionProtocolEnum? FromStringOrDefault(string value) + { + return value switch { + "HTTP" => EncryptionProtocolEnum.HTTP, + "TLSv1.2" => EncryptionProtocolEnum.TLSv12, + "TLSv1.3" => EncryptionProtocolEnum.TLSv13, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EncryptionProtocolEnum? value) + { + if (value == null) + return null; + + if (value == EncryptionProtocolEnum.HTTP) + return "HTTP"; + + if (value == EncryptionProtocolEnum.TLSv12) + return "TLSv1.2"; + + if (value == EncryptionProtocolEnum.TLSv13) + return "TLSv1.3"; + + return null; + } + + /// + /// JsonConverter for writing EncryptionProtocolEnum. + /// + public class EncryptionProtocolEnumJsonConverter : JsonConverter + { + public override EncryptionProtocolEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EncryptionProtocolEnum.FromStringOrDefault(value) ?? new EncryptionProtocolEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EncryptionProtocolEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EncryptionProtocolEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionProtocolOption { get; private set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /* TLSv1.2 */ + [JsonPropertyName("encryptionProtocol")] + public EncryptionProtocolEnum? EncryptionProtocol { get { return this._EncryptionProtocolOption; } set { this._EncryptionProtocolOption = new(value); } } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonConverter(typeof(NetworkTypeEnumJsonConverter))] + public class NetworkTypeEnum : IEnum + { + /// + /// Returns the value of the NetworkTypeEnum. + /// + public string? Value { get; set; } + + /// + /// NetworkTypeEnum.Local - local + /// + public static readonly NetworkTypeEnum Local = new("local"); + + /// + /// NetworkTypeEnum.Public - public + /// + public static readonly NetworkTypeEnum Public = new("public"); + + private NetworkTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NetworkTypeEnum?(string? value) => value == null ? null : new NetworkTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NetworkTypeEnum? option) => option?.Value; + + public static bool operator ==(NetworkTypeEnum? left, NetworkTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NetworkTypeEnum? left, NetworkTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NetworkTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NetworkTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "local" => NetworkTypeEnum.Local, + "public" => NetworkTypeEnum.Public, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NetworkTypeEnum? value) + { + if (value == null) + return null; + + if (value == NetworkTypeEnum.Local) + return "local"; + + if (value == NetworkTypeEnum.Public) + return "public"; + + return null; + } + + /// + /// JsonConverter for writing NetworkTypeEnum. + /// + public class NetworkTypeEnumJsonConverter : JsonConverter + { + public override NetworkTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NetworkTypeEnum.FromStringOrDefault(value) ?? new NetworkTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NetworkTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NetworkTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTypeOption { get; private set; } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonPropertyName("networkType")] + public NetworkTypeEnum? NetworkType { get { return this._NetworkTypeOption; } set { this._NetworkTypeOption = new(value); } } + + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + [JsonPropertyName("filterMerchantAccounts")] + public List FilterMerchantAccounts { get; set; } + + /// + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /* http://www.adyen.com */ + [JsonPropertyName("url")] + public string Url { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsExpiredCertificateOption { get; private set; } + + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsExpiredCertificate")] + public bool? AcceptsExpiredCertificate { get { return this._AcceptsExpiredCertificateOption; } set { this._AcceptsExpiredCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsSelfSignedCertificateOption { get; private set; } + + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsSelfSignedCertificate")] + public bool? AcceptsSelfSignedCertificate { get { return this._AcceptsSelfSignedCertificateOption; } set { this._AcceptsSelfSignedCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsUntrustedRootCertificateOption { get; private set; } + + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsUntrustedRootCertificate")] + public bool? AcceptsUntrustedRootCertificate { get { return this._AcceptsUntrustedRootCertificateOption; } set { this._AcceptsUntrustedRootCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalSettings")] + public AdditionalSettings? AdditionalSettings { get { return this._AdditionalSettingsOption; } set { this._AdditionalSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for this webhook configuration. + /// + /// Your description for this webhook configuration. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// Password to access the webhook URL. + /// + /// Password to access the webhook URL. + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PopulateSoapActionHeaderOption { get; private set; } + + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + [JsonPropertyName("populateSoapActionHeader")] + public bool? PopulateSoapActionHeader { get { return this._PopulateSoapActionHeaderOption; } set { this._PopulateSoapActionHeaderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// Username to access the webhook URL. + /// + /// Username to access the webhook URL. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateCompanyWebhookRequest {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" CommunicationFormat: ").Append(CommunicationFormat).Append("\n"); + sb.Append(" FilterMerchantAccountType: ").Append(FilterMerchantAccountType).Append("\n"); + sb.Append(" FilterMerchantAccounts: ").Append(FilterMerchantAccounts).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" AcceptsExpiredCertificate: ").Append(AcceptsExpiredCertificate).Append("\n"); + sb.Append(" AcceptsSelfSignedCertificate: ").Append(AcceptsSelfSignedCertificate).Append("\n"); + sb.Append(" AcceptsUntrustedRootCertificate: ").Append(AcceptsUntrustedRootCertificate).Append("\n"); + sb.Append(" AdditionalSettings: ").Append(AdditionalSettings).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EncryptionProtocol: ").Append(EncryptionProtocol).Append("\n"); + sb.Append(" NetworkType: ").Append(NetworkType).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PopulateSoapActionHeader: ").Append(PopulateSoapActionHeader).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateCompanyWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateCompanyWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option communicationFormat = default; + Option filterMerchantAccountType = default; + Option?> filterMerchantAccounts = default; + Option type = default; + Option url = default; + Option acceptsExpiredCertificate = default; + Option acceptsSelfSignedCertificate = default; + Option acceptsUntrustedRootCertificate = default; + Option additionalSettings = default; + Option description = default; + Option encryptionProtocol = default; + Option networkType = default; + Option password = default; + Option populateSoapActionHeader = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "communicationFormat": + string? communicationFormatRawValue = utf8JsonReader.GetString(); + communicationFormat = new Option(CreateCompanyWebhookRequest.CommunicationFormatEnum.FromStringOrDefault(communicationFormatRawValue)); + break; + case "filterMerchantAccountType": + string? filterMerchantAccountTypeRawValue = utf8JsonReader.GetString(); + filterMerchantAccountType = new Option(CreateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.FromStringOrDefault(filterMerchantAccountTypeRawValue)); + break; + case "filterMerchantAccounts": + filterMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "acceptsExpiredCertificate": + acceptsExpiredCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsSelfSignedCertificate": + acceptsSelfSignedCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsUntrustedRootCertificate": + acceptsUntrustedRootCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "additionalSettings": + additionalSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "encryptionProtocol": + string? encryptionProtocolRawValue = utf8JsonReader.GetString(); + encryptionProtocol = new Option(CreateCompanyWebhookRequest.EncryptionProtocolEnum.FromStringOrDefault(encryptionProtocolRawValue)); + break; + case "networkType": + string? networkTypeRawValue = utf8JsonReader.GetString(); + networkType = new Option(CreateCompanyWebhookRequest.NetworkTypeEnum.FromStringOrDefault(networkTypeRawValue)); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "populateSoapActionHeader": + populateSoapActionHeader = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(active)); + + if (!communicationFormat.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(communicationFormat)); + + if (!filterMerchantAccountType.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(filterMerchantAccountType)); + + if (!filterMerchantAccounts.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(filterMerchantAccounts)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(type)); + + if (!url.IsSet) + throw new ArgumentException("Property is required for class CreateCompanyWebhookRequest.", nameof(url)); + + return new CreateCompanyWebhookRequest(active.Value!.Value!, communicationFormat.Value!.Value!, filterMerchantAccountType.Value!.Value!, filterMerchantAccounts.Value!, type.Value!, url.Value!, acceptsExpiredCertificate, acceptsSelfSignedCertificate, acceptsUntrustedRootCertificate, additionalSettings, description, encryptionProtocol, networkType, password, populateSoapActionHeader, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateCompanyWebhookRequest createCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createCompanyWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateCompanyWebhookRequest createCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", createCompanyWebhookRequest.Active); + + if (createCompanyWebhookRequest.CommunicationFormat != null) + { + string? communicationFormatRawValue = CreateCompanyWebhookRequest.CommunicationFormatEnum.ToJsonValue(createCompanyWebhookRequest.CommunicationFormat); + writer.WriteString("communicationFormat", communicationFormatRawValue); + } + + if (createCompanyWebhookRequest.FilterMerchantAccountType != null) + { + string? filterMerchantAccountTypeRawValue = CreateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.ToJsonValue(createCompanyWebhookRequest.FilterMerchantAccountType); + writer.WriteString("filterMerchantAccountType", filterMerchantAccountTypeRawValue); + } + + writer.WritePropertyName("filterMerchantAccounts"); + JsonSerializer.Serialize(writer, createCompanyWebhookRequest.FilterMerchantAccounts, jsonSerializerOptions); + if (createCompanyWebhookRequest.Type != null) + writer.WriteString("type", createCompanyWebhookRequest.Type); + + if (createCompanyWebhookRequest.Url != null) + writer.WriteString("url", createCompanyWebhookRequest.Url); + + if (createCompanyWebhookRequest._AcceptsExpiredCertificateOption.IsSet) + writer.WriteBoolean("acceptsExpiredCertificate", createCompanyWebhookRequest._AcceptsExpiredCertificateOption.Value!.Value); + + if (createCompanyWebhookRequest._AcceptsSelfSignedCertificateOption.IsSet) + writer.WriteBoolean("acceptsSelfSignedCertificate", createCompanyWebhookRequest._AcceptsSelfSignedCertificateOption.Value!.Value); + + if (createCompanyWebhookRequest._AcceptsUntrustedRootCertificateOption.IsSet) + writer.WriteBoolean("acceptsUntrustedRootCertificate", createCompanyWebhookRequest._AcceptsUntrustedRootCertificateOption.Value!.Value); + + if (createCompanyWebhookRequest._AdditionalSettingsOption.IsSet) + { + writer.WritePropertyName("additionalSettings"); + JsonSerializer.Serialize(writer, createCompanyWebhookRequest.AdditionalSettings, jsonSerializerOptions); + } + if (createCompanyWebhookRequest._DescriptionOption.IsSet) + if (createCompanyWebhookRequest.Description != null) + writer.WriteString("description", createCompanyWebhookRequest.Description); + + if (createCompanyWebhookRequest._EncryptionProtocolOption.IsSet && createCompanyWebhookRequest.EncryptionProtocol != null) + { + string? encryptionProtocolRawValue = CreateCompanyWebhookRequest.EncryptionProtocolEnum.ToJsonValue(createCompanyWebhookRequest._EncryptionProtocolOption.Value!.Value); + writer.WriteString("encryptionProtocol", encryptionProtocolRawValue); + } + + if (createCompanyWebhookRequest._NetworkTypeOption.IsSet && createCompanyWebhookRequest.NetworkType != null) + { + string? networkTypeRawValue = CreateCompanyWebhookRequest.NetworkTypeEnum.ToJsonValue(createCompanyWebhookRequest._NetworkTypeOption.Value!.Value); + writer.WriteString("networkType", networkTypeRawValue); + } + + if (createCompanyWebhookRequest._PasswordOption.IsSet) + if (createCompanyWebhookRequest.Password != null) + writer.WriteString("password", createCompanyWebhookRequest.Password); + + if (createCompanyWebhookRequest._PopulateSoapActionHeaderOption.IsSet) + writer.WriteBoolean("populateSoapActionHeader", createCompanyWebhookRequest._PopulateSoapActionHeaderOption.Value!.Value); + + if (createCompanyWebhookRequest._UsernameOption.IsSet) + if (createCompanyWebhookRequest.Username != null) + writer.WriteString("username", createCompanyWebhookRequest.Username); + } + } +} diff --git a/Adyen/Management/Models/CreateMerchantApiCredentialRequest.cs b/Adyen/Management/Models/CreateMerchantApiCredentialRequest.cs new file mode 100644 index 000000000..92af57372 --- /dev/null +++ b/Adyen/Management/Models/CreateMerchantApiCredentialRequest.cs @@ -0,0 +1,230 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateMerchantApiCredentialRequest. + /// + public partial class CreateMerchantApiCredentialRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + /// Description of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + [JsonConstructor] + public CreateMerchantApiCredentialRequest(Option?> allowedOrigins = default, Option description = default, Option?> roles = default) + { + _AllowedOriginsOption = allowedOrigins; + _DescriptionOption = description; + _RolesOption = roles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateMerchantApiCredentialRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// The list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + /// + /// The list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the new API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.' can be assigned to other API credentials. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateMerchantApiCredentialRequest {\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateMerchantApiCredentialRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateMerchantApiCredentialRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> allowedOrigins = default; + Option description = default; + Option?> roles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CreateMerchantApiCredentialRequest(allowedOrigins, description, roles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateMerchantApiCredentialRequest createMerchantApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createMerchantApiCredentialRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateMerchantApiCredentialRequest createMerchantApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createMerchantApiCredentialRequest._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, createMerchantApiCredentialRequest.AllowedOrigins, jsonSerializerOptions); + } + if (createMerchantApiCredentialRequest._DescriptionOption.IsSet) + if (createMerchantApiCredentialRequest.Description != null) + writer.WriteString("description", createMerchantApiCredentialRequest.Description); + + if (createMerchantApiCredentialRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createMerchantApiCredentialRequest.Roles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/CreateMerchantRequest.cs b/Adyen/Management/Models/CreateMerchantRequest.cs new file mode 100644 index 000000000..ea576be0f --- /dev/null +++ b/Adyen/Management/Models/CreateMerchantRequest.cs @@ -0,0 +1,329 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateMerchantRequest. + /// + public partial class CreateMerchantRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the company account. + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). Required for an Adyen for Platforms Manage integration. + /// Your description for the merchant account, maximum 300 characters. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). Required for an Adyen for Platforms Manage integration. + /// Sets the pricing plan for the merchant account. Required for an Adyen for Platforms Manage integration. Your Adyen contact will provide the values that you can use. + /// Your reference for the merchant account. To make this reference the unique identifier of the merchant account, your Adyen contact can set up a template on your company account. The template can have 6 to 255 characters with upper- and lower-case letters, underscores, and numbers. When your company account has a template, then the `reference` is required and must be unique within the company account. + /// List of sales channels that the merchant will process payments with + [JsonConstructor] + public CreateMerchantRequest(string companyId, Option businessLineId = default, Option description = default, Option legalEntityId = default, Option pricingPlan = default, Option reference = default, Option?> salesChannels = default) + { + CompanyId = companyId; + _BusinessLineIdOption = businessLineId; + _DescriptionOption = description; + _LegalEntityIdOption = legalEntityId; + _PricingPlanOption = pricingPlan; + _ReferenceOption = reference; + _SalesChannelsOption = salesChannels; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateMerchantRequest() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string CompanyId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessLineIdOption { get; private set; } + + /// + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). Required for an Adyen for Platforms Manage integration. + /// + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). Required for an Adyen for Platforms Manage integration. + [JsonPropertyName("businessLineId")] + public string? BusinessLineId { get { return this._BusinessLineIdOption; } set { this._BusinessLineIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the merchant account, maximum 300 characters. + /// + /// Your description for the merchant account, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LegalEntityIdOption { get; private set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). Required for an Adyen for Platforms Manage integration. + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). Required for an Adyen for Platforms Manage integration. + [JsonPropertyName("legalEntityId")] + public string? LegalEntityId { get { return this._LegalEntityIdOption; } set { this._LegalEntityIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PricingPlanOption { get; private set; } + + /// + /// Sets the pricing plan for the merchant account. Required for an Adyen for Platforms Manage integration. Your Adyen contact will provide the values that you can use. + /// + /// Sets the pricing plan for the merchant account. Required for an Adyen for Platforms Manage integration. Your Adyen contact will provide the values that you can use. + [JsonPropertyName("pricingPlan")] + public string? PricingPlan { get { return this._PricingPlanOption; } set { this._PricingPlanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the merchant account. To make this reference the unique identifier of the merchant account, your Adyen contact can set up a template on your company account. The template can have 6 to 255 characters with upper- and lower-case letters, underscores, and numbers. When your company account has a template, then the `reference` is required and must be unique within the company account. + /// + /// Your reference for the merchant account. To make this reference the unique identifier of the merchant account, your Adyen contact can set up a template on your company account. The template can have 6 to 255 characters with upper- and lower-case letters, underscores, and numbers. When your company account has a template, then the `reference` is required and must be unique within the company account. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SalesChannelsOption { get; private set; } + + /// + /// List of sales channels that the merchant will process payments with + /// + /// List of sales channels that the merchant will process payments with + [JsonPropertyName("salesChannels")] + public List? SalesChannels { get { return this._SalesChannelsOption; } set { this._SalesChannelsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateMerchantRequest {\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" BusinessLineId: ").Append(BusinessLineId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" PricingPlan: ").Append(PricingPlan).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SalesChannels: ").Append(SalesChannels).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateMerchantRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateMerchantRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option companyId = default; + Option businessLineId = default; + Option description = default; + Option legalEntityId = default; + Option pricingPlan = default; + Option reference = default; + Option?> salesChannels = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "businessLineId": + businessLineId = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "pricingPlan": + pricingPlan = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "salesChannels": + salesChannels = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!companyId.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantRequest.", nameof(companyId)); + + return new CreateMerchantRequest(companyId.Value!, businessLineId, description, legalEntityId, pricingPlan, reference, salesChannels); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateMerchantRequest createMerchantRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createMerchantRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateMerchantRequest createMerchantRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createMerchantRequest.CompanyId != null) + writer.WriteString("companyId", createMerchantRequest.CompanyId); + + if (createMerchantRequest._BusinessLineIdOption.IsSet) + if (createMerchantRequest.BusinessLineId != null) + writer.WriteString("businessLineId", createMerchantRequest.BusinessLineId); + + if (createMerchantRequest._DescriptionOption.IsSet) + if (createMerchantRequest.Description != null) + writer.WriteString("description", createMerchantRequest.Description); + + if (createMerchantRequest._LegalEntityIdOption.IsSet) + if (createMerchantRequest.LegalEntityId != null) + writer.WriteString("legalEntityId", createMerchantRequest.LegalEntityId); + + if (createMerchantRequest._PricingPlanOption.IsSet) + if (createMerchantRequest.PricingPlan != null) + writer.WriteString("pricingPlan", createMerchantRequest.PricingPlan); + + if (createMerchantRequest._ReferenceOption.IsSet) + if (createMerchantRequest.Reference != null) + writer.WriteString("reference", createMerchantRequest.Reference); + + if (createMerchantRequest._SalesChannelsOption.IsSet) + { + writer.WritePropertyName("salesChannels"); + JsonSerializer.Serialize(writer, createMerchantRequest.SalesChannels, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/CreateMerchantResponse.cs b/Adyen/Management/Models/CreateMerchantResponse.cs new file mode 100644 index 000000000..2108b745d --- /dev/null +++ b/Adyen/Management/Models/CreateMerchantResponse.cs @@ -0,0 +1,333 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateMerchantResponse. + /// + public partial class CreateMerchantResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). + /// The unique identifier of the company account. + /// Your description for the merchant account, maximum 300 characters. + /// The unique identifier of the merchant account. If Adyen set up a template for the `reference`, then the `id` will have the same value as the `reference` that you sent in the request. Otherwise, the value is generated by Adyen. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). + /// Partner pricing plan for the merchant, applicable for merchants under AfP managed company accounts. + /// Your reference for the merchant account. + [JsonConstructor] + public CreateMerchantResponse(Option businessLineId = default, Option companyId = default, Option description = default, Option id = default, Option legalEntityId = default, Option pricingPlan = default, Option reference = default) + { + _BusinessLineIdOption = businessLineId; + _CompanyIdOption = companyId; + _DescriptionOption = description; + _IdOption = id; + _LegalEntityIdOption = legalEntityId; + _PricingPlanOption = pricingPlan; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateMerchantResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessLineIdOption { get; private set; } + + /// + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). + /// + /// The unique identifier of the [business line](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines). + [JsonPropertyName("businessLineId")] + public string? BusinessLineId { get { return this._BusinessLineIdOption; } set { this._BusinessLineIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the merchant account, maximum 300 characters. + /// + /// Your description for the merchant account, maximum 300 characters. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the merchant account. If Adyen set up a template for the `reference`, then the `id` will have the same value as the `reference` that you sent in the request. Otherwise, the value is generated by Adyen. + /// + /// The unique identifier of the merchant account. If Adyen set up a template for the `reference`, then the `id` will have the same value as the `reference` that you sent in the request. Otherwise, the value is generated by Adyen. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LegalEntityIdOption { get; private set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/legalEntities). + [JsonPropertyName("legalEntityId")] + public string? LegalEntityId { get { return this._LegalEntityIdOption; } set { this._LegalEntityIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PricingPlanOption { get; private set; } + + /// + /// Partner pricing plan for the merchant, applicable for merchants under AfP managed company accounts. + /// + /// Partner pricing plan for the merchant, applicable for merchants under AfP managed company accounts. + [JsonPropertyName("pricingPlan")] + public string? PricingPlan { get { return this._PricingPlanOption; } set { this._PricingPlanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the merchant account. + /// + /// Your reference for the merchant account. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateMerchantResponse {\n"); + sb.Append(" BusinessLineId: ").Append(BusinessLineId).Append("\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append(" PricingPlan: ").Append(PricingPlan).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateMerchantResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateMerchantResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option businessLineId = default; + Option companyId = default; + Option description = default; + Option id = default; + Option legalEntityId = default; + Option pricingPlan = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "businessLineId": + businessLineId = new Option(utf8JsonReader.GetString()!); + break; + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "pricingPlan": + pricingPlan = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CreateMerchantResponse(businessLineId, companyId, description, id, legalEntityId, pricingPlan, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateMerchantResponse createMerchantResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createMerchantResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateMerchantResponse createMerchantResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (createMerchantResponse._BusinessLineIdOption.IsSet) + if (createMerchantResponse.BusinessLineId != null) + writer.WriteString("businessLineId", createMerchantResponse.BusinessLineId); + + if (createMerchantResponse._CompanyIdOption.IsSet) + if (createMerchantResponse.CompanyId != null) + writer.WriteString("companyId", createMerchantResponse.CompanyId); + + if (createMerchantResponse._DescriptionOption.IsSet) + if (createMerchantResponse.Description != null) + writer.WriteString("description", createMerchantResponse.Description); + + if (createMerchantResponse._IdOption.IsSet) + if (createMerchantResponse.Id != null) + writer.WriteString("id", createMerchantResponse.Id); + + if (createMerchantResponse._LegalEntityIdOption.IsSet) + if (createMerchantResponse.LegalEntityId != null) + writer.WriteString("legalEntityId", createMerchantResponse.LegalEntityId); + + if (createMerchantResponse._PricingPlanOption.IsSet) + if (createMerchantResponse.PricingPlan != null) + writer.WriteString("pricingPlan", createMerchantResponse.PricingPlan); + + if (createMerchantResponse._ReferenceOption.IsSet) + if (createMerchantResponse.Reference != null) + writer.WriteString("reference", createMerchantResponse.Reference); + } + } +} diff --git a/Adyen/Management/Models/CreateMerchantUserRequest.cs b/Adyen/Management/Models/CreateMerchantUserRequest.cs new file mode 100644 index 000000000..fdc8b34c5 --- /dev/null +++ b/Adyen/Management/Models/CreateMerchantUserRequest.cs @@ -0,0 +1,323 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateMerchantUserRequest. + /// + public partial class CreateMerchantUserRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// name + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonConstructor] + public CreateMerchantUserRequest(string email, Name name, string username, Option?> accountGroups = default, Option loginMethod = default, Option?> roles = default, Option timeZoneCode = default) + { + Email = email; + Name = name; + Username = username; + _AccountGroupsOption = accountGroups; + _LoginMethodOption = loginMethod; + _RolesOption = roles; + _TimeZoneCodeOption = timeZoneCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateMerchantUserRequest() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name Name { get; set; } + + /// + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + /// + /// The user's email address that will be their username. Must be the same as the one in the `email` field. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LoginMethodOption { get; private set; } + + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + [JsonPropertyName("loginMethod")] + public string? LoginMethod { get { return this._LoginMethodOption; } set { this._LoginMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneCodeOption { get; private set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string? TimeZoneCode { get { return this._TimeZoneCodeOption; } set { this._TimeZoneCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateMerchantUserRequest {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" LoginMethod: ").Append(LoginMethod).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateMerchantUserRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateMerchantUserRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option name = default; + Option username = default; + Option?> accountGroups = default; + Option loginMethod = default; + Option?> roles = default; + Option timeZoneCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "loginMethod": + loginMethod = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantUserRequest.", nameof(email)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantUserRequest.", nameof(name)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantUserRequest.", nameof(username)); + + return new CreateMerchantUserRequest(email.Value!, name.Value!, username.Value!, accountGroups, loginMethod, roles, timeZoneCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateMerchantUserRequest createMerchantUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createMerchantUserRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateMerchantUserRequest createMerchantUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createMerchantUserRequest.Email != null) + writer.WriteString("email", createMerchantUserRequest.Email); + + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, createMerchantUserRequest.Name, jsonSerializerOptions); + if (createMerchantUserRequest.Username != null) + writer.WriteString("username", createMerchantUserRequest.Username); + + if (createMerchantUserRequest._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, createMerchantUserRequest.AccountGroups, jsonSerializerOptions); + } + if (createMerchantUserRequest._LoginMethodOption.IsSet) + if (createMerchantUserRequest.LoginMethod != null) + writer.WriteString("loginMethod", createMerchantUserRequest.LoginMethod); + + if (createMerchantUserRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createMerchantUserRequest.Roles, jsonSerializerOptions); + } + if (createMerchantUserRequest._TimeZoneCodeOption.IsSet) + if (createMerchantUserRequest.TimeZoneCode != null) + writer.WriteString("timeZoneCode", createMerchantUserRequest.TimeZoneCode); + } + } +} diff --git a/Adyen/Management/Models/CreateMerchantWebhookRequest.cs b/Adyen/Management/Models/CreateMerchantWebhookRequest.cs new file mode 100644 index 000000000..f8a2bb039 --- /dev/null +++ b/Adyen/Management/Models/CreateMerchantWebhookRequest.cs @@ -0,0 +1,822 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateMerchantWebhookRequest. + /// + public partial class CreateMerchantWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// additionalSettings + /// Your description for this webhook configuration. + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// Password to access the webhook URL. + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// Username to access the webhook URL. + [JsonConstructor] + public CreateMerchantWebhookRequest(bool active, CommunicationFormatEnum communicationFormat, string type, string url, Option acceptsExpiredCertificate = default, Option acceptsSelfSignedCertificate = default, Option acceptsUntrustedRootCertificate = default, Option additionalSettings = default, Option description = default, Option encryptionProtocol = default, Option networkType = default, Option password = default, Option populateSoapActionHeader = default, Option username = default) + { + Active = active; + CommunicationFormat = communicationFormat; + Type = type; + Url = url; + _AcceptsExpiredCertificateOption = acceptsExpiredCertificate; + _AcceptsSelfSignedCertificateOption = acceptsSelfSignedCertificate; + _AcceptsUntrustedRootCertificateOption = acceptsUntrustedRootCertificate; + _AdditionalSettingsOption = additionalSettings; + _DescriptionOption = description; + _EncryptionProtocolOption = encryptionProtocol; + _NetworkTypeOption = networkType; + _PasswordOption = password; + _PopulateSoapActionHeaderOption = populateSoapActionHeader; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateMerchantWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + [JsonConverter(typeof(CommunicationFormatEnumJsonConverter))] + public class CommunicationFormatEnum : IEnum + { + /// + /// Returns the value of the CommunicationFormatEnum. + /// + public string? Value { get; set; } + + /// + /// CommunicationFormatEnum.Http - http + /// + public static readonly CommunicationFormatEnum Http = new("http"); + + /// + /// CommunicationFormatEnum.Json - json + /// + public static readonly CommunicationFormatEnum Json = new("json"); + + /// + /// CommunicationFormatEnum.Soap - soap + /// + public static readonly CommunicationFormatEnum Soap = new("soap"); + + private CommunicationFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CommunicationFormatEnum?(string? value) => value == null ? null : new CommunicationFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CommunicationFormatEnum? option) => option?.Value; + + public static bool operator ==(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CommunicationFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CommunicationFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "http" => CommunicationFormatEnum.Http, + "json" => CommunicationFormatEnum.Json, + "soap" => CommunicationFormatEnum.Soap, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CommunicationFormatEnum? value) + { + if (value == null) + return null; + + if (value == CommunicationFormatEnum.Http) + return "http"; + + if (value == CommunicationFormatEnum.Json) + return "json"; + + if (value == CommunicationFormatEnum.Soap) + return "soap"; + + return null; + } + + /// + /// JsonConverter for writing CommunicationFormatEnum. + /// + public class CommunicationFormatEnumJsonConverter : JsonConverter + { + public override CommunicationFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CommunicationFormatEnum.FromStringOrDefault(value) ?? new CommunicationFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CommunicationFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CommunicationFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /* soap */ + [JsonPropertyName("communicationFormat")] + public CommunicationFormatEnum CommunicationFormat { get; set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + [JsonConverter(typeof(EncryptionProtocolEnumJsonConverter))] + public class EncryptionProtocolEnum : IEnum + { + /// + /// Returns the value of the EncryptionProtocolEnum. + /// + public string? Value { get; set; } + + /// + /// EncryptionProtocolEnum.HTTP - HTTP + /// + public static readonly EncryptionProtocolEnum HTTP = new("HTTP"); + + /// + /// EncryptionProtocolEnum.TLSv12 - TLSv1.2 + /// + public static readonly EncryptionProtocolEnum TLSv12 = new("TLSv1.2"); + + /// + /// EncryptionProtocolEnum.TLSv13 - TLSv1.3 + /// + public static readonly EncryptionProtocolEnum TLSv13 = new("TLSv1.3"); + + private EncryptionProtocolEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EncryptionProtocolEnum?(string? value) => value == null ? null : new EncryptionProtocolEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EncryptionProtocolEnum? option) => option?.Value; + + public static bool operator ==(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EncryptionProtocolEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EncryptionProtocolEnum? FromStringOrDefault(string value) + { + return value switch { + "HTTP" => EncryptionProtocolEnum.HTTP, + "TLSv1.2" => EncryptionProtocolEnum.TLSv12, + "TLSv1.3" => EncryptionProtocolEnum.TLSv13, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EncryptionProtocolEnum? value) + { + if (value == null) + return null; + + if (value == EncryptionProtocolEnum.HTTP) + return "HTTP"; + + if (value == EncryptionProtocolEnum.TLSv12) + return "TLSv1.2"; + + if (value == EncryptionProtocolEnum.TLSv13) + return "TLSv1.3"; + + return null; + } + + /// + /// JsonConverter for writing EncryptionProtocolEnum. + /// + public class EncryptionProtocolEnumJsonConverter : JsonConverter + { + public override EncryptionProtocolEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EncryptionProtocolEnum.FromStringOrDefault(value) ?? new EncryptionProtocolEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EncryptionProtocolEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EncryptionProtocolEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionProtocolOption { get; private set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /* TLSv1.2 */ + [JsonPropertyName("encryptionProtocol")] + public EncryptionProtocolEnum? EncryptionProtocol { get { return this._EncryptionProtocolOption; } set { this._EncryptionProtocolOption = new(value); } } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonConverter(typeof(NetworkTypeEnumJsonConverter))] + public class NetworkTypeEnum : IEnum + { + /// + /// Returns the value of the NetworkTypeEnum. + /// + public string? Value { get; set; } + + /// + /// NetworkTypeEnum.Local - local + /// + public static readonly NetworkTypeEnum Local = new("local"); + + /// + /// NetworkTypeEnum.Public - public + /// + public static readonly NetworkTypeEnum Public = new("public"); + + private NetworkTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NetworkTypeEnum?(string? value) => value == null ? null : new NetworkTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NetworkTypeEnum? option) => option?.Value; + + public static bool operator ==(NetworkTypeEnum? left, NetworkTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NetworkTypeEnum? left, NetworkTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NetworkTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NetworkTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "local" => NetworkTypeEnum.Local, + "public" => NetworkTypeEnum.Public, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NetworkTypeEnum? value) + { + if (value == null) + return null; + + if (value == NetworkTypeEnum.Local) + return "local"; + + if (value == NetworkTypeEnum.Public) + return "public"; + + return null; + } + + /// + /// JsonConverter for writing NetworkTypeEnum. + /// + public class NetworkTypeEnumJsonConverter : JsonConverter + { + public override NetworkTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NetworkTypeEnum.FromStringOrDefault(value) ?? new NetworkTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NetworkTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NetworkTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTypeOption { get; private set; } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonPropertyName("networkType")] + public NetworkTypeEnum? NetworkType { get { return this._NetworkTypeOption; } set { this._NetworkTypeOption = new(value); } } + + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// + /// The type of webhook that is being created. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **rreq-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /* http://www.adyen.com */ + [JsonPropertyName("url")] + public string Url { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsExpiredCertificateOption { get; private set; } + + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsExpiredCertificate")] + public bool? AcceptsExpiredCertificate { get { return this._AcceptsExpiredCertificateOption; } set { this._AcceptsExpiredCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsSelfSignedCertificateOption { get; private set; } + + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsSelfSignedCertificate")] + public bool? AcceptsSelfSignedCertificate { get { return this._AcceptsSelfSignedCertificateOption; } set { this._AcceptsSelfSignedCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsUntrustedRootCertificateOption { get; private set; } + + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsUntrustedRootCertificate")] + public bool? AcceptsUntrustedRootCertificate { get { return this._AcceptsUntrustedRootCertificateOption; } set { this._AcceptsUntrustedRootCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalSettings")] + public AdditionalSettings? AdditionalSettings { get { return this._AdditionalSettingsOption; } set { this._AdditionalSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for this webhook configuration. + /// + /// Your description for this webhook configuration. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// Password to access the webhook URL. + /// + /// Password to access the webhook URL. + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PopulateSoapActionHeaderOption { get; private set; } + + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + [JsonPropertyName("populateSoapActionHeader")] + public bool? PopulateSoapActionHeader { get { return this._PopulateSoapActionHeaderOption; } set { this._PopulateSoapActionHeaderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// Username to access the webhook URL. + /// + /// Username to access the webhook URL. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateMerchantWebhookRequest {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" CommunicationFormat: ").Append(CommunicationFormat).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" AcceptsExpiredCertificate: ").Append(AcceptsExpiredCertificate).Append("\n"); + sb.Append(" AcceptsSelfSignedCertificate: ").Append(AcceptsSelfSignedCertificate).Append("\n"); + sb.Append(" AcceptsUntrustedRootCertificate: ").Append(AcceptsUntrustedRootCertificate).Append("\n"); + sb.Append(" AdditionalSettings: ").Append(AdditionalSettings).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EncryptionProtocol: ").Append(EncryptionProtocol).Append("\n"); + sb.Append(" NetworkType: ").Append(NetworkType).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PopulateSoapActionHeader: ").Append(PopulateSoapActionHeader).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateMerchantWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateMerchantWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option communicationFormat = default; + Option type = default; + Option url = default; + Option acceptsExpiredCertificate = default; + Option acceptsSelfSignedCertificate = default; + Option acceptsUntrustedRootCertificate = default; + Option additionalSettings = default; + Option description = default; + Option encryptionProtocol = default; + Option networkType = default; + Option password = default; + Option populateSoapActionHeader = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "communicationFormat": + string? communicationFormatRawValue = utf8JsonReader.GetString(); + communicationFormat = new Option(CreateMerchantWebhookRequest.CommunicationFormatEnum.FromStringOrDefault(communicationFormatRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "acceptsExpiredCertificate": + acceptsExpiredCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsSelfSignedCertificate": + acceptsSelfSignedCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsUntrustedRootCertificate": + acceptsUntrustedRootCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "additionalSettings": + additionalSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "encryptionProtocol": + string? encryptionProtocolRawValue = utf8JsonReader.GetString(); + encryptionProtocol = new Option(CreateMerchantWebhookRequest.EncryptionProtocolEnum.FromStringOrDefault(encryptionProtocolRawValue)); + break; + case "networkType": + string? networkTypeRawValue = utf8JsonReader.GetString(); + networkType = new Option(CreateMerchantWebhookRequest.NetworkTypeEnum.FromStringOrDefault(networkTypeRawValue)); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "populateSoapActionHeader": + populateSoapActionHeader = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantWebhookRequest.", nameof(active)); + + if (!communicationFormat.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantWebhookRequest.", nameof(communicationFormat)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantWebhookRequest.", nameof(type)); + + if (!url.IsSet) + throw new ArgumentException("Property is required for class CreateMerchantWebhookRequest.", nameof(url)); + + return new CreateMerchantWebhookRequest(active.Value!.Value!, communicationFormat.Value!.Value!, type.Value!, url.Value!, acceptsExpiredCertificate, acceptsSelfSignedCertificate, acceptsUntrustedRootCertificate, additionalSettings, description, encryptionProtocol, networkType, password, populateSoapActionHeader, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateMerchantWebhookRequest createMerchantWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createMerchantWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateMerchantWebhookRequest createMerchantWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", createMerchantWebhookRequest.Active); + + if (createMerchantWebhookRequest.CommunicationFormat != null) + { + string? communicationFormatRawValue = CreateMerchantWebhookRequest.CommunicationFormatEnum.ToJsonValue(createMerchantWebhookRequest.CommunicationFormat); + writer.WriteString("communicationFormat", communicationFormatRawValue); + } + + if (createMerchantWebhookRequest.Type != null) + writer.WriteString("type", createMerchantWebhookRequest.Type); + + if (createMerchantWebhookRequest.Url != null) + writer.WriteString("url", createMerchantWebhookRequest.Url); + + if (createMerchantWebhookRequest._AcceptsExpiredCertificateOption.IsSet) + writer.WriteBoolean("acceptsExpiredCertificate", createMerchantWebhookRequest._AcceptsExpiredCertificateOption.Value!.Value); + + if (createMerchantWebhookRequest._AcceptsSelfSignedCertificateOption.IsSet) + writer.WriteBoolean("acceptsSelfSignedCertificate", createMerchantWebhookRequest._AcceptsSelfSignedCertificateOption.Value!.Value); + + if (createMerchantWebhookRequest._AcceptsUntrustedRootCertificateOption.IsSet) + writer.WriteBoolean("acceptsUntrustedRootCertificate", createMerchantWebhookRequest._AcceptsUntrustedRootCertificateOption.Value!.Value); + + if (createMerchantWebhookRequest._AdditionalSettingsOption.IsSet) + { + writer.WritePropertyName("additionalSettings"); + JsonSerializer.Serialize(writer, createMerchantWebhookRequest.AdditionalSettings, jsonSerializerOptions); + } + if (createMerchantWebhookRequest._DescriptionOption.IsSet) + if (createMerchantWebhookRequest.Description != null) + writer.WriteString("description", createMerchantWebhookRequest.Description); + + if (createMerchantWebhookRequest._EncryptionProtocolOption.IsSet && createMerchantWebhookRequest.EncryptionProtocol != null) + { + string? encryptionProtocolRawValue = CreateMerchantWebhookRequest.EncryptionProtocolEnum.ToJsonValue(createMerchantWebhookRequest._EncryptionProtocolOption.Value!.Value); + writer.WriteString("encryptionProtocol", encryptionProtocolRawValue); + } + + if (createMerchantWebhookRequest._NetworkTypeOption.IsSet && createMerchantWebhookRequest.NetworkType != null) + { + string? networkTypeRawValue = CreateMerchantWebhookRequest.NetworkTypeEnum.ToJsonValue(createMerchantWebhookRequest._NetworkTypeOption.Value!.Value); + writer.WriteString("networkType", networkTypeRawValue); + } + + if (createMerchantWebhookRequest._PasswordOption.IsSet) + if (createMerchantWebhookRequest.Password != null) + writer.WriteString("password", createMerchantWebhookRequest.Password); + + if (createMerchantWebhookRequest._PopulateSoapActionHeaderOption.IsSet) + writer.WriteBoolean("populateSoapActionHeader", createMerchantWebhookRequest._PopulateSoapActionHeaderOption.Value!.Value); + + if (createMerchantWebhookRequest._UsernameOption.IsSet) + if (createMerchantWebhookRequest.Username != null) + writer.WriteString("username", createMerchantWebhookRequest.Username); + } + } +} diff --git a/Adyen/Management/Models/CreateUserResponse.cs b/Adyen/Management/Models/CreateUserResponse.cs new file mode 100644 index 000000000..4aebdf26f --- /dev/null +++ b/Adyen/Management/Models/CreateUserResponse.cs @@ -0,0 +1,389 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CreateUserResponse. + /// + public partial class CreateUserResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// The unique identifier of the user. + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// The username for this user. + /// links + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Indicates whether this user is active. + /// Set of apps available to this user + /// name + [JsonConstructor] + public CreateUserResponse(string email, string id, List roles, string timeZoneCode, string username, Option links = default, Option?> accountGroups = default, Option active = default, Option?> apps = default, Option name = default) + { + Email = email; + Id = id; + Roles = roles; + TimeZoneCode = timeZoneCode; + Username = username; + _LinksOption = links; + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _AppsOption = apps; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateUserResponse() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// The unique identifier of the user. + /// + /// The unique identifier of the user. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string TimeZoneCode { get; set; } + + /// + /// The username for this user. + /// + /// The username for this user. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates whether this user is active. + /// + /// Indicates whether this user is active. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AppsOption { get; private set; } + + /// + /// Set of apps available to this user + /// + /// Set of apps available to this user + [JsonPropertyName("apps")] + public List? Apps { get { return this._AppsOption; } set { this._AppsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateUserResponse {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Apps: ").Append(Apps).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateUserResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateUserResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option id = default; + Option?> roles = default; + Option timeZoneCode = default; + Option username = default; + Option links = default; + Option?> accountGroups = default; + Option active = default; + Option?> apps = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "apps": + apps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class CreateUserResponse.", nameof(email)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CreateUserResponse.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class CreateUserResponse.", nameof(roles)); + + if (!timeZoneCode.IsSet) + throw new ArgumentException("Property is required for class CreateUserResponse.", nameof(timeZoneCode)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class CreateUserResponse.", nameof(username)); + + return new CreateUserResponse(email.Value!, id.Value!, roles.Value!, timeZoneCode.Value!, username.Value!, links, accountGroups, active, apps, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateUserResponse createUserResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createUserResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateUserResponse createUserResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (createUserResponse.Email != null) + writer.WriteString("email", createUserResponse.Email); + + if (createUserResponse.Id != null) + writer.WriteString("id", createUserResponse.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, createUserResponse.Roles, jsonSerializerOptions); + if (createUserResponse.TimeZoneCode != null) + writer.WriteString("timeZoneCode", createUserResponse.TimeZoneCode); + + if (createUserResponse.Username != null) + writer.WriteString("username", createUserResponse.Username); + + if (createUserResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, createUserResponse.Links, jsonSerializerOptions); + } + if (createUserResponse._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, createUserResponse.AccountGroups, jsonSerializerOptions); + } + if (createUserResponse._ActiveOption.IsSet) + writer.WriteBoolean("active", createUserResponse._ActiveOption.Value!.Value); + + if (createUserResponse._AppsOption.IsSet) + { + writer.WritePropertyName("apps"); + JsonSerializer.Serialize(writer, createUserResponse.Apps, jsonSerializerOptions); + } + if (createUserResponse._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, createUserResponse.Name, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Currency.cs b/Adyen/Management/Models/Currency.cs new file mode 100644 index 000000000..9067d6720 --- /dev/null +++ b/Adyen/Management/Models/Currency.cs @@ -0,0 +1,243 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Currency. + /// + public partial class Currency : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, **AUD**. + /// Surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The maximum surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// Surcharge percentage per transaction. The maximum number of decimal places is two. For example, **1%** or **2.27%**. + [JsonConstructor] + public Currency(string currencyCode, Option amount = default, Option maxAmount = default, Option percentage = default) + { + CurrencyCode = currencyCode; + _AmountOption = amount; + _MaxAmountOption = maxAmount; + _PercentageOption = percentage; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Currency() + { + } + + partial void OnCreated(); + + /// + /// Three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, **AUD**. + /// + /// Three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, **AUD**. + [JsonPropertyName("currencyCode")] + public string CurrencyCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// Surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// Surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("amount")] + public int? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxAmountOption { get; private set; } + + /// + /// The maximum surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The maximum surcharge amount per transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("maxAmount")] + public int? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PercentageOption { get; private set; } + + /// + /// Surcharge percentage per transaction. The maximum number of decimal places is two. For example, **1%** or **2.27%**. + /// + /// Surcharge percentage per transaction. The maximum number of decimal places is two. For example, **1%** or **2.27%**. + [JsonPropertyName("percentage")] + public double? Percentage { get { return this._PercentageOption; } set { this._PercentageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Currency {\n"); + sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append(" Percentage: ").Append(Percentage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CurrencyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Currency Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currencyCode = default; + Option amount = default; + Option maxAmount = default; + Option percentage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currencyCode": + currencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "maxAmount": + maxAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "percentage": + percentage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (!currencyCode.IsSet) + throw new ArgumentException("Property is required for class Currency.", nameof(currencyCode)); + + return new Currency(currencyCode.Value!, amount, maxAmount, percentage); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Currency currency, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, currency, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Currency currency, JsonSerializerOptions jsonSerializerOptions) + { + + if (currency.CurrencyCode != null) + writer.WriteString("currencyCode", currency.CurrencyCode); + + if (currency._AmountOption.IsSet) + writer.WriteNumber("amount", currency._AmountOption.Value!.Value); + + if (currency._MaxAmountOption.IsSet) + writer.WriteNumber("maxAmount", currency._MaxAmountOption.Value!.Value); + + if (currency._PercentageOption.IsSet) + writer.WriteNumber("percentage", currency._PercentageOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/CustomNotification.cs b/Adyen/Management/Models/CustomNotification.cs new file mode 100644 index 000000000..d5d08099b --- /dev/null +++ b/Adyen/Management/Models/CustomNotification.cs @@ -0,0 +1,330 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// CustomNotification. + /// + public partial class CustomNotification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The event that caused the notification to be sent.Currently supported values: * **AUTHORISATION** * **CANCELLATION** * **REFUND** * **CAPTURE** * **REPORT_AVAILABLE** * **CHARGEBACK** * **REQUEST_FOR_INFORMATION** * **NOTIFICATION_OF_CHARGEBACK** * **NOTIFICATIONTEST** * **ORDER_OPENED** * **ORDER_CLOSED** * **CHARGEBACK_REVERSED** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** + /// The time of the event. Format: [ISO 8601](http://www.w3.org/TR/NOTE-datetime), YYYY-MM-DDThh:mm:ssTZD. + /// Your reference for the custom test notification. + /// The payment method for the payment that the notification is about. Possible values: * **amex** * **visa** * **mc** * **maestro** * **bcmc** * **paypal** * **sms** * **bankTransfer_NL** * **bankTransfer_DE** * **bankTransfer_BE** * **ideal** * **elv** * **sepadirectdebit** + /// A description of what caused the notification. + /// The outcome of the event which the notification is about. Set to either **true** or **false**. + [JsonConstructor] + public CustomNotification(Option amount = default, Option eventCode = default, Option eventDate = default, Option merchantReference = default, Option paymentMethod = default, Option reason = default, Option success = default) + { + _AmountOption = amount; + _EventCodeOption = eventCode; + _EventDateOption = eventDate; + _MerchantReferenceOption = merchantReference; + _PaymentMethodOption = paymentMethod; + _ReasonOption = reason; + _SuccessOption = success; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CustomNotification() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EventCodeOption { get; private set; } + + /// + /// The event that caused the notification to be sent.Currently supported values: * **AUTHORISATION** * **CANCELLATION** * **REFUND** * **CAPTURE** * **REPORT_AVAILABLE** * **CHARGEBACK** * **REQUEST_FOR_INFORMATION** * **NOTIFICATION_OF_CHARGEBACK** * **NOTIFICATIONTEST** * **ORDER_OPENED** * **ORDER_CLOSED** * **CHARGEBACK_REVERSED** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** + /// + /// The event that caused the notification to be sent.Currently supported values: * **AUTHORISATION** * **CANCELLATION** * **REFUND** * **CAPTURE** * **REPORT_AVAILABLE** * **CHARGEBACK** * **REQUEST_FOR_INFORMATION** * **NOTIFICATION_OF_CHARGEBACK** * **NOTIFICATIONTEST** * **ORDER_OPENED** * **ORDER_CLOSED** * **CHARGEBACK_REVERSED** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** + [JsonPropertyName("eventCode")] + public string? EventCode { get { return this._EventCodeOption; } set { this._EventCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EventDateOption { get; private set; } + + /// + /// The time of the event. Format: [ISO 8601](http://www.w3.org/TR/NOTE-datetime), YYYY-MM-DDThh:mm:ssTZD. + /// + /// The time of the event. Format: [ISO 8601](http://www.w3.org/TR/NOTE-datetime), YYYY-MM-DDThh:mm:ssTZD. + [JsonPropertyName("eventDate")] + public DateTimeOffset? EventDate { get { return this._EventDateOption; } set { this._EventDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// Your reference for the custom test notification. + /// + /// Your reference for the custom test notification. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// The payment method for the payment that the notification is about. Possible values: * **amex** * **visa** * **mc** * **maestro** * **bcmc** * **paypal** * **sms** * **bankTransfer_NL** * **bankTransfer_DE** * **bankTransfer_BE** * **ideal** * **elv** * **sepadirectdebit** + /// + /// The payment method for the payment that the notification is about. Possible values: * **amex** * **visa** * **mc** * **maestro** * **bcmc** * **paypal** * **sms** * **bankTransfer_NL** * **bankTransfer_DE** * **bankTransfer_BE** * **ideal** * **elv** * **sepadirectdebit** + [JsonPropertyName("paymentMethod")] + public string? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// A description of what caused the notification. + /// + /// A description of what caused the notification. + [JsonPropertyName("reason")] + public string? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuccessOption { get; private set; } + + /// + /// The outcome of the event which the notification is about. Set to either **true** or **false**. + /// + /// The outcome of the event which the notification is about. Set to either **true** or **false**. + [JsonPropertyName("success")] + public bool? Success { get { return this._SuccessOption; } set { this._SuccessOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CustomNotification {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" EventCode: ").Append(EventCode).Append("\n"); + sb.Append(" EventDate: ").Append(EventDate).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Success: ").Append(Success).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CustomNotificationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EventDate. + /// + public static string EventDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CustomNotification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option eventCode = default; + Option eventDate = default; + Option merchantReference = default; + Option paymentMethod = default; + Option reason = default; + Option success = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eventCode": + eventCode = new Option(utf8JsonReader.GetString()!); + break; + case "eventDate": + eventDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "reason": + reason = new Option(utf8JsonReader.GetString()!); + break; + case "success": + success = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new CustomNotification(amount, eventCode, eventDate, merchantReference, paymentMethod, reason, success); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CustomNotification customNotification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, customNotification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CustomNotification customNotification, JsonSerializerOptions jsonSerializerOptions) + { + + if (customNotification._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, customNotification.Amount, jsonSerializerOptions); + } + if (customNotification._EventCodeOption.IsSet) + if (customNotification.EventCode != null) + writer.WriteString("eventCode", customNotification.EventCode); + + if (customNotification._EventDateOption.IsSet) + writer.WriteString("eventDate", customNotification._EventDateOption.Value!.Value.ToString(EventDateFormat)); + + if (customNotification._MerchantReferenceOption.IsSet) + if (customNotification.MerchantReference != null) + writer.WriteString("merchantReference", customNotification.MerchantReference); + + if (customNotification._PaymentMethodOption.IsSet) + if (customNotification.PaymentMethod != null) + writer.WriteString("paymentMethod", customNotification.PaymentMethod); + + if (customNotification._ReasonOption.IsSet) + if (customNotification.Reason != null) + writer.WriteString("reason", customNotification.Reason); + + if (customNotification._SuccessOption.IsSet) + writer.WriteBoolean("success", customNotification._SuccessOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/DataCenter.cs b/Adyen/Management/Models/DataCenter.cs new file mode 100644 index 000000000..d3860235a --- /dev/null +++ b/Adyen/Management/Models/DataCenter.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// DataCenter. + /// + public partial class DataCenter : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique [live URL prefix](https://docs.adyen.com/development-resources/live-endpoints#live-url-prefix) for your live endpoint. Each data center has its own live URL prefix. This field is empty for requests made in the test environment. + /// The name assigned to a data center, for example **EU** for the European data center. Possible values are: * **default**: the European data center. This value is always returned in the test environment. * **AU** * **EU** * **US** + [JsonConstructor] + public DataCenter(Option livePrefix = default, Option name = default) + { + _LivePrefixOption = livePrefix; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DataCenter() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LivePrefixOption { get; private set; } + + /// + /// The unique [live URL prefix](https://docs.adyen.com/development-resources/live-endpoints#live-url-prefix) for your live endpoint. Each data center has its own live URL prefix. This field is empty for requests made in the test environment. + /// + /// The unique [live URL prefix](https://docs.adyen.com/development-resources/live-endpoints#live-url-prefix) for your live endpoint. Each data center has its own live URL prefix. This field is empty for requests made in the test environment. + [JsonPropertyName("livePrefix")] + public string? LivePrefix { get { return this._LivePrefixOption; } set { this._LivePrefixOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name assigned to a data center, for example **EU** for the European data center. Possible values are: * **default**: the European data center. This value is always returned in the test environment. * **AU** * **EU** * **US** + /// + /// The name assigned to a data center, for example **EU** for the European data center. Possible values are: * **default**: the European data center. This value is always returned in the test environment. * **AU** * **EU** * **US** + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DataCenter {\n"); + sb.Append(" LivePrefix: ").Append(LivePrefix).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DataCenterJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DataCenter Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option livePrefix = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "livePrefix": + livePrefix = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DataCenter(livePrefix, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DataCenter dataCenter, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dataCenter, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DataCenter dataCenter, JsonSerializerOptions jsonSerializerOptions) + { + + if (dataCenter._LivePrefixOption.IsSet) + if (dataCenter.LivePrefix != null) + writer.WriteString("livePrefix", dataCenter.LivePrefix); + + if (dataCenter._NameOption.IsSet) + if (dataCenter.Name != null) + writer.WriteString("name", dataCenter.Name); + } + } +} diff --git a/Adyen/Management/Models/DinersInfo.cs b/Adyen/Management/Models/DinersInfo.cs new file mode 100644 index 000000000..af5d3cd37 --- /dev/null +++ b/Adyen/Management/Models/DinersInfo.cs @@ -0,0 +1,358 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// DinersInfo. + /// + public partial class DinersInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan. Format: 14 numeric characters. + /// Indicates whether the JCB Merchant ID is reused from a previously configured JCB payment method. The default value is **false**. For merchants operating in Japan, this field is required and must be set to **true**. (default to false) + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB. * **gatewayContract**: JCB receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. + /// transactionDescription + [JsonConstructor] + public DinersInfo(Option midNumber = default, bool reuseMidNumber = false, Option serviceLevel = default, Option transactionDescription = default) + { + _MidNumberOption = midNumber; + ReuseMidNumber = reuseMidNumber; + _ServiceLevelOption = serviceLevel; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DinersInfo() + { + } + + partial void OnCreated(); + + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB. * **gatewayContract**: JCB receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB. * **gatewayContract**: JCB receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. + [JsonConverter(typeof(ServiceLevelEnumJsonConverter))] + public class ServiceLevelEnum : IEnum + { + /// + /// Returns the value of the ServiceLevelEnum. + /// + public string? Value { get; set; } + + /// + /// ServiceLevelEnum.NoContract - noContract + /// + public static readonly ServiceLevelEnum NoContract = new("noContract"); + + /// + /// ServiceLevelEnum.GatewayContract - gatewayContract + /// + public static readonly ServiceLevelEnum GatewayContract = new("gatewayContract"); + + private ServiceLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ServiceLevelEnum?(string? value) => value == null ? null : new ServiceLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ServiceLevelEnum? option) => option?.Value; + + public static bool operator ==(ServiceLevelEnum? left, ServiceLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ServiceLevelEnum? left, ServiceLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ServiceLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ServiceLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "noContract" => ServiceLevelEnum.NoContract, + "gatewayContract" => ServiceLevelEnum.GatewayContract, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ServiceLevelEnum? value) + { + if (value == null) + return null; + + if (value == ServiceLevelEnum.NoContract) + return "noContract"; + + if (value == ServiceLevelEnum.GatewayContract) + return "gatewayContract"; + + return null; + } + + /// + /// JsonConverter for writing ServiceLevelEnum. + /// + public class ServiceLevelEnumJsonConverter : JsonConverter + { + public override ServiceLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ServiceLevelEnum.FromStringOrDefault(value) ?? new ServiceLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ServiceLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ServiceLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ServiceLevelOption { get; private set; } + + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB. * **gatewayContract**: JCB receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB. * **gatewayContract**: JCB receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. + [JsonPropertyName("serviceLevel")] + public ServiceLevelEnum? ServiceLevel { get { return this._ServiceLevelOption; } set { this._ServiceLevelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MidNumberOption { get; private set; } + + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan. Format: 14 numeric characters. + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan. Format: 14 numeric characters. + [JsonPropertyName("midNumber")] + public string? MidNumber { get { return this._MidNumberOption; } set { this._MidNumberOption = new(value); } } + + /// + /// Indicates whether the JCB Merchant ID is reused from a previously configured JCB payment method. The default value is **false**. For merchants operating in Japan, this field is required and must be set to **true**. + /// + /// Indicates whether the JCB Merchant ID is reused from a previously configured JCB payment method. The default value is **false**. For merchants operating in Japan, this field is required and must be set to **true**. + [JsonPropertyName("reuseMidNumber")] + public bool ReuseMidNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DinersInfo {\n"); + sb.Append(" MidNumber: ").Append(MidNumber).Append("\n"); + sb.Append(" ReuseMidNumber: ").Append(ReuseMidNumber).Append("\n"); + sb.Append(" ServiceLevel: ").Append(ServiceLevel).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MidNumber (string) maxLength + if (this.MidNumber != null && this.MidNumber.Length > 14) + { + yield return new ValidationResult("Invalid value for MidNumber, length must be less than 14.", new [] { "MidNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DinersInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DinersInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option midNumber = default; + Option reuseMidNumber = default; + Option serviceLevel = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "midNumber": + midNumber = new Option(utf8JsonReader.GetString()!); + break; + case "reuseMidNumber": + reuseMidNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "serviceLevel": + string? serviceLevelRawValue = utf8JsonReader.GetString(); + serviceLevel = new Option(DinersInfo.ServiceLevelEnum.FromStringOrDefault(serviceLevelRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!reuseMidNumber.IsSet) + throw new ArgumentException("Property is required for class DinersInfo.", nameof(reuseMidNumber)); + + return new DinersInfo(midNumber, reuseMidNumber.Value!.Value!, serviceLevel, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DinersInfo dinersInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dinersInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DinersInfo dinersInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (dinersInfo._MidNumberOption.IsSet) + if (dinersInfo.MidNumber != null) + writer.WriteString("midNumber", dinersInfo.MidNumber); + + writer.WriteBoolean("reuseMidNumber", dinersInfo.ReuseMidNumber); + + if (dinersInfo._ServiceLevelOption.IsSet && dinersInfo.ServiceLevel != null) + { + string? serviceLevelRawValue = DinersInfo.ServiceLevelEnum.ToJsonValue(dinersInfo._ServiceLevelOption.Value!.Value); + writer.WriteString("serviceLevel", serviceLevelRawValue); + } + + if (dinersInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, dinersInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/EventUrl.cs b/Adyen/Management/Models/EventUrl.cs new file mode 100644 index 000000000..d6497ca93 --- /dev/null +++ b/Adyen/Management/Models/EventUrl.cs @@ -0,0 +1,205 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// EventUrl. + /// + public partial class EventUrl : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// One or more local URLs to send event notifications to when using Terminal API. + /// One or more public URLs to send event notifications to when using Terminal API. + [JsonConstructor] + public EventUrl(Option?> eventLocalUrls = default, Option?> eventPublicUrls = default) + { + _EventLocalUrlsOption = eventLocalUrls; + _EventPublicUrlsOption = eventPublicUrls; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EventUrl() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventLocalUrlsOption { get; private set; } + + /// + /// One or more local URLs to send event notifications to when using Terminal API. + /// + /// One or more local URLs to send event notifications to when using Terminal API. + [JsonPropertyName("eventLocalUrls")] + public List? EventLocalUrls { get { return this._EventLocalUrlsOption; } set { this._EventLocalUrlsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventPublicUrlsOption { get; private set; } + + /// + /// One or more public URLs to send event notifications to when using Terminal API. + /// + /// One or more public URLs to send event notifications to when using Terminal API. + [JsonPropertyName("eventPublicUrls")] + public List? EventPublicUrls { get { return this._EventPublicUrlsOption; } set { this._EventPublicUrlsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EventUrl {\n"); + sb.Append(" EventLocalUrls: ").Append(EventLocalUrls).Append("\n"); + sb.Append(" EventPublicUrls: ").Append(EventPublicUrls).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EventUrlJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EventUrl Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> eventLocalUrls = default; + Option?> eventPublicUrls = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "eventLocalUrls": + eventLocalUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eventPublicUrls": + eventPublicUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new EventUrl(eventLocalUrls, eventPublicUrls); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EventUrl eventUrl, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, eventUrl, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EventUrl eventUrl, JsonSerializerOptions jsonSerializerOptions) + { + + if (eventUrl._EventLocalUrlsOption.IsSet) + { + writer.WritePropertyName("eventLocalUrls"); + JsonSerializer.Serialize(writer, eventUrl.EventLocalUrls, jsonSerializerOptions); + } + if (eventUrl._EventPublicUrlsOption.IsSet) + { + writer.WritePropertyName("eventPublicUrls"); + JsonSerializer.Serialize(writer, eventUrl.EventPublicUrls, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ExternalTerminalAction.cs b/Adyen/Management/Models/ExternalTerminalAction.cs new file mode 100644 index 000000000..1f94586ed --- /dev/null +++ b/Adyen/Management/Models/ExternalTerminalAction.cs @@ -0,0 +1,360 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ExternalTerminalAction. + /// + public partial class ExternalTerminalAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of terminal action: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, or **UninstallAndroidCertificate**. + /// Technical information about the terminal action. + /// The date and time when the action was carried out. + /// The unique ID of the terminal action. + /// The result message for the action. + /// The date and time when the action was scheduled to happen. + /// The status of the terminal action: **pending**, **successful**, **failed**, **cancelled**, or **tryLater**. + /// The unique ID of the terminal that the action applies to. + [JsonConstructor] + public ExternalTerminalAction(Option actionType = default, Option config = default, Option confirmedAt = default, Option id = default, Option result = default, Option scheduledAt = default, Option status = default, Option terminalId = default) + { + _ActionTypeOption = actionType; + _ConfigOption = config; + _ConfirmedAtOption = confirmedAt; + _IdOption = id; + _ResultOption = result; + _ScheduledAtOption = scheduledAt; + _StatusOption = status; + _TerminalIdOption = terminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExternalTerminalAction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActionTypeOption { get; private set; } + + /// + /// The type of terminal action: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, or **UninstallAndroidCertificate**. + /// + /// The type of terminal action: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, or **UninstallAndroidCertificate**. + [JsonPropertyName("actionType")] + public string? ActionType { get { return this._ActionTypeOption; } set { this._ActionTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConfigOption { get; private set; } + + /// + /// Technical information about the terminal action. + /// + /// Technical information about the terminal action. + [JsonPropertyName("config")] + public string? Config { get { return this._ConfigOption; } set { this._ConfigOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConfirmedAtOption { get; private set; } + + /// + /// The date and time when the action was carried out. + /// + /// The date and time when the action was carried out. + [JsonPropertyName("confirmedAt")] + public DateTimeOffset? ConfirmedAt { get { return this._ConfirmedAtOption; } set { this._ConfirmedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique ID of the terminal action. + /// + /// The unique ID of the terminal action. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The result message for the action. + /// + /// The result message for the action. + [JsonPropertyName("result")] + public string? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScheduledAtOption { get; private set; } + + /// + /// The date and time when the action was scheduled to happen. + /// + /// The date and time when the action was scheduled to happen. + [JsonPropertyName("scheduledAt")] + public DateTimeOffset? ScheduledAt { get { return this._ScheduledAtOption; } set { this._ScheduledAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the terminal action: **pending**, **successful**, **failed**, **cancelled**, or **tryLater**. + /// + /// The status of the terminal action: **pending**, **successful**, **failed**, **cancelled**, or **tryLater**. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The unique ID of the terminal that the action applies to. + /// + /// The unique ID of the terminal that the action applies to. + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExternalTerminalAction {\n"); + sb.Append(" ActionType: ").Append(ActionType).Append("\n"); + sb.Append(" Config: ").Append(Config).Append("\n"); + sb.Append(" ConfirmedAt: ").Append(ConfirmedAt).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" ScheduledAt: ").Append(ScheduledAt).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExternalTerminalActionJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ConfirmedAt. + /// + public static string ConfirmedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ScheduledAt. + /// + public static string ScheduledAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExternalTerminalAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option actionType = default; + Option config = default; + Option confirmedAt = default; + Option id = default; + Option result = default; + Option scheduledAt = default; + Option status = default; + Option terminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "actionType": + actionType = new Option(utf8JsonReader.GetString()!); + break; + case "config": + config = new Option(utf8JsonReader.GetString()!); + break; + case "confirmedAt": + confirmedAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + case "scheduledAt": + scheduledAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExternalTerminalAction(actionType, config, confirmedAt, id, result, scheduledAt, status, terminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExternalTerminalAction externalTerminalAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, externalTerminalAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExternalTerminalAction externalTerminalAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (externalTerminalAction._ActionTypeOption.IsSet) + if (externalTerminalAction.ActionType != null) + writer.WriteString("actionType", externalTerminalAction.ActionType); + + if (externalTerminalAction._ConfigOption.IsSet) + if (externalTerminalAction.Config != null) + writer.WriteString("config", externalTerminalAction.Config); + + if (externalTerminalAction._ConfirmedAtOption.IsSet) + writer.WriteString("confirmedAt", externalTerminalAction._ConfirmedAtOption.Value!.Value.ToString(ConfirmedAtFormat)); + + if (externalTerminalAction._IdOption.IsSet) + if (externalTerminalAction.Id != null) + writer.WriteString("id", externalTerminalAction.Id); + + if (externalTerminalAction._ResultOption.IsSet) + if (externalTerminalAction.Result != null) + writer.WriteString("result", externalTerminalAction.Result); + + if (externalTerminalAction._ScheduledAtOption.IsSet) + writer.WriteString("scheduledAt", externalTerminalAction._ScheduledAtOption.Value!.Value.ToString(ScheduledAtFormat)); + + if (externalTerminalAction._StatusOption.IsSet) + if (externalTerminalAction.Status != null) + writer.WriteString("status", externalTerminalAction.Status); + + if (externalTerminalAction._TerminalIdOption.IsSet) + if (externalTerminalAction.TerminalId != null) + writer.WriteString("terminalId", externalTerminalAction.TerminalId); + } + } +} diff --git a/Adyen/Management/Models/File.cs b/Adyen/Management/Models/File.cs new file mode 100644 index 000000000..14cf8cc42 --- /dev/null +++ b/Adyen/Management/Models/File.cs @@ -0,0 +1,191 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// File. + /// + public partial class File : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The certificate content converted to a Base64-encoded string. + /// The name of the certificate. Must be unique across Wi-Fi profiles. + [JsonConstructor] + public File(string data, string name) + { + Data = data; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public File() + { + } + + partial void OnCreated(); + + /// + /// The certificate content converted to a Base64-encoded string. + /// + /// The certificate content converted to a Base64-encoded string. + [JsonPropertyName("data")] + public string Data { get; set; } + + /// + /// The name of the certificate. Must be unique across Wi-Fi profiles. + /// + /// The name of the certificate. Must be unique across Wi-Fi profiles. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class File {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FileJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class File.", nameof(data)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class File.", nameof(name)); + + return new File(data.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, file, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) + { + + if (file.Data != null) + writer.WriteString("data", file.Data); + + if (file.Name != null) + writer.WriteString("name", file.Name); + } + } +} diff --git a/Adyen/Management/Models/GenerateApiKeyResponse.cs b/Adyen/Management/Models/GenerateApiKeyResponse.cs new file mode 100644 index 000000000..9f66fe7e4 --- /dev/null +++ b/Adyen/Management/Models/GenerateApiKeyResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// GenerateApiKeyResponse. + /// + public partial class GenerateApiKeyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The generated API key. + [JsonConstructor] + public GenerateApiKeyResponse(string apiKey) + { + ApiKey = apiKey; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GenerateApiKeyResponse() + { + } + + partial void OnCreated(); + + /// + /// The generated API key. + /// + /// The generated API key. + [JsonPropertyName("apiKey")] + public string ApiKey { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GenerateApiKeyResponse {\n"); + sb.Append(" ApiKey: ").Append(ApiKey).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GenerateApiKeyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GenerateApiKeyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option apiKey = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "apiKey": + apiKey = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!apiKey.IsSet) + throw new ArgumentException("Property is required for class GenerateApiKeyResponse.", nameof(apiKey)); + + return new GenerateApiKeyResponse(apiKey.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GenerateApiKeyResponse generateApiKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, generateApiKeyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GenerateApiKeyResponse generateApiKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (generateApiKeyResponse.ApiKey != null) + writer.WriteString("apiKey", generateApiKeyResponse.ApiKey); + } + } +} diff --git a/Adyen/Management/Models/GenerateClientKeyResponse.cs b/Adyen/Management/Models/GenerateClientKeyResponse.cs new file mode 100644 index 000000000..2923f63ce --- /dev/null +++ b/Adyen/Management/Models/GenerateClientKeyResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// GenerateClientKeyResponse. + /// + public partial class GenerateClientKeyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Generated client key + [JsonConstructor] + public GenerateClientKeyResponse(string clientKey) + { + ClientKey = clientKey; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GenerateClientKeyResponse() + { + } + + partial void OnCreated(); + + /// + /// Generated client key + /// + /// Generated client key + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GenerateClientKeyResponse {\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GenerateClientKeyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GenerateClientKeyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option clientKey = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class GenerateClientKeyResponse.", nameof(clientKey)); + + return new GenerateClientKeyResponse(clientKey.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GenerateClientKeyResponse generateClientKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, generateClientKeyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GenerateClientKeyResponse generateClientKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (generateClientKeyResponse.ClientKey != null) + writer.WriteString("clientKey", generateClientKeyResponse.ClientKey); + } + } +} diff --git a/Adyen/Management/Models/GenerateHmacKeyResponse.cs b/Adyen/Management/Models/GenerateHmacKeyResponse.cs new file mode 100644 index 000000000..2fde0ab68 --- /dev/null +++ b/Adyen/Management/Models/GenerateHmacKeyResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// GenerateHmacKeyResponse. + /// + public partial class GenerateHmacKeyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The HMAC key generated for this webhook. + [JsonConstructor] + public GenerateHmacKeyResponse(string hmacKey) + { + HmacKey = hmacKey; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GenerateHmacKeyResponse() + { + } + + partial void OnCreated(); + + /// + /// The HMAC key generated for this webhook. + /// + /// The HMAC key generated for this webhook. + [JsonPropertyName("hmacKey")] + public string HmacKey { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GenerateHmacKeyResponse {\n"); + sb.Append(" HmacKey: ").Append(HmacKey).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GenerateHmacKeyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GenerateHmacKeyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option hmacKey = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "hmacKey": + hmacKey = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!hmacKey.IsSet) + throw new ArgumentException("Property is required for class GenerateHmacKeyResponse.", nameof(hmacKey)); + + return new GenerateHmacKeyResponse(hmacKey.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GenerateHmacKeyResponse generateHmacKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, generateHmacKeyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GenerateHmacKeyResponse generateHmacKeyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (generateHmacKeyResponse.HmacKey != null) + writer.WriteString("hmacKey", generateHmacKeyResponse.HmacKey); + } + } +} diff --git a/Adyen/Management/Models/GenericPmWithTdiInfo.cs b/Adyen/Management/Models/GenericPmWithTdiInfo.cs new file mode 100644 index 000000000..a296fa39f --- /dev/null +++ b/Adyen/Management/Models/GenericPmWithTdiInfo.cs @@ -0,0 +1,178 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// GenericPmWithTdiInfo. + /// + public partial class GenericPmWithTdiInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// transactionDescription + [JsonConstructor] + public GenericPmWithTdiInfo(Option transactionDescription = default) + { + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GenericPmWithTdiInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GenericPmWithTdiInfo {\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GenericPmWithTdiInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GenericPmWithTdiInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new GenericPmWithTdiInfo(transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GenericPmWithTdiInfo genericPmWithTdiInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, genericPmWithTdiInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GenericPmWithTdiInfo genericPmWithTdiInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (genericPmWithTdiInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, genericPmWithTdiInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/GooglePayInfo.cs b/Adyen/Management/Models/GooglePayInfo.cs new file mode 100644 index 000000000..b53f920f5 --- /dev/null +++ b/Adyen/Management/Models/GooglePayInfo.cs @@ -0,0 +1,207 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// GooglePayInfo. + /// + public partial class GooglePayInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Google Pay [Merchant ID](https://support.google.com/paymentscenter/answer/7163092?hl=en). Character length and limitations: 16 alphanumeric characters or 20 numeric characters. + /// Indicates whether the Google Pay Merchant ID is used for several merchant accounts. Default value: **false**. + [JsonConstructor] + public GooglePayInfo(string merchantId, Option reuseMerchantId = default) + { + MerchantId = merchantId; + _ReuseMerchantIdOption = reuseMerchantId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public GooglePayInfo() + { + } + + partial void OnCreated(); + + /// + /// Google Pay [Merchant ID](https://support.google.com/paymentscenter/answer/7163092?hl=en). Character length and limitations: 16 alphanumeric characters or 20 numeric characters. + /// + /// Google Pay [Merchant ID](https://support.google.com/paymentscenter/answer/7163092?hl=en). Character length and limitations: 16 alphanumeric characters or 20 numeric characters. + [JsonPropertyName("merchantId")] + public string MerchantId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReuseMerchantIdOption { get; private set; } + + /// + /// Indicates whether the Google Pay Merchant ID is used for several merchant accounts. Default value: **false**. + /// + /// Indicates whether the Google Pay Merchant ID is used for several merchant accounts. Default value: **false**. + [JsonPropertyName("reuseMerchantId")] + public bool? ReuseMerchantId { get { return this._ReuseMerchantIdOption; } set { this._ReuseMerchantIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GooglePayInfo {\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" ReuseMerchantId: ").Append(ReuseMerchantId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MerchantId (string) maxLength + if (this.MerchantId != null && this.MerchantId.Length > 20) + { + yield return new ValidationResult("Invalid value for MerchantId, length must be less than 20.", new [] { "MerchantId" }); + } + + // MerchantId (string) minLength + if (this.MerchantId != null && this.MerchantId.Length < 16) + { + yield return new ValidationResult("Invalid value for MerchantId, length must be greater than 16.", new [] { "MerchantId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GooglePayInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override GooglePayInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantId = default; + Option reuseMerchantId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "reuseMerchantId": + reuseMerchantId = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!merchantId.IsSet) + throw new ArgumentException("Property is required for class GooglePayInfo.", nameof(merchantId)); + + return new GooglePayInfo(merchantId.Value!, reuseMerchantId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, GooglePayInfo googlePayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, googlePayInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, GooglePayInfo googlePayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (googlePayInfo.MerchantId != null) + writer.WriteString("merchantId", googlePayInfo.MerchantId); + + if (googlePayInfo._ReuseMerchantIdOption.IsSet) + writer.WriteBoolean("reuseMerchantId", googlePayInfo._ReuseMerchantIdOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Gratuity.cs b/Adyen/Management/Models/Gratuity.cs new file mode 100644 index 000000000..babdc0e8e --- /dev/null +++ b/Adyen/Management/Models/Gratuity.cs @@ -0,0 +1,251 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Gratuity. + /// + public partial class Gratuity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether one of the predefined tipping options is to let the shopper enter a custom tip. If **true**, only three of the other options defined in `predefinedTipEntries` are shown. + /// The currency that the tipping settings apply to. + /// Tipping options the shopper can choose from if `usePredefinedTipEntries` is **true**. The maximum number of predefined options is four, or three plus the option to enter a custom tip. The options can be a mix of: - A percentage of the transaction amount. Example: **5%** - A tip amount in [minor units](https://docs.adyen.com/development-resources/currency-codes). Example: **500** for a EUR 5 tip. + /// Indicates whether the terminal shows a prompt to enter a tip (**false**), or predefined tipping options to choose from (**true**). + [JsonConstructor] + public Gratuity(Option allowCustomAmount = default, Option currency = default, Option?> predefinedTipEntries = default, Option usePredefinedTipEntries = default) + { + _AllowCustomAmountOption = allowCustomAmount; + _CurrencyOption = currency; + _PredefinedTipEntriesOption = predefinedTipEntries; + _UsePredefinedTipEntriesOption = usePredefinedTipEntries; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Gratuity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowCustomAmountOption { get; private set; } + + /// + /// Indicates whether one of the predefined tipping options is to let the shopper enter a custom tip. If **true**, only three of the other options defined in `predefinedTipEntries` are shown. + /// + /// Indicates whether one of the predefined tipping options is to let the shopper enter a custom tip. If **true**, only three of the other options defined in `predefinedTipEntries` are shown. + [JsonPropertyName("allowCustomAmount")] + public bool? AllowCustomAmount { get { return this._AllowCustomAmountOption; } set { this._AllowCustomAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The currency that the tipping settings apply to. + /// + /// The currency that the tipping settings apply to. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PredefinedTipEntriesOption { get; private set; } + + /// + /// Tipping options the shopper can choose from if `usePredefinedTipEntries` is **true**. The maximum number of predefined options is four, or three plus the option to enter a custom tip. The options can be a mix of: - A percentage of the transaction amount. Example: **5%** - A tip amount in [minor units](https://docs.adyen.com/development-resources/currency-codes). Example: **500** for a EUR 5 tip. + /// + /// Tipping options the shopper can choose from if `usePredefinedTipEntries` is **true**. The maximum number of predefined options is four, or three plus the option to enter a custom tip. The options can be a mix of: - A percentage of the transaction amount. Example: **5%** - A tip amount in [minor units](https://docs.adyen.com/development-resources/currency-codes). Example: **500** for a EUR 5 tip. + [JsonPropertyName("predefinedTipEntries")] + public List? PredefinedTipEntries { get { return this._PredefinedTipEntriesOption; } set { this._PredefinedTipEntriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsePredefinedTipEntriesOption { get; private set; } + + /// + /// Indicates whether the terminal shows a prompt to enter a tip (**false**), or predefined tipping options to choose from (**true**). + /// + /// Indicates whether the terminal shows a prompt to enter a tip (**false**), or predefined tipping options to choose from (**true**). + [JsonPropertyName("usePredefinedTipEntries")] + public bool? UsePredefinedTipEntries { get { return this._UsePredefinedTipEntriesOption; } set { this._UsePredefinedTipEntriesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Gratuity {\n"); + sb.Append(" AllowCustomAmount: ").Append(AllowCustomAmount).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" PredefinedTipEntries: ").Append(PredefinedTipEntries).Append("\n"); + sb.Append(" UsePredefinedTipEntries: ").Append(UsePredefinedTipEntries).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class GratuityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Gratuity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowCustomAmount = default; + Option currency = default; + Option?> predefinedTipEntries = default; + Option usePredefinedTipEntries = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowCustomAmount": + allowCustomAmount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "predefinedTipEntries": + predefinedTipEntries = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "usePredefinedTipEntries": + usePredefinedTipEntries = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Gratuity(allowCustomAmount, currency, predefinedTipEntries, usePredefinedTipEntries); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Gratuity gratuity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, gratuity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Gratuity gratuity, JsonSerializerOptions jsonSerializerOptions) + { + + if (gratuity._AllowCustomAmountOption.IsSet) + writer.WriteBoolean("allowCustomAmount", gratuity._AllowCustomAmountOption.Value!.Value); + + if (gratuity._CurrencyOption.IsSet) + if (gratuity.Currency != null) + writer.WriteString("currency", gratuity.Currency); + + if (gratuity._PredefinedTipEntriesOption.IsSet) + { + writer.WritePropertyName("predefinedTipEntries"); + JsonSerializer.Serialize(writer, gratuity.PredefinedTipEntries, jsonSerializerOptions); + } + if (gratuity._UsePredefinedTipEntriesOption.IsSet) + writer.WriteBoolean("usePredefinedTipEntries", gratuity._UsePredefinedTipEntriesOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Hardware.cs b/Adyen/Management/Models/Hardware.cs new file mode 100644 index 000000000..d557ae0b0 --- /dev/null +++ b/Adyen/Management/Models/Hardware.cs @@ -0,0 +1,224 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Hardware. + /// + public partial class Hardware : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The brightness of the display when the terminal is being used, expressed as a percentage. + /// The hour of the day when the terminal is set to reset the Totals report. By default, the reset hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + /// The hour of the day when the terminal is set to reboot to apply the configuration and software updates. By default, the restart hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + [JsonConstructor] + public Hardware(Option displayMaximumBackLight = default, Option resetTotalsHour = default, Option restartHour = default) + { + _DisplayMaximumBackLightOption = displayMaximumBackLight; + _ResetTotalsHourOption = resetTotalsHour; + _RestartHourOption = restartHour; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Hardware() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisplayMaximumBackLightOption { get; private set; } + + /// + /// The brightness of the display when the terminal is being used, expressed as a percentage. + /// + /// The brightness of the display when the terminal is being used, expressed as a percentage. + [JsonPropertyName("displayMaximumBackLight")] + public int? DisplayMaximumBackLight { get { return this._DisplayMaximumBackLightOption; } set { this._DisplayMaximumBackLightOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResetTotalsHourOption { get; private set; } + + /// + /// The hour of the day when the terminal is set to reset the Totals report. By default, the reset hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + /// + /// The hour of the day when the terminal is set to reset the Totals report. By default, the reset hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + [JsonPropertyName("resetTotalsHour")] + public int? ResetTotalsHour { get { return this._ResetTotalsHourOption; } set { this._ResetTotalsHourOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RestartHourOption { get; private set; } + + /// + /// The hour of the day when the terminal is set to reboot to apply the configuration and software updates. By default, the restart hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + /// + /// The hour of the day when the terminal is set to reboot to apply the configuration and software updates. By default, the restart hour is at 6:00 AM in the timezone of the terminal. Minimum value: 0, maximum value: 23. + [JsonPropertyName("restartHour")] + public int? RestartHour { get { return this._RestartHourOption; } set { this._RestartHourOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Hardware {\n"); + sb.Append(" DisplayMaximumBackLight: ").Append(DisplayMaximumBackLight).Append("\n"); + sb.Append(" ResetTotalsHour: ").Append(ResetTotalsHour).Append("\n"); + sb.Append(" RestartHour: ").Append(RestartHour).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HardwareJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Hardware Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option displayMaximumBackLight = default; + Option resetTotalsHour = default; + Option restartHour = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "displayMaximumBackLight": + displayMaximumBackLight = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "resetTotalsHour": + resetTotalsHour = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "restartHour": + restartHour = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Hardware(displayMaximumBackLight, resetTotalsHour, restartHour); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Hardware hardware, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hardware, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Hardware hardware, JsonSerializerOptions jsonSerializerOptions) + { + + if (hardware._DisplayMaximumBackLightOption.IsSet) + writer.WriteNumber("displayMaximumBackLight", hardware._DisplayMaximumBackLightOption.Value!.Value); + + if (hardware._ResetTotalsHourOption.IsSet) + writer.WriteNumber("resetTotalsHour", hardware._ResetTotalsHourOption.Value!.Value); + + if (hardware._RestartHourOption.IsSet) + writer.WriteNumber("restartHour", hardware._RestartHourOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/IdName.cs b/Adyen/Management/Models/IdName.cs new file mode 100644 index 000000000..7cee163e4 --- /dev/null +++ b/Adyen/Management/Models/IdName.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// IdName. + /// + public partial class IdName : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the terminal model. + /// The name of the terminal model. + [JsonConstructor] + public IdName(Option id = default, Option name = default) + { + _IdOption = id; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IdName() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The identifier of the terminal model. + /// + /// The identifier of the terminal model. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the terminal model. + /// + /// The name of the terminal model. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IdName {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IdNameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IdName Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new IdName(id, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IdName idName, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, idName, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IdName idName, JsonSerializerOptions jsonSerializerOptions) + { + + if (idName._IdOption.IsSet) + if (idName.Id != null) + writer.WriteString("id", idName.Id); + + if (idName._NameOption.IsSet) + if (idName.Name != null) + writer.WriteString("name", idName.Name); + } + } +} diff --git a/Adyen/Management/Models/InstallAndroidAppDetails.cs b/Adyen/Management/Models/InstallAndroidAppDetails.cs new file mode 100644 index 000000000..818b5b0f1 --- /dev/null +++ b/Adyen/Management/Models/InstallAndroidAppDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// InstallAndroidAppDetails. + /// + public partial class InstallAndroidAppDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the app to be installed. + /// Type of terminal action: Install an Android app. (default to TypeEnum.InstallAndroidApp) + [JsonConstructor] + public InstallAndroidAppDetails(Option appId = default, Option type = default) + { + _AppIdOption = appId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InstallAndroidAppDetails() + { + } + + partial void OnCreated(); + + /// + /// Type of terminal action: Install an Android app. + /// + /// Type of terminal action: Install an Android app. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.InstallAndroidApp - InstallAndroidApp + /// + public static readonly TypeEnum InstallAndroidApp = new("InstallAndroidApp"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "InstallAndroidApp" => TypeEnum.InstallAndroidApp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.InstallAndroidApp) + return "InstallAndroidApp"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of terminal action: Install an Android app. + /// + /// Type of terminal action: Install an Android app. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AppIdOption { get; private set; } + + /// + /// The unique identifier of the app to be installed. + /// + /// The unique identifier of the app to be installed. + [JsonPropertyName("appId")] + public string? AppId { get { return this._AppIdOption; } set { this._AppIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InstallAndroidAppDetails {\n"); + sb.Append(" AppId: ").Append(AppId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InstallAndroidAppDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InstallAndroidAppDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option appId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "appId": + appId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InstallAndroidAppDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new InstallAndroidAppDetails(appId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InstallAndroidAppDetails installAndroidAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, installAndroidAppDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InstallAndroidAppDetails installAndroidAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (installAndroidAppDetails._AppIdOption.IsSet) + if (installAndroidAppDetails.AppId != null) + writer.WriteString("appId", installAndroidAppDetails.AppId); + + if (installAndroidAppDetails._TypeOption.IsSet && installAndroidAppDetails.Type != null) + { + string? typeRawValue = InstallAndroidAppDetails.TypeEnum.ToJsonValue(installAndroidAppDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/InstallAndroidCertificateDetails.cs b/Adyen/Management/Models/InstallAndroidCertificateDetails.cs new file mode 100644 index 000000000..6af894c9f --- /dev/null +++ b/Adyen/Management/Models/InstallAndroidCertificateDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// InstallAndroidCertificateDetails. + /// + public partial class InstallAndroidCertificateDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the certificate to be installed. + /// Type of terminal action: Install an Android certificate. (default to TypeEnum.InstallAndroidCertificate) + [JsonConstructor] + public InstallAndroidCertificateDetails(Option certificateId = default, Option type = default) + { + _CertificateIdOption = certificateId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InstallAndroidCertificateDetails() + { + } + + partial void OnCreated(); + + /// + /// Type of terminal action: Install an Android certificate. + /// + /// Type of terminal action: Install an Android certificate. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.InstallAndroidCertificate - InstallAndroidCertificate + /// + public static readonly TypeEnum InstallAndroidCertificate = new("InstallAndroidCertificate"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "InstallAndroidCertificate" => TypeEnum.InstallAndroidCertificate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.InstallAndroidCertificate) + return "InstallAndroidCertificate"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of terminal action: Install an Android certificate. + /// + /// Type of terminal action: Install an Android certificate. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CertificateIdOption { get; private set; } + + /// + /// The unique identifier of the certificate to be installed. + /// + /// The unique identifier of the certificate to be installed. + [JsonPropertyName("certificateId")] + public string? CertificateId { get { return this._CertificateIdOption; } set { this._CertificateIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InstallAndroidCertificateDetails {\n"); + sb.Append(" CertificateId: ").Append(CertificateId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InstallAndroidCertificateDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InstallAndroidCertificateDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option certificateId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "certificateId": + certificateId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InstallAndroidCertificateDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new InstallAndroidCertificateDetails(certificateId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InstallAndroidCertificateDetails installAndroidCertificateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, installAndroidCertificateDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InstallAndroidCertificateDetails installAndroidCertificateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (installAndroidCertificateDetails._CertificateIdOption.IsSet) + if (installAndroidCertificateDetails.CertificateId != null) + writer.WriteString("certificateId", installAndroidCertificateDetails.CertificateId); + + if (installAndroidCertificateDetails._TypeOption.IsSet && installAndroidCertificateDetails.Type != null) + { + string? typeRawValue = InstallAndroidCertificateDetails.TypeEnum.ToJsonValue(installAndroidCertificateDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/InvalidField.cs b/Adyen/Management/Models/InvalidField.cs new file mode 100644 index 000000000..64990b9d1 --- /dev/null +++ b/Adyen/Management/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Description of the validation error. + /// The field that has an invalid value. + /// The invalid value. + [JsonConstructor] + public InvalidField(string message, string name, string value) + { + Message = message; + Name = name; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option message = default; + Option name = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + return new InvalidField(message.Value!, name.Value!, value.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + } + } +} diff --git a/Adyen/Management/Models/JCBInfo.cs b/Adyen/Management/Models/JCBInfo.cs new file mode 100644 index 000000000..10db40f11 --- /dev/null +++ b/Adyen/Management/Models/JCBInfo.cs @@ -0,0 +1,373 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// JCBInfo. + /// + public partial class JCBInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan or merchants operating in Canada, Australia and New Zealand when requesting `gatewayContract` or `paymentDesignatorContract` service levels.Format: 14 numeric characters for Japan, 10 numeric characters for Canada, Australia and New Zealand. + /// Indicates whether the JCB Merchant ID is reused from a previously setup JCB payment method. The default value is **false**.For merchants operating in Japan, this field is required and must be set to **true**. (default to false) + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB for merchants operating in Japan or American Express for merchants operating in Canada, Australia and New Zealand. * **gatewayContract**: JCB or American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Available only for merchants operating in Canada, Australia and New Zealand. Adyen receives the settlement, and handles disputes and payouts. + /// transactionDescription + [JsonConstructor] + public JCBInfo(Option midNumber = default, Option reuseMidNumber = default, Option serviceLevel = default, Option transactionDescription = default) + { + _MidNumberOption = midNumber; + _ReuseMidNumberOption = reuseMidNumber; + _ServiceLevelOption = serviceLevel; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public JCBInfo() + { + } + + partial void OnCreated(); + + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB for merchants operating in Japan or American Express for merchants operating in Canada, Australia and New Zealand. * **gatewayContract**: JCB or American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Available only for merchants operating in Canada, Australia and New Zealand. Adyen receives the settlement, and handles disputes and payouts. + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB for merchants operating in Japan or American Express for merchants operating in Canada, Australia and New Zealand. * **gatewayContract**: JCB or American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Available only for merchants operating in Canada, Australia and New Zealand. Adyen receives the settlement, and handles disputes and payouts. + [JsonConverter(typeof(ServiceLevelEnumJsonConverter))] + public class ServiceLevelEnum : IEnum + { + /// + /// Returns the value of the ServiceLevelEnum. + /// + public string? Value { get; set; } + + /// + /// ServiceLevelEnum.NoContract - noContract + /// + public static readonly ServiceLevelEnum NoContract = new("noContract"); + + /// + /// ServiceLevelEnum.GatewayContract - gatewayContract + /// + public static readonly ServiceLevelEnum GatewayContract = new("gatewayContract"); + + /// + /// ServiceLevelEnum.PaymentDesignatorContract - paymentDesignatorContract + /// + public static readonly ServiceLevelEnum PaymentDesignatorContract = new("paymentDesignatorContract"); + + private ServiceLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ServiceLevelEnum?(string? value) => value == null ? null : new ServiceLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ServiceLevelEnum? option) => option?.Value; + + public static bool operator ==(ServiceLevelEnum? left, ServiceLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ServiceLevelEnum? left, ServiceLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ServiceLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ServiceLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "noContract" => ServiceLevelEnum.NoContract, + "gatewayContract" => ServiceLevelEnum.GatewayContract, + "paymentDesignatorContract" => ServiceLevelEnum.PaymentDesignatorContract, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ServiceLevelEnum? value) + { + if (value == null) + return null; + + if (value == ServiceLevelEnum.NoContract) + return "noContract"; + + if (value == ServiceLevelEnum.GatewayContract) + return "gatewayContract"; + + if (value == ServiceLevelEnum.PaymentDesignatorContract) + return "paymentDesignatorContract"; + + return null; + } + + /// + /// JsonConverter for writing ServiceLevelEnum. + /// + public class ServiceLevelEnumJsonConverter : JsonConverter + { + public override ServiceLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ServiceLevelEnum.FromStringOrDefault(value) ?? new ServiceLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ServiceLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ServiceLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ServiceLevelOption { get; private set; } + + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB for merchants operating in Japan or American Express for merchants operating in Canada, Australia and New Zealand. * **gatewayContract**: JCB or American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Available only for merchants operating in Canada, Australia and New Zealand. Adyen receives the settlement, and handles disputes and payouts. + /// + /// Specifies the service level (settlement type) of this payment method. Required for merchants operating in Japan. Possible values: * **noContract**: Adyen holds the contract with JCB for merchants operating in Japan or American Express for merchants operating in Canada, Australia and New Zealand. * **gatewayContract**: JCB or American Express receives the settlement and handles disputes, then pays out to you or your sub-merchant directly. * **paymentDesignatorContract**: Available only for merchants operating in Canada, Australia and New Zealand. Adyen receives the settlement, and handles disputes and payouts. + [JsonPropertyName("serviceLevel")] + public ServiceLevelEnum? ServiceLevel { get { return this._ServiceLevelOption; } set { this._ServiceLevelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MidNumberOption { get; private set; } + + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan or merchants operating in Canada, Australia and New Zealand when requesting `gatewayContract` or `paymentDesignatorContract` service levels.Format: 14 numeric characters for Japan, 10 numeric characters for Canada, Australia and New Zealand. + /// + /// MID (Merchant ID) number. Required for merchants operating in Japan or merchants operating in Canada, Australia and New Zealand when requesting `gatewayContract` or `paymentDesignatorContract` service levels.Format: 14 numeric characters for Japan, 10 numeric characters for Canada, Australia and New Zealand. + [JsonPropertyName("midNumber")] + public string? MidNumber { get { return this._MidNumberOption; } set { this._MidNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReuseMidNumberOption { get; private set; } + + /// + /// Indicates whether the JCB Merchant ID is reused from a previously setup JCB payment method. The default value is **false**.For merchants operating in Japan, this field is required and must be set to **true**. + /// + /// Indicates whether the JCB Merchant ID is reused from a previously setup JCB payment method. The default value is **false**.For merchants operating in Japan, this field is required and must be set to **true**. + [JsonPropertyName("reuseMidNumber")] + public bool? ReuseMidNumber { get { return this._ReuseMidNumberOption; } set { this._ReuseMidNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class JCBInfo {\n"); + sb.Append(" MidNumber: ").Append(MidNumber).Append("\n"); + sb.Append(" ReuseMidNumber: ").Append(ReuseMidNumber).Append("\n"); + sb.Append(" ServiceLevel: ").Append(ServiceLevel).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // MidNumber (string) maxLength + if (this.MidNumber != null && this.MidNumber.Length > 14) + { + yield return new ValidationResult("Invalid value for MidNumber, length must be less than 14.", new [] { "MidNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class JCBInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override JCBInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option midNumber = default; + Option reuseMidNumber = default; + Option serviceLevel = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "midNumber": + midNumber = new Option(utf8JsonReader.GetString()!); + break; + case "reuseMidNumber": + reuseMidNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "serviceLevel": + string? serviceLevelRawValue = utf8JsonReader.GetString(); + serviceLevel = new Option(JCBInfo.ServiceLevelEnum.FromStringOrDefault(serviceLevelRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new JCBInfo(midNumber, reuseMidNumber, serviceLevel, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, JCBInfo jCBInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, jCBInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, JCBInfo jCBInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (jCBInfo._MidNumberOption.IsSet) + if (jCBInfo.MidNumber != null) + writer.WriteString("midNumber", jCBInfo.MidNumber); + + if (jCBInfo._ReuseMidNumberOption.IsSet) + writer.WriteBoolean("reuseMidNumber", jCBInfo._ReuseMidNumberOption.Value!.Value); + + if (jCBInfo._ServiceLevelOption.IsSet && jCBInfo.ServiceLevel != null) + { + string? serviceLevelRawValue = JCBInfo.ServiceLevelEnum.ToJsonValue(jCBInfo._ServiceLevelOption.Value!.Value); + writer.WriteString("serviceLevel", serviceLevelRawValue); + } + + if (jCBInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, jCBInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Key.cs b/Adyen/Management/Models/Key.cs new file mode 100644 index 000000000..52bc3a2fc --- /dev/null +++ b/Adyen/Management/Models/Key.cs @@ -0,0 +1,226 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Key. + /// + public partial class Key : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the shared key. + /// The secure passphrase to protect the shared key. Must consist of: * At least 12 characters. * At least 1 uppercase letter: `[A-Z]`. * At least 1 lowercase letter: `[a-z]`. * At least 1 digit: `[0-9]`. * At least 1 special character. Limited to the following: `~`, `@`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `_`, `+`, `=`, `}`, `{`, `]`, `[`, `;`, `:`, `?`, `.`, `,`, `>`, `<`. + /// The version number of the shared key. + [JsonConstructor] + public Key(Option identifier = default, Option passphrase = default, Option version = default) + { + _IdentifierOption = identifier; + _PassphraseOption = passphrase; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Key() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdentifierOption { get; private set; } + + /// + /// The unique identifier of the shared key. + /// + /// The unique identifier of the shared key. + [JsonPropertyName("identifier")] + public string? Identifier { get { return this._IdentifierOption; } set { this._IdentifierOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PassphraseOption { get; private set; } + + /// + /// The secure passphrase to protect the shared key. Must consist of: * At least 12 characters. * At least 1 uppercase letter: `[A-Z]`. * At least 1 lowercase letter: `[a-z]`. * At least 1 digit: `[0-9]`. * At least 1 special character. Limited to the following: `~`, `@`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `_`, `+`, `=`, `}`, `{`, `]`, `[`, `;`, `:`, `?`, `.`, `,`, `>`, `<`. + /// + /// The secure passphrase to protect the shared key. Must consist of: * At least 12 characters. * At least 1 uppercase letter: `[A-Z]`. * At least 1 lowercase letter: `[a-z]`. * At least 1 digit: `[0-9]`. * At least 1 special character. Limited to the following: `~`, `@`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `_`, `+`, `=`, `}`, `{`, `]`, `[`, `;`, `:`, `?`, `.`, `,`, `>`, `<`. + [JsonPropertyName("passphrase")] + public string? Passphrase { get { return this._PassphraseOption; } set { this._PassphraseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// The version number of the shared key. + /// + /// The version number of the shared key. + [JsonPropertyName("version")] + public int? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Key {\n"); + sb.Append(" Identifier: ").Append(Identifier).Append("\n"); + sb.Append(" Passphrase: ").Append(Passphrase).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class KeyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Key Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option identifier = default; + Option passphrase = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "identifier": + identifier = new Option(utf8JsonReader.GetString()!); + break; + case "passphrase": + passphrase = new Option(utf8JsonReader.GetString()!); + break; + case "version": + version = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Key(identifier, passphrase, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Key key, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, key, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Key key, JsonSerializerOptions jsonSerializerOptions) + { + + if (key._IdentifierOption.IsSet) + if (key.Identifier != null) + writer.WriteString("identifier", key.Identifier); + + if (key._PassphraseOption.IsSet) + if (key.Passphrase != null) + writer.WriteString("passphrase", key.Passphrase); + + if (key._VersionOption.IsSet) + writer.WriteNumber("version", key._VersionOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/KlarnaInfo.cs b/Adyen/Management/Models/KlarnaInfo.cs new file mode 100644 index 000000000..d3702d49b --- /dev/null +++ b/Adyen/Management/Models/KlarnaInfo.cs @@ -0,0 +1,360 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// KlarnaInfo. + /// + public partial class KlarnaInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address for disputes. + /// The region of operation. For example, **NA**, **EU**, **CH**, **AU**. + /// The email address of merchant support. + /// Indicates the status of [Automatic capture](https://docs.adyen.com/online-payments/capture#automatic-capture). Default value: **false**. + [JsonConstructor] + public KlarnaInfo(string disputeEmail, RegionEnum region, string supportEmail, Option autoCapture = default) + { + DisputeEmail = disputeEmail; + Region = region; + SupportEmail = supportEmail; + _AutoCaptureOption = autoCapture; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public KlarnaInfo() + { + } + + partial void OnCreated(); + + /// + /// The region of operation. For example, **NA**, **EU**, **CH**, **AU**. + /// + /// The region of operation. For example, **NA**, **EU**, **CH**, **AU**. + [JsonConverter(typeof(RegionEnumJsonConverter))] + public class RegionEnum : IEnum + { + /// + /// Returns the value of the RegionEnum. + /// + public string? Value { get; set; } + + /// + /// RegionEnum.NA - NA + /// + public static readonly RegionEnum NA = new("NA"); + + /// + /// RegionEnum.EU - EU + /// + public static readonly RegionEnum EU = new("EU"); + + /// + /// RegionEnum.CH - CH + /// + public static readonly RegionEnum CH = new("CH"); + + /// + /// RegionEnum.AU - AU + /// + public static readonly RegionEnum AU = new("AU"); + + private RegionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RegionEnum?(string? value) => value == null ? null : new RegionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RegionEnum? option) => option?.Value; + + public static bool operator ==(RegionEnum? left, RegionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RegionEnum? left, RegionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RegionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RegionEnum? FromStringOrDefault(string value) + { + return value switch { + "NA" => RegionEnum.NA, + "EU" => RegionEnum.EU, + "CH" => RegionEnum.CH, + "AU" => RegionEnum.AU, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RegionEnum? value) + { + if (value == null) + return null; + + if (value == RegionEnum.NA) + return "NA"; + + if (value == RegionEnum.EU) + return "EU"; + + if (value == RegionEnum.CH) + return "CH"; + + if (value == RegionEnum.AU) + return "AU"; + + return null; + } + + /// + /// JsonConverter for writing RegionEnum. + /// + public class RegionEnumJsonConverter : JsonConverter + { + public override RegionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RegionEnum.FromStringOrDefault(value) ?? new RegionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RegionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RegionEnum.ToJsonValue(value)); + } + } + } + + /// + /// The region of operation. For example, **NA**, **EU**, **CH**, **AU**. + /// + /// The region of operation. For example, **NA**, **EU**, **CH**, **AU**. + [JsonPropertyName("region")] + public RegionEnum Region { get; set; } + + /// + /// The email address for disputes. + /// + /// The email address for disputes. + [JsonPropertyName("disputeEmail")] + public string DisputeEmail { get; set; } + + /// + /// The email address of merchant support. + /// + /// The email address of merchant support. + [JsonPropertyName("supportEmail")] + public string SupportEmail { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AutoCaptureOption { get; private set; } + + /// + /// Indicates the status of [Automatic capture](https://docs.adyen.com/online-payments/capture#automatic-capture). Default value: **false**. + /// + /// Indicates the status of [Automatic capture](https://docs.adyen.com/online-payments/capture#automatic-capture). Default value: **false**. + [JsonPropertyName("autoCapture")] + public bool? AutoCapture { get { return this._AutoCaptureOption; } set { this._AutoCaptureOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class KlarnaInfo {\n"); + sb.Append(" DisputeEmail: ").Append(DisputeEmail).Append("\n"); + sb.Append(" Region: ").Append(Region).Append("\n"); + sb.Append(" SupportEmail: ").Append(SupportEmail).Append("\n"); + sb.Append(" AutoCapture: ").Append(AutoCapture).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class KlarnaInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override KlarnaInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option disputeEmail = default; + Option region = default; + Option supportEmail = default; + Option autoCapture = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "disputeEmail": + disputeEmail = new Option(utf8JsonReader.GetString()!); + break; + case "region": + string? regionRawValue = utf8JsonReader.GetString(); + region = new Option(KlarnaInfo.RegionEnum.FromStringOrDefault(regionRawValue)); + break; + case "supportEmail": + supportEmail = new Option(utf8JsonReader.GetString()!); + break; + case "autoCapture": + autoCapture = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!disputeEmail.IsSet) + throw new ArgumentException("Property is required for class KlarnaInfo.", nameof(disputeEmail)); + + if (!region.IsSet) + throw new ArgumentException("Property is required for class KlarnaInfo.", nameof(region)); + + if (!supportEmail.IsSet) + throw new ArgumentException("Property is required for class KlarnaInfo.", nameof(supportEmail)); + + return new KlarnaInfo(disputeEmail.Value!, region.Value!.Value!, supportEmail.Value!, autoCapture); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, KlarnaInfo klarnaInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, klarnaInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, KlarnaInfo klarnaInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (klarnaInfo.DisputeEmail != null) + writer.WriteString("disputeEmail", klarnaInfo.DisputeEmail); + + if (klarnaInfo.Region != null) + { + string? regionRawValue = KlarnaInfo.RegionEnum.ToJsonValue(klarnaInfo.Region); + writer.WriteString("region", regionRawValue); + } + + if (klarnaInfo.SupportEmail != null) + writer.WriteString("supportEmail", klarnaInfo.SupportEmail); + + if (klarnaInfo._AutoCaptureOption.IsSet) + writer.WriteBoolean("autoCapture", klarnaInfo._AutoCaptureOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Links.cs b/Adyen/Management/Models/Links.cs new file mode 100644 index 000000000..b5d71acf6 --- /dev/null +++ b/Adyen/Management/Models/Links.cs @@ -0,0 +1,170 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Links. + /// + public partial class Links : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// self + [JsonConstructor] + public Links(LinksElement self) + { + Self = self; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Links() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Links {\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Links Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option self = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!self.IsSet) + throw new ArgumentException("Property is required for class Links.", nameof(self)); + + return new Links(self.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Links links, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, links, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Links links, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, links.Self, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Management/Models/LinksElement.cs b/Adyen/Management/Models/LinksElement.cs new file mode 100644 index 000000000..d7976130a --- /dev/null +++ b/Adyen/Management/Models/LinksElement.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// LinksElement. + /// + public partial class LinksElement : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// href + [JsonConstructor] + public LinksElement(Option href = default) + { + _HrefOption = href; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LinksElement() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HrefOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("href")] + public string? Href { get { return this._HrefOption; } set { this._HrefOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LinksElement {\n"); + sb.Append(" Href: ").Append(Href).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LinksElementJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LinksElement Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option href = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "href": + href = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new LinksElement(href); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LinksElement linksElement, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, linksElement, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LinksElement linksElement, JsonSerializerOptions jsonSerializerOptions) + { + + if (linksElement._HrefOption.IsSet) + if (linksElement.Href != null) + writer.WriteString("href", linksElement.Href); + } + } +} diff --git a/Adyen/Management/Models/ListCompanyApiCredentialsResponse.cs b/Adyen/Management/Models/ListCompanyApiCredentialsResponse.cs new file mode 100644 index 000000000..38d4f00c6 --- /dev/null +++ b/Adyen/Management/Models/ListCompanyApiCredentialsResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListCompanyApiCredentialsResponse. + /// + public partial class ListCompanyApiCredentialsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of API credentials. + [JsonConstructor] + public ListCompanyApiCredentialsResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListCompanyApiCredentialsResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of API credentials. + /// + /// The list of API credentials. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListCompanyApiCredentialsResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListCompanyApiCredentialsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListCompanyApiCredentialsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyApiCredentialsResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyApiCredentialsResponse.", nameof(pagesTotal)); + + return new ListCompanyApiCredentialsResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListCompanyApiCredentialsResponse listCompanyApiCredentialsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listCompanyApiCredentialsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListCompanyApiCredentialsResponse listCompanyApiCredentialsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listCompanyApiCredentialsResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listCompanyApiCredentialsResponse.PagesTotal); + + if (listCompanyApiCredentialsResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listCompanyApiCredentialsResponse.Links, jsonSerializerOptions); + } + if (listCompanyApiCredentialsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listCompanyApiCredentialsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListCompanyResponse.cs b/Adyen/Management/Models/ListCompanyResponse.cs new file mode 100644 index 000000000..7343436b5 --- /dev/null +++ b/Adyen/Management/Models/ListCompanyResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListCompanyResponse. + /// + public partial class ListCompanyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of companies. + [JsonConstructor] + public ListCompanyResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListCompanyResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of companies. + /// + /// The list of companies. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListCompanyResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListCompanyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListCompanyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyResponse.", nameof(pagesTotal)); + + return new ListCompanyResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListCompanyResponse listCompanyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listCompanyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListCompanyResponse listCompanyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listCompanyResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listCompanyResponse.PagesTotal); + + if (listCompanyResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listCompanyResponse.Links, jsonSerializerOptions); + } + if (listCompanyResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listCompanyResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListCompanyUsersResponse.cs b/Adyen/Management/Models/ListCompanyUsersResponse.cs new file mode 100644 index 000000000..3ef796ff5 --- /dev/null +++ b/Adyen/Management/Models/ListCompanyUsersResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListCompanyUsersResponse. + /// + public partial class ListCompanyUsersResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of users. + [JsonConstructor] + public ListCompanyUsersResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListCompanyUsersResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of users. + /// + /// The list of users. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListCompanyUsersResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListCompanyUsersResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListCompanyUsersResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyUsersResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListCompanyUsersResponse.", nameof(pagesTotal)); + + return new ListCompanyUsersResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListCompanyUsersResponse listCompanyUsersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listCompanyUsersResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListCompanyUsersResponse listCompanyUsersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listCompanyUsersResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listCompanyUsersResponse.PagesTotal); + + if (listCompanyUsersResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listCompanyUsersResponse.Links, jsonSerializerOptions); + } + if (listCompanyUsersResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listCompanyUsersResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListExternalTerminalActionsResponse.cs b/Adyen/Management/Models/ListExternalTerminalActionsResponse.cs new file mode 100644 index 000000000..c8813c735 --- /dev/null +++ b/Adyen/Management/Models/ListExternalTerminalActionsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListExternalTerminalActionsResponse. + /// + public partial class ListExternalTerminalActionsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of terminal actions. + [JsonConstructor] + public ListExternalTerminalActionsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListExternalTerminalActionsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of terminal actions. + /// + /// The list of terminal actions. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListExternalTerminalActionsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListExternalTerminalActionsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListExternalTerminalActionsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ListExternalTerminalActionsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListExternalTerminalActionsResponse listExternalTerminalActionsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listExternalTerminalActionsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListExternalTerminalActionsResponse listExternalTerminalActionsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (listExternalTerminalActionsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listExternalTerminalActionsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListMerchantApiCredentialsResponse.cs b/Adyen/Management/Models/ListMerchantApiCredentialsResponse.cs new file mode 100644 index 000000000..cd02c095c --- /dev/null +++ b/Adyen/Management/Models/ListMerchantApiCredentialsResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListMerchantApiCredentialsResponse. + /// + public partial class ListMerchantApiCredentialsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of API credentials. + [JsonConstructor] + public ListMerchantApiCredentialsResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListMerchantApiCredentialsResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of API credentials. + /// + /// The list of API credentials. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListMerchantApiCredentialsResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListMerchantApiCredentialsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListMerchantApiCredentialsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantApiCredentialsResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantApiCredentialsResponse.", nameof(pagesTotal)); + + return new ListMerchantApiCredentialsResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListMerchantApiCredentialsResponse listMerchantApiCredentialsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listMerchantApiCredentialsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListMerchantApiCredentialsResponse listMerchantApiCredentialsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listMerchantApiCredentialsResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listMerchantApiCredentialsResponse.PagesTotal); + + if (listMerchantApiCredentialsResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listMerchantApiCredentialsResponse.Links, jsonSerializerOptions); + } + if (listMerchantApiCredentialsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listMerchantApiCredentialsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListMerchantResponse.cs b/Adyen/Management/Models/ListMerchantResponse.cs new file mode 100644 index 000000000..8192f761f --- /dev/null +++ b/Adyen/Management/Models/ListMerchantResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListMerchantResponse. + /// + public partial class ListMerchantResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of merchant accounts. + [JsonConstructor] + public ListMerchantResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListMerchantResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of merchant accounts. + /// + /// The list of merchant accounts. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListMerchantResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListMerchantResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListMerchantResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantResponse.", nameof(pagesTotal)); + + return new ListMerchantResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListMerchantResponse listMerchantResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listMerchantResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListMerchantResponse listMerchantResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listMerchantResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listMerchantResponse.PagesTotal); + + if (listMerchantResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listMerchantResponse.Links, jsonSerializerOptions); + } + if (listMerchantResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listMerchantResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListMerchantUsersResponse.cs b/Adyen/Management/Models/ListMerchantUsersResponse.cs new file mode 100644 index 000000000..9106812ff --- /dev/null +++ b/Adyen/Management/Models/ListMerchantUsersResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListMerchantUsersResponse. + /// + public partial class ListMerchantUsersResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of users. + [JsonConstructor] + public ListMerchantUsersResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListMerchantUsersResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of users. + /// + /// The list of users. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListMerchantUsersResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListMerchantUsersResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListMerchantUsersResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantUsersResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListMerchantUsersResponse.", nameof(pagesTotal)); + + return new ListMerchantUsersResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListMerchantUsersResponse listMerchantUsersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listMerchantUsersResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListMerchantUsersResponse listMerchantUsersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listMerchantUsersResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listMerchantUsersResponse.PagesTotal); + + if (listMerchantUsersResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listMerchantUsersResponse.Links, jsonSerializerOptions); + } + if (listMerchantUsersResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listMerchantUsersResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListStoresResponse.cs b/Adyen/Management/Models/ListStoresResponse.cs new file mode 100644 index 000000000..9684aaa98 --- /dev/null +++ b/Adyen/Management/Models/ListStoresResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListStoresResponse. + /// + public partial class ListStoresResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// List of stores + [JsonConstructor] + public ListStoresResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListStoresResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List of stores + /// + /// List of stores + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListStoresResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListStoresResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListStoresResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListStoresResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListStoresResponse.", nameof(pagesTotal)); + + return new ListStoresResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListStoresResponse listStoresResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listStoresResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListStoresResponse listStoresResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listStoresResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listStoresResponse.PagesTotal); + + if (listStoresResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listStoresResponse.Links, jsonSerializerOptions); + } + if (listStoresResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listStoresResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListTerminalsResponse.cs b/Adyen/Management/Models/ListTerminalsResponse.cs new file mode 100644 index 000000000..b36304b0a --- /dev/null +++ b/Adyen/Management/Models/ListTerminalsResponse.cs @@ -0,0 +1,241 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListTerminalsResponse. + /// + public partial class ListTerminalsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of terminals and their details. + [JsonConstructor] + public ListTerminalsResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListTerminalsResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of terminals and their details. + /// + /// The list of terminals and their details. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListTerminalsResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListTerminalsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListTerminalsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListTerminalsResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListTerminalsResponse.", nameof(pagesTotal)); + + return new ListTerminalsResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListTerminalsResponse listTerminalsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listTerminalsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListTerminalsResponse listTerminalsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listTerminalsResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listTerminalsResponse.PagesTotal); + + if (listTerminalsResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listTerminalsResponse.Links, jsonSerializerOptions); + } + if (listTerminalsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listTerminalsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ListWebhooksResponse.cs b/Adyen/Management/Models/ListWebhooksResponse.cs new file mode 100644 index 000000000..9db453a50 --- /dev/null +++ b/Adyen/Management/Models/ListWebhooksResponse.cs @@ -0,0 +1,266 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ListWebhooksResponse. + /// + public partial class ListWebhooksResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// Reference to the account. + /// The list of webhooks configured for this account. + [JsonConstructor] + public ListWebhooksResponse(int itemsTotal, int pagesTotal, Option links = default, Option accountReference = default, Option?> data = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _AccountReferenceOption = accountReference; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ListWebhooksResponse() + { + } + + partial void OnCreated(); + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountReferenceOption { get; private set; } + + /// + /// Reference to the account. + /// + /// Reference to the account. + [JsonPropertyName("accountReference")] + public string? AccountReference { get { return this._AccountReferenceOption; } set { this._AccountReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of webhooks configured for this account. + /// + /// The list of webhooks configured for this account. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ListWebhooksResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AccountReference: ").Append(AccountReference).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ListWebhooksResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ListWebhooksResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option accountReference = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountReference": + accountReference = new Option(utf8JsonReader.GetString()!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class ListWebhooksResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class ListWebhooksResponse.", nameof(pagesTotal)); + + return new ListWebhooksResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, accountReference, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ListWebhooksResponse listWebhooksResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, listWebhooksResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ListWebhooksResponse listWebhooksResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", listWebhooksResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", listWebhooksResponse.PagesTotal); + + if (listWebhooksResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, listWebhooksResponse.Links, jsonSerializerOptions); + } + if (listWebhooksResponse._AccountReferenceOption.IsSet) + if (listWebhooksResponse.AccountReference != null) + writer.WriteString("accountReference", listWebhooksResponse.AccountReference); + + if (listWebhooksResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, listWebhooksResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Localization.cs b/Adyen/Management/Models/Localization.cs new file mode 100644 index 000000000..14f346739 --- /dev/null +++ b/Adyen/Management/Models/Localization.cs @@ -0,0 +1,227 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Localization. + /// + public partial class Localization : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Language of the terminal. + /// Secondary language of the terminal. + /// The time zone of the terminal. + [JsonConstructor] + public Localization(Option language = default, Option secondaryLanguage = default, Option timezone = default) + { + _LanguageOption = language; + _SecondaryLanguageOption = secondaryLanguage; + _TimezoneOption = timezone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Localization() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LanguageOption { get; private set; } + + /// + /// Language of the terminal. + /// + /// Language of the terminal. + [JsonPropertyName("language")] + public string? Language { get { return this._LanguageOption; } set { this._LanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SecondaryLanguageOption { get; private set; } + + /// + /// Secondary language of the terminal. + /// + /// Secondary language of the terminal. + [JsonPropertyName("secondaryLanguage")] + public string? SecondaryLanguage { get { return this._SecondaryLanguageOption; } set { this._SecondaryLanguageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimezoneOption { get; private set; } + + /// + /// The time zone of the terminal. + /// + /// The time zone of the terminal. + [JsonPropertyName("timezone")] + public string? Timezone { get { return this._TimezoneOption; } set { this._TimezoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Localization {\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" SecondaryLanguage: ").Append(SecondaryLanguage).Append("\n"); + sb.Append(" Timezone: ").Append(Timezone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LocalizationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Localization Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option language = default; + Option secondaryLanguage = default; + Option timezone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "secondaryLanguage": + secondaryLanguage = new Option(utf8JsonReader.GetString()!); + break; + case "timezone": + timezone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Localization(language, secondaryLanguage, timezone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Localization localization, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, localization, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Localization localization, JsonSerializerOptions jsonSerializerOptions) + { + + if (localization._LanguageOption.IsSet) + if (localization.Language != null) + writer.WriteString("language", localization.Language); + + if (localization._SecondaryLanguageOption.IsSet) + if (localization.SecondaryLanguage != null) + writer.WriteString("secondaryLanguage", localization.SecondaryLanguage); + + if (localization._TimezoneOption.IsSet) + if (localization.Timezone != null) + writer.WriteString("timezone", localization.Timezone); + } + } +} diff --git a/Adyen/Management/Models/Logo.cs b/Adyen/Management/Models/Logo.cs new file mode 100644 index 000000000..e95392260 --- /dev/null +++ b/Adyen/Management/Models/Logo.cs @@ -0,0 +1,183 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Logo. + /// + public partial class Logo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The image file, converted to a Base64-encoded string, of the logo to be shown on the terminal. + [JsonConstructor] + public Logo(Option data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Logo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DataOption { get; private set; } + + /// + /// The image file, converted to a Base64-encoded string, of the logo to be shown on the terminal. + /// + /// The image file, converted to a Base64-encoded string, of the logo to be shown on the terminal. + [JsonPropertyName("data")] + public string? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Logo {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Data (string) maxLength + if (this.Data != null && this.Data.Length > 350000) + { + yield return new ValidationResult("Invalid value for Data, length must be less than 350000.", new [] { "Data" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LogoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Logo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Logo(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Logo logo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, logo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Logo logo, JsonSerializerOptions jsonSerializerOptions) + { + + if (logo._DataOption.IsSet) + if (logo.Data != null) + writer.WriteString("data", logo.Data); + } + } +} diff --git a/Adyen/Management/Models/MeApiCredential.cs b/Adyen/Management/Models/MeApiCredential.cs new file mode 100644 index 000000000..e681653bd --- /dev/null +++ b/Adyen/Management/Models/MeApiCredential.cs @@ -0,0 +1,375 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// MeApiCredential. + /// + public partial class MeApiCredential : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// Unique identifier of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// links + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// Name of the company linked to the API credential. + /// Description of the API credential. + [JsonConstructor] + public MeApiCredential(bool active, List allowedIpAddresses, string clientKey, string id, List roles, string username, Option links = default, Option?> allowedOrigins = default, Option companyName = default, Option description = default) + { + Active = active; + AllowedIpAddresses = allowedIpAddresses; + ClientKey = clientKey; + Id = id; + Roles = roles; + Username = username; + _LinksOption = links; + _AllowedOriginsOption = allowedOrigins; + _CompanyNameOption = companyName; + _DescriptionOption = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MeApiCredential() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + /// + /// Indicates if the API credential is enabled. Must be set to **true** to use the credential in your integration. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + /// + /// List of IP addresses from which your client can make requests. If the list is empty, we allow requests from any IP. If the list is not empty and we get a request from an IP which is not on the list, you get a security error. + [JsonPropertyName("allowedIpAddresses")] + public List AllowedIpAddresses { get; set; } + + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + /// + /// Public key used for [client-side authentication](https://docs.adyen.com/development-resources/client-side-authentication). The client key is required for Drop-in and Components integrations. + [JsonPropertyName("clientKey")] + public string ClientKey { get; set; } + + /// + /// Unique identifier of the API credential. + /// + /// Unique identifier of the API credential. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + /// + /// The name of the [API credential](https://docs.adyen.com/development-resources/api-credentials), for example **ws@Company.TestCompany**. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public ApiCredentialLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + /// + /// List containing the [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) linked to the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyNameOption { get; private set; } + + /// + /// Name of the company linked to the API credential. + /// + /// Name of the company linked to the API credential. + [JsonPropertyName("companyName")] + public string? CompanyName { get { return this._CompanyNameOption; } set { this._CompanyNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MeApiCredential {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedIpAddresses: ").Append(AllowedIpAddresses).Append("\n"); + sb.Append(" ClientKey: ").Append(ClientKey).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" CompanyName: ").Append(CompanyName).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 50) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 50.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MeApiCredentialJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MeApiCredential Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedIpAddresses = default; + Option clientKey = default; + Option id = default; + Option?> roles = default; + Option username = default; + Option links = default; + Option?> allowedOrigins = default; + Option companyName = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedIpAddresses": + allowedIpAddresses = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clientKey": + clientKey = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "companyName": + companyName = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(active)); + + if (!allowedIpAddresses.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(allowedIpAddresses)); + + if (!clientKey.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(clientKey)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(roles)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class MeApiCredential.", nameof(username)); + + return new MeApiCredential(active.Value!.Value!, allowedIpAddresses.Value!, clientKey.Value!, id.Value!, roles.Value!, username.Value!, links, allowedOrigins, companyName, description); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MeApiCredential meApiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, meApiCredential, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MeApiCredential meApiCredential, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", meApiCredential.Active); + + writer.WritePropertyName("allowedIpAddresses"); + JsonSerializer.Serialize(writer, meApiCredential.AllowedIpAddresses, jsonSerializerOptions); + if (meApiCredential.ClientKey != null) + writer.WriteString("clientKey", meApiCredential.ClientKey); + + if (meApiCredential.Id != null) + writer.WriteString("id", meApiCredential.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, meApiCredential.Roles, jsonSerializerOptions); + if (meApiCredential.Username != null) + writer.WriteString("username", meApiCredential.Username); + + if (meApiCredential._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, meApiCredential.Links, jsonSerializerOptions); + } + if (meApiCredential._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, meApiCredential.AllowedOrigins, jsonSerializerOptions); + } + if (meApiCredential._CompanyNameOption.IsSet) + if (meApiCredential.CompanyName != null) + writer.WriteString("companyName", meApiCredential.CompanyName); + + if (meApiCredential._DescriptionOption.IsSet) + if (meApiCredential.Description != null) + writer.WriteString("description", meApiCredential.Description); + } + } +} diff --git a/Adyen/Management/Models/MealVoucherFRInfo.cs b/Adyen/Management/Models/MealVoucherFRInfo.cs new file mode 100644 index 000000000..a210f741f --- /dev/null +++ b/Adyen/Management/Models/MealVoucherFRInfo.cs @@ -0,0 +1,223 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// MealVoucherFRInfo. + /// + public partial class MealVoucherFRInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Meal Voucher conecsId. Format: digits only + /// Meal Voucher siret. Format: 14 digits. + /// The list of additional payment methods. Allowed values: **mealVoucher_FR_edenred**, **mealVoucher_FR_groupeup**, **mealVoucher_FR_natixis**, **mealVoucher_FR_sodexo**. + [JsonConstructor] + public MealVoucherFRInfo(string conecsId, string siret, List subTypes) + { + ConecsId = conecsId; + Siret = siret; + SubTypes = subTypes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MealVoucherFRInfo() + { + } + + partial void OnCreated(); + + /// + /// Meal Voucher conecsId. Format: digits only + /// + /// Meal Voucher conecsId. Format: digits only + [JsonPropertyName("conecsId")] + public string ConecsId { get; set; } + + /// + /// Meal Voucher siret. Format: 14 digits. + /// + /// Meal Voucher siret. Format: 14 digits. + [JsonPropertyName("siret")] + public string Siret { get; set; } + + /// + /// The list of additional payment methods. Allowed values: **mealVoucher_FR_edenred**, **mealVoucher_FR_groupeup**, **mealVoucher_FR_natixis**, **mealVoucher_FR_sodexo**. + /// + /// The list of additional payment methods. Allowed values: **mealVoucher_FR_edenred**, **mealVoucher_FR_groupeup**, **mealVoucher_FR_natixis**, **mealVoucher_FR_sodexo**. + [JsonPropertyName("subTypes")] + public List SubTypes { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MealVoucherFRInfo {\n"); + sb.Append(" ConecsId: ").Append(ConecsId).Append("\n"); + sb.Append(" Siret: ").Append(Siret).Append("\n"); + sb.Append(" SubTypes: ").Append(SubTypes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Siret (string) maxLength + if (this.Siret != null && this.Siret.Length > 14) + { + yield return new ValidationResult("Invalid value for Siret, length must be less than 14.", new [] { "Siret" }); + } + + // Siret (string) minLength + if (this.Siret != null && this.Siret.Length < 14) + { + yield return new ValidationResult("Invalid value for Siret, length must be greater than 14.", new [] { "Siret" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MealVoucherFRInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MealVoucherFRInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option conecsId = default; + Option siret = default; + Option?> subTypes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "conecsId": + conecsId = new Option(utf8JsonReader.GetString()!); + break; + case "siret": + siret = new Option(utf8JsonReader.GetString()!); + break; + case "subTypes": + subTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!conecsId.IsSet) + throw new ArgumentException("Property is required for class MealVoucherFRInfo.", nameof(conecsId)); + + if (!siret.IsSet) + throw new ArgumentException("Property is required for class MealVoucherFRInfo.", nameof(siret)); + + if (!subTypes.IsSet) + throw new ArgumentException("Property is required for class MealVoucherFRInfo.", nameof(subTypes)); + + return new MealVoucherFRInfo(conecsId.Value!, siret.Value!, subTypes.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MealVoucherFRInfo mealVoucherFRInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mealVoucherFRInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MealVoucherFRInfo mealVoucherFRInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (mealVoucherFRInfo.ConecsId != null) + writer.WriteString("conecsId", mealVoucherFRInfo.ConecsId); + + if (mealVoucherFRInfo.Siret != null) + writer.WriteString("siret", mealVoucherFRInfo.Siret); + + writer.WritePropertyName("subTypes"); + JsonSerializer.Serialize(writer, mealVoucherFRInfo.SubTypes, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Management/Models/Merchant.cs b/Adyen/Management/Models/Merchant.cs new file mode 100644 index 000000000..835417fe4 --- /dev/null +++ b/Adyen/Management/Models/Merchant.cs @@ -0,0 +1,503 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Merchant. + /// + public partial class Merchant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// The [capture delay](https://docs.adyen.com/online-payments/capture#capture-delay) set for the merchant account. Possible values: * **Immediate** * **Manual** * Number of days from **1** to **29** + /// The unique identifier of the company account this merchant belongs to + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + /// The default [`shopperInteraction`](https://docs.adyen.com/api-explorer/#/CheckoutService/v68/post/payments__reqParam_shopperInteraction) value used when processing payments through this merchant account. + /// Your description for the merchant account, maximum 300 characters + /// The unique identifier of the merchant account. + /// The city where the legal entity of this merchant account is registered. + /// The name of the legal entity associated with the merchant account. + /// Only applies to merchant accounts managed by Adyen's partners. The name of the pricing plan assigned to the merchant account. + /// The currency of the country where the legal entity of this merchant account is registered. Format: [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, a legal entity based in the United States has USD as the primary settlement currency. + /// Reference of the merchant account. + /// The URL for the ecommerce website used with this merchant account. + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. You cannot process new payments but you can still modify payments, for example issue refunds. You can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonConstructor] + public Merchant(Option links = default, Option captureDelay = default, Option companyId = default, Option?> dataCenters = default, Option defaultShopperInteraction = default, Option description = default, Option id = default, Option merchantCity = default, Option name = default, Option pricingPlan = default, Option primarySettlementCurrency = default, Option reference = default, Option shopWebAddress = default, Option status = default) + { + _LinksOption = links; + _CaptureDelayOption = captureDelay; + _CompanyIdOption = companyId; + _DataCentersOption = dataCenters; + _DefaultShopperInteractionOption = defaultShopperInteraction; + _DescriptionOption = description; + _IdOption = id; + _MerchantCityOption = merchantCity; + _NameOption = name; + _PricingPlanOption = pricingPlan; + _PrimarySettlementCurrencyOption = primarySettlementCurrency; + _ReferenceOption = reference; + _ShopWebAddressOption = shopWebAddress; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Merchant() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public MerchantLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayOption { get; private set; } + + /// + /// The [capture delay](https://docs.adyen.com/online-payments/capture#capture-delay) set for the merchant account. Possible values: * **Immediate** * **Manual** * Number of days from **1** to **29** + /// + /// The [capture delay](https://docs.adyen.com/online-payments/capture#capture-delay) set for the merchant account. Possible values: * **Immediate** * **Manual** * Number of days from **1** to **29** + [JsonPropertyName("captureDelay")] + public string? CaptureDelay { get { return this._CaptureDelayOption; } set { this._CaptureDelayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account this merchant belongs to + /// + /// The unique identifier of the company account this merchant belongs to + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataCentersOption { get; private set; } + + /// + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + /// + /// List of available data centers. Adyen has several data centers around the world.In the URL that you use for making API requests, we recommend you use the live URL prefix from the data center closest to your shoppers. + [JsonPropertyName("dataCenters")] + public List? DataCenters { get { return this._DataCentersOption; } set { this._DataCentersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultShopperInteractionOption { get; private set; } + + /// + /// The default [`shopperInteraction`](https://docs.adyen.com/api-explorer/#/CheckoutService/v68/post/payments__reqParam_shopperInteraction) value used when processing payments through this merchant account. + /// + /// The default [`shopperInteraction`](https://docs.adyen.com/api-explorer/#/CheckoutService/v68/post/payments__reqParam_shopperInteraction) value used when processing payments through this merchant account. + [JsonPropertyName("defaultShopperInteraction")] + public string? DefaultShopperInteraction { get { return this._DefaultShopperInteractionOption; } set { this._DefaultShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the merchant account, maximum 300 characters + /// + /// Your description for the merchant account, maximum 300 characters + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantCityOption { get; private set; } + + /// + /// The city where the legal entity of this merchant account is registered. + /// + /// The city where the legal entity of this merchant account is registered. + [JsonPropertyName("merchantCity")] + public string? MerchantCity { get { return this._MerchantCityOption; } set { this._MerchantCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the legal entity associated with the merchant account. + /// + /// The name of the legal entity associated with the merchant account. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PricingPlanOption { get; private set; } + + /// + /// Only applies to merchant accounts managed by Adyen's partners. The name of the pricing plan assigned to the merchant account. + /// + /// Only applies to merchant accounts managed by Adyen's partners. The name of the pricing plan assigned to the merchant account. + [JsonPropertyName("pricingPlan")] + public string? PricingPlan { get { return this._PricingPlanOption; } set { this._PricingPlanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrimarySettlementCurrencyOption { get; private set; } + + /// + /// The currency of the country where the legal entity of this merchant account is registered. Format: [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, a legal entity based in the United States has USD as the primary settlement currency. + /// + /// The currency of the country where the legal entity of this merchant account is registered. Format: [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). For example, a legal entity based in the United States has USD as the primary settlement currency. + [JsonPropertyName("primarySettlementCurrency")] + public string? PrimarySettlementCurrency { get { return this._PrimarySettlementCurrencyOption; } set { this._PrimarySettlementCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Reference of the merchant account. + /// + /// Reference of the merchant account. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopWebAddressOption { get; private set; } + + /// + /// The URL for the ecommerce website used with this merchant account. + /// + /// The URL for the ecommerce website used with this merchant account. + [JsonPropertyName("shopWebAddress")] + public string? ShopWebAddress { get { return this._ShopWebAddressOption; } set { this._ShopWebAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. You cannot process new payments but you can still modify payments, for example issue refunds. You can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. You cannot process new payments but you can still modify payments, for example issue refunds. You can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Merchant {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" CaptureDelay: ").Append(CaptureDelay).Append("\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" DataCenters: ").Append(DataCenters).Append("\n"); + sb.Append(" DefaultShopperInteraction: ").Append(DefaultShopperInteraction).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantCity: ").Append(MerchantCity).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PricingPlan: ").Append(PricingPlan).Append("\n"); + sb.Append(" PrimarySettlementCurrency: ").Append(PrimarySettlementCurrency).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ShopWebAddress: ").Append(ShopWebAddress).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Merchant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option captureDelay = default; + Option companyId = default; + Option?> dataCenters = default; + Option defaultShopperInteraction = default; + Option description = default; + Option id = default; + Option merchantCity = default; + Option name = default; + Option pricingPlan = default; + Option primarySettlementCurrency = default; + Option reference = default; + Option shopWebAddress = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelay": + captureDelay = new Option(utf8JsonReader.GetString()!); + break; + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "dataCenters": + dataCenters = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "defaultShopperInteraction": + defaultShopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantCity": + merchantCity = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "pricingPlan": + pricingPlan = new Option(utf8JsonReader.GetString()!); + break; + case "primarySettlementCurrency": + primarySettlementCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "shopWebAddress": + shopWebAddress = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Merchant(links, captureDelay, companyId, dataCenters, defaultShopperInteraction, description, id, merchantCity, name, pricingPlan, primarySettlementCurrency, reference, shopWebAddress, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Merchant merchant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Merchant merchant, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchant._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, merchant.Links, jsonSerializerOptions); + } + if (merchant._CaptureDelayOption.IsSet) + if (merchant.CaptureDelay != null) + writer.WriteString("captureDelay", merchant.CaptureDelay); + + if (merchant._CompanyIdOption.IsSet) + if (merchant.CompanyId != null) + writer.WriteString("companyId", merchant.CompanyId); + + if (merchant._DataCentersOption.IsSet) + { + writer.WritePropertyName("dataCenters"); + JsonSerializer.Serialize(writer, merchant.DataCenters, jsonSerializerOptions); + } + if (merchant._DefaultShopperInteractionOption.IsSet) + if (merchant.DefaultShopperInteraction != null) + writer.WriteString("defaultShopperInteraction", merchant.DefaultShopperInteraction); + + if (merchant._DescriptionOption.IsSet) + if (merchant.Description != null) + writer.WriteString("description", merchant.Description); + + if (merchant._IdOption.IsSet) + if (merchant.Id != null) + writer.WriteString("id", merchant.Id); + + if (merchant._MerchantCityOption.IsSet) + if (merchant.MerchantCity != null) + writer.WriteString("merchantCity", merchant.MerchantCity); + + if (merchant._NameOption.IsSet) + if (merchant.Name != null) + writer.WriteString("name", merchant.Name); + + if (merchant._PricingPlanOption.IsSet) + if (merchant.PricingPlan != null) + writer.WriteString("pricingPlan", merchant.PricingPlan); + + if (merchant._PrimarySettlementCurrencyOption.IsSet) + if (merchant.PrimarySettlementCurrency != null) + writer.WriteString("primarySettlementCurrency", merchant.PrimarySettlementCurrency); + + if (merchant._ReferenceOption.IsSet) + if (merchant.Reference != null) + writer.WriteString("reference", merchant.Reference); + + if (merchant._ShopWebAddressOption.IsSet) + if (merchant.ShopWebAddress != null) + writer.WriteString("shopWebAddress", merchant.ShopWebAddress); + + if (merchant._StatusOption.IsSet) + if (merchant.Status != null) + writer.WriteString("status", merchant.Status); + } + } +} diff --git a/Adyen/Management/Models/MerchantLinks.cs b/Adyen/Management/Models/MerchantLinks.cs new file mode 100644 index 000000000..17b5accd9 --- /dev/null +++ b/Adyen/Management/Models/MerchantLinks.cs @@ -0,0 +1,245 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// MerchantLinks. + /// + public partial class MerchantLinks : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// self + /// apiCredentials + /// users + /// webhooks + [JsonConstructor] + public MerchantLinks(LinksElement self, Option apiCredentials = default, Option users = default, Option webhooks = default) + { + Self = self; + _ApiCredentialsOption = apiCredentials; + _UsersOption = users; + _WebhooksOption = webhooks; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantLinks() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApiCredentialsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("apiCredentials")] + public LinksElement? ApiCredentials { get { return this._ApiCredentialsOption; } set { this._ApiCredentialsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("users")] + public LinksElement? Users { get { return this._UsersOption; } set { this._UsersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WebhooksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("webhooks")] + public LinksElement? Webhooks { get { return this._WebhooksOption; } set { this._WebhooksOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantLinks {\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append(" ApiCredentials: ").Append(ApiCredentials).Append("\n"); + sb.Append(" Users: ").Append(Users).Append("\n"); + sb.Append(" Webhooks: ").Append(Webhooks).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantLinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantLinks Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option self = default; + Option apiCredentials = default; + Option users = default; + Option webhooks = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "apiCredentials": + apiCredentials = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "users": + users = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "webhooks": + webhooks = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!self.IsSet) + throw new ArgumentException("Property is required for class MerchantLinks.", nameof(self)); + + return new MerchantLinks(self.Value!, apiCredentials, users, webhooks); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantLinks merchantLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantLinks, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantLinks merchantLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, merchantLinks.Self, jsonSerializerOptions); + if (merchantLinks._ApiCredentialsOption.IsSet) + { + writer.WritePropertyName("apiCredentials"); + JsonSerializer.Serialize(writer, merchantLinks.ApiCredentials, jsonSerializerOptions); + } + if (merchantLinks._UsersOption.IsSet) + { + writer.WritePropertyName("users"); + JsonSerializer.Serialize(writer, merchantLinks.Users, jsonSerializerOptions); + } + if (merchantLinks._WebhooksOption.IsSet) + { + writer.WritePropertyName("webhooks"); + JsonSerializer.Serialize(writer, merchantLinks.Webhooks, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/MinorUnitsMonetaryValue.cs b/Adyen/Management/Models/MinorUnitsMonetaryValue.cs new file mode 100644 index 000000000..94bce6ada --- /dev/null +++ b/Adyen/Management/Models/MinorUnitsMonetaryValue.cs @@ -0,0 +1,201 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// MinorUnitsMonetaryValue. + /// + public partial class MinorUnitsMonetaryValue : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonConstructor] + public MinorUnitsMonetaryValue(Option amount = default, Option currencyCode = default) + { + _AmountOption = amount; + _CurrencyCodeOption = currencyCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MinorUnitsMonetaryValue() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// The transaction amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The transaction amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("amount")] + public int? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyCodeOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currencyCode")] + public string? CurrencyCode { get { return this._CurrencyCodeOption; } set { this._CurrencyCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MinorUnitsMonetaryValue {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MinorUnitsMonetaryValueJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MinorUnitsMonetaryValue Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option currencyCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "currencyCode": + currencyCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MinorUnitsMonetaryValue(amount, currencyCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MinorUnitsMonetaryValue minorUnitsMonetaryValue, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, minorUnitsMonetaryValue, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MinorUnitsMonetaryValue minorUnitsMonetaryValue, JsonSerializerOptions jsonSerializerOptions) + { + + if (minorUnitsMonetaryValue._AmountOption.IsSet) + writer.WriteNumber("amount", minorUnitsMonetaryValue._AmountOption.Value!.Value); + + if (minorUnitsMonetaryValue._CurrencyCodeOption.IsSet) + if (minorUnitsMonetaryValue.CurrencyCode != null) + writer.WriteString("currencyCode", minorUnitsMonetaryValue.CurrencyCode); + } + } +} diff --git a/Adyen/Management/Models/ModelConfiguration.cs b/Adyen/Management/Models/ModelConfiguration.cs new file mode 100644 index 000000000..4fa79299f --- /dev/null +++ b/Adyen/Management/Models/ModelConfiguration.cs @@ -0,0 +1,267 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ModelConfiguration. + /// + public partial class ModelConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Payment method, like **eftpos_australia** or **mc**. See the [possible values](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// Currency and percentage or amount of the surcharge. + /// Set to **true** to apply surcharges only to commercial/business cards. + /// The country/region of the card issuer. If used, the surcharge settings only apply to the card issued in that country/region. + /// Funding source. Possible values: * **Credit** * **Debit** + [JsonConstructor] + public ModelConfiguration(string brand, List currencies, Option commercial = default, Option?> country = default, Option?> sources = default) + { + Brand = brand; + Currencies = currencies; + _CommercialOption = commercial; + _CountryOption = country; + _SourcesOption = sources; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ModelConfiguration() + { + } + + partial void OnCreated(); + + /// + /// Payment method, like **eftpos_australia** or **mc**. See the [possible values](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// + /// Payment method, like **eftpos_australia** or **mc**. See the [possible values](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + [JsonPropertyName("brand")] + public string Brand { get; set; } + + /// + /// Currency and percentage or amount of the surcharge. + /// + /// Currency and percentage or amount of the surcharge. + [JsonPropertyName("currencies")] + public List Currencies { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CommercialOption { get; private set; } + + /// + /// Set to **true** to apply surcharges only to commercial/business cards. + /// + /// Set to **true** to apply surcharges only to commercial/business cards. + [JsonPropertyName("commercial")] + public bool? Commercial { get { return this._CommercialOption; } set { this._CommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CountryOption { get; private set; } + + /// + /// The country/region of the card issuer. If used, the surcharge settings only apply to the card issued in that country/region. + /// + /// The country/region of the card issuer. If used, the surcharge settings only apply to the card issued in that country/region. + [JsonPropertyName("country")] + public List? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SourcesOption { get; private set; } + + /// + /// Funding source. Possible values: * **Credit** * **Debit** + /// + /// Funding source. Possible values: * **Credit** * **Debit** + [JsonPropertyName("sources")] + public List? Sources { get { return this._SourcesOption; } set { this._SourcesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModelConfiguration {\n"); + sb.Append(" Brand: ").Append(Brand).Append("\n"); + sb.Append(" Currencies: ").Append(Currencies).Append("\n"); + sb.Append(" Commercial: ").Append(Commercial).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Sources: ").Append(Sources).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModelConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ModelConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option brand = default; + Option?> currencies = default; + Option commercial = default; + Option?> country = default; + Option?> sources = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "brand": + brand = new Option(utf8JsonReader.GetString()!); + break; + case "currencies": + currencies = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "commercial": + commercial = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "country": + country = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sources": + sources = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!brand.IsSet) + throw new ArgumentException("Property is required for class ModelConfiguration.", nameof(brand)); + + if (!currencies.IsSet) + throw new ArgumentException("Property is required for class ModelConfiguration.", nameof(currencies)); + + return new ModelConfiguration(brand.Value!, currencies.Value!, commercial, country, sources); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModelConfiguration modelConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modelConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ModelConfiguration modelConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (modelConfiguration.Brand != null) + writer.WriteString("brand", modelConfiguration.Brand); + + writer.WritePropertyName("currencies"); + JsonSerializer.Serialize(writer, modelConfiguration.Currencies, jsonSerializerOptions); + if (modelConfiguration._CommercialOption.IsSet) + writer.WriteBoolean("commercial", modelConfiguration._CommercialOption.Value!.Value); + + if (modelConfiguration._CountryOption.IsSet) + { + writer.WritePropertyName("country"); + JsonSerializer.Serialize(writer, modelConfiguration.Country, jsonSerializerOptions); + } + if (modelConfiguration._SourcesOption.IsSet) + { + writer.WritePropertyName("sources"); + JsonSerializer.Serialize(writer, modelConfiguration.Sources, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Name.cs b/Adyen/Management/Models/Name.cs new file mode 100644 index 000000000..34cb25f2d --- /dev/null +++ b/Adyen/Management/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/Management/Models/Name2.cs b/Adyen/Management/Models/Name2.cs new file mode 100644 index 000000000..61ea97e14 --- /dev/null +++ b/Adyen/Management/Models/Name2.cs @@ -0,0 +1,214 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Name2. + /// + public partial class Name2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name2(Option firstName = default, Option lastName = default) + { + _FirstNameOption = firstName; + _LastNameOption = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name2() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name2 {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class Name2JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Name2(firstName, lastName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name2 name2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name2 name2, JsonSerializerOptions jsonSerializerOptions) + { + + if (name2._FirstNameOption.IsSet) + if (name2.FirstName != null) + writer.WriteString("firstName", name2.FirstName); + + if (name2._LastNameOption.IsSet) + if (name2.LastName != null) + writer.WriteString("lastName", name2.LastName); + } + } +} diff --git a/Adyen/Management/Models/Nexo.cs b/Adyen/Management/Models/Nexo.cs new file mode 100644 index 000000000..9e5724c25 --- /dev/null +++ b/Adyen/Management/Models/Nexo.cs @@ -0,0 +1,280 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Nexo. + /// + public partial class Nexo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// displayUrls + /// encryptionKey + /// eventUrls + /// One or more URLs to send event messages to when using Terminal API. + /// notification + [JsonConstructor] + public Nexo(Option displayUrls = default, Option encryptionKey = default, Option eventUrls = default, Option?> nexoEventUrls = default, Option notification = default) + { + _DisplayUrlsOption = displayUrls; + _EncryptionKeyOption = encryptionKey; + _EventUrlsOption = eventUrls; + _NexoEventUrlsOption = nexoEventUrls; + _NotificationOption = notification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Nexo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisplayUrlsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("displayUrls")] + public NotificationUrl? DisplayUrls { get { return this._DisplayUrlsOption; } set { this._DisplayUrlsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("encryptionKey")] + public Key? EncryptionKey { get { return this._EncryptionKeyOption; } set { this._EncryptionKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EventUrlsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eventUrls")] + public EventUrl? EventUrls { get { return this._EventUrlsOption; } set { this._EventUrlsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _NexoEventUrlsOption { get; private set; } + + /// + /// One or more URLs to send event messages to when using Terminal API. + /// + /// One or more URLs to send event messages to when using Terminal API. + [JsonPropertyName("nexoEventUrls")] + [Obsolete("Deprecated since Management API v1. Use `eventUrls` instead.")] + public List? NexoEventUrls { get { return this._NexoEventUrlsOption; } set { this._NexoEventUrlsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("notification")] + public Notification? Notification { get { return this._NotificationOption; } set { this._NotificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Nexo {\n"); + sb.Append(" DisplayUrls: ").Append(DisplayUrls).Append("\n"); + sb.Append(" EncryptionKey: ").Append(EncryptionKey).Append("\n"); + sb.Append(" EventUrls: ").Append(EventUrls).Append("\n"); + sb.Append(" NexoEventUrls: ").Append(NexoEventUrls).Append("\n"); + sb.Append(" Notification: ").Append(Notification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NexoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Nexo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option displayUrls = default; + Option encryptionKey = default; + Option eventUrls = default; + Option?> nexoEventUrls = default; + Option notification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "displayUrls": + displayUrls = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "encryptionKey": + encryptionKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eventUrls": + eventUrls = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nexoEventUrls": + nexoEventUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notification": + notification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Nexo(displayUrls, encryptionKey, eventUrls, nexoEventUrls, notification); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Nexo nexo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nexo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Nexo nexo, JsonSerializerOptions jsonSerializerOptions) + { + + if (nexo._DisplayUrlsOption.IsSet) + { + writer.WritePropertyName("displayUrls"); + JsonSerializer.Serialize(writer, nexo.DisplayUrls, jsonSerializerOptions); + } + if (nexo._EncryptionKeyOption.IsSet) + { + writer.WritePropertyName("encryptionKey"); + JsonSerializer.Serialize(writer, nexo.EncryptionKey, jsonSerializerOptions); + } + if (nexo._EventUrlsOption.IsSet) + { + writer.WritePropertyName("eventUrls"); + JsonSerializer.Serialize(writer, nexo.EventUrls, jsonSerializerOptions); + } + if (nexo._NexoEventUrlsOption.IsSet) + { + writer.WritePropertyName("nexoEventUrls"); + JsonSerializer.Serialize(writer, nexo.NexoEventUrls, jsonSerializerOptions); + } + if (nexo._NotificationOption.IsSet) + { + writer.WritePropertyName("notification"); + JsonSerializer.Serialize(writer, nexo.Notification, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Notification.cs b/Adyen/Management/Models/Notification.cs new file mode 100644 index 000000000..57f34c993 --- /dev/null +++ b/Adyen/Management/Models/Notification.cs @@ -0,0 +1,390 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Notification. + /// + public partial class Notification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of event notification sent when you select the notification button. + /// The text shown in the prompt which opens when you select the notification button. For example, the description of the input box for pay-at-table. + /// Enables sending event notifications either by pressing the Confirm key on terminals with a keypad or by tapping the event notification button on the terminal screen. + /// Shows or hides the event notification button on the screen of terminal models that have a keypad. + /// The name of the notification button on the terminal screen. + [JsonConstructor] + public Notification(Option category = default, Option details = default, Option enabled = default, Option showButton = default, Option title = default) + { + _CategoryOption = category; + _DetailsOption = details; + _EnabledOption = enabled; + _ShowButtonOption = showButton; + _TitleOption = title; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Notification() + { + } + + partial void OnCreated(); + + /// + /// The type of event notification sent when you select the notification button. + /// + /// The type of event notification sent when you select the notification button. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.SaleWakeUp - SaleWakeUp + /// + public static readonly CategoryEnum SaleWakeUp = new("SaleWakeUp"); + + /// + /// CategoryEnum.KeyPressed - KeyPressed + /// + public static readonly CategoryEnum KeyPressed = new("KeyPressed"); + + /// + /// CategoryEnum.Empty - + /// + public static readonly CategoryEnum Empty = new(""); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "SaleWakeUp" => CategoryEnum.SaleWakeUp, + "KeyPressed" => CategoryEnum.KeyPressed, + "" => CategoryEnum.Empty, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.SaleWakeUp) + return "SaleWakeUp"; + + if (value == CategoryEnum.KeyPressed) + return "KeyPressed"; + + if (value == CategoryEnum.Empty) + return ""; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryOption { get; private set; } + + /// + /// The type of event notification sent when you select the notification button. + /// + /// The type of event notification sent when you select the notification button. + [JsonPropertyName("category")] + public CategoryEnum? Category { get { return this._CategoryOption; } set { this._CategoryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailsOption { get; private set; } + + /// + /// The text shown in the prompt which opens when you select the notification button. For example, the description of the input box for pay-at-table. + /// + /// The text shown in the prompt which opens when you select the notification button. For example, the description of the input box for pay-at-table. + [JsonPropertyName("details")] + public string? Details { get { return this._DetailsOption; } set { this._DetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Enables sending event notifications either by pressing the Confirm key on terminals with a keypad or by tapping the event notification button on the terminal screen. + /// + /// Enables sending event notifications either by pressing the Confirm key on terminals with a keypad or by tapping the event notification button on the terminal screen. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShowButtonOption { get; private set; } + + /// + /// Shows or hides the event notification button on the screen of terminal models that have a keypad. + /// + /// Shows or hides the event notification button on the screen of terminal models that have a keypad. + [JsonPropertyName("showButton")] + public bool? ShowButton { get { return this._ShowButtonOption; } set { this._ShowButtonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// The name of the notification button on the terminal screen. + /// + /// The name of the notification button on the terminal screen. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Notification {\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Details: ").Append(Details).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" ShowButton: ").Append(ShowButton).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NotificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Notification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option category = default; + Option details = default; + Option enabled = default; + Option showButton = default; + Option title = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(Notification.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "details": + details = new Option(utf8JsonReader.GetString()!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "showButton": + showButton = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Notification(category, details, enabled, showButton, title); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Notification notification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, notification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Notification notification, JsonSerializerOptions jsonSerializerOptions) + { + + if (notification._CategoryOption.IsSet && notification.Category != null) + { + string? categoryRawValue = Notification.CategoryEnum.ToJsonValue(notification._CategoryOption.Value!.Value); + writer.WriteString("category", categoryRawValue); + } + + if (notification._DetailsOption.IsSet) + if (notification.Details != null) + writer.WriteString("details", notification.Details); + + if (notification._EnabledOption.IsSet) + writer.WriteBoolean("enabled", notification._EnabledOption.Value!.Value); + + if (notification._ShowButtonOption.IsSet) + writer.WriteBoolean("showButton", notification._ShowButtonOption.Value!.Value); + + if (notification._TitleOption.IsSet) + if (notification.Title != null) + writer.WriteString("title", notification.Title); + } + } +} diff --git a/Adyen/Management/Models/NotificationUrl.cs b/Adyen/Management/Models/NotificationUrl.cs new file mode 100644 index 000000000..9ed34f5c5 --- /dev/null +++ b/Adyen/Management/Models/NotificationUrl.cs @@ -0,0 +1,205 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// NotificationUrl. + /// + public partial class NotificationUrl : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// One or more local URLs to send notifications to when using Terminal API. + /// One or more public URLs to send notifications to when using Terminal API. + [JsonConstructor] + public NotificationUrl(Option?> localUrls = default, Option?> publicUrls = default) + { + _LocalUrlsOption = localUrls; + _PublicUrlsOption = publicUrls; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NotificationUrl() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalUrlsOption { get; private set; } + + /// + /// One or more local URLs to send notifications to when using Terminal API. + /// + /// One or more local URLs to send notifications to when using Terminal API. + [JsonPropertyName("localUrls")] + public List? LocalUrls { get { return this._LocalUrlsOption; } set { this._LocalUrlsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PublicUrlsOption { get; private set; } + + /// + /// One or more public URLs to send notifications to when using Terminal API. + /// + /// One or more public URLs to send notifications to when using Terminal API. + [JsonPropertyName("publicUrls")] + public List? PublicUrls { get { return this._PublicUrlsOption; } set { this._PublicUrlsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NotificationUrl {\n"); + sb.Append(" LocalUrls: ").Append(LocalUrls).Append("\n"); + sb.Append(" PublicUrls: ").Append(PublicUrls).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NotificationUrlJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NotificationUrl Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> localUrls = default; + Option?> publicUrls = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "localUrls": + localUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "publicUrls": + publicUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new NotificationUrl(localUrls, publicUrls); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NotificationUrl notificationUrl, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, notificationUrl, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NotificationUrl notificationUrl, JsonSerializerOptions jsonSerializerOptions) + { + + if (notificationUrl._LocalUrlsOption.IsSet) + { + writer.WritePropertyName("localUrls"); + JsonSerializer.Serialize(writer, notificationUrl.LocalUrls, jsonSerializerOptions); + } + if (notificationUrl._PublicUrlsOption.IsSet) + { + writer.WritePropertyName("publicUrls"); + JsonSerializer.Serialize(writer, notificationUrl.PublicUrls, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/NyceInfo.cs b/Adyen/Management/Models/NyceInfo.cs new file mode 100644 index 000000000..1bafc3ba2 --- /dev/null +++ b/Adyen/Management/Models/NyceInfo.cs @@ -0,0 +1,313 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// NyceInfo. + /// + public partial class NyceInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// transactionDescription + [JsonConstructor] + public NyceInfo(ProcessingTypeEnum processingType, Option transactionDescription = default) + { + ProcessingType = processingType; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NyceInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.Billpay - billpay + /// + public static readonly ProcessingTypeEnum Billpay = new("billpay"); + + /// + /// ProcessingTypeEnum.Ecom - ecom + /// + public static readonly ProcessingTypeEnum Ecom = new("ecom"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "billpay" => ProcessingTypeEnum.Billpay, + "ecom" => ProcessingTypeEnum.Ecom, + "pos" => ProcessingTypeEnum.Pos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.Billpay) + return "billpay"; + + if (value == ProcessingTypeEnum.Ecom) + return "ecom"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum ProcessingType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NyceInfo {\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NyceInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NyceInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option processingType = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(NyceInfo.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!processingType.IsSet) + throw new ArgumentException("Property is required for class NyceInfo.", nameof(processingType)); + + return new NyceInfo(processingType.Value!.Value!, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NyceInfo nyceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nyceInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NyceInfo nyceInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (nyceInfo.ProcessingType != null) + { + string? processingTypeRawValue = NyceInfo.ProcessingTypeEnum.ToJsonValue(nyceInfo.ProcessingType); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (nyceInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, nyceInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/OfflineProcessing.cs b/Adyen/Management/Models/OfflineProcessing.cs new file mode 100644 index 000000000..942262539 --- /dev/null +++ b/Adyen/Management/Models/OfflineProcessing.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// OfflineProcessing. + /// + public partial class OfflineProcessing : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The maximum offline transaction amount for chip cards, in the processing currency and specified in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The maximum offline transaction amount for swiped cards, in the specified currency. + [JsonConstructor] + public OfflineProcessing(Option chipFloorLimit = default, Option?> offlineSwipeLimits = default) + { + _ChipFloorLimitOption = chipFloorLimit; + _OfflineSwipeLimitsOption = offlineSwipeLimits; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OfflineProcessing() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChipFloorLimitOption { get; private set; } + + /// + /// The maximum offline transaction amount for chip cards, in the processing currency and specified in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The maximum offline transaction amount for chip cards, in the processing currency and specified in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("chipFloorLimit")] + public int? ChipFloorLimit { get { return this._ChipFloorLimitOption; } set { this._ChipFloorLimitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _OfflineSwipeLimitsOption { get; private set; } + + /// + /// The maximum offline transaction amount for swiped cards, in the specified currency. + /// + /// The maximum offline transaction amount for swiped cards, in the specified currency. + [JsonPropertyName("offlineSwipeLimits")] + public List? OfflineSwipeLimits { get { return this._OfflineSwipeLimitsOption; } set { this._OfflineSwipeLimitsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OfflineProcessing {\n"); + sb.Append(" ChipFloorLimit: ").Append(ChipFloorLimit).Append("\n"); + sb.Append(" OfflineSwipeLimits: ").Append(OfflineSwipeLimits).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OfflineProcessingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OfflineProcessing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option chipFloorLimit = default; + Option?> offlineSwipeLimits = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "chipFloorLimit": + chipFloorLimit = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "offlineSwipeLimits": + offlineSwipeLimits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new OfflineProcessing(chipFloorLimit, offlineSwipeLimits); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OfflineProcessing offlineProcessing, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, offlineProcessing, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OfflineProcessing offlineProcessing, JsonSerializerOptions jsonSerializerOptions) + { + + if (offlineProcessing._ChipFloorLimitOption.IsSet) + writer.WriteNumber("chipFloorLimit", offlineProcessing._ChipFloorLimitOption.Value!.Value); + + if (offlineProcessing._OfflineSwipeLimitsOption.IsSet) + { + writer.WritePropertyName("offlineSwipeLimits"); + JsonSerializer.Serialize(writer, offlineProcessing.OfflineSwipeLimits, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Opi.cs b/Adyen/Management/Models/Opi.cs new file mode 100644 index 000000000..0e6e559ef --- /dev/null +++ b/Adyen/Management/Models/Opi.cs @@ -0,0 +1,226 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Opi. + /// + public partial class Opi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if Pay at table is enabled. + /// The store number to use for Pay at Table. + /// The URL and port number used for Pay at Table communication. + [JsonConstructor] + public Opi(Option enablePayAtTable = default, Option payAtTableStoreNumber = default, Option payAtTableURL = default) + { + _EnablePayAtTableOption = enablePayAtTable; + _PayAtTableStoreNumberOption = payAtTableStoreNumber; + _PayAtTableURLOption = payAtTableURL; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Opi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnablePayAtTableOption { get; private set; } + + /// + /// Indicates if Pay at table is enabled. + /// + /// Indicates if Pay at table is enabled. + [JsonPropertyName("enablePayAtTable")] + public bool? EnablePayAtTable { get { return this._EnablePayAtTableOption; } set { this._EnablePayAtTableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayAtTableStoreNumberOption { get; private set; } + + /// + /// The store number to use for Pay at Table. + /// + /// The store number to use for Pay at Table. + [JsonPropertyName("payAtTableStoreNumber")] + public string? PayAtTableStoreNumber { get { return this._PayAtTableStoreNumberOption; } set { this._PayAtTableStoreNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayAtTableURLOption { get; private set; } + + /// + /// The URL and port number used for Pay at Table communication. + /// + /// The URL and port number used for Pay at Table communication. + [JsonPropertyName("payAtTableURL")] + public string? PayAtTableURL { get { return this._PayAtTableURLOption; } set { this._PayAtTableURLOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Opi {\n"); + sb.Append(" EnablePayAtTable: ").Append(EnablePayAtTable).Append("\n"); + sb.Append(" PayAtTableStoreNumber: ").Append(PayAtTableStoreNumber).Append("\n"); + sb.Append(" PayAtTableURL: ").Append(PayAtTableURL).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Opi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enablePayAtTable = default; + Option payAtTableStoreNumber = default; + Option payAtTableURL = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enablePayAtTable": + enablePayAtTable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "payAtTableStoreNumber": + payAtTableStoreNumber = new Option(utf8JsonReader.GetString()!); + break; + case "payAtTableURL": + payAtTableURL = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Opi(enablePayAtTable, payAtTableStoreNumber, payAtTableURL); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Opi opi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, opi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Opi opi, JsonSerializerOptions jsonSerializerOptions) + { + + if (opi._EnablePayAtTableOption.IsSet) + writer.WriteBoolean("enablePayAtTable", opi._EnablePayAtTableOption.Value!.Value); + + if (opi._PayAtTableStoreNumberOption.IsSet) + if (opi.PayAtTableStoreNumber != null) + writer.WriteString("payAtTableStoreNumber", opi.PayAtTableStoreNumber); + + if (opi._PayAtTableURLOption.IsSet) + if (opi.PayAtTableURL != null) + writer.WriteString("payAtTableURL", opi.PayAtTableURL); + } + } +} diff --git a/Adyen/Management/Models/OrderItem.cs b/Adyen/Management/Models/OrderItem.cs new file mode 100644 index 000000000..692b34674 --- /dev/null +++ b/Adyen/Management/Models/OrderItem.cs @@ -0,0 +1,250 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// OrderItem. + /// + public partial class OrderItem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the product. + /// The number of installments for the specified product `id`. + /// The name of the product. + /// The number of items with the specified product `id` included in the order. + [JsonConstructor] + public OrderItem(Option id = default, Option installments = default, Option name = default, Option quantity = default) + { + _IdOption = id; + _InstallmentsOption = installments; + _NameOption = name; + _QuantityOption = quantity; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public OrderItem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the product. + /// + /// The unique identifier of the product. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// The number of installments for the specified product `id`. + /// + /// The number of installments for the specified product `id`. + [JsonPropertyName("installments")] + public long? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the product. + /// + /// The name of the product. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _QuantityOption { get; private set; } + + /// + /// The number of items with the specified product `id` included in the order. + /// + /// The number of items with the specified product `id` included in the order. + [JsonPropertyName("quantity")] + public int? Quantity { get { return this._QuantityOption; } set { this._QuantityOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OrderItem {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OrderItemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override OrderItem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option installments = default; + Option name = default; + Option quantity = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "installments": + installments = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "quantity": + quantity = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new OrderItem(id, installments, name, quantity); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OrderItem orderItem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, orderItem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OrderItem orderItem, JsonSerializerOptions jsonSerializerOptions) + { + + if (orderItem._IdOption.IsSet) + if (orderItem.Id != null) + writer.WriteString("id", orderItem.Id); + + if (orderItem._InstallmentsOption.IsSet) + writer.WriteNumber("installments", orderItem._InstallmentsOption.Value!.Value); + + if (orderItem._NameOption.IsSet) + if (orderItem.Name != null) + writer.WriteString("name", orderItem.Name); + + if (orderItem._QuantityOption.IsSet) + writer.WriteNumber("quantity", orderItem._QuantityOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/PaginationLinks.cs b/Adyen/Management/Models/PaginationLinks.cs new file mode 100644 index 000000000..51a13cc69 --- /dev/null +++ b/Adyen/Management/Models/PaginationLinks.cs @@ -0,0 +1,256 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PaginationLinks. + /// + public partial class PaginationLinks : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// first + /// last + /// self + /// next + /// prev + [JsonConstructor] + public PaginationLinks(LinksElement first, LinksElement last, LinksElement self, Option next = default, Option prev = default) + { + First = first; + Last = last; + Self = self; + _NextOption = next; + _PrevOption = prev; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaginationLinks() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("first")] + public LinksElement First { get; set; } + + /// + /// . + /// + [JsonPropertyName("last")] + public LinksElement Last { get; set; } + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NextOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("next")] + public LinksElement? Next { get { return this._NextOption; } set { this._NextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrevOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("prev")] + public LinksElement? Prev { get { return this._PrevOption; } set { this._PrevOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaginationLinks {\n"); + sb.Append(" First: ").Append(First).Append("\n"); + sb.Append(" Last: ").Append(Last).Append("\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append(" Next: ").Append(Next).Append("\n"); + sb.Append(" Prev: ").Append(Prev).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaginationLinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaginationLinks Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option first = default; + Option last = default; + Option self = default; + Option next = default; + Option prev = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "first": + first = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "last": + last = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next": + next = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "prev": + prev = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!first.IsSet) + throw new ArgumentException("Property is required for class PaginationLinks.", nameof(first)); + + if (!last.IsSet) + throw new ArgumentException("Property is required for class PaginationLinks.", nameof(last)); + + if (!self.IsSet) + throw new ArgumentException("Property is required for class PaginationLinks.", nameof(self)); + + return new PaginationLinks(first.Value!, last.Value!, self.Value!, next, prev); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaginationLinks paginationLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paginationLinks, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaginationLinks paginationLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("first"); + JsonSerializer.Serialize(writer, paginationLinks.First, jsonSerializerOptions); + writer.WritePropertyName("last"); + JsonSerializer.Serialize(writer, paginationLinks.Last, jsonSerializerOptions); + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, paginationLinks.Self, jsonSerializerOptions); + if (paginationLinks._NextOption.IsSet) + { + writer.WritePropertyName("next"); + JsonSerializer.Serialize(writer, paginationLinks.Next, jsonSerializerOptions); + } + if (paginationLinks._PrevOption.IsSet) + { + writer.WritePropertyName("prev"); + JsonSerializer.Serialize(writer, paginationLinks.Prev, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Passcodes.cs b/Adyen/Management/Models/Passcodes.cs new file mode 100644 index 000000000..dc090a5da --- /dev/null +++ b/Adyen/Management/Models/Passcodes.cs @@ -0,0 +1,282 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Passcodes. + /// + public partial class Passcodes : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The passcode for the Admin menu and the Settings menu. + /// The passcode for referenced and unreferenced refunds on standalone terminals. + /// The passcode to unlock the terminal screen after a timeout. + /// The passcode for the Transactions menu. + [JsonConstructor] + public Passcodes(Option adminMenuPin = default, Option refundPin = default, Option screenLockPin = default, Option txMenuPin = default) + { + _AdminMenuPinOption = adminMenuPin; + _RefundPinOption = refundPin; + _ScreenLockPinOption = screenLockPin; + _TxMenuPinOption = txMenuPin; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Passcodes() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdminMenuPinOption { get; private set; } + + /// + /// The passcode for the Admin menu and the Settings menu. + /// + /// The passcode for the Admin menu and the Settings menu. + [JsonPropertyName("adminMenuPin")] + public string? AdminMenuPin { get { return this._AdminMenuPinOption; } set { this._AdminMenuPinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundPinOption { get; private set; } + + /// + /// The passcode for referenced and unreferenced refunds on standalone terminals. + /// + /// The passcode for referenced and unreferenced refunds on standalone terminals. + [JsonPropertyName("refundPin")] + public string? RefundPin { get { return this._RefundPinOption; } set { this._RefundPinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScreenLockPinOption { get; private set; } + + /// + /// The passcode to unlock the terminal screen after a timeout. + /// + /// The passcode to unlock the terminal screen after a timeout. + [JsonPropertyName("screenLockPin")] + public string? ScreenLockPin { get { return this._ScreenLockPinOption; } set { this._ScreenLockPinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TxMenuPinOption { get; private set; } + + /// + /// The passcode for the Transactions menu. + /// + /// The passcode for the Transactions menu. + [JsonPropertyName("txMenuPin")] + public string? TxMenuPin { get { return this._TxMenuPinOption; } set { this._TxMenuPinOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Passcodes {\n"); + sb.Append(" AdminMenuPin: ").Append(AdminMenuPin).Append("\n"); + sb.Append(" RefundPin: ").Append(RefundPin).Append("\n"); + sb.Append(" ScreenLockPin: ").Append(ScreenLockPin).Append("\n"); + sb.Append(" TxMenuPin: ").Append(TxMenuPin).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AdminMenuPin (string) maxLength + if (this.AdminMenuPin != null && this.AdminMenuPin.Length > 6) + { + yield return new ValidationResult("Invalid value for AdminMenuPin, length must be less than 6.", new [] { "AdminMenuPin" }); + } + + // RefundPin (string) maxLength + if (this.RefundPin != null && this.RefundPin.Length > 6) + { + yield return new ValidationResult("Invalid value for RefundPin, length must be less than 6.", new [] { "RefundPin" }); + } + + // ScreenLockPin (string) maxLength + if (this.ScreenLockPin != null && this.ScreenLockPin.Length > 6) + { + yield return new ValidationResult("Invalid value for ScreenLockPin, length must be less than 6.", new [] { "ScreenLockPin" }); + } + + // ScreenLockPin (string) minLength + if (this.ScreenLockPin != null && this.ScreenLockPin.Length < 4) + { + yield return new ValidationResult("Invalid value for ScreenLockPin, length must be greater than 4.", new [] { "ScreenLockPin" }); + } + + // TxMenuPin (string) maxLength + if (this.TxMenuPin != null && this.TxMenuPin.Length > 6) + { + yield return new ValidationResult("Invalid value for TxMenuPin, length must be less than 6.", new [] { "TxMenuPin" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PasscodesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Passcodes Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option adminMenuPin = default; + Option refundPin = default; + Option screenLockPin = default; + Option txMenuPin = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "adminMenuPin": + adminMenuPin = new Option(utf8JsonReader.GetString()!); + break; + case "refundPin": + refundPin = new Option(utf8JsonReader.GetString()!); + break; + case "screenLockPin": + screenLockPin = new Option(utf8JsonReader.GetString()!); + break; + case "txMenuPin": + txMenuPin = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Passcodes(adminMenuPin, refundPin, screenLockPin, txMenuPin); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Passcodes passcodes, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, passcodes, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Passcodes passcodes, JsonSerializerOptions jsonSerializerOptions) + { + + if (passcodes._AdminMenuPinOption.IsSet) + if (passcodes.AdminMenuPin != null) + writer.WriteString("adminMenuPin", passcodes.AdminMenuPin); + + if (passcodes._RefundPinOption.IsSet) + if (passcodes.RefundPin != null) + writer.WriteString("refundPin", passcodes.RefundPin); + + if (passcodes._ScreenLockPinOption.IsSet) + if (passcodes.ScreenLockPin != null) + writer.WriteString("screenLockPin", passcodes.ScreenLockPin); + + if (passcodes._TxMenuPinOption.IsSet) + if (passcodes.TxMenuPin != null) + writer.WriteString("txMenuPin", passcodes.TxMenuPin); + } + } +} diff --git a/Adyen/Management/Models/PayAtTable.cs b/Adyen/Management/Models/PayAtTable.cs new file mode 100644 index 000000000..e05cf531a --- /dev/null +++ b/Adyen/Management/Models/PayAtTable.cs @@ -0,0 +1,438 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayAtTable. + /// + public partial class PayAtTable : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Allowed authentication methods: Magswipe, Manual Entry. + /// Enable Pay at table. + /// Sets the allowed payment instrument for Pay at table transactions. Can be: **cash** or **card**. If not set, the terminal presents both options. + [JsonConstructor] + public PayAtTable(Option authenticationMethod = default, Option enablePayAtTable = default, Option paymentInstrument = default) + { + _AuthenticationMethodOption = authenticationMethod; + _EnablePayAtTableOption = enablePayAtTable; + _PaymentInstrumentOption = paymentInstrument; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayAtTable() + { + } + + partial void OnCreated(); + + /// + /// Allowed authentication methods: Magswipe, Manual Entry. + /// + /// Allowed authentication methods: Magswipe, Manual Entry. + [JsonConverter(typeof(AuthenticationMethodEnumJsonConverter))] + public class AuthenticationMethodEnum : IEnum + { + /// + /// Returns the value of the AuthenticationMethodEnum. + /// + public string? Value { get; set; } + + /// + /// AuthenticationMethodEnum.MAGSWIPE - MAGSWIPE + /// + public static readonly AuthenticationMethodEnum MAGSWIPE = new("MAGSWIPE"); + + /// + /// AuthenticationMethodEnum.MKE - MKE + /// + public static readonly AuthenticationMethodEnum MKE = new("MKE"); + + private AuthenticationMethodEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AuthenticationMethodEnum?(string? value) => value == null ? null : new AuthenticationMethodEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AuthenticationMethodEnum? option) => option?.Value; + + public static bool operator ==(AuthenticationMethodEnum? left, AuthenticationMethodEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AuthenticationMethodEnum? left, AuthenticationMethodEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AuthenticationMethodEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AuthenticationMethodEnum? FromStringOrDefault(string value) + { + return value switch { + "MAGSWIPE" => AuthenticationMethodEnum.MAGSWIPE, + "MKE" => AuthenticationMethodEnum.MKE, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AuthenticationMethodEnum? value) + { + if (value == null) + return null; + + if (value == AuthenticationMethodEnum.MAGSWIPE) + return "MAGSWIPE"; + + if (value == AuthenticationMethodEnum.MKE) + return "MKE"; + + return null; + } + + /// + /// JsonConverter for writing AuthenticationMethodEnum. + /// + public class AuthenticationMethodEnumJsonConverter : JsonConverter + { + public override AuthenticationMethodEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AuthenticationMethodEnum.FromStringOrDefault(value) ?? new AuthenticationMethodEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AuthenticationMethodEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AuthenticationMethodEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationMethodOption { get; private set; } + + /// + /// Allowed authentication methods: Magswipe, Manual Entry. + /// + /// Allowed authentication methods: Magswipe, Manual Entry. + [JsonPropertyName("authenticationMethod")] + public AuthenticationMethodEnum? AuthenticationMethod { get { return this._AuthenticationMethodOption; } set { this._AuthenticationMethodOption = new(value); } } + + /// + /// Sets the allowed payment instrument for Pay at table transactions. Can be: **cash** or **card**. If not set, the terminal presents both options. + /// + /// Sets the allowed payment instrument for Pay at table transactions. Can be: **cash** or **card**. If not set, the terminal presents both options. + [JsonConverter(typeof(PaymentInstrumentEnumJsonConverter))] + public class PaymentInstrumentEnum : IEnum + { + /// + /// Returns the value of the PaymentInstrumentEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentInstrumentEnum.Cash - Cash + /// + public static readonly PaymentInstrumentEnum Cash = new("Cash"); + + /// + /// PaymentInstrumentEnum.Card - Card + /// + public static readonly PaymentInstrumentEnum Card = new("Card"); + + private PaymentInstrumentEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentInstrumentEnum?(string? value) => value == null ? null : new PaymentInstrumentEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentInstrumentEnum? option) => option?.Value; + + public static bool operator ==(PaymentInstrumentEnum? left, PaymentInstrumentEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentInstrumentEnum? left, PaymentInstrumentEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentInstrumentEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentInstrumentEnum? FromStringOrDefault(string value) + { + return value switch { + "Cash" => PaymentInstrumentEnum.Cash, + "Card" => PaymentInstrumentEnum.Card, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentInstrumentEnum? value) + { + if (value == null) + return null; + + if (value == PaymentInstrumentEnum.Cash) + return "Cash"; + + if (value == PaymentInstrumentEnum.Card) + return "Card"; + + return null; + } + + /// + /// JsonConverter for writing PaymentInstrumentEnum. + /// + public class PaymentInstrumentEnumJsonConverter : JsonConverter + { + public override PaymentInstrumentEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentInstrumentEnum.FromStringOrDefault(value) ?? new PaymentInstrumentEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentInstrumentEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentInstrumentEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// Sets the allowed payment instrument for Pay at table transactions. Can be: **cash** or **card**. If not set, the terminal presents both options. + /// + /// Sets the allowed payment instrument for Pay at table transactions. Can be: **cash** or **card**. If not set, the terminal presents both options. + [JsonPropertyName("paymentInstrument")] + public PaymentInstrumentEnum? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnablePayAtTableOption { get; private set; } + + /// + /// Enable Pay at table. + /// + /// Enable Pay at table. + [JsonPropertyName("enablePayAtTable")] + public bool? EnablePayAtTable { get { return this._EnablePayAtTableOption; } set { this._EnablePayAtTableOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayAtTable {\n"); + sb.Append(" AuthenticationMethod: ").Append(AuthenticationMethod).Append("\n"); + sb.Append(" EnablePayAtTable: ").Append(EnablePayAtTable).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayAtTableJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayAtTable Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationMethod = default; + Option enablePayAtTable = default; + Option paymentInstrument = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationMethod": + string? authenticationMethodRawValue = utf8JsonReader.GetString(); + authenticationMethod = new Option(PayAtTable.AuthenticationMethodEnum.FromStringOrDefault(authenticationMethodRawValue)); + break; + case "enablePayAtTable": + enablePayAtTable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentInstrument": + string? paymentInstrumentRawValue = utf8JsonReader.GetString(); + paymentInstrument = new Option(PayAtTable.PaymentInstrumentEnum.FromStringOrDefault(paymentInstrumentRawValue)); + break; + default: + break; + } + } + } + + + return new PayAtTable(authenticationMethod, enablePayAtTable, paymentInstrument); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayAtTable payAtTable, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payAtTable, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayAtTable payAtTable, JsonSerializerOptions jsonSerializerOptions) + { + + if (payAtTable._AuthenticationMethodOption.IsSet && payAtTable.AuthenticationMethod != null) + { + string? authenticationMethodRawValue = PayAtTable.AuthenticationMethodEnum.ToJsonValue(payAtTable._AuthenticationMethodOption.Value!.Value); + writer.WriteString("authenticationMethod", authenticationMethodRawValue); + } + + if (payAtTable._EnablePayAtTableOption.IsSet) + writer.WriteBoolean("enablePayAtTable", payAtTable._EnablePayAtTableOption.Value!.Value); + + var paymentInstrumentRawValue = PayAtTable.PaymentInstrumentEnum.ToJsonValue(payAtTable._PaymentInstrumentOption.Value!.Value); + if (paymentInstrumentRawValue != null) + writer.WriteString("paymentInstrument", paymentInstrumentRawValue); + else + writer.WriteNull("paymentInstrument"); + } + } +} diff --git a/Adyen/Management/Models/PayByBankPlaidInfo.cs b/Adyen/Management/Models/PayByBankPlaidInfo.cs new file mode 100644 index 000000000..76a5d518a --- /dev/null +++ b/Adyen/Management/Models/PayByBankPlaidInfo.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayByBankPlaidInfo. + /// + public partial class PayByBankPlaidInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Merchant logo (max. size 150kB). Format: Base64-encoded string. + /// transactionDescription + [JsonConstructor] + public PayByBankPlaidInfo(Option logo = default, Option transactionDescription = default) + { + _LogoOption = logo; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayByBankPlaidInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LogoOption { get; private set; } + + /// + /// Merchant logo (max. size 150kB). Format: Base64-encoded string. + /// + /// Merchant logo (max. size 150kB). Format: Base64-encoded string. + [JsonPropertyName("logo")] + public string? Logo { get { return this._LogoOption; } set { this._LogoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayByBankPlaidInfo {\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayByBankPlaidInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayByBankPlaidInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option logo = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PayByBankPlaidInfo(logo, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayByBankPlaidInfo payByBankPlaidInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payByBankPlaidInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayByBankPlaidInfo payByBankPlaidInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (payByBankPlaidInfo._LogoOption.IsSet) + if (payByBankPlaidInfo.Logo != null) + writer.WriteString("logo", payByBankPlaidInfo.Logo); + + if (payByBankPlaidInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, payByBankPlaidInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/PayMeInfo.cs b/Adyen/Management/Models/PayMeInfo.cs new file mode 100644 index 000000000..a98733f85 --- /dev/null +++ b/Adyen/Management/Models/PayMeInfo.cs @@ -0,0 +1,211 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayMeInfo. + /// + public partial class PayMeInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Merchant display name + /// Merchant logo. Format: Base64-encoded string. + /// The email address of merchant support. + [JsonConstructor] + public PayMeInfo(string displayName, string logo, string supportEmail) + { + DisplayName = displayName; + Logo = logo; + SupportEmail = supportEmail; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayMeInfo() + { + } + + partial void OnCreated(); + + /// + /// Merchant display name + /// + /// Merchant display name + [JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + /// + /// Merchant logo. Format: Base64-encoded string. + /// + /// Merchant logo. Format: Base64-encoded string. + [JsonPropertyName("logo")] + public string Logo { get; set; } + + /// + /// The email address of merchant support. + /// + /// The email address of merchant support. + [JsonPropertyName("supportEmail")] + public string SupportEmail { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayMeInfo {\n"); + sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append(" SupportEmail: ").Append(SupportEmail).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayMeInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayMeInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option displayName = default; + Option logo = default; + Option supportEmail = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "displayName": + displayName = new Option(utf8JsonReader.GetString()!); + break; + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + case "supportEmail": + supportEmail = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!displayName.IsSet) + throw new ArgumentException("Property is required for class PayMeInfo.", nameof(displayName)); + + if (!logo.IsSet) + throw new ArgumentException("Property is required for class PayMeInfo.", nameof(logo)); + + if (!supportEmail.IsSet) + throw new ArgumentException("Property is required for class PayMeInfo.", nameof(supportEmail)); + + return new PayMeInfo(displayName.Value!, logo.Value!, supportEmail.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayMeInfo payMeInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payMeInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayMeInfo payMeInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (payMeInfo.DisplayName != null) + writer.WriteString("displayName", payMeInfo.DisplayName); + + if (payMeInfo.Logo != null) + writer.WriteString("logo", payMeInfo.Logo); + + if (payMeInfo.SupportEmail != null) + writer.WriteString("supportEmail", payMeInfo.SupportEmail); + } + } +} diff --git a/Adyen/Management/Models/PayPalInfo.cs b/Adyen/Management/Models/PayPalInfo.cs new file mode 100644 index 000000000..a2e456f70 --- /dev/null +++ b/Adyen/Management/Models/PayPalInfo.cs @@ -0,0 +1,227 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayPalInfo. + /// + public partial class PayPalInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// PayPal Merchant ID. Character length and limitations: 13 single-byte alphanumeric characters. + /// Your business email address. + /// Indicates if direct (immediate) capture for PayPal is enabled. If set to **true**, this setting overrides the [capture](https://docs.adyen.com/online-payments/capture) settings of your merchant account. Default value: **true**. + [JsonConstructor] + public PayPalInfo(string payerId, string subject, Option directCapture = default) + { + PayerId = payerId; + Subject = subject; + _DirectCaptureOption = directCapture; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayPalInfo() + { + } + + partial void OnCreated(); + + /// + /// PayPal Merchant ID. Character length and limitations: 13 single-byte alphanumeric characters. + /// + /// PayPal Merchant ID. Character length and limitations: 13 single-byte alphanumeric characters. + [JsonPropertyName("payerId")] + public string PayerId { get; set; } + + /// + /// Your business email address. + /// + /// Your business email address. + [JsonPropertyName("subject")] + public string Subject { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectCaptureOption { get; private set; } + + /// + /// Indicates if direct (immediate) capture for PayPal is enabled. If set to **true**, this setting overrides the [capture](https://docs.adyen.com/online-payments/capture) settings of your merchant account. Default value: **true**. + /// + /// Indicates if direct (immediate) capture for PayPal is enabled. If set to **true**, this setting overrides the [capture](https://docs.adyen.com/online-payments/capture) settings of your merchant account. Default value: **true**. + [JsonPropertyName("directCapture")] + public bool? DirectCapture { get { return this._DirectCaptureOption; } set { this._DirectCaptureOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayPalInfo {\n"); + sb.Append(" PayerId: ").Append(PayerId).Append("\n"); + sb.Append(" Subject: ").Append(Subject).Append("\n"); + sb.Append(" DirectCapture: ").Append(DirectCapture).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // PayerId (string) maxLength + if (this.PayerId != null && this.PayerId.Length > 13) + { + yield return new ValidationResult("Invalid value for PayerId, length must be less than 13.", new [] { "PayerId" }); + } + + // PayerId (string) minLength + if (this.PayerId != null && this.PayerId.Length < 13) + { + yield return new ValidationResult("Invalid value for PayerId, length must be greater than 13.", new [] { "PayerId" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayPalInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayPalInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option payerId = default; + Option subject = default; + Option directCapture = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "payerId": + payerId = new Option(utf8JsonReader.GetString()!); + break; + case "subject": + subject = new Option(utf8JsonReader.GetString()!); + break; + case "directCapture": + directCapture = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!payerId.IsSet) + throw new ArgumentException("Property is required for class PayPalInfo.", nameof(payerId)); + + if (!subject.IsSet) + throw new ArgumentException("Property is required for class PayPalInfo.", nameof(subject)); + + return new PayPalInfo(payerId.Value!, subject.Value!, directCapture); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayPalInfo payPalInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payPalInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayPalInfo payPalInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (payPalInfo.PayerId != null) + writer.WriteString("payerId", payPalInfo.PayerId); + + if (payPalInfo.Subject != null) + writer.WriteString("subject", payPalInfo.Subject); + + if (payPalInfo._DirectCaptureOption.IsSet) + writer.WriteBoolean("directCapture", payPalInfo._DirectCaptureOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/PayToInfo.cs b/Adyen/Management/Models/PayToInfo.cs new file mode 100644 index 000000000..ea7e10114 --- /dev/null +++ b/Adyen/Management/Models/PayToInfo.cs @@ -0,0 +1,191 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayToInfo. + /// + public partial class PayToInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Merchant name displayed to the shopper in the Agreements + /// Represents the purpose of the Agreements created, it relates to the business type **Allowed values**: mortgage, utility, loan, gambling, retail, salary, personal, government, pension, tax, other + [JsonConstructor] + public PayToInfo(string merchantName, string payToPurpose) + { + MerchantName = merchantName; + PayToPurpose = payToPurpose; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayToInfo() + { + } + + partial void OnCreated(); + + /// + /// Merchant name displayed to the shopper in the Agreements + /// + /// Merchant name displayed to the shopper in the Agreements + [JsonPropertyName("merchantName")] + public string MerchantName { get; set; } + + /// + /// Represents the purpose of the Agreements created, it relates to the business type **Allowed values**: mortgage, utility, loan, gambling, retail, salary, personal, government, pension, tax, other + /// + /// Represents the purpose of the Agreements created, it relates to the business type **Allowed values**: mortgage, utility, loan, gambling, retail, salary, personal, government, pension, tax, other + [JsonPropertyName("payToPurpose")] + public string PayToPurpose { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayToInfo {\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" PayToPurpose: ").Append(PayToPurpose).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayToInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayToInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantName = default; + Option payToPurpose = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "payToPurpose": + payToPurpose = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantName.IsSet) + throw new ArgumentException("Property is required for class PayToInfo.", nameof(merchantName)); + + if (!payToPurpose.IsSet) + throw new ArgumentException("Property is required for class PayToInfo.", nameof(payToPurpose)); + + return new PayToInfo(merchantName.Value!, payToPurpose.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayToInfo payToInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payToInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayToInfo payToInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (payToInfo.MerchantName != null) + writer.WriteString("merchantName", payToInfo.MerchantName); + + if (payToInfo.PayToPurpose != null) + writer.WriteString("payToPurpose", payToInfo.PayToPurpose); + } + } +} diff --git a/Adyen/Management/Models/Payment.cs b/Adyen/Management/Models/Payment.cs new file mode 100644 index 000000000..ac24acf87 --- /dev/null +++ b/Adyen/Management/Models/Payment.cs @@ -0,0 +1,216 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Payment. + /// + public partial class Payment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The default currency for contactless payments on the payment terminal, as the three-letter [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + /// Hides the minor units for the listed [ISO currency codes](https://en.wikipedia.org/wiki/ISO_4217). + [JsonConstructor] + public Payment(Option contactlessCurrency = default, Option?> hideMinorUnitsInCurrencies = default) + { + _ContactlessCurrencyOption = contactlessCurrency; + _HideMinorUnitsInCurrenciesOption = hideMinorUnitsInCurrencies; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Payment() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactlessCurrencyOption { get; private set; } + + /// + /// The default currency for contactless payments on the payment terminal, as the three-letter [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + /// + /// The default currency for contactless payments on the payment terminal, as the three-letter [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + [JsonPropertyName("contactlessCurrency")] + public string? ContactlessCurrency { get { return this._ContactlessCurrencyOption; } set { this._ContactlessCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _HideMinorUnitsInCurrenciesOption { get; private set; } + + /// + /// Hides the minor units for the listed [ISO currency codes](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// Hides the minor units for the listed [ISO currency codes](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("hideMinorUnitsInCurrencies")] + public List? HideMinorUnitsInCurrencies { get { return this._HideMinorUnitsInCurrenciesOption; } set { this._HideMinorUnitsInCurrenciesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Payment {\n"); + sb.Append(" ContactlessCurrency: ").Append(ContactlessCurrency).Append("\n"); + sb.Append(" HideMinorUnitsInCurrencies: ").Append(HideMinorUnitsInCurrencies).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ContactlessCurrency (string) maxLength + if (this.ContactlessCurrency != null && this.ContactlessCurrency.Length > 3) + { + yield return new ValidationResult("Invalid value for ContactlessCurrency, length must be less than 3.", new [] { "ContactlessCurrency" }); + } + + // ContactlessCurrency (string) minLength + if (this.ContactlessCurrency != null && this.ContactlessCurrency.Length < 3) + { + yield return new ValidationResult("Invalid value for ContactlessCurrency, length must be greater than 3.", new [] { "ContactlessCurrency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Payment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contactlessCurrency = default; + Option?> hideMinorUnitsInCurrencies = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contactlessCurrency": + contactlessCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "hideMinorUnitsInCurrencies": + hideMinorUnitsInCurrencies = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Payment(contactlessCurrency, hideMinorUnitsInCurrencies); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Payment payment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Payment payment, JsonSerializerOptions jsonSerializerOptions) + { + + if (payment._ContactlessCurrencyOption.IsSet) + if (payment.ContactlessCurrency != null) + writer.WriteString("contactlessCurrency", payment.ContactlessCurrency); + + if (payment._HideMinorUnitsInCurrenciesOption.IsSet) + { + writer.WritePropertyName("hideMinorUnitsInCurrencies"); + JsonSerializer.Serialize(writer, payment.HideMinorUnitsInCurrencies, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/PaymentMethod.cs b/Adyen/Management/Models/PaymentMethod.cs new file mode 100644 index 000000000..55c560c34 --- /dev/null +++ b/Adyen/Management/Models/PaymentMethod.cs @@ -0,0 +1,1604 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PaymentMethod. + /// + public partial class PaymentMethod : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource. + /// accel + /// affirm + /// afterpayTouch + /// alipayPlus + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + /// amex + /// applePay + /// bcmc + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + /// cartesBancaires + /// clearpay + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// cup + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// The list of custom routing flags to route payment to the intended acquirer. + /// diners + /// discover + /// eftDirectdebitCA + /// eftposAustralia + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// girocard + /// googlePay + /// ideal + /// interacCard + /// jcb + /// klarna + /// maestro + /// maestroUsa + /// mc + /// mealVoucherFR + /// nyce + /// paybybankPlaid + /// payme + /// paypal + /// payto + /// pulse + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + /// sepadirectdebit + /// The sales channel. + /// sodexo + /// sofort + /// star + /// The unique identifier of the store for which to configure the payment method, if any. + /// swish + /// ticket + /// twint + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + /// vipps + /// visa + /// wechatpay + /// wechatpayPos + [JsonConstructor] + public PaymentMethod(string id, Option accel = default, Option affirm = default, Option afterpayTouch = default, Option alipayPlus = default, Option allowed = default, Option amex = default, Option applePay = default, Option bcmc = default, Option businessLineId = default, Option cartesBancaires = default, Option clearpay = default, Option?> countries = default, Option cup = default, Option?> currencies = default, Option?> customRoutingFlags = default, Option diners = default, Option discover = default, Option eftDirectdebitCA = default, Option eftposAustralia = default, Option enabled = default, Option girocard = default, Option googlePay = default, Option ideal = default, Option interacCard = default, Option jcb = default, Option klarna = default, Option maestro = default, Option maestroUsa = default, Option mc = default, Option mealVoucherFR = default, Option nyce = default, Option paybybankPlaid = default, Option payme = default, Option paypal = default, Option payto = default, Option pulse = default, Option reference = default, Option sepadirectdebit = default, Option shopperInteraction = default, Option sodexo = default, Option sofort = default, Option star = default, Option?> storeIds = default, Option swish = default, Option ticket = default, Option twint = default, Option type = default, Option verificationStatus = default, Option vipps = default, Option visa = default, Option wechatpay = default, Option wechatpayPos = default) + { + Id = id; + _AccelOption = accel; + _AffirmOption = affirm; + _AfterpayTouchOption = afterpayTouch; + _AlipayPlusOption = alipayPlus; + _AllowedOption = allowed; + _AmexOption = amex; + _ApplePayOption = applePay; + _BcmcOption = bcmc; + _BusinessLineIdOption = businessLineId; + _CartesBancairesOption = cartesBancaires; + _ClearpayOption = clearpay; + _CountriesOption = countries; + _CupOption = cup; + _CurrenciesOption = currencies; + _CustomRoutingFlagsOption = customRoutingFlags; + _DinersOption = diners; + _DiscoverOption = discover; + _EftDirectdebitCAOption = eftDirectdebitCA; + _EftposAustraliaOption = eftposAustralia; + _EnabledOption = enabled; + _GirocardOption = girocard; + _GooglePayOption = googlePay; + _IdealOption = ideal; + _InteracCardOption = interacCard; + _JcbOption = jcb; + _KlarnaOption = klarna; + _MaestroOption = maestro; + _MaestroUsaOption = maestroUsa; + _McOption = mc; + _MealVoucherFROption = mealVoucherFR; + _NyceOption = nyce; + _PaybybankPlaidOption = paybybankPlaid; + _PaymeOption = payme; + _PaypalOption = paypal; + _PaytoOption = payto; + _PulseOption = pulse; + _ReferenceOption = reference; + _SepadirectdebitOption = sepadirectdebit; + _ShopperInteractionOption = shopperInteraction; + _SodexoOption = sodexo; + _SofortOption = sofort; + _StarOption = star; + _StoreIdsOption = storeIds; + _SwishOption = swish; + _TicketOption = ticket; + _TwintOption = twint; + _TypeOption = type; + _VerificationStatusOption = verificationStatus; + _VippsOption = vipps; + _VisaOption = visa; + _WechatpayOption = wechatpay; + _WechatpayPosOption = wechatpayPos; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethod() + { + } + + partial void OnCreated(); + + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "valid" => VerificationStatusEnum.Valid, + "pending" => VerificationStatusEnum.Pending, + "invalid" => VerificationStatusEnum.Invalid, + "rejected" => VerificationStatusEnum.Rejected, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// The identifier of the resource. + /// + /// The identifier of the resource. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccelOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accel")] + public AccelInfo? Accel { get { return this._AccelOption; } set { this._AccelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AffirmOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("affirm")] + public AffirmInfo? Affirm { get { return this._AffirmOption; } set { this._AffirmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AfterpayTouchOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("afterpayTouch")] + public AfterpayTouchInfo? AfterpayTouch { get { return this._AfterpayTouchOption; } set { this._AfterpayTouchOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AlipayPlusOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("alipayPlus")] + public AlipayPlusInfo? AlipayPlus { get { return this._AlipayPlusOption; } set { this._AlipayPlusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + /// + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmexOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amex")] + public AmexInfo? Amex { get { return this._AmexOption; } set { this._AmexOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplePayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applePay")] + public ApplePayInfo? ApplePay { get { return this._ApplePayOption; } set { this._ApplePayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BcmcOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bcmc")] + public BcmcInfo? Bcmc { get { return this._BcmcOption; } set { this._BcmcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessLineIdOption { get; private set; } + + /// + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + /// + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + [JsonPropertyName("businessLineId")] + public string? BusinessLineId { get { return this._BusinessLineIdOption; } set { this._BusinessLineIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CartesBancairesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cartesBancaires")] + public CartesBancairesInfo? CartesBancaires { get { return this._CartesBancairesOption; } set { this._CartesBancairesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClearpayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("clearpay")] + public ClearpayInfo? Clearpay { get { return this._ClearpayOption; } set { this._ClearpayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CountriesOption { get; private set; } + + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + [JsonPropertyName("countries")] + public List? Countries { get { return this._CountriesOption; } set { this._CountriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cup")] + public GenericPmWithTdiInfo? Cup { get { return this._CupOption; } set { this._CupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CurrenciesOption { get; private set; } + + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + [JsonPropertyName("currencies")] + public List? Currencies { get { return this._CurrenciesOption; } set { this._CurrenciesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CustomRoutingFlagsOption { get; private set; } + + /// + /// The list of custom routing flags to route payment to the intended acquirer. + /// + /// The list of custom routing flags to route payment to the intended acquirer. + [JsonPropertyName("customRoutingFlags")] + public List? CustomRoutingFlags { get { return this._CustomRoutingFlagsOption; } set { this._CustomRoutingFlagsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DinersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("diners")] + public DinersInfo? Diners { get { return this._DinersOption; } set { this._DinersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DiscoverOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("discover")] + public GenericPmWithTdiInfo? Discover { get { return this._DiscoverOption; } set { this._DiscoverOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftDirectdebitCAOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eft_directdebit_CA")] + public GenericPmWithTdiInfo? EftDirectdebitCA { get { return this._EftDirectdebitCAOption; } set { this._EftDirectdebitCAOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftposAustraliaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eftpos_australia")] + public GenericPmWithTdiInfo? EftposAustralia { get { return this._EftposAustraliaOption; } set { this._EftposAustraliaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GirocardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("girocard")] + public GenericPmWithTdiInfo? Girocard { get { return this._GirocardOption; } set { this._GirocardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GooglePayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("googlePay")] + public GooglePayInfo? GooglePay { get { return this._GooglePayOption; } set { this._GooglePayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdealOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ideal")] + public GenericPmWithTdiInfo? Ideal { get { return this._IdealOption; } set { this._IdealOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InteracCardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interac_card")] + public GenericPmWithTdiInfo? InteracCard { get { return this._InteracCardOption; } set { this._InteracCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JcbOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("jcb")] + public JCBInfo? Jcb { get { return this._JcbOption; } set { this._JcbOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KlarnaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("klarna")] + public KlarnaInfo? Klarna { get { return this._KlarnaOption; } set { this._KlarnaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro")] + public GenericPmWithTdiInfo? Maestro { get { return this._MaestroOption; } set { this._MaestroOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroUsaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro_usa")] + public GenericPmWithTdiInfo? MaestroUsa { get { return this._MaestroUsaOption; } set { this._MaestroUsaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mc")] + public GenericPmWithTdiInfo? Mc { get { return this._McOption; } set { this._McOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MealVoucherFROption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mealVoucher_FR")] + public MealVoucherFRInfo? MealVoucherFR { get { return this._MealVoucherFROption; } set { this._MealVoucherFROption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NyceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nyce")] + public NyceInfo? Nyce { get { return this._NyceOption; } set { this._NyceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaybybankPlaidOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paybybank_plaid")] + public PayByBankPlaidInfo? PaybybankPlaid { get { return this._PaybybankPlaidOption; } set { this._PaybybankPlaidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payme")] + public PayMeInfo? Payme { get { return this._PaymeOption; } set { this._PaymeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaypalOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paypal")] + public PayPalInfo? Paypal { get { return this._PaypalOption; } set { this._PaypalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaytoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payto")] + public PayToInfo? Payto { get { return this._PaytoOption; } set { this._PaytoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PulseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pulse")] + public PulseInfo? Pulse { get { return this._PulseOption; } set { this._PulseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + /// + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sepadirectdebit")] + public SepaDirectDebitInfo? Sepadirectdebit { get { return this._SepadirectdebitOption; } set { this._SepadirectdebitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// The sales channel. + /// + /// The sales channel. + [JsonPropertyName("shopperInteraction")] + public string? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SodexoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sodexo")] + public SodexoInfo? Sodexo { get { return this._SodexoOption; } set { this._SodexoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SofortOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sofort")] + public SofortInfo? Sofort { get { return this._SofortOption; } set { this._SofortOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StarOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("star")] + public StarInfo? Star { get { return this._StarOption; } set { this._StarOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _StoreIdsOption { get; private set; } + + /// + /// The unique identifier of the store for which to configure the payment method, if any. + /// + /// The unique identifier of the store for which to configure the payment method, if any. + [JsonPropertyName("storeIds")] + public List? StoreIds { get { return this._StoreIdsOption; } set { this._StoreIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SwishOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("swish")] + public SwishInfo? Swish { get { return this._SwishOption; } set { this._SwishOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TicketOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ticket")] + public TicketInfo? Ticket { get { return this._TicketOption; } set { this._TicketOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TwintOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("twint")] + public TwintInfo? Twint { get { return this._TwintOption; } set { this._TwintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VippsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("vipps")] + public VippsInfo? Vipps { get { return this._VippsOption; } set { this._VippsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("visa")] + public GenericPmWithTdiInfo? Visa { get { return this._VisaOption; } set { this._VisaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WechatpayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wechatpay")] + public WeChatPayInfo? Wechatpay { get { return this._WechatpayOption; } set { this._WechatpayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WechatpayPosOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wechatpay_pos")] + public WeChatPayPosInfo? WechatpayPos { get { return this._WechatpayPosOption; } set { this._WechatpayPosOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethod {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Accel: ").Append(Accel).Append("\n"); + sb.Append(" Affirm: ").Append(Affirm).Append("\n"); + sb.Append(" AfterpayTouch: ").Append(AfterpayTouch).Append("\n"); + sb.Append(" AlipayPlus: ").Append(AlipayPlus).Append("\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" Amex: ").Append(Amex).Append("\n"); + sb.Append(" ApplePay: ").Append(ApplePay).Append("\n"); + sb.Append(" Bcmc: ").Append(Bcmc).Append("\n"); + sb.Append(" BusinessLineId: ").Append(BusinessLineId).Append("\n"); + sb.Append(" CartesBancaires: ").Append(CartesBancaires).Append("\n"); + sb.Append(" Clearpay: ").Append(Clearpay).Append("\n"); + sb.Append(" Countries: ").Append(Countries).Append("\n"); + sb.Append(" Cup: ").Append(Cup).Append("\n"); + sb.Append(" Currencies: ").Append(Currencies).Append("\n"); + sb.Append(" CustomRoutingFlags: ").Append(CustomRoutingFlags).Append("\n"); + sb.Append(" Diners: ").Append(Diners).Append("\n"); + sb.Append(" Discover: ").Append(Discover).Append("\n"); + sb.Append(" EftDirectdebitCA: ").Append(EftDirectdebitCA).Append("\n"); + sb.Append(" EftposAustralia: ").Append(EftposAustralia).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Girocard: ").Append(Girocard).Append("\n"); + sb.Append(" GooglePay: ").Append(GooglePay).Append("\n"); + sb.Append(" Ideal: ").Append(Ideal).Append("\n"); + sb.Append(" InteracCard: ").Append(InteracCard).Append("\n"); + sb.Append(" Jcb: ").Append(Jcb).Append("\n"); + sb.Append(" Klarna: ").Append(Klarna).Append("\n"); + sb.Append(" Maestro: ").Append(Maestro).Append("\n"); + sb.Append(" MaestroUsa: ").Append(MaestroUsa).Append("\n"); + sb.Append(" Mc: ").Append(Mc).Append("\n"); + sb.Append(" MealVoucherFR: ").Append(MealVoucherFR).Append("\n"); + sb.Append(" Nyce: ").Append(Nyce).Append("\n"); + sb.Append(" PaybybankPlaid: ").Append(PaybybankPlaid).Append("\n"); + sb.Append(" Payme: ").Append(Payme).Append("\n"); + sb.Append(" Paypal: ").Append(Paypal).Append("\n"); + sb.Append(" Payto: ").Append(Payto).Append("\n"); + sb.Append(" Pulse: ").Append(Pulse).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Sepadirectdebit: ").Append(Sepadirectdebit).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" Sodexo: ").Append(Sodexo).Append("\n"); + sb.Append(" Sofort: ").Append(Sofort).Append("\n"); + sb.Append(" Star: ").Append(Star).Append("\n"); + sb.Append(" StoreIds: ").Append(StoreIds).Append("\n"); + sb.Append(" Swish: ").Append(Swish).Append("\n"); + sb.Append(" Ticket: ").Append(Ticket).Append("\n"); + sb.Append(" Twint: ").Append(Twint).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append(" Vipps: ").Append(Vipps).Append("\n"); + sb.Append(" Visa: ").Append(Visa).Append("\n"); + sb.Append(" Wechatpay: ").Append(Wechatpay).Append("\n"); + sb.Append(" WechatpayPos: ").Append(WechatpayPos).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethod Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option accel = default; + Option affirm = default; + Option afterpayTouch = default; + Option alipayPlus = default; + Option allowed = default; + Option amex = default; + Option applePay = default; + Option bcmc = default; + Option businessLineId = default; + Option cartesBancaires = default; + Option clearpay = default; + Option?> countries = default; + Option cup = default; + Option?> currencies = default; + Option?> customRoutingFlags = default; + Option diners = default; + Option discover = default; + Option eftDirectdebitCA = default; + Option eftposAustralia = default; + Option enabled = default; + Option girocard = default; + Option googlePay = default; + Option ideal = default; + Option interacCard = default; + Option jcb = default; + Option klarna = default; + Option maestro = default; + Option maestroUsa = default; + Option mc = default; + Option mealVoucherFR = default; + Option nyce = default; + Option paybybankPlaid = default; + Option payme = default; + Option paypal = default; + Option payto = default; + Option pulse = default; + Option reference = default; + Option sepadirectdebit = default; + Option shopperInteraction = default; + Option sodexo = default; + Option sofort = default; + Option star = default; + Option?> storeIds = default; + Option swish = default; + Option ticket = default; + Option twint = default; + Option type = default; + Option verificationStatus = default; + Option vipps = default; + Option visa = default; + Option wechatpay = default; + Option wechatpayPos = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "accel": + accel = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "affirm": + affirm = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "afterpayTouch": + afterpayTouch = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "alipayPlus": + alipayPlus = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "amex": + amex = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applePay": + applePay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bcmc": + bcmc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "businessLineId": + businessLineId = new Option(utf8JsonReader.GetString()!); + break; + case "cartesBancaires": + cartesBancaires = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clearpay": + clearpay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countries": + countries = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cup": + cup = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currencies": + currencies = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "customRoutingFlags": + customRoutingFlags = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "diners": + diners = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "discover": + discover = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eft_directdebit_CA": + eftDirectdebitCA = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eftpos_australia": + eftposAustralia = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "girocard": + girocard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "googlePay": + googlePay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ideal": + ideal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interac_card": + interacCard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "jcb": + jcb = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "klarna": + klarna = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro": + maestro = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro_usa": + maestroUsa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mc": + mc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mealVoucher_FR": + mealVoucherFR = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nyce": + nyce = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paybybank_plaid": + paybybankPlaid = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payme": + payme = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paypal": + paypal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payto": + payto = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pulse": + pulse = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit": + sepadirectdebit = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperInteraction": + shopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + case "sodexo": + sodexo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sofort": + sofort = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "star": + star = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storeIds": + storeIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "swish": + swish = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ticket": + ticket = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "twint": + twint = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(PaymentMethod.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + case "vipps": + vipps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "visa": + visa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wechatpay": + wechatpay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wechatpay_pos": + wechatpayPos = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PaymentMethod.", nameof(id)); + + return new PaymentMethod(id.Value!, accel, affirm, afterpayTouch, alipayPlus, allowed, amex, applePay, bcmc, businessLineId, cartesBancaires, clearpay, countries, cup, currencies, customRoutingFlags, diners, discover, eftDirectdebitCA, eftposAustralia, enabled, girocard, googlePay, ideal, interacCard, jcb, klarna, maestro, maestroUsa, mc, mealVoucherFR, nyce, paybybankPlaid, payme, paypal, payto, pulse, reference, sepadirectdebit, shopperInteraction, sodexo, sofort, star, storeIds, swish, ticket, twint, type, verificationStatus, vipps, visa, wechatpay, wechatpayPos); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethod paymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethod, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethod paymentMethod, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethod.Id != null) + writer.WriteString("id", paymentMethod.Id); + + if (paymentMethod._AccelOption.IsSet) + { + writer.WritePropertyName("accel"); + JsonSerializer.Serialize(writer, paymentMethod.Accel, jsonSerializerOptions); + } + if (paymentMethod._AffirmOption.IsSet) + { + writer.WritePropertyName("affirm"); + JsonSerializer.Serialize(writer, paymentMethod.Affirm, jsonSerializerOptions); + } + if (paymentMethod._AfterpayTouchOption.IsSet) + { + writer.WritePropertyName("afterpayTouch"); + JsonSerializer.Serialize(writer, paymentMethod.AfterpayTouch, jsonSerializerOptions); + } + if (paymentMethod._AlipayPlusOption.IsSet) + { + writer.WritePropertyName("alipayPlus"); + JsonSerializer.Serialize(writer, paymentMethod.AlipayPlus, jsonSerializerOptions); + } + if (paymentMethod._AllowedOption.IsSet) + writer.WriteBoolean("allowed", paymentMethod._AllowedOption.Value!.Value); + + if (paymentMethod._AmexOption.IsSet) + { + writer.WritePropertyName("amex"); + JsonSerializer.Serialize(writer, paymentMethod.Amex, jsonSerializerOptions); + } + if (paymentMethod._ApplePayOption.IsSet) + { + writer.WritePropertyName("applePay"); + JsonSerializer.Serialize(writer, paymentMethod.ApplePay, jsonSerializerOptions); + } + if (paymentMethod._BcmcOption.IsSet) + { + writer.WritePropertyName("bcmc"); + JsonSerializer.Serialize(writer, paymentMethod.Bcmc, jsonSerializerOptions); + } + if (paymentMethod._BusinessLineIdOption.IsSet) + if (paymentMethod.BusinessLineId != null) + writer.WriteString("businessLineId", paymentMethod.BusinessLineId); + + if (paymentMethod._CartesBancairesOption.IsSet) + { + writer.WritePropertyName("cartesBancaires"); + JsonSerializer.Serialize(writer, paymentMethod.CartesBancaires, jsonSerializerOptions); + } + if (paymentMethod._ClearpayOption.IsSet) + { + writer.WritePropertyName("clearpay"); + JsonSerializer.Serialize(writer, paymentMethod.Clearpay, jsonSerializerOptions); + } + if (paymentMethod._CountriesOption.IsSet) + { + writer.WritePropertyName("countries"); + JsonSerializer.Serialize(writer, paymentMethod.Countries, jsonSerializerOptions); + } + if (paymentMethod._CupOption.IsSet) + { + writer.WritePropertyName("cup"); + JsonSerializer.Serialize(writer, paymentMethod.Cup, jsonSerializerOptions); + } + if (paymentMethod._CurrenciesOption.IsSet) + { + writer.WritePropertyName("currencies"); + JsonSerializer.Serialize(writer, paymentMethod.Currencies, jsonSerializerOptions); + } + if (paymentMethod._CustomRoutingFlagsOption.IsSet) + { + writer.WritePropertyName("customRoutingFlags"); + JsonSerializer.Serialize(writer, paymentMethod.CustomRoutingFlags, jsonSerializerOptions); + } + if (paymentMethod._DinersOption.IsSet) + { + writer.WritePropertyName("diners"); + JsonSerializer.Serialize(writer, paymentMethod.Diners, jsonSerializerOptions); + } + if (paymentMethod._DiscoverOption.IsSet) + { + writer.WritePropertyName("discover"); + JsonSerializer.Serialize(writer, paymentMethod.Discover, jsonSerializerOptions); + } + if (paymentMethod._EftDirectdebitCAOption.IsSet) + { + writer.WritePropertyName("eft_directdebit_CA"); + JsonSerializer.Serialize(writer, paymentMethod.EftDirectdebitCA, jsonSerializerOptions); + } + if (paymentMethod._EftposAustraliaOption.IsSet) + { + writer.WritePropertyName("eftpos_australia"); + JsonSerializer.Serialize(writer, paymentMethod.EftposAustralia, jsonSerializerOptions); + } + if (paymentMethod._EnabledOption.IsSet) + writer.WriteBoolean("enabled", paymentMethod._EnabledOption.Value!.Value); + + if (paymentMethod._GirocardOption.IsSet) + { + writer.WritePropertyName("girocard"); + JsonSerializer.Serialize(writer, paymentMethod.Girocard, jsonSerializerOptions); + } + if (paymentMethod._GooglePayOption.IsSet) + { + writer.WritePropertyName("googlePay"); + JsonSerializer.Serialize(writer, paymentMethod.GooglePay, jsonSerializerOptions); + } + if (paymentMethod._IdealOption.IsSet) + { + writer.WritePropertyName("ideal"); + JsonSerializer.Serialize(writer, paymentMethod.Ideal, jsonSerializerOptions); + } + if (paymentMethod._InteracCardOption.IsSet) + { + writer.WritePropertyName("interac_card"); + JsonSerializer.Serialize(writer, paymentMethod.InteracCard, jsonSerializerOptions); + } + if (paymentMethod._JcbOption.IsSet) + { + writer.WritePropertyName("jcb"); + JsonSerializer.Serialize(writer, paymentMethod.Jcb, jsonSerializerOptions); + } + if (paymentMethod._KlarnaOption.IsSet) + { + writer.WritePropertyName("klarna"); + JsonSerializer.Serialize(writer, paymentMethod.Klarna, jsonSerializerOptions); + } + if (paymentMethod._MaestroOption.IsSet) + { + writer.WritePropertyName("maestro"); + JsonSerializer.Serialize(writer, paymentMethod.Maestro, jsonSerializerOptions); + } + if (paymentMethod._MaestroUsaOption.IsSet) + { + writer.WritePropertyName("maestro_usa"); + JsonSerializer.Serialize(writer, paymentMethod.MaestroUsa, jsonSerializerOptions); + } + if (paymentMethod._McOption.IsSet) + { + writer.WritePropertyName("mc"); + JsonSerializer.Serialize(writer, paymentMethod.Mc, jsonSerializerOptions); + } + if (paymentMethod._MealVoucherFROption.IsSet) + { + writer.WritePropertyName("mealVoucher_FR"); + JsonSerializer.Serialize(writer, paymentMethod.MealVoucherFR, jsonSerializerOptions); + } + if (paymentMethod._NyceOption.IsSet) + { + writer.WritePropertyName("nyce"); + JsonSerializer.Serialize(writer, paymentMethod.Nyce, jsonSerializerOptions); + } + if (paymentMethod._PaybybankPlaidOption.IsSet) + { + writer.WritePropertyName("paybybank_plaid"); + JsonSerializer.Serialize(writer, paymentMethod.PaybybankPlaid, jsonSerializerOptions); + } + if (paymentMethod._PaymeOption.IsSet) + { + writer.WritePropertyName("payme"); + JsonSerializer.Serialize(writer, paymentMethod.Payme, jsonSerializerOptions); + } + if (paymentMethod._PaypalOption.IsSet) + { + writer.WritePropertyName("paypal"); + JsonSerializer.Serialize(writer, paymentMethod.Paypal, jsonSerializerOptions); + } + if (paymentMethod._PaytoOption.IsSet) + { + writer.WritePropertyName("payto"); + JsonSerializer.Serialize(writer, paymentMethod.Payto, jsonSerializerOptions); + } + if (paymentMethod._PulseOption.IsSet) + { + writer.WritePropertyName("pulse"); + JsonSerializer.Serialize(writer, paymentMethod.Pulse, jsonSerializerOptions); + } + if (paymentMethod._ReferenceOption.IsSet) + if (paymentMethod.Reference != null) + writer.WriteString("reference", paymentMethod.Reference); + + if (paymentMethod._SepadirectdebitOption.IsSet) + { + writer.WritePropertyName("sepadirectdebit"); + JsonSerializer.Serialize(writer, paymentMethod.Sepadirectdebit, jsonSerializerOptions); + } + if (paymentMethod._ShopperInteractionOption.IsSet) + if (paymentMethod.ShopperInteraction != null) + writer.WriteString("shopperInteraction", paymentMethod.ShopperInteraction); + + if (paymentMethod._SodexoOption.IsSet) + { + writer.WritePropertyName("sodexo"); + JsonSerializer.Serialize(writer, paymentMethod.Sodexo, jsonSerializerOptions); + } + if (paymentMethod._SofortOption.IsSet) + { + writer.WritePropertyName("sofort"); + JsonSerializer.Serialize(writer, paymentMethod.Sofort, jsonSerializerOptions); + } + if (paymentMethod._StarOption.IsSet) + { + writer.WritePropertyName("star"); + JsonSerializer.Serialize(writer, paymentMethod.Star, jsonSerializerOptions); + } + if (paymentMethod._StoreIdsOption.IsSet) + { + writer.WritePropertyName("storeIds"); + JsonSerializer.Serialize(writer, paymentMethod.StoreIds, jsonSerializerOptions); + } + if (paymentMethod._SwishOption.IsSet) + { + writer.WritePropertyName("swish"); + JsonSerializer.Serialize(writer, paymentMethod.Swish, jsonSerializerOptions); + } + if (paymentMethod._TicketOption.IsSet) + { + writer.WritePropertyName("ticket"); + JsonSerializer.Serialize(writer, paymentMethod.Ticket, jsonSerializerOptions); + } + if (paymentMethod._TwintOption.IsSet) + { + writer.WritePropertyName("twint"); + JsonSerializer.Serialize(writer, paymentMethod.Twint, jsonSerializerOptions); + } + if (paymentMethod._TypeOption.IsSet) + if (paymentMethod.Type != null) + writer.WriteString("type", paymentMethod.Type); + + if (paymentMethod._VerificationStatusOption.IsSet && paymentMethod.VerificationStatus != null) + { + string? verificationStatusRawValue = PaymentMethod.VerificationStatusEnum.ToJsonValue(paymentMethod._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + + if (paymentMethod._VippsOption.IsSet) + { + writer.WritePropertyName("vipps"); + JsonSerializer.Serialize(writer, paymentMethod.Vipps, jsonSerializerOptions); + } + if (paymentMethod._VisaOption.IsSet) + { + writer.WritePropertyName("visa"); + JsonSerializer.Serialize(writer, paymentMethod.Visa, jsonSerializerOptions); + } + if (paymentMethod._WechatpayOption.IsSet) + { + writer.WritePropertyName("wechatpay"); + JsonSerializer.Serialize(writer, paymentMethod.Wechatpay, jsonSerializerOptions); + } + if (paymentMethod._WechatpayPosOption.IsSet) + { + writer.WritePropertyName("wechatpay_pos"); + JsonSerializer.Serialize(writer, paymentMethod.WechatpayPos, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/PaymentMethodResponse.cs b/Adyen/Management/Models/PaymentMethodResponse.cs new file mode 100644 index 000000000..a0a8dc36a --- /dev/null +++ b/Adyen/Management/Models/PaymentMethodResponse.cs @@ -0,0 +1,1521 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PaymentMethodResponse. + /// + public partial class PaymentMethodResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Total number of items. + /// Total number of pages. + /// links + /// The list of supported payment methods and their details. + /// The payment method types that were not successfully requested and their corresponding errors. + [JsonConstructor] + public PaymentMethodResponse(int itemsTotal, int pagesTotal, Option links = default, Option?> data = default, Option?> typesWithErrors = default) + { + ItemsTotal = itemsTotal; + PagesTotal = pagesTotal; + _LinksOption = links; + _DataOption = data; + _TypesWithErrorsOption = typesWithErrors; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodResponse() + { + } + + partial void OnCreated(); + + /// + /// Defines TypesWithErrors. + /// + [JsonConverter(typeof(TypesWithErrorsEnumJsonConverter))] + public class TypesWithErrorsEnum : IEnum + { + /// + /// Returns the value of the TypesWithErrorsEnum. + /// + public string? Value { get; set; } + + /// + /// TypesWithErrorsEnum.Abrapetite - abrapetite + /// + public static readonly TypesWithErrorsEnum Abrapetite = new("abrapetite"); + + /// + /// TypesWithErrorsEnum.AbrapetiteCredit - abrapetite_credit + /// + public static readonly TypesWithErrorsEnum AbrapetiteCredit = new("abrapetite_credit"); + + /// + /// TypesWithErrorsEnum.AbrapetiteDebit - abrapetite_debit + /// + public static readonly TypesWithErrorsEnum AbrapetiteDebit = new("abrapetite_debit"); + + /// + /// TypesWithErrorsEnum.AbrapetitePrepaid - abrapetite_prepaid + /// + public static readonly TypesWithErrorsEnum AbrapetitePrepaid = new("abrapetite_prepaid"); + + /// + /// TypesWithErrorsEnum.Accel - accel + /// + public static readonly TypesWithErrorsEnum Accel = new("accel"); + + /// + /// TypesWithErrorsEnum.Ach - ach + /// + public static readonly TypesWithErrorsEnum Ach = new("ach"); + + /// + /// TypesWithErrorsEnum.Affirm - affirm + /// + public static readonly TypesWithErrorsEnum Affirm = new("affirm"); + + /// + /// TypesWithErrorsEnum.Afterpaytouch - afterpaytouch + /// + public static readonly TypesWithErrorsEnum Afterpaytouch = new("afterpaytouch"); + + /// + /// TypesWithErrorsEnum.Alelo - alelo + /// + public static readonly TypesWithErrorsEnum Alelo = new("alelo"); + + /// + /// TypesWithErrorsEnum.Alipay - alipay + /// + public static readonly TypesWithErrorsEnum Alipay = new("alipay"); + + /// + /// TypesWithErrorsEnum.AlipayHk - alipay_hk + /// + public static readonly TypesWithErrorsEnum AlipayHk = new("alipay_hk"); + + /// + /// TypesWithErrorsEnum.AlipayPlus - alipay_plus + /// + public static readonly TypesWithErrorsEnum AlipayPlus = new("alipay_plus"); + + /// + /// TypesWithErrorsEnum.AlipayWap - alipay_wap + /// + public static readonly TypesWithErrorsEnum AlipayWap = new("alipay_wap"); + + /// + /// TypesWithErrorsEnum.Amex - amex + /// + public static readonly TypesWithErrorsEnum Amex = new("amex"); + + /// + /// TypesWithErrorsEnum.Applepay - applepay + /// + public static readonly TypesWithErrorsEnum Applepay = new("applepay"); + + /// + /// TypesWithErrorsEnum.Avancard - avancard + /// + public static readonly TypesWithErrorsEnum Avancard = new("avancard"); + + /// + /// TypesWithErrorsEnum.AvancardCredit - avancard_credit + /// + public static readonly TypesWithErrorsEnum AvancardCredit = new("avancard_credit"); + + /// + /// TypesWithErrorsEnum.AvancardDebit - avancard_debit + /// + public static readonly TypesWithErrorsEnum AvancardDebit = new("avancard_debit"); + + /// + /// TypesWithErrorsEnum.BaneseCard - banese_card + /// + public static readonly TypesWithErrorsEnum BaneseCard = new("banese_card"); + + /// + /// TypesWithErrorsEnum.BaneseCardCredit - banese_card_credit + /// + public static readonly TypesWithErrorsEnum BaneseCardCredit = new("banese_card_credit"); + + /// + /// TypesWithErrorsEnum.BaneseCardDebit - banese_card_debit + /// + public static readonly TypesWithErrorsEnum BaneseCardDebit = new("banese_card_debit"); + + /// + /// TypesWithErrorsEnum.BaneseCardPrepaid - banese_card_prepaid + /// + public static readonly TypesWithErrorsEnum BaneseCardPrepaid = new("banese_card_prepaid"); + + /// + /// TypesWithErrorsEnum.Bcmc - bcmc + /// + public static readonly TypesWithErrorsEnum Bcmc = new("bcmc"); + + /// + /// TypesWithErrorsEnum.Blik - blik + /// + public static readonly TypesWithErrorsEnum Blik = new("blik"); + + /// + /// TypesWithErrorsEnum.BrSchemes - br_schemes + /// + public static readonly TypesWithErrorsEnum BrSchemes = new("br_schemes"); + + /// + /// TypesWithErrorsEnum.Cartebancaire - cartebancaire + /// + public static readonly TypesWithErrorsEnum Cartebancaire = new("cartebancaire"); + + /// + /// TypesWithErrorsEnum.Clearpay - clearpay + /// + public static readonly TypesWithErrorsEnum Clearpay = new("clearpay"); + + /// + /// TypesWithErrorsEnum.Clicktopay - clicktopay + /// + public static readonly TypesWithErrorsEnum Clicktopay = new("clicktopay"); + + /// + /// TypesWithErrorsEnum.Cooper - cooper + /// + public static readonly TypesWithErrorsEnum Cooper = new("cooper"); + + /// + /// TypesWithErrorsEnum.CooperCredit - cooper_credit + /// + public static readonly TypesWithErrorsEnum CooperCredit = new("cooper_credit"); + + /// + /// TypesWithErrorsEnum.CooperDebit - cooper_debit + /// + public static readonly TypesWithErrorsEnum CooperDebit = new("cooper_debit"); + + /// + /// TypesWithErrorsEnum.CooperFoodDebit - cooper_food_debit + /// + public static readonly TypesWithErrorsEnum CooperFoodDebit = new("cooper_food_debit"); + + /// + /// TypesWithErrorsEnum.CooperMealDebit - cooper_meal_debit + /// + public static readonly TypesWithErrorsEnum CooperMealDebit = new("cooper_meal_debit"); + + /// + /// TypesWithErrorsEnum.CooperPrepaid - cooper_prepaid + /// + public static readonly TypesWithErrorsEnum CooperPrepaid = new("cooper_prepaid"); + + /// + /// TypesWithErrorsEnum.CooperPrivateCredit - cooper_private_credit + /// + public static readonly TypesWithErrorsEnum CooperPrivateCredit = new("cooper_private_credit"); + + /// + /// TypesWithErrorsEnum.CooperRetailCredit - cooper_retail_credit + /// + public static readonly TypesWithErrorsEnum CooperRetailCredit = new("cooper_retail_credit"); + + /// + /// TypesWithErrorsEnum.Credtodos - credtodos + /// + public static readonly TypesWithErrorsEnum Credtodos = new("credtodos"); + + /// + /// TypesWithErrorsEnum.CredtodosPrivateCredit - credtodos_private_credit + /// + public static readonly TypesWithErrorsEnum CredtodosPrivateCredit = new("credtodos_private_credit"); + + /// + /// TypesWithErrorsEnum.CredtodosPrivateDebit - credtodos_private_debit + /// + public static readonly TypesWithErrorsEnum CredtodosPrivateDebit = new("credtodos_private_debit"); + + /// + /// TypesWithErrorsEnum.Cup - cup + /// + public static readonly TypesWithErrorsEnum Cup = new("cup"); + + /// + /// TypesWithErrorsEnum.Diners - diners + /// + public static readonly TypesWithErrorsEnum Diners = new("diners"); + + /// + /// TypesWithErrorsEnum.DirectdebitGB - directdebit_GB + /// + public static readonly TypesWithErrorsEnum DirectdebitGB = new("directdebit_GB"); + + /// + /// TypesWithErrorsEnum.Discover - discover + /// + public static readonly TypesWithErrorsEnum Discover = new("discover"); + + /// + /// TypesWithErrorsEnum.EbankingFI - ebanking_FI + /// + public static readonly TypesWithErrorsEnum EbankingFI = new("ebanking_FI"); + + /// + /// TypesWithErrorsEnum.EftDirectdebitCA - eft_directdebit_CA + /// + public static readonly TypesWithErrorsEnum EftDirectdebitCA = new("eft_directdebit_CA"); + + /// + /// TypesWithErrorsEnum.EftposAustralia - eftpos_australia + /// + public static readonly TypesWithErrorsEnum EftposAustralia = new("eftpos_australia"); + + /// + /// TypesWithErrorsEnum.Elo - elo + /// + public static readonly TypesWithErrorsEnum Elo = new("elo"); + + /// + /// TypesWithErrorsEnum.Elocredit - elocredit + /// + public static readonly TypesWithErrorsEnum Elocredit = new("elocredit"); + + /// + /// TypesWithErrorsEnum.Elodebit - elodebit + /// + public static readonly TypesWithErrorsEnum Elodebit = new("elodebit"); + + /// + /// TypesWithErrorsEnum.Girocard - girocard + /// + public static readonly TypesWithErrorsEnum Girocard = new("girocard"); + + /// + /// TypesWithErrorsEnum.Googlepay - googlepay + /// + public static readonly TypesWithErrorsEnum Googlepay = new("googlepay"); + + /// + /// TypesWithErrorsEnum.GreenCard - green_card + /// + public static readonly TypesWithErrorsEnum GreenCard = new("green_card"); + + /// + /// TypesWithErrorsEnum.GreenCardCredit - green_card_credit + /// + public static readonly TypesWithErrorsEnum GreenCardCredit = new("green_card_credit"); + + /// + /// TypesWithErrorsEnum.GreenCardDebit - green_card_debit + /// + public static readonly TypesWithErrorsEnum GreenCardDebit = new("green_card_debit"); + + /// + /// TypesWithErrorsEnum.GreenCardFoodPrepaid - green_card_food_prepaid + /// + public static readonly TypesWithErrorsEnum GreenCardFoodPrepaid = new("green_card_food_prepaid"); + + /// + /// TypesWithErrorsEnum.GreenCardMealPrepaid - green_card_meal_prepaid + /// + public static readonly TypesWithErrorsEnum GreenCardMealPrepaid = new("green_card_meal_prepaid"); + + /// + /// TypesWithErrorsEnum.GreenCardPrepaid - green_card_prepaid + /// + public static readonly TypesWithErrorsEnum GreenCardPrepaid = new("green_card_prepaid"); + + /// + /// TypesWithErrorsEnum.Hiper - hiper + /// + public static readonly TypesWithErrorsEnum Hiper = new("hiper"); + + /// + /// TypesWithErrorsEnum.Hipercard - hipercard + /// + public static readonly TypesWithErrorsEnum Hipercard = new("hipercard"); + + /// + /// TypesWithErrorsEnum.Ideal - ideal + /// + public static readonly TypesWithErrorsEnum Ideal = new("ideal"); + + /// + /// TypesWithErrorsEnum.InteracCard - interac_card + /// + public static readonly TypesWithErrorsEnum InteracCard = new("interac_card"); + + /// + /// TypesWithErrorsEnum.Jcb - jcb + /// + public static readonly TypesWithErrorsEnum Jcb = new("jcb"); + + /// + /// TypesWithErrorsEnum.Klarna - klarna + /// + public static readonly TypesWithErrorsEnum Klarna = new("klarna"); + + /// + /// TypesWithErrorsEnum.KlarnaAccount - klarna_account + /// + public static readonly TypesWithErrorsEnum KlarnaAccount = new("klarna_account"); + + /// + /// TypesWithErrorsEnum.KlarnaPaynow - klarna_paynow + /// + public static readonly TypesWithErrorsEnum KlarnaPaynow = new("klarna_paynow"); + + /// + /// TypesWithErrorsEnum.LeCard - le_card + /// + public static readonly TypesWithErrorsEnum LeCard = new("le_card"); + + /// + /// TypesWithErrorsEnum.LeCardCredit - le_card_credit + /// + public static readonly TypesWithErrorsEnum LeCardCredit = new("le_card_credit"); + + /// + /// TypesWithErrorsEnum.LeCardDebit - le_card_debit + /// + public static readonly TypesWithErrorsEnum LeCardDebit = new("le_card_debit"); + + /// + /// TypesWithErrorsEnum.Maestro - maestro + /// + public static readonly TypesWithErrorsEnum Maestro = new("maestro"); + + /// + /// TypesWithErrorsEnum.MaestroUsa - maestro_usa + /// + public static readonly TypesWithErrorsEnum MaestroUsa = new("maestro_usa"); + + /// + /// TypesWithErrorsEnum.Maxifrota - maxifrota + /// + public static readonly TypesWithErrorsEnum Maxifrota = new("maxifrota"); + + /// + /// TypesWithErrorsEnum.MaxifrotaPrepaid - maxifrota_prepaid + /// + public static readonly TypesWithErrorsEnum MaxifrotaPrepaid = new("maxifrota_prepaid"); + + /// + /// TypesWithErrorsEnum.Mbway - mbway + /// + public static readonly TypesWithErrorsEnum Mbway = new("mbway"); + + /// + /// TypesWithErrorsEnum.Mc - mc + /// + public static readonly TypesWithErrorsEnum Mc = new("mc"); + + /// + /// TypesWithErrorsEnum.Mcdebit - mcdebit + /// + public static readonly TypesWithErrorsEnum Mcdebit = new("mcdebit"); + + /// + /// TypesWithErrorsEnum.MealVoucherFR - mealVoucher_FR + /// + public static readonly TypesWithErrorsEnum MealVoucherFR = new("mealVoucher_FR"); + + /// + /// TypesWithErrorsEnum.Megaleve - megaleve + /// + public static readonly TypesWithErrorsEnum Megaleve = new("megaleve"); + + /// + /// TypesWithErrorsEnum.MegaleveCredit - megaleve_credit + /// + public static readonly TypesWithErrorsEnum MegaleveCredit = new("megaleve_credit"); + + /// + /// TypesWithErrorsEnum.MegaleveDebit - megaleve_debit + /// + public static readonly TypesWithErrorsEnum MegaleveDebit = new("megaleve_debit"); + + /// + /// TypesWithErrorsEnum.Mobilepay - mobilepay + /// + public static readonly TypesWithErrorsEnum Mobilepay = new("mobilepay"); + + /// + /// TypesWithErrorsEnum.Multibanco - multibanco + /// + public static readonly TypesWithErrorsEnum Multibanco = new("multibanco"); + + /// + /// TypesWithErrorsEnum.Nutricash - nutricash + /// + public static readonly TypesWithErrorsEnum Nutricash = new("nutricash"); + + /// + /// TypesWithErrorsEnum.NutricashPrepaid - nutricash_prepaid + /// + public static readonly TypesWithErrorsEnum NutricashPrepaid = new("nutricash_prepaid"); + + /// + /// TypesWithErrorsEnum.Nyce - nyce + /// + public static readonly TypesWithErrorsEnum Nyce = new("nyce"); + + /// + /// TypesWithErrorsEnum.OnlineBankingPL - onlineBanking_PL + /// + public static readonly TypesWithErrorsEnum OnlineBankingPL = new("onlineBanking_PL"); + + /// + /// TypesWithErrorsEnum.Paybybank - paybybank + /// + public static readonly TypesWithErrorsEnum Paybybank = new("paybybank"); + + /// + /// TypesWithErrorsEnum.PaybybankPlaid - paybybank_plaid + /// + public static readonly TypesWithErrorsEnum PaybybankPlaid = new("paybybank_plaid"); + + /// + /// TypesWithErrorsEnum.Payme - payme + /// + public static readonly TypesWithErrorsEnum Payme = new("payme"); + + /// + /// TypesWithErrorsEnum.PaymePos - payme_pos + /// + public static readonly TypesWithErrorsEnum PaymePos = new("payme_pos"); + + /// + /// TypesWithErrorsEnum.Paynow - paynow + /// + public static readonly TypesWithErrorsEnum Paynow = new("paynow"); + + /// + /// TypesWithErrorsEnum.PaynowPos - paynow_pos + /// + public static readonly TypesWithErrorsEnum PaynowPos = new("paynow_pos"); + + /// + /// TypesWithErrorsEnum.Paypal - paypal + /// + public static readonly TypesWithErrorsEnum Paypal = new("paypal"); + + /// + /// TypesWithErrorsEnum.Payto - payto + /// + public static readonly TypesWithErrorsEnum Payto = new("payto"); + + /// + /// TypesWithErrorsEnum.PersonalCard - personal_card + /// + public static readonly TypesWithErrorsEnum PersonalCard = new("personal_card"); + + /// + /// TypesWithErrorsEnum.PersonalCardCredit - personal_card_credit + /// + public static readonly TypesWithErrorsEnum PersonalCardCredit = new("personal_card_credit"); + + /// + /// TypesWithErrorsEnum.PersonalCardDebit - personal_card_debit + /// + public static readonly TypesWithErrorsEnum PersonalCardDebit = new("personal_card_debit"); + + /// + /// TypesWithErrorsEnum.Pulse - pulse + /// + public static readonly TypesWithErrorsEnum Pulse = new("pulse"); + + /// + /// TypesWithErrorsEnum.Romcard - romcard + /// + public static readonly TypesWithErrorsEnum Romcard = new("romcard"); + + /// + /// TypesWithErrorsEnum.RomcardCredit - romcard_credit + /// + public static readonly TypesWithErrorsEnum RomcardCredit = new("romcard_credit"); + + /// + /// TypesWithErrorsEnum.RomcardDebit - romcard_debit + /// + public static readonly TypesWithErrorsEnum RomcardDebit = new("romcard_debit"); + + /// + /// TypesWithErrorsEnum.Senff - senff + /// + public static readonly TypesWithErrorsEnum Senff = new("senff"); + + /// + /// TypesWithErrorsEnum.SenffCredit - senff_credit + /// + public static readonly TypesWithErrorsEnum SenffCredit = new("senff_credit"); + + /// + /// TypesWithErrorsEnum.Sepadirectdebit - sepadirectdebit + /// + public static readonly TypesWithErrorsEnum Sepadirectdebit = new("sepadirectdebit"); + + /// + /// TypesWithErrorsEnum.Sodexo - sodexo + /// + public static readonly TypesWithErrorsEnum Sodexo = new("sodexo"); + + /// + /// TypesWithErrorsEnum.Star - star + /// + public static readonly TypesWithErrorsEnum Star = new("star"); + + /// + /// TypesWithErrorsEnum.Swish - swish + /// + public static readonly TypesWithErrorsEnum Swish = new("swish"); + + /// + /// TypesWithErrorsEnum.Ticket - ticket + /// + public static readonly TypesWithErrorsEnum Ticket = new("ticket"); + + /// + /// TypesWithErrorsEnum.TodoGiftcard - todo_giftcard + /// + public static readonly TypesWithErrorsEnum TodoGiftcard = new("todo_giftcard"); + + /// + /// TypesWithErrorsEnum.Trustly - trustly + /// + public static readonly TypesWithErrorsEnum Trustly = new("trustly"); + + /// + /// TypesWithErrorsEnum.Twint - twint + /// + public static readonly TypesWithErrorsEnum Twint = new("twint"); + + /// + /// TypesWithErrorsEnum.TwintPos - twint_pos + /// + public static readonly TypesWithErrorsEnum TwintPos = new("twint_pos"); + + /// + /// TypesWithErrorsEnum.UpBrazil - up_brazil + /// + public static readonly TypesWithErrorsEnum UpBrazil = new("up_brazil"); + + /// + /// TypesWithErrorsEnum.UpBrazilCredit - up_brazil_credit + /// + public static readonly TypesWithErrorsEnum UpBrazilCredit = new("up_brazil_credit"); + + /// + /// TypesWithErrorsEnum.UpBrazilDebit - up_brazil_debit + /// + public static readonly TypesWithErrorsEnum UpBrazilDebit = new("up_brazil_debit"); + + /// + /// TypesWithErrorsEnum.UpBrazilPrepaid - up_brazil_prepaid + /// + public static readonly TypesWithErrorsEnum UpBrazilPrepaid = new("up_brazil_prepaid"); + + /// + /// TypesWithErrorsEnum.ValeRefeicao - vale_refeicao + /// + public static readonly TypesWithErrorsEnum ValeRefeicao = new("vale_refeicao"); + + /// + /// TypesWithErrorsEnum.ValeRefeicaoPrepaid - vale_refeicao_prepaid + /// + public static readonly TypesWithErrorsEnum ValeRefeicaoPrepaid = new("vale_refeicao_prepaid"); + + /// + /// TypesWithErrorsEnum.VegasCard - vegas_card + /// + public static readonly TypesWithErrorsEnum VegasCard = new("vegas_card"); + + /// + /// TypesWithErrorsEnum.VegasCardCredit - vegas_card_credit + /// + public static readonly TypesWithErrorsEnum VegasCardCredit = new("vegas_card_credit"); + + /// + /// TypesWithErrorsEnum.VegasCardDebit - vegas_card_debit + /// + public static readonly TypesWithErrorsEnum VegasCardDebit = new("vegas_card_debit"); + + /// + /// TypesWithErrorsEnum.VeroCard - vero_card + /// + public static readonly TypesWithErrorsEnum VeroCard = new("vero_card"); + + /// + /// TypesWithErrorsEnum.VeroCardCredit - vero_card_credit + /// + public static readonly TypesWithErrorsEnum VeroCardCredit = new("vero_card_credit"); + + /// + /// TypesWithErrorsEnum.VeroCardDebit - vero_card_debit + /// + public static readonly TypesWithErrorsEnum VeroCardDebit = new("vero_card_debit"); + + /// + /// TypesWithErrorsEnum.VeroCardPrepaid - vero_card_prepaid + /// + public static readonly TypesWithErrorsEnum VeroCardPrepaid = new("vero_card_prepaid"); + + /// + /// TypesWithErrorsEnum.Vipps - vipps + /// + public static readonly TypesWithErrorsEnum Vipps = new("vipps"); + + /// + /// TypesWithErrorsEnum.Visa - visa + /// + public static readonly TypesWithErrorsEnum Visa = new("visa"); + + /// + /// TypesWithErrorsEnum.Visadebit - visadebit + /// + public static readonly TypesWithErrorsEnum Visadebit = new("visadebit"); + + /// + /// TypesWithErrorsEnum.Vpay - vpay + /// + public static readonly TypesWithErrorsEnum Vpay = new("vpay"); + + /// + /// TypesWithErrorsEnum.Wechatpay - wechatpay + /// + public static readonly TypesWithErrorsEnum Wechatpay = new("wechatpay"); + + /// + /// TypesWithErrorsEnum.WechatpayPos - wechatpay_pos + /// + public static readonly TypesWithErrorsEnum WechatpayPos = new("wechatpay_pos"); + + private TypesWithErrorsEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypesWithErrorsEnum?(string? value) => value == null ? null : new TypesWithErrorsEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypesWithErrorsEnum? option) => option?.Value; + + public static bool operator ==(TypesWithErrorsEnum? left, TypesWithErrorsEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypesWithErrorsEnum? left, TypesWithErrorsEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypesWithErrorsEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypesWithErrorsEnum? FromStringOrDefault(string value) + { + return value switch { + "abrapetite" => TypesWithErrorsEnum.Abrapetite, + "abrapetite_credit" => TypesWithErrorsEnum.AbrapetiteCredit, + "abrapetite_debit" => TypesWithErrorsEnum.AbrapetiteDebit, + "abrapetite_prepaid" => TypesWithErrorsEnum.AbrapetitePrepaid, + "accel" => TypesWithErrorsEnum.Accel, + "ach" => TypesWithErrorsEnum.Ach, + "affirm" => TypesWithErrorsEnum.Affirm, + "afterpaytouch" => TypesWithErrorsEnum.Afterpaytouch, + "alelo" => TypesWithErrorsEnum.Alelo, + "alipay" => TypesWithErrorsEnum.Alipay, + "alipay_hk" => TypesWithErrorsEnum.AlipayHk, + "alipay_plus" => TypesWithErrorsEnum.AlipayPlus, + "alipay_wap" => TypesWithErrorsEnum.AlipayWap, + "amex" => TypesWithErrorsEnum.Amex, + "applepay" => TypesWithErrorsEnum.Applepay, + "avancard" => TypesWithErrorsEnum.Avancard, + "avancard_credit" => TypesWithErrorsEnum.AvancardCredit, + "avancard_debit" => TypesWithErrorsEnum.AvancardDebit, + "banese_card" => TypesWithErrorsEnum.BaneseCard, + "banese_card_credit" => TypesWithErrorsEnum.BaneseCardCredit, + "banese_card_debit" => TypesWithErrorsEnum.BaneseCardDebit, + "banese_card_prepaid" => TypesWithErrorsEnum.BaneseCardPrepaid, + "bcmc" => TypesWithErrorsEnum.Bcmc, + "blik" => TypesWithErrorsEnum.Blik, + "br_schemes" => TypesWithErrorsEnum.BrSchemes, + "cartebancaire" => TypesWithErrorsEnum.Cartebancaire, + "clearpay" => TypesWithErrorsEnum.Clearpay, + "clicktopay" => TypesWithErrorsEnum.Clicktopay, + "cooper" => TypesWithErrorsEnum.Cooper, + "cooper_credit" => TypesWithErrorsEnum.CooperCredit, + "cooper_debit" => TypesWithErrorsEnum.CooperDebit, + "cooper_food_debit" => TypesWithErrorsEnum.CooperFoodDebit, + "cooper_meal_debit" => TypesWithErrorsEnum.CooperMealDebit, + "cooper_prepaid" => TypesWithErrorsEnum.CooperPrepaid, + "cooper_private_credit" => TypesWithErrorsEnum.CooperPrivateCredit, + "cooper_retail_credit" => TypesWithErrorsEnum.CooperRetailCredit, + "credtodos" => TypesWithErrorsEnum.Credtodos, + "credtodos_private_credit" => TypesWithErrorsEnum.CredtodosPrivateCredit, + "credtodos_private_debit" => TypesWithErrorsEnum.CredtodosPrivateDebit, + "cup" => TypesWithErrorsEnum.Cup, + "diners" => TypesWithErrorsEnum.Diners, + "directdebit_GB" => TypesWithErrorsEnum.DirectdebitGB, + "discover" => TypesWithErrorsEnum.Discover, + "ebanking_FI" => TypesWithErrorsEnum.EbankingFI, + "eft_directdebit_CA" => TypesWithErrorsEnum.EftDirectdebitCA, + "eftpos_australia" => TypesWithErrorsEnum.EftposAustralia, + "elo" => TypesWithErrorsEnum.Elo, + "elocredit" => TypesWithErrorsEnum.Elocredit, + "elodebit" => TypesWithErrorsEnum.Elodebit, + "girocard" => TypesWithErrorsEnum.Girocard, + "googlepay" => TypesWithErrorsEnum.Googlepay, + "green_card" => TypesWithErrorsEnum.GreenCard, + "green_card_credit" => TypesWithErrorsEnum.GreenCardCredit, + "green_card_debit" => TypesWithErrorsEnum.GreenCardDebit, + "green_card_food_prepaid" => TypesWithErrorsEnum.GreenCardFoodPrepaid, + "green_card_meal_prepaid" => TypesWithErrorsEnum.GreenCardMealPrepaid, + "green_card_prepaid" => TypesWithErrorsEnum.GreenCardPrepaid, + "hiper" => TypesWithErrorsEnum.Hiper, + "hipercard" => TypesWithErrorsEnum.Hipercard, + "ideal" => TypesWithErrorsEnum.Ideal, + "interac_card" => TypesWithErrorsEnum.InteracCard, + "jcb" => TypesWithErrorsEnum.Jcb, + "klarna" => TypesWithErrorsEnum.Klarna, + "klarna_account" => TypesWithErrorsEnum.KlarnaAccount, + "klarna_paynow" => TypesWithErrorsEnum.KlarnaPaynow, + "le_card" => TypesWithErrorsEnum.LeCard, + "le_card_credit" => TypesWithErrorsEnum.LeCardCredit, + "le_card_debit" => TypesWithErrorsEnum.LeCardDebit, + "maestro" => TypesWithErrorsEnum.Maestro, + "maestro_usa" => TypesWithErrorsEnum.MaestroUsa, + "maxifrota" => TypesWithErrorsEnum.Maxifrota, + "maxifrota_prepaid" => TypesWithErrorsEnum.MaxifrotaPrepaid, + "mbway" => TypesWithErrorsEnum.Mbway, + "mc" => TypesWithErrorsEnum.Mc, + "mcdebit" => TypesWithErrorsEnum.Mcdebit, + "mealVoucher_FR" => TypesWithErrorsEnum.MealVoucherFR, + "megaleve" => TypesWithErrorsEnum.Megaleve, + "megaleve_credit" => TypesWithErrorsEnum.MegaleveCredit, + "megaleve_debit" => TypesWithErrorsEnum.MegaleveDebit, + "mobilepay" => TypesWithErrorsEnum.Mobilepay, + "multibanco" => TypesWithErrorsEnum.Multibanco, + "nutricash" => TypesWithErrorsEnum.Nutricash, + "nutricash_prepaid" => TypesWithErrorsEnum.NutricashPrepaid, + "nyce" => TypesWithErrorsEnum.Nyce, + "onlineBanking_PL" => TypesWithErrorsEnum.OnlineBankingPL, + "paybybank" => TypesWithErrorsEnum.Paybybank, + "paybybank_plaid" => TypesWithErrorsEnum.PaybybankPlaid, + "payme" => TypesWithErrorsEnum.Payme, + "payme_pos" => TypesWithErrorsEnum.PaymePos, + "paynow" => TypesWithErrorsEnum.Paynow, + "paynow_pos" => TypesWithErrorsEnum.PaynowPos, + "paypal" => TypesWithErrorsEnum.Paypal, + "payto" => TypesWithErrorsEnum.Payto, + "personal_card" => TypesWithErrorsEnum.PersonalCard, + "personal_card_credit" => TypesWithErrorsEnum.PersonalCardCredit, + "personal_card_debit" => TypesWithErrorsEnum.PersonalCardDebit, + "pulse" => TypesWithErrorsEnum.Pulse, + "romcard" => TypesWithErrorsEnum.Romcard, + "romcard_credit" => TypesWithErrorsEnum.RomcardCredit, + "romcard_debit" => TypesWithErrorsEnum.RomcardDebit, + "senff" => TypesWithErrorsEnum.Senff, + "senff_credit" => TypesWithErrorsEnum.SenffCredit, + "sepadirectdebit" => TypesWithErrorsEnum.Sepadirectdebit, + "sodexo" => TypesWithErrorsEnum.Sodexo, + "star" => TypesWithErrorsEnum.Star, + "swish" => TypesWithErrorsEnum.Swish, + "ticket" => TypesWithErrorsEnum.Ticket, + "todo_giftcard" => TypesWithErrorsEnum.TodoGiftcard, + "trustly" => TypesWithErrorsEnum.Trustly, + "twint" => TypesWithErrorsEnum.Twint, + "twint_pos" => TypesWithErrorsEnum.TwintPos, + "up_brazil" => TypesWithErrorsEnum.UpBrazil, + "up_brazil_credit" => TypesWithErrorsEnum.UpBrazilCredit, + "up_brazil_debit" => TypesWithErrorsEnum.UpBrazilDebit, + "up_brazil_prepaid" => TypesWithErrorsEnum.UpBrazilPrepaid, + "vale_refeicao" => TypesWithErrorsEnum.ValeRefeicao, + "vale_refeicao_prepaid" => TypesWithErrorsEnum.ValeRefeicaoPrepaid, + "vegas_card" => TypesWithErrorsEnum.VegasCard, + "vegas_card_credit" => TypesWithErrorsEnum.VegasCardCredit, + "vegas_card_debit" => TypesWithErrorsEnum.VegasCardDebit, + "vero_card" => TypesWithErrorsEnum.VeroCard, + "vero_card_credit" => TypesWithErrorsEnum.VeroCardCredit, + "vero_card_debit" => TypesWithErrorsEnum.VeroCardDebit, + "vero_card_prepaid" => TypesWithErrorsEnum.VeroCardPrepaid, + "vipps" => TypesWithErrorsEnum.Vipps, + "visa" => TypesWithErrorsEnum.Visa, + "visadebit" => TypesWithErrorsEnum.Visadebit, + "vpay" => TypesWithErrorsEnum.Vpay, + "wechatpay" => TypesWithErrorsEnum.Wechatpay, + "wechatpay_pos" => TypesWithErrorsEnum.WechatpayPos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypesWithErrorsEnum? value) + { + if (value == null) + return null; + + if (value == TypesWithErrorsEnum.Abrapetite) + return "abrapetite"; + + if (value == TypesWithErrorsEnum.AbrapetiteCredit) + return "abrapetite_credit"; + + if (value == TypesWithErrorsEnum.AbrapetiteDebit) + return "abrapetite_debit"; + + if (value == TypesWithErrorsEnum.AbrapetitePrepaid) + return "abrapetite_prepaid"; + + if (value == TypesWithErrorsEnum.Accel) + return "accel"; + + if (value == TypesWithErrorsEnum.Ach) + return "ach"; + + if (value == TypesWithErrorsEnum.Affirm) + return "affirm"; + + if (value == TypesWithErrorsEnum.Afterpaytouch) + return "afterpaytouch"; + + if (value == TypesWithErrorsEnum.Alelo) + return "alelo"; + + if (value == TypesWithErrorsEnum.Alipay) + return "alipay"; + + if (value == TypesWithErrorsEnum.AlipayHk) + return "alipay_hk"; + + if (value == TypesWithErrorsEnum.AlipayPlus) + return "alipay_plus"; + + if (value == TypesWithErrorsEnum.AlipayWap) + return "alipay_wap"; + + if (value == TypesWithErrorsEnum.Amex) + return "amex"; + + if (value == TypesWithErrorsEnum.Applepay) + return "applepay"; + + if (value == TypesWithErrorsEnum.Avancard) + return "avancard"; + + if (value == TypesWithErrorsEnum.AvancardCredit) + return "avancard_credit"; + + if (value == TypesWithErrorsEnum.AvancardDebit) + return "avancard_debit"; + + if (value == TypesWithErrorsEnum.BaneseCard) + return "banese_card"; + + if (value == TypesWithErrorsEnum.BaneseCardCredit) + return "banese_card_credit"; + + if (value == TypesWithErrorsEnum.BaneseCardDebit) + return "banese_card_debit"; + + if (value == TypesWithErrorsEnum.BaneseCardPrepaid) + return "banese_card_prepaid"; + + if (value == TypesWithErrorsEnum.Bcmc) + return "bcmc"; + + if (value == TypesWithErrorsEnum.Blik) + return "blik"; + + if (value == TypesWithErrorsEnum.BrSchemes) + return "br_schemes"; + + if (value == TypesWithErrorsEnum.Cartebancaire) + return "cartebancaire"; + + if (value == TypesWithErrorsEnum.Clearpay) + return "clearpay"; + + if (value == TypesWithErrorsEnum.Clicktopay) + return "clicktopay"; + + if (value == TypesWithErrorsEnum.Cooper) + return "cooper"; + + if (value == TypesWithErrorsEnum.CooperCredit) + return "cooper_credit"; + + if (value == TypesWithErrorsEnum.CooperDebit) + return "cooper_debit"; + + if (value == TypesWithErrorsEnum.CooperFoodDebit) + return "cooper_food_debit"; + + if (value == TypesWithErrorsEnum.CooperMealDebit) + return "cooper_meal_debit"; + + if (value == TypesWithErrorsEnum.CooperPrepaid) + return "cooper_prepaid"; + + if (value == TypesWithErrorsEnum.CooperPrivateCredit) + return "cooper_private_credit"; + + if (value == TypesWithErrorsEnum.CooperRetailCredit) + return "cooper_retail_credit"; + + if (value == TypesWithErrorsEnum.Credtodos) + return "credtodos"; + + if (value == TypesWithErrorsEnum.CredtodosPrivateCredit) + return "credtodos_private_credit"; + + if (value == TypesWithErrorsEnum.CredtodosPrivateDebit) + return "credtodos_private_debit"; + + if (value == TypesWithErrorsEnum.Cup) + return "cup"; + + if (value == TypesWithErrorsEnum.Diners) + return "diners"; + + if (value == TypesWithErrorsEnum.DirectdebitGB) + return "directdebit_GB"; + + if (value == TypesWithErrorsEnum.Discover) + return "discover"; + + if (value == TypesWithErrorsEnum.EbankingFI) + return "ebanking_FI"; + + if (value == TypesWithErrorsEnum.EftDirectdebitCA) + return "eft_directdebit_CA"; + + if (value == TypesWithErrorsEnum.EftposAustralia) + return "eftpos_australia"; + + if (value == TypesWithErrorsEnum.Elo) + return "elo"; + + if (value == TypesWithErrorsEnum.Elocredit) + return "elocredit"; + + if (value == TypesWithErrorsEnum.Elodebit) + return "elodebit"; + + if (value == TypesWithErrorsEnum.Girocard) + return "girocard"; + + if (value == TypesWithErrorsEnum.Googlepay) + return "googlepay"; + + if (value == TypesWithErrorsEnum.GreenCard) + return "green_card"; + + if (value == TypesWithErrorsEnum.GreenCardCredit) + return "green_card_credit"; + + if (value == TypesWithErrorsEnum.GreenCardDebit) + return "green_card_debit"; + + if (value == TypesWithErrorsEnum.GreenCardFoodPrepaid) + return "green_card_food_prepaid"; + + if (value == TypesWithErrorsEnum.GreenCardMealPrepaid) + return "green_card_meal_prepaid"; + + if (value == TypesWithErrorsEnum.GreenCardPrepaid) + return "green_card_prepaid"; + + if (value == TypesWithErrorsEnum.Hiper) + return "hiper"; + + if (value == TypesWithErrorsEnum.Hipercard) + return "hipercard"; + + if (value == TypesWithErrorsEnum.Ideal) + return "ideal"; + + if (value == TypesWithErrorsEnum.InteracCard) + return "interac_card"; + + if (value == TypesWithErrorsEnum.Jcb) + return "jcb"; + + if (value == TypesWithErrorsEnum.Klarna) + return "klarna"; + + if (value == TypesWithErrorsEnum.KlarnaAccount) + return "klarna_account"; + + if (value == TypesWithErrorsEnum.KlarnaPaynow) + return "klarna_paynow"; + + if (value == TypesWithErrorsEnum.LeCard) + return "le_card"; + + if (value == TypesWithErrorsEnum.LeCardCredit) + return "le_card_credit"; + + if (value == TypesWithErrorsEnum.LeCardDebit) + return "le_card_debit"; + + if (value == TypesWithErrorsEnum.Maestro) + return "maestro"; + + if (value == TypesWithErrorsEnum.MaestroUsa) + return "maestro_usa"; + + if (value == TypesWithErrorsEnum.Maxifrota) + return "maxifrota"; + + if (value == TypesWithErrorsEnum.MaxifrotaPrepaid) + return "maxifrota_prepaid"; + + if (value == TypesWithErrorsEnum.Mbway) + return "mbway"; + + if (value == TypesWithErrorsEnum.Mc) + return "mc"; + + if (value == TypesWithErrorsEnum.Mcdebit) + return "mcdebit"; + + if (value == TypesWithErrorsEnum.MealVoucherFR) + return "mealVoucher_FR"; + + if (value == TypesWithErrorsEnum.Megaleve) + return "megaleve"; + + if (value == TypesWithErrorsEnum.MegaleveCredit) + return "megaleve_credit"; + + if (value == TypesWithErrorsEnum.MegaleveDebit) + return "megaleve_debit"; + + if (value == TypesWithErrorsEnum.Mobilepay) + return "mobilepay"; + + if (value == TypesWithErrorsEnum.Multibanco) + return "multibanco"; + + if (value == TypesWithErrorsEnum.Nutricash) + return "nutricash"; + + if (value == TypesWithErrorsEnum.NutricashPrepaid) + return "nutricash_prepaid"; + + if (value == TypesWithErrorsEnum.Nyce) + return "nyce"; + + if (value == TypesWithErrorsEnum.OnlineBankingPL) + return "onlineBanking_PL"; + + if (value == TypesWithErrorsEnum.Paybybank) + return "paybybank"; + + if (value == TypesWithErrorsEnum.PaybybankPlaid) + return "paybybank_plaid"; + + if (value == TypesWithErrorsEnum.Payme) + return "payme"; + + if (value == TypesWithErrorsEnum.PaymePos) + return "payme_pos"; + + if (value == TypesWithErrorsEnum.Paynow) + return "paynow"; + + if (value == TypesWithErrorsEnum.PaynowPos) + return "paynow_pos"; + + if (value == TypesWithErrorsEnum.Paypal) + return "paypal"; + + if (value == TypesWithErrorsEnum.Payto) + return "payto"; + + if (value == TypesWithErrorsEnum.PersonalCard) + return "personal_card"; + + if (value == TypesWithErrorsEnum.PersonalCardCredit) + return "personal_card_credit"; + + if (value == TypesWithErrorsEnum.PersonalCardDebit) + return "personal_card_debit"; + + if (value == TypesWithErrorsEnum.Pulse) + return "pulse"; + + if (value == TypesWithErrorsEnum.Romcard) + return "romcard"; + + if (value == TypesWithErrorsEnum.RomcardCredit) + return "romcard_credit"; + + if (value == TypesWithErrorsEnum.RomcardDebit) + return "romcard_debit"; + + if (value == TypesWithErrorsEnum.Senff) + return "senff"; + + if (value == TypesWithErrorsEnum.SenffCredit) + return "senff_credit"; + + if (value == TypesWithErrorsEnum.Sepadirectdebit) + return "sepadirectdebit"; + + if (value == TypesWithErrorsEnum.Sodexo) + return "sodexo"; + + if (value == TypesWithErrorsEnum.Star) + return "star"; + + if (value == TypesWithErrorsEnum.Swish) + return "swish"; + + if (value == TypesWithErrorsEnum.Ticket) + return "ticket"; + + if (value == TypesWithErrorsEnum.TodoGiftcard) + return "todo_giftcard"; + + if (value == TypesWithErrorsEnum.Trustly) + return "trustly"; + + if (value == TypesWithErrorsEnum.Twint) + return "twint"; + + if (value == TypesWithErrorsEnum.TwintPos) + return "twint_pos"; + + if (value == TypesWithErrorsEnum.UpBrazil) + return "up_brazil"; + + if (value == TypesWithErrorsEnum.UpBrazilCredit) + return "up_brazil_credit"; + + if (value == TypesWithErrorsEnum.UpBrazilDebit) + return "up_brazil_debit"; + + if (value == TypesWithErrorsEnum.UpBrazilPrepaid) + return "up_brazil_prepaid"; + + if (value == TypesWithErrorsEnum.ValeRefeicao) + return "vale_refeicao"; + + if (value == TypesWithErrorsEnum.ValeRefeicaoPrepaid) + return "vale_refeicao_prepaid"; + + if (value == TypesWithErrorsEnum.VegasCard) + return "vegas_card"; + + if (value == TypesWithErrorsEnum.VegasCardCredit) + return "vegas_card_credit"; + + if (value == TypesWithErrorsEnum.VegasCardDebit) + return "vegas_card_debit"; + + if (value == TypesWithErrorsEnum.VeroCard) + return "vero_card"; + + if (value == TypesWithErrorsEnum.VeroCardCredit) + return "vero_card_credit"; + + if (value == TypesWithErrorsEnum.VeroCardDebit) + return "vero_card_debit"; + + if (value == TypesWithErrorsEnum.VeroCardPrepaid) + return "vero_card_prepaid"; + + if (value == TypesWithErrorsEnum.Vipps) + return "vipps"; + + if (value == TypesWithErrorsEnum.Visa) + return "visa"; + + if (value == TypesWithErrorsEnum.Visadebit) + return "visadebit"; + + if (value == TypesWithErrorsEnum.Vpay) + return "vpay"; + + if (value == TypesWithErrorsEnum.Wechatpay) + return "wechatpay"; + + if (value == TypesWithErrorsEnum.WechatpayPos) + return "wechatpay_pos"; + + return null; + } + + /// + /// JsonConverter for writing TypesWithErrorsEnum. + /// + public class TypesWithErrorsEnumJsonConverter : JsonConverter + { + public override TypesWithErrorsEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypesWithErrorsEnum.FromStringOrDefault(value) ?? new TypesWithErrorsEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypesWithErrorsEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypesWithErrorsEnum.ToJsonValue(value)); + } + } + } + + /// + /// Total number of items. + /// + /// Total number of items. + [JsonPropertyName("itemsTotal")] + public int ItemsTotal { get; set; } + + /// + /// Total number of pages. + /// + /// Total number of pages. + [JsonPropertyName("pagesTotal")] + public int PagesTotal { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public PaginationLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of supported payment methods and their details. + /// + /// The list of supported payment methods and their details. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TypesWithErrorsOption { get; private set; } + + /// + /// The payment method types that were not successfully requested and their corresponding errors. + /// + /// The payment method types that were not successfully requested and their corresponding errors. + [JsonPropertyName("typesWithErrors")] + public List? TypesWithErrors { get { return this._TypesWithErrorsOption; } set { this._TypesWithErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodResponse {\n"); + sb.Append(" ItemsTotal: ").Append(ItemsTotal).Append("\n"); + sb.Append(" PagesTotal: ").Append(PagesTotal).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" TypesWithErrors: ").Append(TypesWithErrors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option itemsTotal = default; + Option pagesTotal = default; + Option links = default; + Option?> data = default; + Option?> typesWithErrors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "itemsTotal": + itemsTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pagesTotal": + pagesTotal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "typesWithErrors": + typesWithErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!itemsTotal.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodResponse.", nameof(itemsTotal)); + + if (!pagesTotal.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodResponse.", nameof(pagesTotal)); + + return new PaymentMethodResponse(itemsTotal.Value!.Value!, pagesTotal.Value!.Value!, links, data, typesWithErrors); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodResponse paymentMethodResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodResponse paymentMethodResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("itemsTotal", paymentMethodResponse.ItemsTotal); + + writer.WriteNumber("pagesTotal", paymentMethodResponse.PagesTotal); + + if (paymentMethodResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, paymentMethodResponse.Links, jsonSerializerOptions); + } + if (paymentMethodResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paymentMethodResponse.Data, jsonSerializerOptions); + } + if (paymentMethodResponse._TypesWithErrorsOption.IsSet) + { + writer.WritePropertyName("typesWithErrors"); + JsonSerializer.Serialize(writer, paymentMethodResponse.TypesWithErrors, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/PaymentMethodSetupInfo.cs b/Adyen/Management/Models/PaymentMethodSetupInfo.cs new file mode 100644 index 000000000..355d36f55 --- /dev/null +++ b/Adyen/Management/Models/PaymentMethodSetupInfo.cs @@ -0,0 +1,2765 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PaymentMethodSetupInfo. + /// + public partial class PaymentMethodSetupInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// accel + /// affirm + /// afterpayTouch + /// alipayPlus + /// amex + /// applePay + /// bcmc + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + /// cartesBancaires + /// clearpay + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// cup + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// The list of custom routing flags to route payment to the intended acquirer. + /// diners + /// discover + /// eftDirectdebitCA + /// eftposAustralia + /// girocard + /// googlePay + /// ideal + /// interacCard + /// jcb + /// klarna + /// maestro + /// maestroUsa + /// mc + /// mealVoucherFR + /// nyce + /// paybybankPlaid + /// payme + /// paypal + /// payto + /// pulse + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + /// sepadirectdebit + /// The sales channel. Required if the merchant account does not have a sales channel. When you provide this field, it overrides the default sales channel set on the merchant account. Possible values: **eCommerce**, **pos**, **contAuth**, and **moto**. + /// sodexo + /// sofort + /// star + /// The unique identifier of the store for which to configure the payment method, if any. + /// swish + /// ticket + /// twint + /// vipps + /// visa + /// wechatpay + /// wechatpayPos + [JsonConstructor] + public PaymentMethodSetupInfo(TypeEnum type, Option accel = default, Option affirm = default, Option afterpayTouch = default, Option alipayPlus = default, Option amex = default, Option applePay = default, Option bcmc = default, Option businessLineId = default, Option cartesBancaires = default, Option clearpay = default, Option?> countries = default, Option cup = default, Option?> currencies = default, Option?> customRoutingFlags = default, Option diners = default, Option discover = default, Option eftDirectdebitCA = default, Option eftposAustralia = default, Option girocard = default, Option googlePay = default, Option ideal = default, Option interacCard = default, Option jcb = default, Option klarna = default, Option maestro = default, Option maestroUsa = default, Option mc = default, Option mealVoucherFR = default, Option nyce = default, Option paybybankPlaid = default, Option payme = default, Option paypal = default, Option payto = default, Option pulse = default, Option reference = default, Option sepadirectdebit = default, Option shopperInteraction = default, Option sodexo = default, Option sofort = default, Option star = default, Option?> storeIds = default, Option swish = default, Option ticket = default, Option twint = default, Option vipps = default, Option visa = default, Option wechatpay = default, Option wechatpayPos = default) + { + Type = type; + _AccelOption = accel; + _AffirmOption = affirm; + _AfterpayTouchOption = afterpayTouch; + _AlipayPlusOption = alipayPlus; + _AmexOption = amex; + _ApplePayOption = applePay; + _BcmcOption = bcmc; + _BusinessLineIdOption = businessLineId; + _CartesBancairesOption = cartesBancaires; + _ClearpayOption = clearpay; + _CountriesOption = countries; + _CupOption = cup; + _CurrenciesOption = currencies; + _CustomRoutingFlagsOption = customRoutingFlags; + _DinersOption = diners; + _DiscoverOption = discover; + _EftDirectdebitCAOption = eftDirectdebitCA; + _EftposAustraliaOption = eftposAustralia; + _GirocardOption = girocard; + _GooglePayOption = googlePay; + _IdealOption = ideal; + _InteracCardOption = interacCard; + _JcbOption = jcb; + _KlarnaOption = klarna; + _MaestroOption = maestro; + _MaestroUsaOption = maestroUsa; + _McOption = mc; + _MealVoucherFROption = mealVoucherFR; + _NyceOption = nyce; + _PaybybankPlaidOption = paybybankPlaid; + _PaymeOption = payme; + _PaypalOption = paypal; + _PaytoOption = payto; + _PulseOption = pulse; + _ReferenceOption = reference; + _SepadirectdebitOption = sepadirectdebit; + _ShopperInteractionOption = shopperInteraction; + _SodexoOption = sodexo; + _SofortOption = sofort; + _StarOption = star; + _StoreIdsOption = storeIds; + _SwishOption = swish; + _TicketOption = ticket; + _TwintOption = twint; + _VippsOption = vipps; + _VisaOption = visa; + _WechatpayOption = wechatpay; + _WechatpayPosOption = wechatpayPos; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodSetupInfo() + { + } + + partial void OnCreated(); + + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Abrapetite - abrapetite + /// + public static readonly TypeEnum Abrapetite = new("abrapetite"); + + /// + /// TypeEnum.AbrapetiteCredit - abrapetite_credit + /// + public static readonly TypeEnum AbrapetiteCredit = new("abrapetite_credit"); + + /// + /// TypeEnum.AbrapetiteDebit - abrapetite_debit + /// + public static readonly TypeEnum AbrapetiteDebit = new("abrapetite_debit"); + + /// + /// TypeEnum.AbrapetitePrepaid - abrapetite_prepaid + /// + public static readonly TypeEnum AbrapetitePrepaid = new("abrapetite_prepaid"); + + /// + /// TypeEnum.Accel - accel + /// + public static readonly TypeEnum Accel = new("accel"); + + /// + /// TypeEnum.Ach - ach + /// + public static readonly TypeEnum Ach = new("ach"); + + /// + /// TypeEnum.Affirm - affirm + /// + public static readonly TypeEnum Affirm = new("affirm"); + + /// + /// TypeEnum.Afterpaytouch - afterpaytouch + /// + public static readonly TypeEnum Afterpaytouch = new("afterpaytouch"); + + /// + /// TypeEnum.Alelo - alelo + /// + public static readonly TypeEnum Alelo = new("alelo"); + + /// + /// TypeEnum.Alipay - alipay + /// + public static readonly TypeEnum Alipay = new("alipay"); + + /// + /// TypeEnum.AlipayHk - alipay_hk + /// + public static readonly TypeEnum AlipayHk = new("alipay_hk"); + + /// + /// TypeEnum.AlipayPlus - alipay_plus + /// + public static readonly TypeEnum AlipayPlus = new("alipay_plus"); + + /// + /// TypeEnum.AlipayWap - alipay_wap + /// + public static readonly TypeEnum AlipayWap = new("alipay_wap"); + + /// + /// TypeEnum.Amex - amex + /// + public static readonly TypeEnum Amex = new("amex"); + + /// + /// TypeEnum.Applepay - applepay + /// + public static readonly TypeEnum Applepay = new("applepay"); + + /// + /// TypeEnum.Avancard - avancard + /// + public static readonly TypeEnum Avancard = new("avancard"); + + /// + /// TypeEnum.AvancardCredit - avancard_credit + /// + public static readonly TypeEnum AvancardCredit = new("avancard_credit"); + + /// + /// TypeEnum.AvancardDebit - avancard_debit + /// + public static readonly TypeEnum AvancardDebit = new("avancard_debit"); + + /// + /// TypeEnum.BaneseCard - banese_card + /// + public static readonly TypeEnum BaneseCard = new("banese_card"); + + /// + /// TypeEnum.BaneseCardCredit - banese_card_credit + /// + public static readonly TypeEnum BaneseCardCredit = new("banese_card_credit"); + + /// + /// TypeEnum.BaneseCardDebit - banese_card_debit + /// + public static readonly TypeEnum BaneseCardDebit = new("banese_card_debit"); + + /// + /// TypeEnum.BaneseCardPrepaid - banese_card_prepaid + /// + public static readonly TypeEnum BaneseCardPrepaid = new("banese_card_prepaid"); + + /// + /// TypeEnum.Bcmc - bcmc + /// + public static readonly TypeEnum Bcmc = new("bcmc"); + + /// + /// TypeEnum.Blik - blik + /// + public static readonly TypeEnum Blik = new("blik"); + + /// + /// TypeEnum.BrSchemes - br_schemes + /// + public static readonly TypeEnum BrSchemes = new("br_schemes"); + + /// + /// TypeEnum.Cartebancaire - cartebancaire + /// + public static readonly TypeEnum Cartebancaire = new("cartebancaire"); + + /// + /// TypeEnum.Clearpay - clearpay + /// + public static readonly TypeEnum Clearpay = new("clearpay"); + + /// + /// TypeEnum.Clicktopay - clicktopay + /// + public static readonly TypeEnum Clicktopay = new("clicktopay"); + + /// + /// TypeEnum.Cooper - cooper + /// + public static readonly TypeEnum Cooper = new("cooper"); + + /// + /// TypeEnum.CooperCredit - cooper_credit + /// + public static readonly TypeEnum CooperCredit = new("cooper_credit"); + + /// + /// TypeEnum.CooperDebit - cooper_debit + /// + public static readonly TypeEnum CooperDebit = new("cooper_debit"); + + /// + /// TypeEnum.CooperFoodDebit - cooper_food_debit + /// + public static readonly TypeEnum CooperFoodDebit = new("cooper_food_debit"); + + /// + /// TypeEnum.CooperMealDebit - cooper_meal_debit + /// + public static readonly TypeEnum CooperMealDebit = new("cooper_meal_debit"); + + /// + /// TypeEnum.CooperPrepaid - cooper_prepaid + /// + public static readonly TypeEnum CooperPrepaid = new("cooper_prepaid"); + + /// + /// TypeEnum.CooperPrivateCredit - cooper_private_credit + /// + public static readonly TypeEnum CooperPrivateCredit = new("cooper_private_credit"); + + /// + /// TypeEnum.CooperRetailCredit - cooper_retail_credit + /// + public static readonly TypeEnum CooperRetailCredit = new("cooper_retail_credit"); + + /// + /// TypeEnum.Credtodos - credtodos + /// + public static readonly TypeEnum Credtodos = new("credtodos"); + + /// + /// TypeEnum.CredtodosPrivateCredit - credtodos_private_credit + /// + public static readonly TypeEnum CredtodosPrivateCredit = new("credtodos_private_credit"); + + /// + /// TypeEnum.CredtodosPrivateDebit - credtodos_private_debit + /// + public static readonly TypeEnum CredtodosPrivateDebit = new("credtodos_private_debit"); + + /// + /// TypeEnum.Cup - cup + /// + public static readonly TypeEnum Cup = new("cup"); + + /// + /// TypeEnum.Diners - diners + /// + public static readonly TypeEnum Diners = new("diners"); + + /// + /// TypeEnum.DirectdebitGB - directdebit_GB + /// + public static readonly TypeEnum DirectdebitGB = new("directdebit_GB"); + + /// + /// TypeEnum.Discover - discover + /// + public static readonly TypeEnum Discover = new("discover"); + + /// + /// TypeEnum.EbankingFI - ebanking_FI + /// + public static readonly TypeEnum EbankingFI = new("ebanking_FI"); + + /// + /// TypeEnum.EftDirectdebitCA - eft_directdebit_CA + /// + public static readonly TypeEnum EftDirectdebitCA = new("eft_directdebit_CA"); + + /// + /// TypeEnum.EftposAustralia - eftpos_australia + /// + public static readonly TypeEnum EftposAustralia = new("eftpos_australia"); + + /// + /// TypeEnum.Elo - elo + /// + public static readonly TypeEnum Elo = new("elo"); + + /// + /// TypeEnum.Elocredit - elocredit + /// + public static readonly TypeEnum Elocredit = new("elocredit"); + + /// + /// TypeEnum.Elodebit - elodebit + /// + public static readonly TypeEnum Elodebit = new("elodebit"); + + /// + /// TypeEnum.Girocard - girocard + /// + public static readonly TypeEnum Girocard = new("girocard"); + + /// + /// TypeEnum.Googlepay - googlepay + /// + public static readonly TypeEnum Googlepay = new("googlepay"); + + /// + /// TypeEnum.GreenCard - green_card + /// + public static readonly TypeEnum GreenCard = new("green_card"); + + /// + /// TypeEnum.GreenCardCredit - green_card_credit + /// + public static readonly TypeEnum GreenCardCredit = new("green_card_credit"); + + /// + /// TypeEnum.GreenCardDebit - green_card_debit + /// + public static readonly TypeEnum GreenCardDebit = new("green_card_debit"); + + /// + /// TypeEnum.GreenCardFoodPrepaid - green_card_food_prepaid + /// + public static readonly TypeEnum GreenCardFoodPrepaid = new("green_card_food_prepaid"); + + /// + /// TypeEnum.GreenCardMealPrepaid - green_card_meal_prepaid + /// + public static readonly TypeEnum GreenCardMealPrepaid = new("green_card_meal_prepaid"); + + /// + /// TypeEnum.GreenCardPrepaid - green_card_prepaid + /// + public static readonly TypeEnum GreenCardPrepaid = new("green_card_prepaid"); + + /// + /// TypeEnum.Hiper - hiper + /// + public static readonly TypeEnum Hiper = new("hiper"); + + /// + /// TypeEnum.Hipercard - hipercard + /// + public static readonly TypeEnum Hipercard = new("hipercard"); + + /// + /// TypeEnum.Ideal - ideal + /// + public static readonly TypeEnum Ideal = new("ideal"); + + /// + /// TypeEnum.InteracCard - interac_card + /// + public static readonly TypeEnum InteracCard = new("interac_card"); + + /// + /// TypeEnum.Jcb - jcb + /// + public static readonly TypeEnum Jcb = new("jcb"); + + /// + /// TypeEnum.Klarna - klarna + /// + public static readonly TypeEnum Klarna = new("klarna"); + + /// + /// TypeEnum.KlarnaAccount - klarna_account + /// + public static readonly TypeEnum KlarnaAccount = new("klarna_account"); + + /// + /// TypeEnum.KlarnaPaynow - klarna_paynow + /// + public static readonly TypeEnum KlarnaPaynow = new("klarna_paynow"); + + /// + /// TypeEnum.LeCard - le_card + /// + public static readonly TypeEnum LeCard = new("le_card"); + + /// + /// TypeEnum.LeCardCredit - le_card_credit + /// + public static readonly TypeEnum LeCardCredit = new("le_card_credit"); + + /// + /// TypeEnum.LeCardDebit - le_card_debit + /// + public static readonly TypeEnum LeCardDebit = new("le_card_debit"); + + /// + /// TypeEnum.Maestro - maestro + /// + public static readonly TypeEnum Maestro = new("maestro"); + + /// + /// TypeEnum.MaestroUsa - maestro_usa + /// + public static readonly TypeEnum MaestroUsa = new("maestro_usa"); + + /// + /// TypeEnum.Maxifrota - maxifrota + /// + public static readonly TypeEnum Maxifrota = new("maxifrota"); + + /// + /// TypeEnum.MaxifrotaPrepaid - maxifrota_prepaid + /// + public static readonly TypeEnum MaxifrotaPrepaid = new("maxifrota_prepaid"); + + /// + /// TypeEnum.Mbway - mbway + /// + public static readonly TypeEnum Mbway = new("mbway"); + + /// + /// TypeEnum.Mc - mc + /// + public static readonly TypeEnum Mc = new("mc"); + + /// + /// TypeEnum.Mcdebit - mcdebit + /// + public static readonly TypeEnum Mcdebit = new("mcdebit"); + + /// + /// TypeEnum.MealVoucherFR - mealVoucher_FR + /// + public static readonly TypeEnum MealVoucherFR = new("mealVoucher_FR"); + + /// + /// TypeEnum.Megaleve - megaleve + /// + public static readonly TypeEnum Megaleve = new("megaleve"); + + /// + /// TypeEnum.MegaleveCredit - megaleve_credit + /// + public static readonly TypeEnum MegaleveCredit = new("megaleve_credit"); + + /// + /// TypeEnum.MegaleveDebit - megaleve_debit + /// + public static readonly TypeEnum MegaleveDebit = new("megaleve_debit"); + + /// + /// TypeEnum.Mobilepay - mobilepay + /// + public static readonly TypeEnum Mobilepay = new("mobilepay"); + + /// + /// TypeEnum.Multibanco - multibanco + /// + public static readonly TypeEnum Multibanco = new("multibanco"); + + /// + /// TypeEnum.Nutricash - nutricash + /// + public static readonly TypeEnum Nutricash = new("nutricash"); + + /// + /// TypeEnum.NutricashPrepaid - nutricash_prepaid + /// + public static readonly TypeEnum NutricashPrepaid = new("nutricash_prepaid"); + + /// + /// TypeEnum.Nyce - nyce + /// + public static readonly TypeEnum Nyce = new("nyce"); + + /// + /// TypeEnum.OnlineBankingPL - onlineBanking_PL + /// + public static readonly TypeEnum OnlineBankingPL = new("onlineBanking_PL"); + + /// + /// TypeEnum.Paybybank - paybybank + /// + public static readonly TypeEnum Paybybank = new("paybybank"); + + /// + /// TypeEnum.PaybybankPlaid - paybybank_plaid + /// + public static readonly TypeEnum PaybybankPlaid = new("paybybank_plaid"); + + /// + /// TypeEnum.Payme - payme + /// + public static readonly TypeEnum Payme = new("payme"); + + /// + /// TypeEnum.PaymePos - payme_pos + /// + public static readonly TypeEnum PaymePos = new("payme_pos"); + + /// + /// TypeEnum.Paynow - paynow + /// + public static readonly TypeEnum Paynow = new("paynow"); + + /// + /// TypeEnum.PaynowPos - paynow_pos + /// + public static readonly TypeEnum PaynowPos = new("paynow_pos"); + + /// + /// TypeEnum.Paypal - paypal + /// + public static readonly TypeEnum Paypal = new("paypal"); + + /// + /// TypeEnum.Payto - payto + /// + public static readonly TypeEnum Payto = new("payto"); + + /// + /// TypeEnum.PersonalCard - personal_card + /// + public static readonly TypeEnum PersonalCard = new("personal_card"); + + /// + /// TypeEnum.PersonalCardCredit - personal_card_credit + /// + public static readonly TypeEnum PersonalCardCredit = new("personal_card_credit"); + + /// + /// TypeEnum.PersonalCardDebit - personal_card_debit + /// + public static readonly TypeEnum PersonalCardDebit = new("personal_card_debit"); + + /// + /// TypeEnum.Pulse - pulse + /// + public static readonly TypeEnum Pulse = new("pulse"); + + /// + /// TypeEnum.Romcard - romcard + /// + public static readonly TypeEnum Romcard = new("romcard"); + + /// + /// TypeEnum.RomcardCredit - romcard_credit + /// + public static readonly TypeEnum RomcardCredit = new("romcard_credit"); + + /// + /// TypeEnum.RomcardDebit - romcard_debit + /// + public static readonly TypeEnum RomcardDebit = new("romcard_debit"); + + /// + /// TypeEnum.Senff - senff + /// + public static readonly TypeEnum Senff = new("senff"); + + /// + /// TypeEnum.SenffCredit - senff_credit + /// + public static readonly TypeEnum SenffCredit = new("senff_credit"); + + /// + /// TypeEnum.Sepadirectdebit - sepadirectdebit + /// + public static readonly TypeEnum Sepadirectdebit = new("sepadirectdebit"); + + /// + /// TypeEnum.Sodexo - sodexo + /// + public static readonly TypeEnum Sodexo = new("sodexo"); + + /// + /// TypeEnum.Star - star + /// + public static readonly TypeEnum Star = new("star"); + + /// + /// TypeEnum.Swish - swish + /// + public static readonly TypeEnum Swish = new("swish"); + + /// + /// TypeEnum.Ticket - ticket + /// + public static readonly TypeEnum Ticket = new("ticket"); + + /// + /// TypeEnum.TodoGiftcard - todo_giftcard + /// + public static readonly TypeEnum TodoGiftcard = new("todo_giftcard"); + + /// + /// TypeEnum.Trustly - trustly + /// + public static readonly TypeEnum Trustly = new("trustly"); + + /// + /// TypeEnum.Twint - twint + /// + public static readonly TypeEnum Twint = new("twint"); + + /// + /// TypeEnum.TwintPos - twint_pos + /// + public static readonly TypeEnum TwintPos = new("twint_pos"); + + /// + /// TypeEnum.UpBrazil - up_brazil + /// + public static readonly TypeEnum UpBrazil = new("up_brazil"); + + /// + /// TypeEnum.UpBrazilCredit - up_brazil_credit + /// + public static readonly TypeEnum UpBrazilCredit = new("up_brazil_credit"); + + /// + /// TypeEnum.UpBrazilDebit - up_brazil_debit + /// + public static readonly TypeEnum UpBrazilDebit = new("up_brazil_debit"); + + /// + /// TypeEnum.UpBrazilPrepaid - up_brazil_prepaid + /// + public static readonly TypeEnum UpBrazilPrepaid = new("up_brazil_prepaid"); + + /// + /// TypeEnum.ValeRefeicao - vale_refeicao + /// + public static readonly TypeEnum ValeRefeicao = new("vale_refeicao"); + + /// + /// TypeEnum.ValeRefeicaoPrepaid - vale_refeicao_prepaid + /// + public static readonly TypeEnum ValeRefeicaoPrepaid = new("vale_refeicao_prepaid"); + + /// + /// TypeEnum.VegasCard - vegas_card + /// + public static readonly TypeEnum VegasCard = new("vegas_card"); + + /// + /// TypeEnum.VegasCardCredit - vegas_card_credit + /// + public static readonly TypeEnum VegasCardCredit = new("vegas_card_credit"); + + /// + /// TypeEnum.VegasCardDebit - vegas_card_debit + /// + public static readonly TypeEnum VegasCardDebit = new("vegas_card_debit"); + + /// + /// TypeEnum.VeroCard - vero_card + /// + public static readonly TypeEnum VeroCard = new("vero_card"); + + /// + /// TypeEnum.VeroCardCredit - vero_card_credit + /// + public static readonly TypeEnum VeroCardCredit = new("vero_card_credit"); + + /// + /// TypeEnum.VeroCardDebit - vero_card_debit + /// + public static readonly TypeEnum VeroCardDebit = new("vero_card_debit"); + + /// + /// TypeEnum.VeroCardPrepaid - vero_card_prepaid + /// + public static readonly TypeEnum VeroCardPrepaid = new("vero_card_prepaid"); + + /// + /// TypeEnum.Vipps - vipps + /// + public static readonly TypeEnum Vipps = new("vipps"); + + /// + /// TypeEnum.Visa - visa + /// + public static readonly TypeEnum Visa = new("visa"); + + /// + /// TypeEnum.Visadebit - visadebit + /// + public static readonly TypeEnum Visadebit = new("visadebit"); + + /// + /// TypeEnum.Vpay - vpay + /// + public static readonly TypeEnum Vpay = new("vpay"); + + /// + /// TypeEnum.Wechatpay - wechatpay + /// + public static readonly TypeEnum Wechatpay = new("wechatpay"); + + /// + /// TypeEnum.WechatpayPos - wechatpay_pos + /// + public static readonly TypeEnum WechatpayPos = new("wechatpay_pos"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "abrapetite" => TypeEnum.Abrapetite, + "abrapetite_credit" => TypeEnum.AbrapetiteCredit, + "abrapetite_debit" => TypeEnum.AbrapetiteDebit, + "abrapetite_prepaid" => TypeEnum.AbrapetitePrepaid, + "accel" => TypeEnum.Accel, + "ach" => TypeEnum.Ach, + "affirm" => TypeEnum.Affirm, + "afterpaytouch" => TypeEnum.Afterpaytouch, + "alelo" => TypeEnum.Alelo, + "alipay" => TypeEnum.Alipay, + "alipay_hk" => TypeEnum.AlipayHk, + "alipay_plus" => TypeEnum.AlipayPlus, + "alipay_wap" => TypeEnum.AlipayWap, + "amex" => TypeEnum.Amex, + "applepay" => TypeEnum.Applepay, + "avancard" => TypeEnum.Avancard, + "avancard_credit" => TypeEnum.AvancardCredit, + "avancard_debit" => TypeEnum.AvancardDebit, + "banese_card" => TypeEnum.BaneseCard, + "banese_card_credit" => TypeEnum.BaneseCardCredit, + "banese_card_debit" => TypeEnum.BaneseCardDebit, + "banese_card_prepaid" => TypeEnum.BaneseCardPrepaid, + "bcmc" => TypeEnum.Bcmc, + "blik" => TypeEnum.Blik, + "br_schemes" => TypeEnum.BrSchemes, + "cartebancaire" => TypeEnum.Cartebancaire, + "clearpay" => TypeEnum.Clearpay, + "clicktopay" => TypeEnum.Clicktopay, + "cooper" => TypeEnum.Cooper, + "cooper_credit" => TypeEnum.CooperCredit, + "cooper_debit" => TypeEnum.CooperDebit, + "cooper_food_debit" => TypeEnum.CooperFoodDebit, + "cooper_meal_debit" => TypeEnum.CooperMealDebit, + "cooper_prepaid" => TypeEnum.CooperPrepaid, + "cooper_private_credit" => TypeEnum.CooperPrivateCredit, + "cooper_retail_credit" => TypeEnum.CooperRetailCredit, + "credtodos" => TypeEnum.Credtodos, + "credtodos_private_credit" => TypeEnum.CredtodosPrivateCredit, + "credtodos_private_debit" => TypeEnum.CredtodosPrivateDebit, + "cup" => TypeEnum.Cup, + "diners" => TypeEnum.Diners, + "directdebit_GB" => TypeEnum.DirectdebitGB, + "discover" => TypeEnum.Discover, + "ebanking_FI" => TypeEnum.EbankingFI, + "eft_directdebit_CA" => TypeEnum.EftDirectdebitCA, + "eftpos_australia" => TypeEnum.EftposAustralia, + "elo" => TypeEnum.Elo, + "elocredit" => TypeEnum.Elocredit, + "elodebit" => TypeEnum.Elodebit, + "girocard" => TypeEnum.Girocard, + "googlepay" => TypeEnum.Googlepay, + "green_card" => TypeEnum.GreenCard, + "green_card_credit" => TypeEnum.GreenCardCredit, + "green_card_debit" => TypeEnum.GreenCardDebit, + "green_card_food_prepaid" => TypeEnum.GreenCardFoodPrepaid, + "green_card_meal_prepaid" => TypeEnum.GreenCardMealPrepaid, + "green_card_prepaid" => TypeEnum.GreenCardPrepaid, + "hiper" => TypeEnum.Hiper, + "hipercard" => TypeEnum.Hipercard, + "ideal" => TypeEnum.Ideal, + "interac_card" => TypeEnum.InteracCard, + "jcb" => TypeEnum.Jcb, + "klarna" => TypeEnum.Klarna, + "klarna_account" => TypeEnum.KlarnaAccount, + "klarna_paynow" => TypeEnum.KlarnaPaynow, + "le_card" => TypeEnum.LeCard, + "le_card_credit" => TypeEnum.LeCardCredit, + "le_card_debit" => TypeEnum.LeCardDebit, + "maestro" => TypeEnum.Maestro, + "maestro_usa" => TypeEnum.MaestroUsa, + "maxifrota" => TypeEnum.Maxifrota, + "maxifrota_prepaid" => TypeEnum.MaxifrotaPrepaid, + "mbway" => TypeEnum.Mbway, + "mc" => TypeEnum.Mc, + "mcdebit" => TypeEnum.Mcdebit, + "mealVoucher_FR" => TypeEnum.MealVoucherFR, + "megaleve" => TypeEnum.Megaleve, + "megaleve_credit" => TypeEnum.MegaleveCredit, + "megaleve_debit" => TypeEnum.MegaleveDebit, + "mobilepay" => TypeEnum.Mobilepay, + "multibanco" => TypeEnum.Multibanco, + "nutricash" => TypeEnum.Nutricash, + "nutricash_prepaid" => TypeEnum.NutricashPrepaid, + "nyce" => TypeEnum.Nyce, + "onlineBanking_PL" => TypeEnum.OnlineBankingPL, + "paybybank" => TypeEnum.Paybybank, + "paybybank_plaid" => TypeEnum.PaybybankPlaid, + "payme" => TypeEnum.Payme, + "payme_pos" => TypeEnum.PaymePos, + "paynow" => TypeEnum.Paynow, + "paynow_pos" => TypeEnum.PaynowPos, + "paypal" => TypeEnum.Paypal, + "payto" => TypeEnum.Payto, + "personal_card" => TypeEnum.PersonalCard, + "personal_card_credit" => TypeEnum.PersonalCardCredit, + "personal_card_debit" => TypeEnum.PersonalCardDebit, + "pulse" => TypeEnum.Pulse, + "romcard" => TypeEnum.Romcard, + "romcard_credit" => TypeEnum.RomcardCredit, + "romcard_debit" => TypeEnum.RomcardDebit, + "senff" => TypeEnum.Senff, + "senff_credit" => TypeEnum.SenffCredit, + "sepadirectdebit" => TypeEnum.Sepadirectdebit, + "sodexo" => TypeEnum.Sodexo, + "star" => TypeEnum.Star, + "swish" => TypeEnum.Swish, + "ticket" => TypeEnum.Ticket, + "todo_giftcard" => TypeEnum.TodoGiftcard, + "trustly" => TypeEnum.Trustly, + "twint" => TypeEnum.Twint, + "twint_pos" => TypeEnum.TwintPos, + "up_brazil" => TypeEnum.UpBrazil, + "up_brazil_credit" => TypeEnum.UpBrazilCredit, + "up_brazil_debit" => TypeEnum.UpBrazilDebit, + "up_brazil_prepaid" => TypeEnum.UpBrazilPrepaid, + "vale_refeicao" => TypeEnum.ValeRefeicao, + "vale_refeicao_prepaid" => TypeEnum.ValeRefeicaoPrepaid, + "vegas_card" => TypeEnum.VegasCard, + "vegas_card_credit" => TypeEnum.VegasCardCredit, + "vegas_card_debit" => TypeEnum.VegasCardDebit, + "vero_card" => TypeEnum.VeroCard, + "vero_card_credit" => TypeEnum.VeroCardCredit, + "vero_card_debit" => TypeEnum.VeroCardDebit, + "vero_card_prepaid" => TypeEnum.VeroCardPrepaid, + "vipps" => TypeEnum.Vipps, + "visa" => TypeEnum.Visa, + "visadebit" => TypeEnum.Visadebit, + "vpay" => TypeEnum.Vpay, + "wechatpay" => TypeEnum.Wechatpay, + "wechatpay_pos" => TypeEnum.WechatpayPos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Abrapetite) + return "abrapetite"; + + if (value == TypeEnum.AbrapetiteCredit) + return "abrapetite_credit"; + + if (value == TypeEnum.AbrapetiteDebit) + return "abrapetite_debit"; + + if (value == TypeEnum.AbrapetitePrepaid) + return "abrapetite_prepaid"; + + if (value == TypeEnum.Accel) + return "accel"; + + if (value == TypeEnum.Ach) + return "ach"; + + if (value == TypeEnum.Affirm) + return "affirm"; + + if (value == TypeEnum.Afterpaytouch) + return "afterpaytouch"; + + if (value == TypeEnum.Alelo) + return "alelo"; + + if (value == TypeEnum.Alipay) + return "alipay"; + + if (value == TypeEnum.AlipayHk) + return "alipay_hk"; + + if (value == TypeEnum.AlipayPlus) + return "alipay_plus"; + + if (value == TypeEnum.AlipayWap) + return "alipay_wap"; + + if (value == TypeEnum.Amex) + return "amex"; + + if (value == TypeEnum.Applepay) + return "applepay"; + + if (value == TypeEnum.Avancard) + return "avancard"; + + if (value == TypeEnum.AvancardCredit) + return "avancard_credit"; + + if (value == TypeEnum.AvancardDebit) + return "avancard_debit"; + + if (value == TypeEnum.BaneseCard) + return "banese_card"; + + if (value == TypeEnum.BaneseCardCredit) + return "banese_card_credit"; + + if (value == TypeEnum.BaneseCardDebit) + return "banese_card_debit"; + + if (value == TypeEnum.BaneseCardPrepaid) + return "banese_card_prepaid"; + + if (value == TypeEnum.Bcmc) + return "bcmc"; + + if (value == TypeEnum.Blik) + return "blik"; + + if (value == TypeEnum.BrSchemes) + return "br_schemes"; + + if (value == TypeEnum.Cartebancaire) + return "cartebancaire"; + + if (value == TypeEnum.Clearpay) + return "clearpay"; + + if (value == TypeEnum.Clicktopay) + return "clicktopay"; + + if (value == TypeEnum.Cooper) + return "cooper"; + + if (value == TypeEnum.CooperCredit) + return "cooper_credit"; + + if (value == TypeEnum.CooperDebit) + return "cooper_debit"; + + if (value == TypeEnum.CooperFoodDebit) + return "cooper_food_debit"; + + if (value == TypeEnum.CooperMealDebit) + return "cooper_meal_debit"; + + if (value == TypeEnum.CooperPrepaid) + return "cooper_prepaid"; + + if (value == TypeEnum.CooperPrivateCredit) + return "cooper_private_credit"; + + if (value == TypeEnum.CooperRetailCredit) + return "cooper_retail_credit"; + + if (value == TypeEnum.Credtodos) + return "credtodos"; + + if (value == TypeEnum.CredtodosPrivateCredit) + return "credtodos_private_credit"; + + if (value == TypeEnum.CredtodosPrivateDebit) + return "credtodos_private_debit"; + + if (value == TypeEnum.Cup) + return "cup"; + + if (value == TypeEnum.Diners) + return "diners"; + + if (value == TypeEnum.DirectdebitGB) + return "directdebit_GB"; + + if (value == TypeEnum.Discover) + return "discover"; + + if (value == TypeEnum.EbankingFI) + return "ebanking_FI"; + + if (value == TypeEnum.EftDirectdebitCA) + return "eft_directdebit_CA"; + + if (value == TypeEnum.EftposAustralia) + return "eftpos_australia"; + + if (value == TypeEnum.Elo) + return "elo"; + + if (value == TypeEnum.Elocredit) + return "elocredit"; + + if (value == TypeEnum.Elodebit) + return "elodebit"; + + if (value == TypeEnum.Girocard) + return "girocard"; + + if (value == TypeEnum.Googlepay) + return "googlepay"; + + if (value == TypeEnum.GreenCard) + return "green_card"; + + if (value == TypeEnum.GreenCardCredit) + return "green_card_credit"; + + if (value == TypeEnum.GreenCardDebit) + return "green_card_debit"; + + if (value == TypeEnum.GreenCardFoodPrepaid) + return "green_card_food_prepaid"; + + if (value == TypeEnum.GreenCardMealPrepaid) + return "green_card_meal_prepaid"; + + if (value == TypeEnum.GreenCardPrepaid) + return "green_card_prepaid"; + + if (value == TypeEnum.Hiper) + return "hiper"; + + if (value == TypeEnum.Hipercard) + return "hipercard"; + + if (value == TypeEnum.Ideal) + return "ideal"; + + if (value == TypeEnum.InteracCard) + return "interac_card"; + + if (value == TypeEnum.Jcb) + return "jcb"; + + if (value == TypeEnum.Klarna) + return "klarna"; + + if (value == TypeEnum.KlarnaAccount) + return "klarna_account"; + + if (value == TypeEnum.KlarnaPaynow) + return "klarna_paynow"; + + if (value == TypeEnum.LeCard) + return "le_card"; + + if (value == TypeEnum.LeCardCredit) + return "le_card_credit"; + + if (value == TypeEnum.LeCardDebit) + return "le_card_debit"; + + if (value == TypeEnum.Maestro) + return "maestro"; + + if (value == TypeEnum.MaestroUsa) + return "maestro_usa"; + + if (value == TypeEnum.Maxifrota) + return "maxifrota"; + + if (value == TypeEnum.MaxifrotaPrepaid) + return "maxifrota_prepaid"; + + if (value == TypeEnum.Mbway) + return "mbway"; + + if (value == TypeEnum.Mc) + return "mc"; + + if (value == TypeEnum.Mcdebit) + return "mcdebit"; + + if (value == TypeEnum.MealVoucherFR) + return "mealVoucher_FR"; + + if (value == TypeEnum.Megaleve) + return "megaleve"; + + if (value == TypeEnum.MegaleveCredit) + return "megaleve_credit"; + + if (value == TypeEnum.MegaleveDebit) + return "megaleve_debit"; + + if (value == TypeEnum.Mobilepay) + return "mobilepay"; + + if (value == TypeEnum.Multibanco) + return "multibanco"; + + if (value == TypeEnum.Nutricash) + return "nutricash"; + + if (value == TypeEnum.NutricashPrepaid) + return "nutricash_prepaid"; + + if (value == TypeEnum.Nyce) + return "nyce"; + + if (value == TypeEnum.OnlineBankingPL) + return "onlineBanking_PL"; + + if (value == TypeEnum.Paybybank) + return "paybybank"; + + if (value == TypeEnum.PaybybankPlaid) + return "paybybank_plaid"; + + if (value == TypeEnum.Payme) + return "payme"; + + if (value == TypeEnum.PaymePos) + return "payme_pos"; + + if (value == TypeEnum.Paynow) + return "paynow"; + + if (value == TypeEnum.PaynowPos) + return "paynow_pos"; + + if (value == TypeEnum.Paypal) + return "paypal"; + + if (value == TypeEnum.Payto) + return "payto"; + + if (value == TypeEnum.PersonalCard) + return "personal_card"; + + if (value == TypeEnum.PersonalCardCredit) + return "personal_card_credit"; + + if (value == TypeEnum.PersonalCardDebit) + return "personal_card_debit"; + + if (value == TypeEnum.Pulse) + return "pulse"; + + if (value == TypeEnum.Romcard) + return "romcard"; + + if (value == TypeEnum.RomcardCredit) + return "romcard_credit"; + + if (value == TypeEnum.RomcardDebit) + return "romcard_debit"; + + if (value == TypeEnum.Senff) + return "senff"; + + if (value == TypeEnum.SenffCredit) + return "senff_credit"; + + if (value == TypeEnum.Sepadirectdebit) + return "sepadirectdebit"; + + if (value == TypeEnum.Sodexo) + return "sodexo"; + + if (value == TypeEnum.Star) + return "star"; + + if (value == TypeEnum.Swish) + return "swish"; + + if (value == TypeEnum.Ticket) + return "ticket"; + + if (value == TypeEnum.TodoGiftcard) + return "todo_giftcard"; + + if (value == TypeEnum.Trustly) + return "trustly"; + + if (value == TypeEnum.Twint) + return "twint"; + + if (value == TypeEnum.TwintPos) + return "twint_pos"; + + if (value == TypeEnum.UpBrazil) + return "up_brazil"; + + if (value == TypeEnum.UpBrazilCredit) + return "up_brazil_credit"; + + if (value == TypeEnum.UpBrazilDebit) + return "up_brazil_debit"; + + if (value == TypeEnum.UpBrazilPrepaid) + return "up_brazil_prepaid"; + + if (value == TypeEnum.ValeRefeicao) + return "vale_refeicao"; + + if (value == TypeEnum.ValeRefeicaoPrepaid) + return "vale_refeicao_prepaid"; + + if (value == TypeEnum.VegasCard) + return "vegas_card"; + + if (value == TypeEnum.VegasCardCredit) + return "vegas_card_credit"; + + if (value == TypeEnum.VegasCardDebit) + return "vegas_card_debit"; + + if (value == TypeEnum.VeroCard) + return "vero_card"; + + if (value == TypeEnum.VeroCardCredit) + return "vero_card_credit"; + + if (value == TypeEnum.VeroCardDebit) + return "vero_card_debit"; + + if (value == TypeEnum.VeroCardPrepaid) + return "vero_card_prepaid"; + + if (value == TypeEnum.Vipps) + return "vipps"; + + if (value == TypeEnum.Visa) + return "visa"; + + if (value == TypeEnum.Visadebit) + return "visadebit"; + + if (value == TypeEnum.Vpay) + return "vpay"; + + if (value == TypeEnum.Wechatpay) + return "wechatpay"; + + if (value == TypeEnum.WechatpayPos) + return "wechatpay_pos"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The sales channel. Required if the merchant account does not have a sales channel. When you provide this field, it overrides the default sales channel set on the merchant account. Possible values: **eCommerce**, **pos**, **contAuth**, and **moto**. + /// + /// The sales channel. Required if the merchant account does not have a sales channel. When you provide this field, it overrides the default sales channel set on the merchant account. Possible values: **eCommerce**, **pos**, **contAuth**, and **moto**. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.ECommerce - eCommerce + /// + public static readonly ShopperInteractionEnum ECommerce = new("eCommerce"); + + /// + /// ShopperInteractionEnum.Pos - pos + /// + public static readonly ShopperInteractionEnum Pos = new("pos"); + + /// + /// ShopperInteractionEnum.Moto - moto + /// + public static readonly ShopperInteractionEnum Moto = new("moto"); + + /// + /// ShopperInteractionEnum.ContAuth - contAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("contAuth"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "eCommerce" => ShopperInteractionEnum.ECommerce, + "pos" => ShopperInteractionEnum.Pos, + "moto" => ShopperInteractionEnum.Moto, + "contAuth" => ShopperInteractionEnum.ContAuth, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.ECommerce) + return "eCommerce"; + + if (value == ShopperInteractionEnum.Pos) + return "pos"; + + if (value == ShopperInteractionEnum.Moto) + return "moto"; + + if (value == ShopperInteractionEnum.ContAuth) + return "contAuth"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// The sales channel. Required if the merchant account does not have a sales channel. When you provide this field, it overrides the default sales channel set on the merchant account. Possible values: **eCommerce**, **pos**, **contAuth**, and **moto**. + /// + /// The sales channel. Required if the merchant account does not have a sales channel. When you provide this field, it overrides the default sales channel set on the merchant account. Possible values: **eCommerce**, **pos**, **contAuth**, and **moto**. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccelOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accel")] + public AccelInfo? Accel { get { return this._AccelOption; } set { this._AccelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AffirmOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("affirm")] + public AffirmInfo? Affirm { get { return this._AffirmOption; } set { this._AffirmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AfterpayTouchOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("afterpayTouch")] + public AfterpayTouchInfo? AfterpayTouch { get { return this._AfterpayTouchOption; } set { this._AfterpayTouchOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AlipayPlusOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("alipayPlus")] + public AlipayPlusInfo? AlipayPlus { get { return this._AlipayPlusOption; } set { this._AlipayPlusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmexOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amex")] + public AmexInfo? Amex { get { return this._AmexOption; } set { this._AmexOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplePayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applePay")] + public ApplePayInfo? ApplePay { get { return this._ApplePayOption; } set { this._ApplePayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BcmcOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bcmc")] + public BcmcInfo? Bcmc { get { return this._BcmcOption; } set { this._BcmcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BusinessLineIdOption { get; private set; } + + /// + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + /// + /// The unique identifier of the business line. Required if you are a [platform model](https://docs.adyen.com/platforms). + [JsonPropertyName("businessLineId")] + public string? BusinessLineId { get { return this._BusinessLineIdOption; } set { this._BusinessLineIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CartesBancairesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cartesBancaires")] + public CartesBancairesInfo? CartesBancaires { get { return this._CartesBancairesOption; } set { this._CartesBancairesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ClearpayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("clearpay")] + public ClearpayInfo? Clearpay { get { return this._ClearpayOption; } set { this._ClearpayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CountriesOption { get; private set; } + + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + [JsonPropertyName("countries")] + public List? Countries { get { return this._CountriesOption; } set { this._CountriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cup")] + public GenericPmWithTdiInfo? Cup { get { return this._CupOption; } set { this._CupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CurrenciesOption { get; private set; } + + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + [JsonPropertyName("currencies")] + public List? Currencies { get { return this._CurrenciesOption; } set { this._CurrenciesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CustomRoutingFlagsOption { get; private set; } + + /// + /// The list of custom routing flags to route payment to the intended acquirer. + /// + /// The list of custom routing flags to route payment to the intended acquirer. + [JsonPropertyName("customRoutingFlags")] + public List? CustomRoutingFlags { get { return this._CustomRoutingFlagsOption; } set { this._CustomRoutingFlagsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DinersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("diners")] + public DinersInfo? Diners { get { return this._DinersOption; } set { this._DinersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DiscoverOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("discover")] + public GenericPmWithTdiInfo? Discover { get { return this._DiscoverOption; } set { this._DiscoverOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftDirectdebitCAOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eft_directdebit_CA")] + public GenericPmWithTdiInfo? EftDirectdebitCA { get { return this._EftDirectdebitCAOption; } set { this._EftDirectdebitCAOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftposAustraliaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eftpos_australia")] + public GenericPmWithTdiInfo? EftposAustralia { get { return this._EftposAustraliaOption; } set { this._EftposAustraliaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GirocardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("girocard")] + public GenericPmWithTdiInfo? Girocard { get { return this._GirocardOption; } set { this._GirocardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GooglePayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("googlePay")] + public GooglePayInfo? GooglePay { get { return this._GooglePayOption; } set { this._GooglePayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdealOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ideal")] + public GenericPmWithTdiInfo? Ideal { get { return this._IdealOption; } set { this._IdealOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InteracCardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interac_card")] + public GenericPmWithTdiInfo? InteracCard { get { return this._InteracCardOption; } set { this._InteracCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JcbOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("jcb")] + public JCBInfo? Jcb { get { return this._JcbOption; } set { this._JcbOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KlarnaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("klarna")] + public KlarnaInfo? Klarna { get { return this._KlarnaOption; } set { this._KlarnaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro")] + public GenericPmWithTdiInfo? Maestro { get { return this._MaestroOption; } set { this._MaestroOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroUsaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro_usa")] + public GenericPmWithTdiInfo? MaestroUsa { get { return this._MaestroUsaOption; } set { this._MaestroUsaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mc")] + public GenericPmWithTdiInfo? Mc { get { return this._McOption; } set { this._McOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MealVoucherFROption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mealVoucher_FR")] + public MealVoucherFRInfo? MealVoucherFR { get { return this._MealVoucherFROption; } set { this._MealVoucherFROption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NyceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nyce")] + public NyceInfo? Nyce { get { return this._NyceOption; } set { this._NyceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaybybankPlaidOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paybybank_plaid")] + public PayByBankPlaidInfo? PaybybankPlaid { get { return this._PaybybankPlaidOption; } set { this._PaybybankPlaidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payme")] + public PayMeInfo? Payme { get { return this._PaymeOption; } set { this._PaymeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaypalOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paypal")] + public PayPalInfo? Paypal { get { return this._PaypalOption; } set { this._PaypalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaytoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payto")] + public PayToInfo? Payto { get { return this._PaytoOption; } set { this._PaytoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PulseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pulse")] + public PulseInfo? Pulse { get { return this._PulseOption; } set { this._PulseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + /// + /// Your reference for the payment method. Supported characters a-z, A-Z, 0-9. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sepadirectdebit")] + public SepaDirectDebitInfo? Sepadirectdebit { get { return this._SepadirectdebitOption; } set { this._SepadirectdebitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SodexoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sodexo")] + public SodexoInfo? Sodexo { get { return this._SodexoOption; } set { this._SodexoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SofortOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sofort")] + public SofortInfo? Sofort { get { return this._SofortOption; } set { this._SofortOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StarOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("star")] + public StarInfo? Star { get { return this._StarOption; } set { this._StarOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _StoreIdsOption { get; private set; } + + /// + /// The unique identifier of the store for which to configure the payment method, if any. + /// + /// The unique identifier of the store for which to configure the payment method, if any. + [JsonPropertyName("storeIds")] + public List? StoreIds { get { return this._StoreIdsOption; } set { this._StoreIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SwishOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("swish")] + public SwishInfo? Swish { get { return this._SwishOption; } set { this._SwishOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TicketOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ticket")] + public TicketInfo? Ticket { get { return this._TicketOption; } set { this._TicketOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TwintOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("twint")] + public TwintInfo? Twint { get { return this._TwintOption; } set { this._TwintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VippsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("vipps")] + public VippsInfo? Vipps { get { return this._VippsOption; } set { this._VippsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("visa")] + public GenericPmWithTdiInfo? Visa { get { return this._VisaOption; } set { this._VisaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WechatpayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wechatpay")] + public WeChatPayInfo? Wechatpay { get { return this._WechatpayOption; } set { this._WechatpayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WechatpayPosOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wechatpay_pos")] + public WeChatPayPosInfo? WechatpayPos { get { return this._WechatpayPosOption; } set { this._WechatpayPosOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodSetupInfo {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Accel: ").Append(Accel).Append("\n"); + sb.Append(" Affirm: ").Append(Affirm).Append("\n"); + sb.Append(" AfterpayTouch: ").Append(AfterpayTouch).Append("\n"); + sb.Append(" AlipayPlus: ").Append(AlipayPlus).Append("\n"); + sb.Append(" Amex: ").Append(Amex).Append("\n"); + sb.Append(" ApplePay: ").Append(ApplePay).Append("\n"); + sb.Append(" Bcmc: ").Append(Bcmc).Append("\n"); + sb.Append(" BusinessLineId: ").Append(BusinessLineId).Append("\n"); + sb.Append(" CartesBancaires: ").Append(CartesBancaires).Append("\n"); + sb.Append(" Clearpay: ").Append(Clearpay).Append("\n"); + sb.Append(" Countries: ").Append(Countries).Append("\n"); + sb.Append(" Cup: ").Append(Cup).Append("\n"); + sb.Append(" Currencies: ").Append(Currencies).Append("\n"); + sb.Append(" CustomRoutingFlags: ").Append(CustomRoutingFlags).Append("\n"); + sb.Append(" Diners: ").Append(Diners).Append("\n"); + sb.Append(" Discover: ").Append(Discover).Append("\n"); + sb.Append(" EftDirectdebitCA: ").Append(EftDirectdebitCA).Append("\n"); + sb.Append(" EftposAustralia: ").Append(EftposAustralia).Append("\n"); + sb.Append(" Girocard: ").Append(Girocard).Append("\n"); + sb.Append(" GooglePay: ").Append(GooglePay).Append("\n"); + sb.Append(" Ideal: ").Append(Ideal).Append("\n"); + sb.Append(" InteracCard: ").Append(InteracCard).Append("\n"); + sb.Append(" Jcb: ").Append(Jcb).Append("\n"); + sb.Append(" Klarna: ").Append(Klarna).Append("\n"); + sb.Append(" Maestro: ").Append(Maestro).Append("\n"); + sb.Append(" MaestroUsa: ").Append(MaestroUsa).Append("\n"); + sb.Append(" Mc: ").Append(Mc).Append("\n"); + sb.Append(" MealVoucherFR: ").Append(MealVoucherFR).Append("\n"); + sb.Append(" Nyce: ").Append(Nyce).Append("\n"); + sb.Append(" PaybybankPlaid: ").Append(PaybybankPlaid).Append("\n"); + sb.Append(" Payme: ").Append(Payme).Append("\n"); + sb.Append(" Paypal: ").Append(Paypal).Append("\n"); + sb.Append(" Payto: ").Append(Payto).Append("\n"); + sb.Append(" Pulse: ").Append(Pulse).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Sepadirectdebit: ").Append(Sepadirectdebit).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" Sodexo: ").Append(Sodexo).Append("\n"); + sb.Append(" Sofort: ").Append(Sofort).Append("\n"); + sb.Append(" Star: ").Append(Star).Append("\n"); + sb.Append(" StoreIds: ").Append(StoreIds).Append("\n"); + sb.Append(" Swish: ").Append(Swish).Append("\n"); + sb.Append(" Ticket: ").Append(Ticket).Append("\n"); + sb.Append(" Twint: ").Append(Twint).Append("\n"); + sb.Append(" Vipps: ").Append(Vipps).Append("\n"); + sb.Append(" Visa: ").Append(Visa).Append("\n"); + sb.Append(" Wechatpay: ").Append(Wechatpay).Append("\n"); + sb.Append(" WechatpayPos: ").Append(WechatpayPos).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodSetupInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodSetupInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option accel = default; + Option affirm = default; + Option afterpayTouch = default; + Option alipayPlus = default; + Option amex = default; + Option applePay = default; + Option bcmc = default; + Option businessLineId = default; + Option cartesBancaires = default; + Option clearpay = default; + Option?> countries = default; + Option cup = default; + Option?> currencies = default; + Option?> customRoutingFlags = default; + Option diners = default; + Option discover = default; + Option eftDirectdebitCA = default; + Option eftposAustralia = default; + Option girocard = default; + Option googlePay = default; + Option ideal = default; + Option interacCard = default; + Option jcb = default; + Option klarna = default; + Option maestro = default; + Option maestroUsa = default; + Option mc = default; + Option mealVoucherFR = default; + Option nyce = default; + Option paybybankPlaid = default; + Option payme = default; + Option paypal = default; + Option payto = default; + Option pulse = default; + Option reference = default; + Option sepadirectdebit = default; + Option shopperInteraction = default; + Option sodexo = default; + Option sofort = default; + Option star = default; + Option?> storeIds = default; + Option swish = default; + Option ticket = default; + Option twint = default; + Option vipps = default; + Option visa = default; + Option wechatpay = default; + Option wechatpayPos = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentMethodSetupInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "accel": + accel = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "affirm": + affirm = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "afterpayTouch": + afterpayTouch = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "alipayPlus": + alipayPlus = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amex": + amex = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applePay": + applePay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bcmc": + bcmc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "businessLineId": + businessLineId = new Option(utf8JsonReader.GetString()!); + break; + case "cartesBancaires": + cartesBancaires = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "clearpay": + clearpay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countries": + countries = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cup": + cup = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currencies": + currencies = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "customRoutingFlags": + customRoutingFlags = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "diners": + diners = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "discover": + discover = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eft_directdebit_CA": + eftDirectdebitCA = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eftpos_australia": + eftposAustralia = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "girocard": + girocard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "googlePay": + googlePay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ideal": + ideal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interac_card": + interacCard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "jcb": + jcb = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "klarna": + klarna = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro": + maestro = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro_usa": + maestroUsa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mc": + mc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mealVoucher_FR": + mealVoucherFR = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nyce": + nyce = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paybybank_plaid": + paybybankPlaid = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payme": + payme = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paypal": + paypal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payto": + payto = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pulse": + pulse = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit": + sepadirectdebit = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PaymentMethodSetupInfo.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "sodexo": + sodexo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sofort": + sofort = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "star": + star = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storeIds": + storeIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "swish": + swish = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ticket": + ticket = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "twint": + twint = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "vipps": + vipps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "visa": + visa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wechatpay": + wechatpay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wechatpay_pos": + wechatpayPos = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodSetupInfo.", nameof(type)); + + return new PaymentMethodSetupInfo(type.Value!.Value!, accel, affirm, afterpayTouch, alipayPlus, amex, applePay, bcmc, businessLineId, cartesBancaires, clearpay, countries, cup, currencies, customRoutingFlags, diners, discover, eftDirectdebitCA, eftposAustralia, girocard, googlePay, ideal, interacCard, jcb, klarna, maestro, maestroUsa, mc, mealVoucherFR, nyce, paybybankPlaid, payme, paypal, payto, pulse, reference, sepadirectdebit, shopperInteraction, sodexo, sofort, star, storeIds, swish, ticket, twint, vipps, visa, wechatpay, wechatpayPos); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodSetupInfo paymentMethodSetupInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodSetupInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodSetupInfo paymentMethodSetupInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodSetupInfo.Type != null) + { + string? typeRawValue = PaymentMethodSetupInfo.TypeEnum.ToJsonValue(paymentMethodSetupInfo.Type); + writer.WriteString("type", typeRawValue); + } + + if (paymentMethodSetupInfo._AccelOption.IsSet) + { + writer.WritePropertyName("accel"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Accel, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._AffirmOption.IsSet) + { + writer.WritePropertyName("affirm"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Affirm, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._AfterpayTouchOption.IsSet) + { + writer.WritePropertyName("afterpayTouch"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.AfterpayTouch, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._AlipayPlusOption.IsSet) + { + writer.WritePropertyName("alipayPlus"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.AlipayPlus, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._AmexOption.IsSet) + { + writer.WritePropertyName("amex"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Amex, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._ApplePayOption.IsSet) + { + writer.WritePropertyName("applePay"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.ApplePay, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._BcmcOption.IsSet) + { + writer.WritePropertyName("bcmc"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Bcmc, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._BusinessLineIdOption.IsSet) + if (paymentMethodSetupInfo.BusinessLineId != null) + writer.WriteString("businessLineId", paymentMethodSetupInfo.BusinessLineId); + + if (paymentMethodSetupInfo._CartesBancairesOption.IsSet) + { + writer.WritePropertyName("cartesBancaires"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.CartesBancaires, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._ClearpayOption.IsSet) + { + writer.WritePropertyName("clearpay"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Clearpay, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._CountriesOption.IsSet) + { + writer.WritePropertyName("countries"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Countries, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._CupOption.IsSet) + { + writer.WritePropertyName("cup"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Cup, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._CurrenciesOption.IsSet) + { + writer.WritePropertyName("currencies"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Currencies, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._CustomRoutingFlagsOption.IsSet) + { + writer.WritePropertyName("customRoutingFlags"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.CustomRoutingFlags, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._DinersOption.IsSet) + { + writer.WritePropertyName("diners"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Diners, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._DiscoverOption.IsSet) + { + writer.WritePropertyName("discover"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Discover, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._EftDirectdebitCAOption.IsSet) + { + writer.WritePropertyName("eft_directdebit_CA"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.EftDirectdebitCA, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._EftposAustraliaOption.IsSet) + { + writer.WritePropertyName("eftpos_australia"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.EftposAustralia, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._GirocardOption.IsSet) + { + writer.WritePropertyName("girocard"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Girocard, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._GooglePayOption.IsSet) + { + writer.WritePropertyName("googlePay"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.GooglePay, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._IdealOption.IsSet) + { + writer.WritePropertyName("ideal"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Ideal, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._InteracCardOption.IsSet) + { + writer.WritePropertyName("interac_card"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.InteracCard, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._JcbOption.IsSet) + { + writer.WritePropertyName("jcb"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Jcb, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._KlarnaOption.IsSet) + { + writer.WritePropertyName("klarna"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Klarna, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._MaestroOption.IsSet) + { + writer.WritePropertyName("maestro"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Maestro, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._MaestroUsaOption.IsSet) + { + writer.WritePropertyName("maestro_usa"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.MaestroUsa, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._McOption.IsSet) + { + writer.WritePropertyName("mc"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Mc, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._MealVoucherFROption.IsSet) + { + writer.WritePropertyName("mealVoucher_FR"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.MealVoucherFR, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._NyceOption.IsSet) + { + writer.WritePropertyName("nyce"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Nyce, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._PaybybankPlaidOption.IsSet) + { + writer.WritePropertyName("paybybank_plaid"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.PaybybankPlaid, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._PaymeOption.IsSet) + { + writer.WritePropertyName("payme"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Payme, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._PaypalOption.IsSet) + { + writer.WritePropertyName("paypal"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Paypal, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._PaytoOption.IsSet) + { + writer.WritePropertyName("payto"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Payto, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._PulseOption.IsSet) + { + writer.WritePropertyName("pulse"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Pulse, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._ReferenceOption.IsSet) + if (paymentMethodSetupInfo.Reference != null) + writer.WriteString("reference", paymentMethodSetupInfo.Reference); + + if (paymentMethodSetupInfo._SepadirectdebitOption.IsSet) + { + writer.WritePropertyName("sepadirectdebit"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Sepadirectdebit, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._ShopperInteractionOption.IsSet && paymentMethodSetupInfo.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PaymentMethodSetupInfo.ShopperInteractionEnum.ToJsonValue(paymentMethodSetupInfo._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (paymentMethodSetupInfo._SodexoOption.IsSet) + { + writer.WritePropertyName("sodexo"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Sodexo, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._SofortOption.IsSet) + { + writer.WritePropertyName("sofort"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Sofort, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._StarOption.IsSet) + { + writer.WritePropertyName("star"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Star, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._StoreIdsOption.IsSet) + { + writer.WritePropertyName("storeIds"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.StoreIds, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._SwishOption.IsSet) + { + writer.WritePropertyName("swish"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Swish, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._TicketOption.IsSet) + { + writer.WritePropertyName("ticket"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Ticket, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._TwintOption.IsSet) + { + writer.WritePropertyName("twint"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Twint, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._VippsOption.IsSet) + { + writer.WritePropertyName("vipps"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Vipps, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._VisaOption.IsSet) + { + writer.WritePropertyName("visa"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Visa, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._WechatpayOption.IsSet) + { + writer.WritePropertyName("wechatpay"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.Wechatpay, jsonSerializerOptions); + } + if (paymentMethodSetupInfo._WechatpayPosOption.IsSet) + { + writer.WritePropertyName("wechatpay_pos"); + JsonSerializer.Serialize(writer, paymentMethodSetupInfo.WechatpayPos, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/PayoutSettings.cs b/Adyen/Management/Models/PayoutSettings.cs new file mode 100644 index 000000000..182506472 --- /dev/null +++ b/Adyen/Management/Models/PayoutSettings.cs @@ -0,0 +1,553 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayoutSettings. + /// + public partial class PayoutSettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the payout setting. + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + /// Indicates if payouts to the bank account are allowed. This value is set automatically based on the status of the verification process. The value is: * **true** if `verificationStatus` is **valid**. * **false** for all other values. + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + /// Determines how long it takes for the funds to reach the bank account. Adyen pays out based on the [payout frequency](https://docs.adyen.com/account/getting-paid#payout-frequency). Depending on the currencies and banks involved in transferring the money, it may take up to three days for the payout funds to arrive in the bank account. Possible values: * **first**: same day. * **urgent**: the next day. * **normal**: between 1 and 3 days. + /// The status of the verification process for the bank account. Possible values: * **valid**: the verification was successful. * **pending**: the verification is in progress. * **invalid**: the information provided is not complete. * **rejected**: there are reasons to refuse working with this entity. + [JsonConstructor] + public PayoutSettings(string id, string transferInstrumentId, Option allowed = default, Option enabled = default, Option enabledFromDate = default, Option priority = default, Option verificationStatus = default) + { + Id = id; + TransferInstrumentId = transferInstrumentId; + _AllowedOption = allowed; + _EnabledOption = enabled; + _EnabledFromDateOption = enabledFromDate; + _PriorityOption = priority; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayoutSettings() + { + } + + partial void OnCreated(); + + /// + /// Determines how long it takes for the funds to reach the bank account. Adyen pays out based on the [payout frequency](https://docs.adyen.com/account/getting-paid#payout-frequency). Depending on the currencies and banks involved in transferring the money, it may take up to three days for the payout funds to arrive in the bank account. Possible values: * **first**: same day. * **urgent**: the next day. * **normal**: between 1 and 3 days. + /// + /// Determines how long it takes for the funds to reach the bank account. Adyen pays out based on the [payout frequency](https://docs.adyen.com/account/getting-paid#payout-frequency). Depending on the currencies and banks involved in transferring the money, it may take up to three days for the payout funds to arrive in the bank account. Possible values: * **first**: same day. * **urgent**: the next day. * **normal**: between 1 and 3 days. + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.First - first + /// + public static readonly PriorityEnum First = new("first"); + + /// + /// PriorityEnum.Normal - normal + /// + public static readonly PriorityEnum Normal = new("normal"); + + /// + /// PriorityEnum.Urgent - urgent + /// + public static readonly PriorityEnum Urgent = new("urgent"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "first" => PriorityEnum.First, + "normal" => PriorityEnum.Normal, + "urgent" => PriorityEnum.Urgent, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.First) + return "first"; + + if (value == PriorityEnum.Normal) + return "normal"; + + if (value == PriorityEnum.Urgent) + return "urgent"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// Determines how long it takes for the funds to reach the bank account. Adyen pays out based on the [payout frequency](https://docs.adyen.com/account/getting-paid#payout-frequency). Depending on the currencies and banks involved in transferring the money, it may take up to three days for the payout funds to arrive in the bank account. Possible values: * **first**: same day. * **urgent**: the next day. * **normal**: between 1 and 3 days. + /// + /// Determines how long it takes for the funds to reach the bank account. Adyen pays out based on the [payout frequency](https://docs.adyen.com/account/getting-paid#payout-frequency). Depending on the currencies and banks involved in transferring the money, it may take up to three days for the payout funds to arrive in the bank account. Possible values: * **first**: same day. * **urgent**: the next day. * **normal**: between 1 and 3 days. + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// The status of the verification process for the bank account. Possible values: * **valid**: the verification was successful. * **pending**: the verification is in progress. * **invalid**: the information provided is not complete. * **rejected**: there are reasons to refuse working with this entity. + /// + /// The status of the verification process for the bank account. Possible values: * **valid**: the verification was successful. * **pending**: the verification is in progress. * **invalid**: the information provided is not complete. * **rejected**: there are reasons to refuse working with this entity. + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "invalid" => VerificationStatusEnum.Invalid, + "pending" => VerificationStatusEnum.Pending, + "rejected" => VerificationStatusEnum.Rejected, + "valid" => VerificationStatusEnum.Valid, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// The status of the verification process for the bank account. Possible values: * **valid**: the verification was successful. * **pending**: the verification is in progress. * **invalid**: the information provided is not complete. * **rejected**: there are reasons to refuse working with this entity. + /// + /// The status of the verification process for the bank account. Possible values: * **valid**: the verification was successful. * **pending**: the verification is in progress. * **invalid**: the information provided is not complete. * **rejected**: there are reasons to refuse working with this entity. + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// The unique identifier of the payout setting. + /// + /// The unique identifier of the payout setting. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + [JsonPropertyName("transferInstrumentId")] + public string TransferInstrumentId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates if payouts to the bank account are allowed. This value is set automatically based on the status of the verification process. The value is: * **true** if `verificationStatus` is **valid**. * **false** for all other values. + /// + /// Indicates if payouts to the bank account are allowed. This value is set automatically based on the status of the verification process. The value is: * **true** if `verificationStatus` is **valid**. * **false** for all other values. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledFromDateOption { get; private set; } + + /// + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + /// + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + [JsonPropertyName("enabledFromDate")] + public string? EnabledFromDate { get { return this._EnabledFromDateOption; } set { this._EnabledFromDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayoutSettings {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" EnabledFromDate: ").Append(EnabledFromDate).Append("\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayoutSettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayoutSettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option transferInstrumentId = default; + Option allowed = default; + Option enabled = default; + Option enabledFromDate = default; + Option priority = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enabledFromDate": + enabledFromDate = new Option(utf8JsonReader.GetString()!); + break; + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(PayoutSettings.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(PayoutSettings.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class PayoutSettings.", nameof(id)); + + if (!transferInstrumentId.IsSet) + throw new ArgumentException("Property is required for class PayoutSettings.", nameof(transferInstrumentId)); + + return new PayoutSettings(id.Value!, transferInstrumentId.Value!, allowed, enabled, enabledFromDate, priority, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayoutSettings payoutSettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payoutSettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayoutSettings payoutSettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (payoutSettings.Id != null) + writer.WriteString("id", payoutSettings.Id); + + if (payoutSettings.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", payoutSettings.TransferInstrumentId); + + if (payoutSettings._AllowedOption.IsSet) + writer.WriteBoolean("allowed", payoutSettings._AllowedOption.Value!.Value); + + if (payoutSettings._EnabledOption.IsSet) + writer.WriteBoolean("enabled", payoutSettings._EnabledOption.Value!.Value); + + if (payoutSettings._EnabledFromDateOption.IsSet) + if (payoutSettings.EnabledFromDate != null) + writer.WriteString("enabledFromDate", payoutSettings.EnabledFromDate); + + if (payoutSettings._PriorityOption.IsSet && payoutSettings.Priority != null) + { + string? priorityRawValue = PayoutSettings.PriorityEnum.ToJsonValue(payoutSettings._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (payoutSettings._VerificationStatusOption.IsSet && payoutSettings.VerificationStatus != null) + { + string? verificationStatusRawValue = PayoutSettings.VerificationStatusEnum.ToJsonValue(payoutSettings._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/PayoutSettingsRequest.cs b/Adyen/Management/Models/PayoutSettingsRequest.cs new file mode 100644 index 000000000..bc069197f --- /dev/null +++ b/Adyen/Management/Models/PayoutSettingsRequest.cs @@ -0,0 +1,220 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayoutSettingsRequest. + /// + public partial class PayoutSettingsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + [JsonConstructor] + public PayoutSettingsRequest(string transferInstrumentId, Option enabled = default, Option enabledFromDate = default) + { + TransferInstrumentId = transferInstrumentId; + _EnabledOption = enabled; + _EnabledFromDateOption = enabledFromDate; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayoutSettingsRequest() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + /// + /// The unique identifier of the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the bank account. + [JsonPropertyName("transferInstrumentId")] + public string TransferInstrumentId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledFromDateOption { get; private set; } + + /// + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + /// + /// The date when Adyen starts paying out to this bank account. Format: [ISO 8601](https://www.w3.org/TR/NOTE-datetime), for example, **2019-11-23T12:25:28Z** or **2020-05-27T20:25:28+08:00**. If not specified, the `enabled` field indicates if payouts are enabled for this bank account. If a date is specified and: * `enabled`: **true**, payouts are enabled starting the specified date. * `enabled`: **false**, payouts are disabled until the specified date. On the specified date, `enabled` changes to **true** and this field is reset to **null**. + [JsonPropertyName("enabledFromDate")] + public string? EnabledFromDate { get { return this._EnabledFromDateOption; } set { this._EnabledFromDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayoutSettingsRequest {\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" EnabledFromDate: ").Append(EnabledFromDate).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayoutSettingsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayoutSettingsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option transferInstrumentId = default; + Option enabled = default; + Option enabledFromDate = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enabledFromDate": + enabledFromDate = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!transferInstrumentId.IsSet) + throw new ArgumentException("Property is required for class PayoutSettingsRequest.", nameof(transferInstrumentId)); + + return new PayoutSettingsRequest(transferInstrumentId.Value!, enabled, enabledFromDate); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayoutSettingsRequest payoutSettingsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payoutSettingsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayoutSettingsRequest payoutSettingsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (payoutSettingsRequest.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", payoutSettingsRequest.TransferInstrumentId); + + if (payoutSettingsRequest._EnabledOption.IsSet) + writer.WriteBoolean("enabled", payoutSettingsRequest._EnabledOption.Value!.Value); + + if (payoutSettingsRequest._EnabledFromDateOption.IsSet) + if (payoutSettingsRequest.EnabledFromDate != null) + writer.WriteString("enabledFromDate", payoutSettingsRequest.EnabledFromDate); + } + } +} diff --git a/Adyen/Management/Models/PayoutSettingsResponse.cs b/Adyen/Management/Models/PayoutSettingsResponse.cs new file mode 100644 index 000000000..0c1b0d1c9 --- /dev/null +++ b/Adyen/Management/Models/PayoutSettingsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PayoutSettingsResponse. + /// + public partial class PayoutSettingsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of payout accounts. + [JsonConstructor] + public PayoutSettingsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayoutSettingsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The list of payout accounts. + /// + /// The list of payout accounts. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayoutSettingsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayoutSettingsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayoutSettingsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new PayoutSettingsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayoutSettingsResponse payoutSettingsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payoutSettingsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayoutSettingsResponse payoutSettingsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (payoutSettingsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, payoutSettingsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Profile.cs b/Adyen/Management/Models/Profile.cs new file mode 100644 index 000000000..b06e8ecad --- /dev/null +++ b/Adyen/Management/Models/Profile.cs @@ -0,0 +1,602 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Profile. + /// + public partial class Profile : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of Wi-Fi network. Possible values: **wpa-psk**, **wpa2-psk**, **wpa-eap**, **wpa2-eap**. + /// Use **infra** for infrastructure-based networks. This applies to most networks. Use **adhoc** only if the communication is p2p-based between base stations. + /// The name of the wireless network. + /// The type of encryption. Possible values: **auto**, **ccmp** (recommended), **tkip** + /// Indicates whether to automatically select the best authentication method available. Does not work on older terminal models. + /// The channel number of the Wi-Fi network. The recommended setting is **0** for automatic channel selection. + /// Indicates whether this is your preferred wireless network. If **true**, the terminal will try connecting to this network first. + /// Specifies the server domain name for EAP-TLS and EAP-PEAP WiFi profiles on Android 11 and above. + /// For `authType` **wpa-eap** or **wpa2-eap**. Possible values: **tls**, **peap**, **leap**, **fast** + /// eapCaCert + /// eapClientCert + /// eapClientKey + /// For `eap` **tls**. The password of the RSA key file, if that file is password-protected. + /// For `authType` **wpa-eap** or **wpa2-eap**. The EAP-PEAP username from your MS-CHAP account. Must match the configuration of your RADIUS server. + /// eapIntermediateCert + /// For `eap` **peap**. The EAP-PEAP password from your MS-CHAP account. Must match the configuration of your RADIUS server. + /// Indicates if the network doesn't broadcast its SSID. Mandatory for Android terminals, because these terminals rely on this setting to be able to connect to any network. + /// Your name for the Wi-Fi profile. + /// For `authType` **wpa-psk or **wpa2-psk**. The password to the wireless network. + [JsonConstructor] + public Profile(string authType, string bssType, string ssid, string wsec, Option autoWifi = default, Option channel = default, Option defaultProfile = default, Option domainSuffix = default, Option eap = default, Option eapCaCert = default, Option eapClientCert = default, Option eapClientKey = default, Option eapClientPwd = default, Option eapIdentity = default, Option eapIntermediateCert = default, Option eapPwd = default, Option hiddenSsid = default, Option name = default, Option psk = default) + { + AuthType = authType; + BssType = bssType; + Ssid = ssid; + Wsec = wsec; + _AutoWifiOption = autoWifi; + _ChannelOption = channel; + _DefaultProfileOption = defaultProfile; + _DomainSuffixOption = domainSuffix; + _EapOption = eap; + _EapCaCertOption = eapCaCert; + _EapClientCertOption = eapClientCert; + _EapClientKeyOption = eapClientKey; + _EapClientPwdOption = eapClientPwd; + _EapIdentityOption = eapIdentity; + _EapIntermediateCertOption = eapIntermediateCert; + _EapPwdOption = eapPwd; + _HiddenSsidOption = hiddenSsid; + _NameOption = name; + _PskOption = psk; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Profile() + { + } + + partial void OnCreated(); + + /// + /// The type of Wi-Fi network. Possible values: **wpa-psk**, **wpa2-psk**, **wpa-eap**, **wpa2-eap**. + /// + /// The type of Wi-Fi network. Possible values: **wpa-psk**, **wpa2-psk**, **wpa-eap**, **wpa2-eap**. + [JsonPropertyName("authType")] + public string AuthType { get; set; } + + /// + /// Use **infra** for infrastructure-based networks. This applies to most networks. Use **adhoc** only if the communication is p2p-based between base stations. + /// + /// Use **infra** for infrastructure-based networks. This applies to most networks. Use **adhoc** only if the communication is p2p-based between base stations. + [JsonPropertyName("bssType")] + public string BssType { get; set; } + + /// + /// The name of the wireless network. + /// + /// The name of the wireless network. + [JsonPropertyName("ssid")] + public string Ssid { get; set; } + + /// + /// The type of encryption. Possible values: **auto**, **ccmp** (recommended), **tkip** + /// + /// The type of encryption. Possible values: **auto**, **ccmp** (recommended), **tkip** + [JsonPropertyName("wsec")] + public string Wsec { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AutoWifiOption { get; private set; } + + /// + /// Indicates whether to automatically select the best authentication method available. Does not work on older terminal models. + /// + /// Indicates whether to automatically select the best authentication method available. Does not work on older terminal models. + [JsonPropertyName("autoWifi")] + public bool? AutoWifi { get { return this._AutoWifiOption; } set { this._AutoWifiOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChannelOption { get; private set; } + + /// + /// The channel number of the Wi-Fi network. The recommended setting is **0** for automatic channel selection. + /// + /// The channel number of the Wi-Fi network. The recommended setting is **0** for automatic channel selection. + [JsonPropertyName("channel")] + public int? Channel { get { return this._ChannelOption; } set { this._ChannelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DefaultProfileOption { get; private set; } + + /// + /// Indicates whether this is your preferred wireless network. If **true**, the terminal will try connecting to this network first. + /// + /// Indicates whether this is your preferred wireless network. If **true**, the terminal will try connecting to this network first. + [JsonPropertyName("defaultProfile")] + public bool? DefaultProfile { get { return this._DefaultProfileOption; } set { this._DefaultProfileOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomainSuffixOption { get; private set; } + + /// + /// Specifies the server domain name for EAP-TLS and EAP-PEAP WiFi profiles on Android 11 and above. + /// + /// Specifies the server domain name for EAP-TLS and EAP-PEAP WiFi profiles on Android 11 and above. + [JsonPropertyName("domainSuffix")] + public string? DomainSuffix { get { return this._DomainSuffixOption; } set { this._DomainSuffixOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapOption { get; private set; } + + /// + /// For `authType` **wpa-eap** or **wpa2-eap**. Possible values: **tls**, **peap**, **leap**, **fast** + /// + /// For `authType` **wpa-eap** or **wpa2-eap**. Possible values: **tls**, **peap**, **leap**, **fast** + [JsonPropertyName("eap")] + public string? Eap { get { return this._EapOption; } set { this._EapOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapCaCertOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eapCaCert")] + public File? EapCaCert { get { return this._EapCaCertOption; } set { this._EapCaCertOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapClientCertOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eapClientCert")] + public File? EapClientCert { get { return this._EapClientCertOption; } set { this._EapClientCertOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapClientKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eapClientKey")] + public File? EapClientKey { get { return this._EapClientKeyOption; } set { this._EapClientKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapClientPwdOption { get; private set; } + + /// + /// For `eap` **tls**. The password of the RSA key file, if that file is password-protected. + /// + /// For `eap` **tls**. The password of the RSA key file, if that file is password-protected. + [JsonPropertyName("eapClientPwd")] + public string? EapClientPwd { get { return this._EapClientPwdOption; } set { this._EapClientPwdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapIdentityOption { get; private set; } + + /// + /// For `authType` **wpa-eap** or **wpa2-eap**. The EAP-PEAP username from your MS-CHAP account. Must match the configuration of your RADIUS server. + /// + /// For `authType` **wpa-eap** or **wpa2-eap**. The EAP-PEAP username from your MS-CHAP account. Must match the configuration of your RADIUS server. + [JsonPropertyName("eapIdentity")] + public string? EapIdentity { get { return this._EapIdentityOption; } set { this._EapIdentityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapIntermediateCertOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eapIntermediateCert")] + public File? EapIntermediateCert { get { return this._EapIntermediateCertOption; } set { this._EapIntermediateCertOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EapPwdOption { get; private set; } + + /// + /// For `eap` **peap**. The EAP-PEAP password from your MS-CHAP account. Must match the configuration of your RADIUS server. + /// + /// For `eap` **peap**. The EAP-PEAP password from your MS-CHAP account. Must match the configuration of your RADIUS server. + [JsonPropertyName("eapPwd")] + public string? EapPwd { get { return this._EapPwdOption; } set { this._EapPwdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HiddenSsidOption { get; private set; } + + /// + /// Indicates if the network doesn't broadcast its SSID. Mandatory for Android terminals, because these terminals rely on this setting to be able to connect to any network. + /// + /// Indicates if the network doesn't broadcast its SSID. Mandatory for Android terminals, because these terminals rely on this setting to be able to connect to any network. + [JsonPropertyName("hiddenSsid")] + public bool? HiddenSsid { get { return this._HiddenSsidOption; } set { this._HiddenSsidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Your name for the Wi-Fi profile. + /// + /// Your name for the Wi-Fi profile. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PskOption { get; private set; } + + /// + /// For `authType` **wpa-psk or **wpa2-psk**. The password to the wireless network. + /// + /// For `authType` **wpa-psk or **wpa2-psk**. The password to the wireless network. + [JsonPropertyName("psk")] + public string? Psk { get { return this._PskOption; } set { this._PskOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Profile {\n"); + sb.Append(" AuthType: ").Append(AuthType).Append("\n"); + sb.Append(" BssType: ").Append(BssType).Append("\n"); + sb.Append(" Ssid: ").Append(Ssid).Append("\n"); + sb.Append(" Wsec: ").Append(Wsec).Append("\n"); + sb.Append(" AutoWifi: ").Append(AutoWifi).Append("\n"); + sb.Append(" Channel: ").Append(Channel).Append("\n"); + sb.Append(" DefaultProfile: ").Append(DefaultProfile).Append("\n"); + sb.Append(" DomainSuffix: ").Append(DomainSuffix).Append("\n"); + sb.Append(" Eap: ").Append(Eap).Append("\n"); + sb.Append(" EapCaCert: ").Append(EapCaCert).Append("\n"); + sb.Append(" EapClientCert: ").Append(EapClientCert).Append("\n"); + sb.Append(" EapClientKey: ").Append(EapClientKey).Append("\n"); + sb.Append(" EapClientPwd: ").Append(EapClientPwd).Append("\n"); + sb.Append(" EapIdentity: ").Append(EapIdentity).Append("\n"); + sb.Append(" EapIntermediateCert: ").Append(EapIntermediateCert).Append("\n"); + sb.Append(" EapPwd: ").Append(EapPwd).Append("\n"); + sb.Append(" HiddenSsid: ").Append(HiddenSsid).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Psk: ").Append(Psk).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProfileJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Profile Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authType = default; + Option bssType = default; + Option ssid = default; + Option wsec = default; + Option autoWifi = default; + Option channel = default; + Option defaultProfile = default; + Option domainSuffix = default; + Option eap = default; + Option eapCaCert = default; + Option eapClientCert = default; + Option eapClientKey = default; + Option eapClientPwd = default; + Option eapIdentity = default; + Option eapIntermediateCert = default; + Option eapPwd = default; + Option hiddenSsid = default; + Option name = default; + Option psk = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authType": + authType = new Option(utf8JsonReader.GetString()!); + break; + case "bssType": + bssType = new Option(utf8JsonReader.GetString()!); + break; + case "ssid": + ssid = new Option(utf8JsonReader.GetString()!); + break; + case "wsec": + wsec = new Option(utf8JsonReader.GetString()!); + break; + case "autoWifi": + autoWifi = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "channel": + channel = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "defaultProfile": + defaultProfile = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "domainSuffix": + domainSuffix = new Option(utf8JsonReader.GetString()!); + break; + case "eap": + eap = new Option(utf8JsonReader.GetString()!); + break; + case "eapCaCert": + eapCaCert = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eapClientCert": + eapClientCert = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eapClientKey": + eapClientKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eapClientPwd": + eapClientPwd = new Option(utf8JsonReader.GetString()!); + break; + case "eapIdentity": + eapIdentity = new Option(utf8JsonReader.GetString()!); + break; + case "eapIntermediateCert": + eapIntermediateCert = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eapPwd": + eapPwd = new Option(utf8JsonReader.GetString()!); + break; + case "hiddenSsid": + hiddenSsid = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "psk": + psk = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!authType.IsSet) + throw new ArgumentException("Property is required for class Profile.", nameof(authType)); + + if (!bssType.IsSet) + throw new ArgumentException("Property is required for class Profile.", nameof(bssType)); + + if (!ssid.IsSet) + throw new ArgumentException("Property is required for class Profile.", nameof(ssid)); + + if (!wsec.IsSet) + throw new ArgumentException("Property is required for class Profile.", nameof(wsec)); + + return new Profile(authType.Value!, bssType.Value!, ssid.Value!, wsec.Value!, autoWifi, channel, defaultProfile, domainSuffix, eap, eapCaCert, eapClientCert, eapClientKey, eapClientPwd, eapIdentity, eapIntermediateCert, eapPwd, hiddenSsid, name, psk); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Profile profile, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, profile, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Profile profile, JsonSerializerOptions jsonSerializerOptions) + { + + if (profile.AuthType != null) + writer.WriteString("authType", profile.AuthType); + + if (profile.BssType != null) + writer.WriteString("bssType", profile.BssType); + + if (profile.Ssid != null) + writer.WriteString("ssid", profile.Ssid); + + if (profile.Wsec != null) + writer.WriteString("wsec", profile.Wsec); + + if (profile._AutoWifiOption.IsSet) + writer.WriteBoolean("autoWifi", profile._AutoWifiOption.Value!.Value); + + if (profile._ChannelOption.IsSet) + writer.WriteNumber("channel", profile._ChannelOption.Value!.Value); + + if (profile._DefaultProfileOption.IsSet) + writer.WriteBoolean("defaultProfile", profile._DefaultProfileOption.Value!.Value); + + if (profile._DomainSuffixOption.IsSet) + if (profile.DomainSuffix != null) + writer.WriteString("domainSuffix", profile.DomainSuffix); + + if (profile._EapOption.IsSet) + if (profile.Eap != null) + writer.WriteString("eap", profile.Eap); + + if (profile._EapCaCertOption.IsSet) + { + writer.WritePropertyName("eapCaCert"); + JsonSerializer.Serialize(writer, profile.EapCaCert, jsonSerializerOptions); + } + if (profile._EapClientCertOption.IsSet) + { + writer.WritePropertyName("eapClientCert"); + JsonSerializer.Serialize(writer, profile.EapClientCert, jsonSerializerOptions); + } + if (profile._EapClientKeyOption.IsSet) + { + writer.WritePropertyName("eapClientKey"); + JsonSerializer.Serialize(writer, profile.EapClientKey, jsonSerializerOptions); + } + if (profile._EapClientPwdOption.IsSet) + if (profile.EapClientPwd != null) + writer.WriteString("eapClientPwd", profile.EapClientPwd); + + if (profile._EapIdentityOption.IsSet) + if (profile.EapIdentity != null) + writer.WriteString("eapIdentity", profile.EapIdentity); + + if (profile._EapIntermediateCertOption.IsSet) + { + writer.WritePropertyName("eapIntermediateCert"); + JsonSerializer.Serialize(writer, profile.EapIntermediateCert, jsonSerializerOptions); + } + if (profile._EapPwdOption.IsSet) + if (profile.EapPwd != null) + writer.WriteString("eapPwd", profile.EapPwd); + + if (profile._HiddenSsidOption.IsSet) + writer.WriteBoolean("hiddenSsid", profile._HiddenSsidOption.Value!.Value); + + if (profile._NameOption.IsSet) + if (profile.Name != null) + writer.WriteString("name", profile.Name); + + if (profile._PskOption.IsSet) + if (profile.Psk != null) + writer.WriteString("psk", profile.Psk); + } + } +} diff --git a/Adyen/Management/Models/PulseInfo.cs b/Adyen/Management/Models/PulseInfo.cs new file mode 100644 index 000000000..79a9bb277 --- /dev/null +++ b/Adyen/Management/Models/PulseInfo.cs @@ -0,0 +1,313 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// PulseInfo. + /// + public partial class PulseInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// transactionDescription + [JsonConstructor] + public PulseInfo(ProcessingTypeEnum processingType, Option transactionDescription = default) + { + ProcessingType = processingType; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PulseInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.Billpay - billpay + /// + public static readonly ProcessingTypeEnum Billpay = new("billpay"); + + /// + /// ProcessingTypeEnum.Ecom - ecom + /// + public static readonly ProcessingTypeEnum Ecom = new("ecom"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "billpay" => ProcessingTypeEnum.Billpay, + "ecom" => ProcessingTypeEnum.Ecom, + "pos" => ProcessingTypeEnum.Pos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.Billpay) + return "billpay"; + + if (value == ProcessingTypeEnum.Ecom) + return "ecom"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum ProcessingType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PulseInfo {\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PulseInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PulseInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option processingType = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(PulseInfo.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!processingType.IsSet) + throw new ArgumentException("Property is required for class PulseInfo.", nameof(processingType)); + + return new PulseInfo(processingType.Value!.Value!, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PulseInfo pulseInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pulseInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PulseInfo pulseInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (pulseInfo.ProcessingType != null) + { + string? processingTypeRawValue = PulseInfo.ProcessingTypeEnum.ToJsonValue(pulseInfo.ProcessingType); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (pulseInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, pulseInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ReceiptOptions.cs b/Adyen/Management/Models/ReceiptOptions.cs new file mode 100644 index 000000000..8f23d4998 --- /dev/null +++ b/Adyen/Management/Models/ReceiptOptions.cs @@ -0,0 +1,232 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ReceiptOptions. + /// + public partial class ReceiptOptions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The receipt logo converted to a Base64-encoded string. The image must be a .bmp file of < 256 KB, dimensions 240 (H) x 384 (W) px. + /// Indicates whether a screen appears asking if you want to print the shopper receipt. + /// Data to print on the receipt as a QR code. This can include static text and the following variables: - `${merchantreference}`: the merchant reference of the transaction. - `${pspreference}`: the PSP reference of the transaction. For example, **http://www.example.com/order/${pspreference}/${merchantreference}**. + [JsonConstructor] + public ReceiptOptions(Option logo = default, Option promptBeforePrinting = default, Option qrCodeData = default) + { + _LogoOption = logo; + _PromptBeforePrintingOption = promptBeforePrinting; + _QrCodeDataOption = qrCodeData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReceiptOptions() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LogoOption { get; private set; } + + /// + /// The receipt logo converted to a Base64-encoded string. The image must be a .bmp file of < 256 KB, dimensions 240 (H) x 384 (W) px. + /// + /// The receipt logo converted to a Base64-encoded string. The image must be a .bmp file of < 256 KB, dimensions 240 (H) x 384 (W) px. + [JsonPropertyName("logo")] + public string? Logo { get { return this._LogoOption; } set { this._LogoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PromptBeforePrintingOption { get; private set; } + + /// + /// Indicates whether a screen appears asking if you want to print the shopper receipt. + /// + /// Indicates whether a screen appears asking if you want to print the shopper receipt. + [JsonPropertyName("promptBeforePrinting")] + public bool? PromptBeforePrinting { get { return this._PromptBeforePrintingOption; } set { this._PromptBeforePrintingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _QrCodeDataOption { get; private set; } + + /// + /// Data to print on the receipt as a QR code. This can include static text and the following variables: - `${merchantreference}`: the merchant reference of the transaction. - `${pspreference}`: the PSP reference of the transaction. For example, **http://www.example.com/order/${pspreference}/${merchantreference}**. + /// + /// Data to print on the receipt as a QR code. This can include static text and the following variables: - `${merchantreference}`: the merchant reference of the transaction. - `${pspreference}`: the PSP reference of the transaction. For example, **http://www.example.com/order/${pspreference}/${merchantreference}**. + [JsonPropertyName("qrCodeData")] + public string? QrCodeData { get { return this._QrCodeDataOption; } set { this._QrCodeDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReceiptOptions {\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append(" PromptBeforePrinting: ").Append(PromptBeforePrinting).Append("\n"); + sb.Append(" QrCodeData: ").Append(QrCodeData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Logo (string) maxLength + if (this.Logo != null && this.Logo.Length > 350000) + { + yield return new ValidationResult("Invalid value for Logo, length must be less than 350000.", new [] { "Logo" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReceiptOptionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReceiptOptions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option logo = default; + Option promptBeforePrinting = default; + Option qrCodeData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + case "promptBeforePrinting": + promptBeforePrinting = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "qrCodeData": + qrCodeData = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ReceiptOptions(logo, promptBeforePrinting, qrCodeData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReceiptOptions receiptOptions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, receiptOptions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReceiptOptions receiptOptions, JsonSerializerOptions jsonSerializerOptions) + { + + if (receiptOptions._LogoOption.IsSet) + if (receiptOptions.Logo != null) + writer.WriteString("logo", receiptOptions.Logo); + + if (receiptOptions._PromptBeforePrintingOption.IsSet) + writer.WriteBoolean("promptBeforePrinting", receiptOptions._PromptBeforePrintingOption.Value!.Value); + + if (receiptOptions._QrCodeDataOption.IsSet) + if (receiptOptions.QrCodeData != null) + writer.WriteString("qrCodeData", receiptOptions.QrCodeData); + } + } +} diff --git a/Adyen/Management/Models/ReceiptPrinting.cs b/Adyen/Management/Models/ReceiptPrinting.cs new file mode 100644 index 000000000..0150ab1f2 --- /dev/null +++ b/Adyen/Management/Models/ReceiptPrinting.cs @@ -0,0 +1,536 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ReceiptPrinting. + /// + public partial class ReceiptPrinting : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Print a merchant receipt when the payment is approved. + /// Print a merchant receipt when the transaction is cancelled. + /// Print a merchant receipt when capturing the payment is approved. + /// Print a merchant receipt when capturing the payment is refused. + /// Print a merchant receipt when the refund is approved. + /// Print a merchant receipt when the refund is refused. + /// Print a merchant receipt when the payment is refused. + /// Print a merchant receipt when a previous transaction is voided. + /// Print a shopper receipt when the payment is approved. + /// Print a shopper receipt when the transaction is cancelled. + /// Print a shopper receipt when capturing the payment is approved. + /// Print a shopper receipt when capturing the payment is refused. + /// Print a shopper receipt when the refund is approved. + /// Print a shopper receipt when the refund is refused. + /// Print a shopper receipt when the payment is refused. + /// Print a shopper receipt when a previous transaction is voided. + [JsonConstructor] + public ReceiptPrinting(Option merchantApproved = default, Option merchantCancelled = default, Option merchantCaptureApproved = default, Option merchantCaptureRefused = default, Option merchantRefundApproved = default, Option merchantRefundRefused = default, Option merchantRefused = default, Option merchantVoid = default, Option shopperApproved = default, Option shopperCancelled = default, Option shopperCaptureApproved = default, Option shopperCaptureRefused = default, Option shopperRefundApproved = default, Option shopperRefundRefused = default, Option shopperRefused = default, Option shopperVoid = default) + { + _MerchantApprovedOption = merchantApproved; + _MerchantCancelledOption = merchantCancelled; + _MerchantCaptureApprovedOption = merchantCaptureApproved; + _MerchantCaptureRefusedOption = merchantCaptureRefused; + _MerchantRefundApprovedOption = merchantRefundApproved; + _MerchantRefundRefusedOption = merchantRefundRefused; + _MerchantRefusedOption = merchantRefused; + _MerchantVoidOption = merchantVoid; + _ShopperApprovedOption = shopperApproved; + _ShopperCancelledOption = shopperCancelled; + _ShopperCaptureApprovedOption = shopperCaptureApproved; + _ShopperCaptureRefusedOption = shopperCaptureRefused; + _ShopperRefundApprovedOption = shopperRefundApproved; + _ShopperRefundRefusedOption = shopperRefundRefused; + _ShopperRefusedOption = shopperRefused; + _ShopperVoidOption = shopperVoid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReceiptPrinting() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantApprovedOption { get; private set; } + + /// + /// Print a merchant receipt when the payment is approved. + /// + /// Print a merchant receipt when the payment is approved. + [JsonPropertyName("merchantApproved")] + public bool? MerchantApproved { get { return this._MerchantApprovedOption; } set { this._MerchantApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantCancelledOption { get; private set; } + + /// + /// Print a merchant receipt when the transaction is cancelled. + /// + /// Print a merchant receipt when the transaction is cancelled. + [JsonPropertyName("merchantCancelled")] + public bool? MerchantCancelled { get { return this._MerchantCancelledOption; } set { this._MerchantCancelledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantCaptureApprovedOption { get; private set; } + + /// + /// Print a merchant receipt when capturing the payment is approved. + /// + /// Print a merchant receipt when capturing the payment is approved. + [JsonPropertyName("merchantCaptureApproved")] + public bool? MerchantCaptureApproved { get { return this._MerchantCaptureApprovedOption; } set { this._MerchantCaptureApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantCaptureRefusedOption { get; private set; } + + /// + /// Print a merchant receipt when capturing the payment is refused. + /// + /// Print a merchant receipt when capturing the payment is refused. + [JsonPropertyName("merchantCaptureRefused")] + public bool? MerchantCaptureRefused { get { return this._MerchantCaptureRefusedOption; } set { this._MerchantCaptureRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRefundApprovedOption { get; private set; } + + /// + /// Print a merchant receipt when the refund is approved. + /// + /// Print a merchant receipt when the refund is approved. + [JsonPropertyName("merchantRefundApproved")] + public bool? MerchantRefundApproved { get { return this._MerchantRefundApprovedOption; } set { this._MerchantRefundApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRefundRefusedOption { get; private set; } + + /// + /// Print a merchant receipt when the refund is refused. + /// + /// Print a merchant receipt when the refund is refused. + [JsonPropertyName("merchantRefundRefused")] + public bool? MerchantRefundRefused { get { return this._MerchantRefundRefusedOption; } set { this._MerchantRefundRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRefusedOption { get; private set; } + + /// + /// Print a merchant receipt when the payment is refused. + /// + /// Print a merchant receipt when the payment is refused. + [JsonPropertyName("merchantRefused")] + public bool? MerchantRefused { get { return this._MerchantRefusedOption; } set { this._MerchantRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantVoidOption { get; private set; } + + /// + /// Print a merchant receipt when a previous transaction is voided. + /// + /// Print a merchant receipt when a previous transaction is voided. + [JsonPropertyName("merchantVoid")] + public bool? MerchantVoid { get { return this._MerchantVoidOption; } set { this._MerchantVoidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperApprovedOption { get; private set; } + + /// + /// Print a shopper receipt when the payment is approved. + /// + /// Print a shopper receipt when the payment is approved. + [JsonPropertyName("shopperApproved")] + public bool? ShopperApproved { get { return this._ShopperApprovedOption; } set { this._ShopperApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperCancelledOption { get; private set; } + + /// + /// Print a shopper receipt when the transaction is cancelled. + /// + /// Print a shopper receipt when the transaction is cancelled. + [JsonPropertyName("shopperCancelled")] + public bool? ShopperCancelled { get { return this._ShopperCancelledOption; } set { this._ShopperCancelledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperCaptureApprovedOption { get; private set; } + + /// + /// Print a shopper receipt when capturing the payment is approved. + /// + /// Print a shopper receipt when capturing the payment is approved. + [JsonPropertyName("shopperCaptureApproved")] + public bool? ShopperCaptureApproved { get { return this._ShopperCaptureApprovedOption; } set { this._ShopperCaptureApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperCaptureRefusedOption { get; private set; } + + /// + /// Print a shopper receipt when capturing the payment is refused. + /// + /// Print a shopper receipt when capturing the payment is refused. + [JsonPropertyName("shopperCaptureRefused")] + public bool? ShopperCaptureRefused { get { return this._ShopperCaptureRefusedOption; } set { this._ShopperCaptureRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperRefundApprovedOption { get; private set; } + + /// + /// Print a shopper receipt when the refund is approved. + /// + /// Print a shopper receipt when the refund is approved. + [JsonPropertyName("shopperRefundApproved")] + public bool? ShopperRefundApproved { get { return this._ShopperRefundApprovedOption; } set { this._ShopperRefundApprovedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperRefundRefusedOption { get; private set; } + + /// + /// Print a shopper receipt when the refund is refused. + /// + /// Print a shopper receipt when the refund is refused. + [JsonPropertyName("shopperRefundRefused")] + public bool? ShopperRefundRefused { get { return this._ShopperRefundRefusedOption; } set { this._ShopperRefundRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperRefusedOption { get; private set; } + + /// + /// Print a shopper receipt when the payment is refused. + /// + /// Print a shopper receipt when the payment is refused. + [JsonPropertyName("shopperRefused")] + public bool? ShopperRefused { get { return this._ShopperRefusedOption; } set { this._ShopperRefusedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperVoidOption { get; private set; } + + /// + /// Print a shopper receipt when a previous transaction is voided. + /// + /// Print a shopper receipt when a previous transaction is voided. + [JsonPropertyName("shopperVoid")] + public bool? ShopperVoid { get { return this._ShopperVoidOption; } set { this._ShopperVoidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReceiptPrinting {\n"); + sb.Append(" MerchantApproved: ").Append(MerchantApproved).Append("\n"); + sb.Append(" MerchantCancelled: ").Append(MerchantCancelled).Append("\n"); + sb.Append(" MerchantCaptureApproved: ").Append(MerchantCaptureApproved).Append("\n"); + sb.Append(" MerchantCaptureRefused: ").Append(MerchantCaptureRefused).Append("\n"); + sb.Append(" MerchantRefundApproved: ").Append(MerchantRefundApproved).Append("\n"); + sb.Append(" MerchantRefundRefused: ").Append(MerchantRefundRefused).Append("\n"); + sb.Append(" MerchantRefused: ").Append(MerchantRefused).Append("\n"); + sb.Append(" MerchantVoid: ").Append(MerchantVoid).Append("\n"); + sb.Append(" ShopperApproved: ").Append(ShopperApproved).Append("\n"); + sb.Append(" ShopperCancelled: ").Append(ShopperCancelled).Append("\n"); + sb.Append(" ShopperCaptureApproved: ").Append(ShopperCaptureApproved).Append("\n"); + sb.Append(" ShopperCaptureRefused: ").Append(ShopperCaptureRefused).Append("\n"); + sb.Append(" ShopperRefundApproved: ").Append(ShopperRefundApproved).Append("\n"); + sb.Append(" ShopperRefundRefused: ").Append(ShopperRefundRefused).Append("\n"); + sb.Append(" ShopperRefused: ").Append(ShopperRefused).Append("\n"); + sb.Append(" ShopperVoid: ").Append(ShopperVoid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReceiptPrintingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReceiptPrinting Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantApproved = default; + Option merchantCancelled = default; + Option merchantCaptureApproved = default; + Option merchantCaptureRefused = default; + Option merchantRefundApproved = default; + Option merchantRefundRefused = default; + Option merchantRefused = default; + Option merchantVoid = default; + Option shopperApproved = default; + Option shopperCancelled = default; + Option shopperCaptureApproved = default; + Option shopperCaptureRefused = default; + Option shopperRefundApproved = default; + Option shopperRefundRefused = default; + Option shopperRefused = default; + Option shopperVoid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantApproved": + merchantApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantCancelled": + merchantCancelled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantCaptureApproved": + merchantCaptureApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantCaptureRefused": + merchantCaptureRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantRefundApproved": + merchantRefundApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantRefundRefused": + merchantRefundRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantRefused": + merchantRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantVoid": + merchantVoid = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperApproved": + shopperApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperCancelled": + shopperCancelled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperCaptureApproved": + shopperCaptureApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperCaptureRefused": + shopperCaptureRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperRefundApproved": + shopperRefundApproved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperRefundRefused": + shopperRefundRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperRefused": + shopperRefused = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "shopperVoid": + shopperVoid = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ReceiptPrinting(merchantApproved, merchantCancelled, merchantCaptureApproved, merchantCaptureRefused, merchantRefundApproved, merchantRefundRefused, merchantRefused, merchantVoid, shopperApproved, shopperCancelled, shopperCaptureApproved, shopperCaptureRefused, shopperRefundApproved, shopperRefundRefused, shopperRefused, shopperVoid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReceiptPrinting receiptPrinting, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, receiptPrinting, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReceiptPrinting receiptPrinting, JsonSerializerOptions jsonSerializerOptions) + { + + if (receiptPrinting._MerchantApprovedOption.IsSet) + writer.WriteBoolean("merchantApproved", receiptPrinting._MerchantApprovedOption.Value!.Value); + + if (receiptPrinting._MerchantCancelledOption.IsSet) + writer.WriteBoolean("merchantCancelled", receiptPrinting._MerchantCancelledOption.Value!.Value); + + if (receiptPrinting._MerchantCaptureApprovedOption.IsSet) + writer.WriteBoolean("merchantCaptureApproved", receiptPrinting._MerchantCaptureApprovedOption.Value!.Value); + + if (receiptPrinting._MerchantCaptureRefusedOption.IsSet) + writer.WriteBoolean("merchantCaptureRefused", receiptPrinting._MerchantCaptureRefusedOption.Value!.Value); + + if (receiptPrinting._MerchantRefundApprovedOption.IsSet) + writer.WriteBoolean("merchantRefundApproved", receiptPrinting._MerchantRefundApprovedOption.Value!.Value); + + if (receiptPrinting._MerchantRefundRefusedOption.IsSet) + writer.WriteBoolean("merchantRefundRefused", receiptPrinting._MerchantRefundRefusedOption.Value!.Value); + + if (receiptPrinting._MerchantRefusedOption.IsSet) + writer.WriteBoolean("merchantRefused", receiptPrinting._MerchantRefusedOption.Value!.Value); + + if (receiptPrinting._MerchantVoidOption.IsSet) + writer.WriteBoolean("merchantVoid", receiptPrinting._MerchantVoidOption.Value!.Value); + + if (receiptPrinting._ShopperApprovedOption.IsSet) + writer.WriteBoolean("shopperApproved", receiptPrinting._ShopperApprovedOption.Value!.Value); + + if (receiptPrinting._ShopperCancelledOption.IsSet) + writer.WriteBoolean("shopperCancelled", receiptPrinting._ShopperCancelledOption.Value!.Value); + + if (receiptPrinting._ShopperCaptureApprovedOption.IsSet) + writer.WriteBoolean("shopperCaptureApproved", receiptPrinting._ShopperCaptureApprovedOption.Value!.Value); + + if (receiptPrinting._ShopperCaptureRefusedOption.IsSet) + writer.WriteBoolean("shopperCaptureRefused", receiptPrinting._ShopperCaptureRefusedOption.Value!.Value); + + if (receiptPrinting._ShopperRefundApprovedOption.IsSet) + writer.WriteBoolean("shopperRefundApproved", receiptPrinting._ShopperRefundApprovedOption.Value!.Value); + + if (receiptPrinting._ShopperRefundRefusedOption.IsSet) + writer.WriteBoolean("shopperRefundRefused", receiptPrinting._ShopperRefundRefusedOption.Value!.Value); + + if (receiptPrinting._ShopperRefusedOption.IsSet) + writer.WriteBoolean("shopperRefused", receiptPrinting._ShopperRefusedOption.Value!.Value); + + if (receiptPrinting._ShopperVoidOption.IsSet) + writer.WriteBoolean("shopperVoid", receiptPrinting._ShopperVoidOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Referenced.cs b/Adyen/Management/Models/Referenced.cs new file mode 100644 index 000000000..4bbcb5d60 --- /dev/null +++ b/Adyen/Management/Models/Referenced.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Referenced. + /// + public partial class Referenced : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether referenced refunds are enabled on the standalone terminal. + [JsonConstructor] + public Referenced(Option enableStandaloneRefunds = default) + { + _EnableStandaloneRefundsOption = enableStandaloneRefunds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Referenced() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableStandaloneRefundsOption { get; private set; } + + /// + /// Indicates whether referenced refunds are enabled on the standalone terminal. + /// + /// Indicates whether referenced refunds are enabled on the standalone terminal. + [JsonPropertyName("enableStandaloneRefunds")] + public bool? EnableStandaloneRefunds { get { return this._EnableStandaloneRefundsOption; } set { this._EnableStandaloneRefundsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Referenced {\n"); + sb.Append(" EnableStandaloneRefunds: ").Append(EnableStandaloneRefunds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReferencedJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Referenced Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enableStandaloneRefunds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enableStandaloneRefunds": + enableStandaloneRefunds = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Referenced(enableStandaloneRefunds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Referenced referenced, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, referenced, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Referenced referenced, JsonSerializerOptions jsonSerializerOptions) + { + + if (referenced._EnableStandaloneRefundsOption.IsSet) + writer.WriteBoolean("enableStandaloneRefunds", referenced._EnableStandaloneRefundsOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Refunds.cs b/Adyen/Management/Models/Refunds.cs new file mode 100644 index 000000000..7daed5cc7 --- /dev/null +++ b/Adyen/Management/Models/Refunds.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Refunds. + /// + public partial class Refunds : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// referenced + /// unreferenced + [JsonConstructor] + public Refunds(Option referenced = default, Option unreferenced = default) + { + _ReferencedOption = referenced; + _UnreferencedOption = unreferenced; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Refunds() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferencedOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("referenced")] + public Referenced? Referenced { get { return this._ReferencedOption; } set { this._ReferencedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnreferencedOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("unreferenced")] + public Unreferenced? Unreferenced { get { return this._UnreferencedOption; } set { this._UnreferencedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Refunds {\n"); + sb.Append(" Referenced: ").Append(Referenced).Append("\n"); + sb.Append(" Unreferenced: ").Append(Unreferenced).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RefundsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Refunds Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option referenced = default; + Option unreferenced = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "referenced": + referenced = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "unreferenced": + unreferenced = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Refunds(referenced, unreferenced); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Refunds refunds, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, refunds, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Refunds refunds, JsonSerializerOptions jsonSerializerOptions) + { + + if (refunds._ReferencedOption.IsSet) + { + writer.WritePropertyName("referenced"); + JsonSerializer.Serialize(writer, refunds.Referenced, jsonSerializerOptions); + } + if (refunds._UnreferencedOption.IsSet) + { + writer.WritePropertyName("unreferenced"); + JsonSerializer.Serialize(writer, refunds.Unreferenced, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ReleaseUpdateDetails.cs b/Adyen/Management/Models/ReleaseUpdateDetails.cs new file mode 100644 index 000000000..01c6bded5 --- /dev/null +++ b/Adyen/Management/Models/ReleaseUpdateDetails.cs @@ -0,0 +1,298 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ReleaseUpdateDetails. + /// + public partial class ReleaseUpdateDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Type of terminal action: Update Release. (default to TypeEnum.ReleaseUpdate) + /// Boolean flag that tells if the terminal should update at the first next maintenance call. If false, terminal will update on its configured reboot time. + [JsonConstructor] + public ReleaseUpdateDetails(Option type = default, Option updateAtFirstMaintenanceCall = default) + { + _TypeOption = type; + _UpdateAtFirstMaintenanceCallOption = updateAtFirstMaintenanceCall; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReleaseUpdateDetails() + { + } + + partial void OnCreated(); + + /// + /// Type of terminal action: Update Release. + /// + /// Type of terminal action: Update Release. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.ReleaseUpdate - ReleaseUpdate + /// + public static readonly TypeEnum ReleaseUpdate = new("ReleaseUpdate"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ReleaseUpdate" => TypeEnum.ReleaseUpdate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.ReleaseUpdate) + return "ReleaseUpdate"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of terminal action: Update Release. + /// + /// Type of terminal action: Update Release. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdateAtFirstMaintenanceCallOption { get; private set; } + + /// + /// Boolean flag that tells if the terminal should update at the first next maintenance call. If false, terminal will update on its configured reboot time. + /// + /// Boolean flag that tells if the terminal should update at the first next maintenance call. If false, terminal will update on its configured reboot time. + [JsonPropertyName("updateAtFirstMaintenanceCall")] + public bool? UpdateAtFirstMaintenanceCall { get { return this._UpdateAtFirstMaintenanceCallOption; } set { this._UpdateAtFirstMaintenanceCallOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReleaseUpdateDetails {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UpdateAtFirstMaintenanceCall: ").Append(UpdateAtFirstMaintenanceCall).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReleaseUpdateDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReleaseUpdateDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option updateAtFirstMaintenanceCall = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ReleaseUpdateDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "updateAtFirstMaintenanceCall": + updateAtFirstMaintenanceCall = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ReleaseUpdateDetails(type, updateAtFirstMaintenanceCall); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReleaseUpdateDetails releaseUpdateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, releaseUpdateDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReleaseUpdateDetails releaseUpdateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (releaseUpdateDetails._TypeOption.IsSet && releaseUpdateDetails.Type != null) + { + string? typeRawValue = ReleaseUpdateDetails.TypeEnum.ToJsonValue(releaseUpdateDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (releaseUpdateDetails._UpdateAtFirstMaintenanceCallOption.IsSet) + writer.WriteBoolean("updateAtFirstMaintenanceCall", releaseUpdateDetails._UpdateAtFirstMaintenanceCallOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/ReprocessAndroidAppResponse.cs b/Adyen/Management/Models/ReprocessAndroidAppResponse.cs new file mode 100644 index 000000000..b005538d9 --- /dev/null +++ b/Adyen/Management/Models/ReprocessAndroidAppResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ReprocessAndroidAppResponse. + /// + public partial class ReprocessAndroidAppResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The result of the reprocess. + [JsonConstructor] + public ReprocessAndroidAppResponse(Option message = default) + { + _MessageOption = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReprocessAndroidAppResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// The result of the reprocess. + /// + /// The result of the reprocess. + [JsonPropertyName("Message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReprocessAndroidAppResponse {\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReprocessAndroidAppResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReprocessAndroidAppResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "Message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ReprocessAndroidAppResponse(message); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReprocessAndroidAppResponse reprocessAndroidAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, reprocessAndroidAppResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReprocessAndroidAppResponse reprocessAndroidAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (reprocessAndroidAppResponse._MessageOption.IsSet) + if (reprocessAndroidAppResponse.Message != null) + writer.WriteString("Message", reprocessAndroidAppResponse.Message); + } + } +} diff --git a/Adyen/Management/Models/RequestActivationResponse.cs b/Adyen/Management/Models/RequestActivationResponse.cs new file mode 100644 index 000000000..65255df3d --- /dev/null +++ b/Adyen/Management/Models/RequestActivationResponse.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// RequestActivationResponse. + /// + public partial class RequestActivationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the company account. + /// The unique identifier of the merchant account you requested to activate. + [JsonConstructor] + public RequestActivationResponse(Option companyId = default, Option merchantId = default) + { + _CompanyIdOption = companyId; + _MerchantIdOption = merchantId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RequestActivationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account you requested to activate. + /// + /// The unique identifier of the merchant account you requested to activate. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequestActivationResponse {\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RequestActivationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RequestActivationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option companyId = default; + Option merchantId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RequestActivationResponse(companyId, merchantId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RequestActivationResponse requestActivationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, requestActivationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RequestActivationResponse requestActivationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (requestActivationResponse._CompanyIdOption.IsSet) + if (requestActivationResponse.CompanyId != null) + writer.WriteString("companyId", requestActivationResponse.CompanyId); + + if (requestActivationResponse._MerchantIdOption.IsSet) + if (requestActivationResponse.MerchantId != null) + writer.WriteString("merchantId", requestActivationResponse.MerchantId); + } + } +} diff --git a/Adyen/Management/Models/RestServiceError.cs b/Adyen/Management/Models/RestServiceError.cs new file mode 100644 index 000000000..538de25bf --- /dev/null +++ b/Adyen/Management/Models/RestServiceError.cs @@ -0,0 +1,352 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// RestServiceError. + /// + public partial class RestServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// A code that identifies the problem type. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// A unique URI that identifies the specific occurrence of the problem. + /// Detailed explanation of each validation error, when applicable. + /// A unique reference for the request, essentially the same as `pspReference`. + /// response + [JsonConstructor] + public RestServiceError(string detail, string errorCode, int status, string title, string type, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option response = default) + { + Detail = detail; + ErrorCode = errorCode; + Status = status; + Title = title; + Type = type; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _ResponseOption = response; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RestServiceError() + { + } + + partial void OnCreated(); + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string Detail { get; set; } + + /// + /// A code that identifies the problem type. + /// + /// A code that identifies the problem type. + [JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A unique URI that identifies the specific occurrence of the problem. + /// + /// A unique URI that identifies the specific occurrence of the problem. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Detailed explanation of each validation error, when applicable. + /// + /// Detailed explanation of each validation error, when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// A unique reference for the request, essentially the same as `pspReference`. + /// + /// A unique reference for the request, essentially the same as `pspReference`. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("response")] + public Object? Response { get { return this._ResponseOption; } set { this._ResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RestServiceError {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RestServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RestServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option status = default; + Option title = default; + Option type = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option response = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "response": + response = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!detail.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(detail)); + + if (!errorCode.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(errorCode)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(status)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(title)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(type)); + + return new RestServiceError(detail.Value!, errorCode.Value!, status.Value!.Value!, title.Value!, type.Value!, instance, invalidFields, requestId, response); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, restServiceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (restServiceError.Detail != null) + writer.WriteString("detail", restServiceError.Detail); + + if (restServiceError.ErrorCode != null) + writer.WriteString("errorCode", restServiceError.ErrorCode); + + writer.WriteNumber("status", restServiceError.Status); + + if (restServiceError.Title != null) + writer.WriteString("title", restServiceError.Title); + + if (restServiceError.Type != null) + writer.WriteString("type", restServiceError.Type); + + if (restServiceError._InstanceOption.IsSet) + if (restServiceError.Instance != null) + writer.WriteString("instance", restServiceError.Instance); + + if (restServiceError._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, restServiceError.InvalidFields, jsonSerializerOptions); + } + if (restServiceError._RequestIdOption.IsSet) + if (restServiceError.RequestId != null) + writer.WriteString("requestId", restServiceError.RequestId); + + if (restServiceError._ResponseOption.IsSet) + { + writer.WritePropertyName("response"); + JsonSerializer.Serialize(writer, restServiceError.Response, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ScheduleTerminalActionsRequest.cs b/Adyen/Management/Models/ScheduleTerminalActionsRequest.cs new file mode 100644 index 000000000..7c4326d42 --- /dev/null +++ b/Adyen/Management/Models/ScheduleTerminalActionsRequest.cs @@ -0,0 +1,254 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ScheduleTerminalActionsRequest. + /// + public partial class ScheduleTerminalActionsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// actionDetails + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + /// A list of unique IDs of the terminals to apply the action to. You can extract the IDs from the [GET `/terminals`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/terminals) response. Maximum length: 100 IDs. + [JsonConstructor] + public ScheduleTerminalActionsRequest(Option actionDetails = default, Option scheduledAt = default, Option storeId = default, Option?> terminalIds = default) + { + _ActionDetailsOption = actionDetails; + _ScheduledAtOption = scheduledAt; + _StoreIdOption = storeId; + _TerminalIdsOption = terminalIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScheduleTerminalActionsRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActionDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("actionDetails")] + public ScheduleTerminalActionsRequestActionDetails? ActionDetails { get { return this._ActionDetailsOption; } set { this._ActionDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScheduledAtOption { get; private set; } + + /// + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + /// + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + [JsonPropertyName("scheduledAt")] + public string? ScheduledAt { get { return this._ScheduledAtOption; } set { this._ScheduledAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + /// + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TerminalIdsOption { get; private set; } + + /// + /// A list of unique IDs of the terminals to apply the action to. You can extract the IDs from the [GET `/terminals`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/terminals) response. Maximum length: 100 IDs. + /// + /// A list of unique IDs of the terminals to apply the action to. You can extract the IDs from the [GET `/terminals`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/terminals) response. Maximum length: 100 IDs. + [JsonPropertyName("terminalIds")] + public List? TerminalIds { get { return this._TerminalIdsOption; } set { this._TerminalIdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScheduleTerminalActionsRequest {\n"); + sb.Append(" ActionDetails: ").Append(ActionDetails).Append("\n"); + sb.Append(" ScheduledAt: ").Append(ScheduledAt).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append(" TerminalIds: ").Append(TerminalIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScheduleTerminalActionsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScheduleTerminalActionsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option actionDetails = default; + Option scheduledAt = default; + Option storeId = default; + Option?> terminalIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "actionDetails": + actionDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "scheduledAt": + scheduledAt = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + case "terminalIds": + terminalIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ScheduleTerminalActionsRequest(actionDetails, scheduledAt, storeId, terminalIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScheduleTerminalActionsRequest scheduleTerminalActionsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scheduleTerminalActionsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScheduleTerminalActionsRequest scheduleTerminalActionsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (scheduleTerminalActionsRequest._ActionDetailsOption.IsSet) + { + writer.WritePropertyName("actionDetails"); + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequest.ActionDetails, jsonSerializerOptions); + } + if (scheduleTerminalActionsRequest._ScheduledAtOption.IsSet) + if (scheduleTerminalActionsRequest.ScheduledAt != null) + writer.WriteString("scheduledAt", scheduleTerminalActionsRequest.ScheduledAt); + + if (scheduleTerminalActionsRequest._StoreIdOption.IsSet) + if (scheduleTerminalActionsRequest.StoreId != null) + writer.WriteString("storeId", scheduleTerminalActionsRequest.StoreId); + + if (scheduleTerminalActionsRequest._TerminalIdsOption.IsSet) + { + writer.WritePropertyName("terminalIds"); + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequest.TerminalIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/ScheduleTerminalActionsRequestActionDetails.cs b/Adyen/Management/Models/ScheduleTerminalActionsRequestActionDetails.cs new file mode 100644 index 000000000..40e2673e1 --- /dev/null +++ b/Adyen/Management/Models/ScheduleTerminalActionsRequestActionDetails.cs @@ -0,0 +1,279 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Information about the action to take.. + /// + public partial class ScheduleTerminalActionsRequestActionDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public ScheduleTerminalActionsRequestActionDetails(InstallAndroidAppDetails installAndroidAppDetails) + { + InstallAndroidAppDetails = installAndroidAppDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public ScheduleTerminalActionsRequestActionDetails(InstallAndroidCertificateDetails installAndroidCertificateDetails) + { + InstallAndroidCertificateDetails = installAndroidCertificateDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public ScheduleTerminalActionsRequestActionDetails(ReleaseUpdateDetails releaseUpdateDetails) + { + ReleaseUpdateDetails = releaseUpdateDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public ScheduleTerminalActionsRequestActionDetails(UninstallAndroidAppDetails uninstallAndroidAppDetails) + { + UninstallAndroidAppDetails = uninstallAndroidAppDetails; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public ScheduleTerminalActionsRequestActionDetails(UninstallAndroidCertificateDetails uninstallAndroidCertificateDetails) + { + UninstallAndroidCertificateDetails = uninstallAndroidCertificateDetails; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public InstallAndroidAppDetails? InstallAndroidAppDetails { get; set; } + + /// + /// .. + /// + public InstallAndroidCertificateDetails? InstallAndroidCertificateDetails { get; set; } + + /// + /// .. + /// + public ReleaseUpdateDetails? ReleaseUpdateDetails { get; set; } + + /// + /// .. + /// + public UninstallAndroidAppDetails? UninstallAndroidAppDetails { get; set; } + + /// + /// .. + /// + public UninstallAndroidCertificateDetails? UninstallAndroidCertificateDetails { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScheduleTerminalActionsRequestActionDetails {\n"); + if (this.InstallAndroidAppDetails != null) + sb.Append(InstallAndroidAppDetails.ToString().Replace("\n", "\n ")); + if (this.InstallAndroidCertificateDetails != null) + sb.Append(InstallAndroidCertificateDetails.ToString().Replace("\n", "\n ")); + if (this.ReleaseUpdateDetails != null) + sb.Append(ReleaseUpdateDetails.ToString().Replace("\n", "\n ")); + if (this.UninstallAndroidAppDetails != null) + sb.Append(UninstallAndroidAppDetails.ToString().Replace("\n", "\n ")); + if (this.UninstallAndroidCertificateDetails != null) + sb.Append(UninstallAndroidCertificateDetails.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScheduleTerminalActionsRequestActionDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScheduleTerminalActionsRequestActionDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + InstallAndroidAppDetails? installAndroidAppDetails = default; + InstallAndroidCertificateDetails? installAndroidCertificateDetails = default; + ReleaseUpdateDetails? releaseUpdateDetails = default; + UninstallAndroidAppDetails? uninstallAndroidAppDetails = default; + UninstallAndroidCertificateDetails? uninstallAndroidCertificateDetails = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderInstallAndroidAppDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInstallAndroidAppDetails, jsonSerializerOptions, out installAndroidAppDetails); + + Utf8JsonReader utf8JsonReaderInstallAndroidCertificateDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInstallAndroidCertificateDetails, jsonSerializerOptions, out installAndroidCertificateDetails); + + Utf8JsonReader utf8JsonReaderReleaseUpdateDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderReleaseUpdateDetails, jsonSerializerOptions, out releaseUpdateDetails); + + Utf8JsonReader utf8JsonReaderUninstallAndroidAppDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUninstallAndroidAppDetails, jsonSerializerOptions, out uninstallAndroidAppDetails); + + Utf8JsonReader utf8JsonReaderUninstallAndroidCertificateDetails = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUninstallAndroidCertificateDetails, jsonSerializerOptions, out uninstallAndroidCertificateDetails); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (installAndroidAppDetails?.Type != null) + return new ScheduleTerminalActionsRequestActionDetails(installAndroidAppDetails); + + if (installAndroidCertificateDetails?.Type != null) + return new ScheduleTerminalActionsRequestActionDetails(installAndroidCertificateDetails); + + if (releaseUpdateDetails?.Type != null) + return new ScheduleTerminalActionsRequestActionDetails(releaseUpdateDetails); + + if (uninstallAndroidAppDetails?.Type != null) + return new ScheduleTerminalActionsRequestActionDetails(uninstallAndroidAppDetails); + + if (uninstallAndroidCertificateDetails?.Type != null) + return new ScheduleTerminalActionsRequestActionDetails(uninstallAndroidCertificateDetails); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScheduleTerminalActionsRequestActionDetails scheduleTerminalActionsRequestActionDetails, JsonSerializerOptions jsonSerializerOptions) + { + if (scheduleTerminalActionsRequestActionDetails.InstallAndroidAppDetails != null) + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequestActionDetails.InstallAndroidAppDetails, jsonSerializerOptions); + if (scheduleTerminalActionsRequestActionDetails.InstallAndroidCertificateDetails != null) + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequestActionDetails.InstallAndroidCertificateDetails, jsonSerializerOptions); + if (scheduleTerminalActionsRequestActionDetails.ReleaseUpdateDetails != null) + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequestActionDetails.ReleaseUpdateDetails, jsonSerializerOptions); + if (scheduleTerminalActionsRequestActionDetails.UninstallAndroidAppDetails != null) + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequestActionDetails.UninstallAndroidAppDetails, jsonSerializerOptions); + if (scheduleTerminalActionsRequestActionDetails.UninstallAndroidCertificateDetails != null) + JsonSerializer.Serialize(writer, scheduleTerminalActionsRequestActionDetails.UninstallAndroidCertificateDetails, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, scheduleTerminalActionsRequestActionDetails, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScheduleTerminalActionsRequestActionDetails scheduleTerminalActionsRequestActionDetails, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Management/Models/ScheduleTerminalActionsResponse.cs b/Adyen/Management/Models/ScheduleTerminalActionsResponse.cs new file mode 100644 index 000000000..bbda5a93c --- /dev/null +++ b/Adyen/Management/Models/ScheduleTerminalActionsResponse.cs @@ -0,0 +1,327 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ScheduleTerminalActionsResponse. + /// + public partial class ScheduleTerminalActionsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// actionDetails + /// A list containing a terminal ID and an action ID for each terminal that the action was scheduled for. + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + /// The validation errors that occurred in the list of terminals, and for each error the IDs of the terminals that the error applies to. + /// The number of terminals for which scheduling the action failed. + /// The number of terminals for which the action was successfully scheduled. This doesn't mean the action has happened yet. + [JsonConstructor] + public ScheduleTerminalActionsResponse(Option actionDetails = default, Option?> items = default, Option scheduledAt = default, Option storeId = default, Option>?> terminalsWithErrors = default, Option totalErrors = default, Option totalScheduled = default) + { + _ActionDetailsOption = actionDetails; + _ItemsOption = items; + _ScheduledAtOption = scheduledAt; + _StoreIdOption = storeId; + _TerminalsWithErrorsOption = terminalsWithErrors; + _TotalErrorsOption = totalErrors; + _TotalScheduledOption = totalScheduled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScheduleTerminalActionsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActionDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("actionDetails")] + public ScheduleTerminalActionsRequestActionDetails? ActionDetails { get { return this._ActionDetailsOption; } set { this._ActionDetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsOption { get; private set; } + + /// + /// A list containing a terminal ID and an action ID for each terminal that the action was scheduled for. + /// + /// A list containing a terminal ID and an action ID for each terminal that the action was scheduled for. + [JsonPropertyName("items")] + public List? Items { get { return this._ItemsOption; } set { this._ItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScheduledAtOption { get; private set; } + + /// + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + /// + /// The date and time when the action should happen. Format: [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339), but without the **Z** before the time offset. For example, **2021-11-15T12:16:21+0100** The action is sent with the first [maintenance call](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api#when-actions-take-effect) after the specified date and time in the time zone of the terminal. An empty value causes the action to be sent as soon as possible: at the next maintenance call. + [JsonPropertyName("scheduledAt")] + public string? ScheduledAt { get { return this._ScheduledAtOption; } set { this._ScheduledAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + /// + /// The unique ID of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores). If present, all terminals in the `terminalIds` list must be assigned to this store. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> _TerminalsWithErrorsOption { get; private set; } + + /// + /// The validation errors that occurred in the list of terminals, and for each error the IDs of the terminals that the error applies to. + /// + /// The validation errors that occurred in the list of terminals, and for each error the IDs of the terminals that the error applies to. + [JsonPropertyName("terminalsWithErrors")] + public Dictionary>? TerminalsWithErrors { get { return this._TerminalsWithErrorsOption; } set { this._TerminalsWithErrorsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalErrorsOption { get; private set; } + + /// + /// The number of terminals for which scheduling the action failed. + /// + /// The number of terminals for which scheduling the action failed. + [JsonPropertyName("totalErrors")] + public int? TotalErrors { get { return this._TotalErrorsOption; } set { this._TotalErrorsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalScheduledOption { get; private set; } + + /// + /// The number of terminals for which the action was successfully scheduled. This doesn't mean the action has happened yet. + /// + /// The number of terminals for which the action was successfully scheduled. This doesn't mean the action has happened yet. + [JsonPropertyName("totalScheduled")] + public int? TotalScheduled { get { return this._TotalScheduledOption; } set { this._TotalScheduledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScheduleTerminalActionsResponse {\n"); + sb.Append(" ActionDetails: ").Append(ActionDetails).Append("\n"); + sb.Append(" Items: ").Append(Items).Append("\n"); + sb.Append(" ScheduledAt: ").Append(ScheduledAt).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append(" TerminalsWithErrors: ").Append(TerminalsWithErrors).Append("\n"); + sb.Append(" TotalErrors: ").Append(TotalErrors).Append("\n"); + sb.Append(" TotalScheduled: ").Append(TotalScheduled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScheduleTerminalActionsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScheduleTerminalActionsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option actionDetails = default; + Option?> items = default; + Option scheduledAt = default; + Option storeId = default; + Option>?> terminalsWithErrors = default; + Option totalErrors = default; + Option totalScheduled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "actionDetails": + actionDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "items": + items = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "scheduledAt": + scheduledAt = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + case "terminalsWithErrors": + terminalsWithErrors = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "totalErrors": + totalErrors = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "totalScheduled": + totalScheduled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ScheduleTerminalActionsResponse(actionDetails, items, scheduledAt, storeId, terminalsWithErrors, totalErrors, totalScheduled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScheduleTerminalActionsResponse scheduleTerminalActionsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scheduleTerminalActionsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScheduleTerminalActionsResponse scheduleTerminalActionsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (scheduleTerminalActionsResponse._ActionDetailsOption.IsSet) + { + writer.WritePropertyName("actionDetails"); + JsonSerializer.Serialize(writer, scheduleTerminalActionsResponse.ActionDetails, jsonSerializerOptions); + } + if (scheduleTerminalActionsResponse._ItemsOption.IsSet) + { + writer.WritePropertyName("items"); + JsonSerializer.Serialize(writer, scheduleTerminalActionsResponse.Items, jsonSerializerOptions); + } + if (scheduleTerminalActionsResponse._ScheduledAtOption.IsSet) + if (scheduleTerminalActionsResponse.ScheduledAt != null) + writer.WriteString("scheduledAt", scheduleTerminalActionsResponse.ScheduledAt); + + if (scheduleTerminalActionsResponse._StoreIdOption.IsSet) + if (scheduleTerminalActionsResponse.StoreId != null) + writer.WriteString("storeId", scheduleTerminalActionsResponse.StoreId); + + if (scheduleTerminalActionsResponse._TerminalsWithErrorsOption.IsSet) + { + writer.WritePropertyName("terminalsWithErrors"); + JsonSerializer.Serialize(writer, scheduleTerminalActionsResponse.TerminalsWithErrors, jsonSerializerOptions); + } + if (scheduleTerminalActionsResponse._TotalErrorsOption.IsSet) + writer.WriteNumber("totalErrors", scheduleTerminalActionsResponse._TotalErrorsOption.Value!.Value); + + if (scheduleTerminalActionsResponse._TotalScheduledOption.IsSet) + writer.WriteNumber("totalScheduled", scheduleTerminalActionsResponse._TotalScheduledOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/SepaDirectDebitInfo.cs b/Adyen/Management/Models/SepaDirectDebitInfo.cs new file mode 100644 index 000000000..83ac480f0 --- /dev/null +++ b/Adyen/Management/Models/SepaDirectDebitInfo.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SepaDirectDebitInfo. + /// + public partial class SepaDirectDebitInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Creditor id + /// transactionDescription + [JsonConstructor] + public SepaDirectDebitInfo(Option creditorId = default, Option transactionDescription = default) + { + _CreditorIdOption = creditorId; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SepaDirectDebitInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreditorIdOption { get; private set; } + + /// + /// Creditor id + /// + /// Creditor id + [JsonPropertyName("creditorId")] + public string? CreditorId { get { return this._CreditorIdOption; } set { this._CreditorIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SepaDirectDebitInfo {\n"); + sb.Append(" CreditorId: ").Append(CreditorId).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SepaDirectDebitInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SepaDirectDebitInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option creditorId = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "creditorId": + creditorId = new Option(utf8JsonReader.GetString()!); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new SepaDirectDebitInfo(creditorId, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SepaDirectDebitInfo sepaDirectDebitInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sepaDirectDebitInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SepaDirectDebitInfo sepaDirectDebitInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (sepaDirectDebitInfo._CreditorIdOption.IsSet) + if (sepaDirectDebitInfo.CreditorId != null) + writer.WriteString("creditorId", sepaDirectDebitInfo.CreditorId); + + if (sepaDirectDebitInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, sepaDirectDebitInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Settings.cs b/Adyen/Management/Models/Settings.cs new file mode 100644 index 000000000..16b3a9806 --- /dev/null +++ b/Adyen/Management/Models/Settings.cs @@ -0,0 +1,225 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Settings. + /// + public partial class Settings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The preferred Wi-Fi band, for use if the terminals support multiple bands. Possible values: All, 2.4GHz, 5GHz. + /// Indicates whether roaming is enabled on the terminals. + /// The connection time-out in seconds. Minimum value: 0. + [JsonConstructor] + public Settings(Option band = default, Option roaming = default, Option timeout = default) + { + _BandOption = band; + _RoamingOption = roaming; + _TimeoutOption = timeout; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Settings() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BandOption { get; private set; } + + /// + /// The preferred Wi-Fi band, for use if the terminals support multiple bands. Possible values: All, 2.4GHz, 5GHz. + /// + /// The preferred Wi-Fi band, for use if the terminals support multiple bands. Possible values: All, 2.4GHz, 5GHz. + [JsonPropertyName("band")] + public string? Band { get { return this._BandOption; } set { this._BandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RoamingOption { get; private set; } + + /// + /// Indicates whether roaming is enabled on the terminals. + /// + /// Indicates whether roaming is enabled on the terminals. + [JsonPropertyName("roaming")] + public bool? Roaming { get { return this._RoamingOption; } set { this._RoamingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeoutOption { get; private set; } + + /// + /// The connection time-out in seconds. Minimum value: 0. + /// + /// The connection time-out in seconds. Minimum value: 0. + [JsonPropertyName("timeout")] + public int? Timeout { get { return this._TimeoutOption; } set { this._TimeoutOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Settings {\n"); + sb.Append(" Band: ").Append(Band).Append("\n"); + sb.Append(" Roaming: ").Append(Roaming).Append("\n"); + sb.Append(" Timeout: ").Append(Timeout).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Settings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option band = default; + Option roaming = default; + Option timeout = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "band": + band = new Option(utf8JsonReader.GetString()!); + break; + case "roaming": + roaming = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "timeout": + timeout = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Settings(band, roaming, timeout); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Settings settings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, settings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Settings settings, JsonSerializerOptions jsonSerializerOptions) + { + + if (settings._BandOption.IsSet) + if (settings.Band != null) + writer.WriteString("band", settings.Band); + + if (settings._RoamingOption.IsSet) + writer.WriteBoolean("roaming", settings._RoamingOption.Value!.Value); + + if (settings._TimeoutOption.IsSet) + writer.WriteNumber("timeout", settings._TimeoutOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/ShippingLocation.cs b/Adyen/Management/Models/ShippingLocation.cs new file mode 100644 index 000000000..83191ccbc --- /dev/null +++ b/Adyen/Management/Models/ShippingLocation.cs @@ -0,0 +1,252 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ShippingLocation. + /// + public partial class ShippingLocation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// contact + /// The unique identifier of the shipping location, for use as `shippingLocationId` when creating an order. + /// The unique name of the shipping location. + [JsonConstructor] + public ShippingLocation(Option address = default, Option contact = default, Option id = default, Option name = default) + { + _AddressOption = address; + _ContactOption = contact; + _IdOption = id; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ShippingLocation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public Address? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContactOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("contact")] + public Contact? Contact { get { return this._ContactOption; } set { this._ContactOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the shipping location, for use as `shippingLocationId` when creating an order. + /// + /// The unique identifier of the shipping location, for use as `shippingLocationId` when creating an order. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The unique name of the shipping location. + /// + /// The unique name of the shipping location. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShippingLocation {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Contact: ").Append(Contact).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShippingLocationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShippingLocation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option contact = default; + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contact": + contact = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ShippingLocation(address, contact, id, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShippingLocation shippingLocation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, shippingLocation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShippingLocation shippingLocation, JsonSerializerOptions jsonSerializerOptions) + { + + if (shippingLocation._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, shippingLocation.Address, jsonSerializerOptions); + } + if (shippingLocation._ContactOption.IsSet) + { + writer.WritePropertyName("contact"); + JsonSerializer.Serialize(writer, shippingLocation.Contact, jsonSerializerOptions); + } + if (shippingLocation._IdOption.IsSet) + if (shippingLocation.Id != null) + writer.WriteString("id", shippingLocation.Id); + + if (shippingLocation._NameOption.IsSet) + if (shippingLocation.Name != null) + writer.WriteString("name", shippingLocation.Name); + } + } +} diff --git a/Adyen/Management/Models/ShippingLocationsResponse.cs b/Adyen/Management/Models/ShippingLocationsResponse.cs new file mode 100644 index 000000000..38b937f97 --- /dev/null +++ b/Adyen/Management/Models/ShippingLocationsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// ShippingLocationsResponse. + /// + public partial class ShippingLocationsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Physical locations where orders can be shipped to. + [JsonConstructor] + public ShippingLocationsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ShippingLocationsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Physical locations where orders can be shipped to. + /// + /// Physical locations where orders can be shipped to. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShippingLocationsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShippingLocationsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShippingLocationsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ShippingLocationsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShippingLocationsResponse shippingLocationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, shippingLocationsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShippingLocationsResponse shippingLocationsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (shippingLocationsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, shippingLocationsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Signature.cs b/Adyen/Management/Models/Signature.cs new file mode 100644 index 000000000..319a89cd3 --- /dev/null +++ b/Adyen/Management/Models/Signature.cs @@ -0,0 +1,256 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Signature. + /// + public partial class Signature : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// If `skipSignature` is false, indicates whether the shopper should provide a signature on the display (**true**) or on the merchant receipt (**false**). + /// Name that identifies the terminal. + /// Slogan shown on the start screen of the device. + /// Skip asking for a signature. This is possible because all global card schemes (American Express, Diners, Discover, JCB, MasterCard, VISA, and UnionPay) regard a signature as optional. + [JsonConstructor] + public Signature(Option askSignatureOnScreen = default, Option deviceName = default, Option deviceSlogan = default, Option skipSignature = default) + { + _AskSignatureOnScreenOption = askSignatureOnScreen; + _DeviceNameOption = deviceName; + _DeviceSloganOption = deviceSlogan; + _SkipSignatureOption = skipSignature; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Signature() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AskSignatureOnScreenOption { get; private set; } + + /// + /// If `skipSignature` is false, indicates whether the shopper should provide a signature on the display (**true**) or on the merchant receipt (**false**). + /// + /// If `skipSignature` is false, indicates whether the shopper should provide a signature on the display (**true**) or on the merchant receipt (**false**). + [JsonPropertyName("askSignatureOnScreen")] + public bool? AskSignatureOnScreen { get { return this._AskSignatureOnScreenOption; } set { this._AskSignatureOnScreenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceNameOption { get; private set; } + + /// + /// Name that identifies the terminal. + /// + /// Name that identifies the terminal. + [JsonPropertyName("deviceName")] + public string? DeviceName { get { return this._DeviceNameOption; } set { this._DeviceNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceSloganOption { get; private set; } + + /// + /// Slogan shown on the start screen of the device. + /// + /// Slogan shown on the start screen of the device. + [JsonPropertyName("deviceSlogan")] + public string? DeviceSlogan { get { return this._DeviceSloganOption; } set { this._DeviceSloganOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SkipSignatureOption { get; private set; } + + /// + /// Skip asking for a signature. This is possible because all global card schemes (American Express, Diners, Discover, JCB, MasterCard, VISA, and UnionPay) regard a signature as optional. + /// + /// Skip asking for a signature. This is possible because all global card schemes (American Express, Diners, Discover, JCB, MasterCard, VISA, and UnionPay) regard a signature as optional. + [JsonPropertyName("skipSignature")] + public bool? SkipSignature { get { return this._SkipSignatureOption; } set { this._SkipSignatureOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Signature {\n"); + sb.Append(" AskSignatureOnScreen: ").Append(AskSignatureOnScreen).Append("\n"); + sb.Append(" DeviceName: ").Append(DeviceName).Append("\n"); + sb.Append(" DeviceSlogan: ").Append(DeviceSlogan).Append("\n"); + sb.Append(" SkipSignature: ").Append(SkipSignature).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceSlogan (string) maxLength + if (this.DeviceSlogan != null && this.DeviceSlogan.Length > 50) + { + yield return new ValidationResult("Invalid value for DeviceSlogan, length must be less than 50.", new [] { "DeviceSlogan" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SignatureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Signature Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option askSignatureOnScreen = default; + Option deviceName = default; + Option deviceSlogan = default; + Option skipSignature = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "askSignatureOnScreen": + askSignatureOnScreen = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "deviceName": + deviceName = new Option(utf8JsonReader.GetString()!); + break; + case "deviceSlogan": + deviceSlogan = new Option(utf8JsonReader.GetString()!); + break; + case "skipSignature": + skipSignature = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Signature(askSignatureOnScreen, deviceName, deviceSlogan, skipSignature); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Signature signature, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, signature, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Signature signature, JsonSerializerOptions jsonSerializerOptions) + { + + if (signature._AskSignatureOnScreenOption.IsSet) + writer.WriteBoolean("askSignatureOnScreen", signature._AskSignatureOnScreenOption.Value!.Value); + + if (signature._DeviceNameOption.IsSet) + if (signature.DeviceName != null) + writer.WriteString("deviceName", signature.DeviceName); + + if (signature._DeviceSloganOption.IsSet) + if (signature.DeviceSlogan != null) + writer.WriteString("deviceSlogan", signature.DeviceSlogan); + + if (signature._SkipSignatureOption.IsSet) + writer.WriteBoolean("skipSignature", signature._SkipSignatureOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/SodexoInfo.cs b/Adyen/Management/Models/SodexoInfo.cs new file mode 100644 index 000000000..80e04cecf --- /dev/null +++ b/Adyen/Management/Models/SodexoInfo.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SodexoInfo. + /// + public partial class SodexoInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Sodexo merchantContactPhone + [JsonConstructor] + public SodexoInfo(string merchantContactPhone) + { + MerchantContactPhone = merchantContactPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SodexoInfo() + { + } + + partial void OnCreated(); + + /// + /// Sodexo merchantContactPhone + /// + /// Sodexo merchantContactPhone + [JsonPropertyName("merchantContactPhone")] + public string MerchantContactPhone { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SodexoInfo {\n"); + sb.Append(" MerchantContactPhone: ").Append(MerchantContactPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SodexoInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SodexoInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantContactPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantContactPhone": + merchantContactPhone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantContactPhone.IsSet) + throw new ArgumentException("Property is required for class SodexoInfo.", nameof(merchantContactPhone)); + + return new SodexoInfo(merchantContactPhone.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SodexoInfo sodexoInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sodexoInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SodexoInfo sodexoInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (sodexoInfo.MerchantContactPhone != null) + writer.WriteString("merchantContactPhone", sodexoInfo.MerchantContactPhone); + } + } +} diff --git a/Adyen/Management/Models/SofortInfo.cs b/Adyen/Management/Models/SofortInfo.cs new file mode 100644 index 000000000..5b1ba9b86 --- /dev/null +++ b/Adyen/Management/Models/SofortInfo.cs @@ -0,0 +1,191 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SofortInfo. + /// + public partial class SofortInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Sofort currency code. For example, **EUR**. + /// Sofort logo. Format: Base64-encoded string. + [JsonConstructor] + public SofortInfo(string currencyCode, string logo) + { + CurrencyCode = currencyCode; + Logo = logo; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SofortInfo() + { + } + + partial void OnCreated(); + + /// + /// Sofort currency code. For example, **EUR**. + /// + /// Sofort currency code. For example, **EUR**. + [JsonPropertyName("currencyCode")] + public string CurrencyCode { get; set; } + + /// + /// Sofort logo. Format: Base64-encoded string. + /// + /// Sofort logo. Format: Base64-encoded string. + [JsonPropertyName("logo")] + public string Logo { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SofortInfo {\n"); + sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SofortInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SofortInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currencyCode = default; + Option logo = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currencyCode": + currencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!currencyCode.IsSet) + throw new ArgumentException("Property is required for class SofortInfo.", nameof(currencyCode)); + + if (!logo.IsSet) + throw new ArgumentException("Property is required for class SofortInfo.", nameof(logo)); + + return new SofortInfo(currencyCode.Value!, logo.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SofortInfo sofortInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sofortInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SofortInfo sofortInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (sofortInfo.CurrencyCode != null) + writer.WriteString("currencyCode", sofortInfo.CurrencyCode); + + if (sofortInfo.Logo != null) + writer.WriteString("logo", sofortInfo.Logo); + } + } +} diff --git a/Adyen/Management/Models/SplitConfiguration.cs b/Adyen/Management/Models/SplitConfiguration.cs new file mode 100644 index 000000000..1c1a7ab18 --- /dev/null +++ b/Adyen/Management/Models/SplitConfiguration.cs @@ -0,0 +1,221 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SplitConfiguration. + /// + public partial class SplitConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your description for the split configuration. + /// Array of rules that define the split configuration behavior. + /// Unique identifier of the split configuration. + [JsonConstructor] + public SplitConfiguration(string description, List rules, Option splitConfigurationId = default) + { + Description = description; + Rules = rules; + _SplitConfigurationIdOption = splitConfigurationId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitConfiguration() + { + } + + partial void OnCreated(); + + /// + /// Your description for the split configuration. + /// + /// Your description for the split configuration. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// Array of rules that define the split configuration behavior. + /// + /// Array of rules that define the split configuration behavior. + [JsonPropertyName("rules")] + public List Rules { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationIdOption { get; } + + /// + /// Unique identifier of the split configuration. + /// + /// Unique identifier of the split configuration. + [JsonPropertyName("splitConfigurationId")] + public string? SplitConfigurationId { get { return this._SplitConfigurationIdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitConfiguration {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Rules: ").Append(Rules).Append("\n"); + sb.Append(" SplitConfigurationId: ").Append(SplitConfigurationId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option?> rules = default; + Option splitConfigurationId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "rules": + rules = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "splitConfigurationId": + splitConfigurationId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!description.IsSet) + throw new ArgumentException("Property is required for class SplitConfiguration.", nameof(description)); + + if (!rules.IsSet) + throw new ArgumentException("Property is required for class SplitConfiguration.", nameof(rules)); + + return new SplitConfiguration(description.Value!, rules.Value!, splitConfigurationId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitConfiguration splitConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitConfiguration splitConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (splitConfiguration.Description != null) + writer.WriteString("description", splitConfiguration.Description); + + writer.WritePropertyName("rules"); + JsonSerializer.Serialize(writer, splitConfiguration.Rules, jsonSerializerOptions); + if (splitConfiguration._SplitConfigurationIdOption.IsSet) + if (splitConfiguration.SplitConfigurationId != null) + writer.WriteString("splitConfigurationId", splitConfiguration.SplitConfigurationId); + } + } +} diff --git a/Adyen/Management/Models/SplitConfigurationList.cs b/Adyen/Management/Models/SplitConfigurationList.cs new file mode 100644 index 000000000..b27a9f401 --- /dev/null +++ b/Adyen/Management/Models/SplitConfigurationList.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SplitConfigurationList. + /// + public partial class SplitConfigurationList : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of split configurations applied to the stores under the merchant account. + [JsonConstructor] + public SplitConfigurationList(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitConfigurationList() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List of split configurations applied to the stores under the merchant account. + /// + /// List of split configurations applied to the stores under the merchant account. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitConfigurationList {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitConfigurationListJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitConfigurationList Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new SplitConfigurationList(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitConfigurationList splitConfigurationList, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitConfigurationList, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitConfigurationList splitConfigurationList, JsonSerializerOptions jsonSerializerOptions) + { + + if (splitConfigurationList._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, splitConfigurationList.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/SplitConfigurationLogic.cs b/Adyen/Management/Models/SplitConfigurationLogic.cs new file mode 100644 index 000000000..0fa5ace94 --- /dev/null +++ b/Adyen/Management/Models/SplitConfigurationLogic.cs @@ -0,0 +1,2071 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SplitConfigurationLogic. + /// + public partial class SplitConfigurationLogic : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// commission + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// additionalCommission + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConstructor] + public SplitConfigurationLogic(Commission commission, Option acquiringFees = default, Option additionalCommission = default, Option adyenCommission = default, Option adyenFees = default, Option adyenMarkup = default, Option chargeback = default, Option chargebackCostAllocation = default, Option interchange = default, Option paymentFee = default, Option refund = default, Option refundCostAllocation = default, Option remainder = default, Option schemeFee = default, Option splitLogicId = default, Option surcharge = default, Option tip = default) + { + Commission = commission; + _AcquiringFeesOption = acquiringFees; + _AdditionalCommissionOption = additionalCommission; + _AdyenCommissionOption = adyenCommission; + _AdyenFeesOption = adyenFees; + _AdyenMarkupOption = adyenMarkup; + _ChargebackOption = chargeback; + _ChargebackCostAllocationOption = chargebackCostAllocation; + _InterchangeOption = interchange; + _PaymentFeeOption = paymentFee; + _RefundOption = refund; + _RefundCostAllocationOption = refundCostAllocation; + _RemainderOption = remainder; + _SchemeFeeOption = schemeFee; + _SplitLogicIdOption = splitLogicId; + _SurchargeOption = surcharge; + _TipOption = tip; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitConfigurationLogic() + { + } + + partial void OnCreated(); + + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AcquiringFeesEnumJsonConverter))] + public class AcquiringFeesEnum : IEnum + { + /// + /// Returns the value of the AcquiringFeesEnum. + /// + public string? Value { get; set; } + + /// + /// AcquiringFeesEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AcquiringFeesEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AcquiringFeesEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AcquiringFeesEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AcquiringFeesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AcquiringFeesEnum?(string? value) => value == null ? null : new AcquiringFeesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AcquiringFeesEnum? option) => option?.Value; + + public static bool operator ==(AcquiringFeesEnum? left, AcquiringFeesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AcquiringFeesEnum? left, AcquiringFeesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AcquiringFeesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AcquiringFeesEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AcquiringFeesEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AcquiringFeesEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AcquiringFeesEnum? value) + { + if (value == null) + return null; + + if (value == AcquiringFeesEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AcquiringFeesEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AcquiringFeesEnum. + /// + public class AcquiringFeesEnumJsonConverter : JsonConverter + { + public override AcquiringFeesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AcquiringFeesEnum.FromStringOrDefault(value) ?? new AcquiringFeesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AcquiringFeesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AcquiringFeesEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquiringFeesOption { get; private set; } + + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("acquiringFees")] + public AcquiringFeesEnum? AcquiringFees { get { return this._AcquiringFeesOption; } set { this._AcquiringFeesOption = new(value); } } + + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenCommissionEnumJsonConverter))] + public class AdyenCommissionEnum : IEnum + { + /// + /// Returns the value of the AdyenCommissionEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenCommissionEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenCommissionEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenCommissionEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenCommissionEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenCommissionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenCommissionEnum?(string? value) => value == null ? null : new AdyenCommissionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenCommissionEnum? option) => option?.Value; + + public static bool operator ==(AdyenCommissionEnum? left, AdyenCommissionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenCommissionEnum? left, AdyenCommissionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenCommissionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenCommissionEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenCommissionEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenCommissionEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenCommissionEnum? value) + { + if (value == null) + return null; + + if (value == AdyenCommissionEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenCommissionEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenCommissionEnum. + /// + public class AdyenCommissionEnumJsonConverter : JsonConverter + { + public override AdyenCommissionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenCommissionEnum.FromStringOrDefault(value) ?? new AdyenCommissionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenCommissionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenCommissionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenCommissionOption { get; private set; } + + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenCommission")] + public AdyenCommissionEnum? AdyenCommission { get { return this._AdyenCommissionOption; } set { this._AdyenCommissionOption = new(value); } } + + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenFeesEnumJsonConverter))] + public class AdyenFeesEnum : IEnum + { + /// + /// Returns the value of the AdyenFeesEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenFeesEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenFeesEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenFeesEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenFeesEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenFeesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenFeesEnum?(string? value) => value == null ? null : new AdyenFeesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenFeesEnum? option) => option?.Value; + + public static bool operator ==(AdyenFeesEnum? left, AdyenFeesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenFeesEnum? left, AdyenFeesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenFeesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenFeesEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenFeesEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenFeesEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenFeesEnum? value) + { + if (value == null) + return null; + + if (value == AdyenFeesEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenFeesEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenFeesEnum. + /// + public class AdyenFeesEnumJsonConverter : JsonConverter + { + public override AdyenFeesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenFeesEnum.FromStringOrDefault(value) ?? new AdyenFeesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenFeesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenFeesEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenFeesOption { get; private set; } + + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenFees")] + public AdyenFeesEnum? AdyenFees { get { return this._AdyenFeesOption; } set { this._AdyenFeesOption = new(value); } } + + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenMarkupEnumJsonConverter))] + public class AdyenMarkupEnum : IEnum + { + /// + /// Returns the value of the AdyenMarkupEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenMarkupEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenMarkupEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenMarkupEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenMarkupEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenMarkupEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenMarkupEnum?(string? value) => value == null ? null : new AdyenMarkupEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenMarkupEnum? option) => option?.Value; + + public static bool operator ==(AdyenMarkupEnum? left, AdyenMarkupEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenMarkupEnum? left, AdyenMarkupEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenMarkupEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenMarkupEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenMarkupEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenMarkupEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenMarkupEnum? value) + { + if (value == null) + return null; + + if (value == AdyenMarkupEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenMarkupEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenMarkupEnum. + /// + public class AdyenMarkupEnumJsonConverter : JsonConverter + { + public override AdyenMarkupEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenMarkupEnum.FromStringOrDefault(value) ?? new AdyenMarkupEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenMarkupEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenMarkupEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenMarkupOption { get; private set; } + + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenMarkup")] + public AdyenMarkupEnum? AdyenMarkup { get { return this._AdyenMarkupOption; } set { this._AdyenMarkupOption = new(value); } } + + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonConverter(typeof(ChargebackEnumJsonConverter))] + public class ChargebackEnum : IEnum + { + /// + /// Returns the value of the ChargebackEnum. + /// + public string? Value { get; set; } + + /// + /// ChargebackEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly ChargebackEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// ChargebackEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly ChargebackEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + /// + /// ChargebackEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly ChargebackEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + private ChargebackEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChargebackEnum?(string? value) => value == null ? null : new ChargebackEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChargebackEnum? option) => option?.Value; + + public static bool operator ==(ChargebackEnum? left, ChargebackEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChargebackEnum? left, ChargebackEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChargebackEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChargebackEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => ChargebackEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => ChargebackEnum.DeductFromOneBalanceAccount, + "deductAccordingToSplitRatio" => ChargebackEnum.DeductAccordingToSplitRatio, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChargebackEnum? value) + { + if (value == null) + return null; + + if (value == ChargebackEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == ChargebackEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + if (value == ChargebackEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + return null; + } + + /// + /// JsonConverter for writing ChargebackEnum. + /// + public class ChargebackEnumJsonConverter : JsonConverter + { + public override ChargebackEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChargebackEnum.FromStringOrDefault(value) ?? new ChargebackEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChargebackEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChargebackEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChargebackOption { get; private set; } + + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonPropertyName("chargeback")] + public ChargebackEnum? Chargeback { get { return this._ChargebackOption; } set { this._ChargebackOption = new(value); } } + + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonConverter(typeof(ChargebackCostAllocationEnumJsonConverter))] + public class ChargebackCostAllocationEnum : IEnum + { + /// + /// Returns the value of the ChargebackCostAllocationEnum. + /// + public string? Value { get; set; } + + /// + /// ChargebackCostAllocationEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly ChargebackCostAllocationEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// ChargebackCostAllocationEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly ChargebackCostAllocationEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private ChargebackCostAllocationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChargebackCostAllocationEnum?(string? value) => value == null ? null : new ChargebackCostAllocationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChargebackCostAllocationEnum? option) => option?.Value; + + public static bool operator ==(ChargebackCostAllocationEnum? left, ChargebackCostAllocationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChargebackCostAllocationEnum? left, ChargebackCostAllocationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChargebackCostAllocationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChargebackCostAllocationEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => ChargebackCostAllocationEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => ChargebackCostAllocationEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChargebackCostAllocationEnum? value) + { + if (value == null) + return null; + + if (value == ChargebackCostAllocationEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == ChargebackCostAllocationEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing ChargebackCostAllocationEnum. + /// + public class ChargebackCostAllocationEnumJsonConverter : JsonConverter + { + public override ChargebackCostAllocationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChargebackCostAllocationEnum.FromStringOrDefault(value) ?? new ChargebackCostAllocationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChargebackCostAllocationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChargebackCostAllocationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChargebackCostAllocationOption { get; private set; } + + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonPropertyName("chargebackCostAllocation")] + public ChargebackCostAllocationEnum? ChargebackCostAllocation { get { return this._ChargebackCostAllocationOption; } set { this._ChargebackCostAllocationOption = new(value); } } + + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(InterchangeEnumJsonConverter))] + public class InterchangeEnum : IEnum + { + /// + /// Returns the value of the InterchangeEnum. + /// + public string? Value { get; set; } + + /// + /// InterchangeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly InterchangeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// InterchangeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly InterchangeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private InterchangeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator InterchangeEnum?(string? value) => value == null ? null : new InterchangeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(InterchangeEnum? option) => option?.Value; + + public static bool operator ==(InterchangeEnum? left, InterchangeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(InterchangeEnum? left, InterchangeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is InterchangeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static InterchangeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => InterchangeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => InterchangeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(InterchangeEnum? value) + { + if (value == null) + return null; + + if (value == InterchangeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == InterchangeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing InterchangeEnum. + /// + public class InterchangeEnumJsonConverter : JsonConverter + { + public override InterchangeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : InterchangeEnum.FromStringOrDefault(value) ?? new InterchangeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, InterchangeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(InterchangeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InterchangeOption { get; private set; } + + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("interchange")] + public InterchangeEnum? Interchange { get { return this._InterchangeOption; } set { this._InterchangeOption = new(value); } } + + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(PaymentFeeEnumJsonConverter))] + public class PaymentFeeEnum : IEnum + { + /// + /// Returns the value of the PaymentFeeEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentFeeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly PaymentFeeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// PaymentFeeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly PaymentFeeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private PaymentFeeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentFeeEnum?(string? value) => value == null ? null : new PaymentFeeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentFeeEnum? option) => option?.Value; + + public static bool operator ==(PaymentFeeEnum? left, PaymentFeeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentFeeEnum? left, PaymentFeeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentFeeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentFeeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => PaymentFeeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => PaymentFeeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentFeeEnum? value) + { + if (value == null) + return null; + + if (value == PaymentFeeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == PaymentFeeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing PaymentFeeEnum. + /// + public class PaymentFeeEnumJsonConverter : JsonConverter + { + public override PaymentFeeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentFeeEnum.FromStringOrDefault(value) ?? new PaymentFeeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentFeeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentFeeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentFeeOption { get; private set; } + + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("paymentFee")] + public PaymentFeeEnum? PaymentFee { get { return this._PaymentFeeOption; } set { this._PaymentFeeOption = new(value); } } + + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + [JsonConverter(typeof(RefundEnumJsonConverter))] + public class RefundEnum : IEnum + { + /// + /// Returns the value of the RefundEnum. + /// + public string? Value { get; set; } + + /// + /// RefundEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly RefundEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// RefundEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly RefundEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + /// + /// RefundEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly RefundEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + private RefundEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RefundEnum?(string? value) => value == null ? null : new RefundEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RefundEnum? option) => option?.Value; + + public static bool operator ==(RefundEnum? left, RefundEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RefundEnum? left, RefundEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RefundEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RefundEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => RefundEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => RefundEnum.DeductFromOneBalanceAccount, + "deductAccordingToSplitRatio" => RefundEnum.DeductAccordingToSplitRatio, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RefundEnum? value) + { + if (value == null) + return null; + + if (value == RefundEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == RefundEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + if (value == RefundEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + return null; + } + + /// + /// JsonConverter for writing RefundEnum. + /// + public class RefundEnumJsonConverter : JsonConverter + { + public override RefundEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RefundEnum.FromStringOrDefault(value) ?? new RefundEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RefundEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RefundEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundOption { get; private set; } + + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + [JsonPropertyName("refund")] + public RefundEnum? Refund { get { return this._RefundOption; } set { this._RefundOption = new(value); } } + + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonConverter(typeof(RefundCostAllocationEnumJsonConverter))] + public class RefundCostAllocationEnum : IEnum + { + /// + /// Returns the value of the RefundCostAllocationEnum. + /// + public string? Value { get; set; } + + /// + /// RefundCostAllocationEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly RefundCostAllocationEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// RefundCostAllocationEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly RefundCostAllocationEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private RefundCostAllocationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RefundCostAllocationEnum?(string? value) => value == null ? null : new RefundCostAllocationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RefundCostAllocationEnum? option) => option?.Value; + + public static bool operator ==(RefundCostAllocationEnum? left, RefundCostAllocationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RefundCostAllocationEnum? left, RefundCostAllocationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RefundCostAllocationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RefundCostAllocationEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => RefundCostAllocationEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => RefundCostAllocationEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RefundCostAllocationEnum? value) + { + if (value == null) + return null; + + if (value == RefundCostAllocationEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == RefundCostAllocationEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing RefundCostAllocationEnum. + /// + public class RefundCostAllocationEnumJsonConverter : JsonConverter + { + public override RefundCostAllocationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RefundCostAllocationEnum.FromStringOrDefault(value) ?? new RefundCostAllocationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RefundCostAllocationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RefundCostAllocationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundCostAllocationOption { get; private set; } + + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonPropertyName("refundCostAllocation")] + public RefundCostAllocationEnum? RefundCostAllocation { get { return this._RefundCostAllocationOption; } set { this._RefundCostAllocationOption = new(value); } } + + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConverter(typeof(RemainderEnumJsonConverter))] + public class RemainderEnum : IEnum + { + /// + /// Returns the value of the RemainderEnum. + /// + public string? Value { get; set; } + + /// + /// RemainderEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly RemainderEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// RemainderEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly RemainderEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private RemainderEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RemainderEnum?(string? value) => value == null ? null : new RemainderEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RemainderEnum? option) => option?.Value; + + public static bool operator ==(RemainderEnum? left, RemainderEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RemainderEnum? left, RemainderEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RemainderEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RemainderEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => RemainderEnum.AddToLiableAccount, + "addToOneBalanceAccount" => RemainderEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RemainderEnum? value) + { + if (value == null) + return null; + + if (value == RemainderEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == RemainderEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing RemainderEnum. + /// + public class RemainderEnumJsonConverter : JsonConverter + { + public override RemainderEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RemainderEnum.FromStringOrDefault(value) ?? new RemainderEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RemainderEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RemainderEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RemainderOption { get; private set; } + + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonPropertyName("remainder")] + public RemainderEnum? Remainder { get { return this._RemainderOption; } set { this._RemainderOption = new(value); } } + + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(SchemeFeeEnumJsonConverter))] + public class SchemeFeeEnum : IEnum + { + /// + /// Returns the value of the SchemeFeeEnum. + /// + public string? Value { get; set; } + + /// + /// SchemeFeeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly SchemeFeeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// SchemeFeeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly SchemeFeeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private SchemeFeeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SchemeFeeEnum?(string? value) => value == null ? null : new SchemeFeeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SchemeFeeEnum? option) => option?.Value; + + public static bool operator ==(SchemeFeeEnum? left, SchemeFeeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SchemeFeeEnum? left, SchemeFeeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SchemeFeeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SchemeFeeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => SchemeFeeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => SchemeFeeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SchemeFeeEnum? value) + { + if (value == null) + return null; + + if (value == SchemeFeeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == SchemeFeeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing SchemeFeeEnum. + /// + public class SchemeFeeEnumJsonConverter : JsonConverter + { + public override SchemeFeeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SchemeFeeEnum.FromStringOrDefault(value) ?? new SchemeFeeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SchemeFeeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SchemeFeeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeFeeOption { get; private set; } + + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("schemeFee")] + public SchemeFeeEnum? SchemeFee { get { return this._SchemeFeeOption; } set { this._SchemeFeeOption = new(value); } } + + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + [JsonConverter(typeof(SurchargeEnumJsonConverter))] + public class SurchargeEnum : IEnum + { + /// + /// Returns the value of the SurchargeEnum. + /// + public string? Value { get; set; } + + /// + /// SurchargeEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly SurchargeEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// SurchargeEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly SurchargeEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private SurchargeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SurchargeEnum?(string? value) => value == null ? null : new SurchargeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SurchargeEnum? option) => option?.Value; + + public static bool operator ==(SurchargeEnum? left, SurchargeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SurchargeEnum? left, SurchargeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SurchargeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SurchargeEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => SurchargeEnum.AddToLiableAccount, + "addToOneBalanceAccount" => SurchargeEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SurchargeEnum? value) + { + if (value == null) + return null; + + if (value == SurchargeEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == SurchargeEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing SurchargeEnum. + /// + public class SurchargeEnumJsonConverter : JsonConverter + { + public override SurchargeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SurchargeEnum.FromStringOrDefault(value) ?? new SurchargeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SurchargeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SurchargeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SurchargeOption { get; private set; } + + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + [JsonPropertyName("surcharge")] + public SurchargeEnum? Surcharge { get { return this._SurchargeOption; } set { this._SurchargeOption = new(value); } } + + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConverter(typeof(TipEnumJsonConverter))] + public class TipEnum : IEnum + { + /// + /// Returns the value of the TipEnum. + /// + public string? Value { get; set; } + + /// + /// TipEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly TipEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// TipEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly TipEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private TipEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TipEnum?(string? value) => value == null ? null : new TipEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TipEnum? option) => option?.Value; + + public static bool operator ==(TipEnum? left, TipEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TipEnum? left, TipEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TipEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TipEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => TipEnum.AddToLiableAccount, + "addToOneBalanceAccount" => TipEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TipEnum? value) + { + if (value == null) + return null; + + if (value == TipEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == TipEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing TipEnum. + /// + public class TipEnumJsonConverter : JsonConverter + { + public override TipEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TipEnum.FromStringOrDefault(value) ?? new TipEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TipEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TipEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TipOption { get; private set; } + + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonPropertyName("tip")] + public TipEnum? Tip { get { return this._TipOption; } set { this._TipOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("commission")] + public Commission Commission { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalCommissionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalCommission")] + public AdditionalCommission? AdditionalCommission { get { return this._AdditionalCommissionOption; } set { this._AdditionalCommissionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitLogicIdOption { get; } + + /// + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + /// + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + [JsonPropertyName("splitLogicId")] + public string? SplitLogicId { get { return this._SplitLogicIdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitConfigurationLogic {\n"); + sb.Append(" Commission: ").Append(Commission).Append("\n"); + sb.Append(" AcquiringFees: ").Append(AcquiringFees).Append("\n"); + sb.Append(" AdditionalCommission: ").Append(AdditionalCommission).Append("\n"); + sb.Append(" AdyenCommission: ").Append(AdyenCommission).Append("\n"); + sb.Append(" AdyenFees: ").Append(AdyenFees).Append("\n"); + sb.Append(" AdyenMarkup: ").Append(AdyenMarkup).Append("\n"); + sb.Append(" Chargeback: ").Append(Chargeback).Append("\n"); + sb.Append(" ChargebackCostAllocation: ").Append(ChargebackCostAllocation).Append("\n"); + sb.Append(" Interchange: ").Append(Interchange).Append("\n"); + sb.Append(" PaymentFee: ").Append(PaymentFee).Append("\n"); + sb.Append(" Refund: ").Append(Refund).Append("\n"); + sb.Append(" RefundCostAllocation: ").Append(RefundCostAllocation).Append("\n"); + sb.Append(" Remainder: ").Append(Remainder).Append("\n"); + sb.Append(" SchemeFee: ").Append(SchemeFee).Append("\n"); + sb.Append(" SplitLogicId: ").Append(SplitLogicId).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" Tip: ").Append(Tip).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitConfigurationLogicJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitConfigurationLogic Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option commission = default; + Option acquiringFees = default; + Option additionalCommission = default; + Option adyenCommission = default; + Option adyenFees = default; + Option adyenMarkup = default; + Option chargeback = default; + Option chargebackCostAllocation = default; + Option interchange = default; + Option paymentFee = default; + Option refund = default; + Option refundCostAllocation = default; + Option remainder = default; + Option schemeFee = default; + Option splitLogicId = default; + Option surcharge = default; + Option tip = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "commission": + commission = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acquiringFees": + string? acquiringFeesRawValue = utf8JsonReader.GetString(); + acquiringFees = new Option(SplitConfigurationLogic.AcquiringFeesEnum.FromStringOrDefault(acquiringFeesRawValue)); + break; + case "additionalCommission": + additionalCommission = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "adyenCommission": + string? adyenCommissionRawValue = utf8JsonReader.GetString(); + adyenCommission = new Option(SplitConfigurationLogic.AdyenCommissionEnum.FromStringOrDefault(adyenCommissionRawValue)); + break; + case "adyenFees": + string? adyenFeesRawValue = utf8JsonReader.GetString(); + adyenFees = new Option(SplitConfigurationLogic.AdyenFeesEnum.FromStringOrDefault(adyenFeesRawValue)); + break; + case "adyenMarkup": + string? adyenMarkupRawValue = utf8JsonReader.GetString(); + adyenMarkup = new Option(SplitConfigurationLogic.AdyenMarkupEnum.FromStringOrDefault(adyenMarkupRawValue)); + break; + case "chargeback": + string? chargebackRawValue = utf8JsonReader.GetString(); + chargeback = new Option(SplitConfigurationLogic.ChargebackEnum.FromStringOrDefault(chargebackRawValue)); + break; + case "chargebackCostAllocation": + string? chargebackCostAllocationRawValue = utf8JsonReader.GetString(); + chargebackCostAllocation = new Option(SplitConfigurationLogic.ChargebackCostAllocationEnum.FromStringOrDefault(chargebackCostAllocationRawValue)); + break; + case "interchange": + string? interchangeRawValue = utf8JsonReader.GetString(); + interchange = new Option(SplitConfigurationLogic.InterchangeEnum.FromStringOrDefault(interchangeRawValue)); + break; + case "paymentFee": + string? paymentFeeRawValue = utf8JsonReader.GetString(); + paymentFee = new Option(SplitConfigurationLogic.PaymentFeeEnum.FromStringOrDefault(paymentFeeRawValue)); + break; + case "refund": + string? refundRawValue = utf8JsonReader.GetString(); + refund = new Option(SplitConfigurationLogic.RefundEnum.FromStringOrDefault(refundRawValue)); + break; + case "refundCostAllocation": + string? refundCostAllocationRawValue = utf8JsonReader.GetString(); + refundCostAllocation = new Option(SplitConfigurationLogic.RefundCostAllocationEnum.FromStringOrDefault(refundCostAllocationRawValue)); + break; + case "remainder": + string? remainderRawValue = utf8JsonReader.GetString(); + remainder = new Option(SplitConfigurationLogic.RemainderEnum.FromStringOrDefault(remainderRawValue)); + break; + case "schemeFee": + string? schemeFeeRawValue = utf8JsonReader.GetString(); + schemeFee = new Option(SplitConfigurationLogic.SchemeFeeEnum.FromStringOrDefault(schemeFeeRawValue)); + break; + case "splitLogicId": + splitLogicId = new Option(utf8JsonReader.GetString()!); + break; + case "surcharge": + string? surchargeRawValue = utf8JsonReader.GetString(); + surcharge = new Option(SplitConfigurationLogic.SurchargeEnum.FromStringOrDefault(surchargeRawValue)); + break; + case "tip": + string? tipRawValue = utf8JsonReader.GetString(); + tip = new Option(SplitConfigurationLogic.TipEnum.FromStringOrDefault(tipRawValue)); + break; + default: + break; + } + } + } + + if (!commission.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationLogic.", nameof(commission)); + + return new SplitConfigurationLogic(commission.Value!, acquiringFees, additionalCommission, adyenCommission, adyenFees, adyenMarkup, chargeback, chargebackCostAllocation, interchange, paymentFee, refund, refundCostAllocation, remainder, schemeFee, splitLogicId, surcharge, tip); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitConfigurationLogic splitConfigurationLogic, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitConfigurationLogic, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitConfigurationLogic splitConfigurationLogic, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("commission"); + JsonSerializer.Serialize(writer, splitConfigurationLogic.Commission, jsonSerializerOptions); + if (splitConfigurationLogic._AcquiringFeesOption.IsSet && splitConfigurationLogic.AcquiringFees != null) + { + string? acquiringFeesRawValue = SplitConfigurationLogic.AcquiringFeesEnum.ToJsonValue(splitConfigurationLogic._AcquiringFeesOption.Value!.Value); + writer.WriteString("acquiringFees", acquiringFeesRawValue); + } + + if (splitConfigurationLogic._AdditionalCommissionOption.IsSet) + { + writer.WritePropertyName("additionalCommission"); + JsonSerializer.Serialize(writer, splitConfigurationLogic.AdditionalCommission, jsonSerializerOptions); + } + if (splitConfigurationLogic._AdyenCommissionOption.IsSet && splitConfigurationLogic.AdyenCommission != null) + { + string? adyenCommissionRawValue = SplitConfigurationLogic.AdyenCommissionEnum.ToJsonValue(splitConfigurationLogic._AdyenCommissionOption.Value!.Value); + writer.WriteString("adyenCommission", adyenCommissionRawValue); + } + + if (splitConfigurationLogic._AdyenFeesOption.IsSet && splitConfigurationLogic.AdyenFees != null) + { + string? adyenFeesRawValue = SplitConfigurationLogic.AdyenFeesEnum.ToJsonValue(splitConfigurationLogic._AdyenFeesOption.Value!.Value); + writer.WriteString("adyenFees", adyenFeesRawValue); + } + + if (splitConfigurationLogic._AdyenMarkupOption.IsSet && splitConfigurationLogic.AdyenMarkup != null) + { + string? adyenMarkupRawValue = SplitConfigurationLogic.AdyenMarkupEnum.ToJsonValue(splitConfigurationLogic._AdyenMarkupOption.Value!.Value); + writer.WriteString("adyenMarkup", adyenMarkupRawValue); + } + + if (splitConfigurationLogic._ChargebackOption.IsSet && splitConfigurationLogic.Chargeback != null) + { + string? chargebackRawValue = SplitConfigurationLogic.ChargebackEnum.ToJsonValue(splitConfigurationLogic._ChargebackOption.Value!.Value); + writer.WriteString("chargeback", chargebackRawValue); + } + + if (splitConfigurationLogic._ChargebackCostAllocationOption.IsSet && splitConfigurationLogic.ChargebackCostAllocation != null) + { + string? chargebackCostAllocationRawValue = SplitConfigurationLogic.ChargebackCostAllocationEnum.ToJsonValue(splitConfigurationLogic._ChargebackCostAllocationOption.Value!.Value); + writer.WriteString("chargebackCostAllocation", chargebackCostAllocationRawValue); + } + + if (splitConfigurationLogic._InterchangeOption.IsSet && splitConfigurationLogic.Interchange != null) + { + string? interchangeRawValue = SplitConfigurationLogic.InterchangeEnum.ToJsonValue(splitConfigurationLogic._InterchangeOption.Value!.Value); + writer.WriteString("interchange", interchangeRawValue); + } + + if (splitConfigurationLogic._PaymentFeeOption.IsSet && splitConfigurationLogic.PaymentFee != null) + { + string? paymentFeeRawValue = SplitConfigurationLogic.PaymentFeeEnum.ToJsonValue(splitConfigurationLogic._PaymentFeeOption.Value!.Value); + writer.WriteString("paymentFee", paymentFeeRawValue); + } + + if (splitConfigurationLogic._RefundOption.IsSet && splitConfigurationLogic.Refund != null) + { + string? refundRawValue = SplitConfigurationLogic.RefundEnum.ToJsonValue(splitConfigurationLogic._RefundOption.Value!.Value); + writer.WriteString("refund", refundRawValue); + } + + if (splitConfigurationLogic._RefundCostAllocationOption.IsSet && splitConfigurationLogic.RefundCostAllocation != null) + { + string? refundCostAllocationRawValue = SplitConfigurationLogic.RefundCostAllocationEnum.ToJsonValue(splitConfigurationLogic._RefundCostAllocationOption.Value!.Value); + writer.WriteString("refundCostAllocation", refundCostAllocationRawValue); + } + + if (splitConfigurationLogic._RemainderOption.IsSet && splitConfigurationLogic.Remainder != null) + { + string? remainderRawValue = SplitConfigurationLogic.RemainderEnum.ToJsonValue(splitConfigurationLogic._RemainderOption.Value!.Value); + writer.WriteString("remainder", remainderRawValue); + } + + if (splitConfigurationLogic._SchemeFeeOption.IsSet && splitConfigurationLogic.SchemeFee != null) + { + string? schemeFeeRawValue = SplitConfigurationLogic.SchemeFeeEnum.ToJsonValue(splitConfigurationLogic._SchemeFeeOption.Value!.Value); + writer.WriteString("schemeFee", schemeFeeRawValue); + } + + if (splitConfigurationLogic._SplitLogicIdOption.IsSet) + if (splitConfigurationLogic.SplitLogicId != null) + writer.WriteString("splitLogicId", splitConfigurationLogic.SplitLogicId); + + if (splitConfigurationLogic._SurchargeOption.IsSet && splitConfigurationLogic.Surcharge != null) + { + string? surchargeRawValue = SplitConfigurationLogic.SurchargeEnum.ToJsonValue(splitConfigurationLogic._SurchargeOption.Value!.Value); + writer.WriteString("surcharge", surchargeRawValue); + } + + if (splitConfigurationLogic._TipOption.IsSet && splitConfigurationLogic.Tip != null) + { + string? tipRawValue = SplitConfigurationLogic.TipEnum.ToJsonValue(splitConfigurationLogic._TipOption.Value!.Value); + writer.WriteString("tip", tipRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/SplitConfigurationRule.cs b/Adyen/Management/Models/SplitConfigurationRule.cs new file mode 100644 index 000000000..1b62d0a2f --- /dev/null +++ b/Adyen/Management/Models/SplitConfigurationRule.cs @@ -0,0 +1,709 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SplitConfigurationRule. + /// + public partial class SplitConfigurationRule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + /// splitLogic + /// The card region condition that determines whether the [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic) applies to the transaction. > This condition is in pilot phase, and not yet available for all platforms. Possible values: * **domestic**: The card issuer and the store where the transaction is processed are registered in the same country. * **international**: The card issuer and the store where the transaction is processed are registered in different countries or regions. Includes all **interRegional** and **intraRegional** transactions. * **interRegional**: The card issuer and the store where the transaction is processed are registered in different regions. * **intraRegional**: The card issuer and the store where the transaction is processed are registered in different countries, but in the same region. * **ANY**: Applies to all transactions, regardless of the processing and issuing country/region. + /// The unique identifier of the split configuration rule. + [JsonConstructor] + public SplitConfigurationRule(string currency, FundingSourceEnum fundingSource, string paymentMethod, ShopperInteractionEnum shopperInteraction, SplitConfigurationLogic splitLogic, Option cardRegion = default, Option ruleId = default) + { + Currency = currency; + FundingSource = fundingSource; + PaymentMethod = paymentMethod; + ShopperInteraction = shopperInteraction; + SplitLogic = splitLogic; + _CardRegionOption = cardRegion; + _RuleIdOption = ruleId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitConfigurationRule() + { + } + + partial void OnCreated(); + + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Charged - charged + /// + public static readonly FundingSourceEnum Charged = new("charged"); + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + /// + /// FundingSourceEnum.DeferredDebit - deferred_debit + /// + public static readonly FundingSourceEnum DeferredDebit = new("deferred_debit"); + + /// + /// FundingSourceEnum.Prepaid - prepaid + /// + public static readonly FundingSourceEnum Prepaid = new("prepaid"); + + /// + /// FundingSourceEnum.ANY - ANY + /// + public static readonly FundingSourceEnum ANY = new("ANY"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "charged" => FundingSourceEnum.Charged, + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + "deferred_debit" => FundingSourceEnum.DeferredDebit, + "prepaid" => FundingSourceEnum.Prepaid, + "ANY" => FundingSourceEnum.ANY, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Charged) + return "charged"; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + if (value == FundingSourceEnum.DeferredDebit) + return "deferred_debit"; + + if (value == FundingSourceEnum.Prepaid) + return "prepaid"; + + if (value == FundingSourceEnum.ANY) + return "ANY"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + [JsonPropertyName("fundingSource")] + public FundingSourceEnum FundingSource { get; set; } + + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + /// + /// ShopperInteractionEnum.ANY - ANY + /// + public static readonly ShopperInteractionEnum ANY = new("ANY"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + "ANY" => ShopperInteractionEnum.ANY, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + if (value == ShopperInteractionEnum.ANY) + return "ANY"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum ShopperInteraction { get; set; } + + /// + /// The card region condition that determines whether the [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic) applies to the transaction. > This condition is in pilot phase, and not yet available for all platforms. Possible values: * **domestic**: The card issuer and the store where the transaction is processed are registered in the same country. * **international**: The card issuer and the store where the transaction is processed are registered in different countries or regions. Includes all **interRegional** and **intraRegional** transactions. * **interRegional**: The card issuer and the store where the transaction is processed are registered in different regions. * **intraRegional**: The card issuer and the store where the transaction is processed are registered in different countries, but in the same region. * **ANY**: Applies to all transactions, regardless of the processing and issuing country/region. + /// + /// The card region condition that determines whether the [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic) applies to the transaction. > This condition is in pilot phase, and not yet available for all platforms. Possible values: * **domestic**: The card issuer and the store where the transaction is processed are registered in the same country. * **international**: The card issuer and the store where the transaction is processed are registered in different countries or regions. Includes all **interRegional** and **intraRegional** transactions. * **interRegional**: The card issuer and the store where the transaction is processed are registered in different regions. * **intraRegional**: The card issuer and the store where the transaction is processed are registered in different countries, but in the same region. * **ANY**: Applies to all transactions, regardless of the processing and issuing country/region. + [JsonConverter(typeof(CardRegionEnumJsonConverter))] + public class CardRegionEnum : IEnum + { + /// + /// Returns the value of the CardRegionEnum. + /// + public string? Value { get; set; } + + /// + /// CardRegionEnum.International - international + /// + public static readonly CardRegionEnum International = new("international"); + + /// + /// CardRegionEnum.IntraRegional - intraRegional + /// + public static readonly CardRegionEnum IntraRegional = new("intraRegional"); + + /// + /// CardRegionEnum.InterRegional - interRegional + /// + public static readonly CardRegionEnum InterRegional = new("interRegional"); + + /// + /// CardRegionEnum.Domestic - domestic + /// + public static readonly CardRegionEnum Domestic = new("domestic"); + + /// + /// CardRegionEnum.ANY - ANY + /// + public static readonly CardRegionEnum ANY = new("ANY"); + + private CardRegionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CardRegionEnum?(string? value) => value == null ? null : new CardRegionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CardRegionEnum? option) => option?.Value; + + public static bool operator ==(CardRegionEnum? left, CardRegionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CardRegionEnum? left, CardRegionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CardRegionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CardRegionEnum? FromStringOrDefault(string value) + { + return value switch { + "international" => CardRegionEnum.International, + "intraRegional" => CardRegionEnum.IntraRegional, + "interRegional" => CardRegionEnum.InterRegional, + "domestic" => CardRegionEnum.Domestic, + "ANY" => CardRegionEnum.ANY, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CardRegionEnum? value) + { + if (value == null) + return null; + + if (value == CardRegionEnum.International) + return "international"; + + if (value == CardRegionEnum.IntraRegional) + return "intraRegional"; + + if (value == CardRegionEnum.InterRegional) + return "interRegional"; + + if (value == CardRegionEnum.Domestic) + return "domestic"; + + if (value == CardRegionEnum.ANY) + return "ANY"; + + return null; + } + + /// + /// JsonConverter for writing CardRegionEnum. + /// + public class CardRegionEnumJsonConverter : JsonConverter + { + public override CardRegionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CardRegionEnum.FromStringOrDefault(value) ?? new CardRegionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CardRegionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CardRegionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardRegionOption { get; private set; } + + /// + /// The card region condition that determines whether the [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic) applies to the transaction. > This condition is in pilot phase, and not yet available for all platforms. Possible values: * **domestic**: The card issuer and the store where the transaction is processed are registered in the same country. * **international**: The card issuer and the store where the transaction is processed are registered in different countries or regions. Includes all **interRegional** and **intraRegional** transactions. * **interRegional**: The card issuer and the store where the transaction is processed are registered in different regions. * **intraRegional**: The card issuer and the store where the transaction is processed are registered in different countries, but in the same region. * **ANY**: Applies to all transactions, regardless of the processing and issuing country/region. + /// + /// The card region condition that determines whether the [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic) applies to the transaction. > This condition is in pilot phase, and not yet available for all platforms. Possible values: * **domestic**: The card issuer and the store where the transaction is processed are registered in the same country. * **international**: The card issuer and the store where the transaction is processed are registered in different countries or regions. Includes all **interRegional** and **intraRegional** transactions. * **interRegional**: The card issuer and the store where the transaction is processed are registered in different regions. * **intraRegional**: The card issuer and the store where the transaction is processed are registered in different countries, but in the same region. * **ANY**: Applies to all transactions, regardless of the processing and issuing country/region. + [JsonPropertyName("cardRegion")] + public CardRegionEnum? CardRegion { get { return this._CardRegionOption; } set { this._CardRegionOption = new(value); } } + + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + /// + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + [JsonPropertyName("paymentMethod")] + public string PaymentMethod { get; set; } + + /// + /// . + /// + [JsonPropertyName("splitLogic")] + public SplitConfigurationLogic SplitLogic { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RuleIdOption { get; } + + /// + /// The unique identifier of the split configuration rule. + /// + /// The unique identifier of the split configuration rule. + [JsonPropertyName("ruleId")] + public string? RuleId { get { return this._RuleIdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitConfigurationRule {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" SplitLogic: ").Append(SplitLogic).Append("\n"); + sb.Append(" CardRegion: ").Append(CardRegion).Append("\n"); + sb.Append(" RuleId: ").Append(RuleId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitConfigurationRuleJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitConfigurationRule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option fundingSource = default; + Option paymentMethod = default; + Option shopperInteraction = default; + Option splitLogic = default; + Option cardRegion = default; + Option ruleId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(SplitConfigurationRule.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(SplitConfigurationRule.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "splitLogic": + splitLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardRegion": + string? cardRegionRawValue = utf8JsonReader.GetString(); + cardRegion = new Option(SplitConfigurationRule.CardRegionEnum.FromStringOrDefault(cardRegionRawValue)); + break; + case "ruleId": + ruleId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationRule.", nameof(currency)); + + if (!fundingSource.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationRule.", nameof(fundingSource)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationRule.", nameof(paymentMethod)); + + if (!shopperInteraction.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationRule.", nameof(shopperInteraction)); + + if (!splitLogic.IsSet) + throw new ArgumentException("Property is required for class SplitConfigurationRule.", nameof(splitLogic)); + + return new SplitConfigurationRule(currency.Value!, fundingSource.Value!.Value!, paymentMethod.Value!, shopperInteraction.Value!.Value!, splitLogic.Value!, cardRegion, ruleId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitConfigurationRule splitConfigurationRule, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitConfigurationRule, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitConfigurationRule splitConfigurationRule, JsonSerializerOptions jsonSerializerOptions) + { + + if (splitConfigurationRule.Currency != null) + writer.WriteString("currency", splitConfigurationRule.Currency); + + if (splitConfigurationRule.FundingSource != null) + { + string? fundingSourceRawValue = SplitConfigurationRule.FundingSourceEnum.ToJsonValue(splitConfigurationRule.FundingSource); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (splitConfigurationRule.PaymentMethod != null) + writer.WriteString("paymentMethod", splitConfigurationRule.PaymentMethod); + + if (splitConfigurationRule.ShopperInteraction != null) + { + string? shopperInteractionRawValue = SplitConfigurationRule.ShopperInteractionEnum.ToJsonValue(splitConfigurationRule.ShopperInteraction); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + writer.WritePropertyName("splitLogic"); + JsonSerializer.Serialize(writer, splitConfigurationRule.SplitLogic, jsonSerializerOptions); + if (splitConfigurationRule._CardRegionOption.IsSet && splitConfigurationRule.CardRegion != null) + { + string? cardRegionRawValue = SplitConfigurationRule.CardRegionEnum.ToJsonValue(splitConfigurationRule._CardRegionOption.Value!.Value); + writer.WriteString("cardRegion", cardRegionRawValue); + } + + if (splitConfigurationRule._RuleIdOption.IsSet) + if (splitConfigurationRule.RuleId != null) + writer.WriteString("ruleId", splitConfigurationRule.RuleId); + } + } +} diff --git a/Adyen/Management/Models/Standalone.cs b/Adyen/Management/Models/Standalone.cs new file mode 100644 index 000000000..45cb52403 --- /dev/null +++ b/Adyen/Management/Models/Standalone.cs @@ -0,0 +1,237 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Standalone. + /// + public partial class Standalone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The default currency of the standalone payment terminal as an [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + /// Indicates whether the tipping options specified in `gratuities` are enabled on the standalone terminal. + /// Enable standalone mode. + [JsonConstructor] + public Standalone(Option currencyCode = default, Option enableGratuities = default, Option enableStandalone = default) + { + _CurrencyCodeOption = currencyCode; + _EnableGratuitiesOption = enableGratuities; + _EnableStandaloneOption = enableStandalone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Standalone() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyCodeOption { get; private set; } + + /// + /// The default currency of the standalone payment terminal as an [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + /// + /// The default currency of the standalone payment terminal as an [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code. + [JsonPropertyName("currencyCode")] + public string? CurrencyCode { get { return this._CurrencyCodeOption; } set { this._CurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableGratuitiesOption { get; private set; } + + /// + /// Indicates whether the tipping options specified in `gratuities` are enabled on the standalone terminal. + /// + /// Indicates whether the tipping options specified in `gratuities` are enabled on the standalone terminal. + [JsonPropertyName("enableGratuities")] + public bool? EnableGratuities { get { return this._EnableGratuitiesOption; } set { this._EnableGratuitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableStandaloneOption { get; private set; } + + /// + /// Enable standalone mode. + /// + /// Enable standalone mode. + [JsonPropertyName("enableStandalone")] + public bool? EnableStandalone { get { return this._EnableStandaloneOption; } set { this._EnableStandaloneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Standalone {\n"); + sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); + sb.Append(" EnableGratuities: ").Append(EnableGratuities).Append("\n"); + sb.Append(" EnableStandalone: ").Append(EnableStandalone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CurrencyCode (string) maxLength + if (this.CurrencyCode != null && this.CurrencyCode.Length > 3) + { + yield return new ValidationResult("Invalid value for CurrencyCode, length must be less than 3.", new [] { "CurrencyCode" }); + } + + // CurrencyCode (string) minLength + if (this.CurrencyCode != null && this.CurrencyCode.Length < 3) + { + yield return new ValidationResult("Invalid value for CurrencyCode, length must be greater than 3.", new [] { "CurrencyCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StandaloneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Standalone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currencyCode = default; + Option enableGratuities = default; + Option enableStandalone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currencyCode": + currencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "enableGratuities": + enableGratuities = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enableStandalone": + enableStandalone = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Standalone(currencyCode, enableGratuities, enableStandalone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Standalone standalone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, standalone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Standalone standalone, JsonSerializerOptions jsonSerializerOptions) + { + + if (standalone._CurrencyCodeOption.IsSet) + if (standalone.CurrencyCode != null) + writer.WriteString("currencyCode", standalone.CurrencyCode); + + if (standalone._EnableGratuitiesOption.IsSet) + writer.WriteBoolean("enableGratuities", standalone._EnableGratuitiesOption.Value!.Value); + + if (standalone._EnableStandaloneOption.IsSet) + writer.WriteBoolean("enableStandalone", standalone._EnableStandaloneOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/StarInfo.cs b/Adyen/Management/Models/StarInfo.cs new file mode 100644 index 000000000..1232753d8 --- /dev/null +++ b/Adyen/Management/Models/StarInfo.cs @@ -0,0 +1,313 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StarInfo. + /// + public partial class StarInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// transactionDescription + [JsonConstructor] + public StarInfo(ProcessingTypeEnum processingType, Option transactionDescription = default) + { + ProcessingType = processingType; + _TransactionDescriptionOption = transactionDescription; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StarInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.Billpay - billpay + /// + public static readonly ProcessingTypeEnum Billpay = new("billpay"); + + /// + /// ProcessingTypeEnum.Ecom - ecom + /// + public static readonly ProcessingTypeEnum Ecom = new("ecom"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "billpay" => ProcessingTypeEnum.Billpay, + "ecom" => ProcessingTypeEnum.Ecom, + "pos" => ProcessingTypeEnum.Pos, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.Billpay) + return "billpay"; + + if (value == ProcessingTypeEnum.Ecom) + return "ecom"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + /// + /// The type of transactions processed over this payment method. Allowed values: - **pos** for in-person payments. - **billpay** for subscription payments, both the initial payment and the later recurring payments. These transactions have `recurringProcessingModel` **Subscription**. - **ecom** for all other card not present transactions. This includes non-recurring transactions and transactions with `recurringProcessingModel` **CardOnFile** or **UnscheduledCardOnFile**. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum ProcessingType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionDescriptionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionDescription")] + public TransactionDescriptionInfo? TransactionDescription { get { return this._TransactionDescriptionOption; } set { this._TransactionDescriptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StarInfo {\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" TransactionDescription: ").Append(TransactionDescription).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StarInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StarInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option processingType = default; + Option transactionDescription = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(StarInfo.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "transactionDescription": + transactionDescription = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!processingType.IsSet) + throw new ArgumentException("Property is required for class StarInfo.", nameof(processingType)); + + return new StarInfo(processingType.Value!.Value!, transactionDescription); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StarInfo starInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, starInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StarInfo starInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (starInfo.ProcessingType != null) + { + string? processingTypeRawValue = StarInfo.ProcessingTypeEnum.ToJsonValue(starInfo.ProcessingType); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (starInfo._TransactionDescriptionOption.IsSet) + { + writer.WritePropertyName("transactionDescription"); + JsonSerializer.Serialize(writer, starInfo.TransactionDescription, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/Store.cs b/Adyen/Management/Models/Store.cs new file mode 100644 index 000000000..2ac68be73 --- /dev/null +++ b/Adyen/Management/Models/Store.cs @@ -0,0 +1,594 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Store. + /// + public partial class Store : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// address + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businesslines__resParam_id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// The description of the store. + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// The unique identifier of the store. This value is generated by Adyen. + /// The unique identifier of the merchant account that the store belongs to. + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// A reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_) + /// The store name shown on the shopper's bank or credit card statement and on the shopper receipt. + /// splitConfiguration + /// The status of the store. Possible values are: - **active**. This value is assigned automatically when a store is created. - **inactive**. The terminals under the store are blocked from accepting new transactions, but capturing outstanding transactions is still possible. - **closed**. This status is irreversible. The terminals under the store are reassigned to the merchant inventory. + /// subMerchantData + [JsonConstructor] + public Store(Option links = default, Option address = default, Option?> businessLineIds = default, Option description = default, Option externalReferenceId = default, Option id = default, Option merchantId = default, Option phoneNumber = default, Option reference = default, Option shopperStatement = default, Option splitConfiguration = default, Option status = default, Option subMerchantData = default) + { + _LinksOption = links; + _AddressOption = address; + _BusinessLineIdsOption = businessLineIds; + _DescriptionOption = description; + _ExternalReferenceIdOption = externalReferenceId; + _IdOption = id; + _MerchantIdOption = merchantId; + _PhoneNumberOption = phoneNumber; + _ReferenceOption = reference; + _ShopperStatementOption = shopperStatement; + _SplitConfigurationOption = splitConfiguration; + _StatusOption = status; + _SubMerchantDataOption = subMerchantData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Store() + { + } + + partial void OnCreated(); + + /// + /// The status of the store. Possible values are: - **active**. This value is assigned automatically when a store is created. - **inactive**. The terminals under the store are blocked from accepting new transactions, but capturing outstanding transactions is still possible. - **closed**. This status is irreversible. The terminals under the store are reassigned to the merchant inventory. + /// + /// The status of the store. Possible values are: - **active**. This value is assigned automatically when a store is created. - **inactive**. The terminals under the store are blocked from accepting new transactions, but capturing outstanding transactions is still possible. - **closed**. This status is irreversible. The terminals under the store are reassigned to the merchant inventory. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the store. Possible values are: - **active**. This value is assigned automatically when a store is created. - **inactive**. The terminals under the store are blocked from accepting new transactions, but capturing outstanding transactions is still possible. - **closed**. This status is irreversible. The terminals under the store are reassigned to the merchant inventory. + /// + /// The status of the store. Possible values are: - **active**. This value is assigned automatically when a store is created. - **inactive**. The terminals under the store are blocked from accepting new transactions, but capturing outstanding transactions is still possible. - **closed**. This status is irreversible. The terminals under the store are reassigned to the merchant inventory. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public StoreLocation? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BusinessLineIdsOption { get; private set; } + + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businesslines__resParam_id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businesslines__resParam_id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + [JsonPropertyName("businessLineIds")] + public List? BusinessLineIds { get { return this._BusinessLineIdsOption; } set { this._BusinessLineIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the store. + /// + /// The description of the store. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReferenceIdOption { get; private set; } + + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + [JsonPropertyName("externalReferenceId")] + public string? ExternalReferenceId { get { return this._ExternalReferenceIdOption; } set { this._ExternalReferenceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the store. This value is generated by Adyen. + /// + /// The unique identifier of the store. This value is generated by Adyen. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account that the store belongs to. + /// + /// The unique identifier of the merchant account that the store belongs to. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_) + /// + /// A reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_) + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The store name shown on the shopper's bank or credit card statement and on the shopper receipt. + /// + /// The store name shown on the shopper's bank or credit card statement and on the shopper receipt. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("splitConfiguration")] + public StoreSplitConfiguration? SplitConfiguration { get { return this._SplitConfigurationOption; } set { this._SplitConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchantData")] + public SubMerchantData? SubMerchantData { get { return this._SubMerchantDataOption; } set { this._SubMerchantDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Store {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" BusinessLineIds: ").Append(BusinessLineIds).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExternalReferenceId: ").Append(ExternalReferenceId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SplitConfiguration: ").Append(SplitConfiguration).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SubMerchantData: ").Append(SubMerchantData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Store Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option address = default; + Option?> businessLineIds = default; + Option description = default; + Option externalReferenceId = default; + Option id = default; + Option merchantId = default; + Option phoneNumber = default; + Option reference = default; + Option shopperStatement = default; + Option splitConfiguration = default; + Option status = default; + Option subMerchantData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "businessLineIds": + businessLineIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "externalReferenceId": + externalReferenceId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "splitConfiguration": + splitConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Store.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "subMerchantData": + subMerchantData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Store(links, address, businessLineIds, description, externalReferenceId, id, merchantId, phoneNumber, reference, shopperStatement, splitConfiguration, status, subMerchantData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Store store, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, store, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Store store, JsonSerializerOptions jsonSerializerOptions) + { + + if (store._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, store.Links, jsonSerializerOptions); + } + if (store._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, store.Address, jsonSerializerOptions); + } + if (store._BusinessLineIdsOption.IsSet) + { + writer.WritePropertyName("businessLineIds"); + JsonSerializer.Serialize(writer, store.BusinessLineIds, jsonSerializerOptions); + } + if (store._DescriptionOption.IsSet) + if (store.Description != null) + writer.WriteString("description", store.Description); + + if (store._ExternalReferenceIdOption.IsSet) + if (store.ExternalReferenceId != null) + writer.WriteString("externalReferenceId", store.ExternalReferenceId); + + if (store._IdOption.IsSet) + if (store.Id != null) + writer.WriteString("id", store.Id); + + if (store._MerchantIdOption.IsSet) + if (store.MerchantId != null) + writer.WriteString("merchantId", store.MerchantId); + + if (store._PhoneNumberOption.IsSet) + if (store.PhoneNumber != null) + writer.WriteString("phoneNumber", store.PhoneNumber); + + if (store._ReferenceOption.IsSet) + if (store.Reference != null) + writer.WriteString("reference", store.Reference); + + if (store._ShopperStatementOption.IsSet) + if (store.ShopperStatement != null) + writer.WriteString("shopperStatement", store.ShopperStatement); + + if (store._SplitConfigurationOption.IsSet) + { + writer.WritePropertyName("splitConfiguration"); + JsonSerializer.Serialize(writer, store.SplitConfiguration, jsonSerializerOptions); + } + if (store._StatusOption.IsSet && store.Status != null) + { + string? statusRawValue = Store.StatusEnum.ToJsonValue(store._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (store._SubMerchantDataOption.IsSet) + { + writer.WritePropertyName("subMerchantData"); + JsonSerializer.Serialize(writer, store.SubMerchantData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/StoreAndForward.cs b/Adyen/Management/Models/StoreAndForward.cs new file mode 100644 index 000000000..2f64699d0 --- /dev/null +++ b/Adyen/Management/Models/StoreAndForward.cs @@ -0,0 +1,228 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StoreAndForward. + /// + public partial class StoreAndForward : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The maximum amount that the terminal accepts for a single store-and-forward payment. + /// The maximum number of store-and-forward transactions per terminal that you can process while offline. + /// supportedCardTypes + [JsonConstructor] + public StoreAndForward(Option?> maxAmount = default, Option maxPayments = default, Option supportedCardTypes = default) + { + _MaxAmountOption = maxAmount; + _MaxPaymentsOption = maxPayments; + _SupportedCardTypesOption = supportedCardTypes; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreAndForward() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MaxAmountOption { get; private set; } + + /// + /// The maximum amount that the terminal accepts for a single store-and-forward payment. + /// + /// The maximum amount that the terminal accepts for a single store-and-forward payment. + [JsonPropertyName("maxAmount")] + public List? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxPaymentsOption { get; private set; } + + /// + /// The maximum number of store-and-forward transactions per terminal that you can process while offline. + /// + /// The maximum number of store-and-forward transactions per terminal that you can process while offline. + [JsonPropertyName("maxPayments")] + public int? MaxPayments { get { return this._MaxPaymentsOption; } set { this._MaxPaymentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SupportedCardTypesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("supportedCardTypes")] + public SupportedCardTypes? SupportedCardTypes { get { return this._SupportedCardTypesOption; } set { this._SupportedCardTypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreAndForward {\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append(" MaxPayments: ").Append(MaxPayments).Append("\n"); + sb.Append(" SupportedCardTypes: ").Append(SupportedCardTypes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreAndForwardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreAndForward Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> maxAmount = default; + Option maxPayments = default; + Option supportedCardTypes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "maxAmount": + maxAmount = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maxPayments": + maxPayments = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "supportedCardTypes": + supportedCardTypes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new StoreAndForward(maxAmount, maxPayments, supportedCardTypes); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreAndForward storeAndForward, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeAndForward, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreAndForward storeAndForward, JsonSerializerOptions jsonSerializerOptions) + { + + if (storeAndForward._MaxAmountOption.IsSet) + { + writer.WritePropertyName("maxAmount"); + JsonSerializer.Serialize(writer, storeAndForward.MaxAmount, jsonSerializerOptions); + } + if (storeAndForward._MaxPaymentsOption.IsSet) + writer.WriteNumber("maxPayments", storeAndForward._MaxPaymentsOption.Value!.Value); + + if (storeAndForward._SupportedCardTypesOption.IsSet) + { + writer.WritePropertyName("supportedCardTypes"); + JsonSerializer.Serialize(writer, storeAndForward.SupportedCardTypes, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/StoreCreationRequest.cs b/Adyen/Management/Models/StoreCreationRequest.cs new file mode 100644 index 000000000..3e7a74206 --- /dev/null +++ b/Adyen/Management/Models/StoreCreationRequest.cs @@ -0,0 +1,356 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StoreCreationRequest. + /// + public partial class StoreCreationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// Your description of the store. + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + /// splitConfiguration + /// subMerchantData + [JsonConstructor] + public StoreCreationRequest(StoreLocation address, string description, string phoneNumber, string shopperStatement, Option?> businessLineIds = default, Option externalReferenceId = default, Option reference = default, Option splitConfiguration = default, Option subMerchantData = default) + { + Address = address; + Description = description; + PhoneNumber = phoneNumber; + ShopperStatement = shopperStatement; + _BusinessLineIdsOption = businessLineIds; + _ExternalReferenceIdOption = externalReferenceId; + _ReferenceOption = reference; + _SplitConfigurationOption = splitConfiguration; + _SubMerchantDataOption = subMerchantData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreCreationRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public StoreLocation Address { get; set; } + + /// + /// Your description of the store. + /// + /// Your description of the store. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + [JsonPropertyName("phoneNumber")] + public string PhoneNumber { get; set; } + + /// + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + /// + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + [JsonPropertyName("shopperStatement")] + public string ShopperStatement { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BusinessLineIdsOption { get; private set; } + + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + [JsonPropertyName("businessLineIds")] + public List? BusinessLineIds { get { return this._BusinessLineIdsOption; } set { this._BusinessLineIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReferenceIdOption { get; private set; } + + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + [JsonPropertyName("externalReferenceId")] + public string? ExternalReferenceId { get { return this._ExternalReferenceIdOption; } set { this._ExternalReferenceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + /// + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("splitConfiguration")] + public StoreSplitConfiguration? SplitConfiguration { get { return this._SplitConfigurationOption; } set { this._SplitConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchantData")] + public SubMerchantData? SubMerchantData { get { return this._SubMerchantDataOption; } set { this._SubMerchantDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreCreationRequest {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" BusinessLineIds: ").Append(BusinessLineIds).Append("\n"); + sb.Append(" ExternalReferenceId: ").Append(ExternalReferenceId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SplitConfiguration: ").Append(SplitConfiguration).Append("\n"); + sb.Append(" SubMerchantData: ").Append(SubMerchantData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreCreationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreCreationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option description = default; + Option phoneNumber = default; + Option shopperStatement = default; + Option?> businessLineIds = default; + Option externalReferenceId = default; + Option reference = default; + Option splitConfiguration = default; + Option subMerchantData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "businessLineIds": + businessLineIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReferenceId": + externalReferenceId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splitConfiguration": + splitConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subMerchantData": + subMerchantData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class StoreCreationRequest.", nameof(address)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class StoreCreationRequest.", nameof(description)); + + if (!phoneNumber.IsSet) + throw new ArgumentException("Property is required for class StoreCreationRequest.", nameof(phoneNumber)); + + if (!shopperStatement.IsSet) + throw new ArgumentException("Property is required for class StoreCreationRequest.", nameof(shopperStatement)); + + return new StoreCreationRequest(address.Value!, description.Value!, phoneNumber.Value!, shopperStatement.Value!, businessLineIds, externalReferenceId, reference, splitConfiguration, subMerchantData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreCreationRequest storeCreationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeCreationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreCreationRequest storeCreationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, storeCreationRequest.Address, jsonSerializerOptions); + if (storeCreationRequest.Description != null) + writer.WriteString("description", storeCreationRequest.Description); + + if (storeCreationRequest.PhoneNumber != null) + writer.WriteString("phoneNumber", storeCreationRequest.PhoneNumber); + + if (storeCreationRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", storeCreationRequest.ShopperStatement); + + if (storeCreationRequest._BusinessLineIdsOption.IsSet) + { + writer.WritePropertyName("businessLineIds"); + JsonSerializer.Serialize(writer, storeCreationRequest.BusinessLineIds, jsonSerializerOptions); + } + if (storeCreationRequest._ExternalReferenceIdOption.IsSet) + if (storeCreationRequest.ExternalReferenceId != null) + writer.WriteString("externalReferenceId", storeCreationRequest.ExternalReferenceId); + + if (storeCreationRequest._ReferenceOption.IsSet) + if (storeCreationRequest.Reference != null) + writer.WriteString("reference", storeCreationRequest.Reference); + + if (storeCreationRequest._SplitConfigurationOption.IsSet) + { + writer.WritePropertyName("splitConfiguration"); + JsonSerializer.Serialize(writer, storeCreationRequest.SplitConfiguration, jsonSerializerOptions); + } + if (storeCreationRequest._SubMerchantDataOption.IsSet) + { + writer.WritePropertyName("subMerchantData"); + JsonSerializer.Serialize(writer, storeCreationRequest.SubMerchantData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/StoreCreationWithMerchantCodeRequest.cs b/Adyen/Management/Models/StoreCreationWithMerchantCodeRequest.cs new file mode 100644 index 000000000..e3a143511 --- /dev/null +++ b/Adyen/Management/Models/StoreCreationWithMerchantCodeRequest.cs @@ -0,0 +1,376 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StoreCreationWithMerchantCodeRequest. + /// + public partial class StoreCreationWithMerchantCodeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// Your description of the store. + /// The unique identifier of the merchant account that the store belongs to. + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + /// splitConfiguration + /// subMerchantData + [JsonConstructor] + public StoreCreationWithMerchantCodeRequest(StoreLocation address, string description, string merchantId, string phoneNumber, string shopperStatement, Option?> businessLineIds = default, Option externalReferenceId = default, Option reference = default, Option splitConfiguration = default, Option subMerchantData = default) + { + Address = address; + Description = description; + MerchantId = merchantId; + PhoneNumber = phoneNumber; + ShopperStatement = shopperStatement; + _BusinessLineIdsOption = businessLineIds; + _ExternalReferenceIdOption = externalReferenceId; + _ReferenceOption = reference; + _SplitConfigurationOption = splitConfiguration; + _SubMerchantDataOption = subMerchantData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreCreationWithMerchantCodeRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("address")] + public StoreLocation Address { get; set; } + + /// + /// Your description of the store. + /// + /// Your description of the store. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The unique identifier of the merchant account that the store belongs to. + /// + /// The unique identifier of the merchant account that the store belongs to. + [JsonPropertyName("merchantId")] + public string MerchantId { get; set; } + + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + [JsonPropertyName("phoneNumber")] + public string PhoneNumber { get; set; } + + /// + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + /// + /// The store name to be shown on the shopper's bank or credit card statement and on the shopper receipt. Maximum length: 22 characters; can't be all numbers. + [JsonPropertyName("shopperStatement")] + public string ShopperStatement { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BusinessLineIdsOption { get; private set; } + + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/legalentity/latest/post/businessLines#responses-200-id) that the store is associated with. If not specified, the business line of the merchant account is used. Required when there are multiple business lines under the merchant account. + [JsonPropertyName("businessLineIds")] + public List? BusinessLineIds { get { return this._BusinessLineIdsOption; } set { this._BusinessLineIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReferenceIdOption { get; private set; } + + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + [JsonPropertyName("externalReferenceId")] + public string? ExternalReferenceId { get { return this._ExternalReferenceIdOption; } set { this._ExternalReferenceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + /// + /// Your reference to recognize the store by. Also known as the store code. Allowed characters: lowercase and uppercase letters without diacritics, numbers 0 through 9, hyphen (-), and underscore (_). If you do not provide a reference in your POST request, it is populated with the Adyen-generated [id](https://docs.adyen.com/api-explorer/Management/latest/post/stores#responses-200-id). + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("splitConfiguration")] + public StoreSplitConfiguration? SplitConfiguration { get { return this._SplitConfigurationOption; } set { this._SplitConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchantData")] + public SubMerchantData? SubMerchantData { get { return this._SubMerchantDataOption; } set { this._SubMerchantDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreCreationWithMerchantCodeRequest {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" BusinessLineIds: ").Append(BusinessLineIds).Append("\n"); + sb.Append(" ExternalReferenceId: ").Append(ExternalReferenceId).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SplitConfiguration: ").Append(SplitConfiguration).Append("\n"); + sb.Append(" SubMerchantData: ").Append(SubMerchantData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreCreationWithMerchantCodeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreCreationWithMerchantCodeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option description = default; + Option merchantId = default; + Option phoneNumber = default; + Option shopperStatement = default; + Option?> businessLineIds = default; + Option externalReferenceId = default; + Option reference = default; + Option splitConfiguration = default; + Option subMerchantData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "businessLineIds": + businessLineIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReferenceId": + externalReferenceId = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splitConfiguration": + splitConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subMerchantData": + subMerchantData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!address.IsSet) + throw new ArgumentException("Property is required for class StoreCreationWithMerchantCodeRequest.", nameof(address)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class StoreCreationWithMerchantCodeRequest.", nameof(description)); + + if (!merchantId.IsSet) + throw new ArgumentException("Property is required for class StoreCreationWithMerchantCodeRequest.", nameof(merchantId)); + + if (!phoneNumber.IsSet) + throw new ArgumentException("Property is required for class StoreCreationWithMerchantCodeRequest.", nameof(phoneNumber)); + + if (!shopperStatement.IsSet) + throw new ArgumentException("Property is required for class StoreCreationWithMerchantCodeRequest.", nameof(shopperStatement)); + + return new StoreCreationWithMerchantCodeRequest(address.Value!, description.Value!, merchantId.Value!, phoneNumber.Value!, shopperStatement.Value!, businessLineIds, externalReferenceId, reference, splitConfiguration, subMerchantData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreCreationWithMerchantCodeRequest storeCreationWithMerchantCodeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeCreationWithMerchantCodeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreCreationWithMerchantCodeRequest storeCreationWithMerchantCodeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, storeCreationWithMerchantCodeRequest.Address, jsonSerializerOptions); + if (storeCreationWithMerchantCodeRequest.Description != null) + writer.WriteString("description", storeCreationWithMerchantCodeRequest.Description); + + if (storeCreationWithMerchantCodeRequest.MerchantId != null) + writer.WriteString("merchantId", storeCreationWithMerchantCodeRequest.MerchantId); + + if (storeCreationWithMerchantCodeRequest.PhoneNumber != null) + writer.WriteString("phoneNumber", storeCreationWithMerchantCodeRequest.PhoneNumber); + + if (storeCreationWithMerchantCodeRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", storeCreationWithMerchantCodeRequest.ShopperStatement); + + if (storeCreationWithMerchantCodeRequest._BusinessLineIdsOption.IsSet) + { + writer.WritePropertyName("businessLineIds"); + JsonSerializer.Serialize(writer, storeCreationWithMerchantCodeRequest.BusinessLineIds, jsonSerializerOptions); + } + if (storeCreationWithMerchantCodeRequest._ExternalReferenceIdOption.IsSet) + if (storeCreationWithMerchantCodeRequest.ExternalReferenceId != null) + writer.WriteString("externalReferenceId", storeCreationWithMerchantCodeRequest.ExternalReferenceId); + + if (storeCreationWithMerchantCodeRequest._ReferenceOption.IsSet) + if (storeCreationWithMerchantCodeRequest.Reference != null) + writer.WriteString("reference", storeCreationWithMerchantCodeRequest.Reference); + + if (storeCreationWithMerchantCodeRequest._SplitConfigurationOption.IsSet) + { + writer.WritePropertyName("splitConfiguration"); + JsonSerializer.Serialize(writer, storeCreationWithMerchantCodeRequest.SplitConfiguration, jsonSerializerOptions); + } + if (storeCreationWithMerchantCodeRequest._SubMerchantDataOption.IsSet) + { + writer.WritePropertyName("subMerchantData"); + JsonSerializer.Serialize(writer, storeCreationWithMerchantCodeRequest.SubMerchantData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/StoreLocation.cs b/Adyen/Management/Models/StoreLocation.cs new file mode 100644 index 000000000..c34a3e8df --- /dev/null +++ b/Adyen/Management/Models/StoreLocation.cs @@ -0,0 +1,321 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StoreLocation. + /// + public partial class StoreLocation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-letter country code in [ISO_3166-1_alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + /// The name of the city. + /// The street address. + /// Second address line. + /// Third address line. + /// The postal code. + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + [JsonConstructor] + public StoreLocation(string country, Option city = default, Option line1 = default, Option line2 = default, Option line3 = default, Option postalCode = default, Option stateOrProvince = default) + { + Country = country; + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreLocation() + { + } + + partial void OnCreated(); + + /// + /// The two-letter country code in [ISO_3166-1_alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + /// + /// The two-letter country code in [ISO_3166-1_alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The street address. + /// + /// The street address. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// Second address line. + /// + /// Second address line. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Third address line. + /// + /// Third address line. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. + /// + /// The postal code. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + /// + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreLocation {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreLocationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreLocation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class StoreLocation.", nameof(country)); + + return new StoreLocation(country.Value!, city, line1, line2, line3, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreLocation storeLocation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeLocation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreLocation storeLocation, JsonSerializerOptions jsonSerializerOptions) + { + + if (storeLocation.Country != null) + writer.WriteString("country", storeLocation.Country); + + if (storeLocation._CityOption.IsSet) + if (storeLocation.City != null) + writer.WriteString("city", storeLocation.City); + + if (storeLocation._Line1Option.IsSet) + if (storeLocation.Line1 != null) + writer.WriteString("line1", storeLocation.Line1); + + if (storeLocation._Line2Option.IsSet) + if (storeLocation.Line2 != null) + writer.WriteString("line2", storeLocation.Line2); + + if (storeLocation._Line3Option.IsSet) + if (storeLocation.Line3 != null) + writer.WriteString("line3", storeLocation.Line3); + + if (storeLocation._PostalCodeOption.IsSet) + if (storeLocation.PostalCode != null) + writer.WriteString("postalCode", storeLocation.PostalCode); + + if (storeLocation._StateOrProvinceOption.IsSet) + if (storeLocation.StateOrProvince != null) + writer.WriteString("stateOrProvince", storeLocation.StateOrProvince); + } + } +} diff --git a/Adyen/Management/Models/StoreSplitConfiguration.cs b/Adyen/Management/Models/StoreSplitConfiguration.cs new file mode 100644 index 000000000..28a325d20 --- /dev/null +++ b/Adyen/Management/Models/StoreSplitConfiguration.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// StoreSplitConfiguration. + /// + public partial class StoreSplitConfiguration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [unique identifier of the balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id) to which the split amount must be booked, depending on the defined [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/_merchantId_/splitConfigurations#request-rules-splitLogic). + /// The unique identifier of the [split configuration profile](https://docs.adyen.com/platforms/automatic-split-configuration/create-split-configuration/). + [JsonConstructor] + public StoreSplitConfiguration(Option balanceAccountId = default, Option splitConfigurationId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _SplitConfigurationIdOption = splitConfigurationId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreSplitConfiguration() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The [unique identifier of the balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id) to which the split amount must be booked, depending on the defined [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/_merchantId_/splitConfigurations#request-rules-splitLogic). + /// + /// The [unique identifier of the balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id) to which the split amount must be booked, depending on the defined [split logic](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/_merchantId_/splitConfigurations#request-rules-splitLogic). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationIdOption { get; private set; } + + /// + /// The unique identifier of the [split configuration profile](https://docs.adyen.com/platforms/automatic-split-configuration/create-split-configuration/). + /// + /// The unique identifier of the [split configuration profile](https://docs.adyen.com/platforms/automatic-split-configuration/create-split-configuration/). + [JsonPropertyName("splitConfigurationId")] + public string? SplitConfigurationId { get { return this._SplitConfigurationIdOption; } set { this._SplitConfigurationIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreSplitConfiguration {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" SplitConfigurationId: ").Append(SplitConfigurationId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreSplitConfigurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreSplitConfiguration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option splitConfigurationId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "splitConfigurationId": + splitConfigurationId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoreSplitConfiguration(balanceAccountId, splitConfigurationId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreSplitConfiguration storeSplitConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeSplitConfiguration, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreSplitConfiguration storeSplitConfiguration, JsonSerializerOptions jsonSerializerOptions) + { + + if (storeSplitConfiguration._BalanceAccountIdOption.IsSet) + if (storeSplitConfiguration.BalanceAccountId != null) + writer.WriteString("balanceAccountId", storeSplitConfiguration.BalanceAccountId); + + if (storeSplitConfiguration._SplitConfigurationIdOption.IsSet) + if (storeSplitConfiguration.SplitConfigurationId != null) + writer.WriteString("splitConfigurationId", storeSplitConfiguration.SplitConfigurationId); + } + } +} diff --git a/Adyen/Management/Models/SubMerchantData.cs b/Adyen/Management/Models/SubMerchantData.cs new file mode 100644 index 000000000..350721de6 --- /dev/null +++ b/Adyen/Management/Models/SubMerchantData.cs @@ -0,0 +1,237 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SubMerchantData. + /// + public partial class SubMerchantData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email associated with the sub-merchant's account. + /// A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonConstructor] + public SubMerchantData(string email, string id, string mcc, string name) + { + Email = email; + Id = id; + Mcc = mcc; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubMerchantData() + { + } + + partial void OnCreated(); + + /// + /// The email associated with the sub-merchant's account. + /// + /// The email associated with the sub-merchant's account. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// + /// A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("mcc")] + public string Mcc { get; set; } + + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubMerchantData {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) maxLength + if (this.Email != null && this.Email.Length > 320) + { + yield return new ValidationResult("Invalid value for Email, length must be less than 320.", new [] { "Email" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubMerchantDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubMerchantData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option id = default; + Option mcc = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class SubMerchantData.", nameof(email)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class SubMerchantData.", nameof(id)); + + if (!mcc.IsSet) + throw new ArgumentException("Property is required for class SubMerchantData.", nameof(mcc)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class SubMerchantData.", nameof(name)); + + return new SubMerchantData(email.Value!, id.Value!, mcc.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubMerchantData subMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subMerchantData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubMerchantData subMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + if (subMerchantData.Email != null) + writer.WriteString("email", subMerchantData.Email); + + if (subMerchantData.Id != null) + writer.WriteString("id", subMerchantData.Id); + + if (subMerchantData.Mcc != null) + writer.WriteString("mcc", subMerchantData.Mcc); + + if (subMerchantData.Name != null) + writer.WriteString("name", subMerchantData.Name); + } + } +} diff --git a/Adyen/Management/Models/SupportedCardTypes.cs b/Adyen/Management/Models/SupportedCardTypes.cs new file mode 100644 index 000000000..0870bedc2 --- /dev/null +++ b/Adyen/Management/Models/SupportedCardTypes.cs @@ -0,0 +1,272 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SupportedCardTypes. + /// + public partial class SupportedCardTypes : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Set to **true** to accept credit cards. + /// Set to **true** to accept debit cards. + /// Set to **true** to accept cards that allow deferred debit. + /// Set to **true** to accept prepaid cards. + /// Set to **true** to accept card types for which the terminal can't determine the funding source while offline. + [JsonConstructor] + public SupportedCardTypes(Option credit = default, Option debit = default, Option deferredDebit = default, Option prepaid = default, Option unknown = default) + { + _CreditOption = credit; + _DebitOption = debit; + _DeferredDebitOption = deferredDebit; + _PrepaidOption = prepaid; + _UnknownOption = unknown; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SupportedCardTypes() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreditOption { get; private set; } + + /// + /// Set to **true** to accept credit cards. + /// + /// Set to **true** to accept credit cards. + [JsonPropertyName("credit")] + public bool? Credit { get { return this._CreditOption; } set { this._CreditOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DebitOption { get; private set; } + + /// + /// Set to **true** to accept debit cards. + /// + /// Set to **true** to accept debit cards. + [JsonPropertyName("debit")] + public bool? Debit { get { return this._DebitOption; } set { this._DebitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeferredDebitOption { get; private set; } + + /// + /// Set to **true** to accept cards that allow deferred debit. + /// + /// Set to **true** to accept cards that allow deferred debit. + [JsonPropertyName("deferredDebit")] + public bool? DeferredDebit { get { return this._DeferredDebitOption; } set { this._DeferredDebitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrepaidOption { get; private set; } + + /// + /// Set to **true** to accept prepaid cards. + /// + /// Set to **true** to accept prepaid cards. + [JsonPropertyName("prepaid")] + public bool? Prepaid { get { return this._PrepaidOption; } set { this._PrepaidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UnknownOption { get; private set; } + + /// + /// Set to **true** to accept card types for which the terminal can't determine the funding source while offline. + /// + /// Set to **true** to accept card types for which the terminal can't determine the funding source while offline. + [JsonPropertyName("unknown")] + public bool? Unknown { get { return this._UnknownOption; } set { this._UnknownOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SupportedCardTypes {\n"); + sb.Append(" Credit: ").Append(Credit).Append("\n"); + sb.Append(" Debit: ").Append(Debit).Append("\n"); + sb.Append(" DeferredDebit: ").Append(DeferredDebit).Append("\n"); + sb.Append(" Prepaid: ").Append(Prepaid).Append("\n"); + sb.Append(" Unknown: ").Append(Unknown).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SupportedCardTypesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SupportedCardTypes Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option credit = default; + Option debit = default; + Option deferredDebit = default; + Option prepaid = default; + Option unknown = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "credit": + credit = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "debit": + debit = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "deferredDebit": + deferredDebit = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "prepaid": + prepaid = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "unknown": + unknown = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new SupportedCardTypes(credit, debit, deferredDebit, prepaid, unknown); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SupportedCardTypes supportedCardTypes, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, supportedCardTypes, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SupportedCardTypes supportedCardTypes, JsonSerializerOptions jsonSerializerOptions) + { + + if (supportedCardTypes._CreditOption.IsSet) + writer.WriteBoolean("credit", supportedCardTypes._CreditOption.Value!.Value); + + if (supportedCardTypes._DebitOption.IsSet) + writer.WriteBoolean("debit", supportedCardTypes._DebitOption.Value!.Value); + + if (supportedCardTypes._DeferredDebitOption.IsSet) + writer.WriteBoolean("deferredDebit", supportedCardTypes._DeferredDebitOption.Value!.Value); + + if (supportedCardTypes._PrepaidOption.IsSet) + writer.WriteBoolean("prepaid", supportedCardTypes._PrepaidOption.Value!.Value); + + if (supportedCardTypes._UnknownOption.IsSet) + writer.WriteBoolean("unknown", supportedCardTypes._UnknownOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/Surcharge.cs b/Adyen/Management/Models/Surcharge.cs new file mode 100644 index 000000000..6855ce4b3 --- /dev/null +++ b/Adyen/Management/Models/Surcharge.cs @@ -0,0 +1,226 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Surcharge. + /// + public partial class Surcharge : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Show the surcharge details on the terminal, so the shopper can confirm. + /// Surcharge fees or percentages for specific cards, funding sources (credit or debit), and currencies. + /// Exclude the tip amount from the surcharge calculation. + [JsonConstructor] + public Surcharge(Option askConfirmation = default, Option?> configurations = default, Option excludeGratuityFromSurcharge = default) + { + _AskConfirmationOption = askConfirmation; + _ConfigurationsOption = configurations; + _ExcludeGratuityFromSurchargeOption = excludeGratuityFromSurcharge; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Surcharge() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AskConfirmationOption { get; private set; } + + /// + /// Show the surcharge details on the terminal, so the shopper can confirm. + /// + /// Show the surcharge details on the terminal, so the shopper can confirm. + [JsonPropertyName("askConfirmation")] + public bool? AskConfirmation { get { return this._AskConfirmationOption; } set { this._AskConfirmationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ConfigurationsOption { get; private set; } + + /// + /// Surcharge fees or percentages for specific cards, funding sources (credit or debit), and currencies. + /// + /// Surcharge fees or percentages for specific cards, funding sources (credit or debit), and currencies. + [JsonPropertyName("configurations")] + public List? Configurations { get { return this._ConfigurationsOption; } set { this._ConfigurationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExcludeGratuityFromSurchargeOption { get; private set; } + + /// + /// Exclude the tip amount from the surcharge calculation. + /// + /// Exclude the tip amount from the surcharge calculation. + [JsonPropertyName("excludeGratuityFromSurcharge")] + public bool? ExcludeGratuityFromSurcharge { get { return this._ExcludeGratuityFromSurchargeOption; } set { this._ExcludeGratuityFromSurchargeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Surcharge {\n"); + sb.Append(" AskConfirmation: ").Append(AskConfirmation).Append("\n"); + sb.Append(" Configurations: ").Append(Configurations).Append("\n"); + sb.Append(" ExcludeGratuityFromSurcharge: ").Append(ExcludeGratuityFromSurcharge).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SurchargeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Surcharge Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option askConfirmation = default; + Option?> configurations = default; + Option excludeGratuityFromSurcharge = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "askConfirmation": + askConfirmation = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "configurations": + configurations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "excludeGratuityFromSurcharge": + excludeGratuityFromSurcharge = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Surcharge(askConfirmation, configurations, excludeGratuityFromSurcharge); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Surcharge surcharge, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, surcharge, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Surcharge surcharge, JsonSerializerOptions jsonSerializerOptions) + { + + if (surcharge._AskConfirmationOption.IsSet) + writer.WriteBoolean("askConfirmation", surcharge._AskConfirmationOption.Value!.Value); + + if (surcharge._ConfigurationsOption.IsSet) + { + writer.WritePropertyName("configurations"); + JsonSerializer.Serialize(writer, surcharge.Configurations, jsonSerializerOptions); + } + if (surcharge._ExcludeGratuityFromSurchargeOption.IsSet) + writer.WriteBoolean("excludeGratuityFromSurcharge", surcharge._ExcludeGratuityFromSurchargeOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/SwishInfo.cs b/Adyen/Management/Models/SwishInfo.cs new file mode 100644 index 000000000..4eee8b52b --- /dev/null +++ b/Adyen/Management/Models/SwishInfo.cs @@ -0,0 +1,183 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// SwishInfo. + /// + public partial class SwishInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Swish number. Format: 10 digits without spaces. For example, **1231111111**. + [JsonConstructor] + public SwishInfo(string swishNumber) + { + SwishNumber = swishNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SwishInfo() + { + } + + partial void OnCreated(); + + /// + /// Swish number. Format: 10 digits without spaces. For example, **1231111111**. + /// + /// Swish number. Format: 10 digits without spaces. For example, **1231111111**. + [JsonPropertyName("swishNumber")] + public string SwishNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SwishInfo {\n"); + sb.Append(" SwishNumber: ").Append(SwishNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SwishNumber (string) maxLength + if (this.SwishNumber != null && this.SwishNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for SwishNumber, length must be less than 10.", new [] { "SwishNumber" }); + } + + // SwishNumber (string) minLength + if (this.SwishNumber != null && this.SwishNumber.Length < 10) + { + yield return new ValidationResult("Invalid value for SwishNumber, length must be greater than 10.", new [] { "SwishNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SwishInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SwishInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option swishNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "swishNumber": + swishNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!swishNumber.IsSet) + throw new ArgumentException("Property is required for class SwishInfo.", nameof(swishNumber)); + + return new SwishInfo(swishNumber.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SwishInfo swishInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, swishInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SwishInfo swishInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (swishInfo.SwishNumber != null) + writer.WriteString("swishNumber", swishInfo.SwishNumber); + } + } +} diff --git a/Adyen/Management/Models/TapToPay.cs b/Adyen/Management/Models/TapToPay.cs new file mode 100644 index 000000000..0e854d98d --- /dev/null +++ b/Adyen/Management/Models/TapToPay.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TapToPay. + /// + public partial class TapToPay : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The text shown on the screen during the Tap to Pay transaction. + [JsonConstructor] + public TapToPay(Option merchantDisplayName = default) + { + _MerchantDisplayNameOption = merchantDisplayName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TapToPay() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantDisplayNameOption { get; private set; } + + /// + /// The text shown on the screen during the Tap to Pay transaction. + /// + /// The text shown on the screen during the Tap to Pay transaction. + [JsonPropertyName("merchantDisplayName")] + public string? MerchantDisplayName { get { return this._MerchantDisplayNameOption; } set { this._MerchantDisplayNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TapToPay {\n"); + sb.Append(" MerchantDisplayName: ").Append(MerchantDisplayName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TapToPayJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TapToPay Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantDisplayName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantDisplayName": + merchantDisplayName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TapToPay(merchantDisplayName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TapToPay tapToPay, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tapToPay, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TapToPay tapToPay, JsonSerializerOptions jsonSerializerOptions) + { + + if (tapToPay._MerchantDisplayNameOption.IsSet) + if (tapToPay.MerchantDisplayName != null) + writer.WriteString("merchantDisplayName", tapToPay.MerchantDisplayName); + } + } +} diff --git a/Adyen/Management/Models/Terminal.cs b/Adyen/Management/Models/Terminal.cs new file mode 100644 index 000000000..d9b388653 --- /dev/null +++ b/Adyen/Management/Models/Terminal.cs @@ -0,0 +1,385 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Terminal. + /// + public partial class Terminal : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// assignment + /// connectivity + /// The software release currently in use on the terminal. + /// The unique identifier of the terminal. + /// Date and time of the last activity on the terminal. Not included when the last activity was more than 14 days ago. + /// Date and time of the last transaction on the terminal. Not included when the last transaction was more than 14 days ago. + /// The model name of the terminal. + /// The exact time of the terminal reboot, in the timezone of the terminal in **HH:mm** format. + /// The serial number of the terminal. + [JsonConstructor] + public Terminal(Option assignment = default, Option connectivity = default, Option firmwareVersion = default, Option id = default, Option lastActivityAt = default, Option lastTransactionAt = default, Option model = default, Option restartLocalTime = default, Option serialNumber = default) + { + _AssignmentOption = assignment; + _ConnectivityOption = connectivity; + _FirmwareVersionOption = firmwareVersion; + _IdOption = id; + _LastActivityAtOption = lastActivityAt; + _LastTransactionAtOption = lastTransactionAt; + _ModelOption = model; + _RestartLocalTimeOption = restartLocalTime; + _SerialNumberOption = serialNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Terminal() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssignmentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("assignment")] + public TerminalAssignment? Assignment { get { return this._AssignmentOption; } set { this._AssignmentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConnectivityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("connectivity")] + public TerminalConnectivity? Connectivity { get { return this._ConnectivityOption; } set { this._ConnectivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirmwareVersionOption { get; private set; } + + /// + /// The software release currently in use on the terminal. + /// + /// The software release currently in use on the terminal. + [JsonPropertyName("firmwareVersion")] + public string? FirmwareVersion { get { return this._FirmwareVersionOption; } set { this._FirmwareVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the terminal. + /// + /// The unique identifier of the terminal. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastActivityAtOption { get; private set; } + + /// + /// Date and time of the last activity on the terminal. Not included when the last activity was more than 14 days ago. + /// + /// Date and time of the last activity on the terminal. Not included when the last activity was more than 14 days ago. + [JsonPropertyName("lastActivityAt")] + public DateTimeOffset? LastActivityAt { get { return this._LastActivityAtOption; } set { this._LastActivityAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastTransactionAtOption { get; private set; } + + /// + /// Date and time of the last transaction on the terminal. Not included when the last transaction was more than 14 days ago. + /// + /// Date and time of the last transaction on the terminal. Not included when the last transaction was more than 14 days ago. + [JsonPropertyName("lastTransactionAt")] + public DateTimeOffset? LastTransactionAt { get { return this._LastTransactionAtOption; } set { this._LastTransactionAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModelOption { get; private set; } + + /// + /// The model name of the terminal. + /// + /// The model name of the terminal. + [JsonPropertyName("model")] + public string? Model { get { return this._ModelOption; } set { this._ModelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RestartLocalTimeOption { get; private set; } + + /// + /// The exact time of the terminal reboot, in the timezone of the terminal in **HH:mm** format. + /// + /// The exact time of the terminal reboot, in the timezone of the terminal in **HH:mm** format. + [JsonPropertyName("restartLocalTime")] + public string? RestartLocalTime { get { return this._RestartLocalTimeOption; } set { this._RestartLocalTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SerialNumberOption { get; private set; } + + /// + /// The serial number of the terminal. + /// + /// The serial number of the terminal. + [JsonPropertyName("serialNumber")] + public string? SerialNumber { get { return this._SerialNumberOption; } set { this._SerialNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Terminal {\n"); + sb.Append(" Assignment: ").Append(Assignment).Append("\n"); + sb.Append(" Connectivity: ").Append(Connectivity).Append("\n"); + sb.Append(" FirmwareVersion: ").Append(FirmwareVersion).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LastActivityAt: ").Append(LastActivityAt).Append("\n"); + sb.Append(" LastTransactionAt: ").Append(LastTransactionAt).Append("\n"); + sb.Append(" Model: ").Append(Model).Append("\n"); + sb.Append(" RestartLocalTime: ").Append(RestartLocalTime).Append("\n"); + sb.Append(" SerialNumber: ").Append(SerialNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastActivityAt. + /// + public static string LastActivityAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize LastTransactionAt. + /// + public static string LastTransactionAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Terminal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option assignment = default; + Option connectivity = default; + Option firmwareVersion = default; + Option id = default; + Option lastActivityAt = default; + Option lastTransactionAt = default; + Option model = default; + Option restartLocalTime = default; + Option serialNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "assignment": + assignment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "connectivity": + connectivity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "firmwareVersion": + firmwareVersion = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "lastActivityAt": + lastActivityAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "lastTransactionAt": + lastTransactionAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "model": + model = new Option(utf8JsonReader.GetString()!); + break; + case "restartLocalTime": + restartLocalTime = new Option(utf8JsonReader.GetString()!); + break; + case "serialNumber": + serialNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Terminal(assignment, connectivity, firmwareVersion, id, lastActivityAt, lastTransactionAt, model, restartLocalTime, serialNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Terminal terminal, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminal, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Terminal terminal, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminal._AssignmentOption.IsSet) + { + writer.WritePropertyName("assignment"); + JsonSerializer.Serialize(writer, terminal.Assignment, jsonSerializerOptions); + } + if (terminal._ConnectivityOption.IsSet) + { + writer.WritePropertyName("connectivity"); + JsonSerializer.Serialize(writer, terminal.Connectivity, jsonSerializerOptions); + } + if (terminal._FirmwareVersionOption.IsSet) + if (terminal.FirmwareVersion != null) + writer.WriteString("firmwareVersion", terminal.FirmwareVersion); + + if (terminal._IdOption.IsSet) + if (terminal.Id != null) + writer.WriteString("id", terminal.Id); + + if (terminal._LastActivityAtOption.IsSet) + writer.WriteString("lastActivityAt", terminal._LastActivityAtOption.Value!.Value.ToString(LastActivityAtFormat)); + + if (terminal._LastTransactionAtOption.IsSet) + writer.WriteString("lastTransactionAt", terminal._LastTransactionAtOption.Value!.Value.ToString(LastTransactionAtFormat)); + + if (terminal._ModelOption.IsSet) + if (terminal.Model != null) + writer.WriteString("model", terminal.Model); + + if (terminal._RestartLocalTimeOption.IsSet) + if (terminal.RestartLocalTime != null) + writer.WriteString("restartLocalTime", terminal.RestartLocalTime); + + if (terminal._SerialNumberOption.IsSet) + if (terminal.SerialNumber != null) + writer.WriteString("serialNumber", terminal.SerialNumber); + } + } +} diff --git a/Adyen/Management/Models/TerminalActionScheduleDetail.cs b/Adyen/Management/Models/TerminalActionScheduleDetail.cs new file mode 100644 index 000000000..7f6187b1e --- /dev/null +++ b/Adyen/Management/Models/TerminalActionScheduleDetail.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalActionScheduleDetail. + /// + public partial class TerminalActionScheduleDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The ID of the action on the specified terminal. + /// The unique ID of the terminal that the action applies to. + [JsonConstructor] + public TerminalActionScheduleDetail(Option id = default, Option terminalId = default) + { + _IdOption = id; + _TerminalIdOption = terminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalActionScheduleDetail() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the action on the specified terminal. + /// + /// The ID of the action on the specified terminal. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The unique ID of the terminal that the action applies to. + /// + /// The unique ID of the terminal that the action applies to. + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalActionScheduleDetail {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalActionScheduleDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalActionScheduleDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option terminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalActionScheduleDetail(id, terminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalActionScheduleDetail terminalActionScheduleDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalActionScheduleDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalActionScheduleDetail terminalActionScheduleDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalActionScheduleDetail._IdOption.IsSet) + if (terminalActionScheduleDetail.Id != null) + writer.WriteString("id", terminalActionScheduleDetail.Id); + + if (terminalActionScheduleDetail._TerminalIdOption.IsSet) + if (terminalActionScheduleDetail.TerminalId != null) + writer.WriteString("terminalId", terminalActionScheduleDetail.TerminalId); + } + } +} diff --git a/Adyen/Management/Models/TerminalAssignment.cs b/Adyen/Management/Models/TerminalAssignment.cs new file mode 100644 index 000000000..607886e8d --- /dev/null +++ b/Adyen/Management/Models/TerminalAssignment.cs @@ -0,0 +1,391 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalAssignment. + /// + public partial class TerminalAssignment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the company account to which terminal is assigned. + /// The status of the reassignment. Possible values: * `reassignmentInProgress`: the terminal was boarded and is now scheduled to remove the configuration. Wait for the terminal to synchronize with the Adyen platform. * `deployed`: the terminal is deployed and reassigned. * `inventory`: the terminal is in inventory and cannot process transactions. * `boarded`: the terminal is boarded to a store, or a merchant account representing a store, and can process transactions. + /// The unique identifier of the merchant account to which terminal is assigned. + /// reassignmentTarget + /// The unique identifier of the store to which terminal is assigned. + [JsonConstructor] + public TerminalAssignment(string companyId, StatusEnum status, Option merchantId = default, Option reassignmentTarget = default, Option storeId = default) + { + CompanyId = companyId; + Status = status; + _MerchantIdOption = merchantId; + _ReassignmentTargetOption = reassignmentTarget; + _StoreIdOption = storeId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalAssignment() + { + } + + partial void OnCreated(); + + /// + /// The status of the reassignment. Possible values: * `reassignmentInProgress`: the terminal was boarded and is now scheduled to remove the configuration. Wait for the terminal to synchronize with the Adyen platform. * `deployed`: the terminal is deployed and reassigned. * `inventory`: the terminal is in inventory and cannot process transactions. * `boarded`: the terminal is boarded to a store, or a merchant account representing a store, and can process transactions. + /// + /// The status of the reassignment. Possible values: * `reassignmentInProgress`: the terminal was boarded and is now scheduled to remove the configuration. Wait for the terminal to synchronize with the Adyen platform. * `deployed`: the terminal is deployed and reassigned. * `inventory`: the terminal is in inventory and cannot process transactions. * `boarded`: the terminal is boarded to a store, or a merchant account representing a store, and can process transactions. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Boarded - boarded + /// + public static readonly StatusEnum Boarded = new("boarded"); + + /// + /// StatusEnum.Deployed - deployed + /// + public static readonly StatusEnum Deployed = new("deployed"); + + /// + /// StatusEnum.Inventory - inventory + /// + public static readonly StatusEnum Inventory = new("inventory"); + + /// + /// StatusEnum.ReassignmentInProgress - reassignmentInProgress + /// + public static readonly StatusEnum ReassignmentInProgress = new("reassignmentInProgress"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "boarded" => StatusEnum.Boarded, + "deployed" => StatusEnum.Deployed, + "inventory" => StatusEnum.Inventory, + "reassignmentInProgress" => StatusEnum.ReassignmentInProgress, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Boarded) + return "boarded"; + + if (value == StatusEnum.Deployed) + return "deployed"; + + if (value == StatusEnum.Inventory) + return "inventory"; + + if (value == StatusEnum.ReassignmentInProgress) + return "reassignmentInProgress"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the reassignment. Possible values: * `reassignmentInProgress`: the terminal was boarded and is now scheduled to remove the configuration. Wait for the terminal to synchronize with the Adyen platform. * `deployed`: the terminal is deployed and reassigned. * `inventory`: the terminal is in inventory and cannot process transactions. * `boarded`: the terminal is boarded to a store, or a merchant account representing a store, and can process transactions. + /// + /// The status of the reassignment. Possible values: * `reassignmentInProgress`: the terminal was boarded and is now scheduled to remove the configuration. Wait for the terminal to synchronize with the Adyen platform. * `deployed`: the terminal is deployed and reassigned. * `inventory`: the terminal is in inventory and cannot process transactions. * `boarded`: the terminal is boarded to a store, or a merchant account representing a store, and can process transactions. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The unique identifier of the company account to which terminal is assigned. + /// + /// The unique identifier of the company account to which terminal is assigned. + [JsonPropertyName("companyId")] + public string CompanyId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account to which terminal is assigned. + /// + /// The unique identifier of the merchant account to which terminal is assigned. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReassignmentTargetOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("reassignmentTarget")] + public TerminalReassignmentTarget? ReassignmentTarget { get { return this._ReassignmentTargetOption; } set { this._ReassignmentTargetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the store to which terminal is assigned. + /// + /// The unique identifier of the store to which terminal is assigned. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalAssignment {\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" ReassignmentTarget: ").Append(ReassignmentTarget).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalAssignmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalAssignment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option companyId = default; + Option status = default; + Option merchantId = default; + Option reassignmentTarget = default; + Option storeId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TerminalAssignment.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "reassignmentTarget": + reassignmentTarget = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!companyId.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignment.", nameof(companyId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignment.", nameof(status)); + + return new TerminalAssignment(companyId.Value!, status.Value!.Value!, merchantId, reassignmentTarget, storeId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalAssignment terminalAssignment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalAssignment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalAssignment terminalAssignment, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalAssignment.CompanyId != null) + writer.WriteString("companyId", terminalAssignment.CompanyId); + + if (terminalAssignment.Status != null) + { + string? statusRawValue = TerminalAssignment.StatusEnum.ToJsonValue(terminalAssignment.Status); + writer.WriteString("status", statusRawValue); + } + + if (terminalAssignment._MerchantIdOption.IsSet) + if (terminalAssignment.MerchantId != null) + writer.WriteString("merchantId", terminalAssignment.MerchantId); + + if (terminalAssignment._ReassignmentTargetOption.IsSet) + { + writer.WritePropertyName("reassignmentTarget"); + JsonSerializer.Serialize(writer, terminalAssignment.ReassignmentTarget, jsonSerializerOptions); + } + if (terminalAssignment._StoreIdOption.IsSet) + if (terminalAssignment.StoreId != null) + writer.WriteString("storeId", terminalAssignment.StoreId); + } + } +} diff --git a/Adyen/Management/Models/TerminalConnectivity.cs b/Adyen/Management/Models/TerminalConnectivity.cs new file mode 100644 index 000000000..46d0363ca --- /dev/null +++ b/Adyen/Management/Models/TerminalConnectivity.cs @@ -0,0 +1,253 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalConnectivity. + /// + public partial class TerminalConnectivity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bluetooth + /// cellular + /// ethernet + /// wifi + [JsonConstructor] + public TerminalConnectivity(Option bluetooth = default, Option cellular = default, Option ethernet = default, Option wifi = default) + { + _BluetoothOption = bluetooth; + _CellularOption = cellular; + _EthernetOption = ethernet; + _WifiOption = wifi; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalConnectivity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BluetoothOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bluetooth")] + public TerminalConnectivityBluetooth? Bluetooth { get { return this._BluetoothOption; } set { this._BluetoothOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CellularOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cellular")] + public TerminalConnectivityCellular? Cellular { get { return this._CellularOption; } set { this._CellularOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EthernetOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ethernet")] + public TerminalConnectivityEthernet? Ethernet { get { return this._EthernetOption; } set { this._EthernetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WifiOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wifi")] + public TerminalConnectivityWifi? Wifi { get { return this._WifiOption; } set { this._WifiOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalConnectivity {\n"); + sb.Append(" Bluetooth: ").Append(Bluetooth).Append("\n"); + sb.Append(" Cellular: ").Append(Cellular).Append("\n"); + sb.Append(" Ethernet: ").Append(Ethernet).Append("\n"); + sb.Append(" Wifi: ").Append(Wifi).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalConnectivityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalConnectivity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bluetooth = default; + Option cellular = default; + Option ethernet = default; + Option wifi = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bluetooth": + bluetooth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cellular": + cellular = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ethernet": + ethernet = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wifi": + wifi = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalConnectivity(bluetooth, cellular, ethernet, wifi); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalConnectivity terminalConnectivity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalConnectivity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalConnectivity terminalConnectivity, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalConnectivity._BluetoothOption.IsSet) + { + writer.WritePropertyName("bluetooth"); + JsonSerializer.Serialize(writer, terminalConnectivity.Bluetooth, jsonSerializerOptions); + } + if (terminalConnectivity._CellularOption.IsSet) + { + writer.WritePropertyName("cellular"); + JsonSerializer.Serialize(writer, terminalConnectivity.Cellular, jsonSerializerOptions); + } + if (terminalConnectivity._EthernetOption.IsSet) + { + writer.WritePropertyName("ethernet"); + JsonSerializer.Serialize(writer, terminalConnectivity.Ethernet, jsonSerializerOptions); + } + if (terminalConnectivity._WifiOption.IsSet) + { + writer.WritePropertyName("wifi"); + JsonSerializer.Serialize(writer, terminalConnectivity.Wifi, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalConnectivityBluetooth.cs b/Adyen/Management/Models/TerminalConnectivityBluetooth.cs new file mode 100644 index 000000000..96cbe0c12 --- /dev/null +++ b/Adyen/Management/Models/TerminalConnectivityBluetooth.cs @@ -0,0 +1,202 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalConnectivityBluetooth. + /// + public partial class TerminalConnectivityBluetooth : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The terminal's Bluetooth IP address. + /// The terminal's Bluetooth MAC address. + [JsonConstructor] + public TerminalConnectivityBluetooth(Option ipAddress = default, Option macAddress = default) + { + _IpAddressOption = ipAddress; + _MacAddressOption = macAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalConnectivityBluetooth() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IpAddressOption { get; private set; } + + /// + /// The terminal's Bluetooth IP address. + /// + /// The terminal's Bluetooth IP address. + [JsonPropertyName("ipAddress")] + public string? IpAddress { get { return this._IpAddressOption; } set { this._IpAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MacAddressOption { get; private set; } + + /// + /// The terminal's Bluetooth MAC address. + /// + /// The terminal's Bluetooth MAC address. + [JsonPropertyName("macAddress")] + public string? MacAddress { get { return this._MacAddressOption; } set { this._MacAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalConnectivityBluetooth {\n"); + sb.Append(" IpAddress: ").Append(IpAddress).Append("\n"); + sb.Append(" MacAddress: ").Append(MacAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalConnectivityBluetoothJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalConnectivityBluetooth Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option ipAddress = default; + Option macAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ipAddress": + ipAddress = new Option(utf8JsonReader.GetString()!); + break; + case "macAddress": + macAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalConnectivityBluetooth(ipAddress, macAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalConnectivityBluetooth terminalConnectivityBluetooth, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalConnectivityBluetooth, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalConnectivityBluetooth terminalConnectivityBluetooth, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalConnectivityBluetooth._IpAddressOption.IsSet) + if (terminalConnectivityBluetooth.IpAddress != null) + writer.WriteString("ipAddress", terminalConnectivityBluetooth.IpAddress); + + if (terminalConnectivityBluetooth._MacAddressOption.IsSet) + if (terminalConnectivityBluetooth.MacAddress != null) + writer.WriteString("macAddress", terminalConnectivityBluetooth.MacAddress); + } + } +} diff --git a/Adyen/Management/Models/TerminalConnectivityCellular.cs b/Adyen/Management/Models/TerminalConnectivityCellular.cs new file mode 100644 index 000000000..f57e4e0b3 --- /dev/null +++ b/Adyen/Management/Models/TerminalConnectivityCellular.cs @@ -0,0 +1,360 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalConnectivityCellular. + /// + public partial class TerminalConnectivityCellular : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The integrated circuit card identifier (ICCID) of the primary SIM card in the terminal. + /// The integrated circuit card identifier (ICCID) of the secondary SIM card in the terminal, typically used for a [third-party SIM card](https://docs.adyen.com/point-of-sale/design-your-integration/network-and-connectivity/cellular-failover/#using-a-third-party-sim-card). + /// On a terminal that supports 3G or 4G connectivity, indicates the status of the primary SIM card in the terminal. + [JsonConstructor] + public TerminalConnectivityCellular(Option iccid = default, Option iccid2 = default, Option status = default) + { + _IccidOption = iccid; + _Iccid2Option = iccid2; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalConnectivityCellular() + { + } + + partial void OnCreated(); + + /// + /// On a terminal that supports 3G or 4G connectivity, indicates the status of the primary SIM card in the terminal. + /// + /// On a terminal that supports 3G or 4G connectivity, indicates the status of the primary SIM card in the terminal. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Activated - activated + /// + public static readonly StatusEnum Activated = new("activated"); + + /// + /// StatusEnum.Deactivated - deactivated + /// + public static readonly StatusEnum Deactivated = new("deactivated"); + + /// + /// StatusEnum.Deprecated - deprecated + /// + public static readonly StatusEnum Deprecated = new("deprecated"); + + /// + /// StatusEnum.Inventory - inventory + /// + public static readonly StatusEnum Inventory = new("inventory"); + + /// + /// StatusEnum.ReadyForActivation - readyForActivation + /// + public static readonly StatusEnum ReadyForActivation = new("readyForActivation"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "activated" => StatusEnum.Activated, + "deactivated" => StatusEnum.Deactivated, + "deprecated" => StatusEnum.Deprecated, + "inventory" => StatusEnum.Inventory, + "readyForActivation" => StatusEnum.ReadyForActivation, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Activated) + return "activated"; + + if (value == StatusEnum.Deactivated) + return "deactivated"; + + if (value == StatusEnum.Deprecated) + return "deprecated"; + + if (value == StatusEnum.Inventory) + return "inventory"; + + if (value == StatusEnum.ReadyForActivation) + return "readyForActivation"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// On a terminal that supports 3G or 4G connectivity, indicates the status of the primary SIM card in the terminal. + /// + /// On a terminal that supports 3G or 4G connectivity, indicates the status of the primary SIM card in the terminal. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IccidOption { get; private set; } + + /// + /// The integrated circuit card identifier (ICCID) of the primary SIM card in the terminal. + /// + /// The integrated circuit card identifier (ICCID) of the primary SIM card in the terminal. + [JsonPropertyName("iccid")] + public string? Iccid { get { return this._IccidOption; } set { this._IccidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Iccid2Option { get; private set; } + + /// + /// The integrated circuit card identifier (ICCID) of the secondary SIM card in the terminal, typically used for a [third-party SIM card](https://docs.adyen.com/point-of-sale/design-your-integration/network-and-connectivity/cellular-failover/#using-a-third-party-sim-card). + /// + /// The integrated circuit card identifier (ICCID) of the secondary SIM card in the terminal, typically used for a [third-party SIM card](https://docs.adyen.com/point-of-sale/design-your-integration/network-and-connectivity/cellular-failover/#using-a-third-party-sim-card). + [JsonPropertyName("iccid2")] + public string? Iccid2 { get { return this._Iccid2Option; } set { this._Iccid2Option = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalConnectivityCellular {\n"); + sb.Append(" Iccid: ").Append(Iccid).Append("\n"); + sb.Append(" Iccid2: ").Append(Iccid2).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalConnectivityCellularJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalConnectivityCellular Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iccid = default; + Option iccid2 = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iccid": + iccid = new Option(utf8JsonReader.GetString()!); + break; + case "iccid2": + iccid2 = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TerminalConnectivityCellular.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + default: + break; + } + } + } + + + return new TerminalConnectivityCellular(iccid, iccid2, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalConnectivityCellular terminalConnectivityCellular, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalConnectivityCellular, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalConnectivityCellular terminalConnectivityCellular, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalConnectivityCellular._IccidOption.IsSet) + if (terminalConnectivityCellular.Iccid != null) + writer.WriteString("iccid", terminalConnectivityCellular.Iccid); + + if (terminalConnectivityCellular._Iccid2Option.IsSet) + if (terminalConnectivityCellular.Iccid2 != null) + writer.WriteString("iccid2", terminalConnectivityCellular.Iccid2); + + if (terminalConnectivityCellular._StatusOption.IsSet && terminalConnectivityCellular.Status != null) + { + string? statusRawValue = TerminalConnectivityCellular.StatusEnum.ToJsonValue(terminalConnectivityCellular._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalConnectivityEthernet.cs b/Adyen/Management/Models/TerminalConnectivityEthernet.cs new file mode 100644 index 000000000..ad59bd175 --- /dev/null +++ b/Adyen/Management/Models/TerminalConnectivityEthernet.cs @@ -0,0 +1,227 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalConnectivityEthernet. + /// + public partial class TerminalConnectivityEthernet : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The terminal's ethernet IP address. + /// The ethernet link negotiation that the terminal uses. + /// The terminal's ethernet MAC address. + [JsonConstructor] + public TerminalConnectivityEthernet(Option ipAddress = default, Option linkNegotiation = default, Option macAddress = default) + { + _IpAddressOption = ipAddress; + _LinkNegotiationOption = linkNegotiation; + _MacAddressOption = macAddress; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalConnectivityEthernet() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IpAddressOption { get; private set; } + + /// + /// The terminal's ethernet IP address. + /// + /// The terminal's ethernet IP address. + [JsonPropertyName("ipAddress")] + public string? IpAddress { get { return this._IpAddressOption; } set { this._IpAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinkNegotiationOption { get; private set; } + + /// + /// The ethernet link negotiation that the terminal uses. + /// + /// The ethernet link negotiation that the terminal uses. + [JsonPropertyName("linkNegotiation")] + public string? LinkNegotiation { get { return this._LinkNegotiationOption; } set { this._LinkNegotiationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MacAddressOption { get; private set; } + + /// + /// The terminal's ethernet MAC address. + /// + /// The terminal's ethernet MAC address. + [JsonPropertyName("macAddress")] + public string? MacAddress { get { return this._MacAddressOption; } set { this._MacAddressOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalConnectivityEthernet {\n"); + sb.Append(" IpAddress: ").Append(IpAddress).Append("\n"); + sb.Append(" LinkNegotiation: ").Append(LinkNegotiation).Append("\n"); + sb.Append(" MacAddress: ").Append(MacAddress).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalConnectivityEthernetJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalConnectivityEthernet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option ipAddress = default; + Option linkNegotiation = default; + Option macAddress = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ipAddress": + ipAddress = new Option(utf8JsonReader.GetString()!); + break; + case "linkNegotiation": + linkNegotiation = new Option(utf8JsonReader.GetString()!); + break; + case "macAddress": + macAddress = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalConnectivityEthernet(ipAddress, linkNegotiation, macAddress); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalConnectivityEthernet terminalConnectivityEthernet, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalConnectivityEthernet, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalConnectivityEthernet terminalConnectivityEthernet, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalConnectivityEthernet._IpAddressOption.IsSet) + if (terminalConnectivityEthernet.IpAddress != null) + writer.WriteString("ipAddress", terminalConnectivityEthernet.IpAddress); + + if (terminalConnectivityEthernet._LinkNegotiationOption.IsSet) + if (terminalConnectivityEthernet.LinkNegotiation != null) + writer.WriteString("linkNegotiation", terminalConnectivityEthernet.LinkNegotiation); + + if (terminalConnectivityEthernet._MacAddressOption.IsSet) + if (terminalConnectivityEthernet.MacAddress != null) + writer.WriteString("macAddress", terminalConnectivityEthernet.MacAddress); + } + } +} diff --git a/Adyen/Management/Models/TerminalConnectivityWifi.cs b/Adyen/Management/Models/TerminalConnectivityWifi.cs new file mode 100644 index 000000000..54a531110 --- /dev/null +++ b/Adyen/Management/Models/TerminalConnectivityWifi.cs @@ -0,0 +1,227 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalConnectivityWifi. + /// + public partial class TerminalConnectivityWifi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The terminal's IP address in the Wi-Fi network. + /// The terminal's MAC address in the Wi-Fi network. + /// The SSID of the Wi-Fi network that the terminal is connected to. + [JsonConstructor] + public TerminalConnectivityWifi(Option ipAddress = default, Option macAddress = default, Option ssid = default) + { + _IpAddressOption = ipAddress; + _MacAddressOption = macAddress; + _SsidOption = ssid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalConnectivityWifi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IpAddressOption { get; private set; } + + /// + /// The terminal's IP address in the Wi-Fi network. + /// + /// The terminal's IP address in the Wi-Fi network. + [JsonPropertyName("ipAddress")] + public string? IpAddress { get { return this._IpAddressOption; } set { this._IpAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MacAddressOption { get; private set; } + + /// + /// The terminal's MAC address in the Wi-Fi network. + /// + /// The terminal's MAC address in the Wi-Fi network. + [JsonPropertyName("macAddress")] + public string? MacAddress { get { return this._MacAddressOption; } set { this._MacAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SsidOption { get; private set; } + + /// + /// The SSID of the Wi-Fi network that the terminal is connected to. + /// + /// The SSID of the Wi-Fi network that the terminal is connected to. + [JsonPropertyName("ssid")] + public string? Ssid { get { return this._SsidOption; } set { this._SsidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalConnectivityWifi {\n"); + sb.Append(" IpAddress: ").Append(IpAddress).Append("\n"); + sb.Append(" MacAddress: ").Append(MacAddress).Append("\n"); + sb.Append(" Ssid: ").Append(Ssid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalConnectivityWifiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalConnectivityWifi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option ipAddress = default; + Option macAddress = default; + Option ssid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ipAddress": + ipAddress = new Option(utf8JsonReader.GetString()!); + break; + case "macAddress": + macAddress = new Option(utf8JsonReader.GetString()!); + break; + case "ssid": + ssid = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalConnectivityWifi(ipAddress, macAddress, ssid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalConnectivityWifi terminalConnectivityWifi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalConnectivityWifi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalConnectivityWifi terminalConnectivityWifi, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalConnectivityWifi._IpAddressOption.IsSet) + if (terminalConnectivityWifi.IpAddress != null) + writer.WriteString("ipAddress", terminalConnectivityWifi.IpAddress); + + if (terminalConnectivityWifi._MacAddressOption.IsSet) + if (terminalConnectivityWifi.MacAddress != null) + writer.WriteString("macAddress", terminalConnectivityWifi.MacAddress); + + if (terminalConnectivityWifi._SsidOption.IsSet) + if (terminalConnectivityWifi.Ssid != null) + writer.WriteString("ssid", terminalConnectivityWifi.Ssid); + } + } +} diff --git a/Adyen/Management/Models/TerminalInstructions.cs b/Adyen/Management/Models/TerminalInstructions.cs new file mode 100644 index 000000000..38f23a94b --- /dev/null +++ b/Adyen/Management/Models/TerminalInstructions.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalInstructions. + /// + public partial class TerminalInstructions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the Adyen app on the payment terminal restarts automatically when the configuration is updated. + [JsonConstructor] + public TerminalInstructions(Option adyenAppRestart = default) + { + _AdyenAppRestartOption = adyenAppRestart; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalInstructions() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenAppRestartOption { get; private set; } + + /// + /// Indicates whether the Adyen app on the payment terminal restarts automatically when the configuration is updated. + /// + /// Indicates whether the Adyen app on the payment terminal restarts automatically when the configuration is updated. + [JsonPropertyName("adyenAppRestart")] + public bool? AdyenAppRestart { get { return this._AdyenAppRestartOption; } set { this._AdyenAppRestartOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalInstructions {\n"); + sb.Append(" AdyenAppRestart: ").Append(AdyenAppRestart).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalInstructionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalInstructions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option adyenAppRestart = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "adyenAppRestart": + adyenAppRestart = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new TerminalInstructions(adyenAppRestart); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalInstructions terminalInstructions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalInstructions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalInstructions terminalInstructions, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalInstructions._AdyenAppRestartOption.IsSet) + writer.WriteBoolean("adyenAppRestart", terminalInstructions._AdyenAppRestartOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/TerminalModelsResponse.cs b/Adyen/Management/Models/TerminalModelsResponse.cs new file mode 100644 index 000000000..9a74405f4 --- /dev/null +++ b/Adyen/Management/Models/TerminalModelsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalModelsResponse. + /// + public partial class TerminalModelsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The terminal models that the API credential has access to. + [JsonConstructor] + public TerminalModelsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalModelsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// The terminal models that the API credential has access to. + /// + /// The terminal models that the API credential has access to. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalModelsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalModelsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalModelsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalModelsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalModelsResponse terminalModelsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalModelsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalModelsResponse terminalModelsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalModelsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, terminalModelsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalOrder.cs b/Adyen/Management/Models/TerminalOrder.cs new file mode 100644 index 000000000..68b679f57 --- /dev/null +++ b/Adyen/Management/Models/TerminalOrder.cs @@ -0,0 +1,353 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalOrder. + /// + public partial class TerminalOrder : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// billingEntity + /// The merchant-defined purchase order number. This will be printed on the packing list. + /// The unique identifier of the order. + /// The products included in the order. + /// The date and time that the order was placed, in UTC ISO 8601 format. For example, \"2011-12-03T10:15:30Z\". + /// shippingLocation + /// The processing status of the order. + /// The URL, provided by the carrier company, where the shipment can be tracked. + [JsonConstructor] + public TerminalOrder(Option billingEntity = default, Option customerOrderReference = default, Option id = default, Option?> items = default, Option orderDate = default, Option shippingLocation = default, Option status = default, Option trackingUrl = default) + { + _BillingEntityOption = billingEntity; + _CustomerOrderReferenceOption = customerOrderReference; + _IdOption = id; + _ItemsOption = items; + _OrderDateOption = orderDate; + _ShippingLocationOption = shippingLocation; + _StatusOption = status; + _TrackingUrlOption = trackingUrl; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalOrder() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingEntityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingEntity")] + public BillingEntity? BillingEntity { get { return this._BillingEntityOption; } set { this._BillingEntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomerOrderReferenceOption { get; private set; } + + /// + /// The merchant-defined purchase order number. This will be printed on the packing list. + /// + /// The merchant-defined purchase order number. This will be printed on the packing list. + [JsonPropertyName("customerOrderReference")] + public string? CustomerOrderReference { get { return this._CustomerOrderReferenceOption; } set { this._CustomerOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the order. + /// + /// The unique identifier of the order. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsOption { get; private set; } + + /// + /// The products included in the order. + /// + /// The products included in the order. + [JsonPropertyName("items")] + public List? Items { get { return this._ItemsOption; } set { this._ItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderDateOption { get; private set; } + + /// + /// The date and time that the order was placed, in UTC ISO 8601 format. For example, \"2011-12-03T10:15:30Z\". + /// + /// The date and time that the order was placed, in UTC ISO 8601 format. For example, \"2011-12-03T10:15:30Z\". + [JsonPropertyName("orderDate")] + public string? OrderDate { get { return this._OrderDateOption; } set { this._OrderDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShippingLocationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shippingLocation")] + public ShippingLocation? ShippingLocation { get { return this._ShippingLocationOption; } set { this._ShippingLocationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The processing status of the order. + /// + /// The processing status of the order. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingUrlOption { get; private set; } + + /// + /// The URL, provided by the carrier company, where the shipment can be tracked. + /// + /// The URL, provided by the carrier company, where the shipment can be tracked. + [JsonPropertyName("trackingUrl")] + public string? TrackingUrl { get { return this._TrackingUrlOption; } set { this._TrackingUrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalOrder {\n"); + sb.Append(" BillingEntity: ").Append(BillingEntity).Append("\n"); + sb.Append(" CustomerOrderReference: ").Append(CustomerOrderReference).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Items: ").Append(Items).Append("\n"); + sb.Append(" OrderDate: ").Append(OrderDate).Append("\n"); + sb.Append(" ShippingLocation: ").Append(ShippingLocation).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TrackingUrl: ").Append(TrackingUrl).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalOrderJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalOrder Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingEntity = default; + Option customerOrderReference = default; + Option id = default; + Option?> items = default; + Option orderDate = default; + Option shippingLocation = default; + Option status = default; + Option trackingUrl = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingEntity": + billingEntity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "customerOrderReference": + customerOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "items": + items = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderDate": + orderDate = new Option(utf8JsonReader.GetString()!); + break; + case "shippingLocation": + shippingLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "trackingUrl": + trackingUrl = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalOrder(billingEntity, customerOrderReference, id, items, orderDate, shippingLocation, status, trackingUrl); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalOrder terminalOrder, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalOrder, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalOrder terminalOrder, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalOrder._BillingEntityOption.IsSet) + { + writer.WritePropertyName("billingEntity"); + JsonSerializer.Serialize(writer, terminalOrder.BillingEntity, jsonSerializerOptions); + } + if (terminalOrder._CustomerOrderReferenceOption.IsSet) + if (terminalOrder.CustomerOrderReference != null) + writer.WriteString("customerOrderReference", terminalOrder.CustomerOrderReference); + + if (terminalOrder._IdOption.IsSet) + if (terminalOrder.Id != null) + writer.WriteString("id", terminalOrder.Id); + + if (terminalOrder._ItemsOption.IsSet) + { + writer.WritePropertyName("items"); + JsonSerializer.Serialize(writer, terminalOrder.Items, jsonSerializerOptions); + } + if (terminalOrder._OrderDateOption.IsSet) + if (terminalOrder.OrderDate != null) + writer.WriteString("orderDate", terminalOrder.OrderDate); + + if (terminalOrder._ShippingLocationOption.IsSet) + { + writer.WritePropertyName("shippingLocation"); + JsonSerializer.Serialize(writer, terminalOrder.ShippingLocation, jsonSerializerOptions); + } + if (terminalOrder._StatusOption.IsSet) + if (terminalOrder.Status != null) + writer.WriteString("status", terminalOrder.Status); + + if (terminalOrder._TrackingUrlOption.IsSet) + if (terminalOrder.TrackingUrl != null) + writer.WriteString("trackingUrl", terminalOrder.TrackingUrl); + } + } +} diff --git a/Adyen/Management/Models/TerminalOrderRequest.cs b/Adyen/Management/Models/TerminalOrderRequest.cs new file mode 100644 index 000000000..a37bba037 --- /dev/null +++ b/Adyen/Management/Models/TerminalOrderRequest.cs @@ -0,0 +1,303 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalOrderRequest. + /// + public partial class TerminalOrderRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identification of the billing entity to use for the order. > When ordering products in Brazil, you do not need to include the `billingEntityId` in the request. + /// The merchant-defined purchase order reference. + /// The products included in the order. + /// Type of order + /// The identification of the shipping location to use for the order. + /// The tax number of the billing entity. + [JsonConstructor] + public TerminalOrderRequest(Option billingEntityId = default, Option customerOrderReference = default, Option?> items = default, Option orderType = default, Option shippingLocationId = default, Option taxId = default) + { + _BillingEntityIdOption = billingEntityId; + _CustomerOrderReferenceOption = customerOrderReference; + _ItemsOption = items; + _OrderTypeOption = orderType; + _ShippingLocationIdOption = shippingLocationId; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalOrderRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingEntityIdOption { get; private set; } + + /// + /// The identification of the billing entity to use for the order. > When ordering products in Brazil, you do not need to include the `billingEntityId` in the request. + /// + /// The identification of the billing entity to use for the order. > When ordering products in Brazil, you do not need to include the `billingEntityId` in the request. + [JsonPropertyName("billingEntityId")] + public string? BillingEntityId { get { return this._BillingEntityIdOption; } set { this._BillingEntityIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomerOrderReferenceOption { get; private set; } + + /// + /// The merchant-defined purchase order reference. + /// + /// The merchant-defined purchase order reference. + [JsonPropertyName("customerOrderReference")] + public string? CustomerOrderReference { get { return this._CustomerOrderReferenceOption; } set { this._CustomerOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsOption { get; private set; } + + /// + /// The products included in the order. + /// + /// The products included in the order. + [JsonPropertyName("items")] + public List? Items { get { return this._ItemsOption; } set { this._ItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderTypeOption { get; private set; } + + /// + /// Type of order + /// + /// Type of order + [JsonPropertyName("orderType")] + public string? OrderType { get { return this._OrderTypeOption; } set { this._OrderTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShippingLocationIdOption { get; private set; } + + /// + /// The identification of the shipping location to use for the order. + /// + /// The identification of the shipping location to use for the order. + [JsonPropertyName("shippingLocationId")] + public string? ShippingLocationId { get { return this._ShippingLocationIdOption; } set { this._ShippingLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The tax number of the billing entity. + /// + /// The tax number of the billing entity. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalOrderRequest {\n"); + sb.Append(" BillingEntityId: ").Append(BillingEntityId).Append("\n"); + sb.Append(" CustomerOrderReference: ").Append(CustomerOrderReference).Append("\n"); + sb.Append(" Items: ").Append(Items).Append("\n"); + sb.Append(" OrderType: ").Append(OrderType).Append("\n"); + sb.Append(" ShippingLocationId: ").Append(ShippingLocationId).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalOrderRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalOrderRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingEntityId = default; + Option customerOrderReference = default; + Option?> items = default; + Option orderType = default; + Option shippingLocationId = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingEntityId": + billingEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "customerOrderReference": + customerOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "items": + items = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderType": + orderType = new Option(utf8JsonReader.GetString()!); + break; + case "shippingLocationId": + shippingLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalOrderRequest(billingEntityId, customerOrderReference, items, orderType, shippingLocationId, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalOrderRequest terminalOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalOrderRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalOrderRequest terminalOrderRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalOrderRequest._BillingEntityIdOption.IsSet) + if (terminalOrderRequest.BillingEntityId != null) + writer.WriteString("billingEntityId", terminalOrderRequest.BillingEntityId); + + if (terminalOrderRequest._CustomerOrderReferenceOption.IsSet) + if (terminalOrderRequest.CustomerOrderReference != null) + writer.WriteString("customerOrderReference", terminalOrderRequest.CustomerOrderReference); + + if (terminalOrderRequest._ItemsOption.IsSet) + { + writer.WritePropertyName("items"); + JsonSerializer.Serialize(writer, terminalOrderRequest.Items, jsonSerializerOptions); + } + if (terminalOrderRequest._OrderTypeOption.IsSet) + if (terminalOrderRequest.OrderType != null) + writer.WriteString("orderType", terminalOrderRequest.OrderType); + + if (terminalOrderRequest._ShippingLocationIdOption.IsSet) + if (terminalOrderRequest.ShippingLocationId != null) + writer.WriteString("shippingLocationId", terminalOrderRequest.ShippingLocationId); + + if (terminalOrderRequest._TaxIdOption.IsSet) + if (terminalOrderRequest.TaxId != null) + writer.WriteString("taxId", terminalOrderRequest.TaxId); + } + } +} diff --git a/Adyen/Management/Models/TerminalOrdersResponse.cs b/Adyen/Management/Models/TerminalOrdersResponse.cs new file mode 100644 index 000000000..1ff8ec908 --- /dev/null +++ b/Adyen/Management/Models/TerminalOrdersResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalOrdersResponse. + /// + public partial class TerminalOrdersResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of orders for payment terminal packages and parts. + [JsonConstructor] + public TerminalOrdersResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalOrdersResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List of orders for payment terminal packages and parts. + /// + /// List of orders for payment terminal packages and parts. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalOrdersResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalOrdersResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalOrdersResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalOrdersResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalOrdersResponse terminalOrdersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalOrdersResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalOrdersResponse terminalOrdersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalOrdersResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, terminalOrdersResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalProduct.cs b/Adyen/Management/Models/TerminalProduct.cs new file mode 100644 index 000000000..2924aaa5e --- /dev/null +++ b/Adyen/Management/Models/TerminalProduct.cs @@ -0,0 +1,279 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalProduct. + /// + public partial class TerminalProduct : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Information about items included and integration options. + /// The unique identifier of the product. + /// A list of parts included in the terminal package. + /// The descriptive name of the product. + /// price + [JsonConstructor] + public TerminalProduct(Option description = default, Option id = default, Option?> itemsIncluded = default, Option name = default, Option price = default) + { + _DescriptionOption = description; + _IdOption = id; + _ItemsIncludedOption = itemsIncluded; + _NameOption = name; + _PriceOption = price; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalProduct() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Information about items included and integration options. + /// + /// Information about items included and integration options. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the product. + /// + /// The unique identifier of the product. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ItemsIncludedOption { get; private set; } + + /// + /// A list of parts included in the terminal package. + /// + /// A list of parts included in the terminal package. + [JsonPropertyName("itemsIncluded")] + public List? ItemsIncluded { get { return this._ItemsIncludedOption; } set { this._ItemsIncludedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The descriptive name of the product. + /// + /// The descriptive name of the product. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("price")] + public TerminalProductPrice? Price { get { return this._PriceOption; } set { this._PriceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalProduct {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" ItemsIncluded: ").Append(ItemsIncluded).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Price: ").Append(Price).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalProductJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalProduct Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option?> itemsIncluded = default; + Option name = default; + Option price = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "itemsIncluded": + itemsIncluded = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "price": + price = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalProduct(description, id, itemsIncluded, name, price); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalProduct terminalProduct, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalProduct, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalProduct terminalProduct, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalProduct._DescriptionOption.IsSet) + if (terminalProduct.Description != null) + writer.WriteString("description", terminalProduct.Description); + + if (terminalProduct._IdOption.IsSet) + if (terminalProduct.Id != null) + writer.WriteString("id", terminalProduct.Id); + + if (terminalProduct._ItemsIncludedOption.IsSet) + { + writer.WritePropertyName("itemsIncluded"); + JsonSerializer.Serialize(writer, terminalProduct.ItemsIncluded, jsonSerializerOptions); + } + if (terminalProduct._NameOption.IsSet) + if (terminalProduct.Name != null) + writer.WriteString("name", terminalProduct.Name); + + if (terminalProduct._PriceOption.IsSet) + { + writer.WritePropertyName("price"); + JsonSerializer.Serialize(writer, terminalProduct.Price, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalProductPrice.cs b/Adyen/Management/Models/TerminalProductPrice.cs new file mode 100644 index 000000000..e6883ffe2 --- /dev/null +++ b/Adyen/Management/Models/TerminalProductPrice.cs @@ -0,0 +1,201 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalProductPrice. + /// + public partial class TerminalProductPrice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// The price of the item. + [JsonConstructor] + public TerminalProductPrice(Option currency = default, Option value = default) + { + _CurrencyOption = currency; + _ValueOption = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalProductPrice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueOption { get; private set; } + + /// + /// The price of the item. + /// + /// The price of the item. + [JsonPropertyName("value")] + public double? Value { get { return this._ValueOption; } set { this._ValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalProductPrice {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalProductPriceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalProductPrice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + + return new TerminalProductPrice(currency, value); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalProductPrice terminalProductPrice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalProductPrice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalProductPrice terminalProductPrice, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalProductPrice._CurrencyOption.IsSet) + if (terminalProductPrice.Currency != null) + writer.WriteString("currency", terminalProductPrice.Currency); + + if (terminalProductPrice._ValueOption.IsSet) + writer.WriteNumber("value", terminalProductPrice._ValueOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/TerminalProductsResponse.cs b/Adyen/Management/Models/TerminalProductsResponse.cs new file mode 100644 index 000000000..504eeb19a --- /dev/null +++ b/Adyen/Management/Models/TerminalProductsResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalProductsResponse. + /// + public partial class TerminalProductsResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Terminal products that can be ordered. + [JsonConstructor] + public TerminalProductsResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalProductsResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Terminal products that can be ordered. + /// + /// Terminal products that can be ordered. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalProductsResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalProductsResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalProductsResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalProductsResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalProductsResponse terminalProductsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalProductsResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalProductsResponse terminalProductsResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalProductsResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, terminalProductsResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TerminalReassignmentRequest.cs b/Adyen/Management/Models/TerminalReassignmentRequest.cs new file mode 100644 index 000000000..e9a1c66c0 --- /dev/null +++ b/Adyen/Management/Models/TerminalReassignmentRequest.cs @@ -0,0 +1,251 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalReassignmentRequest. + /// + public partial class TerminalReassignmentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the company account to which the terminal is reassigned. + /// Must be specified when reassigning terminals to a merchant account: - If set to **true**, reassigns terminals to the inventory of the merchant account and the terminals cannot process transactions. - If set to **false**, reassigns terminals directly to the merchant account and the terminals can process transactions. + /// The unique identifier of the merchant account to which the terminal is reassigned. When reassigning terminals to a merchant account, you must specify the `inventory` field. + /// The unique identifier of the store to which the terminal is reassigned. + [JsonConstructor] + public TerminalReassignmentRequest(Option companyId = default, Option inventory = default, Option merchantId = default, Option storeId = default) + { + _CompanyIdOption = companyId; + _InventoryOption = inventory; + _MerchantIdOption = merchantId; + _StoreIdOption = storeId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalReassignmentRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account to which the terminal is reassigned. + /// + /// The unique identifier of the company account to which the terminal is reassigned. + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InventoryOption { get; private set; } + + /// + /// Must be specified when reassigning terminals to a merchant account: - If set to **true**, reassigns terminals to the inventory of the merchant account and the terminals cannot process transactions. - If set to **false**, reassigns terminals directly to the merchant account and the terminals can process transactions. + /// + /// Must be specified when reassigning terminals to a merchant account: - If set to **true**, reassigns terminals to the inventory of the merchant account and the terminals cannot process transactions. - If set to **false**, reassigns terminals directly to the merchant account and the terminals can process transactions. + [JsonPropertyName("inventory")] + public bool? Inventory { get { return this._InventoryOption; } set { this._InventoryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account to which the terminal is reassigned. When reassigning terminals to a merchant account, you must specify the `inventory` field. + /// + /// The unique identifier of the merchant account to which the terminal is reassigned. When reassigning terminals to a merchant account, you must specify the `inventory` field. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the store to which the terminal is reassigned. + /// + /// The unique identifier of the store to which the terminal is reassigned. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalReassignmentRequest {\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" Inventory: ").Append(Inventory).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalReassignmentRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalReassignmentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option companyId = default; + Option inventory = default; + Option merchantId = default; + Option storeId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "inventory": + inventory = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalReassignmentRequest(companyId, inventory, merchantId, storeId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalReassignmentRequest terminalReassignmentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalReassignmentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalReassignmentRequest terminalReassignmentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalReassignmentRequest._CompanyIdOption.IsSet) + if (terminalReassignmentRequest.CompanyId != null) + writer.WriteString("companyId", terminalReassignmentRequest.CompanyId); + + if (terminalReassignmentRequest._InventoryOption.IsSet) + writer.WriteBoolean("inventory", terminalReassignmentRequest._InventoryOption.Value!.Value); + + if (terminalReassignmentRequest._MerchantIdOption.IsSet) + if (terminalReassignmentRequest.MerchantId != null) + writer.WriteString("merchantId", terminalReassignmentRequest.MerchantId); + + if (terminalReassignmentRequest._StoreIdOption.IsSet) + if (terminalReassignmentRequest.StoreId != null) + writer.WriteString("storeId", terminalReassignmentRequest.StoreId); + } + } +} diff --git a/Adyen/Management/Models/TerminalReassignmentTarget.cs b/Adyen/Management/Models/TerminalReassignmentTarget.cs new file mode 100644 index 000000000..1df1b09e5 --- /dev/null +++ b/Adyen/Management/Models/TerminalReassignmentTarget.cs @@ -0,0 +1,245 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalReassignmentTarget. + /// + public partial class TerminalReassignmentTarget : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the terminal is reassigned to the inventory of the merchant account. - If **true**, the terminal is in the inventory of the merchant account and cannot process transactions. - If **false**, the terminal is reassigned directly to the merchant account and can process transactions. + /// The unique identifier of the company account to which the terminal is reassigned. + /// The unique identifier of the merchant account to which the terminal is reassigned. + /// The unique identifier of the store to which the terminal is reassigned. + [JsonConstructor] + public TerminalReassignmentTarget(bool inventory, Option companyId = default, Option merchantId = default, Option storeId = default) + { + Inventory = inventory; + _CompanyIdOption = companyId; + _MerchantIdOption = merchantId; + _StoreIdOption = storeId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalReassignmentTarget() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the terminal is reassigned to the inventory of the merchant account. - If **true**, the terminal is in the inventory of the merchant account and cannot process transactions. - If **false**, the terminal is reassigned directly to the merchant account and can process transactions. + /// + /// Indicates if the terminal is reassigned to the inventory of the merchant account. - If **true**, the terminal is in the inventory of the merchant account and cannot process transactions. - If **false**, the terminal is reassigned directly to the merchant account and can process transactions. + [JsonPropertyName("inventory")] + public bool Inventory { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account to which the terminal is reassigned. + /// + /// The unique identifier of the company account to which the terminal is reassigned. + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account to which the terminal is reassigned. + /// + /// The unique identifier of the merchant account to which the terminal is reassigned. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the store to which the terminal is reassigned. + /// + /// The unique identifier of the store to which the terminal is reassigned. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalReassignmentTarget {\n"); + sb.Append(" Inventory: ").Append(Inventory).Append("\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalReassignmentTargetJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalReassignmentTarget Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option inventory = default; + Option companyId = default; + Option merchantId = default; + Option storeId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "inventory": + inventory = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!inventory.IsSet) + throw new ArgumentException("Property is required for class TerminalReassignmentTarget.", nameof(inventory)); + + return new TerminalReassignmentTarget(inventory.Value!.Value!, companyId, merchantId, storeId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalReassignmentTarget terminalReassignmentTarget, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalReassignmentTarget, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalReassignmentTarget terminalReassignmentTarget, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("inventory", terminalReassignmentTarget.Inventory); + + if (terminalReassignmentTarget._CompanyIdOption.IsSet) + if (terminalReassignmentTarget.CompanyId != null) + writer.WriteString("companyId", terminalReassignmentTarget.CompanyId); + + if (terminalReassignmentTarget._MerchantIdOption.IsSet) + if (terminalReassignmentTarget.MerchantId != null) + writer.WriteString("merchantId", terminalReassignmentTarget.MerchantId); + + if (terminalReassignmentTarget._StoreIdOption.IsSet) + if (terminalReassignmentTarget.StoreId != null) + writer.WriteString("storeId", terminalReassignmentTarget.StoreId); + } + } +} diff --git a/Adyen/Management/Models/TerminalSettings.cs b/Adyen/Management/Models/TerminalSettings.cs new file mode 100644 index 000000000..a9d2c178b --- /dev/null +++ b/Adyen/Management/Models/TerminalSettings.cs @@ -0,0 +1,707 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TerminalSettings. + /// + public partial class TerminalSettings : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cardholderReceipt + /// connectivity + /// Settings for tipping with or without predefined options to choose from. The maximum number of predefined options is four, or three plus the option to enter a custom tip. + /// hardware + /// localization + /// nexo + /// offlineProcessing + /// opi + /// passcodes + /// payAtTable + /// payment + /// receiptOptions + /// receiptPrinting + /// refunds + /// signature + /// standalone + /// storeAndForward + /// surcharge + /// tapToPay + /// terminalInstructions + /// timeouts + /// wifiProfiles + [JsonConstructor] + public TerminalSettings(Option cardholderReceipt = default, Option connectivity = default, Option?> gratuities = default, Option hardware = default, Option localization = default, Option nexo = default, Option offlineProcessing = default, Option opi = default, Option passcodes = default, Option payAtTable = default, Option payment = default, Option receiptOptions = default, Option receiptPrinting = default, Option refunds = default, Option signature = default, Option standalone = default, Option storeAndForward = default, Option surcharge = default, Option tapToPay = default, Option terminalInstructions = default, Option timeouts = default, Option wifiProfiles = default) + { + _CardholderReceiptOption = cardholderReceipt; + _ConnectivityOption = connectivity; + _GratuitiesOption = gratuities; + _HardwareOption = hardware; + _LocalizationOption = localization; + _NexoOption = nexo; + _OfflineProcessingOption = offlineProcessing; + _OpiOption = opi; + _PasscodesOption = passcodes; + _PayAtTableOption = payAtTable; + _PaymentOption = payment; + _ReceiptOptionsOption = receiptOptions; + _ReceiptPrintingOption = receiptPrinting; + _RefundsOption = refunds; + _SignatureOption = signature; + _StandaloneOption = standalone; + _StoreAndForwardOption = storeAndForward; + _SurchargeOption = surcharge; + _TapToPayOption = tapToPay; + _TerminalInstructionsOption = terminalInstructions; + _TimeoutsOption = timeouts; + _WifiProfilesOption = wifiProfiles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalSettings() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardholderReceiptOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cardholderReceipt")] + public CardholderReceipt? CardholderReceipt { get { return this._CardholderReceiptOption; } set { this._CardholderReceiptOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ConnectivityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("connectivity")] + public Connectivity? Connectivity { get { return this._ConnectivityOption; } set { this._ConnectivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _GratuitiesOption { get; private set; } + + /// + /// Settings for tipping with or without predefined options to choose from. The maximum number of predefined options is four, or three plus the option to enter a custom tip. + /// + /// Settings for tipping with or without predefined options to choose from. The maximum number of predefined options is four, or three plus the option to enter a custom tip. + [JsonPropertyName("gratuities")] + public List? Gratuities { get { return this._GratuitiesOption; } set { this._GratuitiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HardwareOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("hardware")] + public Hardware? Hardware { get { return this._HardwareOption; } set { this._HardwareOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LocalizationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("localization")] + public Localization? Localization { get { return this._LocalizationOption; } set { this._LocalizationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NexoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nexo")] + public Nexo? Nexo { get { return this._NexoOption; } set { this._NexoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OfflineProcessingOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("offlineProcessing")] + public OfflineProcessing? OfflineProcessing { get { return this._OfflineProcessingOption; } set { this._OfflineProcessingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("opi")] + public Opi? Opi { get { return this._OpiOption; } set { this._OpiOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasscodesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("passcodes")] + public Passcodes? Passcodes { get { return this._PasscodesOption; } set { this._PasscodesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayAtTableOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payAtTable")] + public PayAtTable? PayAtTable { get { return this._PayAtTableOption; } set { this._PayAtTableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("payment")] + public Payment? Payment { get { return this._PaymentOption; } set { this._PaymentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiptOptionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("receiptOptions")] + public ReceiptOptions? ReceiptOptions { get { return this._ReceiptOptionsOption; } set { this._ReceiptOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiptPrintingOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("receiptPrinting")] + public ReceiptPrinting? ReceiptPrinting { get { return this._ReceiptPrintingOption; } set { this._ReceiptPrintingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("refunds")] + public Refunds? Refunds { get { return this._RefundsOption; } set { this._RefundsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SignatureOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("signature")] + public Signature? Signature { get { return this._SignatureOption; } set { this._SignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StandaloneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("standalone")] + public Standalone? Standalone { get { return this._StandaloneOption; } set { this._StandaloneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreAndForwardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("storeAndForward")] + public StoreAndForward? StoreAndForward { get { return this._StoreAndForwardOption; } set { this._StoreAndForwardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SurchargeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("surcharge")] + public Surcharge? Surcharge { get { return this._SurchargeOption; } set { this._SurchargeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TapToPayOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tapToPay")] + public TapToPay? TapToPay { get { return this._TapToPayOption; } set { this._TapToPayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalInstructionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("terminalInstructions")] + public TerminalInstructions? TerminalInstructions { get { return this._TerminalInstructionsOption; } set { this._TerminalInstructionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeoutsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("timeouts")] + public Timeouts? Timeouts { get { return this._TimeoutsOption; } set { this._TimeoutsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WifiProfilesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("wifiProfiles")] + public WifiProfiles? WifiProfiles { get { return this._WifiProfilesOption; } set { this._WifiProfilesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalSettings {\n"); + sb.Append(" CardholderReceipt: ").Append(CardholderReceipt).Append("\n"); + sb.Append(" Connectivity: ").Append(Connectivity).Append("\n"); + sb.Append(" Gratuities: ").Append(Gratuities).Append("\n"); + sb.Append(" Hardware: ").Append(Hardware).Append("\n"); + sb.Append(" Localization: ").Append(Localization).Append("\n"); + sb.Append(" Nexo: ").Append(Nexo).Append("\n"); + sb.Append(" OfflineProcessing: ").Append(OfflineProcessing).Append("\n"); + sb.Append(" Opi: ").Append(Opi).Append("\n"); + sb.Append(" Passcodes: ").Append(Passcodes).Append("\n"); + sb.Append(" PayAtTable: ").Append(PayAtTable).Append("\n"); + sb.Append(" Payment: ").Append(Payment).Append("\n"); + sb.Append(" ReceiptOptions: ").Append(ReceiptOptions).Append("\n"); + sb.Append(" ReceiptPrinting: ").Append(ReceiptPrinting).Append("\n"); + sb.Append(" Refunds: ").Append(Refunds).Append("\n"); + sb.Append(" Signature: ").Append(Signature).Append("\n"); + sb.Append(" Standalone: ").Append(Standalone).Append("\n"); + sb.Append(" StoreAndForward: ").Append(StoreAndForward).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" TapToPay: ").Append(TapToPay).Append("\n"); + sb.Append(" TerminalInstructions: ").Append(TerminalInstructions).Append("\n"); + sb.Append(" Timeouts: ").Append(Timeouts).Append("\n"); + sb.Append(" WifiProfiles: ").Append(WifiProfiles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalSettingsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalSettings Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardholderReceipt = default; + Option connectivity = default; + Option?> gratuities = default; + Option hardware = default; + Option localization = default; + Option nexo = default; + Option offlineProcessing = default; + Option opi = default; + Option passcodes = default; + Option payAtTable = default; + Option payment = default; + Option receiptOptions = default; + Option receiptPrinting = default; + Option refunds = default; + Option signature = default; + Option standalone = default; + Option storeAndForward = default; + Option surcharge = default; + Option tapToPay = default; + Option terminalInstructions = default; + Option timeouts = default; + Option wifiProfiles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardholderReceipt": + cardholderReceipt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "connectivity": + connectivity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "gratuities": + gratuities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "hardware": + hardware = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localization": + localization = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nexo": + nexo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "offlineProcessing": + offlineProcessing = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "opi": + opi = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "passcodes": + passcodes = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payAtTable": + payAtTable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "payment": + payment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "receiptOptions": + receiptOptions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "receiptPrinting": + receiptPrinting = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "refunds": + refunds = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signature": + signature = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "standalone": + standalone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storeAndForward": + storeAndForward = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "surcharge": + surcharge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tapToPay": + tapToPay = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "terminalInstructions": + terminalInstructions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeouts": + timeouts = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wifiProfiles": + wifiProfiles = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TerminalSettings(cardholderReceipt, connectivity, gratuities, hardware, localization, nexo, offlineProcessing, opi, passcodes, payAtTable, payment, receiptOptions, receiptPrinting, refunds, signature, standalone, storeAndForward, surcharge, tapToPay, terminalInstructions, timeouts, wifiProfiles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalSettings terminalSettings, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalSettings, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalSettings terminalSettings, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalSettings._CardholderReceiptOption.IsSet) + { + writer.WritePropertyName("cardholderReceipt"); + JsonSerializer.Serialize(writer, terminalSettings.CardholderReceipt, jsonSerializerOptions); + } + if (terminalSettings._ConnectivityOption.IsSet) + { + writer.WritePropertyName("connectivity"); + JsonSerializer.Serialize(writer, terminalSettings.Connectivity, jsonSerializerOptions); + } + if (terminalSettings._GratuitiesOption.IsSet) + if (terminalSettings._GratuitiesOption.Value != null) + { + writer.WritePropertyName("gratuities"); + JsonSerializer.Serialize(writer, terminalSettings.Gratuities, jsonSerializerOptions); + } + else + writer.WriteNull("gratuities"); + if (terminalSettings._HardwareOption.IsSet) + { + writer.WritePropertyName("hardware"); + JsonSerializer.Serialize(writer, terminalSettings.Hardware, jsonSerializerOptions); + } + if (terminalSettings._LocalizationOption.IsSet) + { + writer.WritePropertyName("localization"); + JsonSerializer.Serialize(writer, terminalSettings.Localization, jsonSerializerOptions); + } + if (terminalSettings._NexoOption.IsSet) + { + writer.WritePropertyName("nexo"); + JsonSerializer.Serialize(writer, terminalSettings.Nexo, jsonSerializerOptions); + } + if (terminalSettings._OfflineProcessingOption.IsSet) + { + writer.WritePropertyName("offlineProcessing"); + JsonSerializer.Serialize(writer, terminalSettings.OfflineProcessing, jsonSerializerOptions); + } + if (terminalSettings._OpiOption.IsSet) + { + writer.WritePropertyName("opi"); + JsonSerializer.Serialize(writer, terminalSettings.Opi, jsonSerializerOptions); + } + if (terminalSettings._PasscodesOption.IsSet) + { + writer.WritePropertyName("passcodes"); + JsonSerializer.Serialize(writer, terminalSettings.Passcodes, jsonSerializerOptions); + } + if (terminalSettings._PayAtTableOption.IsSet) + { + writer.WritePropertyName("payAtTable"); + JsonSerializer.Serialize(writer, terminalSettings.PayAtTable, jsonSerializerOptions); + } + if (terminalSettings._PaymentOption.IsSet) + { + writer.WritePropertyName("payment"); + JsonSerializer.Serialize(writer, terminalSettings.Payment, jsonSerializerOptions); + } + if (terminalSettings._ReceiptOptionsOption.IsSet) + { + writer.WritePropertyName("receiptOptions"); + JsonSerializer.Serialize(writer, terminalSettings.ReceiptOptions, jsonSerializerOptions); + } + if (terminalSettings._ReceiptPrintingOption.IsSet) + { + writer.WritePropertyName("receiptPrinting"); + JsonSerializer.Serialize(writer, terminalSettings.ReceiptPrinting, jsonSerializerOptions); + } + if (terminalSettings._RefundsOption.IsSet) + { + writer.WritePropertyName("refunds"); + JsonSerializer.Serialize(writer, terminalSettings.Refunds, jsonSerializerOptions); + } + if (terminalSettings._SignatureOption.IsSet) + { + writer.WritePropertyName("signature"); + JsonSerializer.Serialize(writer, terminalSettings.Signature, jsonSerializerOptions); + } + if (terminalSettings._StandaloneOption.IsSet) + { + writer.WritePropertyName("standalone"); + JsonSerializer.Serialize(writer, terminalSettings.Standalone, jsonSerializerOptions); + } + if (terminalSettings._StoreAndForwardOption.IsSet) + { + writer.WritePropertyName("storeAndForward"); + JsonSerializer.Serialize(writer, terminalSettings.StoreAndForward, jsonSerializerOptions); + } + if (terminalSettings._SurchargeOption.IsSet) + { + writer.WritePropertyName("surcharge"); + JsonSerializer.Serialize(writer, terminalSettings.Surcharge, jsonSerializerOptions); + } + if (terminalSettings._TapToPayOption.IsSet) + { + writer.WritePropertyName("tapToPay"); + JsonSerializer.Serialize(writer, terminalSettings.TapToPay, jsonSerializerOptions); + } + if (terminalSettings._TerminalInstructionsOption.IsSet) + { + writer.WritePropertyName("terminalInstructions"); + JsonSerializer.Serialize(writer, terminalSettings.TerminalInstructions, jsonSerializerOptions); + } + if (terminalSettings._TimeoutsOption.IsSet) + { + writer.WritePropertyName("timeouts"); + JsonSerializer.Serialize(writer, terminalSettings.Timeouts, jsonSerializerOptions); + } + if (terminalSettings._WifiProfilesOption.IsSet) + { + writer.WritePropertyName("wifiProfiles"); + JsonSerializer.Serialize(writer, terminalSettings.WifiProfiles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TestCompanyWebhookRequest.cs b/Adyen/Management/Models/TestCompanyWebhookRequest.cs new file mode 100644 index 000000000..cabd35eef --- /dev/null +++ b/Adyen/Management/Models/TestCompanyWebhookRequest.cs @@ -0,0 +1,230 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TestCompanyWebhookRequest. + /// + public partial class TestCompanyWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of `merchantId` values for which test webhooks will be sent. The list can have a maximum of 20 `merchantId` values. If not specified, we send sample notifications to all the merchant accounts that the webhook is configured for. If this is more than 20 merchant accounts, use this list to specify a subset of the merchant accounts for which to send test notifications. + /// notification + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + [JsonConstructor] + public TestCompanyWebhookRequest(Option?> merchantIds = default, Option notification = default, Option?> types = default) + { + _MerchantIdsOption = merchantIds; + _NotificationOption = notification; + _TypesOption = types; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TestCompanyWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MerchantIdsOption { get; private set; } + + /// + /// List of `merchantId` values for which test webhooks will be sent. The list can have a maximum of 20 `merchantId` values. If not specified, we send sample notifications to all the merchant accounts that the webhook is configured for. If this is more than 20 merchant accounts, use this list to specify a subset of the merchant accounts for which to send test notifications. + /// + /// List of `merchantId` values for which test webhooks will be sent. The list can have a maximum of 20 `merchantId` values. If not specified, we send sample notifications to all the merchant accounts that the webhook is configured for. If this is more than 20 merchant accounts, use this list to specify a subset of the merchant accounts for which to send test notifications. + [JsonPropertyName("merchantIds")] + public List? MerchantIds { get { return this._MerchantIdsOption; } set { this._MerchantIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("notification")] + public CustomNotification? Notification { get { return this._NotificationOption; } set { this._NotificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TypesOption { get; private set; } + + /// + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + /// + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + [JsonPropertyName("types")] + public List? Types { get { return this._TypesOption; } set { this._TypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestCompanyWebhookRequest {\n"); + sb.Append(" MerchantIds: ").Append(MerchantIds).Append("\n"); + sb.Append(" Notification: ").Append(Notification).Append("\n"); + sb.Append(" Types: ").Append(Types).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestCompanyWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TestCompanyWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> merchantIds = default; + Option notification = default; + Option?> types = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantIds": + merchantIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notification": + notification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "types": + types = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TestCompanyWebhookRequest(merchantIds, notification, types); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestCompanyWebhookRequest testCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, testCompanyWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TestCompanyWebhookRequest testCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (testCompanyWebhookRequest._MerchantIdsOption.IsSet) + { + writer.WritePropertyName("merchantIds"); + JsonSerializer.Serialize(writer, testCompanyWebhookRequest.MerchantIds, jsonSerializerOptions); + } + if (testCompanyWebhookRequest._NotificationOption.IsSet) + { + writer.WritePropertyName("notification"); + JsonSerializer.Serialize(writer, testCompanyWebhookRequest.Notification, jsonSerializerOptions); + } + if (testCompanyWebhookRequest._TypesOption.IsSet) + { + writer.WritePropertyName("types"); + JsonSerializer.Serialize(writer, testCompanyWebhookRequest.Types, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TestOutput.cs b/Adyen/Management/Models/TestOutput.cs new file mode 100644 index 000000000..b6b371887 --- /dev/null +++ b/Adyen/Management/Models/TestOutput.cs @@ -0,0 +1,297 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TestOutput. + /// + public partial class TestOutput : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the test request. Possible values are: * **success**, `data.responseCode`: **2xx**. * **failed**, in all other cases. You can use the value of the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot failed test webhooks. + /// Unique identifier of the merchant account that the notification is about. + /// A short, human-readable explanation of the test result. Your server must respond with **HTTP 2xx* for the test webhook to be successful (`data.status`: **success**). Find out more about [accepting notifications](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks) You can use the value of this field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot unsuccessful test webhooks. + /// The [body of the notification webhook](https://docs.adyen.com/development-resources/webhooks/understand-notifications#notification-structure) that was sent to your server. + /// The HTTP response code for your server's response to the test webhook. You can use the value of this field together with the the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field value to troubleshoot failed test webhooks. + /// The time between sending the test webhook and receiving the response from your server. You can use it as an indication of how long your server takes to process a webhook notification. Measured in milliseconds, for example **304 ms**. + [JsonConstructor] + public TestOutput(string status, Option merchantId = default, Option output = default, Option requestSent = default, Option responseCode = default, Option responseTime = default) + { + Status = status; + _MerchantIdOption = merchantId; + _OutputOption = output; + _RequestSentOption = requestSent; + _ResponseCodeOption = responseCode; + _ResponseTimeOption = responseTime; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TestOutput() + { + } + + partial void OnCreated(); + + /// + /// The status of the test request. Possible values are: * **success**, `data.responseCode`: **2xx**. * **failed**, in all other cases. You can use the value of the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot failed test webhooks. + /// + /// The status of the test request. Possible values are: * **success**, `data.responseCode`: **2xx**. * **failed**, in all other cases. You can use the value of the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot failed test webhooks. + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// Unique identifier of the merchant account that the notification is about. + /// + /// Unique identifier of the merchant account that the notification is about. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutputOption { get; private set; } + + /// + /// A short, human-readable explanation of the test result. Your server must respond with **HTTP 2xx* for the test webhook to be successful (`data.status`: **success**). Find out more about [accepting notifications](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks) You can use the value of this field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot unsuccessful test webhooks. + /// + /// A short, human-readable explanation of the test result. Your server must respond with **HTTP 2xx* for the test webhook to be successful (`data.status`: **success**). Find out more about [accepting notifications](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks) You can use the value of this field together with the [`responseCode`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-responseCode) value to troubleshoot unsuccessful test webhooks. + [JsonPropertyName("output")] + public string? Output { get { return this._OutputOption; } set { this._OutputOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestSentOption { get; private set; } + + /// + /// The [body of the notification webhook](https://docs.adyen.com/development-resources/webhooks/understand-notifications#notification-structure) that was sent to your server. + /// + /// The [body of the notification webhook](https://docs.adyen.com/development-resources/webhooks/understand-notifications#notification-structure) that was sent to your server. + [JsonPropertyName("requestSent")] + public string? RequestSent { get { return this._RequestSentOption; } set { this._RequestSentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseCodeOption { get; private set; } + + /// + /// The HTTP response code for your server's response to the test webhook. You can use the value of this field together with the the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field value to troubleshoot failed test webhooks. + /// + /// The HTTP response code for your server's response to the test webhook. You can use the value of this field together with the the [`output`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/webhooks/{id}/test__resParam_data-output) field value to troubleshoot failed test webhooks. + /* 200 */ + [JsonPropertyName("responseCode")] + public string? ResponseCode { get { return this._ResponseCodeOption; } set { this._ResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseTimeOption { get; private set; } + + /// + /// The time between sending the test webhook and receiving the response from your server. You can use it as an indication of how long your server takes to process a webhook notification. Measured in milliseconds, for example **304 ms**. + /// + /// The time between sending the test webhook and receiving the response from your server. You can use it as an indication of how long your server takes to process a webhook notification. Measured in milliseconds, for example **304 ms**. + [JsonPropertyName("responseTime")] + public string? ResponseTime { get { return this._ResponseTimeOption; } set { this._ResponseTimeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestOutput {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Output: ").Append(Output).Append("\n"); + sb.Append(" RequestSent: ").Append(RequestSent).Append("\n"); + sb.Append(" ResponseCode: ").Append(ResponseCode).Append("\n"); + sb.Append(" ResponseTime: ").Append(ResponseTime).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestOutputJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TestOutput Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option merchantId = default; + Option output = default; + Option requestSent = default; + Option responseCode = default; + Option responseTime = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "output": + output = new Option(utf8JsonReader.GetString()!); + break; + case "requestSent": + requestSent = new Option(utf8JsonReader.GetString()!); + break; + case "responseCode": + responseCode = new Option(utf8JsonReader.GetString()!); + break; + case "responseTime": + responseTime = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class TestOutput.", nameof(status)); + + return new TestOutput(status.Value!, merchantId, output, requestSent, responseCode, responseTime); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestOutput testOutput, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, testOutput, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TestOutput testOutput, JsonSerializerOptions jsonSerializerOptions) + { + + if (testOutput.Status != null) + writer.WriteString("status", testOutput.Status); + + if (testOutput._MerchantIdOption.IsSet) + if (testOutput.MerchantId != null) + writer.WriteString("merchantId", testOutput.MerchantId); + + if (testOutput._OutputOption.IsSet) + if (testOutput.Output != null) + writer.WriteString("output", testOutput.Output); + + if (testOutput._RequestSentOption.IsSet) + if (testOutput.RequestSent != null) + writer.WriteString("requestSent", testOutput.RequestSent); + + if (testOutput._ResponseCodeOption.IsSet) + if (testOutput.ResponseCode != null) + writer.WriteString("responseCode", testOutput.ResponseCode); + + if (testOutput._ResponseTimeOption.IsSet) + if (testOutput.ResponseTime != null) + writer.WriteString("responseTime", testOutput.ResponseTime); + } + } +} diff --git a/Adyen/Management/Models/TestWebhookRequest.cs b/Adyen/Management/Models/TestWebhookRequest.cs new file mode 100644 index 000000000..49e7eaf55 --- /dev/null +++ b/Adyen/Management/Models/TestWebhookRequest.cs @@ -0,0 +1,204 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TestWebhookRequest. + /// + public partial class TestWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// notification + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + [JsonConstructor] + public TestWebhookRequest(Option notification = default, Option?> types = default) + { + _NotificationOption = notification; + _TypesOption = types; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TestWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("notification")] + public CustomNotification? Notification { get { return this._NotificationOption; } set { this._NotificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TypesOption { get; private set; } + + /// + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + /// + /// List of event codes for which to send test notifications. Only the webhook types below are supported. Possible values if webhook `type`: **standard**: * **AUTHORISATION** * **CHARGEBACK_REVERSED** * **ORDER_CLOSED** * **ORDER_OPENED** * **PAIDOUT_REVERSED** * **PAYOUT_THIRDPARTY** * **REFUNDED_REVERSED** * **REFUND_WITH_DATA** * **REPORT_AVAILABLE** * **CUSTOM** - set your custom notification fields in the [`notification`](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookId}/test__reqParam_notification) object. Possible values if webhook `type`: **banktransfer-notification**: * **PENDING** Possible values if webhook `type`: **report-notification**: * **REPORT_AVAILABLE** Possible values if webhook `type`: **ideal-notification**: * **AUTHORISATION** Possible values if webhook `type`: **pending-notification**: * **PENDING** + [JsonPropertyName("types")] + public List? Types { get { return this._TypesOption; } set { this._TypesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestWebhookRequest {\n"); + sb.Append(" Notification: ").Append(Notification).Append("\n"); + sb.Append(" Types: ").Append(Types).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TestWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notification = default; + Option?> types = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notification": + notification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "types": + types = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TestWebhookRequest(notification, types); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestWebhookRequest testWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, testWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TestWebhookRequest testWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (testWebhookRequest._NotificationOption.IsSet) + { + writer.WritePropertyName("notification"); + JsonSerializer.Serialize(writer, testWebhookRequest.Notification, jsonSerializerOptions); + } + if (testWebhookRequest._TypesOption.IsSet) + { + writer.WritePropertyName("types"); + JsonSerializer.Serialize(writer, testWebhookRequest.Types, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TestWebhookResponse.cs b/Adyen/Management/Models/TestWebhookResponse.cs new file mode 100644 index 000000000..a87748345 --- /dev/null +++ b/Adyen/Management/Models/TestWebhookResponse.cs @@ -0,0 +1,179 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TestWebhookResponse. + /// + public partial class TestWebhookResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List with test results. Each test webhook we send has a list element with the result. + [JsonConstructor] + public TestWebhookResponse(Option?> data = default) + { + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TestWebhookResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// List with test results. Each test webhook we send has a list element with the result. + /// + /// List with test results. Each test webhook we send has a list element with the result. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TestWebhookResponse {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TestWebhookResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TestWebhookResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TestWebhookResponse(data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TestWebhookResponse testWebhookResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, testWebhookResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TestWebhookResponse testWebhookResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (testWebhookResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, testWebhookResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/TicketInfo.cs b/Adyen/Management/Models/TicketInfo.cs new file mode 100644 index 000000000..c5af3bfd0 --- /dev/null +++ b/Adyen/Management/Models/TicketInfo.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TicketInfo. + /// + public partial class TicketInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Ticket requestorId + [JsonConstructor] + public TicketInfo(Option requestorId = default) + { + _RequestorIdOption = requestorId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TicketInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestorIdOption { get; private set; } + + /// + /// Ticket requestorId + /// + /// Ticket requestorId + [JsonPropertyName("requestorId")] + public string? RequestorId { get { return this._RequestorIdOption; } set { this._RequestorIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TicketInfo {\n"); + sb.Append(" RequestorId: ").Append(RequestorId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TicketInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TicketInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requestorId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "requestorId": + requestorId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TicketInfo(requestorId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TicketInfo ticketInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ticketInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TicketInfo ticketInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (ticketInfo._RequestorIdOption.IsSet) + if (ticketInfo.RequestorId != null) + writer.WriteString("requestorId", ticketInfo.RequestorId); + } + } +} diff --git a/Adyen/Management/Models/Timeouts.cs b/Adyen/Management/Models/Timeouts.cs new file mode 100644 index 000000000..86f0b27d1 --- /dev/null +++ b/Adyen/Management/Models/Timeouts.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Timeouts. + /// + public partial class Timeouts : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates the number of seconds of inactivity after which the terminal display goes into sleep mode. + [JsonConstructor] + public Timeouts(Option fromActiveToSleep = default) + { + _FromActiveToSleepOption = fromActiveToSleep; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Timeouts() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FromActiveToSleepOption { get; private set; } + + /// + /// Indicates the number of seconds of inactivity after which the terminal display goes into sleep mode. + /// + /// Indicates the number of seconds of inactivity after which the terminal display goes into sleep mode. + [JsonPropertyName("fromActiveToSleep")] + public int? FromActiveToSleep { get { return this._FromActiveToSleepOption; } set { this._FromActiveToSleepOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Timeouts {\n"); + sb.Append(" FromActiveToSleep: ").Append(FromActiveToSleep).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TimeoutsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Timeouts Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option fromActiveToSleep = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "fromActiveToSleep": + fromActiveToSleep = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Timeouts(fromActiveToSleep); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Timeouts timeouts, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, timeouts, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Timeouts timeouts, JsonSerializerOptions jsonSerializerOptions) + { + + if (timeouts._FromActiveToSleepOption.IsSet) + writer.WriteNumber("fromActiveToSleep", timeouts._FromActiveToSleepOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/TransactionDescriptionInfo.cs b/Adyen/Management/Models/TransactionDescriptionInfo.cs new file mode 100644 index 000000000..8a4ce5c9c --- /dev/null +++ b/Adyen/Management/Models/TransactionDescriptionInfo.cs @@ -0,0 +1,323 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TransactionDescriptionInfo. + /// + public partial class TransactionDescriptionInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The type of transaction description you want to use: - **fixed**: The transaction description set in this request is used for all payments with this payment method. - **append**: The transaction description set in this request is used as a base for all payments with this payment method. The [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is appended to this base description. Note that if the combined length exceeds 22 characters, banks may truncate the string. - **dynamic**: Only the [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is used for payments with this payment method. (default to TypeEnum.Dynamic) + [JsonConstructor] + public TransactionDescriptionInfo(Option doingBusinessAsName = default, Option type = default) + { + _DoingBusinessAsNameOption = doingBusinessAsName; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionDescriptionInfo() + { + } + + partial void OnCreated(); + + /// + /// The type of transaction description you want to use: - **fixed**: The transaction description set in this request is used for all payments with this payment method. - **append**: The transaction description set in this request is used as a base for all payments with this payment method. The [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is appended to this base description. Note that if the combined length exceeds 22 characters, banks may truncate the string. - **dynamic**: Only the [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is used for payments with this payment method. + /// + /// The type of transaction description you want to use: - **fixed**: The transaction description set in this request is used for all payments with this payment method. - **append**: The transaction description set in this request is used as a base for all payments with this payment method. The [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is appended to this base description. Note that if the combined length exceeds 22 characters, banks may truncate the string. - **dynamic**: Only the [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is used for payments with this payment method. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Append - append + /// + public static readonly TypeEnum Append = new("append"); + + /// + /// TypeEnum.Dynamic - dynamic + /// + public static readonly TypeEnum Dynamic = new("dynamic"); + + /// + /// TypeEnum.Fixed - fixed + /// + public static readonly TypeEnum Fixed = new("fixed"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "append" => TypeEnum.Append, + "dynamic" => TypeEnum.Dynamic, + "fixed" => TypeEnum.Fixed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Append) + return "append"; + + if (value == TypeEnum.Dynamic) + return "dynamic"; + + if (value == TypeEnum.Fixed) + return "fixed"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transaction description you want to use: - **fixed**: The transaction description set in this request is used for all payments with this payment method. - **append**: The transaction description set in this request is used as a base for all payments with this payment method. The [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is appended to this base description. Note that if the combined length exceeds 22 characters, banks may truncate the string. - **dynamic**: Only the [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is used for payments with this payment method. + /// + /// The type of transaction description you want to use: - **fixed**: The transaction description set in this request is used for all payments with this payment method. - **append**: The transaction description set in this request is used as a base for all payments with this payment method. The [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is appended to this base description. Note that if the combined length exceeds 22 characters, banks may truncate the string. - **dynamic**: Only the [transaction description set in the request to process the payment](https://docs.adyen.com/api-explorer/Checkout/70/post/sessions#request-shopperStatement) is used for payments with this payment method. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DoingBusinessAsNameOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("doingBusinessAsName")] + public string? DoingBusinessAsName { get { return this._DoingBusinessAsNameOption; } set { this._DoingBusinessAsNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionDescriptionInfo {\n"); + sb.Append(" DoingBusinessAsName: ").Append(DoingBusinessAsName).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DoingBusinessAsName (string) maxLength + if (this.DoingBusinessAsName != null && this.DoingBusinessAsName.Length > 22) + { + yield return new ValidationResult("Invalid value for DoingBusinessAsName, length must be less than 22.", new [] { "DoingBusinessAsName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionDescriptionInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionDescriptionInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option doingBusinessAsName = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "doingBusinessAsName": + doingBusinessAsName = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransactionDescriptionInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new TransactionDescriptionInfo(doingBusinessAsName, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionDescriptionInfo transactionDescriptionInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionDescriptionInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionDescriptionInfo transactionDescriptionInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionDescriptionInfo._DoingBusinessAsNameOption.IsSet) + if (transactionDescriptionInfo.DoingBusinessAsName != null) + writer.WriteString("doingBusinessAsName", transactionDescriptionInfo.DoingBusinessAsName); + + if (transactionDescriptionInfo._TypeOption.IsSet && transactionDescriptionInfo.Type != null) + { + string? typeRawValue = TransactionDescriptionInfo.TypeEnum.ToJsonValue(transactionDescriptionInfo._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/TwintInfo.cs b/Adyen/Management/Models/TwintInfo.cs new file mode 100644 index 000000000..6bb00e0e7 --- /dev/null +++ b/Adyen/Management/Models/TwintInfo.cs @@ -0,0 +1,171 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// TwintInfo. + /// + public partial class TwintInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Twint logo. Format: Base64-encoded string. + [JsonConstructor] + public TwintInfo(string logo) + { + Logo = logo; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TwintInfo() + { + } + + partial void OnCreated(); + + /// + /// Twint logo. Format: Base64-encoded string. + /// + /// Twint logo. Format: Base64-encoded string. + [JsonPropertyName("logo")] + public string Logo { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TwintInfo {\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TwintInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TwintInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option logo = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!logo.IsSet) + throw new ArgumentException("Property is required for class TwintInfo.", nameof(logo)); + + return new TwintInfo(logo.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TwintInfo twintInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, twintInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TwintInfo twintInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (twintInfo.Logo != null) + writer.WriteString("logo", twintInfo.Logo); + } + } +} diff --git a/Adyen/Management/Models/UninstallAndroidAppDetails.cs b/Adyen/Management/Models/UninstallAndroidAppDetails.cs new file mode 100644 index 000000000..25a4e0298 --- /dev/null +++ b/Adyen/Management/Models/UninstallAndroidAppDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UninstallAndroidAppDetails. + /// + public partial class UninstallAndroidAppDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the app to be uninstalled. + /// Type of terminal action: Uninstall an Android app. (default to TypeEnum.UninstallAndroidApp) + [JsonConstructor] + public UninstallAndroidAppDetails(Option appId = default, Option type = default) + { + _AppIdOption = appId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UninstallAndroidAppDetails() + { + } + + partial void OnCreated(); + + /// + /// Type of terminal action: Uninstall an Android app. + /// + /// Type of terminal action: Uninstall an Android app. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UninstallAndroidApp - UninstallAndroidApp + /// + public static readonly TypeEnum UninstallAndroidApp = new("UninstallAndroidApp"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "UninstallAndroidApp" => TypeEnum.UninstallAndroidApp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UninstallAndroidApp) + return "UninstallAndroidApp"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of terminal action: Uninstall an Android app. + /// + /// Type of terminal action: Uninstall an Android app. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AppIdOption { get; private set; } + + /// + /// The unique identifier of the app to be uninstalled. + /// + /// The unique identifier of the app to be uninstalled. + [JsonPropertyName("appId")] + public string? AppId { get { return this._AppIdOption; } set { this._AppIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UninstallAndroidAppDetails {\n"); + sb.Append(" AppId: ").Append(AppId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UninstallAndroidAppDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UninstallAndroidAppDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option appId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "appId": + appId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UninstallAndroidAppDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new UninstallAndroidAppDetails(appId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UninstallAndroidAppDetails uninstallAndroidAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uninstallAndroidAppDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UninstallAndroidAppDetails uninstallAndroidAppDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (uninstallAndroidAppDetails._AppIdOption.IsSet) + if (uninstallAndroidAppDetails.AppId != null) + writer.WriteString("appId", uninstallAndroidAppDetails.AppId); + + if (uninstallAndroidAppDetails._TypeOption.IsSet && uninstallAndroidAppDetails.Type != null) + { + string? typeRawValue = UninstallAndroidAppDetails.TypeEnum.ToJsonValue(uninstallAndroidAppDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/UninstallAndroidCertificateDetails.cs b/Adyen/Management/Models/UninstallAndroidCertificateDetails.cs new file mode 100644 index 000000000..5fdf89221 --- /dev/null +++ b/Adyen/Management/Models/UninstallAndroidCertificateDetails.cs @@ -0,0 +1,299 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UninstallAndroidCertificateDetails. + /// + public partial class UninstallAndroidCertificateDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the certificate to be uninstalled. + /// Type of terminal action: Uninstall an Android certificate. (default to TypeEnum.UninstallAndroidCertificate) + [JsonConstructor] + public UninstallAndroidCertificateDetails(Option certificateId = default, Option type = default) + { + _CertificateIdOption = certificateId; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UninstallAndroidCertificateDetails() + { + } + + partial void OnCreated(); + + /// + /// Type of terminal action: Uninstall an Android certificate. + /// + /// Type of terminal action: Uninstall an Android certificate. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UninstallAndroidCertificate - UninstallAndroidCertificate + /// + public static readonly TypeEnum UninstallAndroidCertificate = new("UninstallAndroidCertificate"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "UninstallAndroidCertificate" => TypeEnum.UninstallAndroidCertificate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UninstallAndroidCertificate) + return "UninstallAndroidCertificate"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of terminal action: Uninstall an Android certificate. + /// + /// Type of terminal action: Uninstall an Android certificate. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CertificateIdOption { get; private set; } + + /// + /// The unique identifier of the certificate to be uninstalled. + /// + /// The unique identifier of the certificate to be uninstalled. + [JsonPropertyName("certificateId")] + public string? CertificateId { get { return this._CertificateIdOption; } set { this._CertificateIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UninstallAndroidCertificateDetails {\n"); + sb.Append(" CertificateId: ").Append(CertificateId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UninstallAndroidCertificateDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UninstallAndroidCertificateDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option certificateId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "certificateId": + certificateId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UninstallAndroidCertificateDetails.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new UninstallAndroidCertificateDetails(certificateId, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UninstallAndroidCertificateDetails uninstallAndroidCertificateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uninstallAndroidCertificateDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UninstallAndroidCertificateDetails uninstallAndroidCertificateDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (uninstallAndroidCertificateDetails._CertificateIdOption.IsSet) + if (uninstallAndroidCertificateDetails.CertificateId != null) + writer.WriteString("certificateId", uninstallAndroidCertificateDetails.CertificateId); + + if (uninstallAndroidCertificateDetails._TypeOption.IsSet && uninstallAndroidCertificateDetails.Type != null) + { + string? typeRawValue = UninstallAndroidCertificateDetails.TypeEnum.ToJsonValue(uninstallAndroidCertificateDetails._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/Unreferenced.cs b/Adyen/Management/Models/Unreferenced.cs new file mode 100644 index 000000000..f44496ece --- /dev/null +++ b/Adyen/Management/Models/Unreferenced.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Unreferenced. + /// + public partial class Unreferenced : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether unreferenced refunds are enabled on the terminal. + [JsonConstructor] + public Unreferenced(Option enableUnreferencedRefunds = default) + { + _EnableUnreferencedRefundsOption = enableUnreferencedRefunds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Unreferenced() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnableUnreferencedRefundsOption { get; private set; } + + /// + /// Indicates whether unreferenced refunds are enabled on the terminal. + /// + /// Indicates whether unreferenced refunds are enabled on the terminal. + [JsonPropertyName("enableUnreferencedRefunds")] + public bool? EnableUnreferencedRefunds { get { return this._EnableUnreferencedRefundsOption; } set { this._EnableUnreferencedRefundsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Unreferenced {\n"); + sb.Append(" EnableUnreferencedRefunds: ").Append(EnableUnreferencedRefunds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UnreferencedJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Unreferenced Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enableUnreferencedRefunds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enableUnreferencedRefunds": + enableUnreferencedRefunds = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new Unreferenced(enableUnreferencedRefunds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Unreferenced unreferenced, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, unreferenced, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Unreferenced unreferenced, JsonSerializerOptions jsonSerializerOptions) + { + + if (unreferenced._EnableUnreferencedRefundsOption.IsSet) + writer.WriteBoolean("enableUnreferencedRefunds", unreferenced._EnableUnreferencedRefundsOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/UpdatableAddress.cs b/Adyen/Management/Models/UpdatableAddress.cs new file mode 100644 index 000000000..ae62ce9c0 --- /dev/null +++ b/Adyen/Management/Models/UpdatableAddress.cs @@ -0,0 +1,302 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdatableAddress. + /// + public partial class UpdatableAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. + /// The street address. + /// Second address line. + /// Third address line. + /// The postal code. + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + [JsonConstructor] + public UpdatableAddress(Option city = default, Option line1 = default, Option line2 = default, Option line3 = default, Option postalCode = default, Option stateOrProvince = default) + { + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _Line3Option = line3; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdatableAddress() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. + /// + /// The name of the city. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The street address. + /// + /// The street address. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// Second address line. + /// + /// Second address line. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line3Option { get; private set; } + + /// + /// Third address line. + /// + /// Third address line. + [JsonPropertyName("line3")] + public string? Line3 { get { return this._Line3Option; } set { this._Line3Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. + /// + /// The postal code. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + /// + /// The state or province code as defined in [ISO 3166-2](https://www.iso.org/standard/72483.html). For example, **ON** for Ontario, Canada. Required for the following countries: - Australia - Brazil - Canada - India - Mexico - New Zealand - United States + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdatableAddress {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" Line3: ").Append(Line3).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdatableAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdatableAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option line1 = default; + Option line2 = default; + Option line3 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "line3": + line3 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UpdatableAddress(city, line1, line2, line3, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdatableAddress updatableAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updatableAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdatableAddress updatableAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (updatableAddress._CityOption.IsSet) + if (updatableAddress.City != null) + writer.WriteString("city", updatableAddress.City); + + if (updatableAddress._Line1Option.IsSet) + if (updatableAddress.Line1 != null) + writer.WriteString("line1", updatableAddress.Line1); + + if (updatableAddress._Line2Option.IsSet) + if (updatableAddress.Line2 != null) + writer.WriteString("line2", updatableAddress.Line2); + + if (updatableAddress._Line3Option.IsSet) + if (updatableAddress.Line3 != null) + writer.WriteString("line3", updatableAddress.Line3); + + if (updatableAddress._PostalCodeOption.IsSet) + if (updatableAddress.PostalCode != null) + writer.WriteString("postalCode", updatableAddress.PostalCode); + + if (updatableAddress._StateOrProvinceOption.IsSet) + if (updatableAddress.StateOrProvince != null) + writer.WriteString("stateOrProvince", updatableAddress.StateOrProvince); + } + } +} diff --git a/Adyen/Management/Models/UpdateCompanyApiCredentialRequest.cs b/Adyen/Management/Models/UpdateCompanyApiCredentialRequest.cs new file mode 100644 index 000000000..1593d323f --- /dev/null +++ b/Adyen/Management/Models/UpdateCompanyApiCredentialRequest.cs @@ -0,0 +1,280 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateCompanyApiCredentialRequest. + /// + public partial class UpdateCompanyApiCredentialRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + /// List of merchant accounts that the API credential has access to. + /// Description of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + [JsonConstructor] + public UpdateCompanyApiCredentialRequest(Option active = default, Option?> allowedOrigins = default, Option?> associatedMerchantAccounts = default, Option description = default, Option?> roles = default) + { + _ActiveOption = active; + _AllowedOriginsOption = allowedOrigins; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _DescriptionOption = description; + _RolesOption = roles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateCompanyApiCredentialRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates if the API credential is enabled. + /// + /// Indicates if the API credential is enabled. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + /// + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// List of merchant accounts that the API credential has access to. + /// + /// List of merchant accounts that the API credential has access to. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.' can be assigned to other API credentials. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateCompanyApiCredentialRequest {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateCompanyApiCredentialRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateCompanyApiCredentialRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedOrigins = default; + Option?> associatedMerchantAccounts = default; + Option description = default; + Option?> roles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new UpdateCompanyApiCredentialRequest(active, allowedOrigins, associatedMerchantAccounts, description, roles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateCompanyApiCredentialRequest updateCompanyApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateCompanyApiCredentialRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateCompanyApiCredentialRequest updateCompanyApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateCompanyApiCredentialRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateCompanyApiCredentialRequest._ActiveOption.Value!.Value); + + if (updateCompanyApiCredentialRequest._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, updateCompanyApiCredentialRequest.AllowedOrigins, jsonSerializerOptions); + } + if (updateCompanyApiCredentialRequest._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, updateCompanyApiCredentialRequest.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (updateCompanyApiCredentialRequest._DescriptionOption.IsSet) + if (updateCompanyApiCredentialRequest.Description != null) + writer.WriteString("description", updateCompanyApiCredentialRequest.Description); + + if (updateCompanyApiCredentialRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, updateCompanyApiCredentialRequest.Roles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/UpdateCompanyUserRequest.cs b/Adyen/Management/Models/UpdateCompanyUserRequest.cs new file mode 100644 index 000000000..735fc3634 --- /dev/null +++ b/Adyen/Management/Models/UpdateCompanyUserRequest.cs @@ -0,0 +1,354 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateCompanyUserRequest. + /// + public partial class UpdateCompanyUserRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Indicates whether this user is active. + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) to associate the user with. + /// The email address of the user. + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// name + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonConstructor] + public UpdateCompanyUserRequest(Option?> accountGroups = default, Option active = default, Option?> associatedMerchantAccounts = default, Option email = default, Option loginMethod = default, Option name = default, Option?> roles = default, Option timeZoneCode = default) + { + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _AssociatedMerchantAccountsOption = associatedMerchantAccounts; + _EmailOption = email; + _LoginMethodOption = loginMethod; + _NameOption = name; + _RolesOption = roles; + _TimeZoneCodeOption = timeZoneCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateCompanyUserRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates whether this user is active. + /// + /// Indicates whether this user is active. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AssociatedMerchantAccountsOption { get; private set; } + + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) to associate the user with. + /// + /// The list of [merchant accounts](https://docs.adyen.com/account/account-structure#merchant-accounts) to associate the user with. + [JsonPropertyName("associatedMerchantAccounts")] + public List? AssociatedMerchantAccounts { get { return this._AssociatedMerchantAccountsOption; } set { this._AssociatedMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LoginMethodOption { get; private set; } + + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + [JsonPropertyName("loginMethod")] + public string? LoginMethod { get { return this._LoginMethodOption; } set { this._LoginMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name2? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneCodeOption { get; private set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string? TimeZoneCode { get { return this._TimeZoneCodeOption; } set { this._TimeZoneCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateCompanyUserRequest {\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AssociatedMerchantAccounts: ").Append(AssociatedMerchantAccounts).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" LoginMethod: ").Append(LoginMethod).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateCompanyUserRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateCompanyUserRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> accountGroups = default; + Option active = default; + Option?> associatedMerchantAccounts = default; + Option email = default; + Option loginMethod = default; + Option name = default; + Option?> roles = default; + Option timeZoneCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "associatedMerchantAccounts": + associatedMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "loginMethod": + loginMethod = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UpdateCompanyUserRequest(accountGroups, active, associatedMerchantAccounts, email, loginMethod, name, roles, timeZoneCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateCompanyUserRequest updateCompanyUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateCompanyUserRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateCompanyUserRequest updateCompanyUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateCompanyUserRequest._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, updateCompanyUserRequest.AccountGroups, jsonSerializerOptions); + } + if (updateCompanyUserRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateCompanyUserRequest._ActiveOption.Value!.Value); + + if (updateCompanyUserRequest._AssociatedMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("associatedMerchantAccounts"); + JsonSerializer.Serialize(writer, updateCompanyUserRequest.AssociatedMerchantAccounts, jsonSerializerOptions); + } + if (updateCompanyUserRequest._EmailOption.IsSet) + if (updateCompanyUserRequest.Email != null) + writer.WriteString("email", updateCompanyUserRequest.Email); + + if (updateCompanyUserRequest._LoginMethodOption.IsSet) + if (updateCompanyUserRequest.LoginMethod != null) + writer.WriteString("loginMethod", updateCompanyUserRequest.LoginMethod); + + if (updateCompanyUserRequest._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, updateCompanyUserRequest.Name, jsonSerializerOptions); + } + if (updateCompanyUserRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, updateCompanyUserRequest.Roles, jsonSerializerOptions); + } + if (updateCompanyUserRequest._TimeZoneCodeOption.IsSet) + if (updateCompanyUserRequest.TimeZoneCode != null) + writer.WriteString("timeZoneCode", updateCompanyUserRequest.TimeZoneCode); + } + } +} diff --git a/Adyen/Management/Models/UpdateCompanyWebhookRequest.cs b/Adyen/Management/Models/UpdateCompanyWebhookRequest.cs new file mode 100644 index 000000000..da34d5c83 --- /dev/null +++ b/Adyen/Management/Models/UpdateCompanyWebhookRequest.cs @@ -0,0 +1,983 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateCompanyWebhookRequest. + /// + public partial class UpdateCompanyWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// additionalSettings + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// Your description for this webhook configuration. + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **includeAccounts**: The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts**: The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// Password to access the webhook URL. + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// Username to access the webhook URL. + [JsonConstructor] + public UpdateCompanyWebhookRequest(Option acceptsExpiredCertificate = default, Option acceptsSelfSignedCertificate = default, Option acceptsUntrustedRootCertificate = default, Option active = default, Option additionalSettings = default, Option communicationFormat = default, Option description = default, Option encryptionProtocol = default, Option filterMerchantAccountType = default, Option?> filterMerchantAccounts = default, Option networkType = default, Option password = default, Option populateSoapActionHeader = default, Option url = default, Option username = default) + { + _AcceptsExpiredCertificateOption = acceptsExpiredCertificate; + _AcceptsSelfSignedCertificateOption = acceptsSelfSignedCertificate; + _AcceptsUntrustedRootCertificateOption = acceptsUntrustedRootCertificate; + _ActiveOption = active; + _AdditionalSettingsOption = additionalSettings; + _CommunicationFormatOption = communicationFormat; + _DescriptionOption = description; + _EncryptionProtocolOption = encryptionProtocol; + _FilterMerchantAccountTypeOption = filterMerchantAccountType; + _FilterMerchantAccountsOption = filterMerchantAccounts; + _NetworkTypeOption = networkType; + _PasswordOption = password; + _PopulateSoapActionHeaderOption = populateSoapActionHeader; + _UrlOption = url; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateCompanyWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + [JsonConverter(typeof(CommunicationFormatEnumJsonConverter))] + public class CommunicationFormatEnum : IEnum + { + /// + /// Returns the value of the CommunicationFormatEnum. + /// + public string? Value { get; set; } + + /// + /// CommunicationFormatEnum.Http - http + /// + public static readonly CommunicationFormatEnum Http = new("http"); + + /// + /// CommunicationFormatEnum.Json - json + /// + public static readonly CommunicationFormatEnum Json = new("json"); + + /// + /// CommunicationFormatEnum.Soap - soap + /// + public static readonly CommunicationFormatEnum Soap = new("soap"); + + private CommunicationFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CommunicationFormatEnum?(string? value) => value == null ? null : new CommunicationFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CommunicationFormatEnum? option) => option?.Value; + + public static bool operator ==(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CommunicationFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CommunicationFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "http" => CommunicationFormatEnum.Http, + "json" => CommunicationFormatEnum.Json, + "soap" => CommunicationFormatEnum.Soap, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CommunicationFormatEnum? value) + { + if (value == null) + return null; + + if (value == CommunicationFormatEnum.Http) + return "http"; + + if (value == CommunicationFormatEnum.Json) + return "json"; + + if (value == CommunicationFormatEnum.Soap) + return "soap"; + + return null; + } + + /// + /// JsonConverter for writing CommunicationFormatEnum. + /// + public class CommunicationFormatEnumJsonConverter : JsonConverter + { + public override CommunicationFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CommunicationFormatEnum.FromStringOrDefault(value) ?? new CommunicationFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CommunicationFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CommunicationFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CommunicationFormatOption { get; private set; } + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /* soap */ + [JsonPropertyName("communicationFormat")] + public CommunicationFormatEnum? CommunicationFormat { get { return this._CommunicationFormatOption; } set { this._CommunicationFormatOption = new(value); } } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + [JsonConverter(typeof(EncryptionProtocolEnumJsonConverter))] + public class EncryptionProtocolEnum : IEnum + { + /// + /// Returns the value of the EncryptionProtocolEnum. + /// + public string? Value { get; set; } + + /// + /// EncryptionProtocolEnum.HTTP - HTTP + /// + public static readonly EncryptionProtocolEnum HTTP = new("HTTP"); + + /// + /// EncryptionProtocolEnum.TLSv12 - TLSv1.2 + /// + public static readonly EncryptionProtocolEnum TLSv12 = new("TLSv1.2"); + + /// + /// EncryptionProtocolEnum.TLSv13 - TLSv1.3 + /// + public static readonly EncryptionProtocolEnum TLSv13 = new("TLSv1.3"); + + private EncryptionProtocolEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EncryptionProtocolEnum?(string? value) => value == null ? null : new EncryptionProtocolEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EncryptionProtocolEnum? option) => option?.Value; + + public static bool operator ==(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EncryptionProtocolEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EncryptionProtocolEnum? FromStringOrDefault(string value) + { + return value switch { + "HTTP" => EncryptionProtocolEnum.HTTP, + "TLSv1.2" => EncryptionProtocolEnum.TLSv12, + "TLSv1.3" => EncryptionProtocolEnum.TLSv13, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EncryptionProtocolEnum? value) + { + if (value == null) + return null; + + if (value == EncryptionProtocolEnum.HTTP) + return "HTTP"; + + if (value == EncryptionProtocolEnum.TLSv12) + return "TLSv1.2"; + + if (value == EncryptionProtocolEnum.TLSv13) + return "TLSv1.3"; + + return null; + } + + /// + /// JsonConverter for writing EncryptionProtocolEnum. + /// + public class EncryptionProtocolEnumJsonConverter : JsonConverter + { + public override EncryptionProtocolEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EncryptionProtocolEnum.FromStringOrDefault(value) ?? new EncryptionProtocolEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EncryptionProtocolEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EncryptionProtocolEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionProtocolOption { get; private set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /* TLSv1.2 */ + [JsonPropertyName("encryptionProtocol")] + public EncryptionProtocolEnum? EncryptionProtocol { get { return this._EncryptionProtocolOption; } set { this._EncryptionProtocolOption = new(value); } } + + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **includeAccounts**: The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts**: The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **includeAccounts**: The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts**: The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + [JsonConverter(typeof(FilterMerchantAccountTypeEnumJsonConverter))] + public class FilterMerchantAccountTypeEnum : IEnum + { + /// + /// Returns the value of the FilterMerchantAccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FilterMerchantAccountTypeEnum.AllAccounts - allAccounts + /// + public static readonly FilterMerchantAccountTypeEnum AllAccounts = new("allAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.ExcludeAccounts - excludeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum ExcludeAccounts = new("excludeAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.IncludeAccounts - includeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum IncludeAccounts = new("includeAccounts"); + + private FilterMerchantAccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FilterMerchantAccountTypeEnum?(string? value) => value == null ? null : new FilterMerchantAccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FilterMerchantAccountTypeEnum? option) => option?.Value; + + public static bool operator ==(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FilterMerchantAccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FilterMerchantAccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "allAccounts" => FilterMerchantAccountTypeEnum.AllAccounts, + "excludeAccounts" => FilterMerchantAccountTypeEnum.ExcludeAccounts, + "includeAccounts" => FilterMerchantAccountTypeEnum.IncludeAccounts, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FilterMerchantAccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == FilterMerchantAccountTypeEnum.AllAccounts) + return "allAccounts"; + + if (value == FilterMerchantAccountTypeEnum.ExcludeAccounts) + return "excludeAccounts"; + + if (value == FilterMerchantAccountTypeEnum.IncludeAccounts) + return "includeAccounts"; + + return null; + } + + /// + /// JsonConverter for writing FilterMerchantAccountTypeEnum. + /// + public class FilterMerchantAccountTypeEnumJsonConverter : JsonConverter + { + public override FilterMerchantAccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FilterMerchantAccountTypeEnum.FromStringOrDefault(value) ?? new FilterMerchantAccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FilterMerchantAccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FilterMerchantAccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FilterMerchantAccountTypeOption { get; private set; } + + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **includeAccounts**: The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts**: The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are filtered when configuring the webhook. Possible values: * **includeAccounts**: The webhook is configured for the merchant accounts listed in `filterMerchantAccounts`. * **excludeAccounts**: The webhook is not configured for the merchant accounts listed in `filterMerchantAccounts`. * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + [JsonPropertyName("filterMerchantAccountType")] + public FilterMerchantAccountTypeEnum? FilterMerchantAccountType { get { return this._FilterMerchantAccountTypeOption; } set { this._FilterMerchantAccountTypeOption = new(value); } } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonConverter(typeof(NetworkTypeEnumJsonConverter))] + public class NetworkTypeEnum : IEnum + { + /// + /// Returns the value of the NetworkTypeEnum. + /// + public string? Value { get; set; } + + /// + /// NetworkTypeEnum.Local - local + /// + public static readonly NetworkTypeEnum Local = new("local"); + + /// + /// NetworkTypeEnum.Public - public + /// + public static readonly NetworkTypeEnum Public = new("public"); + + private NetworkTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NetworkTypeEnum?(string? value) => value == null ? null : new NetworkTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NetworkTypeEnum? option) => option?.Value; + + public static bool operator ==(NetworkTypeEnum? left, NetworkTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NetworkTypeEnum? left, NetworkTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NetworkTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NetworkTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "local" => NetworkTypeEnum.Local, + "public" => NetworkTypeEnum.Public, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NetworkTypeEnum? value) + { + if (value == null) + return null; + + if (value == NetworkTypeEnum.Local) + return "local"; + + if (value == NetworkTypeEnum.Public) + return "public"; + + return null; + } + + /// + /// JsonConverter for writing NetworkTypeEnum. + /// + public class NetworkTypeEnumJsonConverter : JsonConverter + { + public override NetworkTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NetworkTypeEnum.FromStringOrDefault(value) ?? new NetworkTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NetworkTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NetworkTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTypeOption { get; private set; } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonPropertyName("networkType")] + public NetworkTypeEnum? NetworkType { get { return this._NetworkTypeOption; } set { this._NetworkTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsExpiredCertificateOption { get; private set; } + + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsExpiredCertificate")] + public bool? AcceptsExpiredCertificate { get { return this._AcceptsExpiredCertificateOption; } set { this._AcceptsExpiredCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsSelfSignedCertificateOption { get; private set; } + + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsSelfSignedCertificate")] + public bool? AcceptsSelfSignedCertificate { get { return this._AcceptsSelfSignedCertificateOption; } set { this._AcceptsSelfSignedCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsUntrustedRootCertificateOption { get; private set; } + + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsUntrustedRootCertificate")] + public bool? AcceptsUntrustedRootCertificate { get { return this._AcceptsUntrustedRootCertificateOption; } set { this._AcceptsUntrustedRootCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalSettings")] + public AdditionalSettings? AdditionalSettings { get { return this._AdditionalSettingsOption; } set { this._AdditionalSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for this webhook configuration. + /// + /// Your description for this webhook configuration. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FilterMerchantAccountsOption { get; private set; } + + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + [JsonPropertyName("filterMerchantAccounts")] + public List? FilterMerchantAccounts { get { return this._FilterMerchantAccountsOption; } set { this._FilterMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// Password to access the webhook URL. + /// + /// Password to access the webhook URL. + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PopulateSoapActionHeaderOption { get; private set; } + + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + [JsonPropertyName("populateSoapActionHeader")] + public bool? PopulateSoapActionHeader { get { return this._PopulateSoapActionHeaderOption; } set { this._PopulateSoapActionHeaderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /* http://www.adyen.com */ + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// Username to access the webhook URL. + /// + /// Username to access the webhook URL. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateCompanyWebhookRequest {\n"); + sb.Append(" AcceptsExpiredCertificate: ").Append(AcceptsExpiredCertificate).Append("\n"); + sb.Append(" AcceptsSelfSignedCertificate: ").Append(AcceptsSelfSignedCertificate).Append("\n"); + sb.Append(" AcceptsUntrustedRootCertificate: ").Append(AcceptsUntrustedRootCertificate).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AdditionalSettings: ").Append(AdditionalSettings).Append("\n"); + sb.Append(" CommunicationFormat: ").Append(CommunicationFormat).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EncryptionProtocol: ").Append(EncryptionProtocol).Append("\n"); + sb.Append(" FilterMerchantAccountType: ").Append(FilterMerchantAccountType).Append("\n"); + sb.Append(" FilterMerchantAccounts: ").Append(FilterMerchantAccounts).Append("\n"); + sb.Append(" NetworkType: ").Append(NetworkType).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PopulateSoapActionHeader: ").Append(PopulateSoapActionHeader).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateCompanyWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateCompanyWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptsExpiredCertificate = default; + Option acceptsSelfSignedCertificate = default; + Option acceptsUntrustedRootCertificate = default; + Option active = default; + Option additionalSettings = default; + Option communicationFormat = default; + Option description = default; + Option encryptionProtocol = default; + Option filterMerchantAccountType = default; + Option?> filterMerchantAccounts = default; + Option networkType = default; + Option password = default; + Option populateSoapActionHeader = default; + Option url = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptsExpiredCertificate": + acceptsExpiredCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsSelfSignedCertificate": + acceptsSelfSignedCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsUntrustedRootCertificate": + acceptsUntrustedRootCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "additionalSettings": + additionalSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "communicationFormat": + string? communicationFormatRawValue = utf8JsonReader.GetString(); + communicationFormat = new Option(UpdateCompanyWebhookRequest.CommunicationFormatEnum.FromStringOrDefault(communicationFormatRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "encryptionProtocol": + string? encryptionProtocolRawValue = utf8JsonReader.GetString(); + encryptionProtocol = new Option(UpdateCompanyWebhookRequest.EncryptionProtocolEnum.FromStringOrDefault(encryptionProtocolRawValue)); + break; + case "filterMerchantAccountType": + string? filterMerchantAccountTypeRawValue = utf8JsonReader.GetString(); + filterMerchantAccountType = new Option(UpdateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.FromStringOrDefault(filterMerchantAccountTypeRawValue)); + break; + case "filterMerchantAccounts": + filterMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "networkType": + string? networkTypeRawValue = utf8JsonReader.GetString(); + networkType = new Option(UpdateCompanyWebhookRequest.NetworkTypeEnum.FromStringOrDefault(networkTypeRawValue)); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "populateSoapActionHeader": + populateSoapActionHeader = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UpdateCompanyWebhookRequest(acceptsExpiredCertificate, acceptsSelfSignedCertificate, acceptsUntrustedRootCertificate, active, additionalSettings, communicationFormat, description, encryptionProtocol, filterMerchantAccountType, filterMerchantAccounts, networkType, password, populateSoapActionHeader, url, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateCompanyWebhookRequest updateCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateCompanyWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateCompanyWebhookRequest updateCompanyWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateCompanyWebhookRequest._AcceptsExpiredCertificateOption.IsSet) + writer.WriteBoolean("acceptsExpiredCertificate", updateCompanyWebhookRequest._AcceptsExpiredCertificateOption.Value!.Value); + + if (updateCompanyWebhookRequest._AcceptsSelfSignedCertificateOption.IsSet) + writer.WriteBoolean("acceptsSelfSignedCertificate", updateCompanyWebhookRequest._AcceptsSelfSignedCertificateOption.Value!.Value); + + if (updateCompanyWebhookRequest._AcceptsUntrustedRootCertificateOption.IsSet) + writer.WriteBoolean("acceptsUntrustedRootCertificate", updateCompanyWebhookRequest._AcceptsUntrustedRootCertificateOption.Value!.Value); + + if (updateCompanyWebhookRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateCompanyWebhookRequest._ActiveOption.Value!.Value); + + if (updateCompanyWebhookRequest._AdditionalSettingsOption.IsSet) + { + writer.WritePropertyName("additionalSettings"); + JsonSerializer.Serialize(writer, updateCompanyWebhookRequest.AdditionalSettings, jsonSerializerOptions); + } + if (updateCompanyWebhookRequest._CommunicationFormatOption.IsSet && updateCompanyWebhookRequest.CommunicationFormat != null) + { + string? communicationFormatRawValue = UpdateCompanyWebhookRequest.CommunicationFormatEnum.ToJsonValue(updateCompanyWebhookRequest._CommunicationFormatOption.Value!.Value); + writer.WriteString("communicationFormat", communicationFormatRawValue); + } + + if (updateCompanyWebhookRequest._DescriptionOption.IsSet) + if (updateCompanyWebhookRequest.Description != null) + writer.WriteString("description", updateCompanyWebhookRequest.Description); + + if (updateCompanyWebhookRequest._EncryptionProtocolOption.IsSet && updateCompanyWebhookRequest.EncryptionProtocol != null) + { + string? encryptionProtocolRawValue = UpdateCompanyWebhookRequest.EncryptionProtocolEnum.ToJsonValue(updateCompanyWebhookRequest._EncryptionProtocolOption.Value!.Value); + writer.WriteString("encryptionProtocol", encryptionProtocolRawValue); + } + + if (updateCompanyWebhookRequest._FilterMerchantAccountTypeOption.IsSet && updateCompanyWebhookRequest.FilterMerchantAccountType != null) + { + string? filterMerchantAccountTypeRawValue = UpdateCompanyWebhookRequest.FilterMerchantAccountTypeEnum.ToJsonValue(updateCompanyWebhookRequest._FilterMerchantAccountTypeOption.Value!.Value); + writer.WriteString("filterMerchantAccountType", filterMerchantAccountTypeRawValue); + } + + if (updateCompanyWebhookRequest._FilterMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("filterMerchantAccounts"); + JsonSerializer.Serialize(writer, updateCompanyWebhookRequest.FilterMerchantAccounts, jsonSerializerOptions); + } + if (updateCompanyWebhookRequest._NetworkTypeOption.IsSet && updateCompanyWebhookRequest.NetworkType != null) + { + string? networkTypeRawValue = UpdateCompanyWebhookRequest.NetworkTypeEnum.ToJsonValue(updateCompanyWebhookRequest._NetworkTypeOption.Value!.Value); + writer.WriteString("networkType", networkTypeRawValue); + } + + if (updateCompanyWebhookRequest._PasswordOption.IsSet) + if (updateCompanyWebhookRequest.Password != null) + writer.WriteString("password", updateCompanyWebhookRequest.Password); + + if (updateCompanyWebhookRequest._PopulateSoapActionHeaderOption.IsSet) + writer.WriteBoolean("populateSoapActionHeader", updateCompanyWebhookRequest._PopulateSoapActionHeaderOption.Value!.Value); + + if (updateCompanyWebhookRequest._UrlOption.IsSet) + if (updateCompanyWebhookRequest.Url != null) + writer.WriteString("url", updateCompanyWebhookRequest.Url); + + if (updateCompanyWebhookRequest._UsernameOption.IsSet) + if (updateCompanyWebhookRequest.Username != null) + writer.WriteString("username", updateCompanyWebhookRequest.Username); + } + } +} diff --git a/Adyen/Management/Models/UpdateMerchantApiCredentialRequest.cs b/Adyen/Management/Models/UpdateMerchantApiCredentialRequest.cs new file mode 100644 index 000000000..9c5224807 --- /dev/null +++ b/Adyen/Management/Models/UpdateMerchantApiCredentialRequest.cs @@ -0,0 +1,254 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateMerchantApiCredentialRequest. + /// + public partial class UpdateMerchantApiCredentialRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the API credential is enabled. + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + /// Description of the API credential. + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + [JsonConstructor] + public UpdateMerchantApiCredentialRequest(Option active = default, Option?> allowedOrigins = default, Option description = default, Option?> roles = default) + { + _ActiveOption = active; + _AllowedOriginsOption = allowedOrigins; + _DescriptionOption = description; + _RolesOption = roles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateMerchantApiCredentialRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates if the API credential is enabled. + /// + /// Indicates if the API credential is enabled. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AllowedOriginsOption { get; private set; } + + /// + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + /// + /// The new list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential. + [JsonPropertyName("allowedOrigins")] + public List? AllowedOrigins { get { return this._AllowedOriginsOption; } set { this._AllowedOriginsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Description of the API credential. + /// + /// Description of the API credential. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.<CompanyName>' can be assigned to other API credentials. + /// + /// List of [roles](https://docs.adyen.com/development-resources/api-credentials#roles-1) for the API credential. Only roles assigned to 'ws@Company.' can be assigned to other API credentials. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateMerchantApiCredentialRequest {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AllowedOrigins: ").Append(AllowedOrigins).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateMerchantApiCredentialRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateMerchantApiCredentialRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option?> allowedOrigins = default; + Option description = default; + Option?> roles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedOrigins": + allowedOrigins = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new UpdateMerchantApiCredentialRequest(active, allowedOrigins, description, roles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateMerchantApiCredentialRequest updateMerchantApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateMerchantApiCredentialRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateMerchantApiCredentialRequest updateMerchantApiCredentialRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateMerchantApiCredentialRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateMerchantApiCredentialRequest._ActiveOption.Value!.Value); + + if (updateMerchantApiCredentialRequest._AllowedOriginsOption.IsSet) + { + writer.WritePropertyName("allowedOrigins"); + JsonSerializer.Serialize(writer, updateMerchantApiCredentialRequest.AllowedOrigins, jsonSerializerOptions); + } + if (updateMerchantApiCredentialRequest._DescriptionOption.IsSet) + if (updateMerchantApiCredentialRequest.Description != null) + writer.WriteString("description", updateMerchantApiCredentialRequest.Description); + + if (updateMerchantApiCredentialRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, updateMerchantApiCredentialRequest.Roles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/UpdateMerchantUserRequest.cs b/Adyen/Management/Models/UpdateMerchantUserRequest.cs new file mode 100644 index 000000000..958ca38f7 --- /dev/null +++ b/Adyen/Management/Models/UpdateMerchantUserRequest.cs @@ -0,0 +1,328 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateMerchantUserRequest. + /// + public partial class UpdateMerchantUserRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Sets the status of the user to active (**true**) or inactive (**false**). + /// The email address of the user. + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// name + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonConstructor] + public UpdateMerchantUserRequest(Option?> accountGroups = default, Option active = default, Option email = default, Option loginMethod = default, Option name = default, Option?> roles = default, Option timeZoneCode = default) + { + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _EmailOption = email; + _LoginMethodOption = loginMethod; + _NameOption = name; + _RolesOption = roles; + _TimeZoneCodeOption = timeZoneCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateMerchantUserRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Sets the status of the user to active (**true**) or inactive (**false**). + /// + /// Sets the status of the user to active (**true**) or inactive (**false**). + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LoginMethodOption { get; private set; } + + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + /// + /// The requested login method for the user. To use SSO, you must already have SSO configured with Adyen before creating the user. Possible values: **Username & account**, **Email**, or **SSO** + [JsonPropertyName("loginMethod")] + public string? LoginMethod { get { return this._LoginMethodOption; } set { this._LoginMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name2? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimeZoneCodeOption { get; private set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string? TimeZoneCode { get { return this._TimeZoneCodeOption; } set { this._TimeZoneCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateMerchantUserRequest {\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" LoginMethod: ").Append(LoginMethod).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateMerchantUserRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateMerchantUserRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> accountGroups = default; + Option active = default; + Option email = default; + Option loginMethod = default; + Option name = default; + Option?> roles = default; + Option timeZoneCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "loginMethod": + loginMethod = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UpdateMerchantUserRequest(accountGroups, active, email, loginMethod, name, roles, timeZoneCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateMerchantUserRequest updateMerchantUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateMerchantUserRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateMerchantUserRequest updateMerchantUserRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateMerchantUserRequest._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, updateMerchantUserRequest.AccountGroups, jsonSerializerOptions); + } + if (updateMerchantUserRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateMerchantUserRequest._ActiveOption.Value!.Value); + + if (updateMerchantUserRequest._EmailOption.IsSet) + if (updateMerchantUserRequest.Email != null) + writer.WriteString("email", updateMerchantUserRequest.Email); + + if (updateMerchantUserRequest._LoginMethodOption.IsSet) + if (updateMerchantUserRequest.LoginMethod != null) + writer.WriteString("loginMethod", updateMerchantUserRequest.LoginMethod); + + if (updateMerchantUserRequest._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, updateMerchantUserRequest.Name, jsonSerializerOptions); + } + if (updateMerchantUserRequest._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, updateMerchantUserRequest.Roles, jsonSerializerOptions); + } + if (updateMerchantUserRequest._TimeZoneCodeOption.IsSet) + if (updateMerchantUserRequest.TimeZoneCode != null) + writer.WriteString("timeZoneCode", updateMerchantUserRequest.TimeZoneCode); + } + } +} diff --git a/Adyen/Management/Models/UpdateMerchantWebhookRequest.cs b/Adyen/Management/Models/UpdateMerchantWebhookRequest.cs new file mode 100644 index 000000000..43760b2d6 --- /dev/null +++ b/Adyen/Management/Models/UpdateMerchantWebhookRequest.cs @@ -0,0 +1,817 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateMerchantWebhookRequest. + /// + public partial class UpdateMerchantWebhookRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// additionalSettings + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// Your description for this webhook configuration. + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// Password to access the webhook URL. + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// Username to access the webhook URL. + [JsonConstructor] + public UpdateMerchantWebhookRequest(Option acceptsExpiredCertificate = default, Option acceptsSelfSignedCertificate = default, Option acceptsUntrustedRootCertificate = default, Option active = default, Option additionalSettings = default, Option communicationFormat = default, Option description = default, Option encryptionProtocol = default, Option networkType = default, Option password = default, Option populateSoapActionHeader = default, Option url = default, Option username = default) + { + _AcceptsExpiredCertificateOption = acceptsExpiredCertificate; + _AcceptsSelfSignedCertificateOption = acceptsSelfSignedCertificate; + _AcceptsUntrustedRootCertificateOption = acceptsUntrustedRootCertificate; + _ActiveOption = active; + _AdditionalSettingsOption = additionalSettings; + _CommunicationFormatOption = communicationFormat; + _DescriptionOption = description; + _EncryptionProtocolOption = encryptionProtocol; + _NetworkTypeOption = networkType; + _PasswordOption = password; + _PopulateSoapActionHeaderOption = populateSoapActionHeader; + _UrlOption = url; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateMerchantWebhookRequest() + { + } + + partial void OnCreated(); + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + [JsonConverter(typeof(CommunicationFormatEnumJsonConverter))] + public class CommunicationFormatEnum : IEnum + { + /// + /// Returns the value of the CommunicationFormatEnum. + /// + public string? Value { get; set; } + + /// + /// CommunicationFormatEnum.Http - http + /// + public static readonly CommunicationFormatEnum Http = new("http"); + + /// + /// CommunicationFormatEnum.Json - json + /// + public static readonly CommunicationFormatEnum Json = new("json"); + + /// + /// CommunicationFormatEnum.Soap - soap + /// + public static readonly CommunicationFormatEnum Soap = new("soap"); + + private CommunicationFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CommunicationFormatEnum?(string? value) => value == null ? null : new CommunicationFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CommunicationFormatEnum? option) => option?.Value; + + public static bool operator ==(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CommunicationFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CommunicationFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "http" => CommunicationFormatEnum.Http, + "json" => CommunicationFormatEnum.Json, + "soap" => CommunicationFormatEnum.Soap, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CommunicationFormatEnum? value) + { + if (value == null) + return null; + + if (value == CommunicationFormatEnum.Http) + return "http"; + + if (value == CommunicationFormatEnum.Json) + return "json"; + + if (value == CommunicationFormatEnum.Soap) + return "soap"; + + return null; + } + + /// + /// JsonConverter for writing CommunicationFormatEnum. + /// + public class CommunicationFormatEnumJsonConverter : JsonConverter + { + public override CommunicationFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CommunicationFormatEnum.FromStringOrDefault(value) ?? new CommunicationFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CommunicationFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CommunicationFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CommunicationFormatOption { get; private set; } + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /* soap */ + [JsonPropertyName("communicationFormat")] + public CommunicationFormatEnum? CommunicationFormat { get { return this._CommunicationFormatOption; } set { this._CommunicationFormatOption = new(value); } } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + [JsonConverter(typeof(EncryptionProtocolEnumJsonConverter))] + public class EncryptionProtocolEnum : IEnum + { + /// + /// Returns the value of the EncryptionProtocolEnum. + /// + public string? Value { get; set; } + + /// + /// EncryptionProtocolEnum.HTTP - HTTP + /// + public static readonly EncryptionProtocolEnum HTTP = new("HTTP"); + + /// + /// EncryptionProtocolEnum.TLSv12 - TLSv1.2 + /// + public static readonly EncryptionProtocolEnum TLSv12 = new("TLSv1.2"); + + /// + /// EncryptionProtocolEnum.TLSv13 - TLSv1.3 + /// + public static readonly EncryptionProtocolEnum TLSv13 = new("TLSv1.3"); + + private EncryptionProtocolEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EncryptionProtocolEnum?(string? value) => value == null ? null : new EncryptionProtocolEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EncryptionProtocolEnum? option) => option?.Value; + + public static bool operator ==(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EncryptionProtocolEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EncryptionProtocolEnum? FromStringOrDefault(string value) + { + return value switch { + "HTTP" => EncryptionProtocolEnum.HTTP, + "TLSv1.2" => EncryptionProtocolEnum.TLSv12, + "TLSv1.3" => EncryptionProtocolEnum.TLSv13, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EncryptionProtocolEnum? value) + { + if (value == null) + return null; + + if (value == EncryptionProtocolEnum.HTTP) + return "HTTP"; + + if (value == EncryptionProtocolEnum.TLSv12) + return "TLSv1.2"; + + if (value == EncryptionProtocolEnum.TLSv13) + return "TLSv1.3"; + + return null; + } + + /// + /// JsonConverter for writing EncryptionProtocolEnum. + /// + public class EncryptionProtocolEnumJsonConverter : JsonConverter + { + public override EncryptionProtocolEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EncryptionProtocolEnum.FromStringOrDefault(value) ?? new EncryptionProtocolEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EncryptionProtocolEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EncryptionProtocolEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionProtocolOption { get; private set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /* TLSv1.2 */ + [JsonPropertyName("encryptionProtocol")] + public EncryptionProtocolEnum? EncryptionProtocol { get { return this._EncryptionProtocolOption; } set { this._EncryptionProtocolOption = new(value); } } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonConverter(typeof(NetworkTypeEnumJsonConverter))] + public class NetworkTypeEnum : IEnum + { + /// + /// Returns the value of the NetworkTypeEnum. + /// + public string? Value { get; set; } + + /// + /// NetworkTypeEnum.Local - local + /// + public static readonly NetworkTypeEnum Local = new("local"); + + /// + /// NetworkTypeEnum.Public - public + /// + public static readonly NetworkTypeEnum Public = new("public"); + + private NetworkTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NetworkTypeEnum?(string? value) => value == null ? null : new NetworkTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NetworkTypeEnum? option) => option?.Value; + + public static bool operator ==(NetworkTypeEnum? left, NetworkTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NetworkTypeEnum? left, NetworkTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NetworkTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NetworkTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "local" => NetworkTypeEnum.Local, + "public" => NetworkTypeEnum.Public, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NetworkTypeEnum? value) + { + if (value == null) + return null; + + if (value == NetworkTypeEnum.Local) + return "local"; + + if (value == NetworkTypeEnum.Public) + return "public"; + + return null; + } + + /// + /// JsonConverter for writing NetworkTypeEnum. + /// + public class NetworkTypeEnumJsonConverter : JsonConverter + { + public override NetworkTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NetworkTypeEnum.FromStringOrDefault(value) ?? new NetworkTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NetworkTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NetworkTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTypeOption { get; private set; } + + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + /// + /// Network type for Terminal API notification webhooks. Possible values: * **public** * **local** Default Value: **public**. + [JsonPropertyName("networkType")] + public NetworkTypeEnum? NetworkType { get { return this._NetworkTypeOption; } set { this._NetworkTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsExpiredCertificateOption { get; private set; } + + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsExpiredCertificate")] + public bool? AcceptsExpiredCertificate { get { return this._AcceptsExpiredCertificateOption; } set { this._AcceptsExpiredCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsSelfSignedCertificateOption { get; private set; } + + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsSelfSignedCertificate")] + public bool? AcceptsSelfSignedCertificate { get { return this._AcceptsSelfSignedCertificateOption; } set { this._AcceptsSelfSignedCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsUntrustedRootCertificateOption { get; private set; } + + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsUntrustedRootCertificate")] + public bool? AcceptsUntrustedRootCertificate { get { return this._AcceptsUntrustedRootCertificateOption; } set { this._AcceptsUntrustedRootCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for us to send webhooks about events related an account. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalSettings")] + public AdditionalSettings? AdditionalSettings { get { return this._AdditionalSettingsOption; } set { this._AdditionalSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for this webhook configuration. + /// + /// Your description for this webhook configuration. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// Password to access the webhook URL. + /// + /// Password to access the webhook URL. + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PopulateSoapActionHeaderOption { get; private set; } + + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + [JsonPropertyName("populateSoapActionHeader")] + public bool? PopulateSoapActionHeader { get { return this._PopulateSoapActionHeaderOption; } set { this._PopulateSoapActionHeaderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /* http://www.adyen.com */ + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// Username to access the webhook URL. + /// + /// Username to access the webhook URL. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateMerchantWebhookRequest {\n"); + sb.Append(" AcceptsExpiredCertificate: ").Append(AcceptsExpiredCertificate).Append("\n"); + sb.Append(" AcceptsSelfSignedCertificate: ").Append(AcceptsSelfSignedCertificate).Append("\n"); + sb.Append(" AcceptsUntrustedRootCertificate: ").Append(AcceptsUntrustedRootCertificate).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" AdditionalSettings: ").Append(AdditionalSettings).Append("\n"); + sb.Append(" CommunicationFormat: ").Append(CommunicationFormat).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EncryptionProtocol: ").Append(EncryptionProtocol).Append("\n"); + sb.Append(" NetworkType: ").Append(NetworkType).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PopulateSoapActionHeader: ").Append(PopulateSoapActionHeader).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateMerchantWebhookRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateMerchantWebhookRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptsExpiredCertificate = default; + Option acceptsSelfSignedCertificate = default; + Option acceptsUntrustedRootCertificate = default; + Option active = default; + Option additionalSettings = default; + Option communicationFormat = default; + Option description = default; + Option encryptionProtocol = default; + Option networkType = default; + Option password = default; + Option populateSoapActionHeader = default; + Option url = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptsExpiredCertificate": + acceptsExpiredCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsSelfSignedCertificate": + acceptsSelfSignedCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsUntrustedRootCertificate": + acceptsUntrustedRootCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "additionalSettings": + additionalSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "communicationFormat": + string? communicationFormatRawValue = utf8JsonReader.GetString(); + communicationFormat = new Option(UpdateMerchantWebhookRequest.CommunicationFormatEnum.FromStringOrDefault(communicationFormatRawValue)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "encryptionProtocol": + string? encryptionProtocolRawValue = utf8JsonReader.GetString(); + encryptionProtocol = new Option(UpdateMerchantWebhookRequest.EncryptionProtocolEnum.FromStringOrDefault(encryptionProtocolRawValue)); + break; + case "networkType": + string? networkTypeRawValue = utf8JsonReader.GetString(); + networkType = new Option(UpdateMerchantWebhookRequest.NetworkTypeEnum.FromStringOrDefault(networkTypeRawValue)); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "populateSoapActionHeader": + populateSoapActionHeader = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UpdateMerchantWebhookRequest(acceptsExpiredCertificate, acceptsSelfSignedCertificate, acceptsUntrustedRootCertificate, active, additionalSettings, communicationFormat, description, encryptionProtocol, networkType, password, populateSoapActionHeader, url, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateMerchantWebhookRequest updateMerchantWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateMerchantWebhookRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateMerchantWebhookRequest updateMerchantWebhookRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateMerchantWebhookRequest._AcceptsExpiredCertificateOption.IsSet) + writer.WriteBoolean("acceptsExpiredCertificate", updateMerchantWebhookRequest._AcceptsExpiredCertificateOption.Value!.Value); + + if (updateMerchantWebhookRequest._AcceptsSelfSignedCertificateOption.IsSet) + writer.WriteBoolean("acceptsSelfSignedCertificate", updateMerchantWebhookRequest._AcceptsSelfSignedCertificateOption.Value!.Value); + + if (updateMerchantWebhookRequest._AcceptsUntrustedRootCertificateOption.IsSet) + writer.WriteBoolean("acceptsUntrustedRootCertificate", updateMerchantWebhookRequest._AcceptsUntrustedRootCertificateOption.Value!.Value); + + if (updateMerchantWebhookRequest._ActiveOption.IsSet) + writer.WriteBoolean("active", updateMerchantWebhookRequest._ActiveOption.Value!.Value); + + if (updateMerchantWebhookRequest._AdditionalSettingsOption.IsSet) + { + writer.WritePropertyName("additionalSettings"); + JsonSerializer.Serialize(writer, updateMerchantWebhookRequest.AdditionalSettings, jsonSerializerOptions); + } + if (updateMerchantWebhookRequest._CommunicationFormatOption.IsSet && updateMerchantWebhookRequest.CommunicationFormat != null) + { + string? communicationFormatRawValue = UpdateMerchantWebhookRequest.CommunicationFormatEnum.ToJsonValue(updateMerchantWebhookRequest._CommunicationFormatOption.Value!.Value); + writer.WriteString("communicationFormat", communicationFormatRawValue); + } + + if (updateMerchantWebhookRequest._DescriptionOption.IsSet) + if (updateMerchantWebhookRequest.Description != null) + writer.WriteString("description", updateMerchantWebhookRequest.Description); + + if (updateMerchantWebhookRequest._EncryptionProtocolOption.IsSet && updateMerchantWebhookRequest.EncryptionProtocol != null) + { + string? encryptionProtocolRawValue = UpdateMerchantWebhookRequest.EncryptionProtocolEnum.ToJsonValue(updateMerchantWebhookRequest._EncryptionProtocolOption.Value!.Value); + writer.WriteString("encryptionProtocol", encryptionProtocolRawValue); + } + + if (updateMerchantWebhookRequest._NetworkTypeOption.IsSet && updateMerchantWebhookRequest.NetworkType != null) + { + string? networkTypeRawValue = UpdateMerchantWebhookRequest.NetworkTypeEnum.ToJsonValue(updateMerchantWebhookRequest._NetworkTypeOption.Value!.Value); + writer.WriteString("networkType", networkTypeRawValue); + } + + if (updateMerchantWebhookRequest._PasswordOption.IsSet) + if (updateMerchantWebhookRequest.Password != null) + writer.WriteString("password", updateMerchantWebhookRequest.Password); + + if (updateMerchantWebhookRequest._PopulateSoapActionHeaderOption.IsSet) + writer.WriteBoolean("populateSoapActionHeader", updateMerchantWebhookRequest._PopulateSoapActionHeaderOption.Value!.Value); + + if (updateMerchantWebhookRequest._UrlOption.IsSet) + if (updateMerchantWebhookRequest.Url != null) + writer.WriteString("url", updateMerchantWebhookRequest.Url); + + if (updateMerchantWebhookRequest._UsernameOption.IsSet) + if (updateMerchantWebhookRequest.Username != null) + writer.WriteString("username", updateMerchantWebhookRequest.Username); + } + } +} diff --git a/Adyen/Management/Models/UpdatePaymentMethodInfo.cs b/Adyen/Management/Models/UpdatePaymentMethodInfo.cs new file mode 100644 index 000000000..900bdc519 --- /dev/null +++ b/Adyen/Management/Models/UpdatePaymentMethodInfo.cs @@ -0,0 +1,832 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdatePaymentMethodInfo. + /// + public partial class UpdatePaymentMethodInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accel + /// bcmc + /// cartesBancaires + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// cup + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// Custom routing flags for acquirer routing. + /// diners + /// discover + /// eftDirectdebitCA + /// eftposAustralia + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// girocard + /// ideal + /// interacCard + /// jcb + /// maestro + /// maestroUsa + /// mc + /// nyce + /// paybybankPlaid + /// pulse + /// sepadirectdebit + /// star + /// The store for this payment method + /// The list of stores for this payment method + /// visa + [JsonConstructor] + public UpdatePaymentMethodInfo(Option accel = default, Option bcmc = default, Option cartesBancaires = default, Option?> countries = default, Option cup = default, Option?> currencies = default, Option?> customRoutingFlags = default, Option diners = default, Option discover = default, Option eftDirectdebitCA = default, Option eftposAustralia = default, Option enabled = default, Option girocard = default, Option ideal = default, Option interacCard = default, Option jcb = default, Option maestro = default, Option maestroUsa = default, Option mc = default, Option nyce = default, Option paybybankPlaid = default, Option pulse = default, Option sepadirectdebit = default, Option star = default, Option storeId = default, Option?> storeIds = default, Option visa = default) + { + _AccelOption = accel; + _BcmcOption = bcmc; + _CartesBancairesOption = cartesBancaires; + _CountriesOption = countries; + _CupOption = cup; + _CurrenciesOption = currencies; + _CustomRoutingFlagsOption = customRoutingFlags; + _DinersOption = diners; + _DiscoverOption = discover; + _EftDirectdebitCAOption = eftDirectdebitCA; + _EftposAustraliaOption = eftposAustralia; + _EnabledOption = enabled; + _GirocardOption = girocard; + _IdealOption = ideal; + _InteracCardOption = interacCard; + _JcbOption = jcb; + _MaestroOption = maestro; + _MaestroUsaOption = maestroUsa; + _McOption = mc; + _NyceOption = nyce; + _PaybybankPlaidOption = paybybankPlaid; + _PulseOption = pulse; + _SepadirectdebitOption = sepadirectdebit; + _StarOption = star; + _StoreIdOption = storeId; + _StoreIdsOption = storeIds; + _VisaOption = visa; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdatePaymentMethodInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccelOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accel")] + public AccelInfo? Accel { get { return this._AccelOption; } set { this._AccelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BcmcOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bcmc")] + public BcmcInfo? Bcmc { get { return this._BcmcOption; } set { this._BcmcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CartesBancairesOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cartesBancaires")] + public CartesBancairesInfo? CartesBancaires { get { return this._CartesBancairesOption; } set { this._CartesBancairesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CountriesOption { get; private set; } + + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + /// + /// The list of countries where a payment method is available. By default, all countries supported by the payment method. + [JsonPropertyName("countries")] + public List? Countries { get { return this._CountriesOption; } set { this._CountriesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CupOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("cup")] + public GenericPmWithTdiInfo? Cup { get { return this._CupOption; } set { this._CupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CurrenciesOption { get; private set; } + + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + /// + /// The list of currencies that a payment method supports. By default, all currencies supported by the payment method. + [JsonPropertyName("currencies")] + public List? Currencies { get { return this._CurrenciesOption; } set { this._CurrenciesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _CustomRoutingFlagsOption { get; private set; } + + /// + /// Custom routing flags for acquirer routing. + /// + /// Custom routing flags for acquirer routing. + [JsonPropertyName("customRoutingFlags")] + public List? CustomRoutingFlags { get { return this._CustomRoutingFlagsOption; } set { this._CustomRoutingFlagsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DinersOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("diners")] + public GenericPmWithTdiInfo? Diners { get { return this._DinersOption; } set { this._DinersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DiscoverOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("discover")] + public GenericPmWithTdiInfo? Discover { get { return this._DiscoverOption; } set { this._DiscoverOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftDirectdebitCAOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eft_directdebit_CA")] + public GenericPmWithTdiInfo? EftDirectdebitCA { get { return this._EftDirectdebitCAOption; } set { this._EftDirectdebitCAOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EftposAustraliaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("eftpos_australia")] + public GenericPmWithTdiInfo? EftposAustralia { get { return this._EftposAustraliaOption; } set { this._EftposAustraliaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GirocardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("girocard")] + public GenericPmWithTdiInfo? Girocard { get { return this._GirocardOption; } set { this._GirocardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdealOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ideal")] + public GenericPmWithTdiInfo? Ideal { get { return this._IdealOption; } set { this._IdealOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InteracCardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interac_card")] + public GenericPmWithTdiInfo? InteracCard { get { return this._InteracCardOption; } set { this._InteracCardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JcbOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("jcb")] + public GenericPmWithTdiInfo? Jcb { get { return this._JcbOption; } set { this._JcbOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro")] + public GenericPmWithTdiInfo? Maestro { get { return this._MaestroOption; } set { this._MaestroOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaestroUsaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maestro_usa")] + public GenericPmWithTdiInfo? MaestroUsa { get { return this._MaestroUsaOption; } set { this._MaestroUsaOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mc")] + public GenericPmWithTdiInfo? Mc { get { return this._McOption; } set { this._McOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NyceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nyce")] + public NyceInfo? Nyce { get { return this._NyceOption; } set { this._NyceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaybybankPlaidOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paybybank_plaid")] + public PayByBankPlaidInfo? PaybybankPlaid { get { return this._PaybybankPlaidOption; } set { this._PaybybankPlaidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PulseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("pulse")] + public PulseInfo? Pulse { get { return this._PulseOption; } set { this._PulseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sepadirectdebit")] + public SepaDirectDebitInfo? Sepadirectdebit { get { return this._SepadirectdebitOption; } set { this._SepadirectdebitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StarOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("star")] + public StarInfo? Star { get { return this._StarOption; } set { this._StarOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The store for this payment method + /// + /// The store for this payment method + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _StoreIdsOption { get; private set; } + + /// + /// The list of stores for this payment method + /// + /// The list of stores for this payment method + [JsonPropertyName("storeIds")] + [Obsolete("Deprecated since Management API v3. Use `storeId` instead. Only one store per payment method is allowed.")] + public List? StoreIds { get { return this._StoreIdsOption; } set { this._StoreIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("visa")] + public GenericPmWithTdiInfo? Visa { get { return this._VisaOption; } set { this._VisaOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdatePaymentMethodInfo {\n"); + sb.Append(" Accel: ").Append(Accel).Append("\n"); + sb.Append(" Bcmc: ").Append(Bcmc).Append("\n"); + sb.Append(" CartesBancaires: ").Append(CartesBancaires).Append("\n"); + sb.Append(" Countries: ").Append(Countries).Append("\n"); + sb.Append(" Cup: ").Append(Cup).Append("\n"); + sb.Append(" Currencies: ").Append(Currencies).Append("\n"); + sb.Append(" CustomRoutingFlags: ").Append(CustomRoutingFlags).Append("\n"); + sb.Append(" Diners: ").Append(Diners).Append("\n"); + sb.Append(" Discover: ").Append(Discover).Append("\n"); + sb.Append(" EftDirectdebitCA: ").Append(EftDirectdebitCA).Append("\n"); + sb.Append(" EftposAustralia: ").Append(EftposAustralia).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Girocard: ").Append(Girocard).Append("\n"); + sb.Append(" Ideal: ").Append(Ideal).Append("\n"); + sb.Append(" InteracCard: ").Append(InteracCard).Append("\n"); + sb.Append(" Jcb: ").Append(Jcb).Append("\n"); + sb.Append(" Maestro: ").Append(Maestro).Append("\n"); + sb.Append(" MaestroUsa: ").Append(MaestroUsa).Append("\n"); + sb.Append(" Mc: ").Append(Mc).Append("\n"); + sb.Append(" Nyce: ").Append(Nyce).Append("\n"); + sb.Append(" PaybybankPlaid: ").Append(PaybybankPlaid).Append("\n"); + sb.Append(" Pulse: ").Append(Pulse).Append("\n"); + sb.Append(" Sepadirectdebit: ").Append(Sepadirectdebit).Append("\n"); + sb.Append(" Star: ").Append(Star).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append(" StoreIds: ").Append(StoreIds).Append("\n"); + sb.Append(" Visa: ").Append(Visa).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdatePaymentMethodInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdatePaymentMethodInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accel = default; + Option bcmc = default; + Option cartesBancaires = default; + Option?> countries = default; + Option cup = default; + Option?> currencies = default; + Option?> customRoutingFlags = default; + Option diners = default; + Option discover = default; + Option eftDirectdebitCA = default; + Option eftposAustralia = default; + Option enabled = default; + Option girocard = default; + Option ideal = default; + Option interacCard = default; + Option jcb = default; + Option maestro = default; + Option maestroUsa = default; + Option mc = default; + Option nyce = default; + Option paybybankPlaid = default; + Option pulse = default; + Option sepadirectdebit = default; + Option star = default; + Option storeId = default; + Option?> storeIds = default; + Option visa = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accel": + accel = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bcmc": + bcmc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cartesBancaires": + cartesBancaires = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "countries": + countries = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cup": + cup = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "currencies": + currencies = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "customRoutingFlags": + customRoutingFlags = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "diners": + diners = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "discover": + discover = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eft_directdebit_CA": + eftDirectdebitCA = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "eftpos_australia": + eftposAustralia = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "girocard": + girocard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ideal": + ideal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interac_card": + interacCard = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "jcb": + jcb = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro": + maestro = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "maestro_usa": + maestroUsa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mc": + mc = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nyce": + nyce = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paybybank_plaid": + paybybankPlaid = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pulse": + pulse = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sepadirectdebit": + sepadirectdebit = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "star": + star = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + case "storeIds": + storeIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "visa": + visa = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new UpdatePaymentMethodInfo(accel, bcmc, cartesBancaires, countries, cup, currencies, customRoutingFlags, diners, discover, eftDirectdebitCA, eftposAustralia, enabled, girocard, ideal, interacCard, jcb, maestro, maestroUsa, mc, nyce, paybybankPlaid, pulse, sepadirectdebit, star, storeId, storeIds, visa); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdatePaymentMethodInfo updatePaymentMethodInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updatePaymentMethodInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdatePaymentMethodInfo updatePaymentMethodInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (updatePaymentMethodInfo._AccelOption.IsSet) + { + writer.WritePropertyName("accel"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Accel, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._BcmcOption.IsSet) + { + writer.WritePropertyName("bcmc"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Bcmc, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._CartesBancairesOption.IsSet) + { + writer.WritePropertyName("cartesBancaires"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.CartesBancaires, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._CountriesOption.IsSet) + { + writer.WritePropertyName("countries"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Countries, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._CupOption.IsSet) + { + writer.WritePropertyName("cup"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Cup, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._CurrenciesOption.IsSet) + { + writer.WritePropertyName("currencies"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Currencies, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._CustomRoutingFlagsOption.IsSet) + { + writer.WritePropertyName("customRoutingFlags"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.CustomRoutingFlags, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._DinersOption.IsSet) + { + writer.WritePropertyName("diners"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Diners, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._DiscoverOption.IsSet) + { + writer.WritePropertyName("discover"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Discover, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._EftDirectdebitCAOption.IsSet) + { + writer.WritePropertyName("eft_directdebit_CA"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.EftDirectdebitCA, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._EftposAustraliaOption.IsSet) + { + writer.WritePropertyName("eftpos_australia"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.EftposAustralia, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._EnabledOption.IsSet) + writer.WriteBoolean("enabled", updatePaymentMethodInfo._EnabledOption.Value!.Value); + + if (updatePaymentMethodInfo._GirocardOption.IsSet) + { + writer.WritePropertyName("girocard"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Girocard, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._IdealOption.IsSet) + { + writer.WritePropertyName("ideal"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Ideal, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._InteracCardOption.IsSet) + { + writer.WritePropertyName("interac_card"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.InteracCard, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._JcbOption.IsSet) + { + writer.WritePropertyName("jcb"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Jcb, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._MaestroOption.IsSet) + { + writer.WritePropertyName("maestro"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Maestro, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._MaestroUsaOption.IsSet) + { + writer.WritePropertyName("maestro_usa"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.MaestroUsa, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._McOption.IsSet) + { + writer.WritePropertyName("mc"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Mc, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._NyceOption.IsSet) + { + writer.WritePropertyName("nyce"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Nyce, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._PaybybankPlaidOption.IsSet) + { + writer.WritePropertyName("paybybank_plaid"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.PaybybankPlaid, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._PulseOption.IsSet) + { + writer.WritePropertyName("pulse"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Pulse, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._SepadirectdebitOption.IsSet) + { + writer.WritePropertyName("sepadirectdebit"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Sepadirectdebit, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._StarOption.IsSet) + { + writer.WritePropertyName("star"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Star, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._StoreIdOption.IsSet) + if (updatePaymentMethodInfo.StoreId != null) + writer.WriteString("storeId", updatePaymentMethodInfo.StoreId); + + if (updatePaymentMethodInfo._StoreIdsOption.IsSet) + { + writer.WritePropertyName("storeIds"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.StoreIds, jsonSerializerOptions); + } + if (updatePaymentMethodInfo._VisaOption.IsSet) + { + writer.WritePropertyName("visa"); + JsonSerializer.Serialize(writer, updatePaymentMethodInfo.Visa, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/UpdatePayoutSettingsRequest.cs b/Adyen/Management/Models/UpdatePayoutSettingsRequest.cs new file mode 100644 index 000000000..c56496ddc --- /dev/null +++ b/Adyen/Management/Models/UpdatePayoutSettingsRequest.cs @@ -0,0 +1,176 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdatePayoutSettingsRequest. + /// + public partial class UpdatePayoutSettingsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + [JsonConstructor] + public UpdatePayoutSettingsRequest(Option enabled = default) + { + _EnabledOption = enabled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdatePayoutSettingsRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + /// + /// Indicates if payouts to this bank account are enabled. Default: **true**. To receive payouts into this bank account, both `enabled` and `allowed` must be **true**. + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdatePayoutSettingsRequest {\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdatePayoutSettingsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdatePayoutSettingsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enabled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new UpdatePayoutSettingsRequest(enabled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdatePayoutSettingsRequest updatePayoutSettingsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updatePayoutSettingsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdatePayoutSettingsRequest updatePayoutSettingsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updatePayoutSettingsRequest._EnabledOption.IsSet) + writer.WriteBoolean("enabled", updatePayoutSettingsRequest._EnabledOption.Value!.Value); + } + } +} diff --git a/Adyen/Management/Models/UpdateSplitConfigurationLogicRequest.cs b/Adyen/Management/Models/UpdateSplitConfigurationLogicRequest.cs new file mode 100644 index 000000000..9c9666b62 --- /dev/null +++ b/Adyen/Management/Models/UpdateSplitConfigurationLogicRequest.cs @@ -0,0 +1,2071 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateSplitConfigurationLogicRequest. + /// + public partial class UpdateSplitConfigurationLogicRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// commission + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// additionalCommission + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConstructor] + public UpdateSplitConfigurationLogicRequest(Commission commission, Option acquiringFees = default, Option additionalCommission = default, Option adyenCommission = default, Option adyenFees = default, Option adyenMarkup = default, Option chargeback = default, Option chargebackCostAllocation = default, Option interchange = default, Option paymentFee = default, Option refund = default, Option refundCostAllocation = default, Option remainder = default, Option schemeFee = default, Option splitLogicId = default, Option surcharge = default, Option tip = default) + { + Commission = commission; + _AcquiringFeesOption = acquiringFees; + _AdditionalCommissionOption = additionalCommission; + _AdyenCommissionOption = adyenCommission; + _AdyenFeesOption = adyenFees; + _AdyenMarkupOption = adyenMarkup; + _ChargebackOption = chargeback; + _ChargebackCostAllocationOption = chargebackCostAllocation; + _InterchangeOption = interchange; + _PaymentFeeOption = paymentFee; + _RefundOption = refund; + _RefundCostAllocationOption = refundCostAllocation; + _RemainderOption = remainder; + _SchemeFeeOption = schemeFee; + _SplitLogicIdOption = splitLogicId; + _SurchargeOption = surcharge; + _TipOption = tip; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateSplitConfigurationLogicRequest() + { + } + + partial void OnCreated(); + + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AcquiringFeesEnumJsonConverter))] + public class AcquiringFeesEnum : IEnum + { + /// + /// Returns the value of the AcquiringFeesEnum. + /// + public string? Value { get; set; } + + /// + /// AcquiringFeesEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AcquiringFeesEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AcquiringFeesEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AcquiringFeesEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AcquiringFeesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AcquiringFeesEnum?(string? value) => value == null ? null : new AcquiringFeesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AcquiringFeesEnum? option) => option?.Value; + + public static bool operator ==(AcquiringFeesEnum? left, AcquiringFeesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AcquiringFeesEnum? left, AcquiringFeesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AcquiringFeesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AcquiringFeesEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AcquiringFeesEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AcquiringFeesEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AcquiringFeesEnum? value) + { + if (value == null) + return null; + + if (value == AcquiringFeesEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AcquiringFeesEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AcquiringFeesEnum. + /// + public class AcquiringFeesEnumJsonConverter : JsonConverter + { + public override AcquiringFeesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AcquiringFeesEnum.FromStringOrDefault(value) ?? new AcquiringFeesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AcquiringFeesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AcquiringFeesEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquiringFeesOption { get; private set; } + + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the acquiring fees (the aggregated amount of interchange and scheme fee) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("acquiringFees")] + public AcquiringFeesEnum? AcquiringFees { get { return this._AcquiringFeesOption; } set { this._AcquiringFeesOption = new(value); } } + + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenCommissionEnumJsonConverter))] + public class AdyenCommissionEnum : IEnum + { + /// + /// Returns the value of the AdyenCommissionEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenCommissionEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenCommissionEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenCommissionEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenCommissionEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenCommissionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenCommissionEnum?(string? value) => value == null ? null : new AdyenCommissionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenCommissionEnum? option) => option?.Value; + + public static bool operator ==(AdyenCommissionEnum? left, AdyenCommissionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenCommissionEnum? left, AdyenCommissionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenCommissionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenCommissionEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenCommissionEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenCommissionEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenCommissionEnum? value) + { + if (value == null) + return null; + + if (value == AdyenCommissionEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenCommissionEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenCommissionEnum. + /// + public class AdyenCommissionEnumJsonConverter : JsonConverter + { + public override AdyenCommissionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenCommissionEnum.FromStringOrDefault(value) ?? new AdyenCommissionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenCommissionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenCommissionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenCommissionOption { get; private set; } + + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenCommission")] + public AdyenCommissionEnum? AdyenCommission { get { return this._AdyenCommissionOption; } set { this._AdyenCommissionOption = new(value); } } + + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenFeesEnumJsonConverter))] + public class AdyenFeesEnum : IEnum + { + /// + /// Returns the value of the AdyenFeesEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenFeesEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenFeesEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenFeesEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenFeesEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenFeesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenFeesEnum?(string? value) => value == null ? null : new AdyenFeesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenFeesEnum? option) => option?.Value; + + public static bool operator ==(AdyenFeesEnum? left, AdyenFeesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenFeesEnum? left, AdyenFeesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenFeesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenFeesEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenFeesEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenFeesEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenFeesEnum? value) + { + if (value == null) + return null; + + if (value == AdyenFeesEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenFeesEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenFeesEnum. + /// + public class AdyenFeesEnumJsonConverter : JsonConverter + { + public override AdyenFeesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenFeesEnum.FromStringOrDefault(value) ?? new AdyenFeesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenFeesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenFeesEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenFeesOption { get; private set; } + + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the fees due to Adyen (markup or commission) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenFees")] + public AdyenFeesEnum? AdyenFees { get { return this._AdyenFeesOption; } set { this._AdyenFeesOption = new(value); } } + + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(AdyenMarkupEnumJsonConverter))] + public class AdyenMarkupEnum : IEnum + { + /// + /// Returns the value of the AdyenMarkupEnum. + /// + public string? Value { get; set; } + + /// + /// AdyenMarkupEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly AdyenMarkupEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// AdyenMarkupEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly AdyenMarkupEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private AdyenMarkupEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AdyenMarkupEnum?(string? value) => value == null ? null : new AdyenMarkupEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AdyenMarkupEnum? option) => option?.Value; + + public static bool operator ==(AdyenMarkupEnum? left, AdyenMarkupEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AdyenMarkupEnum? left, AdyenMarkupEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AdyenMarkupEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AdyenMarkupEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => AdyenMarkupEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => AdyenMarkupEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AdyenMarkupEnum? value) + { + if (value == null) + return null; + + if (value == AdyenMarkupEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == AdyenMarkupEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing AdyenMarkupEnum. + /// + public class AdyenMarkupEnumJsonConverter : JsonConverter + { + public override AdyenMarkupEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AdyenMarkupEnum.FromStringOrDefault(value) ?? new AdyenMarkupEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AdyenMarkupEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AdyenMarkupEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenMarkupOption { get; private set; } + + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/what-is-interchange) from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("adyenMarkup")] + public AdyenMarkupEnum? AdyenMarkup { get { return this._AdyenMarkupOption; } set { this._AdyenMarkupOption = new(value); } } + + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonConverter(typeof(ChargebackEnumJsonConverter))] + public class ChargebackEnum : IEnum + { + /// + /// Returns the value of the ChargebackEnum. + /// + public string? Value { get; set; } + + /// + /// ChargebackEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly ChargebackEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// ChargebackEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly ChargebackEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + /// + /// ChargebackEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly ChargebackEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + private ChargebackEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChargebackEnum?(string? value) => value == null ? null : new ChargebackEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChargebackEnum? option) => option?.Value; + + public static bool operator ==(ChargebackEnum? left, ChargebackEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChargebackEnum? left, ChargebackEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChargebackEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChargebackEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => ChargebackEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => ChargebackEnum.DeductFromOneBalanceAccount, + "deductAccordingToSplitRatio" => ChargebackEnum.DeductAccordingToSplitRatio, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChargebackEnum? value) + { + if (value == null) + return null; + + if (value == ChargebackEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == ChargebackEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + if (value == ChargebackEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + return null; + } + + /// + /// JsonConverter for writing ChargebackEnum. + /// + public class ChargebackEnumJsonConverter : JsonConverter + { + public override ChargebackEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChargebackEnum.FromStringOrDefault(value) ?? new ChargebackEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChargebackEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChargebackEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChargebackOption { get; private set; } + + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// Specifies how and from which balance account(s) to deduct the chargeback amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonPropertyName("chargeback")] + public ChargebackEnum? Chargeback { get { return this._ChargebackOption; } set { this._ChargebackOption = new(value); } } + + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonConverter(typeof(ChargebackCostAllocationEnumJsonConverter))] + public class ChargebackCostAllocationEnum : IEnum + { + /// + /// Returns the value of the ChargebackCostAllocationEnum. + /// + public string? Value { get; set; } + + /// + /// ChargebackCostAllocationEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly ChargebackCostAllocationEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// ChargebackCostAllocationEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly ChargebackCostAllocationEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private ChargebackCostAllocationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChargebackCostAllocationEnum?(string? value) => value == null ? null : new ChargebackCostAllocationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChargebackCostAllocationEnum? option) => option?.Value; + + public static bool operator ==(ChargebackCostAllocationEnum? left, ChargebackCostAllocationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChargebackCostAllocationEnum? left, ChargebackCostAllocationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChargebackCostAllocationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChargebackCostAllocationEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => ChargebackCostAllocationEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => ChargebackCostAllocationEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChargebackCostAllocationEnum? value) + { + if (value == null) + return null; + + if (value == ChargebackCostAllocationEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == ChargebackCostAllocationEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing ChargebackCostAllocationEnum. + /// + public class ChargebackCostAllocationEnumJsonConverter : JsonConverter + { + public override ChargebackCostAllocationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChargebackCostAllocationEnum.FromStringOrDefault(value) ?? new ChargebackCostAllocationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChargebackCostAllocationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChargebackCostAllocationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChargebackCostAllocationOption { get; private set; } + + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the chargeback costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonPropertyName("chargebackCostAllocation")] + public ChargebackCostAllocationEnum? ChargebackCostAllocation { get { return this._ChargebackCostAllocationOption; } set { this._ChargebackCostAllocationOption = new(value); } } + + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(InterchangeEnumJsonConverter))] + public class InterchangeEnum : IEnum + { + /// + /// Returns the value of the InterchangeEnum. + /// + public string? Value { get; set; } + + /// + /// InterchangeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly InterchangeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// InterchangeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly InterchangeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private InterchangeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator InterchangeEnum?(string? value) => value == null ? null : new InterchangeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(InterchangeEnum? option) => option?.Value; + + public static bool operator ==(InterchangeEnum? left, InterchangeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(InterchangeEnum? left, InterchangeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is InterchangeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static InterchangeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => InterchangeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => InterchangeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(InterchangeEnum? value) + { + if (value == null) + return null; + + if (value == InterchangeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == InterchangeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing InterchangeEnum. + /// + public class InterchangeEnumJsonConverter : JsonConverter + { + public override InterchangeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : InterchangeEnum.FromStringOrDefault(value) ?? new InterchangeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, InterchangeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(InterchangeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InterchangeOption { get; private set; } + + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the interchange fee from specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("interchange")] + public InterchangeEnum? Interchange { get { return this._InterchangeOption; } set { this._InterchangeOption = new(value); } } + + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(PaymentFeeEnumJsonConverter))] + public class PaymentFeeEnum : IEnum + { + /// + /// Returns the value of the PaymentFeeEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentFeeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly PaymentFeeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// PaymentFeeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly PaymentFeeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private PaymentFeeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentFeeEnum?(string? value) => value == null ? null : new PaymentFeeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentFeeEnum? option) => option?.Value; + + public static bool operator ==(PaymentFeeEnum? left, PaymentFeeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentFeeEnum? left, PaymentFeeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentFeeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentFeeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => PaymentFeeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => PaymentFeeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentFeeEnum? value) + { + if (value == null) + return null; + + if (value == PaymentFeeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == PaymentFeeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing PaymentFeeEnum. + /// + public class PaymentFeeEnumJsonConverter : JsonConverter + { + public override PaymentFeeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentFeeEnum.FromStringOrDefault(value) ?? new PaymentFeeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentFeeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentFeeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentFeeOption { get; private set; } + + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts all transaction fees incurred by the payment from the specified balance account. The transaction fees include the acquiring fees (interchange and scheme fee), and the fees due to Adyen (markup or commission). You can book any and all these fees to different balance account by specifying other transaction fee parameters in your split configuration profile: - [`adyenCommission`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenCommission): The transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`adyenMarkup`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenMarkup): The transaction fee due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained#interchange-vs-blended). - [`schemeFee`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-schemeFee): The fee paid to the card scheme for using their network. - [`interchange`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-interchange): The fee paid to the issuer for each payment transaction made with the card network. - [`adyenFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-adyenFees): The aggregated amount of Adyen's commission and markup. - [`acquiringFees`](https://docs.adyen.com/api-explorer/Management/latest/post/merchants/(merchantId)/splitConfigurations#request-rules-splitLogic-acquiringFees): The aggregated amount of the interchange and scheme fees. If you don't include at least one transaction fee type in the `splitLogic` object, Adyen updates the payment request with the `paymentFee` parameter, booking all transaction fees to your platform's liable balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("paymentFee")] + public PaymentFeeEnum? PaymentFee { get { return this._PaymentFeeOption; } set { this._PaymentFeeOption = new(value); } } + + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + [JsonConverter(typeof(RefundEnumJsonConverter))] + public class RefundEnum : IEnum + { + /// + /// Returns the value of the RefundEnum. + /// + public string? Value { get; set; } + + /// + /// RefundEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly RefundEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// RefundEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly RefundEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + /// + /// RefundEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly RefundEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + private RefundEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RefundEnum?(string? value) => value == null ? null : new RefundEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RefundEnum? option) => option?.Value; + + public static bool operator ==(RefundEnum? left, RefundEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RefundEnum? left, RefundEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RefundEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RefundEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => RefundEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => RefundEnum.DeductFromOneBalanceAccount, + "deductAccordingToSplitRatio" => RefundEnum.DeductAccordingToSplitRatio, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RefundEnum? value) + { + if (value == null) + return null; + + if (value == RefundEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == RefundEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + if (value == RefundEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + return null; + } + + /// + /// JsonConverter for writing RefundEnum. + /// + public class RefundEnumJsonConverter : JsonConverter + { + public override RefundEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RefundEnum.FromStringOrDefault(value) ?? new RefundEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RefundEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RefundEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundOption { get; private set; } + + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + /// + /// Specifies how and from which balance account(s) to deduct the refund amount. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio** + [JsonPropertyName("refund")] + public RefundEnum? Refund { get { return this._RefundOption; } set { this._RefundOption = new(value); } } + + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonConverter(typeof(RefundCostAllocationEnumJsonConverter))] + public class RefundCostAllocationEnum : IEnum + { + /// + /// Returns the value of the RefundCostAllocationEnum. + /// + public string? Value { get; set; } + + /// + /// RefundCostAllocationEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly RefundCostAllocationEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// RefundCostAllocationEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly RefundCostAllocationEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private RefundCostAllocationEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RefundCostAllocationEnum?(string? value) => value == null ? null : new RefundCostAllocationEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RefundCostAllocationEnum? option) => option?.Value; + + public static bool operator ==(RefundCostAllocationEnum? left, RefundCostAllocationEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RefundCostAllocationEnum? left, RefundCostAllocationEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RefundCostAllocationEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RefundCostAllocationEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => RefundCostAllocationEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => RefundCostAllocationEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RefundCostAllocationEnum? value) + { + if (value == null) + return null; + + if (value == RefundCostAllocationEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == RefundCostAllocationEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing RefundCostAllocationEnum. + /// + public class RefundCostAllocationEnumJsonConverter : JsonConverter + { + public override RefundCostAllocationEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RefundCostAllocationEnum.FromStringOrDefault(value) ?? new RefundCostAllocationEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RefundCostAllocationEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RefundCostAllocationEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefundCostAllocationOption { get; private set; } + + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + /// + /// Deducts the refund costs from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount** + [JsonPropertyName("refundCostAllocation")] + public RefundCostAllocationEnum? RefundCostAllocation { get { return this._RefundCostAllocationOption; } set { this._RefundCostAllocationOption = new(value); } } + + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConverter(typeof(RemainderEnumJsonConverter))] + public class RemainderEnum : IEnum + { + /// + /// Returns the value of the RemainderEnum. + /// + public string? Value { get; set; } + + /// + /// RemainderEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly RemainderEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// RemainderEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly RemainderEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private RemainderEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RemainderEnum?(string? value) => value == null ? null : new RemainderEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RemainderEnum? option) => option?.Value; + + public static bool operator ==(RemainderEnum? left, RemainderEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RemainderEnum? left, RemainderEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RemainderEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RemainderEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => RemainderEnum.AddToLiableAccount, + "addToOneBalanceAccount" => RemainderEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RemainderEnum? value) + { + if (value == null) + return null; + + if (value == RemainderEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == RemainderEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing RemainderEnum. + /// + public class RemainderEnumJsonConverter : JsonConverter + { + public override RemainderEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RemainderEnum.FromStringOrDefault(value) ?? new RemainderEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RemainderEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RemainderEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RemainderOption { get; private set; } + + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the amount left over after currency conversion to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonPropertyName("remainder")] + public RemainderEnum? Remainder { get { return this._RemainderOption; } set { this._RemainderOption = new(value); } } + + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonConverter(typeof(SchemeFeeEnumJsonConverter))] + public class SchemeFeeEnum : IEnum + { + /// + /// Returns the value of the SchemeFeeEnum. + /// + public string? Value { get; set; } + + /// + /// SchemeFeeEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly SchemeFeeEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// SchemeFeeEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly SchemeFeeEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private SchemeFeeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SchemeFeeEnum?(string? value) => value == null ? null : new SchemeFeeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SchemeFeeEnum? option) => option?.Value; + + public static bool operator ==(SchemeFeeEnum? left, SchemeFeeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SchemeFeeEnum? left, SchemeFeeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SchemeFeeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SchemeFeeEnum? FromStringOrDefault(string value) + { + return value switch { + "deductFromLiableAccount" => SchemeFeeEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => SchemeFeeEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SchemeFeeEnum? value) + { + if (value == null) + return null; + + if (value == SchemeFeeEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == SchemeFeeEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing SchemeFeeEnum. + /// + public class SchemeFeeEnumJsonConverter : JsonConverter + { + public override SchemeFeeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SchemeFeeEnum.FromStringOrDefault(value) ?? new SchemeFeeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SchemeFeeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SchemeFeeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeFeeOption { get; private set; } + + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + /// + /// Deducts the scheme fee from the specified balance account. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**. + [JsonPropertyName("schemeFee")] + public SchemeFeeEnum? SchemeFee { get { return this._SchemeFeeOption; } set { this._SchemeFeeOption = new(value); } } + + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + [JsonConverter(typeof(SurchargeEnumJsonConverter))] + public class SurchargeEnum : IEnum + { + /// + /// Returns the value of the SurchargeEnum. + /// + public string? Value { get; set; } + + /// + /// SurchargeEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly SurchargeEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// SurchargeEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly SurchargeEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private SurchargeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SurchargeEnum?(string? value) => value == null ? null : new SurchargeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SurchargeEnum? option) => option?.Value; + + public static bool operator ==(SurchargeEnum? left, SurchargeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SurchargeEnum? left, SurchargeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SurchargeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SurchargeEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => SurchargeEnum.AddToLiableAccount, + "addToOneBalanceAccount" => SurchargeEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SurchargeEnum? value) + { + if (value == null) + return null; + + if (value == SurchargeEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == SurchargeEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing SurchargeEnum. + /// + public class SurchargeEnumJsonConverter : JsonConverter + { + public override SurchargeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SurchargeEnum.FromStringOrDefault(value) ?? new SurchargeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SurchargeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SurchargeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SurchargeOption { get; private set; } + + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + /// + /// Books the surcharge amount to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount** + [JsonPropertyName("surcharge")] + public SurchargeEnum? Surcharge { get { return this._SurchargeOption; } set { this._SurchargeOption = new(value); } } + + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonConverter(typeof(TipEnumJsonConverter))] + public class TipEnum : IEnum + { + /// + /// Returns the value of the TipEnum. + /// + public string? Value { get; set; } + + /// + /// TipEnum.AddToLiableAccount - addToLiableAccount + /// + public static readonly TipEnum AddToLiableAccount = new("addToLiableAccount"); + + /// + /// TipEnum.AddToOneBalanceAccount - addToOneBalanceAccount + /// + public static readonly TipEnum AddToOneBalanceAccount = new("addToOneBalanceAccount"); + + private TipEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TipEnum?(string? value) => value == null ? null : new TipEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TipEnum? option) => option?.Value; + + public static bool operator ==(TipEnum? left, TipEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TipEnum? left, TipEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TipEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TipEnum? FromStringOrDefault(string value) + { + return value switch { + "addToLiableAccount" => TipEnum.AddToLiableAccount, + "addToOneBalanceAccount" => TipEnum.AddToOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TipEnum? value) + { + if (value == null) + return null; + + if (value == TipEnum.AddToLiableAccount) + return "addToLiableAccount"; + + if (value == TipEnum.AddToOneBalanceAccount) + return "addToOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing TipEnum. + /// + public class TipEnumJsonConverter : JsonConverter + { + public override TipEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TipEnum.FromStringOrDefault(value) ?? new TipEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TipEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TipEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TipOption { get; private set; } + + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + /// + /// Books the tips (gratuity) to the specified balance account. Possible values: **addToLiableAccount**, **addToOneBalanceAccount**. + [JsonPropertyName("tip")] + public TipEnum? Tip { get { return this._TipOption; } set { this._TipOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("commission")] + public Commission Commission { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalCommissionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalCommission")] + public AdditionalCommission? AdditionalCommission { get { return this._AdditionalCommissionOption; } set { this._AdditionalCommissionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitLogicIdOption { get; } + + /// + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + /// + /// Unique identifier of the collection of split instructions that are applied when the rule conditions are met. + [JsonPropertyName("splitLogicId")] + public string? SplitLogicId { get { return this._SplitLogicIdOption; } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateSplitConfigurationLogicRequest {\n"); + sb.Append(" Commission: ").Append(Commission).Append("\n"); + sb.Append(" AcquiringFees: ").Append(AcquiringFees).Append("\n"); + sb.Append(" AdditionalCommission: ").Append(AdditionalCommission).Append("\n"); + sb.Append(" AdyenCommission: ").Append(AdyenCommission).Append("\n"); + sb.Append(" AdyenFees: ").Append(AdyenFees).Append("\n"); + sb.Append(" AdyenMarkup: ").Append(AdyenMarkup).Append("\n"); + sb.Append(" Chargeback: ").Append(Chargeback).Append("\n"); + sb.Append(" ChargebackCostAllocation: ").Append(ChargebackCostAllocation).Append("\n"); + sb.Append(" Interchange: ").Append(Interchange).Append("\n"); + sb.Append(" PaymentFee: ").Append(PaymentFee).Append("\n"); + sb.Append(" Refund: ").Append(Refund).Append("\n"); + sb.Append(" RefundCostAllocation: ").Append(RefundCostAllocation).Append("\n"); + sb.Append(" Remainder: ").Append(Remainder).Append("\n"); + sb.Append(" SchemeFee: ").Append(SchemeFee).Append("\n"); + sb.Append(" SplitLogicId: ").Append(SplitLogicId).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" Tip: ").Append(Tip).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateSplitConfigurationLogicRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateSplitConfigurationLogicRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option commission = default; + Option acquiringFees = default; + Option additionalCommission = default; + Option adyenCommission = default; + Option adyenFees = default; + Option adyenMarkup = default; + Option chargeback = default; + Option chargebackCostAllocation = default; + Option interchange = default; + Option paymentFee = default; + Option refund = default; + Option refundCostAllocation = default; + Option remainder = default; + Option schemeFee = default; + Option splitLogicId = default; + Option surcharge = default; + Option tip = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "commission": + commission = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acquiringFees": + string? acquiringFeesRawValue = utf8JsonReader.GetString(); + acquiringFees = new Option(UpdateSplitConfigurationLogicRequest.AcquiringFeesEnum.FromStringOrDefault(acquiringFeesRawValue)); + break; + case "additionalCommission": + additionalCommission = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "adyenCommission": + string? adyenCommissionRawValue = utf8JsonReader.GetString(); + adyenCommission = new Option(UpdateSplitConfigurationLogicRequest.AdyenCommissionEnum.FromStringOrDefault(adyenCommissionRawValue)); + break; + case "adyenFees": + string? adyenFeesRawValue = utf8JsonReader.GetString(); + adyenFees = new Option(UpdateSplitConfigurationLogicRequest.AdyenFeesEnum.FromStringOrDefault(adyenFeesRawValue)); + break; + case "adyenMarkup": + string? adyenMarkupRawValue = utf8JsonReader.GetString(); + adyenMarkup = new Option(UpdateSplitConfigurationLogicRequest.AdyenMarkupEnum.FromStringOrDefault(adyenMarkupRawValue)); + break; + case "chargeback": + string? chargebackRawValue = utf8JsonReader.GetString(); + chargeback = new Option(UpdateSplitConfigurationLogicRequest.ChargebackEnum.FromStringOrDefault(chargebackRawValue)); + break; + case "chargebackCostAllocation": + string? chargebackCostAllocationRawValue = utf8JsonReader.GetString(); + chargebackCostAllocation = new Option(UpdateSplitConfigurationLogicRequest.ChargebackCostAllocationEnum.FromStringOrDefault(chargebackCostAllocationRawValue)); + break; + case "interchange": + string? interchangeRawValue = utf8JsonReader.GetString(); + interchange = new Option(UpdateSplitConfigurationLogicRequest.InterchangeEnum.FromStringOrDefault(interchangeRawValue)); + break; + case "paymentFee": + string? paymentFeeRawValue = utf8JsonReader.GetString(); + paymentFee = new Option(UpdateSplitConfigurationLogicRequest.PaymentFeeEnum.FromStringOrDefault(paymentFeeRawValue)); + break; + case "refund": + string? refundRawValue = utf8JsonReader.GetString(); + refund = new Option(UpdateSplitConfigurationLogicRequest.RefundEnum.FromStringOrDefault(refundRawValue)); + break; + case "refundCostAllocation": + string? refundCostAllocationRawValue = utf8JsonReader.GetString(); + refundCostAllocation = new Option(UpdateSplitConfigurationLogicRequest.RefundCostAllocationEnum.FromStringOrDefault(refundCostAllocationRawValue)); + break; + case "remainder": + string? remainderRawValue = utf8JsonReader.GetString(); + remainder = new Option(UpdateSplitConfigurationLogicRequest.RemainderEnum.FromStringOrDefault(remainderRawValue)); + break; + case "schemeFee": + string? schemeFeeRawValue = utf8JsonReader.GetString(); + schemeFee = new Option(UpdateSplitConfigurationLogicRequest.SchemeFeeEnum.FromStringOrDefault(schemeFeeRawValue)); + break; + case "splitLogicId": + splitLogicId = new Option(utf8JsonReader.GetString()!); + break; + case "surcharge": + string? surchargeRawValue = utf8JsonReader.GetString(); + surcharge = new Option(UpdateSplitConfigurationLogicRequest.SurchargeEnum.FromStringOrDefault(surchargeRawValue)); + break; + case "tip": + string? tipRawValue = utf8JsonReader.GetString(); + tip = new Option(UpdateSplitConfigurationLogicRequest.TipEnum.FromStringOrDefault(tipRawValue)); + break; + default: + break; + } + } + } + + if (!commission.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationLogicRequest.", nameof(commission)); + + return new UpdateSplitConfigurationLogicRequest(commission.Value!, acquiringFees, additionalCommission, adyenCommission, adyenFees, adyenMarkup, chargeback, chargebackCostAllocation, interchange, paymentFee, refund, refundCostAllocation, remainder, schemeFee, splitLogicId, surcharge, tip); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateSplitConfigurationLogicRequest updateSplitConfigurationLogicRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateSplitConfigurationLogicRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateSplitConfigurationLogicRequest updateSplitConfigurationLogicRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("commission"); + JsonSerializer.Serialize(writer, updateSplitConfigurationLogicRequest.Commission, jsonSerializerOptions); + if (updateSplitConfigurationLogicRequest._AcquiringFeesOption.IsSet && updateSplitConfigurationLogicRequest.AcquiringFees != null) + { + string? acquiringFeesRawValue = UpdateSplitConfigurationLogicRequest.AcquiringFeesEnum.ToJsonValue(updateSplitConfigurationLogicRequest._AcquiringFeesOption.Value!.Value); + writer.WriteString("acquiringFees", acquiringFeesRawValue); + } + + if (updateSplitConfigurationLogicRequest._AdditionalCommissionOption.IsSet) + { + writer.WritePropertyName("additionalCommission"); + JsonSerializer.Serialize(writer, updateSplitConfigurationLogicRequest.AdditionalCommission, jsonSerializerOptions); + } + if (updateSplitConfigurationLogicRequest._AdyenCommissionOption.IsSet && updateSplitConfigurationLogicRequest.AdyenCommission != null) + { + string? adyenCommissionRawValue = UpdateSplitConfigurationLogicRequest.AdyenCommissionEnum.ToJsonValue(updateSplitConfigurationLogicRequest._AdyenCommissionOption.Value!.Value); + writer.WriteString("adyenCommission", adyenCommissionRawValue); + } + + if (updateSplitConfigurationLogicRequest._AdyenFeesOption.IsSet && updateSplitConfigurationLogicRequest.AdyenFees != null) + { + string? adyenFeesRawValue = UpdateSplitConfigurationLogicRequest.AdyenFeesEnum.ToJsonValue(updateSplitConfigurationLogicRequest._AdyenFeesOption.Value!.Value); + writer.WriteString("adyenFees", adyenFeesRawValue); + } + + if (updateSplitConfigurationLogicRequest._AdyenMarkupOption.IsSet && updateSplitConfigurationLogicRequest.AdyenMarkup != null) + { + string? adyenMarkupRawValue = UpdateSplitConfigurationLogicRequest.AdyenMarkupEnum.ToJsonValue(updateSplitConfigurationLogicRequest._AdyenMarkupOption.Value!.Value); + writer.WriteString("adyenMarkup", adyenMarkupRawValue); + } + + if (updateSplitConfigurationLogicRequest._ChargebackOption.IsSet && updateSplitConfigurationLogicRequest.Chargeback != null) + { + string? chargebackRawValue = UpdateSplitConfigurationLogicRequest.ChargebackEnum.ToJsonValue(updateSplitConfigurationLogicRequest._ChargebackOption.Value!.Value); + writer.WriteString("chargeback", chargebackRawValue); + } + + if (updateSplitConfigurationLogicRequest._ChargebackCostAllocationOption.IsSet && updateSplitConfigurationLogicRequest.ChargebackCostAllocation != null) + { + string? chargebackCostAllocationRawValue = UpdateSplitConfigurationLogicRequest.ChargebackCostAllocationEnum.ToJsonValue(updateSplitConfigurationLogicRequest._ChargebackCostAllocationOption.Value!.Value); + writer.WriteString("chargebackCostAllocation", chargebackCostAllocationRawValue); + } + + if (updateSplitConfigurationLogicRequest._InterchangeOption.IsSet && updateSplitConfigurationLogicRequest.Interchange != null) + { + string? interchangeRawValue = UpdateSplitConfigurationLogicRequest.InterchangeEnum.ToJsonValue(updateSplitConfigurationLogicRequest._InterchangeOption.Value!.Value); + writer.WriteString("interchange", interchangeRawValue); + } + + if (updateSplitConfigurationLogicRequest._PaymentFeeOption.IsSet && updateSplitConfigurationLogicRequest.PaymentFee != null) + { + string? paymentFeeRawValue = UpdateSplitConfigurationLogicRequest.PaymentFeeEnum.ToJsonValue(updateSplitConfigurationLogicRequest._PaymentFeeOption.Value!.Value); + writer.WriteString("paymentFee", paymentFeeRawValue); + } + + if (updateSplitConfigurationLogicRequest._RefundOption.IsSet && updateSplitConfigurationLogicRequest.Refund != null) + { + string? refundRawValue = UpdateSplitConfigurationLogicRequest.RefundEnum.ToJsonValue(updateSplitConfigurationLogicRequest._RefundOption.Value!.Value); + writer.WriteString("refund", refundRawValue); + } + + if (updateSplitConfigurationLogicRequest._RefundCostAllocationOption.IsSet && updateSplitConfigurationLogicRequest.RefundCostAllocation != null) + { + string? refundCostAllocationRawValue = UpdateSplitConfigurationLogicRequest.RefundCostAllocationEnum.ToJsonValue(updateSplitConfigurationLogicRequest._RefundCostAllocationOption.Value!.Value); + writer.WriteString("refundCostAllocation", refundCostAllocationRawValue); + } + + if (updateSplitConfigurationLogicRequest._RemainderOption.IsSet && updateSplitConfigurationLogicRequest.Remainder != null) + { + string? remainderRawValue = UpdateSplitConfigurationLogicRequest.RemainderEnum.ToJsonValue(updateSplitConfigurationLogicRequest._RemainderOption.Value!.Value); + writer.WriteString("remainder", remainderRawValue); + } + + if (updateSplitConfigurationLogicRequest._SchemeFeeOption.IsSet && updateSplitConfigurationLogicRequest.SchemeFee != null) + { + string? schemeFeeRawValue = UpdateSplitConfigurationLogicRequest.SchemeFeeEnum.ToJsonValue(updateSplitConfigurationLogicRequest._SchemeFeeOption.Value!.Value); + writer.WriteString("schemeFee", schemeFeeRawValue); + } + + if (updateSplitConfigurationLogicRequest._SplitLogicIdOption.IsSet) + if (updateSplitConfigurationLogicRequest.SplitLogicId != null) + writer.WriteString("splitLogicId", updateSplitConfigurationLogicRequest.SplitLogicId); + + if (updateSplitConfigurationLogicRequest._SurchargeOption.IsSet && updateSplitConfigurationLogicRequest.Surcharge != null) + { + string? surchargeRawValue = UpdateSplitConfigurationLogicRequest.SurchargeEnum.ToJsonValue(updateSplitConfigurationLogicRequest._SurchargeOption.Value!.Value); + writer.WriteString("surcharge", surchargeRawValue); + } + + if (updateSplitConfigurationLogicRequest._TipOption.IsSet && updateSplitConfigurationLogicRequest.Tip != null) + { + string? tipRawValue = UpdateSplitConfigurationLogicRequest.TipEnum.ToJsonValue(updateSplitConfigurationLogicRequest._TipOption.Value!.Value); + writer.WriteString("tip", tipRawValue); + } + } + } +} diff --git a/Adyen/Management/Models/UpdateSplitConfigurationRequest.cs b/Adyen/Management/Models/UpdateSplitConfigurationRequest.cs new file mode 100644 index 000000000..9bdad01db --- /dev/null +++ b/Adyen/Management/Models/UpdateSplitConfigurationRequest.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateSplitConfigurationRequest. + /// + public partial class UpdateSplitConfigurationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Your description for the split configuration. + [JsonConstructor] + public UpdateSplitConfigurationRequest(string description) + { + Description = description; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateSplitConfigurationRequest() + { + } + + partial void OnCreated(); + + /// + /// Your description for the split configuration. + /// + /// Your description for the split configuration. + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateSplitConfigurationRequest {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 300) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 300.", new [] { "Description" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateSplitConfigurationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateSplitConfigurationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!description.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationRequest.", nameof(description)); + + return new UpdateSplitConfigurationRequest(description.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateSplitConfigurationRequest updateSplitConfigurationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateSplitConfigurationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateSplitConfigurationRequest updateSplitConfigurationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateSplitConfigurationRequest.Description != null) + writer.WriteString("description", updateSplitConfigurationRequest.Description); + } + } +} diff --git a/Adyen/Management/Models/UpdateSplitConfigurationRuleRequest.cs b/Adyen/Management/Models/UpdateSplitConfigurationRuleRequest.cs new file mode 100644 index 000000000..c1fdcd718 --- /dev/null +++ b/Adyen/Management/Models/UpdateSplitConfigurationRuleRequest.cs @@ -0,0 +1,231 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateSplitConfigurationRuleRequest. + /// + public partial class UpdateSplitConfigurationRuleRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + [JsonConstructor] + public UpdateSplitConfigurationRuleRequest(string currency, string fundingSource, string paymentMethod, string shopperInteraction) + { + Currency = currency; + FundingSource = fundingSource; + PaymentMethod = paymentMethod; + ShopperInteraction = shopperInteraction; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateSplitConfigurationRuleRequest() + { + } + + partial void OnCreated(); + + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The currency condition that defines whether the split logic applies. Its value must be a three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + /// + /// The funding source of the payment method. Possible values: * **credit** * **debit** * **prepaid** * **deferred_debit** * **charged** * **ANY** + [JsonPropertyName("fundingSource")] + public string FundingSource { get; set; } + + /// + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + /// + /// The payment method condition that defines whether the split logic applies. Possible values: * [Payment method variant](https://docs.adyen.com/development-resources/paymentmethodvariant): Apply the split logic for a specific payment method. * **ANY**: Apply the split logic for all available payment methods. + [JsonPropertyName("paymentMethod")] + public string PaymentMethod { get; set; } + + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + /// + /// The sales channel condition that defines whether the split logic applies. Possible values: * **Ecommerce**: online transactions where the cardholder is present. * **ContAuth**: card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). * **Moto**: mail-order and telephone-order transactions where the customer is in contact with the merchant via email or telephone. * **POS**: point-of-sale transactions where the customer is physically present to make a payment using a secure payment terminal. * **ANY**: all sales channels. + [JsonPropertyName("shopperInteraction")] + public string ShopperInteraction { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateSplitConfigurationRuleRequest {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateSplitConfigurationRuleRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateSplitConfigurationRuleRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option fundingSource = default; + Option paymentMethod = default; + Option shopperInteraction = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + shopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationRuleRequest.", nameof(currency)); + + if (!fundingSource.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationRuleRequest.", nameof(fundingSource)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationRuleRequest.", nameof(paymentMethod)); + + if (!shopperInteraction.IsSet) + throw new ArgumentException("Property is required for class UpdateSplitConfigurationRuleRequest.", nameof(shopperInteraction)); + + return new UpdateSplitConfigurationRuleRequest(currency.Value!, fundingSource.Value!, paymentMethod.Value!, shopperInteraction.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateSplitConfigurationRuleRequest updateSplitConfigurationRuleRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateSplitConfigurationRuleRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateSplitConfigurationRuleRequest updateSplitConfigurationRuleRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateSplitConfigurationRuleRequest.Currency != null) + writer.WriteString("currency", updateSplitConfigurationRuleRequest.Currency); + + if (updateSplitConfigurationRuleRequest.FundingSource != null) + writer.WriteString("fundingSource", updateSplitConfigurationRuleRequest.FundingSource); + + if (updateSplitConfigurationRuleRequest.PaymentMethod != null) + writer.WriteString("paymentMethod", updateSplitConfigurationRuleRequest.PaymentMethod); + + if (updateSplitConfigurationRuleRequest.ShopperInteraction != null) + writer.WriteString("shopperInteraction", updateSplitConfigurationRuleRequest.ShopperInteraction); + } + } +} diff --git a/Adyen/Management/Models/UpdateStoreRequest.cs b/Adyen/Management/Models/UpdateStoreRequest.cs new file mode 100644 index 000000000..a23e328cb --- /dev/null +++ b/Adyen/Management/Models/UpdateStoreRequest.cs @@ -0,0 +1,469 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UpdateStoreRequest. + /// + public partial class UpdateStoreRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines__resParam_id) that the store is associated with. + /// The description of the store. + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// splitConfiguration + /// The status of the store. Possible values are: - **active**: This value is assigned automatically when a store is created. - **inactive**: The maximum [transaction limits and number of Store-and-Forward transactions](https://docs.adyen.com/point-of-sale/determine-account-structure/configure-features#payment-features) for the store are set to 0. This blocks new transactions, but captures are still possible. - **closed**: The terminals of the store are reassigned to the merchant inventory, so they can't process payments. You can change the status from **active** to **inactive**, and from **inactive** to **active** or **closed**. Once **closed**, a store can't be reopened. + /// subMerchantData + [JsonConstructor] + public UpdateStoreRequest(Option address = default, Option?> businessLineIds = default, Option description = default, Option externalReferenceId = default, Option phoneNumber = default, Option splitConfiguration = default, Option status = default, Option subMerchantData = default) + { + _AddressOption = address; + _BusinessLineIdsOption = businessLineIds; + _DescriptionOption = description; + _ExternalReferenceIdOption = externalReferenceId; + _PhoneNumberOption = phoneNumber; + _SplitConfigurationOption = splitConfiguration; + _StatusOption = status; + _SubMerchantDataOption = subMerchantData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UpdateStoreRequest() + { + } + + partial void OnCreated(); + + /// + /// The status of the store. Possible values are: - **active**: This value is assigned automatically when a store is created. - **inactive**: The maximum [transaction limits and number of Store-and-Forward transactions](https://docs.adyen.com/point-of-sale/determine-account-structure/configure-features#payment-features) for the store are set to 0. This blocks new transactions, but captures are still possible. - **closed**: The terminals of the store are reassigned to the merchant inventory, so they can't process payments. You can change the status from **active** to **inactive**, and from **inactive** to **active** or **closed**. Once **closed**, a store can't be reopened. + /// + /// The status of the store. Possible values are: - **active**: This value is assigned automatically when a store is created. - **inactive**: The maximum [transaction limits and number of Store-and-Forward transactions](https://docs.adyen.com/point-of-sale/determine-account-structure/configure-features#payment-features) for the store are set to 0. This blocks new transactions, but captures are still possible. - **closed**: The terminals of the store are reassigned to the merchant inventory, so they can't process payments. You can change the status from **active** to **inactive**, and from **inactive** to **active** or **closed**. Once **closed**, a store can't be reopened. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Closed - closed + /// + public static readonly StatusEnum Closed = new("closed"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "closed" => StatusEnum.Closed, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Closed) + return "closed"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the store. Possible values are: - **active**: This value is assigned automatically when a store is created. - **inactive**: The maximum [transaction limits and number of Store-and-Forward transactions](https://docs.adyen.com/point-of-sale/determine-account-structure/configure-features#payment-features) for the store are set to 0. This blocks new transactions, but captures are still possible. - **closed**: The terminals of the store are reassigned to the merchant inventory, so they can't process payments. You can change the status from **active** to **inactive**, and from **inactive** to **active** or **closed**. Once **closed**, a store can't be reopened. + /// + /// The status of the store. Possible values are: - **active**: This value is assigned automatically when a store is created. - **inactive**: The maximum [transaction limits and number of Store-and-Forward transactions](https://docs.adyen.com/point-of-sale/determine-account-structure/configure-features#payment-features) for the store are set to 0. This blocks new transactions, but captures are still possible. - **closed**: The terminals of the store are reassigned to the merchant inventory, so they can't process payments. You can change the status from **active** to **inactive**, and from **inactive** to **active** or **closed**. Once **closed**, a store can't be reopened. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public UpdatableAddress? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BusinessLineIdsOption { get; private set; } + + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines__resParam_id) that the store is associated with. + /// + /// The unique identifiers of the [business lines](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/businessLines__resParam_id) that the store is associated with. + [JsonPropertyName("businessLineIds")] + public List? BusinessLineIds { get { return this._BusinessLineIdsOption; } set { this._BusinessLineIdsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the store. + /// + /// The description of the store. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReferenceIdOption { get; private set; } + + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + /// + /// The unique identifier of the store, used by certain payment methods and tax authorities. Required for CNPJ in Brazil, in the format 00.000.000/0000-00 separated by dots, slashes, hyphens, or without separators. Optional for SIRET in France, up to 14 digits. Optional for Zip in Australia, up to 50 digits. + [JsonPropertyName("externalReferenceId")] + public string? ExternalReferenceId { get { return this._ExternalReferenceIdOption; } set { this._ExternalReferenceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PhoneNumberOption { get; private set; } + + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + /// + /// The phone number of the store, including '+' and country code in the [E.164](https://en.wikipedia.org/wiki/E.164) format. If passed in a different format, we convert and validate the phone number against E.164. + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get { return this._PhoneNumberOption; } set { this._PhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SplitConfigurationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("splitConfiguration")] + public StoreSplitConfiguration? SplitConfiguration { get { return this._SplitConfigurationOption; } set { this._SplitConfigurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchantData")] + public SubMerchantData? SubMerchantData { get { return this._SubMerchantDataOption; } set { this._SubMerchantDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UpdateStoreRequest {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" BusinessLineIds: ").Append(BusinessLineIds).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExternalReferenceId: ").Append(ExternalReferenceId).Append("\n"); + sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); + sb.Append(" SplitConfiguration: ").Append(SplitConfiguration).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" SubMerchantData: ").Append(SubMerchantData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UpdateStoreRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UpdateStoreRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option?> businessLineIds = default; + Option description = default; + Option externalReferenceId = default; + Option phoneNumber = default; + Option splitConfiguration = default; + Option status = default; + Option subMerchantData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "businessLineIds": + businessLineIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "externalReferenceId": + externalReferenceId = new Option(utf8JsonReader.GetString()!); + break; + case "phoneNumber": + phoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splitConfiguration": + splitConfiguration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(UpdateStoreRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "subMerchantData": + subMerchantData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new UpdateStoreRequest(address, businessLineIds, description, externalReferenceId, phoneNumber, splitConfiguration, status, subMerchantData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UpdateStoreRequest updateStoreRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, updateStoreRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UpdateStoreRequest updateStoreRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (updateStoreRequest._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, updateStoreRequest.Address, jsonSerializerOptions); + } + if (updateStoreRequest._BusinessLineIdsOption.IsSet) + { + writer.WritePropertyName("businessLineIds"); + JsonSerializer.Serialize(writer, updateStoreRequest.BusinessLineIds, jsonSerializerOptions); + } + if (updateStoreRequest._DescriptionOption.IsSet) + if (updateStoreRequest.Description != null) + writer.WriteString("description", updateStoreRequest.Description); + + if (updateStoreRequest._ExternalReferenceIdOption.IsSet) + if (updateStoreRequest.ExternalReferenceId != null) + writer.WriteString("externalReferenceId", updateStoreRequest.ExternalReferenceId); + + if (updateStoreRequest._PhoneNumberOption.IsSet) + if (updateStoreRequest.PhoneNumber != null) + writer.WriteString("phoneNumber", updateStoreRequest.PhoneNumber); + + if (updateStoreRequest._SplitConfigurationOption.IsSet) + { + writer.WritePropertyName("splitConfiguration"); + JsonSerializer.Serialize(writer, updateStoreRequest.SplitConfiguration, jsonSerializerOptions); + } + if (updateStoreRequest._StatusOption.IsSet && updateStoreRequest.Status != null) + { + string? statusRawValue = UpdateStoreRequest.StatusEnum.ToJsonValue(updateStoreRequest._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (updateStoreRequest._SubMerchantDataOption.IsSet) + { + writer.WritePropertyName("subMerchantData"); + JsonSerializer.Serialize(writer, updateStoreRequest.SubMerchantData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/UploadAndroidAppResponse.cs b/Adyen/Management/Models/UploadAndroidAppResponse.cs new file mode 100644 index 000000000..21968bc51 --- /dev/null +++ b/Adyen/Management/Models/UploadAndroidAppResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UploadAndroidAppResponse. + /// + public partial class UploadAndroidAppResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the uploaded Android app. + [JsonConstructor] + public UploadAndroidAppResponse(Option id = default) + { + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UploadAndroidAppResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the uploaded Android app. + /// + /// The unique identifier of the uploaded Android app. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UploadAndroidAppResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UploadAndroidAppResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UploadAndroidAppResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UploadAndroidAppResponse(id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UploadAndroidAppResponse uploadAndroidAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uploadAndroidAppResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UploadAndroidAppResponse uploadAndroidAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (uploadAndroidAppResponse._IdOption.IsSet) + if (uploadAndroidAppResponse.Id != null) + writer.WriteString("id", uploadAndroidAppResponse.Id); + } + } +} diff --git a/Adyen/Management/Models/UploadAndroidCertificateResponse.cs b/Adyen/Management/Models/UploadAndroidCertificateResponse.cs new file mode 100644 index 000000000..c4ab3033f --- /dev/null +++ b/Adyen/Management/Models/UploadAndroidCertificateResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// UploadAndroidCertificateResponse. + /// + public partial class UploadAndroidCertificateResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the uploaded Android certificate. + [JsonConstructor] + public UploadAndroidCertificateResponse(Option id = default) + { + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UploadAndroidCertificateResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the uploaded Android certificate. + /// + /// The unique identifier of the uploaded Android certificate. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UploadAndroidCertificateResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UploadAndroidCertificateResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UploadAndroidCertificateResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UploadAndroidCertificateResponse(id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UploadAndroidCertificateResponse uploadAndroidCertificateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uploadAndroidCertificateResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UploadAndroidCertificateResponse uploadAndroidCertificateResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (uploadAndroidCertificateResponse._IdOption.IsSet) + if (uploadAndroidCertificateResponse.Id != null) + writer.WriteString("id", uploadAndroidCertificateResponse.Id); + } + } +} diff --git a/Adyen/Management/Models/Url.cs b/Adyen/Management/Models/Url.cs new file mode 100644 index 000000000..524bbb6da --- /dev/null +++ b/Adyen/Management/Models/Url.cs @@ -0,0 +1,251 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Url. + /// + public partial class Url : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the message sent to this URL should be encrypted. + /// The password for authentication of the notifications. + /// The URL in the format: http(s)://domain.com. + /// The username for authentication of the notifications. + [JsonConstructor] + public Url(Option encrypted = default, Option password = default, Option varUrl = default, Option username = default) + { + _EncryptedOption = encrypted; + _PasswordOption = password; + _VarUrlOption = varUrl; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Url() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptedOption { get; private set; } + + /// + /// Indicates if the message sent to this URL should be encrypted. + /// + /// Indicates if the message sent to this URL should be encrypted. + [JsonPropertyName("encrypted")] + public bool? Encrypted { get { return this._EncryptedOption; } set { this._EncryptedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordOption { get; private set; } + + /// + /// The password for authentication of the notifications. + /// + /// The password for authentication of the notifications. + [JsonPropertyName("password")] + public string? Password { get { return this._PasswordOption; } set { this._PasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VarUrlOption { get; private set; } + + /// + /// The URL in the format: http(s)://domain.com. + /// + /// The URL in the format: http(s)://domain.com. + [JsonPropertyName("url")] + public string? VarUrl { get { return this._VarUrlOption; } set { this._VarUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// The username for authentication of the notifications. + /// + /// The username for authentication of the notifications. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Url {\n"); + sb.Append(" Encrypted: ").Append(Encrypted).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" VarUrl: ").Append(VarUrl).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UrlJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Url Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option encrypted = default; + Option password = default; + Option varUrl = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "encrypted": + encrypted = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "url": + varUrl = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Url(encrypted, password, varUrl, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Url url, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, url, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Url url, JsonSerializerOptions jsonSerializerOptions) + { + + if (url._EncryptedOption.IsSet) + writer.WriteBoolean("encrypted", url._EncryptedOption.Value!.Value); + + if (url._PasswordOption.IsSet) + if (url.Password != null) + writer.WriteString("password", url.Password); + + if (url._VarUrlOption.IsSet) + if (url.VarUrl != null) + writer.WriteString("url", url.VarUrl); + + if (url._UsernameOption.IsSet) + if (url.Username != null) + writer.WriteString("username", url.Username); + } + } +} diff --git a/Adyen/Management/Models/User.cs b/Adyen/Management/Models/User.cs new file mode 100644 index 000000000..6582604b2 --- /dev/null +++ b/Adyen/Management/Models/User.cs @@ -0,0 +1,389 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// User. + /// + public partial class User : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The email address of the user. + /// The unique identifier of the user. + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// The username for this user. + /// links + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// Indicates whether this user is active. + /// Set of apps available to this user + /// name + [JsonConstructor] + public User(string email, string id, List roles, string timeZoneCode, string username, Option links = default, Option?> accountGroups = default, Option active = default, Option?> apps = default, Option name = default) + { + Email = email; + Id = id; + Roles = roles; + TimeZoneCode = timeZoneCode; + Username = username; + _LinksOption = links; + _AccountGroupsOption = accountGroups; + _ActiveOption = active; + _AppsOption = apps; + _NameOption = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public User() + { + } + + partial void OnCreated(); + + /// + /// The email address of the user. + /// + /// The email address of the user. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// The unique identifier of the user. + /// + /// The unique identifier of the user. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + /// + /// The list of [roles](https://docs.adyen.com/account/user-roles) for this user. + [JsonPropertyName("roles")] + public List Roles { get; set; } + + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + /// + /// The [tz database name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) of the time zone of the user. For example, **Europe/Amsterdam**. + [JsonPropertyName("timeZoneCode")] + public string TimeZoneCode { get; set; } + + /// + /// The username for this user. + /// + /// The username for this user. + [JsonPropertyName("username")] + public string Username { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AccountGroupsOption { get; private set; } + + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + /// + /// The list of [account groups](https://docs.adyen.com/account/account-structure#account-groups) associated with this user. + [JsonPropertyName("accountGroups")] + public List? AccountGroups { get { return this._AccountGroupsOption; } set { this._AccountGroupsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ActiveOption { get; private set; } + + /// + /// Indicates whether this user is active. + /// + /// Indicates whether this user is active. + [JsonPropertyName("active")] + public bool? Active { get { return this._ActiveOption; } set { this._ActiveOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AppsOption { get; private set; } + + /// + /// Set of apps available to this user + /// + /// Set of apps available to this user + [JsonPropertyName("apps")] + public List? Apps { get { return this._AppsOption; } set { this._AppsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("name")] + public Name? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append(" TimeZoneCode: ").Append(TimeZoneCode).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AccountGroups: ").Append(AccountGroups).Append("\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" Apps: ").Append(Apps).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Username (string) maxLength + if (this.Username != null && this.Username.Length > 255) + { + yield return new ValidationResult("Invalid value for Username, length must be less than 255.", new [] { "Username" }); + } + + // Username (string) minLength + if (this.Username != null && this.Username.Length < 1) + { + yield return new ValidationResult("Invalid value for Username, length must be greater than 1.", new [] { "Username" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option email = default; + Option id = default; + Option?> roles = default; + Option timeZoneCode = default; + Option username = default; + Option links = default; + Option?> accountGroups = default; + Option active = default; + Option?> apps = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "timeZoneCode": + timeZoneCode = new Option(utf8JsonReader.GetString()!); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountGroups": + accountGroups = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "apps": + apps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "name": + name = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!email.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(email)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(id)); + + if (!roles.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(roles)); + + if (!timeZoneCode.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(timeZoneCode)); + + if (!username.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(username)); + + return new User(email.Value!, id.Value!, roles.Value!, timeZoneCode.Value!, username.Value!, links, accountGroups, active, apps, name); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, user, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + + if (user.Email != null) + writer.WriteString("email", user.Email); + + if (user.Id != null) + writer.WriteString("id", user.Id); + + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, user.Roles, jsonSerializerOptions); + if (user.TimeZoneCode != null) + writer.WriteString("timeZoneCode", user.TimeZoneCode); + + if (user.Username != null) + writer.WriteString("username", user.Username); + + if (user._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, user.Links, jsonSerializerOptions); + } + if (user._AccountGroupsOption.IsSet) + { + writer.WritePropertyName("accountGroups"); + JsonSerializer.Serialize(writer, user.AccountGroups, jsonSerializerOptions); + } + if (user._ActiveOption.IsSet) + writer.WriteBoolean("active", user._ActiveOption.Value!.Value); + + if (user._AppsOption.IsSet) + { + writer.WritePropertyName("apps"); + JsonSerializer.Serialize(writer, user.Apps, jsonSerializerOptions); + } + if (user._NameOption.IsSet) + { + writer.WritePropertyName("name"); + JsonSerializer.Serialize(writer, user.Name, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/VippsInfo.cs b/Adyen/Management/Models/VippsInfo.cs new file mode 100644 index 000000000..f900c892e --- /dev/null +++ b/Adyen/Management/Models/VippsInfo.cs @@ -0,0 +1,196 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// VippsInfo. + /// + public partial class VippsInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Vipps logo. Format: Base64-encoded string. + /// Vipps subscription cancel url (required in case of [recurring payments](https://docs.adyen.com/online-payments/tokenization)) + [JsonConstructor] + public VippsInfo(string logo, Option subscriptionCancelUrl = default) + { + Logo = logo; + _SubscriptionCancelUrlOption = subscriptionCancelUrl; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VippsInfo() + { + } + + partial void OnCreated(); + + /// + /// Vipps logo. Format: Base64-encoded string. + /// + /// Vipps logo. Format: Base64-encoded string. + [JsonPropertyName("logo")] + public string Logo { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubscriptionCancelUrlOption { get; private set; } + + /// + /// Vipps subscription cancel url (required in case of [recurring payments](https://docs.adyen.com/online-payments/tokenization)) + /// + /// Vipps subscription cancel url (required in case of [recurring payments](https://docs.adyen.com/online-payments/tokenization)) + [JsonPropertyName("subscriptionCancelUrl")] + public string? SubscriptionCancelUrl { get { return this._SubscriptionCancelUrlOption; } set { this._SubscriptionCancelUrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VippsInfo {\n"); + sb.Append(" Logo: ").Append(Logo).Append("\n"); + sb.Append(" SubscriptionCancelUrl: ").Append(SubscriptionCancelUrl).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VippsInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VippsInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option logo = default; + Option subscriptionCancelUrl = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "logo": + logo = new Option(utf8JsonReader.GetString()!); + break; + case "subscriptionCancelUrl": + subscriptionCancelUrl = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!logo.IsSet) + throw new ArgumentException("Property is required for class VippsInfo.", nameof(logo)); + + return new VippsInfo(logo.Value!, subscriptionCancelUrl); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VippsInfo vippsInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, vippsInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VippsInfo vippsInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (vippsInfo.Logo != null) + writer.WriteString("logo", vippsInfo.Logo); + + if (vippsInfo._SubscriptionCancelUrlOption.IsSet) + if (vippsInfo.SubscriptionCancelUrl != null) + writer.WriteString("subscriptionCancelUrl", vippsInfo.SubscriptionCancelUrl); + } + } +} diff --git a/Adyen/Management/Models/WeChatPayInfo.cs b/Adyen/Management/Models/WeChatPayInfo.cs new file mode 100644 index 000000000..09764479f --- /dev/null +++ b/Adyen/Management/Models/WeChatPayInfo.cs @@ -0,0 +1,191 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// WeChatPayInfo. + /// + public partial class WeChatPayInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the contact person from merchant support. + /// The email address of merchant support. + [JsonConstructor] + public WeChatPayInfo(string contactPersonName, string email) + { + ContactPersonName = contactPersonName; + Email = email; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WeChatPayInfo() + { + } + + partial void OnCreated(); + + /// + /// The name of the contact person from merchant support. + /// + /// The name of the contact person from merchant support. + [JsonPropertyName("contactPersonName")] + public string ContactPersonName { get; set; } + + /// + /// The email address of merchant support. + /// + /// The email address of merchant support. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WeChatPayInfo {\n"); + sb.Append(" ContactPersonName: ").Append(ContactPersonName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WeChatPayInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WeChatPayInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contactPersonName = default; + Option email = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contactPersonName": + contactPersonName = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!contactPersonName.IsSet) + throw new ArgumentException("Property is required for class WeChatPayInfo.", nameof(contactPersonName)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class WeChatPayInfo.", nameof(email)); + + return new WeChatPayInfo(contactPersonName.Value!, email.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WeChatPayInfo weChatPayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, weChatPayInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WeChatPayInfo weChatPayInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (weChatPayInfo.ContactPersonName != null) + writer.WriteString("contactPersonName", weChatPayInfo.ContactPersonName); + + if (weChatPayInfo.Email != null) + writer.WriteString("email", weChatPayInfo.Email); + } + } +} diff --git a/Adyen/Management/Models/WeChatPayPosInfo.cs b/Adyen/Management/Models/WeChatPayPosInfo.cs new file mode 100644 index 000000000..84546dcf3 --- /dev/null +++ b/Adyen/Management/Models/WeChatPayPosInfo.cs @@ -0,0 +1,191 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// WeChatPayPosInfo. + /// + public partial class WeChatPayPosInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the contact person from merchant support. + /// The email address of merchant support. + [JsonConstructor] + public WeChatPayPosInfo(string contactPersonName, string email) + { + ContactPersonName = contactPersonName; + Email = email; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WeChatPayPosInfo() + { + } + + partial void OnCreated(); + + /// + /// The name of the contact person from merchant support. + /// + /// The name of the contact person from merchant support. + [JsonPropertyName("contactPersonName")] + public string ContactPersonName { get; set; } + + /// + /// The email address of merchant support. + /// + /// The email address of merchant support. + [JsonPropertyName("email")] + public string Email { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WeChatPayPosInfo {\n"); + sb.Append(" ContactPersonName: ").Append(ContactPersonName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WeChatPayPosInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WeChatPayPosInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contactPersonName = default; + Option email = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contactPersonName": + contactPersonName = new Option(utf8JsonReader.GetString()!); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!contactPersonName.IsSet) + throw new ArgumentException("Property is required for class WeChatPayPosInfo.", nameof(contactPersonName)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class WeChatPayPosInfo.", nameof(email)); + + return new WeChatPayPosInfo(contactPersonName.Value!, email.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WeChatPayPosInfo weChatPayPosInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, weChatPayPosInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WeChatPayPosInfo weChatPayPosInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (weChatPayPosInfo.ContactPersonName != null) + writer.WriteString("contactPersonName", weChatPayPosInfo.ContactPersonName); + + if (weChatPayPosInfo.Email != null) + writer.WriteString("email", weChatPayPosInfo.Email); + } + } +} diff --git a/Adyen/Management/Models/Webhook.cs b/Adyen/Management/Models/Webhook.cs new file mode 100644 index 000000000..ad65e99c1 --- /dev/null +++ b/Adyen/Management/Models/Webhook.cs @@ -0,0 +1,1130 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// Webhook. + /// + public partial class Webhook : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for you to receive webhooks about events related an account. + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// The type of webhook. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **terminal-api-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// links + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// Reference to the account the webook is set on. + /// additionalSettings + /// The alias of our SSL certificate. When you receive a notification from us, the alias from the HMAC signature will match this alias. + /// Your description for this webhook configuration. + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// Shows how merchant accounts are included in company-level webhooks. Possible values: * **includeAccounts** * **excludeAccounts** * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// Indicates if the webhook configuration has errors that need troubleshooting. If the value is **true**, troubleshoot the configuration using the [testing endpoint](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookid}/test). + /// Indicates if the webhook is password protected. + /// The [checksum](https://en.wikipedia.org/wiki/Key_checksum_value) of the HMAC key generated for this webhook. You can use this value to uniquely identify the HMAC key configured for this webhook. + /// Unique identifier for this webhook. + /// Network type for Terminal API details webhooks. + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// Username to access the webhook URL. + [JsonConstructor] + public Webhook(bool active, CommunicationFormatEnum communicationFormat, string type, string url, Option links = default, Option acceptsExpiredCertificate = default, Option acceptsSelfSignedCertificate = default, Option acceptsUntrustedRootCertificate = default, Option accountReference = default, Option additionalSettings = default, Option certificateAlias = default, Option description = default, Option encryptionProtocol = default, Option filterMerchantAccountType = default, Option?> filterMerchantAccounts = default, Option hasError = default, Option hasPassword = default, Option hmacKeyCheckValue = default, Option id = default, Option networkType = default, Option populateSoapActionHeader = default, Option username = default) + { + Active = active; + CommunicationFormat = communicationFormat; + Type = type; + Url = url; + _LinksOption = links; + _AcceptsExpiredCertificateOption = acceptsExpiredCertificate; + _AcceptsSelfSignedCertificateOption = acceptsSelfSignedCertificate; + _AcceptsUntrustedRootCertificateOption = acceptsUntrustedRootCertificate; + _AccountReferenceOption = accountReference; + _AdditionalSettingsOption = additionalSettings; + _CertificateAliasOption = certificateAlias; + _DescriptionOption = description; + _EncryptionProtocolOption = encryptionProtocol; + _FilterMerchantAccountTypeOption = filterMerchantAccountType; + _FilterMerchantAccountsOption = filterMerchantAccounts; + _HasErrorOption = hasError; + _HasPasswordOption = hasPassword; + _HmacKeyCheckValueOption = hmacKeyCheckValue; + _IdOption = id; + _NetworkTypeOption = networkType; + _PopulateSoapActionHeaderOption = populateSoapActionHeader; + _UsernameOption = username; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Webhook() + { + } + + partial void OnCreated(); + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + [JsonConverter(typeof(CommunicationFormatEnumJsonConverter))] + public class CommunicationFormatEnum : IEnum + { + /// + /// Returns the value of the CommunicationFormatEnum. + /// + public string? Value { get; set; } + + /// + /// CommunicationFormatEnum.Http - http + /// + public static readonly CommunicationFormatEnum Http = new("http"); + + /// + /// CommunicationFormatEnum.Json - json + /// + public static readonly CommunicationFormatEnum Json = new("json"); + + /// + /// CommunicationFormatEnum.Soap - soap + /// + public static readonly CommunicationFormatEnum Soap = new("soap"); + + private CommunicationFormatEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CommunicationFormatEnum?(string? value) => value == null ? null : new CommunicationFormatEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CommunicationFormatEnum? option) => option?.Value; + + public static bool operator ==(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CommunicationFormatEnum? left, CommunicationFormatEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CommunicationFormatEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CommunicationFormatEnum? FromStringOrDefault(string value) + { + return value switch { + "http" => CommunicationFormatEnum.Http, + "json" => CommunicationFormatEnum.Json, + "soap" => CommunicationFormatEnum.Soap, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CommunicationFormatEnum? value) + { + if (value == null) + return null; + + if (value == CommunicationFormatEnum.Http) + return "http"; + + if (value == CommunicationFormatEnum.Json) + return "json"; + + if (value == CommunicationFormatEnum.Soap) + return "soap"; + + return null; + } + + /// + /// JsonConverter for writing CommunicationFormatEnum. + /// + public class CommunicationFormatEnumJsonConverter : JsonConverter + { + public override CommunicationFormatEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CommunicationFormatEnum.FromStringOrDefault(value) ?? new CommunicationFormatEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CommunicationFormatEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CommunicationFormatEnum.ToJsonValue(value)); + } + } + } + + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /// + /// Format or protocol for receiving webhooks. Possible values: * **soap** * **http** * **json** + /* soap */ + [JsonPropertyName("communicationFormat")] + public CommunicationFormatEnum CommunicationFormat { get; set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + [JsonConverter(typeof(EncryptionProtocolEnumJsonConverter))] + public class EncryptionProtocolEnum : IEnum + { + /// + /// Returns the value of the EncryptionProtocolEnum. + /// + public string? Value { get; set; } + + /// + /// EncryptionProtocolEnum.HTTP - HTTP + /// + public static readonly EncryptionProtocolEnum HTTP = new("HTTP"); + + /// + /// EncryptionProtocolEnum.TLSv12 - TLSv1.2 + /// + public static readonly EncryptionProtocolEnum TLSv12 = new("TLSv1.2"); + + /// + /// EncryptionProtocolEnum.TLSv13 - TLSv1.3 + /// + public static readonly EncryptionProtocolEnum TLSv13 = new("TLSv1.3"); + + private EncryptionProtocolEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EncryptionProtocolEnum?(string? value) => value == null ? null : new EncryptionProtocolEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EncryptionProtocolEnum? option) => option?.Value; + + public static bool operator ==(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EncryptionProtocolEnum? left, EncryptionProtocolEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EncryptionProtocolEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EncryptionProtocolEnum? FromStringOrDefault(string value) + { + return value switch { + "HTTP" => EncryptionProtocolEnum.HTTP, + "TLSv1.2" => EncryptionProtocolEnum.TLSv12, + "TLSv1.3" => EncryptionProtocolEnum.TLSv13, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EncryptionProtocolEnum? value) + { + if (value == null) + return null; + + if (value == EncryptionProtocolEnum.HTTP) + return "HTTP"; + + if (value == EncryptionProtocolEnum.TLSv12) + return "TLSv1.2"; + + if (value == EncryptionProtocolEnum.TLSv13) + return "TLSv1.3"; + + return null; + } + + /// + /// JsonConverter for writing EncryptionProtocolEnum. + /// + public class EncryptionProtocolEnumJsonConverter : JsonConverter + { + public override EncryptionProtocolEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EncryptionProtocolEnum.FromStringOrDefault(value) ?? new EncryptionProtocolEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EncryptionProtocolEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EncryptionProtocolEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EncryptionProtocolOption { get; private set; } + + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /// + /// SSL version to access the public webhook URL specified in the `url` field. Possible values: * **TLSv1.3** * **TLSv1.2** * **HTTP** - Only allowed on Test environment. If not specified, the webhook will use `sslVersion`: **TLSv1.2**. + /* TLSv1.2 */ + [JsonPropertyName("encryptionProtocol")] + public EncryptionProtocolEnum? EncryptionProtocol { get { return this._EncryptionProtocolOption; } set { this._EncryptionProtocolOption = new(value); } } + + /// + /// Shows how merchant accounts are included in company-level webhooks. Possible values: * **includeAccounts** * **excludeAccounts** * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are included in company-level webhooks. Possible values: * **includeAccounts** * **excludeAccounts** * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + [JsonConverter(typeof(FilterMerchantAccountTypeEnumJsonConverter))] + public class FilterMerchantAccountTypeEnum : IEnum + { + /// + /// Returns the value of the FilterMerchantAccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FilterMerchantAccountTypeEnum.AllAccounts - allAccounts + /// + public static readonly FilterMerchantAccountTypeEnum AllAccounts = new("allAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.ExcludeAccounts - excludeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum ExcludeAccounts = new("excludeAccounts"); + + /// + /// FilterMerchantAccountTypeEnum.IncludeAccounts - includeAccounts + /// + public static readonly FilterMerchantAccountTypeEnum IncludeAccounts = new("includeAccounts"); + + private FilterMerchantAccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FilterMerchantAccountTypeEnum?(string? value) => value == null ? null : new FilterMerchantAccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FilterMerchantAccountTypeEnum? option) => option?.Value; + + public static bool operator ==(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FilterMerchantAccountTypeEnum? left, FilterMerchantAccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FilterMerchantAccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FilterMerchantAccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "allAccounts" => FilterMerchantAccountTypeEnum.AllAccounts, + "excludeAccounts" => FilterMerchantAccountTypeEnum.ExcludeAccounts, + "includeAccounts" => FilterMerchantAccountTypeEnum.IncludeAccounts, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FilterMerchantAccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == FilterMerchantAccountTypeEnum.AllAccounts) + return "allAccounts"; + + if (value == FilterMerchantAccountTypeEnum.ExcludeAccounts) + return "excludeAccounts"; + + if (value == FilterMerchantAccountTypeEnum.IncludeAccounts) + return "includeAccounts"; + + return null; + } + + /// + /// JsonConverter for writing FilterMerchantAccountTypeEnum. + /// + public class FilterMerchantAccountTypeEnumJsonConverter : JsonConverter + { + public override FilterMerchantAccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FilterMerchantAccountTypeEnum.FromStringOrDefault(value) ?? new FilterMerchantAccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FilterMerchantAccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FilterMerchantAccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FilterMerchantAccountTypeOption { get; private set; } + + /// + /// Shows how merchant accounts are included in company-level webhooks. Possible values: * **includeAccounts** * **excludeAccounts** * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + /// + /// Shows how merchant accounts are included in company-level webhooks. Possible values: * **includeAccounts** * **excludeAccounts** * **allAccounts**: Includes all merchant accounts, and does not require specifying `filterMerchantAccounts`. + [JsonPropertyName("filterMerchantAccountType")] + public FilterMerchantAccountTypeEnum? FilterMerchantAccountType { get { return this._FilterMerchantAccountTypeOption; } set { this._FilterMerchantAccountTypeOption = new(value); } } + + /// + /// Network type for Terminal API details webhooks. + /// + /// Network type for Terminal API details webhooks. + [JsonConverter(typeof(NetworkTypeEnumJsonConverter))] + public class NetworkTypeEnum : IEnum + { + /// + /// Returns the value of the NetworkTypeEnum. + /// + public string? Value { get; set; } + + /// + /// NetworkTypeEnum.Local - local + /// + public static readonly NetworkTypeEnum Local = new("local"); + + /// + /// NetworkTypeEnum.Public - public + /// + public static readonly NetworkTypeEnum Public = new("public"); + + private NetworkTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator NetworkTypeEnum?(string? value) => value == null ? null : new NetworkTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(NetworkTypeEnum? option) => option?.Value; + + public static bool operator ==(NetworkTypeEnum? left, NetworkTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(NetworkTypeEnum? left, NetworkTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is NetworkTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static NetworkTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "local" => NetworkTypeEnum.Local, + "public" => NetworkTypeEnum.Public, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(NetworkTypeEnum? value) + { + if (value == null) + return null; + + if (value == NetworkTypeEnum.Local) + return "local"; + + if (value == NetworkTypeEnum.Public) + return "public"; + + return null; + } + + /// + /// JsonConverter for writing NetworkTypeEnum. + /// + public class NetworkTypeEnumJsonConverter : JsonConverter + { + public override NetworkTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : NetworkTypeEnum.FromStringOrDefault(value) ?? new NetworkTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, NetworkTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(NetworkTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTypeOption { get; private set; } + + /// + /// Network type for Terminal API details webhooks. + /// + /// Network type for Terminal API details webhooks. + [JsonPropertyName("networkType")] + public NetworkTypeEnum? NetworkType { get { return this._NetworkTypeOption; } set { this._NetworkTypeOption = new(value); } } + + /// + /// Indicates if the webhook configuration is active. The field must be **true** for you to receive webhooks about events related an account. + /// + /// Indicates if the webhook configuration is active. The field must be **true** for you to receive webhooks about events related an account. + [JsonPropertyName("active")] + public bool Active { get; set; } + + /// + /// The type of webhook. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **terminal-api-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + /// + /// The type of webhook. Possible values are: - **standard** - **account-settings-notification** - **banktransfer-notification** - **boletobancario-notification** - **directdebit-notification** - **ach-notification-of-change-notification** - **direct-debit-notice-of-change-notification** - **pending-notification** - **ideal-notification** - **ideal-pending-notification** - **report-notification** - **terminal-api-notification** - **terminal-settings** - **terminal-boarding** Find out more about [standard webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#event-codes) and [other types of webhooks](https://docs.adyen.com/development-resources/webhooks/webhook-types/#other-webhooks). + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /// + /// Public URL where webhooks will be sent, for example **https://www.domain.com/webhook-endpoint**. + /* http://www.adyen.com */ + [JsonPropertyName("url")] + public string Url { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public WebhookLinks? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsExpiredCertificateOption { get; private set; } + + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if expired SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsExpiredCertificate")] + public bool? AcceptsExpiredCertificate { get { return this._AcceptsExpiredCertificateOption; } set { this._AcceptsExpiredCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsSelfSignedCertificateOption { get; private set; } + + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if self-signed SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsSelfSignedCertificate")] + public bool? AcceptsSelfSignedCertificate { get { return this._AcceptsSelfSignedCertificateOption; } set { this._AcceptsSelfSignedCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcceptsUntrustedRootCertificateOption { get; private set; } + + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + /// + /// Indicates if untrusted SSL certificates are accepted. Default value: **false**. + [JsonPropertyName("acceptsUntrustedRootCertificate")] + public bool? AcceptsUntrustedRootCertificate { get { return this._AcceptsUntrustedRootCertificateOption; } set { this._AcceptsUntrustedRootCertificateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountReferenceOption { get; private set; } + + /// + /// Reference to the account the webook is set on. + /// + /// Reference to the account the webook is set on. + [JsonPropertyName("accountReference")] + public string? AccountReference { get { return this._AccountReferenceOption; } set { this._AccountReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalSettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalSettings")] + public AdditionalSettingsResponse? AdditionalSettings { get { return this._AdditionalSettingsOption; } set { this._AdditionalSettingsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CertificateAliasOption { get; private set; } + + /// + /// The alias of our SSL certificate. When you receive a notification from us, the alias from the HMAC signature will match this alias. + /// + /// The alias of our SSL certificate. When you receive a notification from us, the alias from the HMAC signature will match this alias. + [JsonPropertyName("certificateAlias")] + public string? CertificateAlias { get { return this._CertificateAliasOption; } set { this._CertificateAliasOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for this webhook configuration. + /// + /// Your description for this webhook configuration. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _FilterMerchantAccountsOption { get; private set; } + + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + /// + /// A list of merchant account names that are included or excluded from receiving the webhook. Inclusion or exclusion is based on the value defined for `filterMerchantAccountType`. Required if `filterMerchantAccountType` is either: * **includeAccounts** * **excludeAccounts** Not needed for `filterMerchantAccountType`: **allAccounts**. + [JsonPropertyName("filterMerchantAccounts")] + public List? FilterMerchantAccounts { get { return this._FilterMerchantAccountsOption; } set { this._FilterMerchantAccountsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HasErrorOption { get; private set; } + + /// + /// Indicates if the webhook configuration has errors that need troubleshooting. If the value is **true**, troubleshoot the configuration using the [testing endpoint](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookid}/test). + /// + /// Indicates if the webhook configuration has errors that need troubleshooting. If the value is **true**, troubleshoot the configuration using the [testing endpoint](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/webhooks/{webhookid}/test). + [JsonPropertyName("hasError")] + public bool? HasError { get { return this._HasErrorOption; } set { this._HasErrorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HasPasswordOption { get; private set; } + + /// + /// Indicates if the webhook is password protected. + /// + /// Indicates if the webhook is password protected. + [JsonPropertyName("hasPassword")] + public bool? HasPassword { get { return this._HasPasswordOption; } set { this._HasPasswordOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HmacKeyCheckValueOption { get; private set; } + + /// + /// The [checksum](https://en.wikipedia.org/wiki/Key_checksum_value) of the HMAC key generated for this webhook. You can use this value to uniquely identify the HMAC key configured for this webhook. + /// + /// The [checksum](https://en.wikipedia.org/wiki/Key_checksum_value) of the HMAC key generated for this webhook. You can use this value to uniquely identify the HMAC key configured for this webhook. + [JsonPropertyName("hmacKeyCheckValue")] + public string? HmacKeyCheckValue { get { return this._HmacKeyCheckValueOption; } set { this._HmacKeyCheckValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Unique identifier for this webhook. + /// + /// Unique identifier for this webhook. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PopulateSoapActionHeaderOption { get; private set; } + + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + /// + /// Indicates if the SOAP action header needs to be populated. Default value: **false**. Only applies if `communicationFormat`: **soap**. + [JsonPropertyName("populateSoapActionHeader")] + public bool? PopulateSoapActionHeader { get { return this._PopulateSoapActionHeaderOption; } set { this._PopulateSoapActionHeaderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UsernameOption { get; private set; } + + /// + /// Username to access the webhook URL. + /// + /// Username to access the webhook URL. + [JsonPropertyName("username")] + public string? Username { get { return this._UsernameOption; } set { this._UsernameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Webhook {\n"); + sb.Append(" Active: ").Append(Active).Append("\n"); + sb.Append(" CommunicationFormat: ").Append(CommunicationFormat).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" AcceptsExpiredCertificate: ").Append(AcceptsExpiredCertificate).Append("\n"); + sb.Append(" AcceptsSelfSignedCertificate: ").Append(AcceptsSelfSignedCertificate).Append("\n"); + sb.Append(" AcceptsUntrustedRootCertificate: ").Append(AcceptsUntrustedRootCertificate).Append("\n"); + sb.Append(" AccountReference: ").Append(AccountReference).Append("\n"); + sb.Append(" AdditionalSettings: ").Append(AdditionalSettings).Append("\n"); + sb.Append(" CertificateAlias: ").Append(CertificateAlias).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" EncryptionProtocol: ").Append(EncryptionProtocol).Append("\n"); + sb.Append(" FilterMerchantAccountType: ").Append(FilterMerchantAccountType).Append("\n"); + sb.Append(" FilterMerchantAccounts: ").Append(FilterMerchantAccounts).Append("\n"); + sb.Append(" HasError: ").Append(HasError).Append("\n"); + sb.Append(" HasPassword: ").Append(HasPassword).Append("\n"); + sb.Append(" HmacKeyCheckValue: ").Append(HmacKeyCheckValue).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" NetworkType: ").Append(NetworkType).Append("\n"); + sb.Append(" PopulateSoapActionHeader: ").Append(PopulateSoapActionHeader).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebhookJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Webhook Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option active = default; + Option communicationFormat = default; + Option type = default; + Option url = default; + Option links = default; + Option acceptsExpiredCertificate = default; + Option acceptsSelfSignedCertificate = default; + Option acceptsUntrustedRootCertificate = default; + Option accountReference = default; + Option additionalSettings = default; + Option certificateAlias = default; + Option description = default; + Option encryptionProtocol = default; + Option filterMerchantAccountType = default; + Option?> filterMerchantAccounts = default; + Option hasError = default; + Option hasPassword = default; + Option hmacKeyCheckValue = default; + Option id = default; + Option networkType = default; + Option populateSoapActionHeader = default; + Option username = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "active": + active = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "communicationFormat": + string? communicationFormatRawValue = utf8JsonReader.GetString(); + communicationFormat = new Option(Webhook.CommunicationFormatEnum.FromStringOrDefault(communicationFormatRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acceptsExpiredCertificate": + acceptsExpiredCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsSelfSignedCertificate": + acceptsSelfSignedCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "acceptsUntrustedRootCertificate": + acceptsUntrustedRootCertificate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "accountReference": + accountReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalSettings": + additionalSettings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "certificateAlias": + certificateAlias = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "encryptionProtocol": + string? encryptionProtocolRawValue = utf8JsonReader.GetString(); + encryptionProtocol = new Option(Webhook.EncryptionProtocolEnum.FromStringOrDefault(encryptionProtocolRawValue)); + break; + case "filterMerchantAccountType": + string? filterMerchantAccountTypeRawValue = utf8JsonReader.GetString(); + filterMerchantAccountType = new Option(Webhook.FilterMerchantAccountTypeEnum.FromStringOrDefault(filterMerchantAccountTypeRawValue)); + break; + case "filterMerchantAccounts": + filterMerchantAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "hasError": + hasError = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hasPassword": + hasPassword = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hmacKeyCheckValue": + hmacKeyCheckValue = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "networkType": + string? networkTypeRawValue = utf8JsonReader.GetString(); + networkType = new Option(Webhook.NetworkTypeEnum.FromStringOrDefault(networkTypeRawValue)); + break; + case "populateSoapActionHeader": + populateSoapActionHeader = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "username": + username = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!active.IsSet) + throw new ArgumentException("Property is required for class Webhook.", nameof(active)); + + if (!communicationFormat.IsSet) + throw new ArgumentException("Property is required for class Webhook.", nameof(communicationFormat)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Webhook.", nameof(type)); + + if (!url.IsSet) + throw new ArgumentException("Property is required for class Webhook.", nameof(url)); + + return new Webhook(active.Value!.Value!, communicationFormat.Value!.Value!, type.Value!, url.Value!, links, acceptsExpiredCertificate, acceptsSelfSignedCertificate, acceptsUntrustedRootCertificate, accountReference, additionalSettings, certificateAlias, description, encryptionProtocol, filterMerchantAccountType, filterMerchantAccounts, hasError, hasPassword, hmacKeyCheckValue, id, networkType, populateSoapActionHeader, username); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Webhook webhook, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, webhook, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Webhook webhook, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("active", webhook.Active); + + if (webhook.CommunicationFormat != null) + { + string? communicationFormatRawValue = Webhook.CommunicationFormatEnum.ToJsonValue(webhook.CommunicationFormat); + writer.WriteString("communicationFormat", communicationFormatRawValue); + } + + if (webhook.Type != null) + writer.WriteString("type", webhook.Type); + + if (webhook.Url != null) + writer.WriteString("url", webhook.Url); + + if (webhook._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, webhook.Links, jsonSerializerOptions); + } + if (webhook._AcceptsExpiredCertificateOption.IsSet) + writer.WriteBoolean("acceptsExpiredCertificate", webhook._AcceptsExpiredCertificateOption.Value!.Value); + + if (webhook._AcceptsSelfSignedCertificateOption.IsSet) + writer.WriteBoolean("acceptsSelfSignedCertificate", webhook._AcceptsSelfSignedCertificateOption.Value!.Value); + + if (webhook._AcceptsUntrustedRootCertificateOption.IsSet) + writer.WriteBoolean("acceptsUntrustedRootCertificate", webhook._AcceptsUntrustedRootCertificateOption.Value!.Value); + + if (webhook._AccountReferenceOption.IsSet) + if (webhook.AccountReference != null) + writer.WriteString("accountReference", webhook.AccountReference); + + if (webhook._AdditionalSettingsOption.IsSet) + { + writer.WritePropertyName("additionalSettings"); + JsonSerializer.Serialize(writer, webhook.AdditionalSettings, jsonSerializerOptions); + } + if (webhook._CertificateAliasOption.IsSet) + if (webhook.CertificateAlias != null) + writer.WriteString("certificateAlias", webhook.CertificateAlias); + + if (webhook._DescriptionOption.IsSet) + if (webhook.Description != null) + writer.WriteString("description", webhook.Description); + + if (webhook._EncryptionProtocolOption.IsSet && webhook.EncryptionProtocol != null) + { + string? encryptionProtocolRawValue = Webhook.EncryptionProtocolEnum.ToJsonValue(webhook._EncryptionProtocolOption.Value!.Value); + writer.WriteString("encryptionProtocol", encryptionProtocolRawValue); + } + + if (webhook._FilterMerchantAccountTypeOption.IsSet && webhook.FilterMerchantAccountType != null) + { + string? filterMerchantAccountTypeRawValue = Webhook.FilterMerchantAccountTypeEnum.ToJsonValue(webhook._FilterMerchantAccountTypeOption.Value!.Value); + writer.WriteString("filterMerchantAccountType", filterMerchantAccountTypeRawValue); + } + + if (webhook._FilterMerchantAccountsOption.IsSet) + { + writer.WritePropertyName("filterMerchantAccounts"); + JsonSerializer.Serialize(writer, webhook.FilterMerchantAccounts, jsonSerializerOptions); + } + if (webhook._HasErrorOption.IsSet) + writer.WriteBoolean("hasError", webhook._HasErrorOption.Value!.Value); + + if (webhook._HasPasswordOption.IsSet) + writer.WriteBoolean("hasPassword", webhook._HasPasswordOption.Value!.Value); + + if (webhook._HmacKeyCheckValueOption.IsSet) + if (webhook.HmacKeyCheckValue != null) + writer.WriteString("hmacKeyCheckValue", webhook.HmacKeyCheckValue); + + if (webhook._IdOption.IsSet) + if (webhook.Id != null) + writer.WriteString("id", webhook.Id); + + if (webhook._NetworkTypeOption.IsSet && webhook.NetworkType != null) + { + string? networkTypeRawValue = Webhook.NetworkTypeEnum.ToJsonValue(webhook._NetworkTypeOption.Value!.Value); + writer.WriteString("networkType", networkTypeRawValue); + } + + if (webhook._PopulateSoapActionHeaderOption.IsSet) + writer.WriteBoolean("populateSoapActionHeader", webhook._PopulateSoapActionHeaderOption.Value!.Value); + + if (webhook._UsernameOption.IsSet) + if (webhook.Username != null) + writer.WriteString("username", webhook.Username); + } + } +} diff --git a/Adyen/Management/Models/WebhookLinks.cs b/Adyen/Management/Models/WebhookLinks.cs new file mode 100644 index 000000000..84e5658c2 --- /dev/null +++ b/Adyen/Management/Models/WebhookLinks.cs @@ -0,0 +1,256 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// WebhookLinks. + /// + public partial class WebhookLinks : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// generateHmac + /// self + /// testWebhook + /// company + /// merchant + [JsonConstructor] + public WebhookLinks(LinksElement generateHmac, LinksElement self, LinksElement testWebhook, Option company = default, Option merchant = default) + { + GenerateHmac = generateHmac; + Self = self; + TestWebhook = testWebhook; + _CompanyOption = company; + _MerchantOption = merchant; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WebhookLinks() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("generateHmac")] + public LinksElement GenerateHmac { get; set; } + + /// + /// . + /// + [JsonPropertyName("self")] + public LinksElement Self { get; set; } + + /// + /// . + /// + [JsonPropertyName("testWebhook")] + public LinksElement TestWebhook { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("company")] + public LinksElement? Company { get { return this._CompanyOption; } set { this._CompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public LinksElement? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WebhookLinks {\n"); + sb.Append(" GenerateHmac: ").Append(GenerateHmac).Append("\n"); + sb.Append(" Self: ").Append(Self).Append("\n"); + sb.Append(" TestWebhook: ").Append(TestWebhook).Append("\n"); + sb.Append(" Company: ").Append(Company).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WebhookLinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WebhookLinks Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option generateHmac = default; + Option self = default; + Option testWebhook = default; + Option company = default; + Option merchant = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "generateHmac": + generateHmac = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "self": + self = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "testWebhook": + testWebhook = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "company": + company = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!generateHmac.IsSet) + throw new ArgumentException("Property is required for class WebhookLinks.", nameof(generateHmac)); + + if (!self.IsSet) + throw new ArgumentException("Property is required for class WebhookLinks.", nameof(self)); + + if (!testWebhook.IsSet) + throw new ArgumentException("Property is required for class WebhookLinks.", nameof(testWebhook)); + + return new WebhookLinks(generateHmac.Value!, self.Value!, testWebhook.Value!, company, merchant); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WebhookLinks webhookLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, webhookLinks, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WebhookLinks webhookLinks, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("generateHmac"); + JsonSerializer.Serialize(writer, webhookLinks.GenerateHmac, jsonSerializerOptions); + writer.WritePropertyName("self"); + JsonSerializer.Serialize(writer, webhookLinks.Self, jsonSerializerOptions); + writer.WritePropertyName("testWebhook"); + JsonSerializer.Serialize(writer, webhookLinks.TestWebhook, jsonSerializerOptions); + if (webhookLinks._CompanyOption.IsSet) + { + writer.WritePropertyName("company"); + JsonSerializer.Serialize(writer, webhookLinks.Company, jsonSerializerOptions); + } + if (webhookLinks._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, webhookLinks.Merchant, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Models/WifiProfiles.cs b/Adyen/Management/Models/WifiProfiles.cs new file mode 100644 index 000000000..e12af9bfd --- /dev/null +++ b/Adyen/Management/Models/WifiProfiles.cs @@ -0,0 +1,204 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Management.Client; + +namespace Adyen.Management.Models +{ + /// + /// WifiProfiles. + /// + public partial class WifiProfiles : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of remote Wi-Fi profiles. + /// settings + [JsonConstructor] + public WifiProfiles(Option?> profiles = default, Option settings = default) + { + _ProfilesOption = profiles; + _SettingsOption = settings; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public WifiProfiles() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProfilesOption { get; private set; } + + /// + /// List of remote Wi-Fi profiles. + /// + /// List of remote Wi-Fi profiles. + [JsonPropertyName("profiles")] + public List? Profiles { get { return this._ProfilesOption; } set { this._ProfilesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SettingsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("settings")] + public Settings? Settings { get { return this._SettingsOption; } set { this._SettingsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WifiProfiles {\n"); + sb.Append(" Profiles: ").Append(Profiles).Append("\n"); + sb.Append(" Settings: ").Append(Settings).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WifiProfilesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override WifiProfiles Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> profiles = default; + Option settings = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "profiles": + profiles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "settings": + settings = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new WifiProfiles(profiles, settings); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WifiProfiles wifiProfiles, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, wifiProfiles, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WifiProfiles wifiProfiles, JsonSerializerOptions jsonSerializerOptions) + { + + if (wifiProfiles._ProfilesOption.IsSet) + { + writer.WritePropertyName("profiles"); + JsonSerializer.Serialize(writer, wifiProfiles.Profiles, jsonSerializerOptions); + } + if (wifiProfiles._SettingsOption.IsSet) + { + writer.WritePropertyName("settings"); + JsonSerializer.Serialize(writer, wifiProfiles.Settings, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Management/Services/APICredentialsCompanyLevelService.cs b/Adyen/Management/Services/APICredentialsCompanyLevelService.cs new file mode 100644 index 000000000..64f44f395 --- /dev/null +++ b/Adyen/Management/Services/APICredentialsCompanyLevelService.cs @@ -0,0 +1,1869 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAPICredentialsCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + APICredentialsCompanyLevelServiceEvents Events { get; } + + /// + /// Create an API credential. + /// + /// + /// Creates an [API credential](https://docs.adyen.com/development-resources/api-credentials) for the company account identified in the path. In the request, you can specify which merchant accounts the new API credential will have access to, as well as its roles and allowed origins. The response includes several types of authentication details: * [API key](https://docs.adyen.com/development-resources/api-authentication#api-key-authentication): used for API request authentication. * [Client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works): public key used for client-side authentication. * [Username and password](https://docs.adyen.com/development-resources/api-authentication#using-basic-authentication): used for basic authentication. > Make sure you store the API key securely in your system. You won't be able to retrieve it later. If your API key is lost or compromised, you need to [generate a new API key](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// + /// . + /// . + /// of . + Task CreateApiCredentialAsync(string companyId, CreateCompanyApiCredentialRequest createCompanyApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an API credential + /// + /// + /// Returns the [API credential](https://docs.adyen.com/development-resources/api-credentials) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GetApiCredentialAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of API credentials + /// + /// + /// Returns the list of [API credentials](https://docs.adyen.com/development-resources/api-credentials) for the company account. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListApiCredentialsAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an API credential. + /// + /// + /// Changes the API credential's roles, merchant account access, or allowed origins. The request has the new values for the fields you want to change. The response contains the full updated API credential, including the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// + /// . + /// . + /// of . + Task UpdateApiCredentialAsync(string companyId, string apiCredentialId, UpdateCompanyApiCredentialRequest updateCompanyApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateApiCredentialApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetApiCredentialApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListApiCredentialsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateApiCredentialApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class APICredentialsCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateApiCredential; + + internal void ExecuteOnCreateApiCredential(APICredentialsCompanyLevelService.CreateApiCredentialApiResponse apiResponse) + { + OnCreateApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateApiCredential(Exception exception) + { + OnErrorCreateApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetApiCredential; + + internal void ExecuteOnGetApiCredential(APICredentialsCompanyLevelService.GetApiCredentialApiResponse apiResponse) + { + OnGetApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetApiCredential(Exception exception) + { + OnErrorGetApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListApiCredentials; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListApiCredentials; + + internal void ExecuteOnListApiCredentials(APICredentialsCompanyLevelService.ListApiCredentialsApiResponse apiResponse) + { + OnListApiCredentials?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListApiCredentials(Exception exception) + { + OnErrorListApiCredentials?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateApiCredential; + + internal void ExecuteOnUpdateApiCredential(APICredentialsCompanyLevelService.UpdateApiCredentialApiResponse apiResponse) + { + OnUpdateApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateApiCredential(Exception exception) + { + OnErrorUpdateApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class APICredentialsCompanyLevelService : IAPICredentialsCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public APICredentialsCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public APICredentialsCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APICredentialsCompanyLevelServiceEvents aPICredentialsCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = aPICredentialsCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an API credential. Creates an [API credential](https://docs.adyen.com/development-resources/api-credentials) for the company account identified in the path. In the request, you can specify which merchant accounts the new API credential will have access to, as well as its roles and allowed origins. The response includes several types of authentication details: * [API key](https://docs.adyen.com/development-resources/api-authentication#api-key-authentication): used for API request authentication. * [Client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works): public key used for client-side authentication. * [Username and password](https://docs.adyen.com/development-resources/api-authentication#using-basic-authentication): used for basic authentication. > Make sure you store the API key securely in your system. You won't be able to retrieve it later. If your API key is lost or compromised, you need to [generate a new API key](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateApiCredentialAsync(string companyId, CreateCompanyApiCredentialRequest createCompanyApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createCompanyApiCredentialRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createCompanyApiCredentialRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateApiCredential(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateApiCredentialApiResponse : Adyen.Core.Client.ApiResponse, ICreateApiCredentialApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CreateCompanyApiCredentialResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CreateCompanyApiCredentialResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an API credential Returns the [API credential](https://docs.adyen.com/development-resources/api-credentials) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetApiCredentialAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetApiCredential(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetApiCredentialApiResponse : Adyen.Core.Client.ApiResponse, IGetApiCredentialApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CompanyApiCredential? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CompanyApiCredential? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of API credentials Returns the list of [API credentials](https://docs.adyen.com/development-resources/api-credentials) for the company account. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListApiCredentialsAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListApiCredentialsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListApiCredentials(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListApiCredentials(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListApiCredentialsApiResponse : Adyen.Core.Client.ApiResponse, IListApiCredentialsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListApiCredentialsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListApiCredentialsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListCompanyApiCredentialsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListCompanyApiCredentialsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update an API credential. Changes the API credential's roles, merchant account access, or allowed origins. The request has the new values for the fields you want to change. The response contains the full updated API credential, including the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateApiCredentialAsync(string companyId, string apiCredentialId, UpdateCompanyApiCredentialRequest updateCompanyApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateCompanyApiCredentialRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateCompanyApiCredentialRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateApiCredential(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateApiCredentialApiResponse : Adyen.Core.Client.ApiResponse, IUpdateApiCredentialApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateApiCredentialApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CompanyApiCredential? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CompanyApiCredential? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/APICredentialsMerchantLevelService.cs b/Adyen/Management/Services/APICredentialsMerchantLevelService.cs new file mode 100644 index 000000000..02e99e727 --- /dev/null +++ b/Adyen/Management/Services/APICredentialsMerchantLevelService.cs @@ -0,0 +1,565 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAPICredentialsMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + APICredentialsMerchantLevelServiceEvents Events { get; } + + /// + /// Create an API credential + /// + /// + /// Creates an [API credential](https://docs.adyen.com/development-resources/api-credentials) for the company account identified in the path. In the request, you can specify the roles and allowed origins for the new API credential. The response includes the: * [API key](https://docs.adyen.com/development-resources/api-authentication#api-key-authentication): used for API request authentication. * [Client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works): public key used for client-side authentication. * [Username and password](https://docs.adyen.com/development-resources/api-authentication#using-basic-authentication): used for basic authentication. > Make sure you store the API key securely in your system. You won't be able to retrieve it later. If your API key is lost or compromised, you need to [generate a new API key](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task CreateApiCredentialAsync(string merchantId, CreateMerchantApiCredentialRequest createMerchantApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an API credential + /// + /// + /// Returns the [API credential](https://docs.adyen.com/development-resources/api-credentials) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GetApiCredentialAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of API credentials + /// + /// + /// Returns the list of [API credentials](https://docs.adyen.com/development-resources/api-credentials) for the merchant account. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListApiCredentialsAsync(string merchantId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an API credential + /// + /// + /// Changes the API credential's roles, or allowed origins. The request has the new values for the fields you want to change. The response contains the full updated API credential, including the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// + /// . + /// . + /// of . + Task UpdateApiCredentialAsync(string merchantId, string apiCredentialId, UpdateMerchantApiCredentialRequest updateMerchantApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class APICredentialsMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateApiCredential; + + internal void ExecuteOnCreateApiCredential(APICredentialsCompanyLevelService.CreateApiCredentialApiResponse apiResponse) + { + OnCreateApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateApiCredential(Exception exception) + { + OnErrorCreateApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetApiCredential; + + internal void ExecuteOnGetApiCredential(APICredentialsCompanyLevelService.GetApiCredentialApiResponse apiResponse) + { + OnGetApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetApiCredential(Exception exception) + { + OnErrorGetApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListApiCredentials; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListApiCredentials; + + internal void ExecuteOnListApiCredentials(APICredentialsCompanyLevelService.ListApiCredentialsApiResponse apiResponse) + { + OnListApiCredentials?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListApiCredentials(Exception exception) + { + OnErrorListApiCredentials?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateApiCredential; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateApiCredential; + + internal void ExecuteOnUpdateApiCredential(APICredentialsCompanyLevelService.UpdateApiCredentialApiResponse apiResponse) + { + OnUpdateApiCredential?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateApiCredential(Exception exception) + { + OnErrorUpdateApiCredential?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class APICredentialsMerchantLevelService : IAPICredentialsMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public APICredentialsMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public APICredentialsMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APICredentialsMerchantLevelServiceEvents aPICredentialsMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = aPICredentialsMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an API credential Creates an [API credential](https://docs.adyen.com/development-resources/api-credentials) for the company account identified in the path. In the request, you can specify the roles and allowed origins for the new API credential. The response includes the: * [API key](https://docs.adyen.com/development-resources/api-authentication#api-key-authentication): used for API request authentication. * [Client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works): public key used for client-side authentication. * [Username and password](https://docs.adyen.com/development-resources/api-authentication#using-basic-authentication): used for basic authentication. > Make sure you store the API key securely in your system. You won't be able to retrieve it later. If your API key is lost or compromised, you need to [generate a new API key](https://docs.adyen.com/api-explorer/#/ManagementService/v1/post/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateApiCredentialAsync(string merchantId, CreateMerchantApiCredentialRequest createMerchantApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createMerchantApiCredentialRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createMerchantApiCredentialRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + APICredentialsCompanyLevelService.CreateApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateApiCredential(exception); + throw; + } + } + /// + /// Get an API credential Returns the [API credential](https://docs.adyen.com/development-resources/api-credentials) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetApiCredentialAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + APICredentialsCompanyLevelService.GetApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetApiCredential(exception); + throw; + } + } + /// + /// Get a list of API credentials Returns the list of [API credentials](https://docs.adyen.com/development-resources/api-credentials) for the merchant account. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListApiCredentialsAsync(string merchantId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + APICredentialsCompanyLevelService.ListApiCredentialsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListApiCredentials(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListApiCredentials(exception); + throw; + } + } + /// + /// Update an API credential Changes the API credential's roles, or allowed origins. The request has the new values for the fields you want to change. The response contains the full updated API credential, including the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateApiCredentialAsync(string merchantId, string apiCredentialId, UpdateMerchantApiCredentialRequest updateMerchantApiCredentialRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateMerchantApiCredentialRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateMerchantApiCredentialRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + APICredentialsCompanyLevelService.UpdateApiCredentialApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateApiCredential(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateApiCredential(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/APIKeyCompanyLevelService.cs b/Adyen/Management/Services/APIKeyCompanyLevelService.cs new file mode 100644 index 000000000..7b4be96a1 --- /dev/null +++ b/Adyen/Management/Services/APIKeyCompanyLevelService.cs @@ -0,0 +1,529 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAPIKeyCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + APIKeyCompanyLevelServiceEvents Events { get; } + + /// + /// Generate new API key + /// + /// + /// Returns a new API key for the API credential. You can use the new API key a few minutes after generating it. The old API key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GenerateNewApiKeyAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGenerateNewApiKeyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class APIKeyCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateNewApiKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateNewApiKey; + + internal void ExecuteOnGenerateNewApiKey(APIKeyCompanyLevelService.GenerateNewApiKeyApiResponse apiResponse) + { + OnGenerateNewApiKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateNewApiKey(Exception exception) + { + OnErrorGenerateNewApiKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class APIKeyCompanyLevelService : IAPIKeyCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public APIKeyCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public APIKeyCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKeyCompanyLevelServiceEvents aPIKeyCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = aPIKeyCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate new API key Returns a new API key for the API credential. You can use the new API key a few minutes after generating it. The old API key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateNewApiKeyAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GenerateNewApiKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateNewApiKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateNewApiKey(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GenerateNewApiKeyApiResponse : Adyen.Core.Client.ApiResponse, IGenerateNewApiKeyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateNewApiKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateNewApiKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.GenerateApiKeyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.GenerateApiKeyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/APIKeyMerchantLevelService.cs b/Adyen/Management/Services/APIKeyMerchantLevelService.cs new file mode 100644 index 000000000..0a1e7b9a1 --- /dev/null +++ b/Adyen/Management/Services/APIKeyMerchantLevelService.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAPIKeyMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + APIKeyMerchantLevelServiceEvents Events { get; } + + /// + /// Generate new API key + /// + /// + /// Returns a new API key for the API credential. You can use the new API key a few minutes after generating it. The old API key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GenerateNewApiKeyAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class APIKeyMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateNewApiKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateNewApiKey; + + internal void ExecuteOnGenerateNewApiKey(APIKeyCompanyLevelService.GenerateNewApiKeyApiResponse apiResponse) + { + OnGenerateNewApiKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateNewApiKey(Exception exception) + { + OnErrorGenerateNewApiKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class APIKeyMerchantLevelService : IAPIKeyMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public APIKeyMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public APIKeyMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, APIKeyMerchantLevelServiceEvents aPIKeyMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = aPIKeyMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate new API key Returns a new API key for the API credential. You can use the new API key a few minutes after generating it. The old API key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateNewApiKeyAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + APIKeyCompanyLevelService.GenerateNewApiKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateNewApiKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateNewApiKey(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/AccountCompanyLevelService.cs b/Adyen/Management/Services/AccountCompanyLevelService.cs new file mode 100644 index 000000000..ee295c582 --- /dev/null +++ b/Adyen/Management/Services/AccountCompanyLevelService.cs @@ -0,0 +1,1409 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAccountCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AccountCompanyLevelServiceEvents Events { get; } + + /// + /// Get a company account + /// + /// + /// Returns the company account specified in the path. Your API credential must have access to the company account. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of . + Task GetCompanyAccountAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of company accounts + /// + /// + /// Returns the list of company accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListCompanyAccountsAsync(Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of merchant accounts + /// + /// + /// Returns the list of merchant accounts under the company account specified in the path. The list only includes merchant accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListMerchantAccountsAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetCompanyAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListCompanyAccountsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListMerchantAccountsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AccountCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetCompanyAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetCompanyAccount; + + internal void ExecuteOnGetCompanyAccount(AccountCompanyLevelService.GetCompanyAccountApiResponse apiResponse) + { + OnGetCompanyAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCompanyAccount(Exception exception) + { + OnErrorGetCompanyAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListCompanyAccounts; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListCompanyAccounts; + + internal void ExecuteOnListCompanyAccounts(AccountCompanyLevelService.ListCompanyAccountsApiResponse apiResponse) + { + OnListCompanyAccounts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListCompanyAccounts(Exception exception) + { + OnErrorListCompanyAccounts?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListMerchantAccounts; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListMerchantAccounts; + + internal void ExecuteOnListMerchantAccounts(AccountCompanyLevelService.ListMerchantAccountsApiResponse apiResponse) + { + OnListMerchantAccounts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListMerchantAccounts(Exception exception) + { + OnErrorListMerchantAccounts?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AccountCompanyLevelService : IAccountCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AccountCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AccountCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AccountCompanyLevelServiceEvents accountCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = accountCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a company account Returns the company account specified in the path. Your API credential must have access to the company account. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetCompanyAccountAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetCompanyAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetCompanyAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetCompanyAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetCompanyAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetCompanyAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCompanyAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCompanyAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Company? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Company? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of company accounts Returns the list of company accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListCompanyAccountsAsync(Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListCompanyAccountsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListCompanyAccounts(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListCompanyAccounts(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListCompanyAccountsApiResponse : Adyen.Core.Client.ApiResponse, IListCompanyAccountsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListCompanyAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListCompanyAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListCompanyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListCompanyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of merchant accounts Returns the list of merchant accounts under the company account specified in the path. The list only includes merchant accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListMerchantAccountsAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/merchants" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/merchants"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListMerchantAccountsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/merchants", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListMerchantAccounts(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListMerchantAccounts(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListMerchantAccountsApiResponse : Adyen.Core.Client.ApiResponse, IListMerchantAccountsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListMerchantAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListMerchantAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListMerchantResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListMerchantResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/AccountMerchantLevelService.cs b/Adyen/Management/Services/AccountMerchantLevelService.cs new file mode 100644 index 000000000..2436411ab --- /dev/null +++ b/Adyen/Management/Services/AccountMerchantLevelService.cs @@ -0,0 +1,1549 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAccountMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AccountMerchantLevelServiceEvents Events { get; } + + /// + /// Create a merchant account + /// + /// + /// Creates a merchant account for the company account specified in the request. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Accounts read and write + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateMerchantAccountAsync(CreateMerchantRequest createMerchantRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a merchant account + /// + /// + /// Returns the merchant account specified in the path. Your API credential must have access to the merchant account. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task GetMerchantAccountAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of merchant accounts + /// + /// + /// Returns the list of merchant accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListMerchantAccountsAsync(Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Request to activate a merchant account + /// + /// + /// Sends a request to activate the merchant account identified in the path. You get the result of the activation asynchronously through a [`merchant.updated`](https://docs.adyen.com/api-explorer/ManagementNotification/latest/post/merchant.updated) webhook. Once the merchant account is activated, you can start using it to accept payments and payouts. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Accounts read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task RequestToActivateMerchantAccountAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateMerchantAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetMerchantAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRequestToActivateMerchantAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AccountMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateMerchantAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateMerchantAccount; + + internal void ExecuteOnCreateMerchantAccount(AccountMerchantLevelService.CreateMerchantAccountApiResponse apiResponse) + { + OnCreateMerchantAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateMerchantAccount(Exception exception) + { + OnErrorCreateMerchantAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetMerchantAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetMerchantAccount; + + internal void ExecuteOnGetMerchantAccount(AccountMerchantLevelService.GetMerchantAccountApiResponse apiResponse) + { + OnGetMerchantAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetMerchantAccount(Exception exception) + { + OnErrorGetMerchantAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListMerchantAccounts; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListMerchantAccounts; + + internal void ExecuteOnListMerchantAccounts(AccountCompanyLevelService.ListMerchantAccountsApiResponse apiResponse) + { + OnListMerchantAccounts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListMerchantAccounts(Exception exception) + { + OnErrorListMerchantAccounts?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRequestToActivateMerchantAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRequestToActivateMerchantAccount; + + internal void ExecuteOnRequestToActivateMerchantAccount(AccountMerchantLevelService.RequestToActivateMerchantAccountApiResponse apiResponse) + { + OnRequestToActivateMerchantAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRequestToActivateMerchantAccount(Exception exception) + { + OnErrorRequestToActivateMerchantAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AccountMerchantLevelService : IAccountMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AccountMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AccountMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AccountMerchantLevelServiceEvents accountMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = accountMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a merchant account Creates a merchant account for the company account specified in the request. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Accounts read and write + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateMerchantAccountAsync(CreateMerchantRequest createMerchantRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createMerchantRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createMerchantRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateMerchantAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateMerchantAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateMerchantAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateMerchantAccountApiResponse : Adyen.Core.Client.ApiResponse, ICreateMerchantAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CreateMerchantResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CreateMerchantResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a merchant account Returns the merchant account specified in the path. Your API credential must have access to the merchant account. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetMerchantAccountAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetMerchantAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetMerchantAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetMerchantAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetMerchantAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetMerchantAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Merchant? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Merchant? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of merchant accounts Returns the list of merchant accounts that your API credential has access to. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Account read + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListMerchantAccountsAsync(Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AccountCompanyLevelService.ListMerchantAccountsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListMerchantAccounts(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListMerchantAccounts(exception); + throw; + } + } + /// + /// Request to activate a merchant account Sends a request to activate the merchant account identified in the path. You get the result of the activation asynchronously through a [`merchant.updated`](https://docs.adyen.com/api-explorer/ManagementNotification/latest/post/merchant.updated) webhook. Once the merchant account is activated, you can start using it to accept payments and payouts. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Accounts read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RequestToActivateMerchantAccountAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/activate" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/activate"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RequestToActivateMerchantAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/activate", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRequestToActivateMerchantAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRequestToActivateMerchantAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RequestToActivateMerchantAccountApiResponse : Adyen.Core.Client.ApiResponse, IRequestToActivateMerchantAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestToActivateMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestToActivateMerchantAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.RequestActivationResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.RequestActivationResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/AccountStoreLevelService.cs b/Adyen/Management/Services/AccountStoreLevelService.cs new file mode 100644 index 000000000..d6f2595c5 --- /dev/null +++ b/Adyen/Management/Services/AccountStoreLevelService.cs @@ -0,0 +1,3692 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAccountStoreLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AccountStoreLevelServiceEvents Events { get; } + + /// + /// Create a store + /// + /// + /// Creates a store for the merchant account specified in the request. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateStoreAsync(StoreCreationWithMerchantCodeRequest storeCreationWithMerchantCodeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a store + /// + /// + /// Creates a store for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task CreateStoreByMerchantIdAsync(string merchantId, StoreCreationRequest storeCreationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a store + /// + /// + /// Returns the details of the store identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// . + /// . + /// of . + Task GetStoreAsync(string merchantId, string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a store + /// + /// + /// Returns the details of the store identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// . + /// . + /// of . + Task GetStoreByIdAsync(string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of stores + /// + /// + /// Returns a list of stores. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// The reference of the store. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task ListStoresAsync(Option pageNumber = default, Option pageSize = default, Option reference = default, Option merchantId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of stores + /// + /// + /// Returns a list of stores for the merchant account identified in the path. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// The reference of the store. + /// . + /// . + /// of . + Task ListStoresByMerchantIdAsync(string merchantId, Option pageNumber = default, Option pageSize = default, Option reference = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a store + /// + /// + /// Updates the store identified in the path. You can only update some store parameters. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// + /// . + /// . + /// of . + Task UpdateStoreAsync(string merchantId, string storeId, UpdateStoreRequest updateStoreRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a store + /// + /// + /// Updates the store identified in the path. You can only update some store parameters. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// + /// . + /// . + /// of . + Task UpdateStoreByIdAsync(string storeId, UpdateStoreRequest updateStoreRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateStoreApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateStoreByMerchantIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetStoreApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetStoreByIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListStoresApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListStoresByMerchantIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateStoreApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateStoreByIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AccountStoreLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateStore; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateStore; + + internal void ExecuteOnCreateStore(AccountStoreLevelService.CreateStoreApiResponse apiResponse) + { + OnCreateStore?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateStore(Exception exception) + { + OnErrorCreateStore?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateStoreByMerchantId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateStoreByMerchantId; + + internal void ExecuteOnCreateStoreByMerchantId(AccountStoreLevelService.CreateStoreByMerchantIdApiResponse apiResponse) + { + OnCreateStoreByMerchantId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateStoreByMerchantId(Exception exception) + { + OnErrorCreateStoreByMerchantId?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetStore; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetStore; + + internal void ExecuteOnGetStore(AccountStoreLevelService.GetStoreApiResponse apiResponse) + { + OnGetStore?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetStore(Exception exception) + { + OnErrorGetStore?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetStoreById; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetStoreById; + + internal void ExecuteOnGetStoreById(AccountStoreLevelService.GetStoreByIdApiResponse apiResponse) + { + OnGetStoreById?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetStoreById(Exception exception) + { + OnErrorGetStoreById?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListStores; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListStores; + + internal void ExecuteOnListStores(AccountStoreLevelService.ListStoresApiResponse apiResponse) + { + OnListStores?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListStores(Exception exception) + { + OnErrorListStores?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListStoresByMerchantId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListStoresByMerchantId; + + internal void ExecuteOnListStoresByMerchantId(AccountStoreLevelService.ListStoresByMerchantIdApiResponse apiResponse) + { + OnListStoresByMerchantId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListStoresByMerchantId(Exception exception) + { + OnErrorListStoresByMerchantId?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateStore; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateStore; + + internal void ExecuteOnUpdateStore(AccountStoreLevelService.UpdateStoreApiResponse apiResponse) + { + OnUpdateStore?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateStore(Exception exception) + { + OnErrorUpdateStore?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateStoreById; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateStoreById; + + internal void ExecuteOnUpdateStoreById(AccountStoreLevelService.UpdateStoreByIdApiResponse apiResponse) + { + OnUpdateStoreById?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateStoreById(Exception exception) + { + OnErrorUpdateStoreById?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AccountStoreLevelService : IAccountStoreLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AccountStoreLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AccountStoreLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AccountStoreLevelServiceEvents accountStoreLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = accountStoreLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a store Creates a store for the merchant account specified in the request. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateStoreAsync(StoreCreationWithMerchantCodeRequest storeCreationWithMerchantCodeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storeCreationWithMerchantCodeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storeCreationWithMerchantCodeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateStoreApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateStore(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateStore(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateStoreApiResponse : Adyen.Core.Client.ApiResponse, ICreateStoreApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a store Creates a store for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateStoreByMerchantIdAsync(string merchantId, StoreCreationRequest storeCreationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storeCreationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storeCreationRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateStoreByMerchantIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateStoreByMerchantId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateStoreByMerchantId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateStoreByMerchantIdApiResponse : Adyen.Core.Client.ApiResponse, ICreateStoreByMerchantIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateStoreByMerchantIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateStoreByMerchantIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a store Returns the details of the store identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetStoreAsync(string merchantId, string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{storeId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{storeId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetStoreApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{storeId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetStore(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetStore(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetStoreApiResponse : Adyen.Core.Client.ApiResponse, IGetStoreApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a store Returns the details of the store identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetStoreByIdAsync(string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetStoreByIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetStoreById(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetStoreById(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetStoreByIdApiResponse : Adyen.Core.Client.ApiResponse, IGetStoreByIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetStoreByIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetStoreByIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of stores Returns a list of stores. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// The reference of the store. () + /// The unique identifier of the merchant account. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListStoresAsync(Option pageNumber = default, Option pageSize = default, Option reference = default, Option merchantId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (reference.IsSet) + parseQueryString["reference"] = ClientUtils.ParameterToString(reference.Value); + + if (merchantId.IsSet) + parseQueryString["merchantId"] = ClientUtils.ParameterToString(merchantId.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListStoresApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListStores(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListStores(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListStoresApiResponse : Adyen.Core.Client.ApiResponse, IListStoresApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListStoresApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListStoresApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListStoresResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListStoresResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of stores Returns a list of stores for the merchant account identified in the path. The list is grouped into pages as defined by the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// The reference of the store. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListStoresByMerchantIdAsync(string merchantId, Option pageNumber = default, Option pageSize = default, Option reference = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (reference.IsSet) + parseQueryString["reference"] = ClientUtils.ParameterToString(reference.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListStoresByMerchantIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListStoresByMerchantId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListStoresByMerchantId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListStoresByMerchantIdApiResponse : Adyen.Core.Client.ApiResponse, IListStoresByMerchantIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListStoresByMerchantIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListStoresByMerchantIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListStoresResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListStoresResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a store Updates the store identified in the path. You can only update some store parameters. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateStoreAsync(string merchantId, string storeId, UpdateStoreRequest updateStoreRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{storeId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{storeId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateStoreRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateStoreRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateStoreApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{storeId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateStore(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateStore(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateStoreApiResponse : Adyen.Core.Client.ApiResponse, IUpdateStoreApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a store Updates the store identified in the path. You can only update some store parameters. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Stores read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateStoreByIdAsync(string storeId, UpdateStoreRequest updateStoreRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateStoreRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateStoreRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateStoreByIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateStoreById(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateStoreById(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateStoreByIdApiResponse : Adyen.Core.Client.ApiResponse, IUpdateStoreByIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateStoreByIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateStoreByIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Store? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Store? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/AllowedOriginsCompanyLevelService.cs b/Adyen/Management/Services/AllowedOriginsCompanyLevelService.cs new file mode 100644 index 000000000..5d6c88f0a --- /dev/null +++ b/Adyen/Management/Services/AllowedOriginsCompanyLevelService.cs @@ -0,0 +1,1817 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAllowedOriginsCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AllowedOriginsCompanyLevelServiceEvents Events { get; } + + /// + /// Create an allowed origin + /// + /// + /// Adds a new [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) to the API credential's list of allowed origins. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// + /// . + /// . + /// of . + Task CreateAllowedOriginAsync(string companyId, string apiCredentialId, AllowedOrigin allowedOrigin, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete an allowed origin + /// + /// + /// Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. As soon as an allowed origin is removed, we no longer accept client-side requests from that domain. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task DeleteAllowedOriginAsync(string companyId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an allowed origin + /// + /// + /// Returns the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task GetAllowedOriginAsync(string companyId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of allowed origins + /// + /// + /// Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task ListAllowedOriginsAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateAllowedOriginApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteAllowedOriginApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllowedOriginApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListAllowedOriginsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AllowedOriginsCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateAllowedOrigin; + + internal void ExecuteOnCreateAllowedOrigin(AllowedOriginsCompanyLevelService.CreateAllowedOriginApiResponse apiResponse) + { + OnCreateAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateAllowedOrigin(Exception exception) + { + OnErrorCreateAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteAllowedOrigin; + + internal void ExecuteOnDeleteAllowedOrigin(AllowedOriginsCompanyLevelService.DeleteAllowedOriginApiResponse apiResponse) + { + OnDeleteAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteAllowedOrigin(Exception exception) + { + OnErrorDeleteAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllowedOrigin; + + internal void ExecuteOnGetAllowedOrigin(AllowedOriginsCompanyLevelService.GetAllowedOriginApiResponse apiResponse) + { + OnGetAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllowedOrigin(Exception exception) + { + OnErrorGetAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAllowedOrigins; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAllowedOrigins; + + internal void ExecuteOnListAllowedOrigins(AllowedOriginsCompanyLevelService.ListAllowedOriginsApiResponse apiResponse) + { + OnListAllowedOrigins?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAllowedOrigins(Exception exception) + { + OnErrorListAllowedOrigins?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AllowedOriginsCompanyLevelService : IAllowedOriginsCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AllowedOriginsCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AllowedOriginsCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AllowedOriginsCompanyLevelServiceEvents allowedOriginsCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = allowedOriginsCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an allowed origin Adds a new [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) to the API credential's list of allowed origins. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateAllowedOriginAsync(string companyId, string apiCredentialId, AllowedOrigin allowedOrigin, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (allowedOrigin as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(allowedOrigin, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateAllowedOrigin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateAllowedOriginApiResponse : Adyen.Core.Client.ApiResponse, ICreateAllowedOriginApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOrigin? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOrigin? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete an allowed origin Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. As soon as an allowed origin is removed, we no longer accept client-side requests from that domain. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteAllowedOriginAsync(string companyId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteAllowedOrigin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteAllowedOriginApiResponse : Adyen.Core.Client.ApiResponse, IDeleteAllowedOriginApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an allowed origin Returns the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllowedOriginAsync(string companyId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllowedOrigin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllowedOriginApiResponse : Adyen.Core.Client.ApiResponse, IGetAllowedOriginApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOrigin? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOrigin? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of allowed origins Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAllowedOriginsAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListAllowedOriginsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAllowedOrigins(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAllowedOrigins(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListAllowedOriginsApiResponse : Adyen.Core.Client.ApiResponse, IListAllowedOriginsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAllowedOriginsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAllowedOriginsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOriginsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOriginsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/AllowedOriginsMerchantLevelService.cs b/Adyen/Management/Services/AllowedOriginsMerchantLevelService.cs new file mode 100644 index 000000000..745ddcdd5 --- /dev/null +++ b/Adyen/Management/Services/AllowedOriginsMerchantLevelService.cs @@ -0,0 +1,545 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAllowedOriginsMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AllowedOriginsMerchantLevelServiceEvents Events { get; } + + /// + /// Create an allowed origin + /// + /// + /// Adds a new [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) to the API credential's list of allowed origins. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// + /// . + /// . + /// of . + Task CreateAllowedOriginAsync(string merchantId, string apiCredentialId, AllowedOrigin allowedOrigin, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete an allowed origin + /// + /// + /// Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. As soon as an allowed origin is removed, we no longer accept client-side requests from that domain. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task DeleteAllowedOriginAsync(string merchantId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an allowed origin + /// + /// + /// Returns the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task GetAllowedOriginAsync(string merchantId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of allowed origins + /// + /// + /// Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task ListAllowedOriginsAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AllowedOriginsMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateAllowedOrigin; + + internal void ExecuteOnCreateAllowedOrigin(AllowedOriginsCompanyLevelService.CreateAllowedOriginApiResponse apiResponse) + { + OnCreateAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateAllowedOrigin(Exception exception) + { + OnErrorCreateAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteAllowedOrigin; + + internal void ExecuteOnDeleteAllowedOrigin(AllowedOriginsCompanyLevelService.DeleteAllowedOriginApiResponse apiResponse) + { + OnDeleteAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteAllowedOrigin(Exception exception) + { + OnErrorDeleteAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllowedOrigin; + + internal void ExecuteOnGetAllowedOrigin(AllowedOriginsCompanyLevelService.GetAllowedOriginApiResponse apiResponse) + { + OnGetAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllowedOrigin(Exception exception) + { + OnErrorGetAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAllowedOrigins; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAllowedOrigins; + + internal void ExecuteOnListAllowedOrigins(AllowedOriginsCompanyLevelService.ListAllowedOriginsApiResponse apiResponse) + { + OnListAllowedOrigins?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAllowedOrigins(Exception exception) + { + OnErrorListAllowedOrigins?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AllowedOriginsMerchantLevelService : IAllowedOriginsMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AllowedOriginsMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AllowedOriginsMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AllowedOriginsMerchantLevelServiceEvents allowedOriginsMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = allowedOriginsMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an allowed origin Adds a new [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) to the API credential's list of allowed origins. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateAllowedOriginAsync(string merchantId, string apiCredentialId, AllowedOrigin allowedOrigin, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (allowedOrigin as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(allowedOrigin, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AllowedOriginsCompanyLevelService.CreateAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateAllowedOrigin(exception); + throw; + } + } + /// + /// Delete an allowed origin Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. As soon as an allowed origin is removed, we no longer accept client-side requests from that domain. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteAllowedOriginAsync(string merchantId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AllowedOriginsCompanyLevelService.DeleteAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteAllowedOrigin(exception); + throw; + } + } + /// + /// Get an allowed origin Returns the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllowedOriginAsync(string merchantId, string apiCredentialId, string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AllowedOriginsCompanyLevelService.GetAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllowedOrigin(exception); + throw; + } + } + /// + /// Get a list of allowed origins Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) for the API credential identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAllowedOriginsAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AllowedOriginsCompanyLevelService.ListAllowedOriginsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAllowedOrigins(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAllowedOrigins(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/AndroidFilesCompanyLevelService.cs b/Adyen/Management/Services/AndroidFilesCompanyLevelService.cs new file mode 100644 index 000000000..7aab9a563 --- /dev/null +++ b/Adyen/Management/Services/AndroidFilesCompanyLevelService.cs @@ -0,0 +1,2720 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IAndroidFilesCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + AndroidFilesCompanyLevelServiceEvents Events { get; } + + /// + /// Get Android app + /// + /// + /// Returns the details of the Android app identified in the path. These apps have been uploaded to Adyen and can be installed or uninstalled on Android payment terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the app. + /// . + /// . + /// of . + Task GetAndroidAppAsync(string companyId, string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of Android apps + /// + /// + /// Returns a list of the Android apps that are available for the company identified in the path. These apps have been uploaded to Adyen and can be installed or uninstalled on Android payment terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. + /// The package name that uniquely identifies the Android app. + /// The version number of the app. + /// . + /// . + /// of . + Task ListAndroidAppsAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option packageName = default, Option versionCode = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of Android certificates + /// + /// + /// Returns a list of the Android certificates that are available for the company identified in the path. Typically, these certificates enable running apps on Android payment terminals. The certificates in the list have been uploaded to Adyen and can be installed or uninstalled on Android terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. + /// The name of the certificate. + /// . + /// . + /// of . + Task ListAndroidCertificatesAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option certificateName = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Reprocess Android App + /// + /// + /// Reuploads the Android app identified in the path. To make this request, your API credential must have this [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). >By choosing to upload, install, or run any third-party applications on an Adyen payment terminal, you accept full responsibility and liability for any consequences of uploading, installing, or running any such applications. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the app. + /// . + /// . + /// of . + Task ReprocessAndroidAppAsync(string companyId, string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Upload Android App + /// + /// + /// Uploads an Android APK file to Adyen. The maximum APK file size is 200 MB. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). >By choosing to upload, install, or run any third-party applications on an Adyen payment terminal, you accept full responsibility and liability for any consequences of uploading, installing, or running any such applications. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of . + Task UploadAndroidAppAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Upload Android Certificate + /// + /// + /// Uploads an Android Certificate file to Adyen. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of . + Task UploadAndroidCertificateAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetAndroidAppApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListAndroidAppsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListAndroidCertificatesApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IReprocessAndroidAppApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUploadAndroidAppApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUploadAndroidCertificateApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class AndroidFilesCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAndroidApp; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAndroidApp; + + internal void ExecuteOnGetAndroidApp(AndroidFilesCompanyLevelService.GetAndroidAppApiResponse apiResponse) + { + OnGetAndroidApp?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAndroidApp(Exception exception) + { + OnErrorGetAndroidApp?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAndroidApps; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAndroidApps; + + internal void ExecuteOnListAndroidApps(AndroidFilesCompanyLevelService.ListAndroidAppsApiResponse apiResponse) + { + OnListAndroidApps?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAndroidApps(Exception exception) + { + OnErrorListAndroidApps?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAndroidCertificates; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAndroidCertificates; + + internal void ExecuteOnListAndroidCertificates(AndroidFilesCompanyLevelService.ListAndroidCertificatesApiResponse apiResponse) + { + OnListAndroidCertificates?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAndroidCertificates(Exception exception) + { + OnErrorListAndroidCertificates?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnReprocessAndroidApp; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorReprocessAndroidApp; + + internal void ExecuteOnReprocessAndroidApp(AndroidFilesCompanyLevelService.ReprocessAndroidAppApiResponse apiResponse) + { + OnReprocessAndroidApp?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorReprocessAndroidApp(Exception exception) + { + OnErrorReprocessAndroidApp?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUploadAndroidApp; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUploadAndroidApp; + + internal void ExecuteOnUploadAndroidApp(AndroidFilesCompanyLevelService.UploadAndroidAppApiResponse apiResponse) + { + OnUploadAndroidApp?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUploadAndroidApp(Exception exception) + { + OnErrorUploadAndroidApp?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUploadAndroidCertificate; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUploadAndroidCertificate; + + internal void ExecuteOnUploadAndroidCertificate(AndroidFilesCompanyLevelService.UploadAndroidCertificateApiResponse apiResponse) + { + OnUploadAndroidCertificate?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUploadAndroidCertificate(Exception exception) + { + OnErrorUploadAndroidCertificate?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class AndroidFilesCompanyLevelService : IAndroidFilesCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public AndroidFilesCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public AndroidFilesCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, AndroidFilesCompanyLevelServiceEvents androidFilesCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = androidFilesCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get Android app Returns the details of the Android app identified in the path. These apps have been uploaded to Adyen and can be installed or uninstalled on Android payment terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the app. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAndroidAppAsync(string companyId, string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidApps/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidApps/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAndroidAppApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidApps/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAndroidApp(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAndroidApp(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAndroidAppApiResponse : Adyen.Core.Client.ApiResponse, IGetAndroidAppApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AndroidApp? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AndroidApp? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of Android apps Returns a list of the Android apps that are available for the company identified in the path. These apps have been uploaded to Adyen and can be installed or uninstalled on Android payment terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. () + /// The package name that uniquely identifies the Android app. () + /// The version number of the app. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAndroidAppsAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option packageName = default, Option versionCode = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidApps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidApps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (packageName.IsSet) + parseQueryString["packageName"] = ClientUtils.ParameterToString(packageName.Value); + + if (versionCode.IsSet) + parseQueryString["versionCode"] = ClientUtils.ParameterToString(versionCode.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListAndroidAppsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidApps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAndroidApps(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAndroidApps(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListAndroidAppsApiResponse : Adyen.Core.Client.ApiResponse, IListAndroidAppsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAndroidAppsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAndroidAppsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AndroidAppsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AndroidAppsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of Android certificates Returns a list of the Android certificates that are available for the company identified in the path. Typically, these certificates enable running apps on Android payment terminals. The certificates in the list have been uploaded to Adyen and can be installed or uninstalled on Android terminals through [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read * Management API—Android files read and write * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. () + /// The name of the certificate. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAndroidCertificatesAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option certificateName = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidCertificates" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidCertificates"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (certificateName.IsSet) + parseQueryString["certificateName"] = ClientUtils.ParameterToString(certificateName.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListAndroidCertificatesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidCertificates", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAndroidCertificates(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAndroidCertificates(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListAndroidCertificatesApiResponse : Adyen.Core.Client.ApiResponse, IListAndroidCertificatesApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAndroidCertificatesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAndroidCertificatesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AndroidCertificatesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AndroidCertificatesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Reprocess Android App Reuploads the Android app identified in the path. To make this request, your API credential must have this [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). >By choosing to upload, install, or run any third-party applications on an Adyen payment terminal, you accept full responsibility and liability for any consequences of uploading, installing, or running any such applications. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the app. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ReprocessAndroidAppAsync(string companyId, string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidApps/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidApps/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ReprocessAndroidAppApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidApps/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnReprocessAndroidApp(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorReprocessAndroidApp(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ReprocessAndroidAppApiResponse : Adyen.Core.Client.ApiResponse, IReprocessAndroidAppApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReprocessAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReprocessAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ReprocessAndroidAppResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ReprocessAndroidAppResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Upload Android App Uploads an Android APK file to Adyen. The maximum APK file size is 200 MB. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Android files read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). >By choosing to upload, install, or run any third-party applications on an Adyen payment terminal, you accept full responsibility and liability for any consequences of uploading, installing, or running any such applications. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UploadAndroidAppAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidApps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidApps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UploadAndroidAppApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidApps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUploadAndroidApp(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUploadAndroidApp(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UploadAndroidAppApiResponse : Adyen.Core.Client.ApiResponse, IUploadAndroidAppApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadAndroidAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.UploadAndroidAppResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.UploadAndroidAppResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Upload Android Certificate Uploads an Android Certificate file to Adyen. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UploadAndroidCertificateAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/androidCertificates" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/androidCertificates"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UploadAndroidCertificateApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/androidCertificates", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUploadAndroidCertificate(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUploadAndroidCertificate(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UploadAndroidCertificateApiResponse : Adyen.Core.Client.ApiResponse, IUploadAndroidCertificateApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadAndroidCertificateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UploadAndroidCertificateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.UploadAndroidCertificateResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.UploadAndroidCertificateResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/ClientKeyCompanyLevelService.cs b/Adyen/Management/Services/ClientKeyCompanyLevelService.cs new file mode 100644 index 000000000..402952b8b --- /dev/null +++ b/Adyen/Management/Services/ClientKeyCompanyLevelService.cs @@ -0,0 +1,529 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IClientKeyCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ClientKeyCompanyLevelServiceEvents Events { get; } + + /// + /// Generate new client key + /// + /// + /// Returns a new [client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works) for the API credential identified in the path. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GenerateNewClientKeyAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGenerateNewClientKeyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ClientKeyCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateNewClientKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateNewClientKey; + + internal void ExecuteOnGenerateNewClientKey(ClientKeyCompanyLevelService.GenerateNewClientKeyApiResponse apiResponse) + { + OnGenerateNewClientKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateNewClientKey(Exception exception) + { + OnErrorGenerateNewClientKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ClientKeyCompanyLevelService : IClientKeyCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ClientKeyCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ClientKeyCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ClientKeyCompanyLevelServiceEvents clientKeyCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = clientKeyCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate new client key Returns a new [client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works) for the API credential identified in the path. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateNewClientKeyAsync(string companyId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateClientKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateClientKey"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GenerateNewClientKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/apiCredentials/{apiCredentialId}/generateClientKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateNewClientKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateNewClientKey(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GenerateNewClientKeyApiResponse : Adyen.Core.Client.ApiResponse, IGenerateNewClientKeyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateNewClientKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateNewClientKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.GenerateClientKeyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.GenerateClientKeyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/ClientKeyMerchantLevelService.cs b/Adyen/Management/Services/ClientKeyMerchantLevelService.cs new file mode 100644 index 000000000..4fb2fd245 --- /dev/null +++ b/Adyen/Management/Services/ClientKeyMerchantLevelService.cs @@ -0,0 +1,203 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IClientKeyMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ClientKeyMerchantLevelServiceEvents Events { get; } + + /// + /// Generate new client key + /// + /// + /// Returns a new [client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works) for the API credential identified in the path. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of . + Task GenerateNewClientKeyAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ClientKeyMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateNewClientKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateNewClientKey; + + internal void ExecuteOnGenerateNewClientKey(ClientKeyCompanyLevelService.GenerateNewClientKeyApiResponse apiResponse) + { + OnGenerateNewClientKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateNewClientKey(Exception exception) + { + OnErrorGenerateNewClientKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ClientKeyMerchantLevelService : IClientKeyMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ClientKeyMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ClientKeyMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ClientKeyMerchantLevelServiceEvents clientKeyMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = clientKeyMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate new client key Returns a new [client key](https://docs.adyen.com/development-resources/client-side-authentication#how-it-works) for the API credential identified in the path. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the API credential. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateNewClientKeyAsync(string merchantId, string apiCredentialId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateClientKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateClientKey"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BapiCredentialId%7D", Uri.EscapeDataString(apiCredentialId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ClientKeyCompanyLevelService.GenerateNewClientKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateClientKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateNewClientKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateNewClientKey(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/MyAPICredentialService.cs b/Adyen/Management/Services/MyAPICredentialService.cs new file mode 100644 index 000000000..7ba1136ce --- /dev/null +++ b/Adyen/Management/Services/MyAPICredentialService.cs @@ -0,0 +1,2645 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IMyAPICredentialService : IAdyenApiService + { + /// + /// The class containing the events. + /// + MyAPICredentialServiceEvents Events { get; } + + /// + /// Add allowed origin + /// + /// + /// Adds an allowed origin to the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) of your API credential. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task AddAllowedOriginAsync(CreateAllowedOriginRequest createAllowedOriginRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Generate a client key + /// + /// + /// Generates a new [client key](https://docs.adyen.com/development-resources/client-side-authentication/) used to authenticate requests from your payment environment. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of . + Task GenerateClientKeyAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get allowed origin details + /// + /// + /// Returns the details of the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) specified in the path. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task GetAllowedOriginDetailsAsync(string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get allowed origins + /// + /// + /// Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) of your [API credential](https://docs.adyen.com/development-resources/api-credentials) based on the API key you used in the request. You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of . + Task GetAllowedOriginsAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get API credential details + /// + /// + /// Returns your [API credential](https://docs.adyen.com/development-resources/api-credentials) details based on the API Key you used in the request. You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of . + Task GetApiCredentialDetailsAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove allowed origin + /// + /// + /// Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) specified in the path. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of . + Task RemoveAllowedOriginAsync(string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAddAllowedOriginApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGenerateClientKeyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllowedOriginDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllowedOriginsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetApiCredentialDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRemoveAllowedOriginApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class MyAPICredentialServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAddAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAddAllowedOrigin; + + internal void ExecuteOnAddAllowedOrigin(MyAPICredentialService.AddAllowedOriginApiResponse apiResponse) + { + OnAddAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddAllowedOrigin(Exception exception) + { + OnErrorAddAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateClientKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateClientKey; + + internal void ExecuteOnGenerateClientKey(MyAPICredentialService.GenerateClientKeyApiResponse apiResponse) + { + OnGenerateClientKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateClientKey(Exception exception) + { + OnErrorGenerateClientKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllowedOriginDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllowedOriginDetails; + + internal void ExecuteOnGetAllowedOriginDetails(MyAPICredentialService.GetAllowedOriginDetailsApiResponse apiResponse) + { + OnGetAllowedOriginDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllowedOriginDetails(Exception exception) + { + OnErrorGetAllowedOriginDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllowedOrigins; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllowedOrigins; + + internal void ExecuteOnGetAllowedOrigins(MyAPICredentialService.GetAllowedOriginsApiResponse apiResponse) + { + OnGetAllowedOrigins?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllowedOrigins(Exception exception) + { + OnErrorGetAllowedOrigins?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetApiCredentialDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetApiCredentialDetails; + + internal void ExecuteOnGetApiCredentialDetails(MyAPICredentialService.GetApiCredentialDetailsApiResponse apiResponse) + { + OnGetApiCredentialDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetApiCredentialDetails(Exception exception) + { + OnErrorGetApiCredentialDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRemoveAllowedOrigin; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRemoveAllowedOrigin; + + internal void ExecuteOnRemoveAllowedOrigin(MyAPICredentialService.RemoveAllowedOriginApiResponse apiResponse) + { + OnRemoveAllowedOrigin?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveAllowedOrigin(Exception exception) + { + OnErrorRemoveAllowedOrigin?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class MyAPICredentialService : IMyAPICredentialService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public MyAPICredentialServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public MyAPICredentialService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, MyAPICredentialServiceEvents myAPICredentialServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = myAPICredentialServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Add allowed origin Adds an allowed origin to the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) of your API credential. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AddAllowedOriginAsync(CreateAllowedOriginRequest createAllowedOriginRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me/allowedOrigins"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createAllowedOriginRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createAllowedOriginRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AddAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAddAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAddAllowedOrigin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AddAllowedOriginApiResponse : Adyen.Core.Client.ApiResponse, IAddAllowedOriginApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOrigin? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOrigin? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Generate a client key Generates a new [client key](https://docs.adyen.com/development-resources/client-side-authentication/) used to authenticate requests from your payment environment. You can use the new client key a few minutes after generating it. The old client key stops working 24 hours after generating a new one. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—API credentials read and write + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateClientKeyAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me/generateClientKey" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me/generateClientKey"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GenerateClientKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me/generateClientKey", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateClientKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateClientKey(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GenerateClientKeyApiResponse : Adyen.Core.Client.ApiResponse, IGenerateClientKeyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateClientKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateClientKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.GenerateClientKeyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.GenerateClientKeyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get allowed origin details Returns the details of the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) specified in the path. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllowedOriginDetailsAsync(string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllowedOriginDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllowedOriginDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllowedOriginDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllowedOriginDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetAllowedOriginDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOrigin? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOrigin? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get allowed origins Returns the list of [allowed origins](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) of your [API credential](https://docs.adyen.com/development-resources/api-credentials) based on the API key you used in the request. You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllowedOriginsAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me/allowedOrigins" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me/allowedOrigins"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllowedOriginsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me/allowedOrigins", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllowedOrigins(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllowedOrigins(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllowedOriginsApiResponse : Adyen.Core.Client.ApiResponse, IGetAllowedOriginsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllowedOriginsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.AllowedOriginsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.AllowedOriginsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get API credential details Returns your [API credential](https://docs.adyen.com/development-resources/api-credentials) details based on the API Key you used in the request. You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetApiCredentialDetailsAsync( RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetApiCredentialDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetApiCredentialDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetApiCredentialDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetApiCredentialDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetApiCredentialDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApiCredentialDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApiCredentialDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.MeApiCredential? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.MeApiCredential? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Remove allowed origin Removes the [allowed origin](https://docs.adyen.com/development-resources/client-side-authentication#allowed-origins) specified in the path. The API key from the request is used to identify the [API credential](https://docs.adyen.com/development-resources/api-credentials). You can make this request with any of the Management API roles. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the allowed origin. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RemoveAllowedOriginAsync(string originId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/me/allowedOrigins/{originId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/me/allowedOrigins/{originId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BoriginId%7D", Uri.EscapeDataString(originId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RemoveAllowedOriginApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/me/allowedOrigins/{originId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRemoveAllowedOrigin(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRemoveAllowedOrigin(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RemoveAllowedOriginApiResponse : Adyen.Core.Client.ApiResponse, IRemoveAllowedOriginApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveAllowedOriginApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/PaymentMethodsMerchantLevelService.cs b/Adyen/Management/Services/PaymentMethodsMerchantLevelService.cs new file mode 100644 index 000000000..01cdf9e69 --- /dev/null +++ b/Adyen/Management/Services/PaymentMethodsMerchantLevelService.cs @@ -0,0 +1,3009 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentMethodsMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentMethodsMerchantLevelServiceEvents Events { get; } + + /// + /// Add an Apple Pay domain + /// + /// + /// Adds the new domain to the list of Apple Pay domains that are registered with the merchant account and the payment method identified in the path. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/web-drop-in/?tab=adyen-certificate-live_1#going-live). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// + /// . + /// . + /// of . + Task AddApplePayDomainAsync(string merchantId, string paymentMethodId, ApplePayInfo applePayInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all payment methods + /// + /// + /// Returns details for all payment methods of the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store for which to return the payment methods. + /// The unique identifier of the Business Line for which to return the payment methods. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// The number of the page to fetch. + /// . + /// . + /// of . + Task GetAllPaymentMethodsAsync(string merchantId, Option storeId = default, Option businessLineId = default, Option pageSize = default, Option pageNumber = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get Apple Pay domains + /// + /// + /// Returns all Apple Pay domains that are registered with the merchant account and the payment method identified in the path. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/enable-apple-pay#register-merchant-domain). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// . + /// . + /// of . + Task GetApplePayDomainsAsync(string merchantId, string paymentMethodId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get payment method details + /// + /// + /// Returns details for the merchant account and the payment method identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// . + /// . + /// of . + Task GetPaymentMethodDetailsAsync(string merchantId, string paymentMethodId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Request a payment method + /// + /// + /// Sends a request to add a new payment method to the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task RequestPaymentMethodAsync(string merchantId, PaymentMethodSetupInfo paymentMethodSetupInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a payment method + /// + /// + /// Updates payment method details for the merchant account and the payment method identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// + /// . + /// . + /// of . + Task UpdatePaymentMethodAsync(string merchantId, string paymentMethodId, UpdatePaymentMethodInfo updatePaymentMethodInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAddApplePayDomainApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, ITooManyRequests, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + bool IsTooManyRequests { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllPaymentMethodsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, ITooManyRequests, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + bool IsTooManyRequests { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetApplePayDomainsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPaymentMethodDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, ITooManyRequests, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + bool IsTooManyRequests { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRequestPaymentMethodApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, ITooManyRequests, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + bool IsTooManyRequests { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdatePaymentMethodApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, ITooManyRequests, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + bool IsTooManyRequests { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentMethodsMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAddApplePayDomain; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAddApplePayDomain; + + internal void ExecuteOnAddApplePayDomain(PaymentMethodsMerchantLevelService.AddApplePayDomainApiResponse apiResponse) + { + OnAddApplePayDomain?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddApplePayDomain(Exception exception) + { + OnErrorAddApplePayDomain?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllPaymentMethods; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllPaymentMethods; + + internal void ExecuteOnGetAllPaymentMethods(PaymentMethodsMerchantLevelService.GetAllPaymentMethodsApiResponse apiResponse) + { + OnGetAllPaymentMethods?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllPaymentMethods(Exception exception) + { + OnErrorGetAllPaymentMethods?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetApplePayDomains; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetApplePayDomains; + + internal void ExecuteOnGetApplePayDomains(PaymentMethodsMerchantLevelService.GetApplePayDomainsApiResponse apiResponse) + { + OnGetApplePayDomains?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetApplePayDomains(Exception exception) + { + OnErrorGetApplePayDomains?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPaymentMethodDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPaymentMethodDetails; + + internal void ExecuteOnGetPaymentMethodDetails(PaymentMethodsMerchantLevelService.GetPaymentMethodDetailsApiResponse apiResponse) + { + OnGetPaymentMethodDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPaymentMethodDetails(Exception exception) + { + OnErrorGetPaymentMethodDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRequestPaymentMethod; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRequestPaymentMethod; + + internal void ExecuteOnRequestPaymentMethod(PaymentMethodsMerchantLevelService.RequestPaymentMethodApiResponse apiResponse) + { + OnRequestPaymentMethod?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRequestPaymentMethod(Exception exception) + { + OnErrorRequestPaymentMethod?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdatePaymentMethod; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdatePaymentMethod; + + internal void ExecuteOnUpdatePaymentMethod(PaymentMethodsMerchantLevelService.UpdatePaymentMethodApiResponse apiResponse) + { + OnUpdatePaymentMethod?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePaymentMethod(Exception exception) + { + OnErrorUpdatePaymentMethod?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentMethodsMerchantLevelService : IPaymentMethodsMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentMethodsMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentMethodsMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentMethodsMerchantLevelServiceEvents paymentMethodsMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentMethodsMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Add an Apple Pay domain Adds the new domain to the list of Apple Pay domains that are registered with the merchant account and the payment method identified in the path. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/web-drop-in/?tab=adyen-certificate-live_1#going-live). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AddApplePayDomainAsync(string merchantId, string paymentMethodId, ApplePayInfo applePayInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/addApplePayDomains" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/addApplePayDomains"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentMethodId%7D", Uri.EscapeDataString(paymentMethodId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (applePayInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(applePayInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AddApplePayDomainApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/addApplePayDomains", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAddApplePayDomain(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAddApplePayDomain(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AddApplePayDomainApiResponse : Adyen.Core.Client.ApiResponse, IAddApplePayDomainApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddApplePayDomainApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddApplePayDomainApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + public bool IsTooManyRequests => 429 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 429 TooManyRequests. + /// + /// + public Adyen.Management.Models.RestServiceError? TooManyRequests() + { + return IsTooManyRequests + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 429 TooManyRequests and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = TooManyRequests(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)429); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all payment methods Returns details for all payment methods of the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store for which to return the payment methods. () + /// The unique identifier of the Business Line for which to return the payment methods. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// The number of the page to fetch. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllPaymentMethodsAsync(string merchantId, Option storeId = default, Option businessLineId = default, Option pageSize = default, Option pageNumber = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (storeId.IsSet) + parseQueryString["storeId"] = ClientUtils.ParameterToString(storeId.Value); + + if (businessLineId.IsSet) + parseQueryString["businessLineId"] = ClientUtils.ParameterToString(businessLineId.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllPaymentMethodsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllPaymentMethods(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllPaymentMethods(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllPaymentMethodsApiResponse : Adyen.Core.Client.ApiResponse, IGetAllPaymentMethodsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllPaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllPaymentMethodsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PaymentMethodResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PaymentMethodResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + public bool IsTooManyRequests => 429 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 429 TooManyRequests. + /// + /// + public Adyen.Management.Models.RestServiceError? TooManyRequests() + { + return IsTooManyRequests + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 429 TooManyRequests and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = TooManyRequests(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)429); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get Apple Pay domains Returns all Apple Pay domains that are registered with the merchant account and the payment method identified in the path. For more information, see [Apple Pay documentation](https://docs.adyen.com/payment-methods/apple-pay/enable-apple-pay#register-merchant-domain). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetApplePayDomainsAsync(string merchantId, string paymentMethodId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/getApplePayDomains" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/getApplePayDomains"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentMethodId%7D", Uri.EscapeDataString(paymentMethodId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetApplePayDomainsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/getApplePayDomains", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetApplePayDomains(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetApplePayDomains(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetApplePayDomainsApiResponse : Adyen.Core.Client.ApiResponse, IGetApplePayDomainsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApplePayDomainsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetApplePayDomainsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ApplePayInfo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ApplePayInfo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get payment method details Returns details for the merchant account and the payment method identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPaymentMethodDetailsAsync(string merchantId, string paymentMethodId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentMethodId%7D", Uri.EscapeDataString(paymentMethodId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPaymentMethodDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPaymentMethodDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPaymentMethodDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPaymentMethodDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetPaymentMethodDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentMethodDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPaymentMethodDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PaymentMethod? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PaymentMethod? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + public bool IsTooManyRequests => 429 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 429 TooManyRequests. + /// + /// + public Adyen.Management.Models.RestServiceError? TooManyRequests() + { + return IsTooManyRequests + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 429 TooManyRequests and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = TooManyRequests(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)429); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Request a payment method Sends a request to add a new payment method to the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RequestPaymentMethodAsync(string merchantId, PaymentMethodSetupInfo paymentMethodSetupInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentMethodSetupInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentMethodSetupInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RequestPaymentMethodApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRequestPaymentMethod(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRequestPaymentMethod(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RequestPaymentMethodApiResponse : Adyen.Core.Client.ApiResponse, IRequestPaymentMethodApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestPaymentMethodApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestPaymentMethodApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PaymentMethod? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PaymentMethod? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + public bool IsTooManyRequests => 429 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 429 TooManyRequests. + /// + /// + public Adyen.Management.Models.RestServiceError? TooManyRequests() + { + return IsTooManyRequests + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 429 TooManyRequests and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = TooManyRequests(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)429); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a payment method Updates payment method details for the merchant account and the payment method identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payment methods read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payment method. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdatePaymentMethodAsync(string merchantId, string paymentMethodId, UpdatePaymentMethodInfo updatePaymentMethodInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpaymentMethodId%7D", Uri.EscapeDataString(paymentMethodId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updatePaymentMethodInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updatePaymentMethodInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdatePaymentMethodApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdatePaymentMethod(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdatePaymentMethod(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdatePaymentMethodApiResponse : Adyen.Core.Client.ApiResponse, IUpdatePaymentMethodApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentMethodApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePaymentMethodApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PaymentMethod? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PaymentMethod? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 429 TooManyRequests. + /// + /// + public bool IsTooManyRequests => 429 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 429 TooManyRequests. + /// + /// + public Adyen.Management.Models.RestServiceError? TooManyRequests() + { + return IsTooManyRequests + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 429 TooManyRequests and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeTooManyRequestsResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = TooManyRequests(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)429); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/PayoutSettingsMerchantLevelService.cs b/Adyen/Management/Services/PayoutSettingsMerchantLevelService.cs new file mode 100644 index 000000000..f201f64ca --- /dev/null +++ b/Adyen/Management/Services/PayoutSettingsMerchantLevelService.cs @@ -0,0 +1,2303 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPayoutSettingsMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PayoutSettingsMerchantLevelServiceEvents Events { get; } + + /// + /// Add a payout setting + /// + /// + /// Sends a request to add a payout setting for the merchant account specified in the path. A payout setting links the merchant account to the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the payout bank account. Adyen verifies the bank account before allowing and enabling the payout setting. If you're accepting payments in multiple currencies, you may add multiple payout settings for the merchant account. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task AddPayoutSettingAsync(string merchantId, PayoutSettingsRequest payoutSettingsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a payout setting + /// + /// + /// Deletes the payout setting identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// . + /// . + /// of . + Task DeletePayoutSettingAsync(string merchantId, string payoutSettingsId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a payout setting + /// + /// + /// Returns the payout setting identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// . + /// . + /// of . + Task GetPayoutSettingAsync(string merchantId, string payoutSettingsId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of payout settings + /// + /// + /// Returns the list of payout settings for the merchant account identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task ListPayoutSettingsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a payout setting + /// + /// + /// Updates the payout setting identified in the path. You can enable or disable the payout setting. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// + /// . + /// . + /// of . + Task UpdatePayoutSettingAsync(string merchantId, string payoutSettingsId, UpdatePayoutSettingsRequest updatePayoutSettingsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAddPayoutSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeletePayoutSettingApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetPayoutSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListPayoutSettingsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdatePayoutSettingApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PayoutSettingsMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAddPayoutSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAddPayoutSetting; + + internal void ExecuteOnAddPayoutSetting(PayoutSettingsMerchantLevelService.AddPayoutSettingApiResponse apiResponse) + { + OnAddPayoutSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddPayoutSetting(Exception exception) + { + OnErrorAddPayoutSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeletePayoutSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeletePayoutSetting; + + internal void ExecuteOnDeletePayoutSetting(PayoutSettingsMerchantLevelService.DeletePayoutSettingApiResponse apiResponse) + { + OnDeletePayoutSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeletePayoutSetting(Exception exception) + { + OnErrorDeletePayoutSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetPayoutSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetPayoutSetting; + + internal void ExecuteOnGetPayoutSetting(PayoutSettingsMerchantLevelService.GetPayoutSettingApiResponse apiResponse) + { + OnGetPayoutSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetPayoutSetting(Exception exception) + { + OnErrorGetPayoutSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListPayoutSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListPayoutSettings; + + internal void ExecuteOnListPayoutSettings(PayoutSettingsMerchantLevelService.ListPayoutSettingsApiResponse apiResponse) + { + OnListPayoutSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListPayoutSettings(Exception exception) + { + OnErrorListPayoutSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdatePayoutSetting; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdatePayoutSetting; + + internal void ExecuteOnUpdatePayoutSetting(PayoutSettingsMerchantLevelService.UpdatePayoutSettingApiResponse apiResponse) + { + OnUpdatePayoutSetting?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdatePayoutSetting(Exception exception) + { + OnErrorUpdatePayoutSetting?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PayoutSettingsMerchantLevelService : IPayoutSettingsMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PayoutSettingsMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PayoutSettingsMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PayoutSettingsMerchantLevelServiceEvents payoutSettingsMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = payoutSettingsMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Add a payout setting Sends a request to add a payout setting for the merchant account specified in the path. A payout setting links the merchant account to the [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) that contains the details of the payout bank account. Adyen verifies the bank account before allowing and enabling the payout setting. If you're accepting payments in multiple currencies, you may add multiple payout settings for the merchant account. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AddPayoutSettingAsync(string merchantId, PayoutSettingsRequest payoutSettingsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/payoutSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/payoutSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (payoutSettingsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(payoutSettingsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AddPayoutSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/payoutSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAddPayoutSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAddPayoutSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AddPayoutSettingApiResponse : Adyen.Core.Client.ApiResponse, IAddPayoutSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddPayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AddPayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PayoutSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PayoutSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a payout setting Deletes the payout setting identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeletePayoutSettingAsync(string merchantId, string payoutSettingsId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpayoutSettingsId%7D", Uri.EscapeDataString(payoutSettingsId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeletePayoutSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeletePayoutSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeletePayoutSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeletePayoutSettingApiResponse : Adyen.Core.Client.ApiResponse, IDeletePayoutSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeletePayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeletePayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a payout setting Returns the payout setting identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetPayoutSettingAsync(string merchantId, string payoutSettingsId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpayoutSettingsId%7D", Uri.EscapeDataString(payoutSettingsId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetPayoutSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetPayoutSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetPayoutSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetPayoutSettingApiResponse : Adyen.Core.Client.ApiResponse, IGetPayoutSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetPayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PayoutSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PayoutSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of payout settings Returns the list of payout settings for the merchant account identified in the path. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListPayoutSettingsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/payoutSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/payoutSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListPayoutSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/payoutSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListPayoutSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListPayoutSettings(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListPayoutSettingsApiResponse : Adyen.Core.Client.ApiResponse, IListPayoutSettingsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPayoutSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPayoutSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PayoutSettingsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PayoutSettingsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a payout setting Updates the payout setting identified in the path. You can enable or disable the payout setting. Use this endpoint if your integration requires it, such as Adyen for Platforms Manage. Your Adyen contact will set up your access. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Payout account settings read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the payout setting. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdatePayoutSettingAsync(string merchantId, string payoutSettingsId, UpdatePayoutSettingsRequest updatePayoutSettingsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BpayoutSettingsId%7D", Uri.EscapeDataString(payoutSettingsId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updatePayoutSettingsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updatePayoutSettingsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdatePayoutSettingApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/payoutSettings/{payoutSettingsId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdatePayoutSetting(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdatePayoutSetting(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdatePayoutSettingApiResponse : Adyen.Core.Client.ApiResponse, IUpdatePayoutSettingApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdatePayoutSettingApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.PayoutSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.PayoutSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/SplitConfigurationMerchantLevelService.cs b/Adyen/Management/Services/SplitConfigurationMerchantLevelService.cs new file mode 100644 index 000000000..cc9c81caf --- /dev/null +++ b/Adyen/Management/Services/SplitConfigurationMerchantLevelService.cs @@ -0,0 +1,4189 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ISplitConfigurationMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + SplitConfigurationMerchantLevelServiceEvents Events { get; } + + /// + /// Create a rule + /// + /// + /// [Creates a rule](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#create-rule) in the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// + /// . + /// . + /// of . + Task CreateRuleAsync(string merchantId, string splitConfigurationId, SplitConfigurationRule splitConfigurationRule, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a split configuration profile + /// + /// + /// Creates a split configuration profile to [split payments automatically](https://docs.adyen.com/platforms/automatic-split-configuration/). After you [associate it with a store](https://docs.adyen.com/api-explorer/Management/latest/patch/merchants/(merchantId)/stores/(storeId)#request-splitConfiguration) in your merchant account, it splits the funds of all transactions processed through that store between your liable balance account and [your user's balance account](https://docs.adyen.com/api-explorer/Management/latest/patch/merchants/(merchantId)/stores/(storeId)#request-splitConfiguration-balanceAccountId). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task CreateSplitConfigurationAsync(string merchantId, SplitConfiguration splitConfiguration, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a split configuration profile + /// + /// + /// Deletes the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// . + /// . + /// of . + Task DeleteSplitConfigurationAsync(string merchantId, string splitConfigurationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a rule + /// + /// + /// Deletes the rule specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// + /// . + /// . + /// of . + Task DeleteSplitConfigurationRuleAsync(string merchantId, string splitConfigurationId, string ruleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a split configuration profile + /// + /// + /// Returns the details of the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// . + /// . + /// of . + Task GetSplitConfigurationAsync(string merchantId, string splitConfigurationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of split configuration profiles + /// + /// + /// Returns the list of split configuration profiles for the merchant account. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task ListSplitConfigurationsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the split conditions + /// + /// + /// Changes the [split conditions of the rule](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#update-condition) specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The identifier of the split configuration. + /// The unique identifier of the split configuration rule. + /// + /// . + /// . + /// of . + Task UpdateSplitConditionsAsync(string merchantId, string splitConfigurationId, string ruleId, UpdateSplitConfigurationRuleRequest updateSplitConfigurationRuleRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the description of the split configuration profile + /// + /// + /// Changes the description of the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// + /// . + /// . + /// of . + Task UpdateSplitConfigurationDescriptionAsync(string merchantId, string splitConfigurationId, UpdateSplitConfigurationRequest updateSplitConfigurationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the split logic + /// + /// + /// Changes the [split logic](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#update-split-logic) specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// The unique identifier of the split configuration rule. + /// The unique identifier of the split configuration split. + /// + /// . + /// . + /// of . + Task UpdateSplitLogicAsync(string merchantId, string splitConfigurationId, string ruleId, string splitLogicId, UpdateSplitConfigurationLogicRequest updateSplitConfigurationLogicRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateSplitConfigurationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteSplitConfigurationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeleteSplitConfigurationRuleApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetSplitConfigurationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListSplitConfigurationsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateSplitConditionsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateSplitConfigurationDescriptionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateSplitLogicApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class SplitConfigurationMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateRule; + + internal void ExecuteOnCreateRule(SplitConfigurationMerchantLevelService.CreateRuleApiResponse apiResponse) + { + OnCreateRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateRule(Exception exception) + { + OnErrorCreateRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateSplitConfiguration; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateSplitConfiguration; + + internal void ExecuteOnCreateSplitConfiguration(SplitConfigurationMerchantLevelService.CreateSplitConfigurationApiResponse apiResponse) + { + OnCreateSplitConfiguration?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateSplitConfiguration(Exception exception) + { + OnErrorCreateSplitConfiguration?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteSplitConfiguration; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteSplitConfiguration; + + internal void ExecuteOnDeleteSplitConfiguration(SplitConfigurationMerchantLevelService.DeleteSplitConfigurationApiResponse apiResponse) + { + OnDeleteSplitConfiguration?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteSplitConfiguration(Exception exception) + { + OnErrorDeleteSplitConfiguration?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeleteSplitConfigurationRule; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeleteSplitConfigurationRule; + + internal void ExecuteOnDeleteSplitConfigurationRule(SplitConfigurationMerchantLevelService.DeleteSplitConfigurationRuleApiResponse apiResponse) + { + OnDeleteSplitConfigurationRule?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteSplitConfigurationRule(Exception exception) + { + OnErrorDeleteSplitConfigurationRule?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetSplitConfiguration; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetSplitConfiguration; + + internal void ExecuteOnGetSplitConfiguration(SplitConfigurationMerchantLevelService.GetSplitConfigurationApiResponse apiResponse) + { + OnGetSplitConfiguration?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetSplitConfiguration(Exception exception) + { + OnErrorGetSplitConfiguration?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListSplitConfigurations; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListSplitConfigurations; + + internal void ExecuteOnListSplitConfigurations(SplitConfigurationMerchantLevelService.ListSplitConfigurationsApiResponse apiResponse) + { + OnListSplitConfigurations?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListSplitConfigurations(Exception exception) + { + OnErrorListSplitConfigurations?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateSplitConditions; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateSplitConditions; + + internal void ExecuteOnUpdateSplitConditions(SplitConfigurationMerchantLevelService.UpdateSplitConditionsApiResponse apiResponse) + { + OnUpdateSplitConditions?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateSplitConditions(Exception exception) + { + OnErrorUpdateSplitConditions?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateSplitConfigurationDescription; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateSplitConfigurationDescription; + + internal void ExecuteOnUpdateSplitConfigurationDescription(SplitConfigurationMerchantLevelService.UpdateSplitConfigurationDescriptionApiResponse apiResponse) + { + OnUpdateSplitConfigurationDescription?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateSplitConfigurationDescription(Exception exception) + { + OnErrorUpdateSplitConfigurationDescription?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateSplitLogic; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateSplitLogic; + + internal void ExecuteOnUpdateSplitLogic(SplitConfigurationMerchantLevelService.UpdateSplitLogicApiResponse apiResponse) + { + OnUpdateSplitLogic?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateSplitLogic(Exception exception) + { + OnErrorUpdateSplitLogic?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class SplitConfigurationMerchantLevelService : ISplitConfigurationMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public SplitConfigurationMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public SplitConfigurationMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, SplitConfigurationMerchantLevelServiceEvents splitConfigurationMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = splitConfigurationMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a rule [Creates a rule](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#create-rule) in the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateRuleAsync(string merchantId, string splitConfigurationId, SplitConfigurationRule splitConfigurationRule, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (splitConfigurationRule as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(splitConfigurationRule, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateRuleApiResponse : Adyen.Core.Client.ApiResponse, ICreateRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a split configuration profile Creates a split configuration profile to [split payments automatically](https://docs.adyen.com/platforms/automatic-split-configuration/). After you [associate it with a store](https://docs.adyen.com/api-explorer/Management/latest/patch/merchants/(merchantId)/stores/(storeId)#request-splitConfiguration) in your merchant account, it splits the funds of all transactions processed through that store between your liable balance account and [your user's balance account](https://docs.adyen.com/api-explorer/Management/latest/patch/merchants/(merchantId)/stores/(storeId)#request-splitConfiguration-balanceAccountId). To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateSplitConfigurationAsync(string merchantId, SplitConfiguration splitConfiguration, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (splitConfiguration as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(splitConfiguration, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateSplitConfigurationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateSplitConfiguration(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateSplitConfiguration(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateSplitConfigurationApiResponse : Adyen.Core.Client.ApiResponse, ICreateSplitConfigurationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a split configuration profile Deletes the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteSplitConfigurationAsync(string merchantId, string splitConfigurationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteSplitConfigurationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteSplitConfiguration(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteSplitConfiguration(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteSplitConfigurationApiResponse : Adyen.Core.Client.ApiResponse, IDeleteSplitConfigurationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Delete a rule Deletes the rule specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeleteSplitConfigurationRuleAsync(string merchantId, string splitConfigurationId, string ruleId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BruleId%7D", Uri.EscapeDataString(ruleId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeleteSplitConfigurationRuleApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeleteSplitConfigurationRule(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeleteSplitConfigurationRule(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeleteSplitConfigurationRuleApiResponse : Adyen.Core.Client.ApiResponse, IDeleteSplitConfigurationRuleApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSplitConfigurationRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeleteSplitConfigurationRuleApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a split configuration profile Returns the details of the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetSplitConfigurationAsync(string merchantId, string splitConfigurationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetSplitConfigurationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetSplitConfiguration(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetSplitConfiguration(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetSplitConfigurationApiResponse : Adyen.Core.Client.ApiResponse, IGetSplitConfigurationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetSplitConfigurationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of split configuration profiles Returns the list of split configuration profiles for the merchant account. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListSplitConfigurationsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListSplitConfigurationsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListSplitConfigurations(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListSplitConfigurations(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListSplitConfigurationsApiResponse : Adyen.Core.Client.ApiResponse, IListSplitConfigurationsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListSplitConfigurationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListSplitConfigurationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfigurationList? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfigurationList? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the split conditions Changes the [split conditions of the rule](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#update-condition) specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The identifier of the split configuration. + /// The unique identifier of the split configuration rule. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateSplitConditionsAsync(string merchantId, string splitConfigurationId, string ruleId, UpdateSplitConfigurationRuleRequest updateSplitConfigurationRuleRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BruleId%7D", Uri.EscapeDataString(ruleId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateSplitConfigurationRuleRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateSplitConfigurationRuleRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateSplitConditionsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateSplitConditions(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateSplitConditions(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateSplitConditionsApiResponse : Adyen.Core.Client.ApiResponse, IUpdateSplitConditionsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitConditionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitConditionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the description of the split configuration profile Changes the description of the split configuration profile specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateSplitConfigurationDescriptionAsync(string merchantId, string splitConfigurationId, UpdateSplitConfigurationRequest updateSplitConfigurationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateSplitConfigurationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateSplitConfigurationRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateSplitConfigurationDescriptionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateSplitConfigurationDescription(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateSplitConfigurationDescription(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateSplitConfigurationDescriptionApiResponse : Adyen.Core.Client.ApiResponse, IUpdateSplitConfigurationDescriptionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitConfigurationDescriptionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitConfigurationDescriptionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the split logic Changes the [split logic](https://docs.adyen.com/platforms/automatic-split-configuration/manage-split-configurations/api/#update-split-logic) specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API - SplitConfiguration read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the split configuration. + /// The unique identifier of the split configuration rule. + /// The unique identifier of the split configuration split. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateSplitLogicAsync(string merchantId, string splitConfigurationId, string ruleId, string splitLogicId, UpdateSplitConfigurationLogicRequest updateSplitConfigurationLogicRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}/splitLogic/{splitLogicId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}/splitLogic/{splitLogicId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitConfigurationId%7D", Uri.EscapeDataString(splitConfigurationId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BruleId%7D", Uri.EscapeDataString(ruleId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BsplitLogicId%7D", Uri.EscapeDataString(splitLogicId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateSplitConfigurationLogicRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateSplitConfigurationLogicRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateSplitLogicApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}/splitLogic/{splitLogicId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateSplitLogic(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateSplitLogic(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateSplitLogicApiResponse : Adyen.Core.Client.ApiResponse, IUpdateSplitLogicApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitLogicApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateSplitLogicApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.SplitConfiguration? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.SplitConfiguration? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalActionsCompanyLevelService.cs b/Adyen/Management/Services/TerminalActionsCompanyLevelService.cs new file mode 100644 index 000000000..4df8529af --- /dev/null +++ b/Adyen/Management/Services/TerminalActionsCompanyLevelService.cs @@ -0,0 +1,982 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalActionsCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalActionsCompanyLevelServiceEvents Events { get; } + + /// + /// Get terminal action + /// + /// + /// Returns the details of the [terminal action](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the terminal action. + /// . + /// . + /// of . + Task GetTerminalActionAsync(string companyId, string actionId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of terminal actions + /// + /// + /// Returns the [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) that have been scheduled for the company identified in the path.The response doesn't include actions that are scheduled by Adyen. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. + /// Returns terminal actions with the specified status. Allowed values: **pending**, **successful**, **failed**, **cancelled**, **tryLater**. + /// Returns terminal actions of the specified type. Allowed values: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, **UninstallAndroidCertificate**. + /// . + /// . + /// of . + Task ListTerminalActionsAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option status = default, Option type = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetTerminalActionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListTerminalActionsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalActionsCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalAction; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalAction; + + internal void ExecuteOnGetTerminalAction(TerminalActionsCompanyLevelService.GetTerminalActionApiResponse apiResponse) + { + OnGetTerminalAction?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalAction(Exception exception) + { + OnErrorGetTerminalAction?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminalActions; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminalActions; + + internal void ExecuteOnListTerminalActions(TerminalActionsCompanyLevelService.ListTerminalActionsApiResponse apiResponse) + { + OnListTerminalActions?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminalActions(Exception exception) + { + OnErrorListTerminalActions?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalActionsCompanyLevelService : ITerminalActionsCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalActionsCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalActionsCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalActionsCompanyLevelServiceEvents terminalActionsCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalActionsCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get terminal action Returns the details of the [terminal action](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the terminal action. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalActionAsync(string companyId, string actionId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalActions/{actionId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalActions/{actionId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BactionId%7D", Uri.EscapeDataString(actionId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTerminalActionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalActions/{actionId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalAction(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalAction(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTerminalActionApiResponse : Adyen.Core.Client.ApiResponse, IGetTerminalActionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalActionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalActionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ExternalTerminalAction? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ExternalTerminalAction? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of terminal actions Returns the [terminal actions](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) that have been scheduled for the company identified in the path.The response doesn't include actions that are scheduled by Adyen. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. () + /// Returns terminal actions with the specified status. Allowed values: **pending**, **successful**, **failed**, **cancelled**, **tryLater**. () + /// Returns terminal actions of the specified type. Allowed values: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, **UninstallAndroidCertificate**. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalActionsAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option status = default, Option type = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalActions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalActions"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + if (type.IsSet) + parseQueryString["type"] = ClientUtils.ParameterToString(type.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListTerminalActionsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalActions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminalActions(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminalActions(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListTerminalActionsApiResponse : Adyen.Core.Client.ApiResponse, IListTerminalActionsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalActionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalActionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListExternalTerminalActionsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListExternalTerminalActionsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalActionsTerminalLevelService.cs b/Adyen/Management/Services/TerminalActionsTerminalLevelService.cs new file mode 100644 index 000000000..debbd1b40 --- /dev/null +++ b/Adyen/Management/Services/TerminalActionsTerminalLevelService.cs @@ -0,0 +1,541 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalActionsTerminalLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalActionsTerminalLevelServiceEvents Events { get; } + + /// + /// Create a terminal action + /// + /// + /// Schedules a [terminal action](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) by specifying the action and the terminals that the action must be applied to. The following restrictions apply: * You can schedule only one action at a time. For example, to install a new app version and remove an old app version, you have to make two API requests. * The maximum number of terminals in a request is **100**. For example, to apply an action to 250 terminals, you have to divide the terminals over three API requests. * If there is an error with one or more terminal IDs in the request, the action is scheduled for none of the terminals. You need to fix the error and try again. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateTerminalActionAsync(ScheduleTerminalActionsRequest scheduleTerminalActionsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateTerminalActionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalActionsTerminalLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateTerminalAction; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateTerminalAction; + + internal void ExecuteOnCreateTerminalAction(TerminalActionsTerminalLevelService.CreateTerminalActionApiResponse apiResponse) + { + OnCreateTerminalAction?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTerminalAction(Exception exception) + { + OnErrorCreateTerminalAction?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalActionsTerminalLevelService : ITerminalActionsTerminalLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalActionsTerminalLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalActionsTerminalLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalActionsTerminalLevelServiceEvents terminalActionsTerminalLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalActionsTerminalLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a terminal action Schedules a [terminal action](https://docs.adyen.com/point-of-sale/automating-terminal-management/terminal-actions-api) by specifying the action and the terminals that the action must be applied to. The following restrictions apply: * You can schedule only one action at a time. For example, to install a new app version and remove an old app version, you have to make two API requests. * The maximum number of terminals in a request is **100**. For example, to apply an action to 250 terminals, you have to divide the terminals over three API requests. * If there is an error with one or more terminal IDs in the request, the action is scheduled for none of the terminals. You need to fix the error and try again. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal actions read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateTerminalActionAsync(ScheduleTerminalActionsRequest scheduleTerminalActionsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/scheduleActions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/scheduleActions"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (scheduleTerminalActionsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(scheduleTerminalActionsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateTerminalActionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/scheduleActions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateTerminalAction(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateTerminalAction(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateTerminalActionApiResponse : Adyen.Core.Client.ApiResponse, ICreateTerminalActionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTerminalActionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateTerminalActionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ScheduleTerminalActionsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ScheduleTerminalActionsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalOrdersCompanyLevelService.cs b/Adyen/Management/Services/TerminalOrdersCompanyLevelService.cs new file mode 100644 index 000000000..cb854639f --- /dev/null +++ b/Adyen/Management/Services/TerminalOrdersCompanyLevelService.cs @@ -0,0 +1,4525 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalOrdersCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalOrdersCompanyLevelServiceEvents Events { get; } + + /// + /// Cancel an order + /// + /// + /// Cancels the terminal products order identified in the path. Cancelling is only possible while the order has the status **Placed**. To cancel an order, make a POST call without a request body. The response returns the full order details, but with the status changed to **Cancelled**. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// . + /// . + /// of . + Task CancelOrderAsync(string companyId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create an order + /// + /// + /// Creates an order for payment terminal products for the company identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write >Requests to the Management API test endpoint do not create actual orders for test terminals. To order test terminals, you need to [submit a sales order](https://docs.adyen.com/point-of-sale/managing-terminals/order-terminals/#sales-order-steps) in your Customer Area. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// + /// . + /// . + /// of . + Task CreateOrderAsync(string companyId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a shipping location + /// + /// + /// Creates a shipping location for the company identified in the path. A shipping location defines an address where orders can be delivered. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// + /// . + /// . + /// of . + Task CreateShippingLocationAsync(string companyId, ShippingLocation shippingLocation, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an order + /// + /// + /// Returns the details of the terminal products order identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// . + /// . + /// of . + Task GetOrderAsync(string companyId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of billing entities + /// + /// + /// Returns the billing entities of the company identified in the path and all merchant accounts belonging to the company. A billing entity is a legal entity where we charge orders to. An order for terminal products must contain the ID of a billing entity. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The name of the billing entity. + /// . + /// . + /// of . + Task ListBillingEntitiesAsync(string companyId, Option name = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of orders + /// + /// + /// Returns a lists of terminal products orders for the company identified in the path. To filter the list, use one or more of the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Your purchase order number. + /// The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. + /// The number of orders to skip. + /// The number of orders to return. + /// . + /// . + /// of . + Task ListOrdersAsync(string companyId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of shipping locations + /// + /// + /// Returns the shipping locations for the company identified in the path and all merchant accounts belonging to the company. A shipping location includes the address where orders can be delivered, and an ID which you need to specify when ordering terminal products. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The name of the shipping location. + /// The number of locations to skip. + /// The number of locations to return. + /// . + /// . + /// of . + Task ListShippingLocationsAsync(string companyId, Option name = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of terminal models + /// + /// + /// Returns a list of payment terminal models that the company identified in the path has access to. The response includes the terminal model ID, which can be used as a query parameter when getting a list of terminals or a list of products for ordering. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of . + Task ListTerminalModelsAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of terminal products + /// + /// + /// Returns a country-specific list of payment terminal packages and parts that the company identified in the path has access to. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** + /// The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) response. For example, **Verifone.M400** + /// The number of products to skip. + /// The number of products to return. + /// . + /// . + /// of . + Task ListTerminalProductsAsync(string companyId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an order + /// + /// + /// Updates the terminal products order identified in the path. Updating is only possible while the order has the status **Placed**. The request body only needs to contain what you want to change. However, to update the products in the `items` array, you must provide the entire array. For example, if the array has three items: To remove one item, the array must include the remaining two items. Or to add one item, the array must include all four items. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// + /// . + /// . + /// of . + Task UpdateOrderAsync(string companyId, string orderId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICancelOrderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateOrderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICreateShippingLocationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetOrderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListBillingEntitiesApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListOrdersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListShippingLocationsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListTerminalModelsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListTerminalProductsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateOrderApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalOrdersCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelOrder; + + internal void ExecuteOnCancelOrder(TerminalOrdersCompanyLevelService.CancelOrderApiResponse apiResponse) + { + OnCancelOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelOrder(Exception exception) + { + OnErrorCancelOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateOrder; + + internal void ExecuteOnCreateOrder(TerminalOrdersCompanyLevelService.CreateOrderApiResponse apiResponse) + { + OnCreateOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateOrder(Exception exception) + { + OnErrorCreateOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateShippingLocation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateShippingLocation; + + internal void ExecuteOnCreateShippingLocation(TerminalOrdersCompanyLevelService.CreateShippingLocationApiResponse apiResponse) + { + OnCreateShippingLocation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateShippingLocation(Exception exception) + { + OnErrorCreateShippingLocation?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetOrder; + + internal void ExecuteOnGetOrder(TerminalOrdersCompanyLevelService.GetOrderApiResponse apiResponse) + { + OnGetOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetOrder(Exception exception) + { + OnErrorGetOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListBillingEntities; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListBillingEntities; + + internal void ExecuteOnListBillingEntities(TerminalOrdersCompanyLevelService.ListBillingEntitiesApiResponse apiResponse) + { + OnListBillingEntities?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListBillingEntities(Exception exception) + { + OnErrorListBillingEntities?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListOrders; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListOrders; + + internal void ExecuteOnListOrders(TerminalOrdersCompanyLevelService.ListOrdersApiResponse apiResponse) + { + OnListOrders?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListOrders(Exception exception) + { + OnErrorListOrders?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListShippingLocations; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListShippingLocations; + + internal void ExecuteOnListShippingLocations(TerminalOrdersCompanyLevelService.ListShippingLocationsApiResponse apiResponse) + { + OnListShippingLocations?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListShippingLocations(Exception exception) + { + OnErrorListShippingLocations?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminalModels; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminalModels; + + internal void ExecuteOnListTerminalModels(TerminalOrdersCompanyLevelService.ListTerminalModelsApiResponse apiResponse) + { + OnListTerminalModels?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminalModels(Exception exception) + { + OnErrorListTerminalModels?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminalProducts; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminalProducts; + + internal void ExecuteOnListTerminalProducts(TerminalOrdersCompanyLevelService.ListTerminalProductsApiResponse apiResponse) + { + OnListTerminalProducts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminalProducts(Exception exception) + { + OnErrorListTerminalProducts?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateOrder; + + internal void ExecuteOnUpdateOrder(TerminalOrdersCompanyLevelService.UpdateOrderApiResponse apiResponse) + { + OnUpdateOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateOrder(Exception exception) + { + OnErrorUpdateOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalOrdersCompanyLevelService : ITerminalOrdersCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalOrdersCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalOrdersCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalOrdersCompanyLevelServiceEvents terminalOrdersCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalOrdersCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Cancel an order Cancels the terminal products order identified in the path. Cancelling is only possible while the order has the status **Placed**. To cancel an order, make a POST call without a request body. The response returns the full order details, but with the status changed to **Cancelled**. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelOrderAsync(string companyId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalOrders/{orderId}/cancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalOrders/{orderId}/cancel"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalOrders/{orderId}/cancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelOrder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelOrderApiResponse : Adyen.Core.Client.ApiResponse, ICancelOrderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalOrder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalOrder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create an order Creates an order for payment terminal products for the company identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write >Requests to the Management API test endpoint do not create actual orders for test terminals. To order test terminals, you need to [submit a sales order](https://docs.adyen.com/point-of-sale/managing-terminals/order-terminals/#sales-order-steps) in your Customer Area. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateOrderAsync(string companyId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalOrders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalOrders"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalOrders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateOrder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateOrderApiResponse : Adyen.Core.Client.ApiResponse, ICreateOrderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalOrder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalOrder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a shipping location Creates a shipping location for the company identified in the path. A shipping location defines an address where orders can be delivered. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateShippingLocationAsync(string companyId, ShippingLocation shippingLocation, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/shippingLocations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/shippingLocations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (shippingLocation as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(shippingLocation, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateShippingLocationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/shippingLocations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateShippingLocation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateShippingLocation(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateShippingLocationApiResponse : Adyen.Core.Client.ApiResponse, ICreateShippingLocationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateShippingLocationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateShippingLocationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ShippingLocation? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ShippingLocation? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get an order Returns the details of the terminal products order identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetOrderAsync(string companyId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalOrders/{orderId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalOrders/{orderId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalOrders/{orderId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetOrder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetOrderApiResponse : Adyen.Core.Client.ApiResponse, IGetOrderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalOrder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalOrder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of billing entities Returns the billing entities of the company identified in the path and all merchant accounts belonging to the company. A billing entity is a legal entity where we charge orders to. An order for terminal products must contain the ID of a billing entity. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The name of the billing entity. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListBillingEntitiesAsync(string companyId, Option name = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/billingEntities" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/billingEntities"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryString["name"] = ClientUtils.ParameterToString(name.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListBillingEntitiesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/billingEntities", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListBillingEntities(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListBillingEntities(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListBillingEntitiesApiResponse : Adyen.Core.Client.ApiResponse, IListBillingEntitiesApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListBillingEntitiesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListBillingEntitiesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.BillingEntitiesResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.BillingEntitiesResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of orders Returns a lists of terminal products orders for the company identified in the path. To filter the list, use one or more of the query parameters. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Your purchase order number. () + /// The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. () + /// The number of orders to skip. () + /// The number of orders to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListOrdersAsync(string companyId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalOrders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalOrders"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (customerOrderReference.IsSet) + parseQueryString["customerOrderReference"] = ClientUtils.ParameterToString(customerOrderReference.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListOrdersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalOrders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListOrders(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListOrders(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListOrdersApiResponse : Adyen.Core.Client.ApiResponse, IListOrdersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListOrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListOrdersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalOrdersResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalOrdersResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of shipping locations Returns the shipping locations for the company identified in the path and all merchant accounts belonging to the company. A shipping location includes the address where orders can be delivered, and an ID which you need to specify when ordering terminal products. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The name of the shipping location. () + /// The number of locations to skip. () + /// The number of locations to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListShippingLocationsAsync(string companyId, Option name = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/shippingLocations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/shippingLocations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryString["name"] = ClientUtils.ParameterToString(name.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListShippingLocationsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/shippingLocations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListShippingLocations(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListShippingLocations(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListShippingLocationsApiResponse : Adyen.Core.Client.ApiResponse, IListShippingLocationsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListShippingLocationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListShippingLocationsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ShippingLocationsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ShippingLocationsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of terminal models Returns a list of payment terminal models that the company identified in the path has access to. The response includes the terminal model ID, which can be used as a query parameter when getting a list of terminals or a list of products for ordering. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalModelsAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalModels" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalModels"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListTerminalModelsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalModels", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminalModels(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminalModels(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListTerminalModelsApiResponse : Adyen.Core.Client.ApiResponse, IListTerminalModelsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalModelsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalModelsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalModelsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalModelsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of terminal products Returns a country-specific list of payment terminal packages and parts that the company identified in the path has access to. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** + /// The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) response. For example, **Verifone.M400** () + /// The number of products to skip. () + /// The number of products to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalProductsAsync(string companyId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalProducts" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalProducts"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["country"] = ClientUtils.ParameterToString(country); + + if (terminalModelId.IsSet) + parseQueryString["terminalModelId"] = ClientUtils.ParameterToString(terminalModelId.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListTerminalProductsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalProducts", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminalProducts(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminalProducts(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListTerminalProductsApiResponse : Adyen.Core.Client.ApiResponse, IListTerminalProductsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalProductsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalProductsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalProductsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalProductsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update an order Updates the terminal products order identified in the path. Updating is only possible while the order has the status **Placed**. The request body only needs to contain what you want to change. However, to update the products in the `items` array, you must provide the entire array. For example, if the array has three items: To remove one item, the array must include the remaining two items. Or to add one item, the array must include all four items. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the order. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateOrderAsync(string companyId, string orderId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalOrders/{orderId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalOrders/{orderId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalOrders/{orderId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateOrder(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateOrderApiResponse : Adyen.Core.Client.ApiResponse, IUpdateOrderApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateOrderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalOrder? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalOrder? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalOrdersMerchantLevelService.cs b/Adyen/Management/Services/TerminalOrdersMerchantLevelService.cs new file mode 100644 index 000000000..f76d310cd --- /dev/null +++ b/Adyen/Management/Services/TerminalOrdersMerchantLevelService.cs @@ -0,0 +1,1265 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalOrdersMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalOrdersMerchantLevelServiceEvents Events { get; } + + /// + /// Cancel an order + /// + /// + /// Cancels the terminal products order identified in the path. Cancelling is only possible while the order has the status **Placed**. To cancel an order, make a POST call without a request body. The response returns the full order details, but with the status changed to **Cancelled**. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// . + /// . + /// of . + Task CancelOrderAsync(string merchantId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create an order + /// + /// + /// Creates an order for payment terminal products for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write >Requests to the Management API test endpoint do not create actual orders for test terminals. To order test terminals, you need to [submit a sales order](https://docs.adyen.com/point-of-sale/managing-terminals/order-terminals/#sales-order-steps) in your Customer Area. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task CreateOrderAsync(string merchantId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a shipping location + /// + /// + /// Creates a shipping location for the merchant account identified in the path. A shipping location defines an address where orders can be shipped to. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task CreateShippingLocationAsync(string merchantId, ShippingLocation shippingLocation, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get an order + /// + /// + /// Returns the details of the terminal products order identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// . + /// . + /// of . + Task GetOrderAsync(string merchantId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of billing entities + /// + /// + /// Returns the billing entities of the merchant account identified in the path. A billing entity is a legal entity where we charge orders to. An order for terminal products must contain the ID of a billing entity. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The name of the billing entity. + /// . + /// . + /// of . + Task ListBillingEntitiesAsync(string merchantId, Option name = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of orders + /// + /// + /// Returns a list of terminal products orders for the merchant account identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// + /// Your purchase order number. + /// The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. + /// The number of orders to skip. + /// The number of orders to return. + /// . + /// . + /// of . + Task ListOrdersAsync(string merchantId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of shipping locations + /// + /// + /// Returns the shipping locations for the merchant account identified in the path. A shipping location includes the address where orders can be delivered, and an ID which you need to specify when ordering terminal products. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The name of the shipping location. + /// The number of locations to skip. + /// The number of locations to return. + /// . + /// . + /// of . + Task ListShippingLocationsAsync(string merchantId, Option name = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of terminal models + /// + /// + /// Returns the payment terminal models that the merchant account identified in the path has access to. The response includes the terminal model ID, which can be used as a query parameter when getting a list of terminals or a list of products for ordering. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task ListTerminalModelsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of terminal products + /// + /// + /// Returns a country-specific list of payment terminal packages and parts that the merchant account identified in the path has access to. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** + /// The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/merchants/{merchantId}/terminalModels) response. For example, **Verifone.M400** + /// The number of products to skip. + /// The number of products to return. + /// . + /// . + /// of . + Task ListTerminalProductsAsync(string merchantId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update an order + /// + /// + /// Updates the terminal products order identified in the path. Updating is only possible while the order has the status **Placed**. The request body only needs to contain what you want to change. However, to update the products in the `items` array, you must provide the entire array. For example, if the array has three items: To remove one item, the array must include the remaining two items. Or to add one item, the array must include all four items. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// + /// . + /// . + /// of . + Task UpdateOrderAsync(string merchantId, string orderId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalOrdersMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelOrder; + + internal void ExecuteOnCancelOrder(TerminalOrdersCompanyLevelService.CancelOrderApiResponse apiResponse) + { + OnCancelOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelOrder(Exception exception) + { + OnErrorCancelOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateOrder; + + internal void ExecuteOnCreateOrder(TerminalOrdersCompanyLevelService.CreateOrderApiResponse apiResponse) + { + OnCreateOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateOrder(Exception exception) + { + OnErrorCreateOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateShippingLocation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateShippingLocation; + + internal void ExecuteOnCreateShippingLocation(TerminalOrdersCompanyLevelService.CreateShippingLocationApiResponse apiResponse) + { + OnCreateShippingLocation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateShippingLocation(Exception exception) + { + OnErrorCreateShippingLocation?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetOrder; + + internal void ExecuteOnGetOrder(TerminalOrdersCompanyLevelService.GetOrderApiResponse apiResponse) + { + OnGetOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetOrder(Exception exception) + { + OnErrorGetOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListBillingEntities; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListBillingEntities; + + internal void ExecuteOnListBillingEntities(TerminalOrdersCompanyLevelService.ListBillingEntitiesApiResponse apiResponse) + { + OnListBillingEntities?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListBillingEntities(Exception exception) + { + OnErrorListBillingEntities?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListOrders; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListOrders; + + internal void ExecuteOnListOrders(TerminalOrdersCompanyLevelService.ListOrdersApiResponse apiResponse) + { + OnListOrders?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListOrders(Exception exception) + { + OnErrorListOrders?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListShippingLocations; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListShippingLocations; + + internal void ExecuteOnListShippingLocations(TerminalOrdersCompanyLevelService.ListShippingLocationsApiResponse apiResponse) + { + OnListShippingLocations?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListShippingLocations(Exception exception) + { + OnErrorListShippingLocations?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminalModels; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminalModels; + + internal void ExecuteOnListTerminalModels(TerminalOrdersCompanyLevelService.ListTerminalModelsApiResponse apiResponse) + { + OnListTerminalModels?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminalModels(Exception exception) + { + OnErrorListTerminalModels?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminalProducts; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminalProducts; + + internal void ExecuteOnListTerminalProducts(TerminalOrdersCompanyLevelService.ListTerminalProductsApiResponse apiResponse) + { + OnListTerminalProducts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminalProducts(Exception exception) + { + OnErrorListTerminalProducts?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateOrder; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateOrder; + + internal void ExecuteOnUpdateOrder(TerminalOrdersCompanyLevelService.UpdateOrderApiResponse apiResponse) + { + OnUpdateOrder?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateOrder(Exception exception) + { + OnErrorUpdateOrder?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalOrdersMerchantLevelService : ITerminalOrdersMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalOrdersMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalOrdersMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalOrdersMerchantLevelServiceEvents terminalOrdersMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalOrdersMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Cancel an order Cancels the terminal products order identified in the path. Cancelling is only possible while the order has the status **Placed**. To cancel an order, make a POST call without a request body. The response returns the full order details, but with the status changed to **Cancelled**. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelOrderAsync(string merchantId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalOrders/{orderId}/cancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalOrders/{orderId}/cancel"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.CancelOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalOrders/{orderId}/cancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelOrder(exception); + throw; + } + } + /// + /// Create an order Creates an order for payment terminal products for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write >Requests to the Management API test endpoint do not create actual orders for test terminals. To order test terminals, you need to [submit a sales order](https://docs.adyen.com/point-of-sale/managing-terminals/order-terminals/#sales-order-steps) in your Customer Area. In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateOrderAsync(string merchantId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalOrders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalOrders"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.CreateOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalOrders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateOrder(exception); + throw; + } + } + /// + /// Create a shipping location Creates a shipping location for the merchant account identified in the path. A shipping location defines an address where orders can be shipped to. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateShippingLocationAsync(string merchantId, ShippingLocation shippingLocation, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/shippingLocations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/shippingLocations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (shippingLocation as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(shippingLocation, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.CreateShippingLocationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/shippingLocations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateShippingLocation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateShippingLocation(exception); + throw; + } + } + /// + /// Get an order Returns the details of the terminal products order identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetOrderAsync(string merchantId, string orderId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalOrders/{orderId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalOrders/{orderId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.GetOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalOrders/{orderId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetOrder(exception); + throw; + } + } + /// + /// Get a list of billing entities Returns the billing entities of the merchant account identified in the path. A billing entity is a legal entity where we charge orders to. An order for terminal products must contain the ID of a billing entity. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The name of the billing entity. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListBillingEntitiesAsync(string merchantId, Option name = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/billingEntities" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/billingEntities"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryString["name"] = ClientUtils.ParameterToString(name.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.ListBillingEntitiesApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/billingEntities", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListBillingEntities(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListBillingEntities(exception); + throw; + } + } + /// + /// Get a list of orders Returns a list of terminal products orders for the merchant account identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// + /// Your purchase order number. () + /// The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. () + /// The number of orders to skip. () + /// The number of orders to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListOrdersAsync(string merchantId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalOrders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalOrders"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (customerOrderReference.IsSet) + parseQueryString["customerOrderReference"] = ClientUtils.ParameterToString(customerOrderReference.Value); + + if (status.IsSet) + parseQueryString["status"] = ClientUtils.ParameterToString(status.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.ListOrdersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalOrders", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListOrders(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListOrders(exception); + throw; + } + } + /// + /// Get a list of shipping locations Returns the shipping locations for the merchant account identified in the path. A shipping location includes the address where orders can be delivered, and an ID which you need to specify when ordering terminal products. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The name of the shipping location. () + /// The number of locations to skip. () + /// The number of locations to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListShippingLocationsAsync(string merchantId, Option name = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/shippingLocations" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/shippingLocations"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryString["name"] = ClientUtils.ParameterToString(name.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.ListShippingLocationsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/shippingLocations", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListShippingLocations(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListShippingLocations(exception); + throw; + } + } + /// + /// Get a list of terminal models Returns the payment terminal models that the merchant account identified in the path has access to. The response includes the terminal model ID, which can be used as a query parameter when getting a list of terminals or a list of products for ordering. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalModelsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalModels" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalModels"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.ListTerminalModelsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalModels", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminalModels(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminalModels(exception); + throw; + } + } + /// + /// Get a list of terminal products Returns a country-specific list of payment terminal packages and parts that the merchant account identified in the path has access to. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** + /// The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/merchants/{merchantId}/terminalModels) response. For example, **Verifone.M400** () + /// The number of products to skip. () + /// The number of products to return. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalProductsAsync(string merchantId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalProducts" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalProducts"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["country"] = ClientUtils.ParameterToString(country); + + if (terminalModelId.IsSet) + parseQueryString["terminalModelId"] = ClientUtils.ParameterToString(terminalModelId.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.ListTerminalProductsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalProducts", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminalProducts(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminalProducts(exception); + throw; + } + } + /// + /// Update an order Updates the terminal products order identified in the path. Updating is only possible while the order has the status **Placed**. The request body only needs to contain what you want to change. However, to update the products in the `items` array, you must provide the entire array. For example, if the array has three items: To remove one item, the array must include the remaining two items. Or to add one item, the array must include all four items. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal ordering read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the order. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateOrderAsync(string merchantId, string orderId, TerminalOrderRequest terminalOrderRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalOrders/{orderId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalOrders/{orderId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BorderId%7D", Uri.EscapeDataString(orderId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalOrderRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalOrderRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalOrdersCompanyLevelService.UpdateOrderApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalOrders/{orderId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateOrder(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateOrder(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/TerminalSettingsCompanyLevelService.cs b/Adyen/Management/Services/TerminalSettingsCompanyLevelService.cs new file mode 100644 index 000000000..e7c4b5b99 --- /dev/null +++ b/Adyen/Management/Services/TerminalSettingsCompanyLevelService.cs @@ -0,0 +1,1865 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalSettingsCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalSettingsCompanyLevelServiceEvents Events { get; } + + /// + /// Get the terminal logo + /// + /// + /// Returns the logo that is configured for a specific payment terminal model at the company identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the company, unless a different logo is configured at a lower level (merchant account, store, or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of . + Task GetTerminalLogoAsync(string companyId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get terminal settings + /// + /// + /// Returns the payment terminal settings that are configured for the company identified in the path. These settings apply to all terminals under the company, unless different values are configured at a lower level (merchant account, store, or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of . + Task GetTerminalSettingsAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the terminal logo + /// + /// + /// Updates the logo that is configured for a specific payment terminal model at the company identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the company, unless a different logo is configured at a lower level (merchant account, store, or individual terminal). * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from the Adyen PSP level, specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// + /// . + /// . + /// of . + Task UpdateTerminalLogoAsync(string companyId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update terminal settings + /// + /// + /// Updates payment terminal settings for the company identified in the path. These settings apply to all terminals under the company, unless different values are configured at a lower level (merchant account, store, or individual terminal). * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from the Adyen PSP level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// + /// . + /// . + /// of . + Task UpdateTerminalSettingsAsync(string companyId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetTerminalLogoApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTerminalSettingsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTerminalLogoApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTerminalSettingsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalSettingsCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalLogo; + + internal void ExecuteOnGetTerminalLogo(TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse) + { + OnGetTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalLogo(Exception exception) + { + OnErrorGetTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalSettings; + + internal void ExecuteOnGetTerminalSettings(TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse) + { + OnGetTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalSettings(Exception exception) + { + OnErrorGetTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalLogo; + + internal void ExecuteOnUpdateTerminalLogo(TerminalSettingsCompanyLevelService.UpdateTerminalLogoApiResponse apiResponse) + { + OnUpdateTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalLogo(Exception exception) + { + OnErrorUpdateTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalSettings; + + internal void ExecuteOnUpdateTerminalSettings(TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse) + { + OnUpdateTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalSettings(Exception exception) + { + OnErrorUpdateTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalSettingsCompanyLevelService : ITerminalSettingsCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalSettingsCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalSettingsCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalSettingsCompanyLevelServiceEvents terminalSettingsCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalSettingsCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get the terminal logo Returns the logo that is configured for a specific payment terminal model at the company identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the company, unless a different logo is configured at a lower level (merchant account, store, or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalLogoAsync(string companyId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalLogo(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTerminalLogoApiResponse : Adyen.Core.Client.ApiResponse, IGetTerminalLogoApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Logo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Logo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get terminal settings Returns the payment terminal settings that are configured for the company identified in the path. These settings apply to all terminals under the company, unless different values are configured at a lower level (merchant account, store, or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalSettingsAsync(string companyId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalSettings(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTerminalSettingsApiResponse : Adyen.Core.Client.ApiResponse, IGetTerminalSettingsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the terminal logo Updates the logo that is configured for a specific payment terminal model at the company identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the company, unless a different logo is configured at a lower level (merchant account, store, or individual terminal). * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from the Adyen PSP level, specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalLogoAsync(string companyId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (logo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(logo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalLogo(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTerminalLogoApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTerminalLogoApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Logo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Logo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update terminal settings Updates payment terminal settings for the company identified in the path. These settings apply to all terminals under the company, unless different values are configured at a lower level (merchant account, store, or individual terminal). * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from the Adyen PSP level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalSettingsAsync(string companyId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalSettings as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalSettings(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTerminalSettingsApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTerminalSettingsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalSettingsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalSettingsMerchantLevelService.cs b/Adyen/Management/Services/TerminalSettingsMerchantLevelService.cs new file mode 100644 index 000000000..a2e35cfe4 --- /dev/null +++ b/Adyen/Management/Services/TerminalSettingsMerchantLevelService.cs @@ -0,0 +1,561 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalSettingsMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalSettingsMerchantLevelServiceEvents Events { get; } + + /// + /// Get the terminal logo + /// + /// + /// Returns the logo that is configured for a specific payment terminal model at the merchant account identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the merchant account, unless a different logo is configured at a lower level (store or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of . + Task GetTerminalLogoAsync(string merchantId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get terminal settings + /// + /// + /// Returns the payment terminal settings that are configured for the merchant account identified in the path. These settings apply to all terminals under the merchant account unless different values are configured at a lower level (store or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of . + Task GetTerminalSettingsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the terminal logo + /// + /// + /// Updates the logo for a specific payment terminal model at the merchant account identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the merchant account, unless a different logo is configured at a lower level (store or individual terminal). * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from the company account, specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The terminal model. Allowed values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// + /// . + /// . + /// of . + Task UpdateTerminalLogoAsync(string merchantId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update terminal settings + /// + /// + /// Updates payment terminal settings for the merchant account identified in the path. These settings apply to all terminals under the merchant account, unless different values are configured at a lower level (store or individual terminal). * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task UpdateTerminalSettingsAsync(string merchantId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalSettingsMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalLogo; + + internal void ExecuteOnGetTerminalLogo(TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse) + { + OnGetTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalLogo(Exception exception) + { + OnErrorGetTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalSettings; + + internal void ExecuteOnGetTerminalSettings(TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse) + { + OnGetTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalSettings(Exception exception) + { + OnErrorGetTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalLogo; + + internal void ExecuteOnUpdateTerminalLogo(TerminalSettingsCompanyLevelService.UpdateTerminalLogoApiResponse apiResponse) + { + OnUpdateTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalLogo(Exception exception) + { + OnErrorUpdateTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalSettings; + + internal void ExecuteOnUpdateTerminalSettings(TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse) + { + OnUpdateTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalSettings(Exception exception) + { + OnErrorUpdateTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalSettingsMerchantLevelService : ITerminalSettingsMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalSettingsMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalSettingsMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalSettingsMerchantLevelServiceEvents terminalSettingsMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalSettingsMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get the terminal logo Returns the logo that is configured for a specific payment terminal model at the merchant account identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the merchant account, unless a different logo is configured at a lower level (store or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalLogoAsync(string merchantId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalLogo(exception); + throw; + } + } + /// + /// Get terminal settings Returns the payment terminal settings that are configured for the merchant account identified in the path. These settings apply to all terminals under the merchant account unless different values are configured at a lower level (store or individual terminal). To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalSettingsAsync(string merchantId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalSettings(exception); + throw; + } + } + /// + /// Update the terminal logo Updates the logo for a specific payment terminal model at the merchant account identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the merchant account, unless a different logo is configured at a lower level (store or individual terminal). * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from the company account, specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The terminal model. Allowed values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalLogoAsync(string merchantId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (logo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(logo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.UpdateTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalLogo(exception); + throw; + } + } + /// + /// Update terminal settings Updates payment terminal settings for the merchant account identified in the path. These settings apply to all terminals under the merchant account, unless different values are configured at a lower level (store or individual terminal). * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalSettingsAsync(string merchantId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalSettings as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalSettings(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/TerminalSettingsStoreLevelService.cs b/Adyen/Management/Services/TerminalSettingsStoreLevelService.cs new file mode 100644 index 000000000..b083d4aa5 --- /dev/null +++ b/Adyen/Management/Services/TerminalSettingsStoreLevelService.cs @@ -0,0 +1,2341 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalSettingsStoreLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalSettingsStoreLevelServiceEvents Events { get; } + + /// + /// Get the terminal logo + /// + /// + /// Returns the logo that is configured for a specific payment terminal model at the store identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of . + Task GetTerminalLogoAsync(string merchantId, string reference, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the terminal logo + /// + /// + /// Returns the logo that is configured for a specific payment terminal model at the store identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of that model under the store unless a different logo is configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of . + Task GetTerminalLogoByStoreIdAsync(string storeId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get terminal settings + /// + /// + /// Returns the payment terminal settings that are configured for the store identified in the path. These settings apply to all terminals under the store unless different values are configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// . + /// . + /// of . + Task GetTerminalSettingsAsync(string merchantId, string reference, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get terminal settings + /// + /// + /// Returns the payment terminal settings that are configured for the store identified in the path. These settings apply to all terminals under the store unless different values are configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// . + /// . + /// of . + Task GetTerminalSettingsByStoreIdAsync(string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the terminal logo + /// + /// + /// Updates the logo that is configured for a specific payment terminal model at the store identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (merchant or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T + /// + /// . + /// . + /// of . + Task UpdateTerminalLogoAsync(string merchantId, string reference, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the terminal logo + /// + /// + /// Updates the logo that is configured for a specific payment terminal model at the store identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (merchant or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// + /// . + /// . + /// of . + Task UpdateTerminalLogoByStoreIdAsync(string storeId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update terminal settings + /// + /// + /// Updates payment terminal settings for the store identified in the path. These settings apply to all terminals under the store, unless different values are configured for an individual terminal. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// + /// . + /// . + /// of . + Task UpdateTerminalSettingsAsync(string merchantId, string reference, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update terminal settings + /// + /// + /// Updates payment terminal settings for the store identified in the path. These settings apply to all terminals under the store, unless different values are configured for an individual terminal. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// + /// . + /// . + /// of . + Task UpdateTerminalSettingsByStoreIdAsync(string storeId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetTerminalLogoByStoreIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTerminalSettingsByStoreIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTerminalLogoByStoreIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateTerminalSettingsByStoreIdApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalSettingsStoreLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalLogo; + + internal void ExecuteOnGetTerminalLogo(TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse) + { + OnGetTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalLogo(Exception exception) + { + OnErrorGetTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalLogoByStoreId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalLogoByStoreId; + + internal void ExecuteOnGetTerminalLogoByStoreId(TerminalSettingsStoreLevelService.GetTerminalLogoByStoreIdApiResponse apiResponse) + { + OnGetTerminalLogoByStoreId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalLogoByStoreId(Exception exception) + { + OnErrorGetTerminalLogoByStoreId?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalSettings; + + internal void ExecuteOnGetTerminalSettings(TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse) + { + OnGetTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalSettings(Exception exception) + { + OnErrorGetTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalSettingsByStoreId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalSettingsByStoreId; + + internal void ExecuteOnGetTerminalSettingsByStoreId(TerminalSettingsStoreLevelService.GetTerminalSettingsByStoreIdApiResponse apiResponse) + { + OnGetTerminalSettingsByStoreId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalSettingsByStoreId(Exception exception) + { + OnErrorGetTerminalSettingsByStoreId?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalLogo; + + internal void ExecuteOnUpdateTerminalLogo(TerminalSettingsCompanyLevelService.UpdateTerminalLogoApiResponse apiResponse) + { + OnUpdateTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalLogo(Exception exception) + { + OnErrorUpdateTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalLogoByStoreId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalLogoByStoreId; + + internal void ExecuteOnUpdateTerminalLogoByStoreId(TerminalSettingsStoreLevelService.UpdateTerminalLogoByStoreIdApiResponse apiResponse) + { + OnUpdateTerminalLogoByStoreId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalLogoByStoreId(Exception exception) + { + OnErrorUpdateTerminalLogoByStoreId?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalSettings; + + internal void ExecuteOnUpdateTerminalSettings(TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse) + { + OnUpdateTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalSettings(Exception exception) + { + OnErrorUpdateTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalSettingsByStoreId; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalSettingsByStoreId; + + internal void ExecuteOnUpdateTerminalSettingsByStoreId(TerminalSettingsStoreLevelService.UpdateTerminalSettingsByStoreIdApiResponse apiResponse) + { + OnUpdateTerminalSettingsByStoreId?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalSettingsByStoreId(Exception exception) + { + OnErrorUpdateTerminalSettingsByStoreId?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalSettingsStoreLevelService : ITerminalSettingsStoreLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalSettingsStoreLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalSettingsStoreLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalSettingsStoreLevelServiceEvents terminalSettingsStoreLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalSettingsStoreLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get the terminal logo Returns the logo that is configured for a specific payment terminal model at the store identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalLogoAsync(string merchantId, string reference, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{reference}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{reference}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Breference%7D", Uri.EscapeDataString(reference.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{reference}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalLogo(exception); + throw; + } + } + /// + /// Get the terminal logo Returns the logo that is configured for a specific payment terminal model at the store identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. This logo applies to all terminals of that model under the store unless a different logo is configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalLogoByStoreIdAsync(string storeId, string model, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTerminalLogoByStoreIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalLogoByStoreId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalLogoByStoreId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTerminalLogoByStoreIdApiResponse : Adyen.Core.Client.ApiResponse, IGetTerminalLogoByStoreIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalLogoByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalLogoByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Logo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Logo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get terminal settings Returns the payment terminal settings that are configured for the store identified in the path. These settings apply to all terminals under the store unless different values are configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalSettingsAsync(string merchantId, string reference, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{reference}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{reference}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Breference%7D", Uri.EscapeDataString(reference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{reference}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalSettings(exception); + throw; + } + } + /// + /// Get terminal settings Returns the payment terminal settings that are configured for the store identified in the path. These settings apply to all terminals under the store unless different values are configured for an individual terminal. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalSettingsByStoreIdAsync(string storeId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTerminalSettingsByStoreIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalSettingsByStoreId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalSettingsByStoreId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTerminalSettingsByStoreIdApiResponse : Adyen.Core.Client.ApiResponse, IGetTerminalSettingsByStoreIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalSettingsByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTerminalSettingsByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update the terminal logo Updates the logo that is configured for a specific payment terminal model at the store identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (merchant or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalLogoAsync(string merchantId, string reference, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{reference}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{reference}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Breference%7D", Uri.EscapeDataString(reference.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (logo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(logo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.UpdateTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{reference}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalLogo(exception); + throw; + } + } + /// + /// Update the terminal logo Updates the logo that is configured for a specific payment terminal model at the store identified in the path. You can update the logo for only one terminal model at a time. This logo applies to all terminals of the specified model under the store, unless a different logo is configured for an individual terminal. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (merchant or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalLogoByStoreIdAsync(string storeId, string model, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["model"] = ClientUtils.ParameterToString(model); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (logo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(logo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTerminalLogoByStoreIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalLogoByStoreId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalLogoByStoreId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTerminalLogoByStoreIdApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTerminalLogoByStoreIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalLogoByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalLogoByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Logo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Logo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update terminal settings Updates payment terminal settings for the store identified in the path. These settings apply to all terminals under the store, unless different values are configured for an individual terminal. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The reference that identifies the store. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalSettingsAsync(string merchantId, string reference, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{reference}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{reference}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7Breference%7D", Uri.EscapeDataString(reference.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalSettings as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{reference}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalSettings(exception); + throw; + } + } + /// + /// Update terminal settings Updates payment terminal settings for the store identified in the path. These settings apply to all terminals under the store, unless different values are configured for an individual terminal. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the store. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalSettingsByStoreIdAsync(string storeId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/stores/{storeId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/stores/{storeId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalSettings as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateTerminalSettingsByStoreIdApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/stores/{storeId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalSettingsByStoreId(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalSettingsByStoreId(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateTerminalSettingsByStoreIdApiResponse : Adyen.Core.Client.ApiResponse, IUpdateTerminalSettingsByStoreIdApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalSettingsByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateTerminalSettingsByStoreIdApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TerminalSettings? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TerminalSettings? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/TerminalSettingsTerminalLevelService.cs b/Adyen/Management/Services/TerminalSettingsTerminalLevelService.cs new file mode 100644 index 000000000..184302e1a --- /dev/null +++ b/Adyen/Management/Services/TerminalSettingsTerminalLevelService.cs @@ -0,0 +1,871 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalSettingsTerminalLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalSettingsTerminalLevelServiceEvents Events { get; } + + /// + /// Get the terminal logo + /// + /// + /// Returns the logo that is configured for the payment terminal identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// . + /// . + /// of . + Task GetTerminalLogoAsync(string terminalId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get terminal settings + /// + /// + /// Returns the settings that are configured for the payment terminal identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// . + /// . + /// of . + Task GetTerminalSettingsAsync(string terminalId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update the logo + /// + /// + /// Updates the logo for the payment terminal identified in the path. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (store, merchant account, or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// + /// . + /// . + /// of . + Task UpdateLogoAsync(string terminalId, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update terminal settings + /// + /// + /// Updates the settings that are configured for the payment terminal identified in the path. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// + /// . + /// . + /// of . + Task UpdateTerminalSettingsAsync(string terminalId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IUpdateLogoApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalSettingsTerminalLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalLogo; + + internal void ExecuteOnGetTerminalLogo(TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse) + { + OnGetTerminalLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalLogo(Exception exception) + { + OnErrorGetTerminalLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTerminalSettings; + + internal void ExecuteOnGetTerminalSettings(TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse) + { + OnGetTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTerminalSettings(Exception exception) + { + OnErrorGetTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateLogo; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateLogo; + + internal void ExecuteOnUpdateLogo(TerminalSettingsTerminalLevelService.UpdateLogoApiResponse apiResponse) + { + OnUpdateLogo?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateLogo(Exception exception) + { + OnErrorUpdateLogo?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateTerminalSettings; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateTerminalSettings; + + internal void ExecuteOnUpdateTerminalSettings(TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse) + { + OnUpdateTerminalSettings?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTerminalSettings(Exception exception) + { + OnErrorUpdateTerminalSettings?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalSettingsTerminalLevelService : ITerminalSettingsTerminalLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalSettingsTerminalLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalSettingsTerminalLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalSettingsTerminalLevelServiceEvents terminalSettingsTerminalLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalSettingsTerminalLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get the terminal logo Returns the logo that is configured for the payment terminal identified in the path. The logo is returned as a Base64-encoded string. You need to Base64-decode the string to get the actual image file. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalLogoAsync(string terminalId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/{terminalId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/{terminalId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BterminalId%7D", Uri.EscapeDataString(terminalId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/{terminalId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalLogo(exception); + throw; + } + } + /// + /// Get terminal settings Returns the settings that are configured for the payment terminal identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTerminalSettingsAsync(string terminalId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/{terminalId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/{terminalId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BterminalId%7D", Uri.EscapeDataString(terminalId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.GetTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/{terminalId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTerminalSettings(exception); + throw; + } + } + /// + /// Update the logo Updates the logo for the payment terminal identified in the path. * To change the logo, specify the image file as a Base64-encoded string. * To restore the logo inherited from a higher level (store, merchant account, or company account), specify an empty logo value. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateLogoAsync(string terminalId, Logo logo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/{terminalId}/terminalLogos" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/{terminalId}/terminalLogos"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BterminalId%7D", Uri.EscapeDataString(terminalId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (logo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(logo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateLogoApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/{terminalId}/terminalLogos", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateLogo(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateLogo(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateLogoApiResponse : Adyen.Core.Client.ApiResponse, IUpdateLogoApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateLogoApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Logo? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Logo? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update terminal settings Updates the settings that are configured for the payment terminal identified in the path. * To change a parameter value, include the full object that contains the parameter, even if you don't want to change all parameters in the object. * To restore a parameter value inherited from a higher level, include the full object that contains the parameter, and specify an empty value for the parameter or omit the parameter. * Objects that are not included in the request are not updated. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Terminal settings read and write For [sensitive terminal settings](https://docs.adyen.com/point-of-sale/automating-terminal-management/configure-terminals-api#sensitive-terminal-settings), your API credential must have the following role: * Management API—Terminal settings Advanced read and write In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateTerminalSettingsAsync(string terminalId, TerminalSettings terminalSettings, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/{terminalId}/terminalSettings" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/{terminalId}/terminalSettings"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BterminalId%7D", Uri.EscapeDataString(terminalId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalSettings as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalSettings, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TerminalSettingsCompanyLevelService.UpdateTerminalSettingsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/{terminalId}/terminalSettings", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateTerminalSettings(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateTerminalSettings(exception); + throw; + } + } + } +} diff --git a/Adyen/Management/Services/TerminalsTerminalLevelService.cs b/Adyen/Management/Services/TerminalsTerminalLevelService.cs new file mode 100644 index 000000000..51f1ed17b --- /dev/null +++ b/Adyen/Management/Services/TerminalsTerminalLevelService.cs @@ -0,0 +1,982 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITerminalsTerminalLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TerminalsTerminalLevelServiceEvents Events { get; } + + /// + /// Get a list of terminals + /// + /// + /// Returns the payment terminals that the API credential has access to and that match the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API — Terminal actions read In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// Returns terminals with an ID that contains the specified string. If present, other query parameters are ignored. + /// Returns one or more terminals associated with the one-time passwords specified in the request. If this query parameter is used, other query parameters are ignored. + /// Returns terminals located in the countries specified by their [two-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + /// Returns terminals that belong to the merchant accounts specified by their unique merchant account ID. + /// Returns terminals that are assigned to the [stores](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores) specified by their unique store ID. + /// Returns terminals of the [models](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) specified in the format *brand.model*. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. + /// . + /// . + /// of . + Task ListTerminalsAsync(Option searchQuery = default, Option otpQuery = default, Option countries = default, Option merchantIds = default, Option storeIds = default, Option brandModels = default, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Reassign a terminal + /// + /// + /// Reassigns a payment terminal to a company account, merchant account, merchant account inventory, or a store. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Assign Terminal In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// + /// . + /// . + /// of . + Task ReassignTerminalAsync(string terminalId, TerminalReassignmentRequest terminalReassignmentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IListTerminalsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IReassignTerminalApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TerminalsTerminalLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListTerminals; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListTerminals; + + internal void ExecuteOnListTerminals(TerminalsTerminalLevelService.ListTerminalsApiResponse apiResponse) + { + OnListTerminals?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListTerminals(Exception exception) + { + OnErrorListTerminals?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnReassignTerminal; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorReassignTerminal; + + internal void ExecuteOnReassignTerminal(TerminalsTerminalLevelService.ReassignTerminalApiResponse apiResponse) + { + OnReassignTerminal?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorReassignTerminal(Exception exception) + { + OnErrorReassignTerminal?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TerminalsTerminalLevelService : ITerminalsTerminalLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TerminalsTerminalLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TerminalsTerminalLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TerminalsTerminalLevelServiceEvents terminalsTerminalLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = terminalsTerminalLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a list of terminals Returns the payment terminals that the API credential has access to and that match the query parameters. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API — Terminal actions read In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// Returns terminals with an ID that contains the specified string. If present, other query parameters are ignored. () + /// Returns one or more terminals associated with the one-time passwords specified in the request. If this query parameter is used, other query parameters are ignored. () + /// Returns terminals located in the countries specified by their [two-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). () + /// Returns terminals that belong to the merchant accounts specified by their unique merchant account ID. () + /// Returns terminals that are assigned to the [stores](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores) specified by their unique store ID. () + /// Returns terminals of the [models](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) specified in the format *brand.model*. () + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 20 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListTerminalsAsync(Option searchQuery = default, Option otpQuery = default, Option countries = default, Option merchantIds = default, Option storeIds = default, Option brandModels = default, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (searchQuery.IsSet) + parseQueryString["searchQuery"] = ClientUtils.ParameterToString(searchQuery.Value); + + if (otpQuery.IsSet) + parseQueryString["otpQuery"] = ClientUtils.ParameterToString(otpQuery.Value); + + if (countries.IsSet) + parseQueryString["countries"] = ClientUtils.ParameterToString(countries.Value); + + if (merchantIds.IsSet) + parseQueryString["merchantIds"] = ClientUtils.ParameterToString(merchantIds.Value); + + if (storeIds.IsSet) + parseQueryString["storeIds"] = ClientUtils.ParameterToString(storeIds.Value); + + if (brandModels.IsSet) + parseQueryString["brandModels"] = ClientUtils.ParameterToString(brandModels.Value); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListTerminalsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListTerminals(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListTerminals(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListTerminalsApiResponse : Adyen.Core.Client.ApiResponse, IListTerminalsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListTerminalsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListTerminalsResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListTerminalsResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Reassign a terminal Reassigns a payment terminal to a company account, merchant account, merchant account inventory, or a store. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Assign Terminal In the live environment, requests to this endpoint are subject to [rate limits](https://docs.adyen.com/point-of-sale/automating-terminal-management#rate-limits-in-the-live-environment). + /// + /// Thrown when fails to make API call. + /// The unique identifier of the payment terminal. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ReassignTerminalAsync(string terminalId, TerminalReassignmentRequest terminalReassignmentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/terminals/{terminalId}/reassign" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/terminals/{terminalId}/reassign"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BterminalId%7D", Uri.EscapeDataString(terminalId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (terminalReassignmentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(terminalReassignmentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ReassignTerminalApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/terminals/{terminalId}/reassign", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnReassignTerminal(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorReassignTerminal(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ReassignTerminalApiResponse : Adyen.Core.Client.ApiResponse, IReassignTerminalApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReassignTerminalApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReassignTerminalApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/UsersCompanyLevelService.cs b/Adyen/Management/Services/UsersCompanyLevelService.cs new file mode 100644 index 000000000..7fb155d2d --- /dev/null +++ b/Adyen/Management/Services/UsersCompanyLevelService.cs @@ -0,0 +1,1874 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IUsersCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + UsersCompanyLevelServiceEvents Events { get; } + + /// + /// Create a new user + /// + /// + /// Creates the user for the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// + /// . + /// . + /// of . + Task CreateNewUserAsync(string companyId, CreateCompanyUserRequest createCompanyUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get user details + /// + /// + /// Returns user details for the `userId` and the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the user. + /// . + /// . + /// of . + Task GetUserDetailsAsync(string companyId, string userId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of users + /// + /// + /// Returns the list of users for the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to return. + /// The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. + /// The partial or complete username to select all users that match. + /// . + /// . + /// of . + Task ListUsersAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option username = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update user details + /// + /// + /// Updates user details for the `userId` and the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the user. + /// + /// . + /// . + /// of . + Task UpdateUserDetailsAsync(string companyId, string userId, UpdateCompanyUserRequest updateCompanyUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateNewUserApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetUserDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListUsersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateUserDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class UsersCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateNewUser; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateNewUser; + + internal void ExecuteOnCreateNewUser(UsersCompanyLevelService.CreateNewUserApiResponse apiResponse) + { + OnCreateNewUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateNewUser(Exception exception) + { + OnErrorCreateNewUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetUserDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetUserDetails; + + internal void ExecuteOnGetUserDetails(UsersCompanyLevelService.GetUserDetailsApiResponse apiResponse) + { + OnGetUserDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserDetails(Exception exception) + { + OnErrorGetUserDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListUsers; + + internal void ExecuteOnListUsers(UsersCompanyLevelService.ListUsersApiResponse apiResponse) + { + OnListUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListUsers(Exception exception) + { + OnErrorListUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateUserDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateUserDetails; + + internal void ExecuteOnUpdateUserDetails(UsersCompanyLevelService.UpdateUserDetailsApiResponse apiResponse) + { + OnUpdateUserDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateUserDetails(Exception exception) + { + OnErrorUpdateUserDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class UsersCompanyLevelService : IUsersCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public UsersCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public UsersCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, UsersCompanyLevelServiceEvents usersCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = usersCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a new user Creates the user for the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateNewUserAsync(string companyId, CreateCompanyUserRequest createCompanyUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/users"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createCompanyUserRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createCompanyUserRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateNewUserApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/users", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateNewUser(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateNewUser(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateNewUserApiResponse : Adyen.Core.Client.ApiResponse, ICreateNewUserApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateNewUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateNewUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CreateCompanyUserResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CreateCompanyUserResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get user details Returns user details for the `userId` and the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the user. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetUserDetailsAsync(string companyId, string userId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/users/{userId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/users/{userId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BuserId%7D", Uri.EscapeDataString(userId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetUserDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/users/{userId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetUserDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetUserDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetUserDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetUserDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetUserDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetUserDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CompanyUser? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CompanyUser? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of users Returns the list of users for the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The number of the page to return. () + /// The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. () + /// The partial or complete username to select all users that match. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListUsersAsync(string companyId, Option pageNumber = default, Option pageSize = default, Option username = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/users"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (username.IsSet) + parseQueryString["username"] = ClientUtils.ParameterToString(username.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/users", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListUsers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListUsersApiResponse : Adyen.Core.Client.ApiResponse, IListUsersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListCompanyUsersResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListCompanyUsersResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update user details Updates user details for the `userId` and the `companyId` identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// The unique identifier of the user. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateUserDetailsAsync(string companyId, string userId, UpdateCompanyUserRequest updateCompanyUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/users/{userId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/users/{userId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BuserId%7D", Uri.EscapeDataString(userId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateCompanyUserRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateCompanyUserRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateUserDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/users/{userId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateUserDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateUserDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateUserDetailsApiResponse : Adyen.Core.Client.ApiResponse, IUpdateUserDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateUserDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateUserDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.CompanyUser? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.CompanyUser? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/UsersMerchantLevelService.cs b/Adyen/Management/Services/UsersMerchantLevelService.cs new file mode 100644 index 000000000..8ddb8dd73 --- /dev/null +++ b/Adyen/Management/Services/UsersMerchantLevelService.cs @@ -0,0 +1,908 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IUsersMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + UsersMerchantLevelServiceEvents Events { get; } + + /// + /// Create a new user + /// + /// + /// Creates a user for the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// + /// . + /// . + /// of . + Task CreateNewUserAsync(string merchantId, CreateMerchantUserRequest createMerchantUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get user details + /// + /// + /// Returns user details for the `userId` and the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// Unique identifier of the user. + /// . + /// . + /// of . + Task GetUserDetailsAsync(string merchantId, string userId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of users + /// + /// + /// Returns a list of users associated with the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// The number of the page to fetch. + /// The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. + /// The partial or complete username to select all users that match. + /// . + /// . + /// of . + Task ListUsersAsync(string merchantId, Option pageNumber = default, Option pageSize = default, Option username = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a user + /// + /// + /// Updates user details for the `userId` and the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// Unique identifier of the user. + /// + /// . + /// . + /// of . + Task UpdateUserAsync(string merchantId, string userId, UpdateMerchantUserRequest updateMerchantUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IUpdateUserApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class UsersMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateNewUser; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateNewUser; + + internal void ExecuteOnCreateNewUser(UsersCompanyLevelService.CreateNewUserApiResponse apiResponse) + { + OnCreateNewUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateNewUser(Exception exception) + { + OnErrorCreateNewUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetUserDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetUserDetails; + + internal void ExecuteOnGetUserDetails(UsersCompanyLevelService.GetUserDetailsApiResponse apiResponse) + { + OnGetUserDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserDetails(Exception exception) + { + OnErrorGetUserDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListUsers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListUsers; + + internal void ExecuteOnListUsers(UsersCompanyLevelService.ListUsersApiResponse apiResponse) + { + OnListUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListUsers(Exception exception) + { + OnErrorListUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateUser; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateUser; + + internal void ExecuteOnUpdateUser(UsersMerchantLevelService.UpdateUserApiResponse apiResponse) + { + OnUpdateUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateUser(Exception exception) + { + OnErrorUpdateUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class UsersMerchantLevelService : IUsersMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public UsersMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public UsersMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, UsersMerchantLevelServiceEvents usersMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = usersMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a new user Creates a user for the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateNewUserAsync(string merchantId, CreateMerchantUserRequest createMerchantUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/users"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createMerchantUserRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createMerchantUserRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UsersCompanyLevelService.CreateNewUserApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/users", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateNewUser(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateNewUser(exception); + throw; + } + } + /// + /// Get user details Returns user details for the `userId` and the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// Unique identifier of the user. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetUserDetailsAsync(string merchantId, string userId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/users/{userId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/users/{userId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BuserId%7D", Uri.EscapeDataString(userId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UsersCompanyLevelService.GetUserDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/users/{userId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetUserDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetUserDetails(exception); + throw; + } + } + /// + /// Get a list of users Returns a list of users associated with the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// The number of the page to fetch. () + /// The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. () + /// The partial or complete username to select all users that match. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListUsersAsync(string merchantId, Option pageNumber = default, Option pageSize = default, Option username = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/users"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + if (username.IsSet) + parseQueryString["username"] = ClientUtils.ParameterToString(username.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UsersCompanyLevelService.ListUsersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/users", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListUsers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListUsers(exception); + throw; + } + } + /// + /// Update a user Updates user details for the `userId` and the `merchantId` specified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Users read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the merchant. + /// Unique identifier of the user. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateUserAsync(string merchantId, string userId, UpdateMerchantUserRequest updateMerchantUserRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/users/{userId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/users/{userId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BuserId%7D", Uri.EscapeDataString(userId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateMerchantUserRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateMerchantUserRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateUserApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/users/{userId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateUser(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateUser(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateUserApiResponse : Adyen.Core.Client.ApiResponse, IUpdateUserApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.User? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.User? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/WebhooksCompanyLevelService.cs b/Adyen/Management/Services/WebhooksCompanyLevelService.cs new file mode 100644 index 000000000..f2d522bdd --- /dev/null +++ b/Adyen/Management/Services/WebhooksCompanyLevelService.cs @@ -0,0 +1,3151 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IWebhooksCompanyLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + WebhooksCompanyLevelServiceEvents Events { get; } + + /// + /// Generate an HMAC key + /// + /// + /// Returns an [HMAC key](https://en.wikipedia.org/wiki/HMAC) for the webhook identified in the path. This key allows you to check the integrity and the origin of the notifications you receive.By creating an HMAC key, you start receiving [HMAC-signed notifications](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures#enable-hmac-signatures) from Adyen. Find out more about how to [verify HMAC signatures](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of . + Task GenerateHmacKeyAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a webhook + /// + /// + /// Returns the configuration for the webhook identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of . + Task GetWebhookAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List all webhooks + /// + /// + /// Lists all webhook configurations for the company account. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListAllWebhooksAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a webhook + /// + /// + /// Remove the configuration for the webhook identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of . + Task RemoveWebhookAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Set up a webhook + /// + /// + /// Subscribe to receive webhook notifications about events related to your company account. You can add basic authentication to make sure the data is secure. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// + /// . + /// . + /// of . + Task SetUpWebhookAsync(string companyId, CreateCompanyWebhookRequest createCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Test a webhook + /// + /// + /// Sends sample notifications to test if the webhook is set up correctly. We send sample notifications for maximum 20 of the merchant accounts that the webhook is configured for. If the webhook is configured for more than 20 merchant accounts, use the `merchantIds` array to specify a subset of the merchant accounts for which to send test notifications. We send four test notifications for each event code you choose. They cover success and failure scenarios for the hard-coded currencies EUR and GBP, regardless of the currencies configured in the merchant accounts. For custom notifications, we only send the specified custom notification. The response describes the result of the test. The `status` field tells you if the test was successful or not. You can use the other response fields to troubleshoot unsuccessful tests. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// + /// . + /// . + /// of . + Task TestWebhookAsync(string companyId, string webhookId, TestCompanyWebhookRequest testCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a webhook + /// + /// + /// Make changes to the configuration of the webhook identified in the path. The request contains the new values you want to have in the webhook configuration. The response contains the full configuration for the webhook, which includes the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// + /// . + /// . + /// of . + Task UpdateWebhookAsync(string companyId, string webhookId, UpdateCompanyWebhookRequest updateCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGenerateHmacKeyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetWebhookApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListAllWebhooksApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRemoveWebhookApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 204 NoContent. + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISetUpWebhookApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ITestWebhookApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IUpdateWebhookApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class WebhooksCompanyLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateHmacKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateHmacKey; + + internal void ExecuteOnGenerateHmacKey(WebhooksCompanyLevelService.GenerateHmacKeyApiResponse apiResponse) + { + OnGenerateHmacKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateHmacKey(Exception exception) + { + OnErrorGenerateHmacKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetWebhook; + + internal void ExecuteOnGetWebhook(WebhooksCompanyLevelService.GetWebhookApiResponse apiResponse) + { + OnGetWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWebhook(Exception exception) + { + OnErrorGetWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAllWebhooks; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAllWebhooks; + + internal void ExecuteOnListAllWebhooks(WebhooksCompanyLevelService.ListAllWebhooksApiResponse apiResponse) + { + OnListAllWebhooks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAllWebhooks(Exception exception) + { + OnErrorListAllWebhooks?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRemoveWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRemoveWebhook; + + internal void ExecuteOnRemoveWebhook(WebhooksCompanyLevelService.RemoveWebhookApiResponse apiResponse) + { + OnRemoveWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveWebhook(Exception exception) + { + OnErrorRemoveWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSetUpWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSetUpWebhook; + + internal void ExecuteOnSetUpWebhook(WebhooksCompanyLevelService.SetUpWebhookApiResponse apiResponse) + { + OnSetUpWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSetUpWebhook(Exception exception) + { + OnErrorSetUpWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnTestWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorTestWebhook; + + internal void ExecuteOnTestWebhook(WebhooksCompanyLevelService.TestWebhookApiResponse apiResponse) + { + OnTestWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestWebhook(Exception exception) + { + OnErrorTestWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateWebhook; + + internal void ExecuteOnUpdateWebhook(WebhooksCompanyLevelService.UpdateWebhookApiResponse apiResponse) + { + OnUpdateWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateWebhook(Exception exception) + { + OnErrorUpdateWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class WebhooksCompanyLevelService : IWebhooksCompanyLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public WebhooksCompanyLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public WebhooksCompanyLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WebhooksCompanyLevelServiceEvents webhooksCompanyLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = webhooksCompanyLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate an HMAC key Returns an [HMAC key](https://en.wikipedia.org/wiki/HMAC) for the webhook identified in the path. This key allows you to check the integrity and the origin of the notifications you receive.By creating an HMAC key, you start receiving [HMAC-signed notifications](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures#enable-hmac-signatures) from Adyen. Find out more about how to [verify HMAC signatures](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateHmacKeyAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks/{webhookId}/generateHmac" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks/{webhookId}/generateHmac"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GenerateHmacKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks/{webhookId}/generateHmac", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateHmacKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateHmacKey(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GenerateHmacKeyApiResponse : Adyen.Core.Client.ApiResponse, IGenerateHmacKeyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateHmacKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GenerateHmacKeyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.GenerateHmacKeyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.GenerateHmacKeyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a webhook Returns the configuration for the webhook identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetWebhookAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetWebhook(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetWebhookApiResponse : Adyen.Core.Client.ApiResponse, IGetWebhookApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Webhook? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Webhook? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// List all webhooks Lists all webhook configurations for the company account. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAllWebhooksAsync(string companyId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListAllWebhooksApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAllWebhooks(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAllWebhooks(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListAllWebhooksApiResponse : Adyen.Core.Client.ApiResponse, IListAllWebhooksApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAllWebhooksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListAllWebhooksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.ListWebhooksResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.ListWebhooksResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Remove a webhook Remove the configuration for the webhook identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RemoveWebhookAsync(string companyId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RemoveWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRemoveWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRemoveWebhook(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RemoveWebhookApiResponse : Adyen.Core.Client.ApiResponse, IRemoveWebhookApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RemoveWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent. + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Set up a webhook Subscribe to receive webhook notifications about events related to your company account. You can add basic authentication to make sure the data is secure. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SetUpWebhookAsync(string companyId, CreateCompanyWebhookRequest createCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createCompanyWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createCompanyWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SetUpWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSetUpWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSetUpWebhook(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SetUpWebhookApiResponse : Adyen.Core.Client.ApiResponse, ISetUpWebhookApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SetUpWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SetUpWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Webhook? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Webhook? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Test a webhook Sends sample notifications to test if the webhook is set up correctly. We send sample notifications for maximum 20 of the merchant accounts that the webhook is configured for. If the webhook is configured for more than 20 merchant accounts, use the `merchantIds` array to specify a subset of the merchant accounts for which to send test notifications. We send four test notifications for each event code you choose. They cover success and failure scenarios for the hard-coded currencies EUR and GBP, regardless of the currencies configured in the merchant accounts. For custom notifications, we only send the specified custom notification. The response describes the result of the test. The `status` field tells you if the test was successful or not. You can use the other response fields to troubleshoot unsuccessful tests. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task TestWebhookAsync(string companyId, string webhookId, TestCompanyWebhookRequest testCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks/{webhookId}/test" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks/{webhookId}/test"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (testCompanyWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(testCompanyWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TestWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks/{webhookId}/test", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnTestWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorTestWebhook(exception); + throw; + } + } + + /// + /// The . + /// + public partial class TestWebhookApiResponse : Adyen.Core.Client.ApiResponse, ITestWebhookApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TestWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TestWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.TestWebhookResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.TestWebhookResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Update a webhook Make changes to the configuration of the webhook identified in the path. The request contains the new values you want to have in the webhook configuration. The response contains the full configuration for the webhook, which includes the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the company account. + /// Unique identifier of the webhook configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateWebhookAsync(string companyId, string webhookId, UpdateCompanyWebhookRequest updateCompanyWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/companies/{companyId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/companies/{companyId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BcompanyId%7D", Uri.EscapeDataString(companyId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateCompanyWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateCompanyWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + UpdateWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/companies/{companyId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateWebhook(exception); + throw; + } + } + + /// + /// The . + /// + public partial class UpdateWebhookApiResponse : Adyen.Core.Client.ApiResponse, IUpdateWebhookApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public UpdateWebhookApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Management.Models.Webhook? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Management.Models.Webhook? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Management.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Management.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Management.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Management.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Management.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Management.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Management/Services/WebhooksMerchantLevelService.cs b/Adyen/Management/Services/WebhooksMerchantLevelService.cs new file mode 100644 index 000000000..be9518743 --- /dev/null +++ b/Adyen/Management/Services/WebhooksMerchantLevelService.cs @@ -0,0 +1,901 @@ +// +/* + * Management API + * + * Configure and manage your Adyen company and merchant accounts, stores, and payment terminals. ## Authentication Each request to the Management API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. To access the live endpoints, you need to generate a new API key in your live Customer Area. ## Versioning Management API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/companies/{companyId}/webhooks` endpoint, use: ```text https://management-test.adyen.com/v3/companies/{companyId}/webhooks ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v3 ``` ## Release notes Have a look at the [release notes](https://docs.adyen.com/release-notes/management-api) to find out what changed in this version! + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Management.Client; +using Adyen.Management.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Management.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IWebhooksMerchantLevelService : IAdyenApiService + { + /// + /// The class containing the events. + /// + WebhooksMerchantLevelServiceEvents Events { get; } + + /// + /// Generate an HMAC key + /// + /// + /// Returns an [HMAC key](https://en.wikipedia.org/wiki/HMAC) for the webhook identified in the path. This key allows you to check the integrity and the origin of the notifications you receive.By creating an HMAC key, you start receiving [HMAC-signed notifications](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures#enable-hmac-signatures) from Adyen. Find out more about how to [verify HMAC signatures](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task GenerateHmacKeyAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a webhook + /// + /// + /// Returns the configuration for the webhook identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of . + Task GetWebhookAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List all webhooks + /// + /// + /// Lists all webhook configurations for the merchant account. > This call does not return webhook configurations for the company account to which the specified merchant account belongs. You can see these in your Customer Area under **Developers** > **Webhooks**. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. + /// . + /// . + /// of . + Task ListAllWebhooksAsync(string merchantId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a webhook + /// + /// + /// Remove the configuration for the webhook identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of . + Task RemoveWebhookAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Set up a webhook + /// + /// + /// Subscribe to receive webhook notifications about events related to your merchant account. You can add basic authentication to make sure the data is secure. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task SetUpWebhookAsync(string merchantId, CreateMerchantWebhookRequest createMerchantWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Test a webhook + /// + /// + /// Sends sample notifications to test if the webhook is set up correctly. We send four test notifications for each event code you choose. They cover success and failure scenarios for the hard-coded currencies EUR and GBP, regardless of the currencies configured in the merchant accounts. For custom notifications, we only send the specified custom notification. The response describes the result of the test. The `status` field tells you if the test was successful or not. You can use the other fields to troubleshoot unsuccessful tests. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// + /// . + /// . + /// of . + Task TestWebhookAsync(string merchantId, string webhookId, TestWebhookRequest testWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a webhook + /// + /// + /// Make changes to the configuration of the webhook identified in the path. The request contains the new values you want to have in the webhook configuration. The response contains the full configuration for the webhook, which includes the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// + /// . + /// . + /// of . + Task UpdateWebhookAsync(string merchantId, string webhookId, UpdateMerchantWebhookRequest updateMerchantWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class WebhooksMerchantLevelServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGenerateHmacKey; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGenerateHmacKey; + + internal void ExecuteOnGenerateHmacKey(WebhooksCompanyLevelService.GenerateHmacKeyApiResponse apiResponse) + { + OnGenerateHmacKey?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGenerateHmacKey(Exception exception) + { + OnErrorGenerateHmacKey?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetWebhook; + + internal void ExecuteOnGetWebhook(WebhooksCompanyLevelService.GetWebhookApiResponse apiResponse) + { + OnGetWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWebhook(Exception exception) + { + OnErrorGetWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListAllWebhooks; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListAllWebhooks; + + internal void ExecuteOnListAllWebhooks(WebhooksCompanyLevelService.ListAllWebhooksApiResponse apiResponse) + { + OnListAllWebhooks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListAllWebhooks(Exception exception) + { + OnErrorListAllWebhooks?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRemoveWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRemoveWebhook; + + internal void ExecuteOnRemoveWebhook(WebhooksCompanyLevelService.RemoveWebhookApiResponse apiResponse) + { + OnRemoveWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveWebhook(Exception exception) + { + OnErrorRemoveWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSetUpWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSetUpWebhook; + + internal void ExecuteOnSetUpWebhook(WebhooksCompanyLevelService.SetUpWebhookApiResponse apiResponse) + { + OnSetUpWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSetUpWebhook(Exception exception) + { + OnErrorSetUpWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnTestWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorTestWebhook; + + internal void ExecuteOnTestWebhook(WebhooksCompanyLevelService.TestWebhookApiResponse apiResponse) + { + OnTestWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestWebhook(Exception exception) + { + OnErrorTestWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnUpdateWebhook; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorUpdateWebhook; + + internal void ExecuteOnUpdateWebhook(WebhooksCompanyLevelService.UpdateWebhookApiResponse apiResponse) + { + OnUpdateWebhook?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateWebhook(Exception exception) + { + OnErrorUpdateWebhook?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class WebhooksMerchantLevelService : IWebhooksMerchantLevelService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public WebhooksMerchantLevelServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public WebhooksMerchantLevelService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WebhooksMerchantLevelServiceEvents webhooksMerchantLevelServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = webhooksMerchantLevelServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Generate an HMAC key Returns an [HMAC key](https://en.wikipedia.org/wiki/HMAC) for the webhook identified in the path. This key allows you to check the integrity and the origin of the notifications you receive.By creating an HMAC key, you start receiving [HMAC-signed notifications](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures#enable-hmac-signatures) from Adyen. Find out more about how to [verify HMAC signatures](https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures). To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GenerateHmacKeyAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks/{webhookId}/generateHmac" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks/{webhookId}/generateHmac"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.GenerateHmacKeyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks/{webhookId}/generateHmac", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGenerateHmacKey(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGenerateHmacKey(exception); + throw; + } + } + /// + /// Get a webhook Returns the configuration for the webhook identified in the path. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetWebhookAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.GetWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetWebhook(exception); + throw; + } + } + /// + /// List all webhooks Lists all webhook configurations for the merchant account. > This call does not return webhook configurations for the company account to which the specified merchant account belongs. You can see these in your Customer Area under **Developers** > **Webhooks**. To make this request, your API credential must have one of the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The number of the page to fetch. () + /// The number of items to have on a page, maximum 100. The default is 10 items on a page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListAllWebhooksAsync(string merchantId, Option pageNumber = default, Option pageSize = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageNumber.IsSet) + parseQueryString["pageNumber"] = ClientUtils.ParameterToString(pageNumber.Value); + + if (pageSize.IsSet) + parseQueryString["pageSize"] = ClientUtils.ParameterToString(pageSize.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.ListAllWebhooksApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListAllWebhooks(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListAllWebhooks(exception); + throw; + } + } + /// + /// Remove a webhook Remove the configuration for the webhook identified in the path. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RemoveWebhookAsync(string merchantId, string webhookId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Delete; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.RemoveWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRemoveWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRemoveWebhook(exception); + throw; + } + } + /// + /// Set up a webhook Subscribe to receive webhook notifications about events related to your merchant account. You can add basic authentication to make sure the data is secure. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SetUpWebhookAsync(string merchantId, CreateMerchantWebhookRequest createMerchantWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createMerchantWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createMerchantWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.SetUpWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSetUpWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSetUpWebhook(exception); + throw; + } + } + /// + /// Test a webhook Sends sample notifications to test if the webhook is set up correctly. We send four test notifications for each event code you choose. They cover success and failure scenarios for the hard-coded currencies EUR and GBP, regardless of the currencies configured in the merchant accounts. For custom notifications, we only send the specified custom notification. The response describes the result of the test. The `status` field tells you if the test was successful or not. You can use the other fields to troubleshoot unsuccessful tests. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task TestWebhookAsync(string merchantId, string webhookId, TestWebhookRequest testWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks/{webhookId}/test" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks/{webhookId}/test"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (testWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(testWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.TestWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks/{webhookId}/test", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnTestWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorTestWebhook(exception); + throw; + } + } + /// + /// Update a webhook Make changes to the configuration of the webhook identified in the path. The request contains the new values you want to have in the webhook configuration. The response contains the full configuration for the webhook, which includes the new values from the request. To make this request, your API credential must have the following [roles](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Management API—Webhooks read and write + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// Unique identifier of the webhook configuration. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task UpdateWebhookAsync(string merchantId, string webhookId, UpdateMerchantWebhookRequest updateMerchantWebhookRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/webhooks/{webhookId}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/webhooks/{webhookId}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BwebhookId%7D", Uri.EscapeDataString(webhookId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (updateMerchantWebhookRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(updateMerchantWebhookRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Patch; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + WebhooksCompanyLevelService.UpdateWebhookApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/webhooks/{webhookId}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnUpdateWebhook(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorUpdateWebhook(exception); + throw; + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Client/ClientUtils.cs b/Adyen/ManagementWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..db4fc8ddc --- /dev/null +++ b/Adyen/ManagementWebhooks/Client/ClientUtils.cs @@ -0,0 +1,315 @@ +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.ManagementWebhooks.Models; +using Models = Adyen.ManagementWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.ManagementWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.CapabilityProblemEntity.TypeEnum capabilityProblemEntityTypeEnum) + return Models.CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntityTypeEnum); + if (obj is Models.CapabilityProblemEntityRecursive.TypeEnum capabilityProblemEntityRecursiveTypeEnum) + return Models.CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursiveTypeEnum); + if (obj is Models.MerchantCreatedNotificationRequest.TypeEnum merchantCreatedNotificationRequestTypeEnum) + return Models.MerchantCreatedNotificationRequest.TypeEnum.ToJsonValue(merchantCreatedNotificationRequestTypeEnum); + if (obj is Models.MerchantUpdatedNotificationRequest.TypeEnum merchantUpdatedNotificationRequestTypeEnum) + return Models.MerchantUpdatedNotificationRequest.TypeEnum.ToJsonValue(merchantUpdatedNotificationRequestTypeEnum); + if (obj is Models.MidServiceNotificationData.StatusEnum midServiceNotificationDataStatusEnum) + return Models.MidServiceNotificationData.StatusEnum.ToJsonValue(midServiceNotificationDataStatusEnum); + if (obj is Models.MidServiceNotificationData.VerificationStatusEnum midServiceNotificationDataVerificationStatusEnum) + return Models.MidServiceNotificationData.VerificationStatusEnum.ToJsonValue(midServiceNotificationDataVerificationStatusEnum); + if (obj is Models.PaymentMethodCreatedNotificationRequest.TypeEnum paymentMethodCreatedNotificationRequestTypeEnum) + return Models.PaymentMethodCreatedNotificationRequest.TypeEnum.ToJsonValue(paymentMethodCreatedNotificationRequestTypeEnum); + if (obj is Models.PaymentMethodRequestRemovedNotificationRequest.TypeEnum paymentMethodRequestRemovedNotificationRequestTypeEnum) + return Models.PaymentMethodRequestRemovedNotificationRequest.TypeEnum.ToJsonValue(paymentMethodRequestRemovedNotificationRequestTypeEnum); + if (obj is Models.PaymentMethodScheduledForRemovalNotificationRequest.TypeEnum paymentMethodScheduledForRemovalNotificationRequestTypeEnum) + return Models.PaymentMethodScheduledForRemovalNotificationRequest.TypeEnum.ToJsonValue(paymentMethodScheduledForRemovalNotificationRequestTypeEnum); + if (obj is Models.TerminalBoardingNotificationRequest.TypeEnum terminalBoardingNotificationRequestTypeEnum) + return Models.TerminalBoardingNotificationRequest.TypeEnum.ToJsonValue(terminalBoardingNotificationRequestTypeEnum); + if (obj is Models.TerminalSettingsData.UpdateSourceEnum terminalSettingsDataUpdateSourceEnum) + return Models.TerminalSettingsData.UpdateSourceEnum.ToJsonValue(terminalSettingsDataUpdateSourceEnum); + if (obj is Models.TerminalSettingsNotificationRequest.TypeEnum terminalSettingsNotificationRequestTypeEnum) + return Models.TerminalSettingsNotificationRequest.TypeEnum.ToJsonValue(terminalSettingsNotificationRequestTypeEnum); + if (obj is Models.VerificationError.TypeEnum verificationErrorTypeEnum) + return Models.VerificationError.TypeEnum.ToJsonValue(verificationErrorTypeEnum); + if (obj is Models.VerificationErrorRecursive.TypeEnum verificationErrorRecursiveTypeEnum) + return Models.VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursiveTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/ManagementWebhooks/Client/HmacKeyToken.cs b/Adyen/ManagementWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..9446ac1fc --- /dev/null +++ b/Adyen/ManagementWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.ManagementWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/ManagementWebhooks/Client/HostConfiguration.cs b/Adyen/ManagementWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..783dbe356 --- /dev/null +++ b/Adyen/ManagementWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,152 @@ +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.ManagementWebhooks.Client; +using Adyen.ManagementWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.ManagementWebhooks.Client +{ + /// + /// Provides hosting configuration for ManagementWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountCapabilityDataJsonConverter()); + _jsonOptions.Converters.Add(new AccountCreateNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new AccountNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new AccountUpdateNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityJsonConverter()); + _jsonOptions.Converters.Add(new CapabilityProblemEntityRecursiveJsonConverter()); + _jsonOptions.Converters.Add(new MerchantCreatedNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new MerchantUpdatedNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new MidServiceNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodCreatedNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodRequestRemovedNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentMethodScheduledForRemovalNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new RemediatingActionJsonConverter()); + _jsonOptions.Converters.Add(new TerminalAssignmentNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TerminalAssignmentNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new TerminalBoardingDataJsonConverter()); + _jsonOptions.Converters.Add(new TerminalBoardingNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TerminalBoardingNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new TerminalSettingsDataJsonConverter()); + _jsonOptions.Converters.Add(new TerminalSettingsNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TerminalSettingsNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorJsonConverter()); + _jsonOptions.Converters.Add(new VerificationErrorRecursiveJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddManagementWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/ManagementWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/ManagementWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..4892c303c --- /dev/null +++ b/Adyen/ManagementWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.ManagementWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/ManagementWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/ManagementWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..fae6e892f --- /dev/null +++ b/Adyen/ManagementWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.ManagementWebhooks; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the ManagementWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureManagementWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddManagementWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/ManagementWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/ManagementWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..b05edc40f --- /dev/null +++ b/Adyen/ManagementWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen ManagementWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddManagementWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddManagementWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/ManagementWebhooks/Handlers/ManagementWebhooksHandler.cs b/Adyen/ManagementWebhooks/Handlers/ManagementWebhooksHandler.cs new file mode 100644 index 000000000..311a15e05 --- /dev/null +++ b/Adyen/ManagementWebhooks/Handlers/ManagementWebhooksHandler.cs @@ -0,0 +1,160 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.ManagementWebhooks.Client; +using Adyen.ManagementWebhooks.Models; + +namespace Adyen.ManagementWebhooks.Handlers +{ + /// + /// Interface for deserializing ManagementWebhooks webhooks or verify its HMAC signature. + /// + public interface IManagementWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.ManagementWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + MerchantCreatedNotificationRequest? DeserializeMerchantCreatedNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + MerchantUpdatedNotificationRequest? DeserializeMerchantUpdatedNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + PaymentMethodCreatedNotificationRequest? DeserializePaymentMethodCreatedNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + PaymentMethodRequestRemovedNotificationRequest? DeserializePaymentMethodRequestRemovedNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + PaymentMethodScheduledForRemovalNotificationRequest? DeserializePaymentMethodScheduledForRemovalNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TerminalBoardingNotificationRequest? DeserializeTerminalBoardingNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TerminalSettingsNotificationRequest? DeserializeTerminalSettingsNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize ManagementWebhooks or verify the HMAC signature of the webhook. + /// + public partial class ManagementWebhooksHandler : IManagementWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.ManagementWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing ManagementWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public ManagementWebhooksHandler(Adyen.ManagementWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public MerchantCreatedNotificationRequest? DeserializeMerchantCreatedNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public MerchantUpdatedNotificationRequest? DeserializeMerchantUpdatedNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public PaymentMethodCreatedNotificationRequest? DeserializePaymentMethodCreatedNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public PaymentMethodRequestRemovedNotificationRequest? DeserializePaymentMethodRequestRemovedNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public PaymentMethodScheduledForRemovalNotificationRequest? DeserializePaymentMethodScheduledForRemovalNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public TerminalBoardingNotificationRequest? DeserializeTerminalBoardingNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public TerminalSettingsNotificationRequest? DeserializeTerminalSettingsNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/AccountCapabilityData.cs b/Adyen/ManagementWebhooks/Models/AccountCapabilityData.cs new file mode 100644 index 000000000..ef84bb0e6 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/AccountCapabilityData.cs @@ -0,0 +1,344 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// AccountCapabilityData. + /// + public partial class AccountCapabilityData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether you requested the capability. + /// The level that you requested for the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + /// The allowed level of the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + /// The name of the capability. For example, **sendToTransferInstrument**. + /// List of entities that have problems with verification. The information includes the details of the errors and the actions that you can take to resolve them. + /// The verification deadline for the capability that will be disallowed if verification errors are not resolved. + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification was successful. * **rejected**: Adyen checked the information and found reasons to not allow the capability. + [JsonConstructor] + public AccountCapabilityData(bool requested, string requestedLevel, Option allowed = default, Option allowedLevel = default, Option capability = default, Option?> problems = default, Option verificationDeadline = default, Option verificationStatus = default) + { + Requested = requested; + RequestedLevel = requestedLevel; + _AllowedOption = allowed; + _AllowedLevelOption = allowedLevel; + _CapabilityOption = capability; + _ProblemsOption = problems; + _VerificationDeadlineOption = verificationDeadline; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountCapabilityData() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether you requested the capability. + /// + /// Indicates whether you requested the capability. + [JsonPropertyName("requested")] + public bool Requested { get; set; } + + /// + /// The level that you requested for the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The level that you requested for the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("requestedLevel")] + public string RequestedLevel { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + /// + /// Indicates whether the capability is allowed. Adyen sets this to **true** if the verification is successful. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedLevelOption { get; private set; } + + /// + /// The allowed level of the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + /// + /// The allowed level of the capability. Some capabilities have different levels which correspond to thresholds. Higher levels may require additional checks and increased monitoring.Possible values: **notApplicable**, **low**, **medium**, **high**. + [JsonPropertyName("allowedLevel")] + public string? AllowedLevel { get { return this._AllowedLevelOption; } set { this._AllowedLevelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CapabilityOption { get; private set; } + + /// + /// The name of the capability. For example, **sendToTransferInstrument**. + /// + /// The name of the capability. For example, **sendToTransferInstrument**. + [JsonPropertyName("capability")] + public string? Capability { get { return this._CapabilityOption; } set { this._CapabilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ProblemsOption { get; private set; } + + /// + /// List of entities that have problems with verification. The information includes the details of the errors and the actions that you can take to resolve them. + /// + /// List of entities that have problems with verification. The information includes the details of the errors and the actions that you can take to resolve them. + [JsonPropertyName("problems")] + public List? Problems { get { return this._ProblemsOption; } set { this._ProblemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationDeadlineOption { get; private set; } + + /// + /// The verification deadline for the capability that will be disallowed if verification errors are not resolved. + /// + /// The verification deadline for the capability that will be disallowed if verification errors are not resolved. + [JsonPropertyName("verificationDeadline")] + public DateTimeOffset? VerificationDeadline { get { return this._VerificationDeadlineOption; } set { this._VerificationDeadlineOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification was successful. * **rejected**: Adyen checked the information and found reasons to not allow the capability. + /// + /// The status of the verification checks for the capability. Possible values: * **pending**: Adyen is running the verification. * **invalid**: The verification failed. Check if the `errors` array contains more information. * **valid**: The verification was successful. * **rejected**: Adyen checked the information and found reasons to not allow the capability. + [JsonPropertyName("verificationStatus")] + public string? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountCapabilityData {\n"); + sb.Append(" Requested: ").Append(Requested).Append("\n"); + sb.Append(" RequestedLevel: ").Append(RequestedLevel).Append("\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" AllowedLevel: ").Append(AllowedLevel).Append("\n"); + sb.Append(" Capability: ").Append(Capability).Append("\n"); + sb.Append(" Problems: ").Append(Problems).Append("\n"); + sb.Append(" VerificationDeadline: ").Append(VerificationDeadline).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountCapabilityDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize VerificationDeadline. + /// + public static string VerificationDeadlineFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountCapabilityData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requested = default; + Option requestedLevel = default; + Option allowed = default; + Option allowedLevel = default; + Option capability = default; + Option?> problems = default; + Option verificationDeadline = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "requested": + requested = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "requestedLevel": + requestedLevel = new Option(utf8JsonReader.GetString()!); + break; + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "allowedLevel": + allowedLevel = new Option(utf8JsonReader.GetString()!); + break; + case "capability": + capability = new Option(utf8JsonReader.GetString()!); + break; + case "problems": + problems = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationDeadline": + verificationDeadline = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "verificationStatus": + verificationStatus = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!requested.IsSet) + throw new ArgumentException("Property is required for class AccountCapabilityData.", nameof(requested)); + + if (!requestedLevel.IsSet) + throw new ArgumentException("Property is required for class AccountCapabilityData.", nameof(requestedLevel)); + + return new AccountCapabilityData(requested.Value!.Value!, requestedLevel.Value!, allowed, allowedLevel, capability, problems, verificationDeadline, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountCapabilityData accountCapabilityData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountCapabilityData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountCapabilityData accountCapabilityData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteBoolean("requested", accountCapabilityData.Requested); + + if (accountCapabilityData.RequestedLevel != null) + writer.WriteString("requestedLevel", accountCapabilityData.RequestedLevel); + + if (accountCapabilityData._AllowedOption.IsSet) + writer.WriteBoolean("allowed", accountCapabilityData._AllowedOption.Value!.Value); + + if (accountCapabilityData._AllowedLevelOption.IsSet) + if (accountCapabilityData.AllowedLevel != null) + writer.WriteString("allowedLevel", accountCapabilityData.AllowedLevel); + + if (accountCapabilityData._CapabilityOption.IsSet) + if (accountCapabilityData.Capability != null) + writer.WriteString("capability", accountCapabilityData.Capability); + + if (accountCapabilityData._ProblemsOption.IsSet) + { + writer.WritePropertyName("problems"); + JsonSerializer.Serialize(writer, accountCapabilityData.Problems, jsonSerializerOptions); + } + if (accountCapabilityData._VerificationDeadlineOption.IsSet) + writer.WriteString("verificationDeadline", accountCapabilityData._VerificationDeadlineOption.Value!.Value.ToString(VerificationDeadlineFormat)); + + if (accountCapabilityData._VerificationStatusOption.IsSet) + if (accountCapabilityData.VerificationStatus != null) + writer.WriteString("verificationStatus", accountCapabilityData.VerificationStatus); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/AccountCreateNotificationData.cs b/Adyen/ManagementWebhooks/Models/AccountCreateNotificationData.cs new file mode 100644 index 000000000..2d7fbd3d7 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/AccountCreateNotificationData.cs @@ -0,0 +1,255 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// AccountCreateNotificationData. + /// + public partial class AccountCreateNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Key-value pairs that specify the actions that the merchant account can do and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out funds to the bank account. The value is an object containing the settings for the capability. + /// The unique identifier of the company account. + /// The unique identifier of the merchant account. + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + [JsonConstructor] + public AccountCreateNotificationData(Dictionary capabilities, string companyId, string merchantId, string status, Option legalEntityId = default) + { + Capabilities = capabilities; + CompanyId = companyId; + MerchantId = merchantId; + Status = status; + _LegalEntityIdOption = legalEntityId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountCreateNotificationData() + { + } + + partial void OnCreated(); + + /// + /// Key-value pairs that specify the actions that the merchant account can do and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out funds to the bank account. The value is an object containing the settings for the capability. + /// + /// Key-value pairs that specify the actions that the merchant account can do and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out funds to the bank account. The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary Capabilities { get; set; } + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string CompanyId { get; set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("merchantId")] + public string MerchantId { get; set; } + + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LegalEntityIdOption { get; private set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + [JsonPropertyName("legalEntityId")] + public string? LegalEntityId { get { return this._LegalEntityIdOption; } set { this._LegalEntityIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountCreateNotificationData {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountCreateNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountCreateNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option companyId = default; + Option merchantId = default; + Option status = default; + Option legalEntityId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!capabilities.IsSet) + throw new ArgumentException("Property is required for class AccountCreateNotificationData.", nameof(capabilities)); + + if (!companyId.IsSet) + throw new ArgumentException("Property is required for class AccountCreateNotificationData.", nameof(companyId)); + + if (!merchantId.IsSet) + throw new ArgumentException("Property is required for class AccountCreateNotificationData.", nameof(merchantId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AccountCreateNotificationData.", nameof(status)); + + return new AccountCreateNotificationData(capabilities.Value!, companyId.Value!, merchantId.Value!, status.Value!, legalEntityId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountCreateNotificationData accountCreateNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountCreateNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountCreateNotificationData accountCreateNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountCreateNotificationData.Capabilities, jsonSerializerOptions); + if (accountCreateNotificationData.CompanyId != null) + writer.WriteString("companyId", accountCreateNotificationData.CompanyId); + + if (accountCreateNotificationData.MerchantId != null) + writer.WriteString("merchantId", accountCreateNotificationData.MerchantId); + + if (accountCreateNotificationData.Status != null) + writer.WriteString("status", accountCreateNotificationData.Status); + + if (accountCreateNotificationData._LegalEntityIdOption.IsSet) + if (accountCreateNotificationData.LegalEntityId != null) + writer.WriteString("legalEntityId", accountCreateNotificationData.LegalEntityId); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/AccountNotificationResponse.cs b/Adyen/ManagementWebhooks/Models/AccountNotificationResponse.cs new file mode 100644 index 000000000..4c19c5e9d --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/AccountNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// AccountNotificationResponse. + /// + public partial class AccountNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public AccountNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AccountNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountNotificationResponse accountNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountNotificationResponse accountNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountNotificationResponse._NotificationResponseOption.IsSet) + if (accountNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", accountNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/AccountUpdateNotificationData.cs b/Adyen/ManagementWebhooks/Models/AccountUpdateNotificationData.cs new file mode 100644 index 000000000..8b96fff9f --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/AccountUpdateNotificationData.cs @@ -0,0 +1,235 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// AccountUpdateNotificationData. + /// + public partial class AccountUpdateNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Key-value pairs that specify what you can do with the merchant account and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out the funds of a merchant account to a [bank account](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). The value is an object containing the settings for the capability. + /// The unique identifier of the merchant account. + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + [JsonConstructor] + public AccountUpdateNotificationData(Dictionary capabilities, string merchantId, string status, Option legalEntityId = default) + { + Capabilities = capabilities; + MerchantId = merchantId; + Status = status; + _LegalEntityIdOption = legalEntityId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountUpdateNotificationData() + { + } + + partial void OnCreated(); + + /// + /// Key-value pairs that specify what you can do with the merchant account and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out the funds of a merchant account to a [bank account](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). The value is an object containing the settings for the capability. + /// + /// Key-value pairs that specify what you can do with the merchant account and its settings. The key is a capability. For example, the **sendToTransferInstrument** is the capability required before you can pay out the funds of a merchant account to a [bank account](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). The value is an object containing the settings for the capability. + [JsonPropertyName("capabilities")] + public Dictionary Capabilities { get; set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("merchantId")] + public string MerchantId { get; set; } + + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + /// + /// The status of the merchant account. Possible values: * **PreActive**: The merchant account has been created. Users cannot access the merchant account in the Customer Area. The account cannot process payments. * **Active**: Users can access the merchant account in the Customer Area. If the company account is also **Active**, then payment processing and payouts are enabled. * **InactiveWithModifications**: Users can access the merchant account in the Customer Area. The account cannot process new payments but can still modify payments, for example issue refunds. The account can still receive payouts. * **Inactive**: Users can access the merchant account in the Customer Area. Payment processing and payouts are disabled. * **Closed**: The account is closed and this cannot be reversed. Users cannot log in. Payment processing and payouts are disabled. + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LegalEntityIdOption { get; private set; } + + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + /// + /// The unique identifier of the [legal entity](https://docs.adyen.com/api-explorer/legalentity/latest/post/legalEntities#responses-200-id). + [JsonPropertyName("legalEntityId")] + public string? LegalEntityId { get { return this._LegalEntityIdOption; } set { this._LegalEntityIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountUpdateNotificationData {\n"); + sb.Append(" Capabilities: ").Append(Capabilities).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountUpdateNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountUpdateNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> capabilities = default; + Option merchantId = default; + Option status = default; + Option legalEntityId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "capabilities": + capabilities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!capabilities.IsSet) + throw new ArgumentException("Property is required for class AccountUpdateNotificationData.", nameof(capabilities)); + + if (!merchantId.IsSet) + throw new ArgumentException("Property is required for class AccountUpdateNotificationData.", nameof(merchantId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class AccountUpdateNotificationData.", nameof(status)); + + return new AccountUpdateNotificationData(capabilities.Value!, merchantId.Value!, status.Value!, legalEntityId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountUpdateNotificationData accountUpdateNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountUpdateNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountUpdateNotificationData accountUpdateNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("capabilities"); + JsonSerializer.Serialize(writer, accountUpdateNotificationData.Capabilities, jsonSerializerOptions); + if (accountUpdateNotificationData.MerchantId != null) + writer.WriteString("merchantId", accountUpdateNotificationData.MerchantId); + + if (accountUpdateNotificationData.Status != null) + writer.WriteString("status", accountUpdateNotificationData.Status); + + if (accountUpdateNotificationData._LegalEntityIdOption.IsSet) + if (accountUpdateNotificationData.LegalEntityId != null) + writer.WriteString("legalEntityId", accountUpdateNotificationData.LegalEntityId); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/CapabilityProblem.cs b/Adyen/ManagementWebhooks/Models/CapabilityProblem.cs new file mode 100644 index 000000000..38a5ccf30 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/CapabilityProblem.cs @@ -0,0 +1,204 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// CapabilityProblem. + /// + public partial class CapabilityProblem : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// entity + /// List of verification errors. + [JsonConstructor] + public CapabilityProblem(Option entity = default, Option?> verificationErrors = default) + { + _EntityOption = entity; + _VerificationErrorsOption = verificationErrors; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblem() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("entity")] + public CapabilityProblemEntity? Entity { get { return this._EntityOption; } set { this._EntityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _VerificationErrorsOption { get; private set; } + + /// + /// List of verification errors. + /// + /// List of verification errors. + [JsonPropertyName("verificationErrors")] + public List? VerificationErrors { get { return this._VerificationErrorsOption; } set { this._VerificationErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblem {\n"); + sb.Append(" Entity: ").Append(Entity).Append("\n"); + sb.Append(" VerificationErrors: ").Append(VerificationErrors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblem Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option entity = default; + Option?> verificationErrors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "entity": + entity = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "verificationErrors": + verificationErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CapabilityProblem(entity, verificationErrors); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblem, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblem capabilityProblem, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblem._EntityOption.IsSet) + { + writer.WritePropertyName("entity"); + JsonSerializer.Serialize(writer, capabilityProblem.Entity, jsonSerializerOptions); + } + if (capabilityProblem._VerificationErrorsOption.IsSet) + { + writer.WritePropertyName("verificationErrors"); + JsonSerializer.Serialize(writer, capabilityProblem.VerificationErrors, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/CapabilityProblemEntity.cs b/Adyen/ManagementWebhooks/Models/CapabilityProblemEntity.cs new file mode 100644 index 000000000..6b251de12 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/CapabilityProblemEntity.cs @@ -0,0 +1,368 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// CapabilityProblemEntity. + /// + public partial class CapabilityProblemEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// owner + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonConstructor] + public CapabilityProblemEntity(Option?> documents = default, Option id = default, Option owner = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _OwnerOption = owner; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntity() + { + } + + partial void OnCreated(); + + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("owner")] + public CapabilityProblemEntityRecursive? Owner { get { return this._OwnerOption; } set { this._OwnerOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntity {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Owner: ").Append(Owner).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option owner = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "owner": + owner = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntity.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntity(documents, id, owner, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntity capabilityProblemEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntity._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntity._IdOption.IsSet) + if (capabilityProblemEntity.Id != null) + writer.WriteString("id", capabilityProblemEntity.Id); + + if (capabilityProblemEntity._OwnerOption.IsSet) + { + writer.WritePropertyName("owner"); + JsonSerializer.Serialize(writer, capabilityProblemEntity.Owner, jsonSerializerOptions); + } + if (capabilityProblemEntity._TypeOption.IsSet && capabilityProblemEntity.Type != null) + { + string? typeRawValue = CapabilityProblemEntity.TypeEnum.ToJsonValue(capabilityProblemEntity._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/CapabilityProblemEntityRecursive.cs b/Adyen/ManagementWebhooks/Models/CapabilityProblemEntityRecursive.cs new file mode 100644 index 000000000..0bd474ea9 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/CapabilityProblemEntityRecursive.cs @@ -0,0 +1,343 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// CapabilityProblemEntityRecursive. + /// + public partial class CapabilityProblemEntityRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// The ID of the entity. + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonConstructor] + public CapabilityProblemEntityRecursive(Option?> documents = default, Option id = default, Option type = default) + { + _DocumentsOption = documents; + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapabilityProblemEntityRecursive() + { + } + + partial void OnCreated(); + + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankAccount - BankAccount + /// + public static readonly TypeEnum BankAccount = new("BankAccount"); + + /// + /// TypeEnum.Document - Document + /// + public static readonly TypeEnum Document = new("Document"); + + /// + /// TypeEnum.LegalEntity - LegalEntity + /// + public static readonly TypeEnum LegalEntity = new("LegalEntity"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "BankAccount" => TypeEnum.BankAccount, + "Document" => TypeEnum.Document, + "LegalEntity" => TypeEnum.LegalEntity, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankAccount) + return "BankAccount"; + + if (value == TypeEnum.Document) + return "Document"; + + if (value == TypeEnum.LegalEntity) + return "LegalEntity"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + /// + /// The type of entity. Possible values: **LegalEntity**, **BankAccount**, or **Document**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DocumentsOption { get; private set; } + + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + /// + /// List of document IDs to which the verification errors related to the capabilities correspond to. + [JsonPropertyName("documents")] + public List? Documents { get { return this._DocumentsOption; } set { this._DocumentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the entity. + /// + /// The ID of the entity. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapabilityProblemEntityRecursive {\n"); + sb.Append(" Documents: ").Append(Documents).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapabilityProblemEntityRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapabilityProblemEntityRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> documents = default; + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "documents": + documents = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CapabilityProblemEntityRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new CapabilityProblemEntityRecursive(documents, id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capabilityProblemEntityRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapabilityProblemEntityRecursive capabilityProblemEntityRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (capabilityProblemEntityRecursive._DocumentsOption.IsSet) + { + writer.WritePropertyName("documents"); + JsonSerializer.Serialize(writer, capabilityProblemEntityRecursive.Documents, jsonSerializerOptions); + } + if (capabilityProblemEntityRecursive._IdOption.IsSet) + if (capabilityProblemEntityRecursive.Id != null) + writer.WriteString("id", capabilityProblemEntityRecursive.Id); + + if (capabilityProblemEntityRecursive._TypeOption.IsSet && capabilityProblemEntityRecursive.Type != null) + { + string? typeRawValue = CapabilityProblemEntityRecursive.TypeEnum.ToJsonValue(capabilityProblemEntityRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/MerchantCreatedNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/MerchantCreatedNotificationRequest.cs new file mode 100644 index 000000000..32696eb61 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/MerchantCreatedNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// MerchantCreatedNotificationRequest. + /// + public partial class MerchantCreatedNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public MerchantCreatedNotificationRequest(DateTimeOffset createdAt, AccountCreateNotificationData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantCreatedNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.MerchantCreated - merchant.created + /// + public static readonly TypeEnum MerchantCreated = new("merchant.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "merchant.created" => TypeEnum.MerchantCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.MerchantCreated) + return "merchant.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public AccountCreateNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantCreatedNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantCreatedNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantCreatedNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MerchantCreatedNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class MerchantCreatedNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class MerchantCreatedNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class MerchantCreatedNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MerchantCreatedNotificationRequest.", nameof(type)); + + return new MerchantCreatedNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantCreatedNotificationRequest merchantCreatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantCreatedNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantCreatedNotificationRequest merchantCreatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", merchantCreatedNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, merchantCreatedNotificationRequest.Data, jsonSerializerOptions); + if (merchantCreatedNotificationRequest.Environment != null) + writer.WriteString("environment", merchantCreatedNotificationRequest.Environment); + + if (merchantCreatedNotificationRequest.Type != null) + { + string? typeRawValue = MerchantCreatedNotificationRequest.TypeEnum.ToJsonValue(merchantCreatedNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/MerchantUpdatedNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/MerchantUpdatedNotificationRequest.cs new file mode 100644 index 000000000..4e90b0184 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/MerchantUpdatedNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// MerchantUpdatedNotificationRequest. + /// + public partial class MerchantUpdatedNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public MerchantUpdatedNotificationRequest(DateTimeOffset createdAt, AccountUpdateNotificationData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantUpdatedNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.MerchantUpdated - merchant.updated + /// + public static readonly TypeEnum MerchantUpdated = new("merchant.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "merchant.updated" => TypeEnum.MerchantUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.MerchantUpdated) + return "merchant.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public AccountUpdateNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantUpdatedNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantUpdatedNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantUpdatedNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MerchantUpdatedNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class MerchantUpdatedNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class MerchantUpdatedNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class MerchantUpdatedNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MerchantUpdatedNotificationRequest.", nameof(type)); + + return new MerchantUpdatedNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantUpdatedNotificationRequest merchantUpdatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantUpdatedNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantUpdatedNotificationRequest merchantUpdatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", merchantUpdatedNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, merchantUpdatedNotificationRequest.Data, jsonSerializerOptions); + if (merchantUpdatedNotificationRequest.Environment != null) + writer.WriteString("environment", merchantUpdatedNotificationRequest.Environment); + + if (merchantUpdatedNotificationRequest.Type != null) + { + string? typeRawValue = MerchantUpdatedNotificationRequest.TypeEnum.ToJsonValue(merchantUpdatedNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/MidServiceNotificationData.cs b/Adyen/ManagementWebhooks/Models/MidServiceNotificationData.cs new file mode 100644 index 000000000..860999f0e --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/MidServiceNotificationData.cs @@ -0,0 +1,612 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// MidServiceNotificationData. + /// + public partial class MidServiceNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource. + /// The unique identifier of the merchant account. + /// The status of the request to add a payment method. Possible values: * **success**: the payment method was added. * **failure**: the request failed. * **capabilityPending**: the **receivePayments** capability is not allowed. + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// Your reference for the payment method. + /// The unique identifier of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/post/merchants/{id}/paymentMethodSettings__reqParam_storeId), if any. + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + [JsonConstructor] + public MidServiceNotificationData(string id, string merchantId, StatusEnum status, string type, Option allowed = default, Option enabled = default, Option reference = default, Option storeId = default, Option verificationStatus = default) + { + Id = id; + MerchantId = merchantId; + Status = status; + Type = type; + _AllowedOption = allowed; + _EnabledOption = enabled; + _ReferenceOption = reference; + _StoreIdOption = storeId; + _VerificationStatusOption = verificationStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MidServiceNotificationData() + { + } + + partial void OnCreated(); + + /// + /// The status of the request to add a payment method. Possible values: * **success**: the payment method was added. * **failure**: the request failed. * **capabilityPending**: the **receivePayments** capability is not allowed. + /// + /// The status of the request to add a payment method. Possible values: * **success**: the payment method was added. * **failure**: the request failed. * **capabilityPending**: the **receivePayments** capability is not allowed. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Success - success + /// + public static readonly StatusEnum Success = new("success"); + + /// + /// StatusEnum.Failure - failure + /// + public static readonly StatusEnum Failure = new("failure"); + + /// + /// StatusEnum.CapabilityPending - capabilityPending + /// + public static readonly StatusEnum CapabilityPending = new("capabilityPending"); + + /// + /// StatusEnum.DataRequired - dataRequired + /// + public static readonly StatusEnum DataRequired = new("dataRequired"); + + /// + /// StatusEnum.UpdatesExpected - updatesExpected + /// + public static readonly StatusEnum UpdatesExpected = new("updatesExpected"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "success" => StatusEnum.Success, + "failure" => StatusEnum.Failure, + "capabilityPending" => StatusEnum.CapabilityPending, + "dataRequired" => StatusEnum.DataRequired, + "updatesExpected" => StatusEnum.UpdatesExpected, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Success) + return "success"; + + if (value == StatusEnum.Failure) + return "failure"; + + if (value == StatusEnum.CapabilityPending) + return "capabilityPending"; + + if (value == StatusEnum.DataRequired) + return "dataRequired"; + + if (value == StatusEnum.UpdatesExpected) + return "updatesExpected"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the request to add a payment method. Possible values: * **success**: the payment method was added. * **failure**: the request failed. * **capabilityPending**: the **receivePayments** capability is not allowed. + /// + /// The status of the request to add a payment method. Possible values: * **success**: the payment method was added. * **failure**: the request failed. * **capabilityPending**: the **receivePayments** capability is not allowed. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + [JsonConverter(typeof(VerificationStatusEnumJsonConverter))] + public class VerificationStatusEnum : IEnum + { + /// + /// Returns the value of the VerificationStatusEnum. + /// + public string? Value { get; set; } + + /// + /// VerificationStatusEnum.Valid - valid + /// + public static readonly VerificationStatusEnum Valid = new("valid"); + + /// + /// VerificationStatusEnum.Pending - pending + /// + public static readonly VerificationStatusEnum Pending = new("pending"); + + /// + /// VerificationStatusEnum.Invalid - invalid + /// + public static readonly VerificationStatusEnum Invalid = new("invalid"); + + /// + /// VerificationStatusEnum.Rejected - rejected + /// + public static readonly VerificationStatusEnum Rejected = new("rejected"); + + private VerificationStatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator VerificationStatusEnum?(string? value) => value == null ? null : new VerificationStatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(VerificationStatusEnum? option) => option?.Value; + + public static bool operator ==(VerificationStatusEnum? left, VerificationStatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(VerificationStatusEnum? left, VerificationStatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is VerificationStatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static VerificationStatusEnum? FromStringOrDefault(string value) + { + return value switch { + "valid" => VerificationStatusEnum.Valid, + "pending" => VerificationStatusEnum.Pending, + "invalid" => VerificationStatusEnum.Invalid, + "rejected" => VerificationStatusEnum.Rejected, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(VerificationStatusEnum? value) + { + if (value == null) + return null; + + if (value == VerificationStatusEnum.Valid) + return "valid"; + + if (value == VerificationStatusEnum.Pending) + return "pending"; + + if (value == VerificationStatusEnum.Invalid) + return "invalid"; + + if (value == VerificationStatusEnum.Rejected) + return "rejected"; + + return null; + } + + /// + /// JsonConverter for writing VerificationStatusEnum. + /// + public class VerificationStatusEnumJsonConverter : JsonConverter + { + public override VerificationStatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : VerificationStatusEnum.FromStringOrDefault(value) ?? new VerificationStatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, VerificationStatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(VerificationStatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VerificationStatusOption { get; private set; } + + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + /// + /// Payment method status. Possible values: * **valid** * **pending** * **invalid** * **rejected** + [JsonPropertyName("verificationStatus")] + public VerificationStatusEnum? VerificationStatus { get { return this._VerificationStatusOption; } set { this._VerificationStatusOption = new(value); } } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("merchantId")] + public string MerchantId { get; set; } + + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + /// + /// Payment method [variant](https://docs.adyen.com/development-resources/paymentmethodvariant#management-api). + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowedOption { get; private set; } + + /// + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + /// + /// Indicates whether receiving payments is allowed. This value is set to **true** by Adyen after screening your merchant account. + [JsonPropertyName("allowed")] + public bool? Allowed { get { return this._AllowedOption; } set { this._AllowedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnabledOption { get; private set; } + + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + /// + /// Indicates whether the payment method is enabled (**true**) or disabled (**false**). + [JsonPropertyName("enabled")] + public bool? Enabled { get { return this._EnabledOption; } set { this._EnabledOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment method. + /// + /// Your reference for the payment method. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/post/merchants/{id}/paymentMethodSettings__reqParam_storeId), if any. + /// + /// The unique identifier of the [store](https://docs.adyen.com/api-explorer/#/ManagementService/latest/post/merchants/{id}/paymentMethodSettings__reqParam_storeId), if any. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MidServiceNotificationData {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Allowed: ").Append(Allowed).Append("\n"); + sb.Append(" Enabled: ").Append(Enabled).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append(" VerificationStatus: ").Append(VerificationStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MidServiceNotificationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MidServiceNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option merchantId = default; + Option status = default; + Option type = default; + Option allowed = default; + Option enabled = default; + Option reference = default; + Option storeId = default; + Option verificationStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(MidServiceNotificationData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "allowed": + allowed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "enabled": + enabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + case "verificationStatus": + string? verificationStatusRawValue = utf8JsonReader.GetString(); + verificationStatus = new Option(MidServiceNotificationData.VerificationStatusEnum.FromStringOrDefault(verificationStatusRawValue)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class MidServiceNotificationData.", nameof(id)); + + if (!merchantId.IsSet) + throw new ArgumentException("Property is required for class MidServiceNotificationData.", nameof(merchantId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class MidServiceNotificationData.", nameof(status)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MidServiceNotificationData.", nameof(type)); + + return new MidServiceNotificationData(id.Value!, merchantId.Value!, status.Value!.Value!, type.Value!, allowed, enabled, reference, storeId, verificationStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MidServiceNotificationData midServiceNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, midServiceNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MidServiceNotificationData midServiceNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (midServiceNotificationData.Id != null) + writer.WriteString("id", midServiceNotificationData.Id); + + if (midServiceNotificationData.MerchantId != null) + writer.WriteString("merchantId", midServiceNotificationData.MerchantId); + + if (midServiceNotificationData.Status != null) + { + string? statusRawValue = MidServiceNotificationData.StatusEnum.ToJsonValue(midServiceNotificationData.Status); + writer.WriteString("status", statusRawValue); + } + + if (midServiceNotificationData.Type != null) + writer.WriteString("type", midServiceNotificationData.Type); + + if (midServiceNotificationData._AllowedOption.IsSet) + writer.WriteBoolean("allowed", midServiceNotificationData._AllowedOption.Value!.Value); + + if (midServiceNotificationData._EnabledOption.IsSet) + writer.WriteBoolean("enabled", midServiceNotificationData._EnabledOption.Value!.Value); + + if (midServiceNotificationData._ReferenceOption.IsSet) + if (midServiceNotificationData.Reference != null) + writer.WriteString("reference", midServiceNotificationData.Reference); + + if (midServiceNotificationData._StoreIdOption.IsSet) + if (midServiceNotificationData.StoreId != null) + writer.WriteString("storeId", midServiceNotificationData.StoreId); + + if (midServiceNotificationData._VerificationStatusOption.IsSet && midServiceNotificationData.VerificationStatus != null) + { + string? verificationStatusRawValue = MidServiceNotificationData.VerificationStatusEnum.ToJsonValue(midServiceNotificationData._VerificationStatusOption.Value!.Value); + writer.WriteString("verificationStatus", verificationStatusRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/PaymentMethodCreatedNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/PaymentMethodCreatedNotificationRequest.cs new file mode 100644 index 000000000..47dd4a1ad --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/PaymentMethodCreatedNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// PaymentMethodCreatedNotificationRequest. + /// + public partial class PaymentMethodCreatedNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public PaymentMethodCreatedNotificationRequest(DateTimeOffset createdAt, MidServiceNotificationData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodCreatedNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentMethodCreated - paymentMethod.created + /// + public static readonly TypeEnum PaymentMethodCreated = new("paymentMethod.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentMethod.created" => TypeEnum.PaymentMethodCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentMethodCreated) + return "paymentMethod.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public MidServiceNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodCreatedNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodCreatedNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodCreatedNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentMethodCreatedNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodCreatedNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodCreatedNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodCreatedNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodCreatedNotificationRequest.", nameof(type)); + + return new PaymentMethodCreatedNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodCreatedNotificationRequest paymentMethodCreatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodCreatedNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodCreatedNotificationRequest paymentMethodCreatedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", paymentMethodCreatedNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paymentMethodCreatedNotificationRequest.Data, jsonSerializerOptions); + if (paymentMethodCreatedNotificationRequest.Environment != null) + writer.WriteString("environment", paymentMethodCreatedNotificationRequest.Environment); + + if (paymentMethodCreatedNotificationRequest.Type != null) + { + string? typeRawValue = PaymentMethodCreatedNotificationRequest.TypeEnum.ToJsonValue(paymentMethodCreatedNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/PaymentMethodNotificationResponse.cs b/Adyen/ManagementWebhooks/Models/PaymentMethodNotificationResponse.cs new file mode 100644 index 000000000..378cb7078 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/PaymentMethodNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// PaymentMethodNotificationResponse. + /// + public partial class PaymentMethodNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public PaymentMethodNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentMethodNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodNotificationResponse paymentMethodNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodNotificationResponse paymentMethodNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentMethodNotificationResponse._NotificationResponseOption.IsSet) + if (paymentMethodNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", paymentMethodNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/PaymentMethodRequestRemovedNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/PaymentMethodRequestRemovedNotificationRequest.cs new file mode 100644 index 000000000..f24ce421e --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/PaymentMethodRequestRemovedNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// PaymentMethodRequestRemovedNotificationRequest. + /// + public partial class PaymentMethodRequestRemovedNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public PaymentMethodRequestRemovedNotificationRequest(DateTimeOffset createdAt, MidServiceNotificationData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodRequestRemovedNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentMethodRequestRemoved - paymentMethodRequest.removed + /// + public static readonly TypeEnum PaymentMethodRequestRemoved = new("paymentMethodRequest.removed"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentMethodRequest.removed" => TypeEnum.PaymentMethodRequestRemoved, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentMethodRequestRemoved) + return "paymentMethodRequest.removed"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public MidServiceNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodRequestRemovedNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodRequestRemovedNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodRequestRemovedNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentMethodRequestRemovedNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodRequestRemovedNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodRequestRemovedNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodRequestRemovedNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodRequestRemovedNotificationRequest.", nameof(type)); + + return new PaymentMethodRequestRemovedNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodRequestRemovedNotificationRequest paymentMethodRequestRemovedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodRequestRemovedNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodRequestRemovedNotificationRequest paymentMethodRequestRemovedNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", paymentMethodRequestRemovedNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paymentMethodRequestRemovedNotificationRequest.Data, jsonSerializerOptions); + if (paymentMethodRequestRemovedNotificationRequest.Environment != null) + writer.WriteString("environment", paymentMethodRequestRemovedNotificationRequest.Environment); + + if (paymentMethodRequestRemovedNotificationRequest.Type != null) + { + string? typeRawValue = PaymentMethodRequestRemovedNotificationRequest.TypeEnum.ToJsonValue(paymentMethodRequestRemovedNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/PaymentMethodScheduledForRemovalNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/PaymentMethodScheduledForRemovalNotificationRequest.cs new file mode 100644 index 000000000..0a20cd12c --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/PaymentMethodScheduledForRemovalNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// PaymentMethodScheduledForRemovalNotificationRequest. + /// + public partial class PaymentMethodScheduledForRemovalNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public PaymentMethodScheduledForRemovalNotificationRequest(DateTimeOffset createdAt, MidServiceNotificationData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentMethodScheduledForRemovalNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PaymentMethodRequestScheduledForRemoval - paymentMethodRequest.scheduledForRemoval + /// + public static readonly TypeEnum PaymentMethodRequestScheduledForRemoval = new("paymentMethodRequest.scheduledForRemoval"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "paymentMethodRequest.scheduledForRemoval" => TypeEnum.PaymentMethodRequestScheduledForRemoval, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PaymentMethodRequestScheduledForRemoval) + return "paymentMethodRequest.scheduledForRemoval"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public MidServiceNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentMethodScheduledForRemovalNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentMethodScheduledForRemovalNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentMethodScheduledForRemovalNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PaymentMethodScheduledForRemovalNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodScheduledForRemovalNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodScheduledForRemovalNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodScheduledForRemovalNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PaymentMethodScheduledForRemovalNotificationRequest.", nameof(type)); + + return new PaymentMethodScheduledForRemovalNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentMethodScheduledForRemovalNotificationRequest paymentMethodScheduledForRemovalNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentMethodScheduledForRemovalNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentMethodScheduledForRemovalNotificationRequest paymentMethodScheduledForRemovalNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", paymentMethodScheduledForRemovalNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, paymentMethodScheduledForRemovalNotificationRequest.Data, jsonSerializerOptions); + if (paymentMethodScheduledForRemovalNotificationRequest.Environment != null) + writer.WriteString("environment", paymentMethodScheduledForRemovalNotificationRequest.Environment); + + if (paymentMethodScheduledForRemovalNotificationRequest.Type != null) + { + string? typeRawValue = PaymentMethodScheduledForRemovalNotificationRequest.TypeEnum.ToJsonValue(paymentMethodScheduledForRemovalNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/RemediatingAction.cs b/Adyen/ManagementWebhooks/Models/RemediatingAction.cs new file mode 100644 index 000000000..65a3bf774 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/RemediatingAction.cs @@ -0,0 +1,202 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// RemediatingAction. + /// + public partial class RemediatingAction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The remediating action code. + /// A description of how you can resolve the verification error. + [JsonConstructor] + public RemediatingAction(Option code = default, Option message = default) + { + _CodeOption = code; + _MessageOption = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RemediatingAction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The remediating action code. + /// + /// The remediating action code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A description of how you can resolve the verification error. + /// + /// A description of how you can resolve the verification error. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RemediatingAction {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RemediatingActionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RemediatingAction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RemediatingAction(code, message); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, remediatingAction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RemediatingAction remediatingAction, JsonSerializerOptions jsonSerializerOptions) + { + + if (remediatingAction._CodeOption.IsSet) + if (remediatingAction.Code != null) + writer.WriteString("code", remediatingAction.Code); + + if (remediatingAction._MessageOption.IsSet) + if (remediatingAction.Message != null) + writer.WriteString("message", remediatingAction.Message); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationRequest.cs new file mode 100644 index 000000000..0180f5631 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationRequest.cs @@ -0,0 +1,281 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalAssignmentNotificationRequest. + /// + public partial class TerminalAssignmentNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the merchant/company account to which the terminal is assigned. + /// The date and time when an event has been completed. + /// The PSP reference of the request from which the notification originates. + /// The unique identifier of the terminal. + /// The store that the terminal is assigned to, identified by the store reference (also known as store code). + /// The unique identifier of the store to which the terminal is assigned. + [JsonConstructor] + public TerminalAssignmentNotificationRequest(string assignedToAccount, string eventDate, string pspReference, string uniqueTerminalId, Option assignedToStore = default, Option assignedToStoreId = default) + { + AssignedToAccount = assignedToAccount; + EventDate = eventDate; + PspReference = pspReference; + UniqueTerminalId = uniqueTerminalId; + _AssignedToStoreOption = assignedToStore; + _AssignedToStoreIdOption = assignedToStoreId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalAssignmentNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the merchant/company account to which the terminal is assigned. + /// + /// The unique identifier of the merchant/company account to which the terminal is assigned. + [JsonPropertyName("assignedToAccount")] + public string AssignedToAccount { get; set; } + + /// + /// The date and time when an event has been completed. + /// + /// The date and time when an event has been completed. + [JsonPropertyName("eventDate")] + public string EventDate { get; set; } + + /// + /// The PSP reference of the request from which the notification originates. + /// + /// The PSP reference of the request from which the notification originates. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The unique identifier of the terminal. + /// + /// The unique identifier of the terminal. + [JsonPropertyName("uniqueTerminalId")] + public string UniqueTerminalId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssignedToStoreOption { get; private set; } + + /// + /// The store that the terminal is assigned to, identified by the store reference (also known as store code). + /// + /// The store that the terminal is assigned to, identified by the store reference (also known as store code). + [JsonPropertyName("assignedToStore")] + public string? AssignedToStore { get { return this._AssignedToStoreOption; } set { this._AssignedToStoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AssignedToStoreIdOption { get; private set; } + + /// + /// The unique identifier of the store to which the terminal is assigned. + /// + /// The unique identifier of the store to which the terminal is assigned. + [JsonPropertyName("assignedToStoreId")] + public string? AssignedToStoreId { get { return this._AssignedToStoreIdOption; } set { this._AssignedToStoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalAssignmentNotificationRequest {\n"); + sb.Append(" AssignedToAccount: ").Append(AssignedToAccount).Append("\n"); + sb.Append(" EventDate: ").Append(EventDate).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append(" AssignedToStore: ").Append(AssignedToStore).Append("\n"); + sb.Append(" AssignedToStoreId: ").Append(AssignedToStoreId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalAssignmentNotificationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalAssignmentNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option assignedToAccount = default; + Option eventDate = default; + Option pspReference = default; + Option uniqueTerminalId = default; + Option assignedToStore = default; + Option assignedToStoreId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "assignedToAccount": + assignedToAccount = new Option(utf8JsonReader.GetString()!); + break; + case "eventDate": + eventDate = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + case "assignedToStore": + assignedToStore = new Option(utf8JsonReader.GetString()!); + break; + case "assignedToStoreId": + assignedToStoreId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!assignedToAccount.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignmentNotificationRequest.", nameof(assignedToAccount)); + + if (!eventDate.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignmentNotificationRequest.", nameof(eventDate)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignmentNotificationRequest.", nameof(pspReference)); + + if (!uniqueTerminalId.IsSet) + throw new ArgumentException("Property is required for class TerminalAssignmentNotificationRequest.", nameof(uniqueTerminalId)); + + return new TerminalAssignmentNotificationRequest(assignedToAccount.Value!, eventDate.Value!, pspReference.Value!, uniqueTerminalId.Value!, assignedToStore, assignedToStoreId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalAssignmentNotificationRequest terminalAssignmentNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalAssignmentNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalAssignmentNotificationRequest terminalAssignmentNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalAssignmentNotificationRequest.AssignedToAccount != null) + writer.WriteString("assignedToAccount", terminalAssignmentNotificationRequest.AssignedToAccount); + + if (terminalAssignmentNotificationRequest.EventDate != null) + writer.WriteString("eventDate", terminalAssignmentNotificationRequest.EventDate); + + if (terminalAssignmentNotificationRequest.PspReference != null) + writer.WriteString("pspReference", terminalAssignmentNotificationRequest.PspReference); + + if (terminalAssignmentNotificationRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", terminalAssignmentNotificationRequest.UniqueTerminalId); + + if (terminalAssignmentNotificationRequest._AssignedToStoreOption.IsSet) + if (terminalAssignmentNotificationRequest.AssignedToStore != null) + writer.WriteString("assignedToStore", terminalAssignmentNotificationRequest.AssignedToStore); + + if (terminalAssignmentNotificationRequest._AssignedToStoreIdOption.IsSet) + if (terminalAssignmentNotificationRequest.AssignedToStoreId != null) + writer.WriteString("assignedToStoreId", terminalAssignmentNotificationRequest.AssignedToStoreId); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationResponse.cs b/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationResponse.cs new file mode 100644 index 000000000..690700fc1 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalAssignmentNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalAssignmentNotificationResponse. + /// + public partial class TerminalAssignmentNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public TerminalAssignmentNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalAssignmentNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalAssignmentNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalAssignmentNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalAssignmentNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalAssignmentNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalAssignmentNotificationResponse terminalAssignmentNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalAssignmentNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalAssignmentNotificationResponse terminalAssignmentNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalAssignmentNotificationResponse._NotificationResponseOption.IsSet) + if (terminalAssignmentNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", terminalAssignmentNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalBoardingData.cs b/Adyen/ManagementWebhooks/Models/TerminalBoardingData.cs new file mode 100644 index 000000000..821c78430 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalBoardingData.cs @@ -0,0 +1,241 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalBoardingData. + /// + public partial class TerminalBoardingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the company account. + /// The unique identifier of the terminal. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + [JsonConstructor] + public TerminalBoardingData(string companyId, string uniqueTerminalId, Option merchantId = default, Option storeId = default) + { + CompanyId = companyId; + UniqueTerminalId = uniqueTerminalId; + _MerchantIdOption = merchantId; + _StoreIdOption = storeId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalBoardingData() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string CompanyId { get; set; } + + /// + /// The unique identifier of the terminal. + /// + /// The unique identifier of the terminal. + [JsonPropertyName("uniqueTerminalId")] + public string UniqueTerminalId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the store. + /// + /// The unique identifier of the store. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalBoardingData {\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalBoardingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalBoardingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option companyId = default; + Option uniqueTerminalId = default; + Option merchantId = default; + Option storeId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!companyId.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingData.", nameof(companyId)); + + if (!uniqueTerminalId.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingData.", nameof(uniqueTerminalId)); + + return new TerminalBoardingData(companyId.Value!, uniqueTerminalId.Value!, merchantId, storeId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalBoardingData terminalBoardingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalBoardingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalBoardingData terminalBoardingData, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalBoardingData.CompanyId != null) + writer.WriteString("companyId", terminalBoardingData.CompanyId); + + if (terminalBoardingData.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", terminalBoardingData.UniqueTerminalId); + + if (terminalBoardingData._MerchantIdOption.IsSet) + if (terminalBoardingData.MerchantId != null) + writer.WriteString("merchantId", terminalBoardingData.MerchantId); + + if (terminalBoardingData._StoreIdOption.IsSet) + if (terminalBoardingData.StoreId != null) + writer.WriteString("storeId", terminalBoardingData.StoreId); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationRequest.cs new file mode 100644 index 000000000..d04caa21e --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalBoardingNotificationRequest. + /// + public partial class TerminalBoardingNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public TerminalBoardingNotificationRequest(DateTimeOffset createdAt, TerminalBoardingData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalBoardingNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.TerminalBoardingTriggered - terminalBoarding.triggered + /// + public static readonly TypeEnum TerminalBoardingTriggered = new("terminalBoarding.triggered"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "terminalBoarding.triggered" => TypeEnum.TerminalBoardingTriggered, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.TerminalBoardingTriggered) + return "terminalBoarding.triggered"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public TerminalBoardingData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalBoardingNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalBoardingNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalBoardingNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TerminalBoardingNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TerminalBoardingNotificationRequest.", nameof(type)); + + return new TerminalBoardingNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalBoardingNotificationRequest terminalBoardingNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalBoardingNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalBoardingNotificationRequest terminalBoardingNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", terminalBoardingNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, terminalBoardingNotificationRequest.Data, jsonSerializerOptions); + if (terminalBoardingNotificationRequest.Environment != null) + writer.WriteString("environment", terminalBoardingNotificationRequest.Environment); + + if (terminalBoardingNotificationRequest.Type != null) + { + string? typeRawValue = TerminalBoardingNotificationRequest.TypeEnum.ToJsonValue(terminalBoardingNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationResponse.cs b/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationResponse.cs new file mode 100644 index 000000000..55a2b69de --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalBoardingNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalBoardingNotificationResponse. + /// + public partial class TerminalBoardingNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public TerminalBoardingNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalBoardingNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalBoardingNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalBoardingNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalBoardingNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalBoardingNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalBoardingNotificationResponse terminalBoardingNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalBoardingNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalBoardingNotificationResponse terminalBoardingNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalBoardingNotificationResponse._NotificationResponseOption.IsSet) + if (terminalBoardingNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", terminalBoardingNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalSettingsData.cs b/Adyen/ManagementWebhooks/Models/TerminalSettingsData.cs new file mode 100644 index 000000000..b8d04ea5f --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalSettingsData.cs @@ -0,0 +1,398 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalSettingsData. + /// + public partial class TerminalSettingsData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the terminal settings were updated using the Customer Area or the Management API. + /// The user that updated the terminal settings. Can be Adyen or your API credential username. + /// The unique identifier of the company account. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// The unique identifier of the terminal. + [JsonConstructor] + public TerminalSettingsData(UpdateSourceEnum updateSource, string user, Option companyId = default, Option merchantId = default, Option storeId = default, Option terminalId = default) + { + UpdateSource = updateSource; + User = user; + _CompanyIdOption = companyId; + _MerchantIdOption = merchantId; + _StoreIdOption = storeId; + _TerminalIdOption = terminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalSettingsData() + { + } + + partial void OnCreated(); + + /// + /// Indicates whether the terminal settings were updated using the Customer Area or the Management API. + /// + /// Indicates whether the terminal settings were updated using the Customer Area or the Management API. + [JsonConverter(typeof(UpdateSourceEnumJsonConverter))] + public class UpdateSourceEnum : IEnum + { + /// + /// Returns the value of the UpdateSourceEnum. + /// + public string? Value { get; set; } + + /// + /// UpdateSourceEnum.CustomerArea - Customer Area + /// + public static readonly UpdateSourceEnum CustomerArea = new("Customer Area"); + + /// + /// UpdateSourceEnum.ManagementApi - Management Api + /// + public static readonly UpdateSourceEnum ManagementApi = new("Management Api"); + + private UpdateSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator UpdateSourceEnum?(string? value) => value == null ? null : new UpdateSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(UpdateSourceEnum? option) => option?.Value; + + public static bool operator ==(UpdateSourceEnum? left, UpdateSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(UpdateSourceEnum? left, UpdateSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is UpdateSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static UpdateSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "Customer Area" => UpdateSourceEnum.CustomerArea, + "Management Api" => UpdateSourceEnum.ManagementApi, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(UpdateSourceEnum? value) + { + if (value == null) + return null; + + if (value == UpdateSourceEnum.CustomerArea) + return "Customer Area"; + + if (value == UpdateSourceEnum.ManagementApi) + return "Management Api"; + + return null; + } + + /// + /// JsonConverter for writing UpdateSourceEnum. + /// + public class UpdateSourceEnumJsonConverter : JsonConverter + { + public override UpdateSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : UpdateSourceEnum.FromStringOrDefault(value) ?? new UpdateSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, UpdateSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(UpdateSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// Indicates whether the terminal settings were updated using the Customer Area or the Management API. + /// + /// Indicates whether the terminal settings were updated using the Customer Area or the Management API. + [JsonPropertyName("updateSource")] + public UpdateSourceEnum UpdateSource { get; set; } + + /// + /// The user that updated the terminal settings. Can be Adyen or your API credential username. + /// + /// The user that updated the terminal settings. Can be Adyen or your API credential username. + [JsonPropertyName("user")] + public string User { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CompanyIdOption { get; private set; } + + /// + /// The unique identifier of the company account. + /// + /// The unique identifier of the company account. + [JsonPropertyName("companyId")] + public string? CompanyId { get { return this._CompanyIdOption; } set { this._CompanyIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant account. + /// + /// The unique identifier of the merchant account. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreIdOption { get; private set; } + + /// + /// The unique identifier of the store. + /// + /// The unique identifier of the store. + [JsonPropertyName("storeId")] + public string? StoreId { get { return this._StoreIdOption; } set { this._StoreIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The unique identifier of the terminal. + /// + /// The unique identifier of the terminal. + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalSettingsData {\n"); + sb.Append(" UpdateSource: ").Append(UpdateSource).Append("\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" CompanyId: ").Append(CompanyId).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" StoreId: ").Append(StoreId).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalSettingsDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalSettingsData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option updateSource = default; + Option user = default; + Option companyId = default; + Option merchantId = default; + Option storeId = default; + Option terminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "updateSource": + string? updateSourceRawValue = utf8JsonReader.GetString(); + updateSource = new Option(TerminalSettingsData.UpdateSourceEnum.FromStringOrDefault(updateSourceRawValue)); + break; + case "user": + user = new Option(utf8JsonReader.GetString()!); + break; + case "companyId": + companyId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "storeId": + storeId = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!updateSource.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsData.", nameof(updateSource)); + + if (!user.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsData.", nameof(user)); + + return new TerminalSettingsData(updateSource.Value!.Value!, user.Value!, companyId, merchantId, storeId, terminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalSettingsData terminalSettingsData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalSettingsData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalSettingsData terminalSettingsData, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalSettingsData.UpdateSource != null) + { + string? updateSourceRawValue = TerminalSettingsData.UpdateSourceEnum.ToJsonValue(terminalSettingsData.UpdateSource); + writer.WriteString("updateSource", updateSourceRawValue); + } + + if (terminalSettingsData.User != null) + writer.WriteString("user", terminalSettingsData.User); + + if (terminalSettingsData._CompanyIdOption.IsSet) + if (terminalSettingsData.CompanyId != null) + writer.WriteString("companyId", terminalSettingsData.CompanyId); + + if (terminalSettingsData._MerchantIdOption.IsSet) + if (terminalSettingsData.MerchantId != null) + writer.WriteString("merchantId", terminalSettingsData.MerchantId); + + if (terminalSettingsData._StoreIdOption.IsSet) + if (terminalSettingsData.StoreId != null) + writer.WriteString("storeId", terminalSettingsData.StoreId); + + if (terminalSettingsData._TerminalIdOption.IsSet) + if (terminalSettingsData.TerminalId != null) + writer.WriteString("terminalId", terminalSettingsData.TerminalId); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationRequest.cs b/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationRequest.cs new file mode 100644 index 000000000..bad74fb0c --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationRequest.cs @@ -0,0 +1,331 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalSettingsNotificationRequest. + /// + public partial class TerminalSettingsNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Timestamp for when the webhook was created. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of notification. + [JsonConstructor] + public TerminalSettingsNotificationRequest(DateTimeOffset createdAt, TerminalSettingsData data, string environment, TypeEnum type) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalSettingsNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.TerminalSettingsModified - terminalSettings.modified + /// + public static readonly TypeEnum TerminalSettingsModified = new("terminalSettings.modified"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "terminalSettings.modified" => TypeEnum.TerminalSettingsModified, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.TerminalSettingsModified) + return "terminalSettings.modified"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of notification. + /// + /// Type of notification. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Timestamp for when the webhook was created. + /// + /// Timestamp for when the webhook was created. + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public TerminalSettingsData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalSettingsNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalSettingsNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalSettingsNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TerminalSettingsNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TerminalSettingsNotificationRequest.", nameof(type)); + + return new TerminalSettingsNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalSettingsNotificationRequest terminalSettingsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalSettingsNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalSettingsNotificationRequest terminalSettingsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", terminalSettingsNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, terminalSettingsNotificationRequest.Data, jsonSerializerOptions); + if (terminalSettingsNotificationRequest.Environment != null) + writer.WriteString("environment", terminalSettingsNotificationRequest.Environment); + + if (terminalSettingsNotificationRequest.Type != null) + { + string? typeRawValue = TerminalSettingsNotificationRequest.TypeEnum.ToJsonValue(terminalSettingsNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationResponse.cs b/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationResponse.cs new file mode 100644 index 000000000..3a0590e9f --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/TerminalSettingsNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// TerminalSettingsNotificationResponse. + /// + public partial class TerminalSettingsNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public TerminalSettingsNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TerminalSettingsNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TerminalSettingsNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TerminalSettingsNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TerminalSettingsNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TerminalSettingsNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TerminalSettingsNotificationResponse terminalSettingsNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, terminalSettingsNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TerminalSettingsNotificationResponse terminalSettingsNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (terminalSettingsNotificationResponse._NotificationResponseOption.IsSet) + if (terminalSettingsNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", terminalSettingsNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/VerificationError.cs b/Adyen/ManagementWebhooks/Models/VerificationError.cs new file mode 100644 index 000000000..a0c9145b3 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/VerificationError.cs @@ -0,0 +1,403 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// VerificationError. + /// + public partial class VerificationError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The verification error code. + /// The verification error message. + /// The actions that you can take to resolve the verification error. + /// More granular information about the verification error. + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + [JsonConstructor] + public VerificationError(Option code = default, Option message = default, Option?> remediatingActions = default, Option?> subErrors = default, Option type = default) + { + _CodeOption = code; + _MessageOption = message; + _RemediatingActionsOption = remediatingActions; + _SubErrorsOption = subErrors; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationError() + { + } + + partial void OnCreated(); + + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// The verification error message. + /// + /// The verification error message. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// The actions that you can take to resolve the verification error. + /// + /// The actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SubErrorsOption { get; private set; } + + /// + /// More granular information about the verification error. + /// + /// More granular information about the verification error. + [JsonPropertyName("subErrors")] + public List? SubErrors { get { return this._SubErrorsOption; } set { this._SubErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationError {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append(" SubErrors: ").Append(SubErrors).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + Option?> remediatingActions = default; + Option?> subErrors = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "subErrors": + subErrors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationError.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new VerificationError(code, message, remediatingActions, subErrors, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationError verificationError, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationError._CodeOption.IsSet) + if (verificationError.Code != null) + writer.WriteString("code", verificationError.Code); + + if (verificationError._MessageOption.IsSet) + if (verificationError.Message != null) + writer.WriteString("message", verificationError.Message); + + if (verificationError._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationError.RemediatingActions, jsonSerializerOptions); + } + if (verificationError._SubErrorsOption.IsSet) + { + writer.WritePropertyName("subErrors"); + JsonSerializer.Serialize(writer, verificationError.SubErrors, jsonSerializerOptions); + } + if (verificationError._TypeOption.IsSet && verificationError.Type != null) + { + string? typeRawValue = VerificationError.TypeEnum.ToJsonValue(verificationError._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/ManagementWebhooks/Models/VerificationErrorRecursive.cs b/Adyen/ManagementWebhooks/Models/VerificationErrorRecursive.cs new file mode 100644 index 000000000..2360ae8a9 --- /dev/null +++ b/Adyen/ManagementWebhooks/Models/VerificationErrorRecursive.cs @@ -0,0 +1,378 @@ +// +/* + * Management Webhooks + * + * Adyen uses webhooks to inform your system about events that happen with your Adyen company and merchant accounts, stores, payment terminals, and payment methods when using [Management API](https://docs.adyen.com/api-explorer/#/ManagementService/latest/overview). When an event occurs, Adyen makes an HTTP POST request to a URL on your server and includes the details of the event in the request body. See [Webhooks](https://docs.adyen.com/development-resources/webhooks) for more information. + * + * The version of the OpenAPI document: 3 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ManagementWebhooks.Client; + +namespace Adyen.ManagementWebhooks.Models +{ + /// + /// VerificationErrorRecursive. + /// + public partial class VerificationErrorRecursive : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The verification error code. + /// The verification error message. + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + /// The actions that you can take to resolve the verification error. + [JsonConstructor] + public VerificationErrorRecursive(Option code = default, Option message = default, Option type = default, Option?> remediatingActions = default) + { + _CodeOption = code; + _MessageOption = message; + _TypeOption = type; + _RemediatingActionsOption = remediatingActions; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VerificationErrorRecursive() + { + } + + partial void OnCreated(); + + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DataMissing - dataMissing + /// + public static readonly TypeEnum DataMissing = new("dataMissing"); + + /// + /// TypeEnum.DataReview - dataReview + /// + public static readonly TypeEnum DataReview = new("dataReview"); + + /// + /// TypeEnum.InvalidInput - invalidInput + /// + public static readonly TypeEnum InvalidInput = new("invalidInput"); + + /// + /// TypeEnum.PendingStatus - pendingStatus + /// + public static readonly TypeEnum PendingStatus = new("pendingStatus"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dataMissing" => TypeEnum.DataMissing, + "dataReview" => TypeEnum.DataReview, + "invalidInput" => TypeEnum.InvalidInput, + "pendingStatus" => TypeEnum.PendingStatus, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DataMissing) + return "dataMissing"; + + if (value == TypeEnum.DataReview) + return "dataReview"; + + if (value == TypeEnum.InvalidInput) + return "invalidInput"; + + if (value == TypeEnum.PendingStatus) + return "pendingStatus"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + /// + /// The type of verification error. Possible values: **invalidInput**, **dataMissing**, and **pendingStatus**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The verification error code. + /// + /// The verification error code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// The verification error message. + /// + /// The verification error message. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RemediatingActionsOption { get; private set; } + + /// + /// The actions that you can take to resolve the verification error. + /// + /// The actions that you can take to resolve the verification error. + [JsonPropertyName("remediatingActions")] + public List? RemediatingActions { get { return this._RemediatingActionsOption; } set { this._RemediatingActionsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VerificationErrorRecursive {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" RemediatingActions: ").Append(RemediatingActions).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VerificationErrorRecursiveJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VerificationErrorRecursive Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option message = default; + Option type = default; + Option?> remediatingActions = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(VerificationErrorRecursive.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "remediatingActions": + remediatingActions = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new VerificationErrorRecursive(code, message, type, remediatingActions); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, verificationErrorRecursive, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VerificationErrorRecursive verificationErrorRecursive, JsonSerializerOptions jsonSerializerOptions) + { + + if (verificationErrorRecursive._CodeOption.IsSet) + if (verificationErrorRecursive.Code != null) + writer.WriteString("code", verificationErrorRecursive.Code); + + if (verificationErrorRecursive._MessageOption.IsSet) + if (verificationErrorRecursive.Message != null) + writer.WriteString("message", verificationErrorRecursive.Message); + + if (verificationErrorRecursive._TypeOption.IsSet && verificationErrorRecursive.Type != null) + { + string? typeRawValue = VerificationErrorRecursive.TypeEnum.ToJsonValue(verificationErrorRecursive._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (verificationErrorRecursive._RemediatingActionsOption.IsSet) + { + writer.WritePropertyName("remediatingActions"); + JsonSerializer.Serialize(writer, verificationErrorRecursive.RemediatingActions, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Model/AcsWebhooks/AuthenticationNotificationData.cs b/Adyen/Model/AcsWebhooks/AuthenticationNotificationData.cs index 82418b422..dbb25c08a 100644 --- a/Adyen/Model/AcsWebhooks/AuthenticationNotificationData.cs +++ b/Adyen/Model/AcsWebhooks/AuthenticationNotificationData.cs @@ -76,8 +76,8 @@ protected AuthenticationNotificationData() { } /// /// authentication (required). /// The unique identifier of the balance platform.. - /// Unique identifier of the authentication. (required). - /// Unique identifier of the payment instrument that was used for the authentication. (required). + /// The unique identifier of the authentication. (required). + /// The unique identifier of the payment instrument that was used for the authentication. (required). /// purchase (required). /// Outcome of the authentication. Allowed values: * authenticated * rejected * error (required). public AuthenticationNotificationData(AuthenticationInfo authentication = default(AuthenticationInfo), string balancePlatform = default(string), string id = default(string), string paymentInstrumentId = default(string), PurchaseInfo purchase = default(PurchaseInfo), StatusEnum status = default(StatusEnum)) @@ -104,16 +104,16 @@ protected AuthenticationNotificationData() { } public string BalancePlatform { get; set; } /// - /// Unique identifier of the authentication. + /// The unique identifier of the authentication. /// - /// Unique identifier of the authentication. + /// The unique identifier of the authentication. [DataMember(Name = "id", IsRequired = false, EmitDefaultValue = false)] public string Id { get; set; } /// - /// Unique identifier of the payment instrument that was used for the authentication. + /// The unique identifier of the payment instrument that was used for the authentication. /// - /// Unique identifier of the payment instrument that was used for the authentication. + /// The unique identifier of the payment instrument that was used for the authentication. [DataMember(Name = "paymentInstrumentId", IsRequired = false, EmitDefaultValue = false)] public string PaymentInstrumentId { get; set; } diff --git a/Adyen/Model/AcsWebhooks/BalancePlatformNotificationResponse.cs b/Adyen/Model/AcsWebhooks/BalancePlatformNotificationResponse.cs index ecbae9104..1d24000b9 100644 --- a/Adyen/Model/AcsWebhooks/BalancePlatformNotificationResponse.cs +++ b/Adyen/Model/AcsWebhooks/BalancePlatformNotificationResponse.cs @@ -35,16 +35,16 @@ public partial class BalancePlatformNotificationResponse : IEquatable /// Initializes a new instance of the class. /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications).. + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks).. public BalancePlatformNotificationResponse(string notificationResponse = default(string)) { this.NotificationResponse = notificationResponse; } /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications). + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications). + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). [DataMember(Name = "notificationResponse", EmitDefaultValue = false)] public string NotificationResponse { get; set; } diff --git a/Adyen/Model/AcsWebhooks/PurchaseInfo.cs b/Adyen/Model/AcsWebhooks/PurchaseInfo.cs index 511b1a6ab..29200bd8f 100644 --- a/Adyen/Model/AcsWebhooks/PurchaseInfo.cs +++ b/Adyen/Model/AcsWebhooks/PurchaseInfo.cs @@ -40,8 +40,8 @@ protected PurchaseInfo() { } /// /// Initializes a new instance of the class. /// - /// Date of the purchase. (required). - /// Name of the merchant. (required). + /// The date of the purchase. (required). + /// The name of the business that the cardholder purchased from. (required). /// originalAmount (required). public PurchaseInfo(string date = default(string), string merchantName = default(string), Amount originalAmount = default(Amount)) { @@ -51,16 +51,16 @@ protected PurchaseInfo() { } } /// - /// Date of the purchase. + /// The date of the purchase. /// - /// Date of the purchase. + /// The date of the purchase. [DataMember(Name = "date", IsRequired = false, EmitDefaultValue = false)] public string Date { get; set; } /// - /// Name of the merchant. + /// The name of the business that the cardholder purchased from. /// - /// Name of the merchant. + /// The name of the business that the cardholder purchased from. [DataMember(Name = "merchantName", IsRequired = false, EmitDefaultValue = false)] public string MerchantName { get; set; } diff --git a/Adyen/Model/AcsWebhooks/RelayedAuthenticationRequest.cs b/Adyen/Model/AcsWebhooks/RelayedAuthenticationRequest.cs index 0dd6d2895..8c190ddc1 100644 --- a/Adyen/Model/AcsWebhooks/RelayedAuthenticationRequest.cs +++ b/Adyen/Model/AcsWebhooks/RelayedAuthenticationRequest.cs @@ -32,6 +32,28 @@ namespace Adyen.Model.AcsWebhooks [DataContract(Name = "RelayedAuthenticationRequest")] public partial class RelayedAuthenticationRequest : IEquatable, IValidatableObject { + /// + /// Type of notification. + /// + /// Type of notification. + [JsonConverter(typeof(StringEnumConverter))] + public enum TypeEnum + { + /// + /// Enum BalancePlatformAuthenticationRelayed for value: balancePlatform.authentication.relayed + /// + [EnumMember(Value = "balancePlatform.authentication.relayed")] + BalancePlatformAuthenticationRelayed = 1 + + } + + + /// + /// Type of notification. + /// + /// Type of notification. + [DataMember(Name = "type", IsRequired = false, EmitDefaultValue = false)] + public TypeEnum Type { get; set; } /// /// Initializes a new instance of the class. /// @@ -40,16 +62,31 @@ protected RelayedAuthenticationRequest() { } /// /// Initializes a new instance of the class. /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. (required). /// The unique identifier of the challenge. (required). /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_) used for the purchase. (required). /// purchase (required). - public RelayedAuthenticationRequest(string id = default(string), string paymentInstrumentId = default(string), Purchase purchase = default(Purchase)) + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching.. + /// When the event was queued.. + /// Type of notification. (required). + public RelayedAuthenticationRequest(string environment = default(string), string id = default(string), string paymentInstrumentId = default(string), Purchase purchase = default(Purchase), string threeDSRequestorAppURL = default(string), DateTime timestamp = default(DateTime), TypeEnum type = default(TypeEnum)) { + this.Environment = environment; this.Id = id; this.PaymentInstrumentId = paymentInstrumentId; this.Purchase = purchase; + this.Type = type; + this.ThreeDSRequestorAppURL = threeDSRequestorAppURL; + this.Timestamp = timestamp; } + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [DataMember(Name = "environment", IsRequired = false, EmitDefaultValue = false)] + public string Environment { get; set; } + /// /// The unique identifier of the challenge. /// @@ -70,6 +107,20 @@ protected RelayedAuthenticationRequest() { } [DataMember(Name = "purchase", IsRequired = false, EmitDefaultValue = false)] public Purchase Purchase { get; set; } + /// + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching. + /// + /// URL for auto-switching to the threeDS Requestor App. If not present, the threeDS Requestor App doesn't support auto-switching. + [DataMember(Name = "threeDSRequestorAppURL", EmitDefaultValue = false)] + public string ThreeDSRequestorAppURL { get; set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [DataMember(Name = "timestamp", EmitDefaultValue = false)] + public DateTime Timestamp { get; set; } + /// /// Returns the string presentation of the object /// @@ -78,9 +129,13 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class RelayedAuthenticationRequest {\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); sb.Append(" Purchase: ").Append(Purchase).Append("\n"); + sb.Append(" ThreeDSRequestorAppURL: ").Append(ThreeDSRequestorAppURL).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -116,6 +171,11 @@ public bool Equals(RelayedAuthenticationRequest input) return false; } return + ( + this.Environment == input.Environment || + (this.Environment != null && + this.Environment.Equals(input.Environment)) + ) && ( this.Id == input.Id || (this.Id != null && @@ -130,6 +190,20 @@ public bool Equals(RelayedAuthenticationRequest input) this.Purchase == input.Purchase || (this.Purchase != null && this.Purchase.Equals(input.Purchase)) + ) && + ( + this.ThreeDSRequestorAppURL == input.ThreeDSRequestorAppURL || + (this.ThreeDSRequestorAppURL != null && + this.ThreeDSRequestorAppURL.Equals(input.ThreeDSRequestorAppURL)) + ) && + ( + this.Timestamp == input.Timestamp || + (this.Timestamp != null && + this.Timestamp.Equals(input.Timestamp)) + ) && + ( + this.Type == input.Type || + this.Type.Equals(input.Type) ); } @@ -142,6 +216,10 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; + if (this.Environment != null) + { + hashCode = (hashCode * 59) + this.Environment.GetHashCode(); + } if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); @@ -154,6 +232,15 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Purchase.GetHashCode(); } + if (this.ThreeDSRequestorAppURL != null) + { + hashCode = (hashCode * 59) + this.ThreeDSRequestorAppURL.GetHashCode(); + } + if (this.Timestamp != null) + { + hashCode = (hashCode * 59) + this.Timestamp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Type.GetHashCode(); return hashCode; } } diff --git a/Adyen/Model/AcsWebhooks/Resource.cs b/Adyen/Model/AcsWebhooks/Resource.cs index 9dcd4a3d0..b77e9d028 100644 --- a/Adyen/Model/AcsWebhooks/Resource.cs +++ b/Adyen/Model/AcsWebhooks/Resource.cs @@ -36,7 +36,7 @@ public partial class Resource : IEquatable, IValidatableObject /// Initializes a new instance of the class. /// /// The unique identifier of the balance platform.. - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**.. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**.. /// The ID of the resource.. public Resource(string balancePlatform = default(string), DateTime creationDate = default(DateTime), string id = default(string)) { @@ -53,9 +53,9 @@ public partial class Resource : IEquatable, IValidatableObject public string BalancePlatform { get; set; } /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. [DataMember(Name = "creationDate", EmitDefaultValue = false)] public DateTime CreationDate { get; set; } diff --git a/Adyen/Model/ApiError.cs b/Adyen/Model/ApiError.cs deleted file mode 100644 index 6a544f85e..000000000 --- a/Adyen/Model/ApiError.cs +++ /dev/null @@ -1,141 +0,0 @@ -#region License -// /* -// * ###### -// * ###### -// * ############ ####( ###### #####. ###### ############ ############ -// * ############# #####( ###### #####. ###### ############# ############# -// * ###### #####( ###### #####. ###### ##### ###### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ###### -// * ############# ############# ############# ############# ##### ###### -// * ############ ############ ############# ############ ##### ###### -// * ###### -// * ############# -// * ############ -// * -// * Adyen Dotnet API Library -// * -// * Copyright (c) 2020 Adyen B.V. -// * This file is open source and available under the MIT license. -// * See the LICENSE file for more info. -// */ -#endregion - -using Adyen.Model.Recurring; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Text; - -namespace Adyen.Model -{ - public class ApiError : IEquatable, IValidatableObject - { - public int Status { get; set; } - public string ErrorCode { get; set; } - public string Message { get; set; } - public string ErrorType { get; set; } - public string PspReference { get; set; } - - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class ApiError {\n"); - sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); - sb.Append(" Message: ").Append(Message).Append("\n"); - sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); - sb.Append(" PspReference: ").Append(PspReference).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as RecurringDetailsResult); - } - - /// - /// Returns true if RecurringDetailsResult instances are equal - /// - /// Instance of RecurringDetailsResult to be compared - /// Boolean - public bool Equals(ApiError other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this.Status == other.Status || - - this.Status.Equals(other.Status) - ) && - ( - this.ErrorCode == other.ErrorCode || - this.ErrorCode != null && - this.ErrorCode.Equals(other.ErrorCode) - ) && - ( - this.Message == other.Message || - this.Message != null && - this.Message.Equals(other.Message) - ) && - ( - this.ErrorType == other.ErrorType || - this.ErrorType != null && - this.ErrorType.Equals(other.ErrorType) - ) && - ( - this.PspReference == other.PspReference || - this.PspReference != null && - this.PspReference.Equals(other.PspReference) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - hash = hash * 59 + this.Status.GetHashCode(); - if (this.ErrorCode != null) - hash = hash * 59 + this.ErrorCode.GetHashCode(); - if (this.Message != null) - hash = hash * 59 + this.Message.GetHashCode(); - if (this.ErrorType != null) - hash = hash * 59 + this.ErrorType.GetHashCode(); - if (this.PspReference != null) - hash = hash * 59 + this.PspReference.GetHashCode(); - return hash; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } -} diff --git a/Adyen/Model/BalancePlatform/VerificationError.cs b/Adyen/Model/BalancePlatform/VerificationError.cs index 64777db77..ab623fc06 100644 --- a/Adyen/Model/BalancePlatform/VerificationError.cs +++ b/Adyen/Model/BalancePlatform/VerificationError.cs @@ -401,15 +401,20 @@ public enum TypeEnum /// Enum PendingStatus for value: pendingStatus /// [EnumMember(Value = "pendingStatus")] - PendingStatus = 3 - + PendingStatus = 3, + + /// + /// Enum DataReview for value: dataReview + /// + [EnumMember(Value = "dataReview")] + DataReview = 4 } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -420,7 +425,7 @@ public enum TypeEnum /// A description of the error.. /// Contains the actions that you can take to resolve the verification error.. /// Contains more granular information about the verification error.. - /// The type of error. Possible values: **invalidInput**, **dataMissing**.. + /// The type of error. Possible values: **invalidInput**, **dataMissing**, **pendingStatus**, **dataReview** . public VerificationError(List capabilities = default(List), string code = default(string), string message = default(string), List remediatingActions = default(List), List subErrors = default(List), TypeEnum? type = default(TypeEnum?)) { this.Capabilities = capabilities; diff --git a/Adyen/Model/BalancePlatform/VerificationErrorRecursive.cs b/Adyen/Model/BalancePlatform/VerificationErrorRecursive.cs index eb3720572..9bf8551f9 100644 --- a/Adyen/Model/BalancePlatform/VerificationErrorRecursive.cs +++ b/Adyen/Model/BalancePlatform/VerificationErrorRecursive.cs @@ -379,9 +379,9 @@ public enum CapabilitiesEnum [DataMember(Name = "capabilities", EmitDefaultValue = false)] public List Capabilities { get; set; } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -401,15 +401,21 @@ public enum TypeEnum /// Enum PendingStatus for value: pendingStatus /// [EnumMember(Value = "pendingStatus")] - PendingStatus = 3 + PendingStatus = 3, + + /// + /// Enum DataReview for value: dataReview + /// + [EnumMember(Value = "dataReview")] + DataReview = 4 } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// diff --git a/Adyen/Model/Checkout/AdditionalDataSubMerchant.cs b/Adyen/Model/Checkout/AdditionalDataSubMerchant.cs index 883cfbb5f..bfbcea0a1 100644 --- a/Adyen/Model/Checkout/AdditionalDataSubMerchant.cs +++ b/Adyen/Model/Checkout/AdditionalDataSubMerchant.cs @@ -41,7 +41,7 @@ public partial class AdditionalDataSubMerchant : IEquatableRequired for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters. /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters. /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits. - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters. + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters. /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters. /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits. /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters. @@ -106,9 +106,9 @@ public partial class AdditionalDataSubMerchant : IEquatable - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters /// - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters [DataMember(Name = "subMerchant.subSeller[subSellerNr].name", EmitDefaultValue = false)] public string SubMerchantSubSellerSubSellerNrName { get; set; } diff --git a/Adyen/Model/Checkout/AuthenticationData.cs b/Adyen/Model/Checkout/AuthenticationData.cs index 991c56b3c..974b35995 100644 --- a/Adyen/Model/Checkout/AuthenticationData.cs +++ b/Adyen/Model/Checkout/AuthenticationData.cs @@ -64,7 +64,7 @@ public enum AttemptAuthenticationEnum /// Initializes a new instance of the class. /// /// Indicates when 3D Secure authentication should be attempted. This overrides all other rules, including [Dynamic 3D Secure settings](https://docs.adyen.com/risk-management/dynamic-3d-secure). Possible values: * **always**: Perform 3D Secure authentication. * **never**: Don't perform 3D Secure authentication. If PSD2 SCA or other national regulations require authentication, the transaction gets declined.. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: **false**. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. (default to false). /// threeDSRequestData. public AuthenticationData(AttemptAuthenticationEnum? attemptAuthentication = default(AttemptAuthenticationEnum?), bool? authenticationOnly = false, ThreeDSRequestData threeDSRequestData = default(ThreeDSRequestData)) { @@ -74,9 +74,9 @@ public enum AttemptAuthenticationEnum } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: **false**. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: **false**. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization. Default: **false**. [DataMember(Name = "authenticationOnly", EmitDefaultValue = false)] public bool? AuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/BalanceCheckRequest.cs b/Adyen/Model/Checkout/BalanceCheckRequest.cs index e15c595f7..50f294353 100644 --- a/Adyen/Model/Checkout/BalanceCheckRequest.cs +++ b/Adyen/Model/Checkout/BalanceCheckRequest.cs @@ -143,8 +143,8 @@ protected BalanceCheckRequest() { } /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card.. /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail.. /// A session ID used to identify a payment session.. - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations.. - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`.. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// shopperName. @@ -153,9 +153,9 @@ protected BalanceCheckRequest() { } /// The shopper's social security number.. /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split).. /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// threeDS2RequestData. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false). /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available).. /// Set to true if the payment should be routed to a trusted MID.. public BalanceCheckRequest(AccountInfo accountInfo = default(AccountInfo), Amount additionalAmount = default(Amount), Dictionary additionalData = default(Dictionary), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), Address billingAddress = default(Address), BrowserInfo browserInfo = default(BrowserInfo), int? captureDelayHours = default(int?), DateTime dateOfBirth = default(DateTime), ForexQuote dccQuote = default(ForexQuote), Address deliveryAddress = default(Address), DateTime deliveryDate = default(DateTime), string deviceFingerprint = default(string), int? fraudOffset = default(int?), Installments installments = default(Installments), Dictionary localizedShopperStatement = default(Dictionary), string mcc = default(string), string merchantAccount = default(string), string merchantOrderReference = default(string), MerchantRiskIndicator merchantRiskIndicator = default(MerchantRiskIndicator), Dictionary metadata = default(Dictionary), string orderReference = default(string), Dictionary paymentMethod = default(Dictionary), Recurring recurring = default(Recurring), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string reference = default(string), string selectedBrand = default(string), string selectedRecurringDetailReference = default(string), string sessionId = default(string), string shopperEmail = default(string), string shopperIP = default(string), ShopperInteractionEnum? shopperInteraction = default(ShopperInteractionEnum?), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string shopperStatement = default(string), string socialSecurityNumber = default(string), List splits = default(List), string store = default(string), string telephoneNumber = default(string), ThreeDS2RequestData threeDS2RequestData = default(ThreeDS2RequestData), bool? threeDSAuthenticationOnly = false, string totalsGroup = default(string), bool? trustedShopper = default(bool?)) @@ -393,16 +393,16 @@ protected BalanceCheckRequest() { } public string SessionId { get; set; } /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. [DataMember(Name = "shopperEmail", EmitDefaultValue = false)] public string ShopperEmail { get; set; } /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). [DataMember(Name = "shopperIP", EmitDefaultValue = false)] public string ShopperIP { get; set; } @@ -455,9 +455,9 @@ protected BalanceCheckRequest() { } public string Store { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } @@ -468,9 +468,9 @@ protected BalanceCheckRequest() { } public ThreeDS2RequestData ThreeDS2RequestData { get; set; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. [DataMember(Name = "threeDSAuthenticationOnly", EmitDefaultValue = false)] [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] public bool? ThreeDSAuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/CardDetails.cs b/Adyen/Model/Checkout/CardDetails.cs index 1d87040d4..70db52490 100644 --- a/Adyen/Model/Checkout/CardDetails.cs +++ b/Adyen/Model/Checkout/CardDetails.cs @@ -123,13 +123,14 @@ public enum TypeEnum /// The encrypted card number.. /// The encrypted card expiry month.. /// The encrypted card expiry year.. + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder.. /// The encrypted card verification code.. /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// The encoded fastlane data blob. /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**.. /// The name of the card holder.. - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment.. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment.. /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// This is the `recurringDetailReference` returned in the response when you created the token.. /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India.. @@ -140,7 +141,7 @@ public enum TypeEnum /// This is the `recurringDetailReference` returned in the response when you created the token.. /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK.. /// Default payment method details. Common for scheme payment methods, and for simple payment method details. (default to TypeEnum.Scheme). - public CardDetails(string brand = default(string), string checkoutAttemptId = default(string), string cupsecureplusSmscode = default(string), string cvc = default(string), string encryptedCard = default(string), string encryptedCardNumber = default(string), string encryptedExpiryMonth = default(string), string encryptedExpiryYear = default(string), string encryptedSecurityCode = default(string), string expiryMonth = default(string), string expiryYear = default(string), string fastlaneData = default(string), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), string holderName = default(string), string networkPaymentReference = default(string), string number = default(string), string recurringDetailReference = default(string), string shopperNotificationReference = default(string), string srcCorrelationId = default(string), string srcDigitalCardId = default(string), string srcScheme = default(string), string srcTokenReference = default(string), string storedPaymentMethodId = default(string), string threeDS2SdkVersion = default(string), TypeEnum? type = TypeEnum.Scheme) + public CardDetails(string brand = default(string), string checkoutAttemptId = default(string), string cupsecureplusSmscode = default(string), string cvc = default(string), string encryptedCard = default(string), string encryptedCardNumber = default(string), string encryptedExpiryMonth = default(string), string encryptedExpiryYear = default(string), string encryptedPassword = default(string), string encryptedSecurityCode = default(string), string expiryMonth = default(string), string expiryYear = default(string), string fastlaneData = default(string), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), string holderName = default(string), string networkPaymentReference = default(string), string number = default(string), string recurringDetailReference = default(string), string shopperNotificationReference = default(string), string srcCorrelationId = default(string), string srcDigitalCardId = default(string), string srcScheme = default(string), string srcTokenReference = default(string), string storedPaymentMethodId = default(string), string threeDS2SdkVersion = default(string), TypeEnum? type = TypeEnum.Scheme) { this.Brand = brand; this.CheckoutAttemptId = checkoutAttemptId; @@ -150,6 +151,7 @@ public enum TypeEnum this.EncryptedCardNumber = encryptedCardNumber; this.EncryptedExpiryMonth = encryptedExpiryMonth; this.EncryptedExpiryYear = encryptedExpiryYear; + this.EncryptedPassword = encryptedPassword; this.EncryptedSecurityCode = encryptedSecurityCode; this.ExpiryMonth = expiryMonth; this.ExpiryYear = expiryYear; @@ -225,6 +227,13 @@ public enum TypeEnum [DataMember(Name = "encryptedExpiryYear", EmitDefaultValue = false)] public string EncryptedExpiryYear { get; set; } + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + [DataMember(Name = "encryptedPassword", EmitDefaultValue = false)] + public string EncryptedPassword { get; set; } + /// /// The encrypted card verification code. /// @@ -261,9 +270,9 @@ public enum TypeEnum public string HolderName { get; set; } /// - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. /// - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. [DataMember(Name = "networkPaymentReference", EmitDefaultValue = false)] public string NetworkPaymentReference { get; set; } @@ -347,6 +356,7 @@ public override string ToString() sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); sb.Append(" EncryptedExpiryMonth: ").Append(EncryptedExpiryMonth).Append("\n"); sb.Append(" EncryptedExpiryYear: ").Append(EncryptedExpiryYear).Append("\n"); + sb.Append(" EncryptedPassword: ").Append(EncryptedPassword).Append("\n"); sb.Append(" EncryptedSecurityCode: ").Append(EncryptedSecurityCode).Append("\n"); sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); @@ -439,6 +449,11 @@ public bool Equals(CardDetails input) (this.EncryptedExpiryYear != null && this.EncryptedExpiryYear.Equals(input.EncryptedExpiryYear)) ) && + ( + this.EncryptedPassword == input.EncryptedPassword || + (this.EncryptedPassword != null && + this.EncryptedPassword.Equals(input.EncryptedPassword)) + ) && ( this.EncryptedSecurityCode == input.EncryptedSecurityCode || (this.EncryptedSecurityCode != null && @@ -565,6 +580,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.EncryptedExpiryYear.GetHashCode(); } + if (this.EncryptedPassword != null) + { + hashCode = (hashCode * 59) + this.EncryptedPassword.GetHashCode(); + } if (this.EncryptedSecurityCode != null) { hashCode = (hashCode * 59) + this.EncryptedSecurityCode.GetHashCode(); diff --git a/Adyen/Model/Checkout/CardDonations.cs b/Adyen/Model/Checkout/CardDonations.cs index 13a88d4f8..08cb712f9 100644 --- a/Adyen/Model/Checkout/CardDonations.cs +++ b/Adyen/Model/Checkout/CardDonations.cs @@ -123,13 +123,14 @@ public enum TypeEnum /// The encrypted card number.. /// The encrypted card expiry month.. /// The encrypted card expiry year.. + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder.. /// The encrypted card verification code.. /// The card expiry month. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// The card expiry year. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// The encoded fastlane data blob. /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**.. /// The name of the card holder.. - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment.. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment.. /// The card number. Only collect raw card data if you are [fully PCI compliant](https://docs.adyen.com/development-resources/pci-dss-compliance-guide).. /// This is the `recurringDetailReference` returned in the response when you created the token.. /// The `shopperNotificationReference` returned in the response when you requested to notify the shopper. Used only for recurring payments in India.. @@ -140,7 +141,7 @@ public enum TypeEnum /// This is the `recurringDetailReference` returned in the response when you created the token.. /// Required for mobile integrations. Version of the 3D Secure 2 mobile SDK.. /// Default payment method details. Common for scheme payment methods, and for simple payment method details. (default to TypeEnum.Scheme). - public CardDonations(string brand = default(string), string checkoutAttemptId = default(string), string cupsecureplusSmscode = default(string), string cvc = default(string), string encryptedCard = default(string), string encryptedCardNumber = default(string), string encryptedExpiryMonth = default(string), string encryptedExpiryYear = default(string), string encryptedSecurityCode = default(string), string expiryMonth = default(string), string expiryYear = default(string), string fastlaneData = default(string), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), string holderName = default(string), string networkPaymentReference = default(string), string number = default(string), string recurringDetailReference = default(string), string shopperNotificationReference = default(string), string srcCorrelationId = default(string), string srcDigitalCardId = default(string), string srcScheme = default(string), string srcTokenReference = default(string), string storedPaymentMethodId = default(string), string threeDS2SdkVersion = default(string), TypeEnum? type = TypeEnum.Scheme) + public CardDonations(string brand = default(string), string checkoutAttemptId = default(string), string cupsecureplusSmscode = default(string), string cvc = default(string), string encryptedCard = default(string), string encryptedCardNumber = default(string), string encryptedExpiryMonth = default(string), string encryptedExpiryYear = default(string), string encryptedPassword = default(string), string encryptedSecurityCode = default(string), string expiryMonth = default(string), string expiryYear = default(string), string fastlaneData = default(string), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), string holderName = default(string), string networkPaymentReference = default(string), string number = default(string), string recurringDetailReference = default(string), string shopperNotificationReference = default(string), string srcCorrelationId = default(string), string srcDigitalCardId = default(string), string srcScheme = default(string), string srcTokenReference = default(string), string storedPaymentMethodId = default(string), string threeDS2SdkVersion = default(string), TypeEnum? type = TypeEnum.Scheme) { this.Brand = brand; this.CheckoutAttemptId = checkoutAttemptId; @@ -150,6 +151,7 @@ public enum TypeEnum this.EncryptedCardNumber = encryptedCardNumber; this.EncryptedExpiryMonth = encryptedExpiryMonth; this.EncryptedExpiryYear = encryptedExpiryYear; + this.EncryptedPassword = encryptedPassword; this.EncryptedSecurityCode = encryptedSecurityCode; this.ExpiryMonth = expiryMonth; this.ExpiryYear = expiryYear; @@ -225,6 +227,13 @@ public enum TypeEnum [DataMember(Name = "encryptedExpiryYear", EmitDefaultValue = false)] public string EncryptedExpiryYear { get; set; } + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + /// + /// This field contains an encrypted, one-time password or an authentication code provided by the cardholder. + [DataMember(Name = "encryptedPassword", EmitDefaultValue = false)] + public string EncryptedPassword { get; set; } + /// /// The encrypted card verification code. /// @@ -261,9 +270,9 @@ public enum TypeEnum public string HolderName { get; set; } /// - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. /// - /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. + /// The transaction identifier from card schemes. This is the [`networkTxReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-additionalData-ResponseAdditionalDataCommon-networkTxReference) from the response to the first payment. [DataMember(Name = "networkPaymentReference", EmitDefaultValue = false)] public string NetworkPaymentReference { get; set; } @@ -347,6 +356,7 @@ public override string ToString() sb.Append(" EncryptedCardNumber: ").Append(EncryptedCardNumber).Append("\n"); sb.Append(" EncryptedExpiryMonth: ").Append(EncryptedExpiryMonth).Append("\n"); sb.Append(" EncryptedExpiryYear: ").Append(EncryptedExpiryYear).Append("\n"); + sb.Append(" EncryptedPassword: ").Append(EncryptedPassword).Append("\n"); sb.Append(" EncryptedSecurityCode: ").Append(EncryptedSecurityCode).Append("\n"); sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); @@ -439,6 +449,11 @@ public bool Equals(CardDonations input) (this.EncryptedExpiryYear != null && this.EncryptedExpiryYear.Equals(input.EncryptedExpiryYear)) ) && + ( + this.EncryptedPassword == input.EncryptedPassword || + (this.EncryptedPassword != null && + this.EncryptedPassword.Equals(input.EncryptedPassword)) + ) && ( this.EncryptedSecurityCode == input.EncryptedSecurityCode || (this.EncryptedSecurityCode != null && @@ -565,6 +580,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.EncryptedExpiryYear.GetHashCode(); } + if (this.EncryptedPassword != null) + { + hashCode = (hashCode * 59) + this.EncryptedPassword.GetHashCode(); + } if (this.EncryptedSecurityCode != null) { hashCode = (hashCode * 59) + this.EncryptedSecurityCode.GetHashCode(); diff --git a/Adyen/Model/Checkout/CreateCheckoutSessionRequest.cs b/Adyen/Model/Checkout/CreateCheckoutSessionRequest.cs index 8ea96dc09..6cecc7153 100644 --- a/Adyen/Model/Checkout/CreateCheckoutSessionRequest.cs +++ b/Adyen/Model/Checkout/CreateCheckoutSessionRequest.cs @@ -282,10 +282,10 @@ protected CreateCheckoutSessionRequest() { } /// Specifies the redirect method (GET or POST) when redirecting back from the issuer.. /// Specifies the redirect method (GET or POST) when redirecting to the issuer.. /// The reference to uniquely identify a payment. (required). - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. (required). + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. (required). /// riskData. /// The shopper's email address.. - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// shopperName. @@ -300,10 +300,10 @@ protected CreateCheckoutSessionRequest() { } /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned.. /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types).. /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area.. /// threeDS2RequestData. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false). /// Set to true if the payment should be routed to a trusted MID.. public CreateCheckoutSessionRequest(AccountInfo accountInfo = default(AccountInfo), Amount additionalAmount = default(Amount), Dictionary additionalData = default(Dictionary), List allowedPaymentMethods = default(List), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), AuthenticationData authenticationData = default(AuthenticationData), BillingAddress billingAddress = default(BillingAddress), List blockedPaymentMethods = default(List), int? captureDelayHours = default(int?), ChannelEnum? channel = default(ChannelEnum?), Company company = default(Company), string countryCode = default(string), DateTime dateOfBirth = default(DateTime), DateTime deliverAt = default(DateTime), DeliveryAddress deliveryAddress = default(DeliveryAddress), bool? enableOneClick = default(bool?), bool? enablePayOut = default(bool?), bool? enableRecurring = default(bool?), DateTime expiresAt = default(DateTime), FundOrigin fundOrigin = default(FundOrigin), FundRecipient fundRecipient = default(FundRecipient), Dictionary installmentOptions = default(Dictionary), List lineItems = default(List), Mandate mandate = default(Mandate), string mcc = default(string), string merchantAccount = default(string), string merchantOrderReference = default(string), Dictionary metadata = default(Dictionary), ModeEnum? mode = ModeEnum.Embedded, ThreeDSecureData mpiData = default(ThreeDSecureData), PlatformChargebackLogic platformChargebackLogic = default(PlatformChargebackLogic), string recurringExpiry = default(string), string recurringFrequency = default(string), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string redirectFromIssuerMethod = default(string), string redirectToIssuerMethod = default(string), string reference = default(string), string returnUrl = default(string), RiskData riskData = default(RiskData), string shopperEmail = default(string), string shopperIP = default(string), ShopperInteractionEnum? shopperInteraction = default(ShopperInteractionEnum?), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string shopperStatement = default(string), bool? showInstallmentAmount = default(bool?), bool? showRemovePaymentMethodButton = default(bool?), string socialSecurityNumber = default(string), bool? splitCardFundingSources = false, List splits = default(List), string store = default(string), StoreFiltrationModeEnum? storeFiltrationMode = default(StoreFiltrationModeEnum?), bool? storePaymentMethod = default(bool?), StorePaymentMethodModeEnum? storePaymentMethodMode = default(StorePaymentMethodModeEnum?), string telephoneNumber = default(string), string themeId = default(string), CheckoutSessionThreeDS2RequestData threeDS2RequestData = default(CheckoutSessionThreeDS2RequestData), bool? threeDSAuthenticationOnly = false, bool? trustedShopper = default(bool?)) { @@ -604,9 +604,9 @@ protected CreateCheckoutSessionRequest() { } public string Reference { get; set; } /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. [DataMember(Name = "returnUrl", IsRequired = false, EmitDefaultValue = false)] public string ReturnUrl { get; set; } @@ -624,9 +624,9 @@ protected CreateCheckoutSessionRequest() { } public string ShopperEmail { get; set; } /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). [DataMember(Name = "shopperIP", EmitDefaultValue = false)] public string ShopperIP { get; set; } @@ -707,9 +707,9 @@ protected CreateCheckoutSessionRequest() { } public bool? StorePaymentMethod { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } @@ -727,9 +727,9 @@ protected CreateCheckoutSessionRequest() { } public CheckoutSessionThreeDS2RequestData ThreeDS2RequestData { get; set; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. [DataMember(Name = "threeDSAuthenticationOnly", EmitDefaultValue = false)] [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] public bool? ThreeDSAuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/CreateCheckoutSessionResponse.cs b/Adyen/Model/Checkout/CreateCheckoutSessionResponse.cs index b1db134a1..2e2d58a66 100644 --- a/Adyen/Model/Checkout/CreateCheckoutSessionResponse.cs +++ b/Adyen/Model/Checkout/CreateCheckoutSessionResponse.cs @@ -282,11 +282,11 @@ protected CreateCheckoutSessionResponse() { } /// Specifies the redirect method (GET or POST) when redirecting back from the issuer.. /// Specifies the redirect method (GET or POST) when redirecting to the issuer.. /// The reference to uniquely identify a payment. (required). - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. (required). + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. (required). /// riskData. /// The payment session data you need to pass to your front end.. /// The shopper's email address.. - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// shopperName. @@ -301,10 +301,10 @@ protected CreateCheckoutSessionResponse() { } /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned.. /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types).. /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// Sets a custom theme for [Hosted Checkout](https://docs.adyen.com/online-payments/build-your-integration/?platform=Web&integration=Hosted+Checkout). The value can be any of the **Theme ID** values from your Customer Area.. /// threeDS2RequestData. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false). /// Set to true if the payment should be routed to a trusted MID.. /// The URL for the Hosted Checkout page. Redirect the shopper to this URL so they can make the payment.. public CreateCheckoutSessionResponse(AccountInfo accountInfo = default(AccountInfo), Amount additionalAmount = default(Amount), Dictionary additionalData = default(Dictionary), List allowedPaymentMethods = default(List), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), AuthenticationData authenticationData = default(AuthenticationData), BillingAddress billingAddress = default(BillingAddress), List blockedPaymentMethods = default(List), int? captureDelayHours = default(int?), ChannelEnum? channel = default(ChannelEnum?), Company company = default(Company), string countryCode = default(string), DateTime dateOfBirth = default(DateTime), DateTime deliverAt = default(DateTime), DeliveryAddress deliveryAddress = default(DeliveryAddress), bool? enableOneClick = default(bool?), bool? enablePayOut = default(bool?), bool? enableRecurring = default(bool?), DateTime expiresAt = default(DateTime), FundOrigin fundOrigin = default(FundOrigin), FundRecipient fundRecipient = default(FundRecipient), Dictionary installmentOptions = default(Dictionary), List lineItems = default(List), Mandate mandate = default(Mandate), string mcc = default(string), string merchantAccount = default(string), string merchantOrderReference = default(string), Dictionary metadata = default(Dictionary), ModeEnum? mode = ModeEnum.Embedded, ThreeDSecureData mpiData = default(ThreeDSecureData), PlatformChargebackLogic platformChargebackLogic = default(PlatformChargebackLogic), string recurringExpiry = default(string), string recurringFrequency = default(string), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string redirectFromIssuerMethod = default(string), string redirectToIssuerMethod = default(string), string reference = default(string), string returnUrl = default(string), RiskData riskData = default(RiskData), string sessionData = default(string), string shopperEmail = default(string), string shopperIP = default(string), ShopperInteractionEnum? shopperInteraction = default(ShopperInteractionEnum?), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string shopperStatement = default(string), bool? showInstallmentAmount = default(bool?), bool? showRemovePaymentMethodButton = default(bool?), string socialSecurityNumber = default(string), bool? splitCardFundingSources = false, List splits = default(List), string store = default(string), StoreFiltrationModeEnum? storeFiltrationMode = default(StoreFiltrationModeEnum?), bool? storePaymentMethod = default(bool?), StorePaymentMethodModeEnum? storePaymentMethodMode = default(StorePaymentMethodModeEnum?), string telephoneNumber = default(string), string themeId = default(string), CheckoutSessionThreeDS2RequestData threeDS2RequestData = default(CheckoutSessionThreeDS2RequestData), bool? threeDSAuthenticationOnly = false, bool? trustedShopper = default(bool?), string url = default(string)) @@ -614,9 +614,9 @@ protected CreateCheckoutSessionResponse() { } public string Reference { get; set; } /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. [DataMember(Name = "returnUrl", IsRequired = false, EmitDefaultValue = false)] public string ReturnUrl { get; set; } @@ -641,9 +641,9 @@ protected CreateCheckoutSessionResponse() { } public string ShopperEmail { get; set; } /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). [DataMember(Name = "shopperIP", EmitDefaultValue = false)] public string ShopperIP { get; set; } @@ -724,9 +724,9 @@ protected CreateCheckoutSessionResponse() { } public bool? StorePaymentMethod { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } @@ -744,9 +744,9 @@ protected CreateCheckoutSessionResponse() { } public CheckoutSessionThreeDS2RequestData ThreeDS2RequestData { get; set; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. [DataMember(Name = "threeDSAuthenticationOnly", EmitDefaultValue = false)] [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] public bool? ThreeDSAuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/DetailsRequestAuthenticationData.cs b/Adyen/Model/Checkout/DetailsRequestAuthenticationData.cs index 26c9d1432..ee3580d0d 100644 --- a/Adyen/Model/Checkout/DetailsRequestAuthenticationData.cs +++ b/Adyen/Model/Checkout/DetailsRequestAuthenticationData.cs @@ -35,16 +35,16 @@ public partial class DetailsRequestAuthenticationData : IEquatable /// Initializes a new instance of the class. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: *false**. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false). public DetailsRequestAuthenticationData(bool? authenticationOnly = false) { this.AuthenticationOnly = authenticationOnly; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: *false**. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. Default: *false**. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. [DataMember(Name = "authenticationOnly", EmitDefaultValue = false)] public bool? AuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/DonationPaymentRequest.cs b/Adyen/Model/Checkout/DonationPaymentRequest.cs index bec73d6fa..1fd2eef0b 100644 --- a/Adyen/Model/Checkout/DonationPaymentRequest.cs +++ b/Adyen/Model/Checkout/DonationPaymentRequest.cs @@ -101,9 +101,9 @@ public enum RecurringProcessingModelEnum [DataMember(Name = "recurringProcessingModel", EmitDefaultValue = false)] public RecurringProcessingModelEnum? RecurringProcessingModel { get; set; } /// - /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. /// - /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. [JsonConverter(typeof(StringEnumConverter))] public enum ShopperInteractionEnum { @@ -135,9 +135,9 @@ public enum ShopperInteractionEnum /// - /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. /// - /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. [DataMember(Name = "shopperInteraction", EmitDefaultValue = false)] public ShopperInteractionEnum? ShopperInteraction { get; set; } /// @@ -172,24 +172,24 @@ protected DonationPaymentRequest() { } /// merchantRiskIndicator. /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. . /// mpiData. - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from.. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash.. /// paymentMethod (required). /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. . /// Specifies the redirect method (GET or POST) when redirecting back from the issuer.. /// Specifies the redirect method (GET or POST) when redirecting to the issuer.. /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. (required). - /// The URL to return to in case of a redirection. The format depends on the channel. This URL can have a maximum of 1024 characters. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. (required). + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. (required). /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00. - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations.. - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. - /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`.. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorization rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorization (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// shopperName. /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address.. /// The shopper's social security number.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// threeDS2RequestData. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false). public DonationPaymentRequest(AccountInfo accountInfo = default(AccountInfo), Dictionary additionalData = default(Dictionary), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), AuthenticationData authenticationData = default(AuthenticationData), BillingAddress billingAddress = default(BillingAddress), BrowserInfo browserInfo = default(BrowserInfo), ChannelEnum? channel = default(ChannelEnum?), string checkoutAttemptId = default(string), string conversionId = default(string), string countryCode = default(string), DateTime dateOfBirth = default(DateTime), DateTime deliverAt = default(DateTime), DeliveryAddress deliveryAddress = default(DeliveryAddress), string deviceFingerprint = default(string), string donationAccount = default(string), string donationCampaignId = default(string), string donationOriginalPspReference = default(string), string donationToken = default(string), List lineItems = default(List), string merchantAccount = default(string), MerchantRiskIndicator merchantRiskIndicator = default(MerchantRiskIndicator), Dictionary metadata = default(Dictionary), ThreeDSecureData mpiData = default(ThreeDSecureData), string origin = default(string), DonationPaymentMethod paymentMethod = default(DonationPaymentMethod), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string redirectFromIssuerMethod = default(string), string redirectToIssuerMethod = default(string), string reference = default(string), string returnUrl = default(string), string sessionValidity = default(string), string shopperEmail = default(string), string shopperIP = default(string), ShopperInteractionEnum? shopperInteraction = default(ShopperInteractionEnum?), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string socialSecurityNumber = default(string), string telephoneNumber = default(string), ThreeDS2RequestFields threeDS2RequestData = default(ThreeDS2RequestFields), bool? threeDSAuthenticationOnly = false) { this.Amount = amount; @@ -390,9 +390,9 @@ protected DonationPaymentRequest() { } public ThreeDSecureData MpiData { get; set; } /// - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. /// - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. [DataMember(Name = "origin", EmitDefaultValue = false)] public string Origin { get; set; } @@ -424,9 +424,9 @@ protected DonationPaymentRequest() { } public string Reference { get; set; } /// - /// The URL to return to in case of a redirection. The format depends on the channel. This URL can have a maximum of 1024 characters. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. /// - /// The URL to return to in case of a redirection. The format depends on the channel. This URL can have a maximum of 1024 characters. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. [DataMember(Name = "returnUrl", IsRequired = false, EmitDefaultValue = false)] public string ReturnUrl { get; set; } @@ -438,16 +438,16 @@ protected DonationPaymentRequest() { } public string SessionValidity { get; set; } /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. [DataMember(Name = "shopperEmail", EmitDefaultValue = false)] public string ShopperEmail { get; set; } /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). [DataMember(Name = "shopperIP", EmitDefaultValue = false)] public string ShopperIP { get; set; } @@ -479,9 +479,9 @@ protected DonationPaymentRequest() { } public string SocialSecurityNumber { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } @@ -492,9 +492,9 @@ protected DonationPaymentRequest() { } public ThreeDS2RequestFields ThreeDS2RequestData { get; set; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. [DataMember(Name = "threeDSAuthenticationOnly", EmitDefaultValue = false)] [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] public bool? ThreeDSAuthenticationOnly { get; set; } diff --git a/Adyen/Model/Checkout/Payment.cs b/Adyen/Model/Checkout/Payment.cs new file mode 100644 index 000000000..05d8a43c4 --- /dev/null +++ b/Adyen/Model/Checkout/Payment.cs @@ -0,0 +1,195 @@ +/* +* Adyen Checkout API +* +* +* The version of the OpenAPI document: 71 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.Checkout +{ + /// + /// Payment + /// + [DataContract(Name = "Payment")] + public partial class Payment : IEquatable, IValidatableObject + { + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + [JsonConverter(typeof(StringEnumConverter))] + public enum ResultCodeEnum + { + /// + /// Enum Authorised for value: Authorised + /// + [EnumMember(Value = "Authorised")] + Authorised = 1 + + } + + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. + [DataMember(Name = "resultCode", EmitDefaultValue = false)] + public ResultCodeEnum? ResultCode { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// amount. + /// paymentMethod. + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request.. + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. . + public Payment(Amount amount = default(Amount), ResponsePaymentMethod paymentMethod = default(ResponsePaymentMethod), string pspReference = default(string), ResultCodeEnum? resultCode = default(ResultCodeEnum?)) + { + this.Amount = amount; + this.PaymentMethod = paymentMethod; + this.PspReference = pspReference; + this.ResultCode = resultCode; + } + + /// + /// Gets or Sets Amount + /// + [DataMember(Name = "amount", EmitDefaultValue = false)] + public Amount Amount { get; set; } + + /// + /// Gets or Sets PaymentMethod + /// + [DataMember(Name = "paymentMethod", EmitDefaultValue = false)] + public ResponsePaymentMethod PaymentMethod { get; set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique. Use this reference when you communicate with us about this request. + [DataMember(Name = "pspReference", EmitDefaultValue = false)] + public string PspReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Payment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Payment); + } + + /// + /// Returns true if Payment instances are equal + /// + /// Instance of Payment to be compared + /// Boolean + public bool Equals(Payment input) + { + if (input == null) + { + return false; + } + return + ( + this.Amount == input.Amount || + (this.Amount != null && + this.Amount.Equals(input.Amount)) + ) && + ( + this.PaymentMethod == input.PaymentMethod || + (this.PaymentMethod != null && + this.PaymentMethod.Equals(input.PaymentMethod)) + ) && + ( + this.PspReference == input.PspReference || + (this.PspReference != null && + this.PspReference.Equals(input.PspReference)) + ) && + ( + this.ResultCode == input.ResultCode || + this.ResultCode.Equals(input.ResultCode) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Amount != null) + { + hashCode = (hashCode * 59) + this.Amount.GetHashCode(); + } + if (this.PaymentMethod != null) + { + hashCode = (hashCode * 59) + this.PaymentMethod.GetHashCode(); + } + if (this.PspReference != null) + { + hashCode = (hashCode * 59) + this.PspReference.GetHashCode(); + } + hashCode = (hashCode * 59) + this.ResultCode.GetHashCode(); + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/Checkout/PaymentAmountUpdateRequest.cs b/Adyen/Model/Checkout/PaymentAmountUpdateRequest.cs index 5aac0b522..61f584801 100644 --- a/Adyen/Model/Checkout/PaymentAmountUpdateRequest.cs +++ b/Adyen/Model/Checkout/PaymentAmountUpdateRequest.cs @@ -76,16 +76,18 @@ protected PaymentAmountUpdateRequest() { } /// /// amount (required). /// applicationInfo. + /// enhancedSchemeData. /// The reason for the amount update. Possible values: * **delayedCharge** * **noShow** * **installment**. /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip.. /// The merchant account that is used to process the payment. (required). /// Your reference for the amount update request. Maximum length: 80 characters.. /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/process-payments) or [platforms](https://docs.adyen.com/platforms/process-payments).. - public PaymentAmountUpdateRequest(Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), IndustryUsageEnum? industryUsage = default(IndustryUsageEnum?), List lineItems = default(List), string merchantAccount = default(string), string reference = default(string), List splits = default(List)) + public PaymentAmountUpdateRequest(Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), IndustryUsageEnum? industryUsage = default(IndustryUsageEnum?), List lineItems = default(List), string merchantAccount = default(string), string reference = default(string), List splits = default(List)) { this.Amount = amount; this.MerchantAccount = merchantAccount; this.ApplicationInfo = applicationInfo; + this.EnhancedSchemeData = enhancedSchemeData; this.IndustryUsage = industryUsage; this.LineItems = lineItems; this.Reference = reference; @@ -104,6 +106,12 @@ protected PaymentAmountUpdateRequest() { } [DataMember(Name = "applicationInfo", EmitDefaultValue = false)] public ApplicationInfo ApplicationInfo { get; set; } + /// + /// Gets or Sets EnhancedSchemeData + /// + [DataMember(Name = "enhancedSchemeData", EmitDefaultValue = false)] + public EnhancedSchemeData EnhancedSchemeData { get; set; } + /// /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. /// @@ -142,6 +150,7 @@ public override string ToString() sb.Append("class PaymentAmountUpdateRequest {\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); sb.Append(" LineItems: ").Append(LineItems).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); @@ -192,6 +201,11 @@ public bool Equals(PaymentAmountUpdateRequest input) (this.ApplicationInfo != null && this.ApplicationInfo.Equals(input.ApplicationInfo)) ) && + ( + this.EnhancedSchemeData == input.EnhancedSchemeData || + (this.EnhancedSchemeData != null && + this.EnhancedSchemeData.Equals(input.EnhancedSchemeData)) + ) && ( this.IndustryUsage == input.IndustryUsage || this.IndustryUsage.Equals(input.IndustryUsage) @@ -237,6 +251,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ApplicationInfo.GetHashCode(); } + if (this.EnhancedSchemeData != null) + { + hashCode = (hashCode * 59) + this.EnhancedSchemeData.GetHashCode(); + } hashCode = (hashCode * 59) + this.IndustryUsage.GetHashCode(); if (this.LineItems != null) { diff --git a/Adyen/Model/Checkout/PaymentCancelRequest.cs b/Adyen/Model/Checkout/PaymentCancelRequest.cs index 3795b9a0f..f31c3bf0b 100644 --- a/Adyen/Model/Checkout/PaymentCancelRequest.cs +++ b/Adyen/Model/Checkout/PaymentCancelRequest.cs @@ -41,12 +41,14 @@ protected PaymentCancelRequest() { } /// Initializes a new instance of the class. /// /// applicationInfo. + /// enhancedSchemeData. /// The merchant account that is used to process the payment. (required). /// Your reference for the cancel request. Maximum length: 80 characters.. - public PaymentCancelRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), string merchantAccount = default(string), string reference = default(string)) + public PaymentCancelRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), string merchantAccount = default(string), string reference = default(string)) { this.MerchantAccount = merchantAccount; this.ApplicationInfo = applicationInfo; + this.EnhancedSchemeData = enhancedSchemeData; this.Reference = reference; } @@ -56,6 +58,12 @@ protected PaymentCancelRequest() { } [DataMember(Name = "applicationInfo", EmitDefaultValue = false)] public ApplicationInfo ApplicationInfo { get; set; } + /// + /// Gets or Sets EnhancedSchemeData + /// + [DataMember(Name = "enhancedSchemeData", EmitDefaultValue = false)] + public EnhancedSchemeData EnhancedSchemeData { get; set; } + /// /// The merchant account that is used to process the payment. /// @@ -79,6 +87,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(); sb.Append("class PaymentCancelRequest {\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" Reference: ").Append(Reference).Append("\n"); sb.Append("}\n"); @@ -121,6 +130,11 @@ public bool Equals(PaymentCancelRequest input) (this.ApplicationInfo != null && this.ApplicationInfo.Equals(input.ApplicationInfo)) ) && + ( + this.EnhancedSchemeData == input.EnhancedSchemeData || + (this.EnhancedSchemeData != null && + this.EnhancedSchemeData.Equals(input.EnhancedSchemeData)) + ) && ( this.MerchantAccount == input.MerchantAccount || (this.MerchantAccount != null && @@ -146,6 +160,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ApplicationInfo.GetHashCode(); } + if (this.EnhancedSchemeData != null) + { + hashCode = (hashCode * 59) + this.EnhancedSchemeData.GetHashCode(); + } if (this.MerchantAccount != null) { hashCode = (hashCode * 59) + this.MerchantAccount.GetHashCode(); diff --git a/Adyen/Model/Checkout/PaymentDetails.cs b/Adyen/Model/Checkout/PaymentDetails.cs index bbb87300a..cf6bec41d 100644 --- a/Adyen/Model/Checkout/PaymentDetails.cs +++ b/Adyen/Model/Checkout/PaymentDetails.cs @@ -285,281 +285,293 @@ public enum TypeEnum [EnumMember(Value = "molpay_fpx")] MolpayFpx = 41, + /// + /// Enum Payme for value: payme + /// + [EnumMember(Value = "payme")] + Payme = 42, + + /// + /// Enum PaymePos for value: payme_pos + /// + [EnumMember(Value = "payme_pos")] + PaymePos = 43, + /// /// Enum Konbini for value: konbini /// [EnumMember(Value = "konbini")] - Konbini = 42, + Konbini = 44, /// /// Enum DirectEbanking for value: directEbanking /// [EnumMember(Value = "directEbanking")] - DirectEbanking = 43, + DirectEbanking = 45, /// /// Enum Boletobancario for value: boletobancario /// [EnumMember(Value = "boletobancario")] - Boletobancario = 44, + Boletobancario = 46, /// /// Enum Neteller for value: neteller /// [EnumMember(Value = "neteller")] - Neteller = 45, + Neteller = 47, /// /// Enum Cashticket for value: cashticket /// [EnumMember(Value = "cashticket")] - Cashticket = 46, + Cashticket = 48, /// /// Enum Ikano for value: ikano /// [EnumMember(Value = "ikano")] - Ikano = 47, + Ikano = 49, /// /// Enum Karenmillen for value: karenmillen /// [EnumMember(Value = "karenmillen")] - Karenmillen = 48, + Karenmillen = 50, /// /// Enum Oasis for value: oasis /// [EnumMember(Value = "oasis")] - Oasis = 49, + Oasis = 51, /// /// Enum Warehouse for value: warehouse /// [EnumMember(Value = "warehouse")] - Warehouse = 50, + Warehouse = 52, /// /// Enum PrimeiropayBoleto for value: primeiropay_boleto /// [EnumMember(Value = "primeiropay_boleto")] - PrimeiropayBoleto = 51, + PrimeiropayBoleto = 53, /// /// Enum Mada for value: mada /// [EnumMember(Value = "mada")] - Mada = 52, + Mada = 54, /// /// Enum Benefit for value: benefit /// [EnumMember(Value = "benefit")] - Benefit = 53, + Benefit = 55, /// /// Enum Knet for value: knet /// [EnumMember(Value = "knet")] - Knet = 54, + Knet = 56, /// /// Enum Omannet for value: omannet /// [EnumMember(Value = "omannet")] - Omannet = 55, + Omannet = 57, /// /// Enum GopayWallet for value: gopay_wallet /// [EnumMember(Value = "gopay_wallet")] - GopayWallet = 56, + GopayWallet = 58, /// /// Enum KcpNaverpay for value: kcp_naverpay /// [EnumMember(Value = "kcp_naverpay")] - KcpNaverpay = 57, + KcpNaverpay = 59, /// /// Enum OnlinebankingIN for value: onlinebanking_IN /// [EnumMember(Value = "onlinebanking_IN")] - OnlinebankingIN = 58, + OnlinebankingIN = 60, /// /// Enum Fawry for value: fawry /// [EnumMember(Value = "fawry")] - Fawry = 59, + Fawry = 61, /// /// Enum Atome for value: atome /// [EnumMember(Value = "atome")] - Atome = 60, + Atome = 62, /// /// Enum Moneybookers for value: moneybookers /// [EnumMember(Value = "moneybookers")] - Moneybookers = 61, + Moneybookers = 63, /// /// Enum Naps for value: naps /// [EnumMember(Value = "naps")] - Naps = 62, + Naps = 64, /// /// Enum Nordea for value: nordea /// [EnumMember(Value = "nordea")] - Nordea = 63, + Nordea = 65, /// /// Enum BoletobancarioBradesco for value: boletobancario_bradesco /// [EnumMember(Value = "boletobancario_bradesco")] - BoletobancarioBradesco = 64, + BoletobancarioBradesco = 66, /// /// Enum BoletobancarioItau for value: boletobancario_itau /// [EnumMember(Value = "boletobancario_itau")] - BoletobancarioItau = 65, + BoletobancarioItau = 67, /// /// Enum BoletobancarioSantander for value: boletobancario_santander /// [EnumMember(Value = "boletobancario_santander")] - BoletobancarioSantander = 66, + BoletobancarioSantander = 68, /// /// Enum BoletobancarioBancodobrasil for value: boletobancario_bancodobrasil /// [EnumMember(Value = "boletobancario_bancodobrasil")] - BoletobancarioBancodobrasil = 67, + BoletobancarioBancodobrasil = 69, /// /// Enum BoletobancarioHsbc for value: boletobancario_hsbc /// [EnumMember(Value = "boletobancario_hsbc")] - BoletobancarioHsbc = 68, + BoletobancarioHsbc = 70, /// /// Enum MolpayMaybank2u for value: molpay_maybank2u /// [EnumMember(Value = "molpay_maybank2u")] - MolpayMaybank2u = 69, + MolpayMaybank2u = 71, /// /// Enum MolpayCimb for value: molpay_cimb /// [EnumMember(Value = "molpay_cimb")] - MolpayCimb = 70, + MolpayCimb = 72, /// /// Enum MolpayRhb for value: molpay_rhb /// [EnumMember(Value = "molpay_rhb")] - MolpayRhb = 71, + MolpayRhb = 73, /// /// Enum MolpayAmb for value: molpay_amb /// [EnumMember(Value = "molpay_amb")] - MolpayAmb = 72, + MolpayAmb = 74, /// /// Enum MolpayHlb for value: molpay_hlb /// [EnumMember(Value = "molpay_hlb")] - MolpayHlb = 73, + MolpayHlb = 75, /// /// Enum MolpayAffinEpg for value: molpay_affin_epg /// [EnumMember(Value = "molpay_affin_epg")] - MolpayAffinEpg = 74, + MolpayAffinEpg = 76, /// /// Enum MolpayBankislam for value: molpay_bankislam /// [EnumMember(Value = "molpay_bankislam")] - MolpayBankislam = 75, + MolpayBankislam = 77, /// /// Enum MolpayPublicbank for value: molpay_publicbank /// [EnumMember(Value = "molpay_publicbank")] - MolpayPublicbank = 76, + MolpayPublicbank = 78, /// /// Enum FpxAgrobank for value: fpx_agrobank /// [EnumMember(Value = "fpx_agrobank")] - FpxAgrobank = 77, + FpxAgrobank = 79, /// /// Enum Touchngo for value: touchngo /// [EnumMember(Value = "touchngo")] - Touchngo = 78, + Touchngo = 80, /// /// Enum Maybank2uMae for value: maybank2u_mae /// [EnumMember(Value = "maybank2u_mae")] - Maybank2uMae = 79, + Maybank2uMae = 81, /// /// Enum Duitnow for value: duitnow /// [EnumMember(Value = "duitnow")] - Duitnow = 80, + Duitnow = 82, /// /// Enum Promptpay for value: promptpay /// [EnumMember(Value = "promptpay")] - Promptpay = 81, + Promptpay = 83, /// /// Enum TwintPos for value: twint_pos /// [EnumMember(Value = "twint_pos")] - TwintPos = 82, + TwintPos = 84, /// /// Enum AlipayHk for value: alipay_hk /// [EnumMember(Value = "alipay_hk")] - AlipayHk = 83, + AlipayHk = 85, /// /// Enum AlipayHkWeb for value: alipay_hk_web /// [EnumMember(Value = "alipay_hk_web")] - AlipayHkWeb = 84, + AlipayHkWeb = 86, /// /// Enum AlipayHkWap for value: alipay_hk_wap /// [EnumMember(Value = "alipay_hk_wap")] - AlipayHkWap = 85, + AlipayHkWap = 87, /// /// Enum AlipayWap for value: alipay_wap /// [EnumMember(Value = "alipay_wap")] - AlipayWap = 86, + AlipayWap = 88, /// /// Enum Balanceplatform for value: balanceplatform /// [EnumMember(Value = "balanceplatform")] - Balanceplatform = 87 + Balanceplatform = 89 } diff --git a/Adyen/Model/Checkout/PaymentLinkRequest.cs b/Adyen/Model/Checkout/PaymentLinkRequest.cs index 2053acec1..b21f923cb 100644 --- a/Adyen/Model/Checkout/PaymentLinkRequest.cs +++ b/Adyen/Model/Checkout/PaymentLinkRequest.cs @@ -193,7 +193,7 @@ protected PaymentLinkRequest() { } /// An array of objects specifying how to split a payment when using [Adyen for Platforms](https://docs.adyen.com/platforms/process-payments#providing-split-information), [Classic Platforms integration](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information), or [Issuing](https://docs.adyen.com/issuing/manage-funds#split).. /// The physical store, for which this payment is processed.. /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area.. /// threeDS2RequestData. public PaymentLinkRequest(List allowedPaymentMethods = default(List), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), Address billingAddress = default(Address), List blockedPaymentMethods = default(List), int? captureDelayHours = default(int?), string countryCode = default(string), DateTime dateOfBirth = default(DateTime), DateTime deliverAt = default(DateTime), Address deliveryAddress = default(Address), string description = default(string), DateTime expiresAt = default(DateTime), FundOrigin fundOrigin = default(FundOrigin), FundRecipient fundRecipient = default(FundRecipient), Dictionary installmentOptions = default(Dictionary), List lineItems = default(List), bool? manualCapture = default(bool?), string mcc = default(string), string merchantAccount = default(string), string merchantOrderReference = default(string), Dictionary metadata = default(Dictionary), PlatformChargebackLogic platformChargebackLogic = default(PlatformChargebackLogic), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string reference = default(string), List requiredShopperFields = default(List), string returnUrl = default(string), bool? reusable = default(bool?), RiskData riskData = default(RiskData), string shopperEmail = default(string), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string shopperStatement = default(string), bool? showRemovePaymentMethodButton = true, string socialSecurityNumber = default(string), bool? splitCardFundingSources = false, List splits = default(List), string store = default(string), StorePaymentMethodModeEnum? storePaymentMethodMode = default(StorePaymentMethodModeEnum?), string telephoneNumber = default(string), string themeId = default(string), CheckoutSessionThreeDS2RequestData threeDS2RequestData = default(CheckoutSessionThreeDS2RequestData)) @@ -487,9 +487,9 @@ protected PaymentLinkRequest() { } public string Store { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } diff --git a/Adyen/Model/Checkout/PaymentLinkResponse.cs b/Adyen/Model/Checkout/PaymentLinkResponse.cs index ad21bf01e..6895075ad 100644 --- a/Adyen/Model/Checkout/PaymentLinkResponse.cs +++ b/Adyen/Model/Checkout/PaymentLinkResponse.cs @@ -240,7 +240,7 @@ protected PaymentLinkResponse() { } /// Status of the payment link. Possible values: * **active**: The link can be used to make payments. * **expired**: The expiry date for the payment link has passed. Shoppers can no longer use the link to make payments. * **completed**: The shopper completed the payment. * **paymentPending**: The shopper is in the process of making the payment. Applies to payment methods with an asynchronous flow. (required). /// The physical store, for which this payment is processed.. /// Indicates if the details of the payment method will be stored for the shopper. Possible values: * **disabled** – No details will be stored (default). * **askForConsent** – If the `shopperReference` is provided, the UI lets the shopper choose if they want their payment details to be stored. * **enabled** – If the `shopperReference` is provided, the details will be stored without asking the shopper for consent. When set to **askForConsent** or **enabled**, you must also include the `recurringProcessingModel` parameter.. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// A [theme](https://docs.adyen.com/unified-commerce/pay-by-link/payment-links/api#themes) to customize the appearance of the payment page. If not specified, the payment page is rendered according to the theme set as default in your Customer Area.. /// threeDS2RequestData. /// The date when the payment link status was updated. [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format: YYYY-MM-DDThh:mm:ss+TZD, for example, **2020-12-18T10:15:30+01:00**.. @@ -544,9 +544,9 @@ protected PaymentLinkResponse() { } public string Store { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } diff --git a/Adyen/Model/Checkout/PaymentMethod.cs b/Adyen/Model/Checkout/PaymentMethod.cs index 2e34268ad..14a47b70b 100644 --- a/Adyen/Model/Checkout/PaymentMethod.cs +++ b/Adyen/Model/Checkout/PaymentMethod.cs @@ -72,8 +72,9 @@ public enum FundingSourceEnum /// All input details to be provided to complete the payment with this payment method.. /// A list of issuers for this payment method.. /// The displayable name of this payment method.. + /// Indicates whether this payment method should be promoted or not.. /// The unique payment method code.. - public PaymentMethod(List apps = default(List), string brand = default(string), List brands = default(List), Dictionary configuration = default(Dictionary), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), PaymentMethodGroup group = default(PaymentMethodGroup), List inputDetails = default(List), List issuers = default(List), string name = default(string), string type = default(string)) + public PaymentMethod(List apps = default(List), string brand = default(string), List brands = default(List), Dictionary configuration = default(Dictionary), FundingSourceEnum? fundingSource = default(FundingSourceEnum?), PaymentMethodGroup group = default(PaymentMethodGroup), List inputDetails = default(List), List issuers = default(List), string name = default(string), bool? promoted = default(bool?), string type = default(string)) { this.Apps = apps; this.Brand = brand; @@ -84,6 +85,7 @@ public enum FundingSourceEnum this.InputDetails = inputDetails; this.Issuers = issuers; this.Name = name; + this.Promoted = promoted; this.Type = type; } @@ -143,6 +145,13 @@ public enum FundingSourceEnum [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } + /// + /// Indicates whether this payment method should be promoted or not. + /// + /// Indicates whether this payment method should be promoted or not. + [DataMember(Name = "promoted", EmitDefaultValue = false)] + public bool? Promoted { get; set; } + /// /// The unique payment method code. /// @@ -167,6 +176,7 @@ public override string ToString() sb.Append(" InputDetails: ").Append(InputDetails).Append("\n"); sb.Append(" Issuers: ").Append(Issuers).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Promoted: ").Append(Promoted).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -252,6 +262,10 @@ public bool Equals(PaymentMethod input) (this.Name != null && this.Name.Equals(input.Name)) ) && + ( + this.Promoted == input.Promoted || + this.Promoted.Equals(input.Promoted) + ) && ( this.Type == input.Type || (this.Type != null && @@ -301,6 +315,7 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } + hashCode = (hashCode * 59) + this.Promoted.GetHashCode(); if (this.Type != null) { hashCode = (hashCode * 59) + this.Type.GetHashCode(); diff --git a/Adyen/Model/Checkout/PaymentMethodsRequest.cs b/Adyen/Model/Checkout/PaymentMethodsRequest.cs index 5ea97d524..19f498a3a 100644 --- a/Adyen/Model/Checkout/PaymentMethodsRequest.cs +++ b/Adyen/Model/Checkout/PaymentMethodsRequest.cs @@ -112,32 +112,40 @@ protected PaymentMethodsRequest() { } /// List of payment methods to be presented to the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"allowedPaymentMethods\":[\"ideal\",\"applepay\"]`. /// amount. /// List of payment methods to be hidden from the shopper. To refer to payment methods, use their [payment method type](https://docs.adyen.com/payment-methods/payment-method-types). Example: `\"blockedPaymentMethods\":[\"ideal\",\"applepay\"]`. + /// browserInfo. /// The platform where a payment transaction takes place. This field can be used for filtering out payment methods that are only available on specific platforms. Possible values: * iOS * Android * Web. /// The shopper's country code.. /// The merchant account identifier, with which you want to process the transaction. (required). /// order. /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates.. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`.. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address.. /// Boolean value indicating whether the card payment method should be split into separate debit and credit options. (default to false). /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment.. /// Specifies how payment methods should be filtered based on the 'store' parameter: - 'exclusive': Only payment methods belonging to the specified 'store' are returned. - 'inclusive': Payment methods from the 'store' and those not associated with any other store are returned.. - public PaymentMethodsRequest(Dictionary additionalData = default(Dictionary), List allowedPaymentMethods = default(List), Amount amount = default(Amount), List blockedPaymentMethods = default(List), ChannelEnum? channel = default(ChannelEnum?), string countryCode = default(string), string merchantAccount = default(string), EncryptedOrderData order = default(EncryptedOrderData), string shopperConversionId = default(string), string shopperLocale = default(string), string shopperReference = default(string), bool? splitCardFundingSources = false, string store = default(string), StoreFiltrationModeEnum? storeFiltrationMode = default(StoreFiltrationModeEnum?)) + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. + public PaymentMethodsRequest(Dictionary additionalData = default(Dictionary), List allowedPaymentMethods = default(List), Amount amount = default(Amount), List blockedPaymentMethods = default(List), BrowserInfo browserInfo = default(BrowserInfo), ChannelEnum? channel = default(ChannelEnum?), string countryCode = default(string), string merchantAccount = default(string), EncryptedOrderData order = default(EncryptedOrderData), string shopperConversionId = default(string), string shopperEmail = default(string), string shopperIP = default(string), string shopperLocale = default(string), string shopperReference = default(string), bool? splitCardFundingSources = false, string store = default(string), StoreFiltrationModeEnum? storeFiltrationMode = default(StoreFiltrationModeEnum?), string telephoneNumber = default(string)) { this.MerchantAccount = merchantAccount; this.AdditionalData = additionalData; this.AllowedPaymentMethods = allowedPaymentMethods; this.Amount = amount; this.BlockedPaymentMethods = blockedPaymentMethods; + this.BrowserInfo = browserInfo; this.Channel = channel; this.CountryCode = countryCode; this.Order = order; this.ShopperConversionId = shopperConversionId; + this.ShopperEmail = shopperEmail; + this.ShopperIP = shopperIP; this.ShopperLocale = shopperLocale; this.ShopperReference = shopperReference; this.SplitCardFundingSources = splitCardFundingSources; this.Store = store; this.StoreFiltrationMode = storeFiltrationMode; + this.TelephoneNumber = telephoneNumber; } /// @@ -167,6 +175,12 @@ protected PaymentMethodsRequest() { } [DataMember(Name = "blockedPaymentMethods", EmitDefaultValue = false)] public List BlockedPaymentMethods { get; set; } + /// + /// Gets or Sets BrowserInfo + /// + [DataMember(Name = "browserInfo", EmitDefaultValue = false)] + public BrowserInfo BrowserInfo { get; set; } + /// /// The shopper's country code. /// @@ -194,6 +208,20 @@ protected PaymentMethodsRequest() { } [DataMember(Name = "shopperConversionId", EmitDefaultValue = false)] public string ShopperConversionId { get; set; } + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [DataMember(Name = "shopperEmail", EmitDefaultValue = false)] + public string ShopperEmail { get; set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [DataMember(Name = "shopperIP", EmitDefaultValue = false)] + public string ShopperIP { get; set; } + /// /// The combination of a language code and a country code to specify the language to be used in the payment. /// @@ -222,6 +250,13 @@ protected PaymentMethodsRequest() { } [DataMember(Name = "store", EmitDefaultValue = false)] public string Store { get; set; } + /// + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. + /// + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. + [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] + public string TelephoneNumber { get; set; } + /// /// Returns the string presentation of the object /// @@ -234,16 +269,20 @@ public override string ToString() sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); sb.Append(" Channel: ").Append(Channel).Append("\n"); sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" Order: ").Append(Order).Append("\n"); sb.Append(" ShopperConversionId: ").Append(ShopperConversionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); sb.Append(" SplitCardFundingSources: ").Append(SplitCardFundingSources).Append("\n"); sb.Append(" Store: ").Append(Store).Append("\n"); sb.Append(" StoreFiltrationMode: ").Append(StoreFiltrationMode).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -302,6 +341,11 @@ public bool Equals(PaymentMethodsRequest input) input.BlockedPaymentMethods != null && this.BlockedPaymentMethods.SequenceEqual(input.BlockedPaymentMethods) ) && + ( + this.BrowserInfo == input.BrowserInfo || + (this.BrowserInfo != null && + this.BrowserInfo.Equals(input.BrowserInfo)) + ) && ( this.Channel == input.Channel || this.Channel.Equals(input.Channel) @@ -326,6 +370,16 @@ public bool Equals(PaymentMethodsRequest input) (this.ShopperConversionId != null && this.ShopperConversionId.Equals(input.ShopperConversionId)) ) && + ( + this.ShopperEmail == input.ShopperEmail || + (this.ShopperEmail != null && + this.ShopperEmail.Equals(input.ShopperEmail)) + ) && + ( + this.ShopperIP == input.ShopperIP || + (this.ShopperIP != null && + this.ShopperIP.Equals(input.ShopperIP)) + ) && ( this.ShopperLocale == input.ShopperLocale || (this.ShopperLocale != null && @@ -348,6 +402,11 @@ public bool Equals(PaymentMethodsRequest input) ( this.StoreFiltrationMode == input.StoreFiltrationMode || this.StoreFiltrationMode.Equals(input.StoreFiltrationMode) + ) && + ( + this.TelephoneNumber == input.TelephoneNumber || + (this.TelephoneNumber != null && + this.TelephoneNumber.Equals(input.TelephoneNumber)) ); } @@ -376,6 +435,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.BlockedPaymentMethods.GetHashCode(); } + if (this.BrowserInfo != null) + { + hashCode = (hashCode * 59) + this.BrowserInfo.GetHashCode(); + } hashCode = (hashCode * 59) + this.Channel.GetHashCode(); if (this.CountryCode != null) { @@ -393,6 +456,14 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ShopperConversionId.GetHashCode(); } + if (this.ShopperEmail != null) + { + hashCode = (hashCode * 59) + this.ShopperEmail.GetHashCode(); + } + if (this.ShopperIP != null) + { + hashCode = (hashCode * 59) + this.ShopperIP.GetHashCode(); + } if (this.ShopperLocale != null) { hashCode = (hashCode * 59) + this.ShopperLocale.GetHashCode(); @@ -407,6 +478,10 @@ public override int GetHashCode() hashCode = (hashCode * 59) + this.Store.GetHashCode(); } hashCode = (hashCode * 59) + this.StoreFiltrationMode.GetHashCode(); + if (this.TelephoneNumber != null) + { + hashCode = (hashCode * 59) + this.TelephoneNumber.GetHashCode(); + } return hashCode; } } diff --git a/Adyen/Model/Checkout/PaymentRefundRequest.cs b/Adyen/Model/Checkout/PaymentRefundRequest.cs index 646667bb5..a5652d910 100644 --- a/Adyen/Model/Checkout/PaymentRefundRequest.cs +++ b/Adyen/Model/Checkout/PaymentRefundRequest.cs @@ -88,17 +88,21 @@ protected PaymentRefundRequest() { } /// /// amount (required). /// applicationInfo. + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_pspReference) of the specific capture to refund.. + /// enhancedSchemeData. /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip.. /// The merchant account that is used to process the payment. (required). /// The reason for the refund request. Possible values: * **FRAUD** * **CUSTOMER REQUEST** * **RETURN** * **DUPLICATE** * **OTHER** . /// Your reference for the refund request. Maximum length: 80 characters.. /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to process payments for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/online-payments/split-payments/).. /// The online store or [physical store](https://docs.adyen.com/point-of-sale/design-your-integration/determine-account-structure/#create-stores) that is processing the refund. This must be the same as the store name configured in your Customer Area. Otherwise, you get an error and the refund fails.. - public PaymentRefundRequest(Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), List lineItems = default(List), string merchantAccount = default(string), MerchantRefundReasonEnum? merchantRefundReason = default(MerchantRefundReasonEnum?), string reference = default(string), List splits = default(List), string store = default(string)) + public PaymentRefundRequest(Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), string capturePspReference = default(string), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), List lineItems = default(List), string merchantAccount = default(string), MerchantRefundReasonEnum? merchantRefundReason = default(MerchantRefundReasonEnum?), string reference = default(string), List splits = default(List), string store = default(string)) { this.Amount = amount; this.MerchantAccount = merchantAccount; this.ApplicationInfo = applicationInfo; + this.CapturePspReference = capturePspReference; + this.EnhancedSchemeData = enhancedSchemeData; this.LineItems = lineItems; this.MerchantRefundReason = merchantRefundReason; this.Reference = reference; @@ -118,6 +122,19 @@ protected PaymentRefundRequest() { } [DataMember(Name = "applicationInfo", EmitDefaultValue = false)] public ApplicationInfo ApplicationInfo { get; set; } + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_pspReference) of the specific capture to refund. + /// + /// This is only available for PayPal refunds. The [`pspReference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__resParam_pspReference) of the specific capture to refund. + [DataMember(Name = "capturePspReference", EmitDefaultValue = false)] + public string CapturePspReference { get; set; } + + /// + /// Gets or Sets EnhancedSchemeData + /// + [DataMember(Name = "enhancedSchemeData", EmitDefaultValue = false)] + public EnhancedSchemeData EnhancedSchemeData { get; set; } + /// /// Price and product information of the refunded items, required for [partial refunds](https://docs.adyen.com/online-payments/refund#refund-a-payment). > This field is required for partial refunds with 3x 4x Oney, Affirm, Afterpay, Atome, Clearpay, Klarna, Ratepay, Walley, and Zip. /// @@ -163,6 +180,8 @@ public override string ToString() sb.Append("class PaymentRefundRequest {\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" CapturePspReference: ").Append(CapturePspReference).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); sb.Append(" LineItems: ").Append(LineItems).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" MerchantRefundReason: ").Append(MerchantRefundReason).Append("\n"); @@ -214,6 +233,16 @@ public bool Equals(PaymentRefundRequest input) (this.ApplicationInfo != null && this.ApplicationInfo.Equals(input.ApplicationInfo)) ) && + ( + this.CapturePspReference == input.CapturePspReference || + (this.CapturePspReference != null && + this.CapturePspReference.Equals(input.CapturePspReference)) + ) && + ( + this.EnhancedSchemeData == input.EnhancedSchemeData || + (this.EnhancedSchemeData != null && + this.EnhancedSchemeData.Equals(input.EnhancedSchemeData)) + ) && ( this.LineItems == input.LineItems || this.LineItems != null && @@ -264,6 +293,14 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ApplicationInfo.GetHashCode(); } + if (this.CapturePspReference != null) + { + hashCode = (hashCode * 59) + this.CapturePspReference.GetHashCode(); + } + if (this.EnhancedSchemeData != null) + { + hashCode = (hashCode * 59) + this.EnhancedSchemeData.GetHashCode(); + } if (this.LineItems != null) { hashCode = (hashCode * 59) + this.LineItems.GetHashCode(); diff --git a/Adyen/Model/Checkout/PaymentRequest.cs b/Adyen/Model/Checkout/PaymentRequest.cs index 621c5c153..ddb2751e2 100644 --- a/Adyen/Model/Checkout/PaymentRequest.cs +++ b/Adyen/Model/Checkout/PaymentRequest.cs @@ -252,7 +252,7 @@ protected PaymentRequest() { } /// mpiData. /// order. /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead.. - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from.. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash.. /// paymentMethod (required). /// platformChargebackLogic. /// Date after which no further authorisations shall be performed. Only for 3D Secure 2.. @@ -261,12 +261,12 @@ protected PaymentRequest() { } /// Specifies the redirect method (GET or POST) when redirecting back from the issuer.. /// Specifies the redirect method (GET or POST) when redirecting to the issuer.. /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. (required). - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. (required). + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. (required). /// riskData. /// The date and time until when the session remains valid, in [ISO 8601](https://www.w3.org/TR/NOTE-datetime) format. For example: 2020-07-18T15:42:40.428+01:00. /// A unique ID that can be used to associate `/paymentMethods` and `/payments` requests with the same shopper transaction, offering insights into conversion rates.. - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations.. - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`.. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new).. /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal.. /// The combination of a language code and a country code to specify the language to be used in the payment.. /// shopperName. @@ -278,9 +278,9 @@ protected PaymentRequest() { } /// When true and `shopperReference` is provided, the payment details will be stored for future [recurring payments](https://docs.adyen.com/online-payments/tokenization/#recurring-payment-types).. /// This field contains additional information on the submerchant, who is onboarded to an acquirer through a payment facilitator or aggregator. /// surcharge. - /// The shopper's telephone number.. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication.. /// threeDS2RequestData. - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. (default to false). /// Set to true if the payment should be routed to a trusted MID.. public PaymentRequest(AccountInfo accountInfo = default(AccountInfo), Amount additionalAmount = default(Amount), Dictionary additionalData = default(Dictionary), Amount amount = default(Amount), ApplicationInfo applicationInfo = default(ApplicationInfo), AuthenticationData authenticationData = default(AuthenticationData), CheckoutBankAccount bankAccount = default(CheckoutBankAccount), BillingAddress billingAddress = default(BillingAddress), BrowserInfo browserInfo = default(BrowserInfo), int? captureDelayHours = default(int?), ChannelEnum? channel = default(ChannelEnum?), string checkoutAttemptId = default(string), Company company = default(Company), string conversionId = default(string), string countryCode = default(string), DateTime dateOfBirth = default(DateTime), ForexQuote dccQuote = default(ForexQuote), DateTime deliverAt = default(DateTime), DeliveryAddress deliveryAddress = default(DeliveryAddress), DateTime deliveryDate = default(DateTime), string deviceFingerprint = default(string), bool? enableOneClick = default(bool?), bool? enablePayOut = default(bool?), bool? enableRecurring = default(bool?), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), EntityTypeEnum? entityType = default(EntityTypeEnum?), int? fraudOffset = default(int?), FundOrigin fundOrigin = default(FundOrigin), FundRecipient fundRecipient = default(FundRecipient), IndustryUsageEnum? industryUsage = default(IndustryUsageEnum?), Installments installments = default(Installments), List lineItems = default(List), Dictionary localizedShopperStatement = default(Dictionary), Mandate mandate = default(Mandate), string mcc = default(string), string merchantAccount = default(string), string merchantOrderReference = default(string), MerchantRiskIndicator merchantRiskIndicator = default(MerchantRiskIndicator), Dictionary metadata = default(Dictionary), ThreeDSecureData mpiData = default(ThreeDSecureData), EncryptedOrderData order = default(EncryptedOrderData), string orderReference = default(string), string origin = default(string), CheckoutPaymentMethod paymentMethod = default(CheckoutPaymentMethod), PlatformChargebackLogic platformChargebackLogic = default(PlatformChargebackLogic), string recurringExpiry = default(string), string recurringFrequency = default(string), RecurringProcessingModelEnum? recurringProcessingModel = default(RecurringProcessingModelEnum?), string redirectFromIssuerMethod = default(string), string redirectToIssuerMethod = default(string), string reference = default(string), string returnUrl = default(string), RiskData riskData = default(RiskData), string sessionValidity = default(string), string shopperConversionId = default(string), string shopperEmail = default(string), string shopperIP = default(string), ShopperInteractionEnum? shopperInteraction = default(ShopperInteractionEnum?), string shopperLocale = default(string), Name shopperName = default(Name), string shopperReference = default(string), string shopperStatement = default(string), string socialSecurityNumber = default(string), List splits = default(List), string store = default(string), bool? storePaymentMethod = default(bool?), List subMerchants = default(List), Surcharge surcharge = default(Surcharge), string telephoneNumber = default(string), ThreeDS2RequestFields threeDS2RequestData = default(ThreeDS2RequestFields), bool? threeDSAuthenticationOnly = false, bool? trustedShopper = default(bool?)) { @@ -615,9 +615,9 @@ protected PaymentRequest() { } public string OrderReference { get; set; } /// - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. /// - /// Required for the 3D Secure 2 `channel` **Web** integration. Set this parameter to the origin URL of the page that you are loading the 3D Secure Component from. + /// > Required for browser-based (`channel` **Web**) 3D Secure 2 transactions.Set this to the origin URL of the page where you are rendering the Drop-in/Component. Do not include subdirectories and a trailing slash. [DataMember(Name = "origin", EmitDefaultValue = false)] public string Origin { get; set; } @@ -669,9 +669,9 @@ protected PaymentRequest() { } public string Reference { get; set; } /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. /// - /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.example.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. > The URL must not include personally identifiable information (PII), for example name or email address. + /// The URL to return to in case of a redirection. The format depends on the channel. * For web, include the protocol `http://` or `https://`. You can also include your own additional query parameters, for example, shopper ID or order reference number. Example: `https://your-company.com/checkout?shopperOrder=12xy` * For iOS, use the custom URL for your app. To know more about setting custom URL schemes, refer to the [Apple Developer documentation](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app). Example: `my-app://` * For Android, use a custom URL handled by an Activity on your app. You can configure it with an [intent filter](https://developer.android.com/guide/components/intents-filters). Example: `my-app://your.package.name` If the URL to return to includes non-ASCII characters, like spaces or special letters, URL encode the value. We strongly recommend that you use a maximum of 1024 characters. > The URL must not include personally identifiable information (PII), for example name or email address. [DataMember(Name = "returnUrl", IsRequired = false, EmitDefaultValue = false)] public string ReturnUrl { get; set; } @@ -696,16 +696,16 @@ protected PaymentRequest() { } public string ShopperConversionId { get; set; } /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. /// - /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > For 3D Secure 2 transactions, schemes require `shopperEmail` for all browser-based and mobile implementations. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. [DataMember(Name = "shopperEmail", EmitDefaultValue = false)] public string ShopperEmail { get; set; } /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). /// - /// The shopper's IP address. In general, we recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > For 3D Secure 2 transactions, schemes require `shopperIP` for all browser-based implementations. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks).> Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). [DataMember(Name = "shopperIP", EmitDefaultValue = false)] public string ShopperIP { get; set; } @@ -778,9 +778,9 @@ protected PaymentRequest() { } public Surcharge Surcharge { get; set; } /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. /// - /// The shopper's telephone number. + /// The shopper's telephone number. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we drop the value and do not submit it for authentication. [DataMember(Name = "telephoneNumber", EmitDefaultValue = false)] public string TelephoneNumber { get; set; } @@ -791,9 +791,9 @@ protected PaymentRequest() { } public ThreeDS2RequestFields ThreeDS2RequestData { get; set; } /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. /// - /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorisation.Default: **false**. [DataMember(Name = "threeDSAuthenticationOnly", EmitDefaultValue = false)] [Obsolete("Deprecated since Adyen Checkout API v69. Use `authenticationData.authenticationOnly` instead.")] public bool? ThreeDSAuthenticationOnly { get; set; } @@ -1573,6 +1573,12 @@ public override int GetHashCode() yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, length must be less than 80.", new [] { "Origin" }); } + // ReturnUrl (string) maxLength + if (this.ReturnUrl != null && this.ReturnUrl.Length > 8000) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ReturnUrl, length must be less than 8000.", new [] { "ReturnUrl" }); + } + // ShopperConversionId (string) maxLength if (this.ShopperConversionId != null && this.ShopperConversionId.Length > 256) { diff --git a/Adyen/Model/Checkout/PaymentReversalRequest.cs b/Adyen/Model/Checkout/PaymentReversalRequest.cs index d68e1eacd..7202748ad 100644 --- a/Adyen/Model/Checkout/PaymentReversalRequest.cs +++ b/Adyen/Model/Checkout/PaymentReversalRequest.cs @@ -41,12 +41,14 @@ protected PaymentReversalRequest() { } /// Initializes a new instance of the class. /// /// applicationInfo. + /// enhancedSchemeData. /// The merchant account that is used to process the payment. (required). /// Your reference for the reversal request. Maximum length: 80 characters.. - public PaymentReversalRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), string merchantAccount = default(string), string reference = default(string)) + public PaymentReversalRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), string merchantAccount = default(string), string reference = default(string)) { this.MerchantAccount = merchantAccount; this.ApplicationInfo = applicationInfo; + this.EnhancedSchemeData = enhancedSchemeData; this.Reference = reference; } @@ -56,6 +58,12 @@ protected PaymentReversalRequest() { } [DataMember(Name = "applicationInfo", EmitDefaultValue = false)] public ApplicationInfo ApplicationInfo { get; set; } + /// + /// Gets or Sets EnhancedSchemeData + /// + [DataMember(Name = "enhancedSchemeData", EmitDefaultValue = false)] + public EnhancedSchemeData EnhancedSchemeData { get; set; } + /// /// The merchant account that is used to process the payment. /// @@ -79,6 +87,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(); sb.Append("class PaymentReversalRequest {\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" Reference: ").Append(Reference).Append("\n"); sb.Append("}\n"); @@ -121,6 +130,11 @@ public bool Equals(PaymentReversalRequest input) (this.ApplicationInfo != null && this.ApplicationInfo.Equals(input.ApplicationInfo)) ) && + ( + this.EnhancedSchemeData == input.EnhancedSchemeData || + (this.EnhancedSchemeData != null && + this.EnhancedSchemeData.Equals(input.EnhancedSchemeData)) + ) && ( this.MerchantAccount == input.MerchantAccount || (this.MerchantAccount != null && @@ -146,6 +160,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ApplicationInfo.GetHashCode(); } + if (this.EnhancedSchemeData != null) + { + hashCode = (hashCode * 59) + this.EnhancedSchemeData.GetHashCode(); + } if (this.MerchantAccount != null) { hashCode = (hashCode * 59) + this.MerchantAccount.GetHashCode(); diff --git a/Adyen/Model/Checkout/PixRecurring.cs b/Adyen/Model/Checkout/PixRecurring.cs index 6eca2f8c8..fd084618e 100644 --- a/Adyen/Model/Checkout/PixRecurring.cs +++ b/Adyen/Model/Checkout/PixRecurring.cs @@ -82,6 +82,7 @@ public enum FrequencyEnum /// Initializes a new instance of the class. /// /// The date on which the shopper's payment method will be charged, in YYYY-MM-DD format.. + /// Flag used to define whether liquidation can happen only on business days. /// End date of the billing plan, in YYYY-MM-DD format. The end date must align with the frequency and the start date of the billing plan. If left blank, the subscription will continue indefinitely unless it is cancelled by the shopper.. /// The frequency at which the shopper will be charged.. /// minAmount. @@ -90,9 +91,10 @@ public enum FrequencyEnum /// The text that that will be shown on the shopper's bank statement for the recurring payments. We recommend to add a descriptive text about the subscription to let your shoppers recognize your recurring payments. Maximum length: 35 characters.. /// When set to true, you can retry for failed recurring payments. The default value is true.. /// Start date of the billing plan, in YYYY-MM-DD format. The default value is the transaction date.. - public PixRecurring(string billingDate = default(string), string endsAt = default(string), FrequencyEnum? frequency = default(FrequencyEnum?), Amount minAmount = default(Amount), string originalPspReference = default(string), Amount recurringAmount = default(Amount), string recurringStatement = default(string), bool? retryPolicy = default(bool?), string startsAt = default(string)) + public PixRecurring(string billingDate = default(string), bool? businessDayOnly = default(bool?), string endsAt = default(string), FrequencyEnum? frequency = default(FrequencyEnum?), Amount minAmount = default(Amount), string originalPspReference = default(string), Amount recurringAmount = default(Amount), string recurringStatement = default(string), bool? retryPolicy = default(bool?), string startsAt = default(string)) { this.BillingDate = billingDate; + this.BusinessDayOnly = businessDayOnly; this.EndsAt = endsAt; this.Frequency = frequency; this.MinAmount = minAmount; @@ -110,6 +112,13 @@ public enum FrequencyEnum [DataMember(Name = "billingDate", EmitDefaultValue = false)] public string BillingDate { get; set; } + /// + /// Flag used to define whether liquidation can happen only on business days + /// + /// Flag used to define whether liquidation can happen only on business days + [DataMember(Name = "businessDayOnly", EmitDefaultValue = false)] + public bool? BusinessDayOnly { get; set; } + /// /// End date of the billing plan, in YYYY-MM-DD format. The end date must align with the frequency and the start date of the billing plan. If left blank, the subscription will continue indefinitely unless it is cancelled by the shopper. /// @@ -166,6 +175,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(); sb.Append("class PixRecurring {\n"); sb.Append(" BillingDate: ").Append(BillingDate).Append("\n"); + sb.Append(" BusinessDayOnly: ").Append(BusinessDayOnly).Append("\n"); sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); sb.Append(" Frequency: ").Append(Frequency).Append("\n"); sb.Append(" MinAmount: ").Append(MinAmount).Append("\n"); @@ -214,6 +224,10 @@ public bool Equals(PixRecurring input) (this.BillingDate != null && this.BillingDate.Equals(input.BillingDate)) ) && + ( + this.BusinessDayOnly == input.BusinessDayOnly || + this.BusinessDayOnly.Equals(input.BusinessDayOnly) + ) && ( this.EndsAt == input.EndsAt || (this.EndsAt != null && @@ -267,6 +281,7 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.BillingDate.GetHashCode(); } + hashCode = (hashCode * 59) + this.BusinessDayOnly.GetHashCode(); if (this.EndsAt != null) { hashCode = (hashCode * 59) + this.EndsAt.GetHashCode(); diff --git a/Adyen/Model/Checkout/ResponseAdditionalDataCommon.cs b/Adyen/Model/Checkout/ResponseAdditionalDataCommon.cs index 952bfb504..914418d3a 100644 --- a/Adyen/Model/Checkout/ResponseAdditionalDataCommon.cs +++ b/Adyen/Model/Checkout/ResponseAdditionalDataCommon.cs @@ -61,9 +61,9 @@ public enum FraudResultTypeEnum [DataMember(Name = "fraudResultType", EmitDefaultValue = false)] public FraudResultTypeEnum? FraudResultType { get; set; } /// - /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are:\\n* veryLow\\n* low\\n* medium\\n* high\\n* veryHigh\\n\\n> + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh /// - /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are:\\n* veryLow\\n* low\\n* medium\\n* high\\n* veryHigh\\n\\n> + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh [JsonConverter(typeof(StringEnumConverter))] public enum FraudRiskLevelEnum { @@ -101,9 +101,9 @@ public enum FraudRiskLevelEnum /// - /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are:\\n* veryLow\\n* low\\n* medium\\n* high\\n* veryHigh\\n\\n> + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh /// - /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are:\\n* veryLow\\n* low\\n* medium\\n* high\\n* veryHigh\\n\\n> + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh [DataMember(Name = "fraudRiskLevel", EmitDefaultValue = false)] public FraudRiskLevelEnum? FraudRiskLevel { get; set; } /// @@ -200,7 +200,7 @@ public enum TokenizationStoreOperationTypeEnum /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair.. /// Indicates if the payment is sent to manual review.. /// The fraud result properties of the payment.. - /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are:\\n* veryLow\\n* low\\n* medium\\n* high\\n* veryHigh\\n\\n>. + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh . /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**.. /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\".. /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card. diff --git a/Adyen/Model/Checkout/RivertyDetails.cs b/Adyen/Model/Checkout/RivertyDetails.cs index dc6f32dfe..7b43f55cf 100644 --- a/Adyen/Model/Checkout/RivertyDetails.cs +++ b/Adyen/Model/Checkout/RivertyDetails.cs @@ -82,8 +82,9 @@ protected RivertyDetails() { } /// Shopper name, date of birth, phone number, and email address.. /// This is the `recurringDetailReference` returned in the response when you created the token.. /// This is the `recurringDetailReference` returned in the response when you created the token.. + /// The payment method subtype.. /// **riverty** (required) (default to TypeEnum.Riverty). - public RivertyDetails(string billingAddress = default(string), string checkoutAttemptId = default(string), string deliveryAddress = default(string), string deviceFingerprint = default(string), string iban = default(string), string personalDetails = default(string), string recurringDetailReference = default(string), string storedPaymentMethodId = default(string), TypeEnum type = TypeEnum.Riverty) + public RivertyDetails(string billingAddress = default(string), string checkoutAttemptId = default(string), string deliveryAddress = default(string), string deviceFingerprint = default(string), string iban = default(string), string personalDetails = default(string), string recurringDetailReference = default(string), string storedPaymentMethodId = default(string), string subtype = default(string), TypeEnum type = TypeEnum.Riverty) { this.Type = type; this.BillingAddress = billingAddress; @@ -94,6 +95,7 @@ protected RivertyDetails() { } this.PersonalDetails = personalDetails; this.RecurringDetailReference = recurringDetailReference; this.StoredPaymentMethodId = storedPaymentMethodId; + this.Subtype = subtype; } /// @@ -153,6 +155,13 @@ protected RivertyDetails() { } [DataMember(Name = "storedPaymentMethodId", EmitDefaultValue = false)] public string StoredPaymentMethodId { get; set; } + /// + /// The payment method subtype. + /// + /// The payment method subtype. + [DataMember(Name = "subtype", EmitDefaultValue = false)] + public string Subtype { get; set; } + /// /// Returns the string presentation of the object /// @@ -169,6 +178,7 @@ public override string ToString() sb.Append(" PersonalDetails: ").Append(PersonalDetails).Append("\n"); sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Subtype: ").Append(Subtype).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -245,6 +255,11 @@ public bool Equals(RivertyDetails input) (this.StoredPaymentMethodId != null && this.StoredPaymentMethodId.Equals(input.StoredPaymentMethodId)) ) && + ( + this.Subtype == input.Subtype || + (this.Subtype != null && + this.Subtype.Equals(input.Subtype)) + ) && ( this.Type == input.Type || this.Type.Equals(input.Type) @@ -292,6 +307,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.StoredPaymentMethodId.GetHashCode(); } + if (this.Subtype != null) + { + hashCode = (hashCode * 59) + this.Subtype.GetHashCode(); + } hashCode = (hashCode * 59) + this.Type.GetHashCode(); return hashCode; } diff --git a/Adyen/Model/Checkout/SessionResultResponse.cs b/Adyen/Model/Checkout/SessionResultResponse.cs index d93c1199b..60a5fe465 100644 --- a/Adyen/Model/Checkout/SessionResultResponse.cs +++ b/Adyen/Model/Checkout/SessionResultResponse.cs @@ -87,14 +87,27 @@ public enum StatusEnum /// /// Initializes a new instance of the class. /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**.. /// A unique identifier of the session.. + /// A list of all authorised payments done for this session.. + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status.. /// The status of the session. The status included in the response doesn't get updated. Don't make the request again to check for payment status updates. Possible values: * **completed**: the shopper completed the payment, and the payment was authorized. * **paymentPending**: the shopper is in the process of making the payment. This applies to payment methods with an asynchronous flow, like voucher payments where the shopper completes the payment in a physical shop. * **refused**: the session has been refused, because of too many refused payment attempts. The shopper can no longer complete the payment with this session. * **canceled**: the shopper canceled the payment. * **expired**: the session expired. The shopper can no longer complete the payment with this session. By default, the session expires one hour after it is created.. - public SessionResultResponse(string id = default(string), StatusEnum? status = default(StatusEnum?)) + public SessionResultResponse(Dictionary additionalData = default(Dictionary), string id = default(string), List payments = default(List), string reference = default(string), StatusEnum? status = default(StatusEnum?)) { + this.AdditionalData = additionalData; this.Id = id; + this.Payments = payments; + this.Reference = reference; this.Status = status; } + /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some fields are included only if you enable them. To enable these fields in your Customer Area, go to **Developers** > **Additional data**. + [DataMember(Name = "additionalData", EmitDefaultValue = false)] + public Dictionary AdditionalData { get; set; } + /// /// A unique identifier of the session. /// @@ -102,6 +115,20 @@ public enum StatusEnum [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } + /// + /// A list of all authorised payments done for this session. + /// + /// A list of all authorised payments done for this session. + [DataMember(Name = "payments", EmitDefaultValue = false)] + public List Payments { get; set; } + + /// + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status. + /// + /// The unique reference that you provided in the original `/sessions` request. This identifies the payment and is used in all communication with you about the payment status. + [DataMember(Name = "reference", EmitDefaultValue = false)] + public string Reference { get; set; } + /// /// Returns the string presentation of the object /// @@ -110,7 +137,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class SessionResultResponse {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Payments: ").Append(Payments).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -147,11 +177,28 @@ public bool Equals(SessionResultResponse input) return false; } return + ( + this.AdditionalData == input.AdditionalData || + this.AdditionalData != null && + input.AdditionalData != null && + this.AdditionalData.SequenceEqual(input.AdditionalData) + ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && + ( + this.Payments == input.Payments || + this.Payments != null && + input.Payments != null && + this.Payments.SequenceEqual(input.Payments) + ) && + ( + this.Reference == input.Reference || + (this.Reference != null && + this.Reference.Equals(input.Reference)) + ) && ( this.Status == input.Status || this.Status.Equals(input.Status) @@ -167,10 +214,22 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; + if (this.AdditionalData != null) + { + hashCode = (hashCode * 59) + this.AdditionalData.GetHashCode(); + } if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); } + if (this.Payments != null) + { + hashCode = (hashCode * 59) + this.Payments.GetHashCode(); + } + if (this.Reference != null) + { + hashCode = (hashCode * 59) + this.Reference.GetHashCode(); + } hashCode = (hashCode * 59) + this.Status.GetHashCode(); return hashCode; } diff --git a/Adyen/Model/Checkout/StandalonePaymentCancelRequest.cs b/Adyen/Model/Checkout/StandalonePaymentCancelRequest.cs index 941dadf40..0f75335d7 100644 --- a/Adyen/Model/Checkout/StandalonePaymentCancelRequest.cs +++ b/Adyen/Model/Checkout/StandalonePaymentCancelRequest.cs @@ -41,14 +41,16 @@ protected StandalonePaymentCancelRequest() { } /// Initializes a new instance of the class. /// /// applicationInfo. + /// enhancedSchemeData. /// The merchant account that is used to process the payment. (required). /// The [`reference`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/payments__reqParam_reference) of the payment that you want to cancel. (required). /// Your reference for the cancel request. Maximum length: 80 characters.. - public StandalonePaymentCancelRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), string merchantAccount = default(string), string paymentReference = default(string), string reference = default(string)) + public StandalonePaymentCancelRequest(ApplicationInfo applicationInfo = default(ApplicationInfo), EnhancedSchemeData enhancedSchemeData = default(EnhancedSchemeData), string merchantAccount = default(string), string paymentReference = default(string), string reference = default(string)) { this.MerchantAccount = merchantAccount; this.PaymentReference = paymentReference; this.ApplicationInfo = applicationInfo; + this.EnhancedSchemeData = enhancedSchemeData; this.Reference = reference; } @@ -58,6 +60,12 @@ protected StandalonePaymentCancelRequest() { } [DataMember(Name = "applicationInfo", EmitDefaultValue = false)] public ApplicationInfo ApplicationInfo { get; set; } + /// + /// Gets or Sets EnhancedSchemeData + /// + [DataMember(Name = "enhancedSchemeData", EmitDefaultValue = false)] + public EnhancedSchemeData EnhancedSchemeData { get; set; } + /// /// The merchant account that is used to process the payment. /// @@ -88,6 +96,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(); sb.Append("class StandalonePaymentCancelRequest {\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" EnhancedSchemeData: ").Append(EnhancedSchemeData).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" PaymentReference: ").Append(PaymentReference).Append("\n"); sb.Append(" Reference: ").Append(Reference).Append("\n"); @@ -131,6 +140,11 @@ public bool Equals(StandalonePaymentCancelRequest input) (this.ApplicationInfo != null && this.ApplicationInfo.Equals(input.ApplicationInfo)) ) && + ( + this.EnhancedSchemeData == input.EnhancedSchemeData || + (this.EnhancedSchemeData != null && + this.EnhancedSchemeData.Equals(input.EnhancedSchemeData)) + ) && ( this.MerchantAccount == input.MerchantAccount || (this.MerchantAccount != null && @@ -161,6 +175,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ApplicationInfo.GetHashCode(); } + if (this.EnhancedSchemeData != null) + { + hashCode = (hashCode * 59) + this.EnhancedSchemeData.GetHashCode(); + } if (this.MerchantAccount != null) { hashCode = (hashCode * 59) + this.MerchantAccount.GetHashCode(); diff --git a/Adyen/Model/Checkout/SubMerchantInfo.cs b/Adyen/Model/Checkout/SubMerchantInfo.cs index 0aadcc313..b6faa1053 100644 --- a/Adyen/Model/Checkout/SubMerchantInfo.cs +++ b/Adyen/Model/Checkout/SubMerchantInfo.cs @@ -40,7 +40,7 @@ public partial class SubMerchantInfo : IEquatable, IValidatable /// Required for transactions performed by registered payment facilitators. The email associated with the sub-merchant's account.. /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters. /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits. - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters. + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters. /// Required for transactions performed by registered payment facilitators. The phone number associated with the sub-merchant's account.. /// registeredSince. /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ. @@ -93,9 +93,9 @@ public partial class SubMerchantInfo : IEquatable, IValidatable public string Mcc { get; set; } /// - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters /// - /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } diff --git a/Adyen/Model/Checkout/ThreeDS2RequestData.cs b/Adyen/Model/Checkout/ThreeDS2RequestData.cs index e277b3180..97da42098 100644 --- a/Adyen/Model/Checkout/ThreeDS2RequestData.cs +++ b/Adyen/Model/Checkout/ThreeDS2RequestData.cs @@ -67,9 +67,9 @@ public enum AcctTypeEnum [DataMember(Name = "acctType", EmitDefaultValue = false)] public AcctTypeEnum? AcctType { get; set; } /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. [JsonConverter(typeof(StringEnumConverter))] public enum AddrMatchEnum { @@ -89,9 +89,9 @@ public enum AddrMatchEnum /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. [DataMember(Name = "addrMatch", EmitDefaultValue = false)] public AddrMatchEnum? AddrMatch { get; set; } /// @@ -291,7 +291,7 @@ protected ThreeDS2RequestData() { } /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit. /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform.. /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform.. - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address.. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address.. /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` . /// The environment of the shopper. Allowed values: * `app` * `browser` (required). diff --git a/Adyen/Model/Checkout/ThreeDS2RequestFields.cs b/Adyen/Model/Checkout/ThreeDS2RequestFields.cs index c2fce35b6..f53902a61 100644 --- a/Adyen/Model/Checkout/ThreeDS2RequestFields.cs +++ b/Adyen/Model/Checkout/ThreeDS2RequestFields.cs @@ -67,9 +67,9 @@ public enum AcctTypeEnum [DataMember(Name = "acctType", EmitDefaultValue = false)] public AcctTypeEnum? AcctType { get; set; } /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. [JsonConverter(typeof(StringEnumConverter))] public enum AddrMatchEnum { @@ -89,9 +89,9 @@ public enum AddrMatchEnum /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. /// - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address. [DataMember(Name = "addrMatch", EmitDefaultValue = false)] public AddrMatchEnum? AddrMatch { get; set; } /// @@ -286,7 +286,7 @@ public enum TransactionTypeEnum /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit. /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform.. /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform.. - /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address.. + /// Indicates whether the cardholder shipping Address and cardholder billing address are the same. Allowed values: * **Y** — Shipping Address matches Billing Address. * **N** — Shipping Address does not match Billing Address.. /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false). /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` . /// deviceRenderOptions. diff --git a/Adyen/Model/Checkout/ThreeDSRequestData.cs b/Adyen/Model/Checkout/ThreeDSRequestData.cs index da6917c30..4b5d418bb 100644 --- a/Adyen/Model/Checkout/ThreeDSRequestData.cs +++ b/Adyen/Model/Checkout/ThreeDSRequestData.cs @@ -79,9 +79,9 @@ public enum ChallengeWindowSizeEnum [DataMember(Name = "challengeWindowSize", EmitDefaultValue = false)] public ChallengeWindowSizeEnum? ChallengeWindowSize { get; set; } /// - /// Flag for data only flow. + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. /// - /// Flag for data only flow. + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. [JsonConverter(typeof(StringEnumConverter))] public enum DataOnlyEnum { @@ -101,15 +101,15 @@ public enum DataOnlyEnum /// - /// Flag for data only flow. + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. /// - /// Flag for data only flow. + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. [DataMember(Name = "dataOnly", EmitDefaultValue = false)] public DataOnlyEnum? DataOnly { get; set; } /// - /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be used when available. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Only use the redirect 3D Secure authentication flow. + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. /// - /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be used when available. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Only use the redirect 3D Secure authentication flow. + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. [JsonConverter(typeof(StringEnumConverter))] public enum NativeThreeDSEnum { @@ -129,9 +129,9 @@ public enum NativeThreeDSEnum /// - /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be used when available. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Only use the redirect 3D Secure authentication flow. + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. /// - /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be used when available. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Only use the redirect 3D Secure authentication flow. + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow. [DataMember(Name = "nativeThreeDS", EmitDefaultValue = false)] public NativeThreeDSEnum? NativeThreeDS { get; set; } /// @@ -166,8 +166,8 @@ public enum ThreeDSVersionEnum /// Initializes a new instance of the class. /// /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen. - /// Flag for data only flow.. - /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be used when available. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Only use the redirect 3D Secure authentication flow.. + /// Required to trigger the [data-only flow](https://docs.adyen.com/online-payments/3d-secure/data-only/). When set to **true**, forces the 3D Secure 2 data-only flow for all transactions where it is possible. . + /// Indicates if [native 3D Secure authentication](https://docs.adyen.com/online-payments/3d-secure/native-3ds2) should be triggered when available. Adyen can still select to fallback to the redirect flow to optimize authorization rates and improve the shopper's experience. Possible values: * **preferred**: Use native 3D Secure authentication when available. * **disabled**: Use the redirect 3D Secure authentication flow.. /// The version of 3D Secure to use. Possible values: * **2.1.0** * **2.2.0**. public ThreeDSRequestData(ChallengeWindowSizeEnum? challengeWindowSize = default(ChallengeWindowSizeEnum?), DataOnlyEnum? dataOnly = default(DataOnlyEnum?), NativeThreeDSEnum? nativeThreeDS = default(NativeThreeDSEnum?), ThreeDSVersionEnum? threeDSVersion = default(ThreeDSVersionEnum?)) { diff --git a/Adyen/Model/ConfigurationWebhooks/Card.cs b/Adyen/Model/ConfigurationWebhooks/Card.cs index 3e1d4f563..4bcabca25 100644 --- a/Adyen/Model/ConfigurationWebhooks/Card.cs +++ b/Adyen/Model/ConfigurationWebhooks/Card.cs @@ -86,7 +86,7 @@ protected Card() { } /// The form factor of the card. Possible values: **virtual**, **physical**. (required). /// Last last four digits of the card number.. /// The primary account number (PAN) of the card. > The PAN is masked by default and returned only for single-use virtual cards. (required). - /// Allocates a specific product range for either a physical or a virtual card. Possible values: **fullySupported**, **secureCorporate**. >Reach out to your Adyen contact to get the values relevant for your integration.. + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration.. public Card(Authentication authentication = default(Authentication), string bin = default(string), string brand = default(string), string brandVariant = default(string), string cardholderName = default(string), CardConfiguration configuration = default(CardConfiguration), string cvc = default(string), DeliveryContact deliveryContact = default(DeliveryContact), Expiry expiration = default(Expiry), FormFactorEnum formFactor = default(FormFactorEnum), string lastFour = default(string), string number = default(string), string threeDSecure = default(string)) { this.Brand = brand; @@ -178,9 +178,9 @@ protected Card() { } public string Number { get; set; } /// - /// Allocates a specific product range for either a physical or a virtual card. Possible values: **fullySupported**, **secureCorporate**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. /// - /// Allocates a specific product range for either a physical or a virtual card. Possible values: **fullySupported**, **secureCorporate**. >Reach out to your Adyen contact to get the values relevant for your integration. + /// The 3DS configuration of the physical or the virtual card. Possible values: **fullySupported**, **secureCorporate**. > Reach out to your Adyen contact to get the values relevant for your integration. [DataMember(Name = "threeDSecure", EmitDefaultValue = false)] public string ThreeDSecure { get; set; } diff --git a/Adyen/Model/ConfigurationWebhooks/Device.cs b/Adyen/Model/ConfigurationWebhooks/Device.cs new file mode 100644 index 000000000..57051897d --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/Device.cs @@ -0,0 +1,148 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// Device + /// + [DataContract(Name = "Device")] + public partial class Device : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc. + /// The operating system of the device used for provisioning the network token.. + public Device(string formFactor = default(string), string osName = default(string)) + { + this.FormFactor = formFactor; + this.OsName = osName; + } + + /// + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc + /// + /// The type of the device used for provisioning the network token. For example, **phone**, **mobile_phone**, **watch**, **mobilephone_or_tablet**, etc + [DataMember(Name = "formFactor", EmitDefaultValue = false)] + public string FormFactor { get; set; } + + /// + /// The operating system of the device used for provisioning the network token. + /// + /// The operating system of the device used for provisioning the network token. + [DataMember(Name = "osName", EmitDefaultValue = false)] + public string OsName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Device {\n"); + sb.Append(" FormFactor: ").Append(FormFactor).Append("\n"); + sb.Append(" OsName: ").Append(OsName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Device); + } + + /// + /// Returns true if Device instances are equal + /// + /// Instance of Device to be compared + /// Boolean + public bool Equals(Device input) + { + if (input == null) + { + return false; + } + return + ( + this.FormFactor == input.FormFactor || + (this.FormFactor != null && + this.FormFactor.Equals(input.FormFactor)) + ) && + ( + this.OsName == input.OsName || + (this.OsName != null && + this.OsName.Equals(input.OsName)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.FormFactor != null) + { + hashCode = (hashCode * 59) + this.FormFactor.GetHashCode(); + } + if (this.OsName != null) + { + hashCode = (hashCode * 59) + this.OsName.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationDataV2.cs b/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationDataV2.cs new file mode 100644 index 000000000..48eed65c6 --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationDataV2.cs @@ -0,0 +1,332 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// NetworkTokenNotificationDataV2 + /// + [DataContract(Name = "NetworkTokenNotificationDataV2")] + public partial class NetworkTokenNotificationDataV2 : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// authentication. + /// Specifies whether the authentication process was triggered during token provisioning.. + /// The unique identifier of the balance platform.. + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**.. + /// The unique identifier of the network token.. + /// The unique identifier of the payment instrument to which the network token is associated.. + /// The status of the network token.. + /// The last four digits of the network token. Use this value to help your user to identify their network token.. + /// tokenRequestor. + /// The type of network token.. + /// The rules used to validate the request for provisioning the network token.. + /// wallet. + public NetworkTokenNotificationDataV2(TokenAuthentication authentication = default(TokenAuthentication), bool? authenticationApplied = default(bool?), string balancePlatform = default(string), string decision = default(string), string id = default(string), string paymentInstrumentId = default(string), string status = default(string), string tokenLastFour = default(string), NetworkTokenRequestor tokenRequestor = default(NetworkTokenRequestor), string type = default(string), List validationFacts = default(List), Wallet wallet = default(Wallet)) + { + this.Authentication = authentication; + this.AuthenticationApplied = authenticationApplied; + this.BalancePlatform = balancePlatform; + this.Decision = decision; + this.Id = id; + this.PaymentInstrumentId = paymentInstrumentId; + this.Status = status; + this.TokenLastFour = tokenLastFour; + this.TokenRequestor = tokenRequestor; + this.Type = type; + this.ValidationFacts = validationFacts; + this.Wallet = wallet; + } + + /// + /// Gets or Sets Authentication + /// + [DataMember(Name = "authentication", EmitDefaultValue = false)] + public TokenAuthentication Authentication { get; set; } + + /// + /// Specifies whether the authentication process was triggered during token provisioning. + /// + /// Specifies whether the authentication process was triggered during token provisioning. + [DataMember(Name = "authenticationApplied", EmitDefaultValue = false)] + public bool? AuthenticationApplied { get; set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [DataMember(Name = "balancePlatform", EmitDefaultValue = false)] + public string BalancePlatform { get; set; } + + /// + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**. + /// + /// The decision about the network token provisioning. Possible values: **approved**, **declined**, **requiresAuthentication**. + [DataMember(Name = "decision", EmitDefaultValue = false)] + public string Decision { get; set; } + + /// + /// The unique identifier of the network token. + /// + /// The unique identifier of the network token. + [DataMember(Name = "id", EmitDefaultValue = false)] + public string Id { get; set; } + + /// + /// The unique identifier of the payment instrument to which the network token is associated. + /// + /// The unique identifier of the payment instrument to which the network token is associated. + [DataMember(Name = "paymentInstrumentId", EmitDefaultValue = false)] + public string PaymentInstrumentId { get; set; } + + /// + /// The status of the network token. + /// + /// The status of the network token. + [DataMember(Name = "status", EmitDefaultValue = false)] + public string Status { get; set; } + + /// + /// The last four digits of the network token. Use this value to help your user to identify their network token. + /// + /// The last four digits of the network token. Use this value to help your user to identify their network token. + [DataMember(Name = "tokenLastFour", EmitDefaultValue = false)] + public string TokenLastFour { get; set; } + + /// + /// Gets or Sets TokenRequestor + /// + [DataMember(Name = "tokenRequestor", EmitDefaultValue = false)] + public NetworkTokenRequestor TokenRequestor { get; set; } + + /// + /// The type of network token. + /// + /// The type of network token. + [DataMember(Name = "type", EmitDefaultValue = false)] + public string Type { get; set; } + + /// + /// The rules used to validate the request for provisioning the network token. + /// + /// The rules used to validate the request for provisioning the network token. + [DataMember(Name = "validationFacts", EmitDefaultValue = false)] + public List ValidationFacts { get; set; } + + /// + /// Gets or Sets Wallet + /// + [DataMember(Name = "wallet", EmitDefaultValue = false)] + public Wallet Wallet { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenNotificationDataV2 {\n"); + sb.Append(" Authentication: ").Append(Authentication).Append("\n"); + sb.Append(" AuthenticationApplied: ").Append(AuthenticationApplied).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Decision: ").Append(Decision).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TokenLastFour: ").Append(TokenLastFour).Append("\n"); + sb.Append(" TokenRequestor: ").Append(TokenRequestor).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); + sb.Append(" Wallet: ").Append(Wallet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as NetworkTokenNotificationDataV2); + } + + /// + /// Returns true if NetworkTokenNotificationDataV2 instances are equal + /// + /// Instance of NetworkTokenNotificationDataV2 to be compared + /// Boolean + public bool Equals(NetworkTokenNotificationDataV2 input) + { + if (input == null) + { + return false; + } + return + ( + this.Authentication == input.Authentication || + (this.Authentication != null && + this.Authentication.Equals(input.Authentication)) + ) && + ( + this.AuthenticationApplied == input.AuthenticationApplied || + this.AuthenticationApplied.Equals(input.AuthenticationApplied) + ) && + ( + this.BalancePlatform == input.BalancePlatform || + (this.BalancePlatform != null && + this.BalancePlatform.Equals(input.BalancePlatform)) + ) && + ( + this.Decision == input.Decision || + (this.Decision != null && + this.Decision.Equals(input.Decision)) + ) && + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.PaymentInstrumentId == input.PaymentInstrumentId || + (this.PaymentInstrumentId != null && + this.PaymentInstrumentId.Equals(input.PaymentInstrumentId)) + ) && + ( + this.Status == input.Status || + (this.Status != null && + this.Status.Equals(input.Status)) + ) && + ( + this.TokenLastFour == input.TokenLastFour || + (this.TokenLastFour != null && + this.TokenLastFour.Equals(input.TokenLastFour)) + ) && + ( + this.TokenRequestor == input.TokenRequestor || + (this.TokenRequestor != null && + this.TokenRequestor.Equals(input.TokenRequestor)) + ) && + ( + this.Type == input.Type || + (this.Type != null && + this.Type.Equals(input.Type)) + ) && + ( + this.ValidationFacts == input.ValidationFacts || + this.ValidationFacts != null && + input.ValidationFacts != null && + this.ValidationFacts.SequenceEqual(input.ValidationFacts) + ) && + ( + this.Wallet == input.Wallet || + (this.Wallet != null && + this.Wallet.Equals(input.Wallet)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Authentication != null) + { + hashCode = (hashCode * 59) + this.Authentication.GetHashCode(); + } + hashCode = (hashCode * 59) + this.AuthenticationApplied.GetHashCode(); + if (this.BalancePlatform != null) + { + hashCode = (hashCode * 59) + this.BalancePlatform.GetHashCode(); + } + if (this.Decision != null) + { + hashCode = (hashCode * 59) + this.Decision.GetHashCode(); + } + if (this.Id != null) + { + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + } + if (this.PaymentInstrumentId != null) + { + hashCode = (hashCode * 59) + this.PaymentInstrumentId.GetHashCode(); + } + if (this.Status != null) + { + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + } + if (this.TokenLastFour != null) + { + hashCode = (hashCode * 59) + this.TokenLastFour.GetHashCode(); + } + if (this.TokenRequestor != null) + { + hashCode = (hashCode * 59) + this.TokenRequestor.GetHashCode(); + } + if (this.Type != null) + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } + if (this.ValidationFacts != null) + { + hashCode = (hashCode * 59) + this.ValidationFacts.GetHashCode(); + } + if (this.Wallet != null) + { + hashCode = (hashCode * 59) + this.Wallet.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationRequest.cs b/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationRequest.cs new file mode 100644 index 000000000..4b080ddf6 --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/NetworkTokenNotificationRequest.cs @@ -0,0 +1,207 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// NetworkTokenNotificationRequest + /// + [DataContract(Name = "NetworkTokenNotificationRequest")] + public partial class NetworkTokenNotificationRequest : IEquatable, IValidatableObject + { + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(StringEnumConverter))] + public enum TypeEnum + { + /// + /// Enum Created for value: balancePlatform.networkToken.created + /// + [EnumMember(Value = "balancePlatform.networkToken.created")] + Created = 1, + + /// + /// Enum Updated for value: balancePlatform.networkToken.updated + /// + [EnumMember(Value = "balancePlatform.networkToken.updated")] + Updated = 2 + + } + + + /// + /// The type of webhook. + /// + /// The type of webhook. + [DataMember(Name = "type", IsRequired = false, EmitDefaultValue = false)] + public TypeEnum Type { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected NetworkTokenNotificationRequest() { } + /// + /// Initializes a new instance of the class. + /// + /// data (required). + /// The environment from which the webhook originated. Possible values: **test**, **live**. (required). + /// When the event was queued.. + /// The type of webhook. (required). + public NetworkTokenNotificationRequest(NetworkTokenNotificationDataV2 data = default(NetworkTokenNotificationDataV2), string environment = default(string), DateTime timestamp = default(DateTime), TypeEnum type = default(TypeEnum)) + { + this.Data = data; + this.Environment = environment; + this.Type = type; + this.Timestamp = timestamp; + } + + /// + /// Gets or Sets Data + /// + [DataMember(Name = "data", IsRequired = false, EmitDefaultValue = false)] + public NetworkTokenNotificationDataV2 Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [DataMember(Name = "environment", IsRequired = false, EmitDefaultValue = false)] + public string Environment { get; set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [DataMember(Name = "timestamp", EmitDefaultValue = false)] + public DateTime Timestamp { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as NetworkTokenNotificationRequest); + } + + /// + /// Returns true if NetworkTokenNotificationRequest instances are equal + /// + /// Instance of NetworkTokenNotificationRequest to be compared + /// Boolean + public bool Equals(NetworkTokenNotificationRequest input) + { + if (input == null) + { + return false; + } + return + ( + this.Data == input.Data || + (this.Data != null && + this.Data.Equals(input.Data)) + ) && + ( + this.Environment == input.Environment || + (this.Environment != null && + this.Environment.Equals(input.Environment)) + ) && + ( + this.Timestamp == input.Timestamp || + (this.Timestamp != null && + this.Timestamp.Equals(input.Timestamp)) + ) && + ( + this.Type == input.Type || + this.Type.Equals(input.Type) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Data != null) + { + hashCode = (hashCode * 59) + this.Data.GetHashCode(); + } + if (this.Environment != null) + { + hashCode = (hashCode * 59) + this.Environment.GetHashCode(); + } + if (this.Timestamp != null) + { + hashCode = (hashCode * 59) + this.Timestamp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/NetworkTokenRequestor.cs b/Adyen/Model/ConfigurationWebhooks/NetworkTokenRequestor.cs new file mode 100644 index 000000000..a46d337f8 --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/NetworkTokenRequestor.cs @@ -0,0 +1,148 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// NetworkTokenRequestor + /// + [DataContract(Name = "NetworkTokenRequestor")] + public partial class NetworkTokenRequestor : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The id of the network token requestor.. + /// The name of the network token requestor.. + public NetworkTokenRequestor(string id = default(string), string name = default(string)) + { + this.Id = id; + this.Name = name; + } + + /// + /// The id of the network token requestor. + /// + /// The id of the network token requestor. + [DataMember(Name = "id", EmitDefaultValue = false)] + public string Id { get; set; } + + /// + /// The name of the network token requestor. + /// + /// The name of the network token requestor. + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NetworkTokenRequestor {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as NetworkTokenRequestor); + } + + /// + /// Returns true if NetworkTokenRequestor instances are equal + /// + /// Instance of NetworkTokenRequestor to be compared + /// Boolean + public bool Equals(NetworkTokenRequestor input) + { + if (input == null) + { + return false; + } + return + ( + this.Id == input.Id || + (this.Id != null && + this.Id.Equals(input.Id)) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Id != null) + { + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + } + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/PlatformPaymentConfiguration.cs b/Adyen/Model/ConfigurationWebhooks/PlatformPaymentConfiguration.cs index ba2c0c489..fbb4fd82f 100644 --- a/Adyen/Model/ConfigurationWebhooks/PlatformPaymentConfiguration.cs +++ b/Adyen/Model/ConfigurationWebhooks/PlatformPaymentConfiguration.cs @@ -35,8 +35,8 @@ public partial class PlatformPaymentConfiguration : IEquatable /// Initializes a new instance of the class. /// - /// Specifies at what time a [sales day](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#sales-day) ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**.. - /// Specifies after how many business days the funds in a [settlement batch](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#settlement-batch) are made available in this balance account. Possible values: **1** to **20**, or **null**. * Setting this value to an integer enables Sales day settlement in this balance account. See how Sales day settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/sales-day-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement). * Setting this value to **null** enables Pass-through settlement in this balance account. See how Pass-through settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/pass-through-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/pass-through-settlement). Default value: **null**.. + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**.. + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**.. public PlatformPaymentConfiguration(string salesDayClosingTime = default(string), int? settlementDelayDays = default(int?)) { this.SalesDayClosingTime = salesDayClosingTime; @@ -44,16 +44,16 @@ public partial class PlatformPaymentConfiguration : IEquatable - /// Specifies at what time a [sales day](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#sales-day) ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. /// - /// Specifies at what time a [sales day](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#sales-day) ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. + /// Specifies at what time a sales day ends for this account. Possible values: Time in **\"HH:MM\"** format. **HH** ranges from **00** to **07**. **MM** must be **00**. Default value: **\"00:00\"**. [DataMember(Name = "salesDayClosingTime", EmitDefaultValue = false)] public string SalesDayClosingTime { get; set; } /// - /// Specifies after how many business days the funds in a [settlement batch](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#settlement-batch) are made available in this balance account. Possible values: **1** to **20**, or **null**. * Setting this value to an integer enables Sales day settlement in this balance account. See how Sales day settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/sales-day-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement). * Setting this value to **null** enables Pass-through settlement in this balance account. See how Pass-through settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/pass-through-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/pass-through-settlement). Default value: **null**. + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. /// - /// Specifies after how many business days the funds in a [settlement batch](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement#settlement-batch) are made available in this balance account. Possible values: **1** to **20**, or **null**. * Setting this value to an integer enables Sales day settlement in this balance account. See how Sales day settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/sales-day-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/sales-day-settlement). * Setting this value to **null** enables Pass-through settlement in this balance account. See how Pass-through settlement works in your [marketplace](https://docs.adyen.com/marketplaces/settle-funds/pass-through-settlement) or [platform](https://docs.adyen.com/platforms/settle-funds/pass-through-settlement). Default value: **null**. + /// Specifies after how many business days the funds in a settlement batch are made available in this balance account. Possible values: **1** to **20**, or **null**. Default value: **null**. [DataMember(Name = "settlementDelayDays", EmitDefaultValue = false)] public int? SettlementDelayDays { get; set; } diff --git a/Adyen/Model/ConfigurationWebhooks/SweepConfigurationV2.cs b/Adyen/Model/ConfigurationWebhooks/SweepConfigurationV2.cs index bf9a72e76..600e905ce 100644 --- a/Adyen/Model/ConfigurationWebhooks/SweepConfigurationV2.cs +++ b/Adyen/Model/ConfigurationWebhooks/SweepConfigurationV2.cs @@ -113,9 +113,9 @@ public enum PrioritiesEnum /// - /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). /// - /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup). [DataMember(Name = "priorities", EmitDefaultValue = false)] public List Priorities { get; set; } /// @@ -347,7 +347,7 @@ protected SweepConfigurationV2() { } /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes) in uppercase. For example, **EUR**. The sweep currency must match any of the [balances currencies](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__resParam_balances). (required). /// The message that will be used in the sweep transfer's description body with a maximum length of 140 characters. If the message is longer after replacing placeholders, the message will be cut off at 140 characters.. /// The unique identifier of the sweep. (required). - /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup).. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities, ordered by your preference. Adyen will try to pay out using the priorities in the given order. If the first priority is not currently supported or enabled for your platform, the system will try the next one, and so on. The request will be accepted as long as **at least one** of the provided priorities is valid (i.e., supported by Adyen and activated for your platform). For example, if you provide `[\"wire\",\"regular\"]`, and `wire` is not supported but `regular` is, the request will still be accepted and processed. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Set `category` to **bank**. For more details, see optional priorities setup for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/scheduled-payouts#optional-priorities-setup) or [platforms](https://docs.adyen.com/platforms/payout-to-users/scheduled-payouts#optional-priorities-setup).. /// The reason for disabling the sweep.. /// The human readable reason for disabling the sweep.. /// Your reference for the sweep configuration.. diff --git a/Adyen/Model/ConfigurationWebhooks/TokenAuthentication.cs b/Adyen/Model/ConfigurationWebhooks/TokenAuthentication.cs new file mode 100644 index 000000000..2624aaf5d --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/TokenAuthentication.cs @@ -0,0 +1,148 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// TokenAuthentication + /// + [DataContract(Name = "TokenAuthentication")] + public partial class TokenAuthentication : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**.. + /// The result of the authentication process.. + public TokenAuthentication(string method = default(string), string result = default(string)) + { + this.Method = method; + this.Result = result; + } + + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**. + /// + /// The method used to complete the authentication process. Possible values: **sms_OTP**, **email_OTP**. + [DataMember(Name = "method", EmitDefaultValue = false)] + public string Method { get; set; } + + /// + /// The result of the authentication process. + /// + /// The result of the authentication process. + [DataMember(Name = "result", EmitDefaultValue = false)] + public string Result { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenAuthentication {\n"); + sb.Append(" Method: ").Append(Method).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as TokenAuthentication); + } + + /// + /// Returns true if TokenAuthentication instances are equal + /// + /// Instance of TokenAuthentication to be compared + /// Boolean + public bool Equals(TokenAuthentication input) + { + if (input == null) + { + return false; + } + return + ( + this.Method == input.Method || + (this.Method != null && + this.Method.Equals(input.Method)) + ) && + ( + this.Result == input.Result || + (this.Result != null && + this.Result.Equals(input.Result)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Method != null) + { + hashCode = (hashCode * 59) + this.Method.GetHashCode(); + } + if (this.Result != null) + { + hashCode = (hashCode * 59) + this.Result.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/ValidationFacts.cs b/Adyen/Model/ConfigurationWebhooks/ValidationFacts.cs new file mode 100644 index 000000000..a32b90f8d --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/ValidationFacts.cs @@ -0,0 +1,197 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// ValidationFacts + /// + [DataContract(Name = "ValidationFacts")] + public partial class ValidationFacts : IEquatable, IValidatableObject + { + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + [JsonConverter(typeof(StringEnumConverter))] + public enum ResultEnum + { + /// + /// Enum Invalid for value: invalid + /// + [EnumMember(Value = "invalid")] + Invalid = 1, + + /// + /// Enum NotApplicable for value: notApplicable + /// + [EnumMember(Value = "notApplicable")] + NotApplicable = 2, + + /// + /// Enum NotValidated for value: notValidated + /// + [EnumMember(Value = "notValidated")] + NotValidated = 3, + + /// + /// Enum Valid for value: valid + /// + [EnumMember(Value = "valid")] + Valid = 4 + + } + + + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + /// + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**. + [DataMember(Name = "result", EmitDefaultValue = false)] + public ResultEnum? Result { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**.. + /// The evaluation result of the validation facts. Possible values: **valid**, **invalid**, **notValidated**, **notApplicable**.. + /// The type of the validation fact.. + public ValidationFacts(List reasons = default(List), ResultEnum? result = default(ResultEnum?), string type = default(string)) + { + this.Reasons = reasons; + this.Result = result; + this.Type = type; + } + + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**. + /// + /// The reason for the `result` of the validations. This field is only sent for `validationFacts.type` **walletValidation**, when `validationFacts.result` is **invalid**. + [DataMember(Name = "reasons", EmitDefaultValue = false)] + public List Reasons { get; set; } + + /// + /// The type of the validation fact. + /// + /// The type of the validation fact. + [DataMember(Name = "type", EmitDefaultValue = false)] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ValidationFacts {\n"); + sb.Append(" Reasons: ").Append(Reasons).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as ValidationFacts); + } + + /// + /// Returns true if ValidationFacts instances are equal + /// + /// Instance of ValidationFacts to be compared + /// Boolean + public bool Equals(ValidationFacts input) + { + if (input == null) + { + return false; + } + return + ( + this.Reasons == input.Reasons || + this.Reasons != null && + input.Reasons != null && + this.Reasons.SequenceEqual(input.Reasons) + ) && + ( + this.Result == input.Result || + this.Result.Equals(input.Result) + ) && + ( + this.Type == input.Type || + (this.Type != null && + this.Type.Equals(input.Type)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Reasons != null) + { + hashCode = (hashCode * 59) + this.Reasons.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Result.GetHashCode(); + if (this.Type != null) + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/ConfigurationWebhooks/VerificationError.cs b/Adyen/Model/ConfigurationWebhooks/VerificationError.cs index f53da3050..13056cb02 100644 --- a/Adyen/Model/ConfigurationWebhooks/VerificationError.cs +++ b/Adyen/Model/ConfigurationWebhooks/VerificationError.cs @@ -379,9 +379,9 @@ public enum CapabilitiesEnum [DataMember(Name = "capabilities", EmitDefaultValue = false)] public List Capabilities { get; set; } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -401,15 +401,20 @@ public enum TypeEnum /// Enum PendingStatus for value: pendingStatus /// [EnumMember(Value = "pendingStatus")] - PendingStatus = 3 - + PendingStatus = 3, + + /// + /// Enum DataReview for value: dataReview + /// + [EnumMember(Value = "dataReview")] + DataReview = 4 } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -420,7 +425,7 @@ public enum TypeEnum /// A description of the error.. /// Contains the actions that you can take to resolve the verification error.. /// Contains more granular information about the verification error.. - /// The type of error. Possible values: **invalidInput**, **dataMissing**.. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** . public VerificationError(List capabilities = default(List), string code = default(string), string message = default(string), List remediatingActions = default(List), List subErrors = default(List), TypeEnum? type = default(TypeEnum?)) { this.Capabilities = capabilities; diff --git a/Adyen/Model/ConfigurationWebhooks/VerificationErrorRecursive.cs b/Adyen/Model/ConfigurationWebhooks/VerificationErrorRecursive.cs index f7df3cfaa..0a7dd6603 100644 --- a/Adyen/Model/ConfigurationWebhooks/VerificationErrorRecursive.cs +++ b/Adyen/Model/ConfigurationWebhooks/VerificationErrorRecursive.cs @@ -379,9 +379,9 @@ public enum CapabilitiesEnum [DataMember(Name = "capabilities", EmitDefaultValue = false)] public List Capabilities { get; set; } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -401,15 +401,21 @@ public enum TypeEnum /// Enum PendingStatus for value: pendingStatus /// [EnumMember(Value = "pendingStatus")] - PendingStatus = 3 + PendingStatus = 3, + + /// + /// Enum DataReview for value: dataReview + /// + [EnumMember(Value = "dataReview")] + DataReview = 4 } /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** /// - /// The type of error. Possible values: **invalidInput**, **dataMissing**. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -418,7 +424,7 @@ public enum TypeEnum /// Contains the capabilities that the verification error applies to.. /// The verification error code.. /// A description of the error.. - /// The type of error. Possible values: **invalidInput**, **dataMissing**.. + /// The type of error. Possible values: * **invalidInput** * **dataMissing** * **pendingStatus** * **dataReview** . /// Contains the actions that you can take to resolve the verification error.. public VerificationErrorRecursive(List capabilities = default(List), string code = default(string), string message = default(string), TypeEnum? type = default(TypeEnum?), List remediatingActions = default(List)) { diff --git a/Adyen/Model/ConfigurationWebhooks/Wallet.cs b/Adyen/Model/ConfigurationWebhooks/Wallet.cs new file mode 100644 index 000000000..1f3e1cb73 --- /dev/null +++ b/Adyen/Model/ConfigurationWebhooks/Wallet.cs @@ -0,0 +1,475 @@ +/* +* Configuration webhooks +* +* +* The version of the OpenAPI document: 2 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.ConfigurationWebhooks +{ + /// + /// Wallet + /// + [DataContract(Name = "Wallet")] + public partial class Wallet : IEquatable, IValidatableObject + { + /// + /// Defines RecommendationReasons + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RecommendationReasonsEnum + { + /// + /// Enum AccountCardTooNew for value: accountCardTooNew + /// + [EnumMember(Value = "accountCardTooNew")] + AccountCardTooNew = 1, + + /// + /// Enum AccountHighRisk for value: accountHighRisk + /// + [EnumMember(Value = "accountHighRisk")] + AccountHighRisk = 2, + + /// + /// Enum AccountRecentlyChanged for value: accountRecentlyChanged + /// + [EnumMember(Value = "accountRecentlyChanged")] + AccountRecentlyChanged = 3, + + /// + /// Enum AccountTooNew for value: accountTooNew + /// + [EnumMember(Value = "accountTooNew")] + AccountTooNew = 4, + + /// + /// Enum AccountTooNewSinceLaunch for value: accountTooNewSinceLaunch + /// + [EnumMember(Value = "accountTooNewSinceLaunch")] + AccountTooNewSinceLaunch = 5, + + /// + /// Enum CardholderPanAssociatedToAccountWithinThresholdDays for value: cardholderPanAssociatedToAccountWithinThresholdDays + /// + [EnumMember(Value = "cardholderPanAssociatedToAccountWithinThresholdDays")] + CardholderPanAssociatedToAccountWithinThresholdDays = 6, + + /// + /// Enum ChangesMadeToAccountDataWithinThresholdDays for value: changesMadeToAccountDataWithinThresholdDays + /// + [EnumMember(Value = "changesMadeToAccountDataWithinThresholdDays")] + ChangesMadeToAccountDataWithinThresholdDays = 7, + + /// + /// Enum DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry for value: deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry + /// + [EnumMember(Value = "deviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry")] + DeviceProvisioningLocationOutsideOfCardholdersWalletAccountHomeCountry = 8, + + /// + /// Enum DeviceRecentlyLost for value: deviceRecentlyLost + /// + [EnumMember(Value = "deviceRecentlyLost")] + DeviceRecentlyLost = 9, + + /// + /// Enum EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication for value: encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication + /// + [EnumMember(Value = "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication")] + EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithSuccessfulUpfrontAuthentication = 10, + + /// + /// Enum EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication for value: encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication + /// + [EnumMember(Value = "encryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication")] + EncryptedPaymentInstrumentDataIsBeingPushedByTheIssuerToTheSameDeviceThatIssuerApplicationAuthenticatedButWithoutAnyUpfrontAuthentication = 11, + + /// + /// Enum EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated for value: encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated + /// + [EnumMember(Value = "encryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated")] + EncryptedPaymentInstrumentDataIsPushedToADifferentDeviceThanTheOneThatIssuerApplicationAuthenticated = 12, + + /// + /// Enum EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder for value: encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder + /// + [EnumMember(Value = "encryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder")] + EncryptedPaymentInstrumentDataIsPushedToADifferentUserThanTheCardHolder = 13, + + /// + /// Enum HasSuspendedTokens for value: hasSuspendedTokens + /// + [EnumMember(Value = "hasSuspendedTokens")] + HasSuspendedTokens = 14, + + /// + /// Enum InactiveAccount for value: inactiveAccount + /// + [EnumMember(Value = "inactiveAccount")] + InactiveAccount = 15, + + /// + /// Enum IssuerDeferredIDVDecision for value: issuerDeferredIDVDecision + /// + [EnumMember(Value = "issuerDeferredIDVDecision")] + IssuerDeferredIDVDecision = 16, + + /// + /// Enum IssuerEncryptedPaymentInstrumentDataExpired for value: issuerEncryptedPaymentInstrumentDataExpired + /// + [EnumMember(Value = "issuerEncryptedPaymentInstrumentDataExpired")] + IssuerEncryptedPaymentInstrumentDataExpired = 17, + + /// + /// Enum LowAccountScore for value: lowAccountScore + /// + [EnumMember(Value = "lowAccountScore")] + LowAccountScore = 18, + + /// + /// Enum LowDeviceScore for value: lowDeviceScore + /// + [EnumMember(Value = "lowDeviceScore")] + LowDeviceScore = 19, + + /// + /// Enum LowPhoneNumberScore for value: lowPhoneNumberScore + /// + [EnumMember(Value = "lowPhoneNumberScore")] + LowPhoneNumberScore = 20, + + /// + /// Enum NumberOfActiveTokensGreaterThanThreshold for value: numberOfActiveTokensGreaterThanThreshold + /// + [EnumMember(Value = "numberOfActiveTokensGreaterThanThreshold")] + NumberOfActiveTokensGreaterThanThreshold = 21, + + /// + /// Enum NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold for value: numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold + /// + [EnumMember(Value = "numberOfActiveTokensOnAllDevicesIsGreaterThanThreshold")] + NumberOfActiveTokensOnAllDevicesIsGreaterThanThreshold = 22, + + /// + /// Enum NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays for value: numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays + /// + [EnumMember(Value = "numberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays")] + NumberOfDaysSinceDeviceWasLastReportedLostIsLessThanThresholdDays = 23, + + /// + /// Enum NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold for value: numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold + /// + [EnumMember(Value = "numberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold")] + NumberOfDevicesWithSameUseridWithTokenIsGreaterThanThreshold = 24, + + /// + /// Enum NumberOfTransactionsInLast12MonthsLessThanThresholdNumber for value: numberOfTransactionsInLast12MonthsLessThanThresholdNumber + /// + [EnumMember(Value = "numberOfTransactionsInLast12MonthsLessThanThresholdNumber")] + NumberOfTransactionsInLast12MonthsLessThanThresholdNumber = 25, + + /// + /// Enum OutSideHomeTerritory for value: outSideHomeTerritory + /// + [EnumMember(Value = "outSideHomeTerritory")] + OutSideHomeTerritory = 26, + + /// + /// Enum SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold for value: suspendedCardsInTheWALLETAccountIsGreaterThanThreshold + /// + [EnumMember(Value = "suspendedCardsInTheWALLETAccountIsGreaterThanThreshold")] + SuspendedCardsInTheWALLETAccountIsGreaterThanThreshold = 27, + + /// + /// Enum SuspiciousActivity for value: suspiciousActivity + /// + [EnumMember(Value = "suspiciousActivity")] + SuspiciousActivity = 28, + + /// + /// Enum TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold for value: theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold + /// + [EnumMember(Value = "theNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold")] + TheNumberOfProvisioningAttemptsAcrossAllCardsOnThisDeviceInTheLast24HoursExceedsTheThreshold = 29, + + /// + /// Enum TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold for value: theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold + /// + [EnumMember(Value = "theWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold")] + TheWALLETAccountIntoWhichTheCardIsBeingProvisionedContainDistinctNamesGreaterThanThreshold = 30, + + /// + /// Enum ThisAccountHasNotHadActivityWithinThresholdPeriod for value: thisAccountHasNotHadActivityWithinThresholdPeriod + /// + [EnumMember(Value = "thisAccountHasNotHadActivityWithinThresholdPeriod")] + ThisAccountHasNotHadActivityWithinThresholdPeriod = 31, + + /// + /// Enum TooManyDifferentCardholders for value: tooManyDifferentCardholders + /// + [EnumMember(Value = "tooManyDifferentCardholders")] + TooManyDifferentCardholders = 32, + + /// + /// Enum TooManyRecentAttempts for value: tooManyRecentAttempts + /// + [EnumMember(Value = "tooManyRecentAttempts")] + TooManyRecentAttempts = 33, + + /// + /// Enum TooManyRecentTokens for value: tooManyRecentTokens + /// + [EnumMember(Value = "tooManyRecentTokens")] + TooManyRecentTokens = 34, + + /// + /// Enum UnableToAssess for value: unableToAssess + /// + [EnumMember(Value = "unableToAssess")] + UnableToAssess = 35, + + /// + /// Enum Unknown for value: unknown + /// + [EnumMember(Value = "unknown")] + Unknown = 36, + + /// + /// Enum UserAccountWasCreatedWithinThresholdDays for value: userAccountWasCreatedWithinThresholdDays + /// + [EnumMember(Value = "userAccountWasCreatedWithinThresholdDays")] + UserAccountWasCreatedWithinThresholdDays = 37, + + /// + /// Enum UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken for value: userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken + /// + [EnumMember(Value = "userDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken")] + UserDeviceReceivingEncryptedPaymentInstrumentDataIsDifferentThanTheOneThatIsProvisioningTheToken = 38, + + /// + /// Enum UsersAccountOnDeviceLessThanThresholdDays for value: usersAccountOnDeviceLessThanThresholdDays + /// + [EnumMember(Value = "usersAccountOnDeviceLessThanThresholdDays")] + UsersAccountOnDeviceLessThanThresholdDays = 39, + + /// + /// Enum WalletAccountCreatedWithinThresholdDays for value: walletAccountCreatedWithinThresholdDays + /// + [EnumMember(Value = "walletAccountCreatedWithinThresholdDays")] + WalletAccountCreatedWithinThresholdDays = 40, + + /// + /// Enum WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName for value: walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName + /// + [EnumMember(Value = "walletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName")] + WalletAccountHolderNameOnFileDoesNotMatchCardholderEnteredName = 41 + + } + + + + /// + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** + /// + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** + [DataMember(Name = "recommendationReasons", EmitDefaultValue = false)] + public List RecommendationReasons { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**.. + /// device. + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**.. + /// The method used for provisioning the network token. Possible values: **push**, **manual**.. + /// A list of risk indicators triggered at the time of provisioning the network token. Some example values of risk indicators are: * **accountTooNewSinceLaunch** * **tooManyRecentAttempts** * **lowDeviceScore** * **lowAccountScore** . + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**.. + public Wallet(string accountScore = default(string), Device device = default(Device), string deviceScore = default(string), string provisioningMethod = default(string), List recommendationReasons = default(List), string type = default(string)) + { + this.AccountScore = accountScore; + this.Device = device; + this.DeviceScore = deviceScore; + this.ProvisioningMethod = provisioningMethod; + this.RecommendationReasons = recommendationReasons; + this.Type = type; + } + + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**. + /// + /// The confidence score of the wallet account, calculated by the wallet provider. A high score means that account is considered trustworthy. A low score means that the account is considered suspicious. Possible values: **1** to **5**. + [DataMember(Name = "accountScore", EmitDefaultValue = false)] + public string AccountScore { get; set; } + + /// + /// Gets or Sets Device + /// + [DataMember(Name = "device", EmitDefaultValue = false)] + public Device Device { get; set; } + + /// + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**. + /// + /// The confidence score of the device, calculated by the wallet provider. A high score means that device is considered trustworthy. A low score means that the device is considered suspicious. Possible values: **1** to **5**. + [DataMember(Name = "deviceScore", EmitDefaultValue = false)] + public string DeviceScore { get; set; } + + /// + /// The method used for provisioning the network token. Possible values: **push**, **manual**. + /// + /// The method used for provisioning the network token. Possible values: **push**, **manual**. + [DataMember(Name = "provisioningMethod", EmitDefaultValue = false)] + public string ProvisioningMethod { get; set; } + + /// + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**. + /// + /// The type of wallet that the network token is associated with. Possible values: **applePay**, **googlePay**, **garminPay**. + [DataMember(Name = "type", EmitDefaultValue = false)] + [Obsolete("Deprecated since Configuration webhooks v2. Use name of the `tokenRequestor` instead.")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Wallet {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" Device: ").Append(Device).Append("\n"); + sb.Append(" DeviceScore: ").Append(DeviceScore).Append("\n"); + sb.Append(" ProvisioningMethod: ").Append(ProvisioningMethod).Append("\n"); + sb.Append(" RecommendationReasons: ").Append(RecommendationReasons).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Wallet); + } + + /// + /// Returns true if Wallet instances are equal + /// + /// Instance of Wallet to be compared + /// Boolean + public bool Equals(Wallet input) + { + if (input == null) + { + return false; + } + return + ( + this.AccountScore == input.AccountScore || + (this.AccountScore != null && + this.AccountScore.Equals(input.AccountScore)) + ) && + ( + this.Device == input.Device || + (this.Device != null && + this.Device.Equals(input.Device)) + ) && + ( + this.DeviceScore == input.DeviceScore || + (this.DeviceScore != null && + this.DeviceScore.Equals(input.DeviceScore)) + ) && + ( + this.ProvisioningMethod == input.ProvisioningMethod || + (this.ProvisioningMethod != null && + this.ProvisioningMethod.Equals(input.ProvisioningMethod)) + ) && + ( + this.RecommendationReasons == input.RecommendationReasons || + this.RecommendationReasons.SequenceEqual(input.RecommendationReasons) + ) && + ( + this.Type == input.Type || + (this.Type != null && + this.Type.Equals(input.Type)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.AccountScore != null) + { + hashCode = (hashCode * 59) + this.AccountScore.GetHashCode(); + } + if (this.Device != null) + { + hashCode = (hashCode * 59) + this.Device.GetHashCode(); + } + if (this.DeviceScore != null) + { + hashCode = (hashCode * 59) + this.DeviceScore.GetHashCode(); + } + if (this.ProvisioningMethod != null) + { + hashCode = (hashCode * 59) + this.ProvisioningMethod.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RecommendationReasons.GetHashCode(); + if (this.Type != null) + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/LegalEntityManagement/AcceptTermsOfServiceResponse.cs b/Adyen/Model/LegalEntityManagement/AcceptTermsOfServiceResponse.cs index 43914f22e..b91ac3008 100644 --- a/Adyen/Model/LegalEntityManagement/AcceptTermsOfServiceResponse.cs +++ b/Adyen/Model/LegalEntityManagement/AcceptTermsOfServiceResponse.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.LegalEntityManagement public partial class AcceptTermsOfServiceResponse : IEquatable, IValidatableObject { /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -91,15 +91,21 @@ public enum TypeEnum /// Enum AdyenPccr for value: adyenPccr /// [EnumMember(Value = "adyenPccr")] - AdyenPccr = 9 + AdyenPccr = 9, + + /// + /// Enum KycOnInvite for value: kycOnInvite + /// + [EnumMember(Value = "kycOnInvite")] + KycOnInvite = 10 } /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -110,7 +116,7 @@ public enum TypeEnum /// The IP address of the user that accepted the Terms of Service.. /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English.. /// The unique identifier of the Terms of Service document.. - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** . + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** . public AcceptTermsOfServiceResponse(string acceptedBy = default(string), string id = default(string), string ipAddress = default(string), string language = default(string), string termsOfServiceDocumentId = default(string), TypeEnum? type = default(TypeEnum?)) { this.AcceptedBy = acceptedBy; diff --git a/Adyen/Model/LegalEntityManagement/AdditionalBankIdentification.cs b/Adyen/Model/LegalEntityManagement/AdditionalBankIdentification.cs index 8b0a48558..e39455e1e 100644 --- a/Adyen/Model/LegalEntityManagement/AdditionalBankIdentification.cs +++ b/Adyen/Model/LegalEntityManagement/AdditionalBankIdentification.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.LegalEntityManagement public partial class AdditionalBankIdentification : IEquatable, IValidatableObject { /// - /// The type of additional bank identification, depending on the country. Possible values: * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. /// - /// The type of additional bank identification, depending on the country. Possible values: * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -49,22 +49,33 @@ public enum TypeEnum /// Enum UsRoutingNumber for value: usRoutingNumber /// [EnumMember(Value = "usRoutingNumber")] - UsRoutingNumber = 2 + UsRoutingNumber = 2, + + /// + /// Enum AuBsbCode for value: auBsbCode + /// + [EnumMember(Value = "auBsbCode")] + AuBsbCode = 3, + /// + /// Enum CaRoutingNumber for value: caRoutingNumber + /// + [EnumMember(Value = "caRoutingNumber")] + CaRoutingNumber = 4 + } - /// - /// The type of additional bank identification, depending on the country. Possible values: * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. /// - /// The type of additional bank identification, depending on the country. Possible values: * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// /// Initializes a new instance of the class. /// /// The value of the additional bank identification.. - /// The type of additional bank identification, depending on the country. Possible values: * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces.. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces.. public AdditionalBankIdentification(string code = default(string), TypeEnum? type = default(TypeEnum?)) { this.Code = code; diff --git a/Adyen/Model/LegalEntityManagement/Address.cs b/Adyen/Model/LegalEntityManagement/Address.cs index 838f8fee8..33f278fbd 100644 --- a/Adyen/Model/LegalEntityManagement/Address.cs +++ b/Adyen/Model/LegalEntityManagement/Address.cs @@ -42,7 +42,7 @@ protected Address() { } /// /// The name of the city. Required if `stateOrProvince` is provided. If you specify the city, you must also send `postalCode` and `street`.. /// The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. (required). - /// Postal code. Required if `stateOrProvince` and/or `city` is provided.. + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA.. /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US. If you specify the state or province, you must also send `city`, `postalCode`, and `street`.. /// The name of the street, and the house or building number. Required if `stateOrProvince` and/or `city` is provided.. /// The apartment, unit, or suite number.. @@ -71,9 +71,9 @@ protected Address() { } public string Country { get; set; } /// - /// Postal code. Required if `stateOrProvince` and/or `city` is provided. + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA. /// - /// Postal code. Required if `stateOrProvince` and/or `city` is provided. + /// The postal code. Required if `stateOrProvince` and/or `city` is provided. When using alphanumeric postal codes, all letters must be uppercase. For example, 1234 AB or SW1A 1AA. [DataMember(Name = "postalCode", EmitDefaultValue = false)] public string PostalCode { get; set; } diff --git a/Adyen/Model/LegalEntityManagement/CalculateTermsOfServiceStatusResponse.cs b/Adyen/Model/LegalEntityManagement/CalculateTermsOfServiceStatusResponse.cs index 4cffb8946..9d9a0f1c8 100644 --- a/Adyen/Model/LegalEntityManagement/CalculateTermsOfServiceStatusResponse.cs +++ b/Adyen/Model/LegalEntityManagement/CalculateTermsOfServiceStatusResponse.cs @@ -90,7 +90,13 @@ public enum TermsOfServiceTypesEnum /// Enum AdyenPccr for value: adyenPccr /// [EnumMember(Value = "adyenPccr")] - AdyenPccr = 9 + AdyenPccr = 9, + + /// + /// Enum KycOnInvite for value: kycOnInvite + /// + [EnumMember(Value = "kycOnInvite")] + KycOnInvite = 10 } diff --git a/Adyen/Model/LegalEntityManagement/FinancialReport.cs b/Adyen/Model/LegalEntityManagement/FinancialReport.cs index 96a8d68e8..d16c30112 100644 --- a/Adyen/Model/LegalEntityManagement/FinancialReport.cs +++ b/Adyen/Model/LegalEntityManagement/FinancialReport.cs @@ -221,4 +221,4 @@ public override int GetHashCode() } } -} +} \ No newline at end of file diff --git a/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentRequest.cs b/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentRequest.cs index ea43ec103..33a5d6dec 100644 --- a/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentRequest.cs +++ b/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentRequest.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.LegalEntityManagement public partial class GetTermsOfServiceDocumentRequest : IEquatable, IValidatableObject { /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -91,15 +91,21 @@ public enum TypeEnum /// Enum AdyenPccr for value: adyenPccr /// [EnumMember(Value = "adyenPccr")] - AdyenPccr = 9 + AdyenPccr = 9, + + /// + /// Enum KycOnInvite for value: kycOnInvite + /// + [EnumMember(Value = "kycOnInvite")] + KycOnInvite = 10 } /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [DataMember(Name = "type", IsRequired = false, EmitDefaultValue = false)] public TypeEnum Type { get; set; } /// @@ -112,7 +118,7 @@ protected GetTermsOfServiceDocumentRequest() { } /// /// The language to be used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English. (required). /// The requested format for the Terms of Service document. Default value: JSON. Possible values: **JSON**, **PDF**, or **TXT**.. - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** (required). + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** (required). public GetTermsOfServiceDocumentRequest(string language = default(string), string termsOfServiceDocumentFormat = default(string), TypeEnum type = default(TypeEnum)) { this.Language = language; diff --git a/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentResponse.cs b/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentResponse.cs index 356ad6924..b155cf761 100644 --- a/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentResponse.cs +++ b/Adyen/Model/LegalEntityManagement/GetTermsOfServiceDocumentResponse.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.LegalEntityManagement public partial class GetTermsOfServiceDocumentResponse : IEquatable, IValidatableObject { /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -91,15 +91,21 @@ public enum TypeEnum /// Enum AdyenPccr for value: adyenPccr /// [EnumMember(Value = "adyenPccr")] - AdyenPccr = 9 + AdyenPccr = 9, + + /// + /// Enum KycOnInvite for value: kycOnInvite + /// + [EnumMember(Value = "kycOnInvite")] + KycOnInvite = 10 } /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -110,7 +116,7 @@ public enum TypeEnum /// The language used for the Terms of Service document, specified by the two-letter [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. Possible value: **en** for English.. /// The format of the Terms of Service document.. /// The unique identifier of the Terms of Service document.. - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** . + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** . public GetTermsOfServiceDocumentResponse(byte[] document = default(byte[]), string id = default(string), string language = default(string), string termsOfServiceDocumentFormat = default(string), string termsOfServiceDocumentId = default(string), TypeEnum? type = default(TypeEnum?)) { this.Document = document; diff --git a/Adyen/Model/LegalEntityManagement/TermsOfServiceAcceptanceInfo.cs b/Adyen/Model/LegalEntityManagement/TermsOfServiceAcceptanceInfo.cs index 1aa00d04a..09713eefb 100644 --- a/Adyen/Model/LegalEntityManagement/TermsOfServiceAcceptanceInfo.cs +++ b/Adyen/Model/LegalEntityManagement/TermsOfServiceAcceptanceInfo.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.LegalEntityManagement public partial class TermsOfServiceAcceptanceInfo : IEquatable, IValidatableObject { /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { @@ -91,15 +91,21 @@ public enum TypeEnum /// Enum AdyenPccr for value: adyenPccr /// [EnumMember(Value = "adyenPccr")] - AdyenPccr = 9 + AdyenPccr = 9, + + /// + /// Enum KycOnInvite for value: kycOnInvite + /// + [EnumMember(Value = "kycOnInvite")] + KycOnInvite = 10 } /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** /// - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** [DataMember(Name = "type", EmitDefaultValue = false)] public TypeEnum? Type { get; set; } /// @@ -109,7 +115,7 @@ public enum TypeEnum /// The unique identifier of the legal entity for which the Terms of Service are accepted.. /// The date when the Terms of Service were accepted, in ISO 8601 extended format. For example, 2022-12-18T10:15:30+01:00.. /// An Adyen-generated reference for the accepted Terms of Service.. - /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** . + /// The type of Terms of Service. Possible values: * **adyenForPlatformsManage** * **adyenIssuing** * **adyenForPlatformsAdvanced** * **adyenCapital** * **adyenAccount** * **adyenCard** * **adyenFranchisee** * **adyenPccr** * **adyenChargeCard** * **kycOnInvite** . /// The expiration date for the Terms of Service acceptance, in ISO 8601 extended format. For example, 2022-12-18T00:00:00+01:00.. public TermsOfServiceAcceptanceInfo(string acceptedBy = default(string), string acceptedFor = default(string), DateTime createdAt = default(DateTime), string id = default(string), TypeEnum? type = default(TypeEnum?), DateTime validTo = default(DateTime)) { diff --git a/Adyen/Model/Management/SplitConfigurationRule.cs b/Adyen/Model/Management/SplitConfigurationRule.cs index 40e6e5fb2..d82d51e76 100644 --- a/Adyen/Model/Management/SplitConfigurationRule.cs +++ b/Adyen/Model/Management/SplitConfigurationRule.cs @@ -55,8 +55,25 @@ public enum FundingSourceEnum /// Enum ANY for value: ANY /// [EnumMember(Value = "ANY")] - ANY = 3 + ANY = 3, + /// + /// Enum Charged for value: charged + /// + [EnumMember(Value = "charged")] + Charged = 4, + + /// + /// Enum DeferredDebit for value: deferred_debit + /// + [EnumMember(Value = "deferred_debit")] + DeferredDebit = 5, + + /// + /// Enum Prepaid for value: prepaid + /// + [EnumMember(Value = "prepaid")] + Prepaid = 6 } diff --git a/Adyen/Model/TransactionWebhooks/BalancePlatformNotificationResponse.cs b/Adyen/Model/TransactionWebhooks/BalancePlatformNotificationResponse.cs index 9a20bae19..79ef5c400 100644 --- a/Adyen/Model/TransactionWebhooks/BalancePlatformNotificationResponse.cs +++ b/Adyen/Model/TransactionWebhooks/BalancePlatformNotificationResponse.cs @@ -35,16 +35,16 @@ public partial class BalancePlatformNotificationResponse : IEquatable /// Initializes a new instance of the class. /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications).. + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks).. public BalancePlatformNotificationResponse(string notificationResponse = default(string)) { this.NotificationResponse = notificationResponse; } /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications). + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). /// - /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks#accept-notifications). + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). [DataMember(Name = "notificationResponse", EmitDefaultValue = false)] public string NotificationResponse { get; set; } diff --git a/Adyen/Model/TransactionWebhooks/BankCategoryData.cs b/Adyen/Model/TransactionWebhooks/BankCategoryData.cs index 9eb725b4a..81b2565d2 100644 --- a/Adyen/Model/TransactionWebhooks/BankCategoryData.cs +++ b/Adyen/Model/TransactionWebhooks/BankCategoryData.cs @@ -33,9 +33,9 @@ namespace Adyen.Model.TransactionWebhooks public partial class BankCategoryData : IEquatable, IValidatableObject { /// - /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). /// - /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). [JsonConverter(typeof(StringEnumConverter))] public enum PriorityEnum { @@ -79,9 +79,9 @@ public enum PriorityEnum /// - /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). /// - /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). [DataMember(Name = "priority", EmitDefaultValue = false)] public PriorityEnum? Priority { get; set; } /// @@ -109,7 +109,7 @@ public enum TypeEnum /// /// Initializes a new instance of the class. /// - /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers in [SEPA countries](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN).. + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN).. /// **bank** (default to TypeEnum.Bank). public BankCategoryData(PriorityEnum? priority = default(PriorityEnum?), TypeEnum? type = TypeEnum.Bank) { diff --git a/Adyen/Model/TransactionWebhooks/IssuedCard.cs b/Adyen/Model/TransactionWebhooks/IssuedCard.cs index 35b807d17..7900f7bda 100644 --- a/Adyen/Model/TransactionWebhooks/IssuedCard.cs +++ b/Adyen/Model/TransactionWebhooks/IssuedCard.cs @@ -185,9 +185,10 @@ public enum TypeEnum /// relayedAuthorisationData. /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments.. /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme.. + /// threeDSecure. /// **issuedCard** (default to TypeEnum.IssuedCard). /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information.. - public IssuedCard(string authorisationType = default(string), PanEntryModeEnum? panEntryMode = default(PanEntryModeEnum?), ProcessingTypeEnum? processingType = default(ProcessingTypeEnum?), RelayedAuthorisationData relayedAuthorisationData = default(RelayedAuthorisationData), string schemeTraceId = default(string), string schemeUniqueTransactionId = default(string), TypeEnum? type = TypeEnum.IssuedCard, List validationFacts = default(List)) + public IssuedCard(string authorisationType = default(string), PanEntryModeEnum? panEntryMode = default(PanEntryModeEnum?), ProcessingTypeEnum? processingType = default(ProcessingTypeEnum?), RelayedAuthorisationData relayedAuthorisationData = default(RelayedAuthorisationData), string schemeTraceId = default(string), string schemeUniqueTransactionId = default(string), ThreeDSecure threeDSecure = default(ThreeDSecure), TypeEnum? type = TypeEnum.IssuedCard, List validationFacts = default(List)) { this.AuthorisationType = authorisationType; this.PanEntryMode = panEntryMode; @@ -195,6 +196,7 @@ public enum TypeEnum this.RelayedAuthorisationData = relayedAuthorisationData; this.SchemeTraceId = schemeTraceId; this.SchemeUniqueTransactionId = schemeUniqueTransactionId; + this.ThreeDSecure = threeDSecure; this.Type = type; this.ValidationFacts = validationFacts; } @@ -226,6 +228,12 @@ public enum TypeEnum [DataMember(Name = "schemeUniqueTransactionId", EmitDefaultValue = false)] public string SchemeUniqueTransactionId { get; set; } + /// + /// Gets or Sets ThreeDSecure + /// + [DataMember(Name = "threeDSecure", EmitDefaultValue = false)] + public ThreeDSecure ThreeDSecure { get; set; } + /// /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. /// @@ -247,6 +255,7 @@ public override string ToString() sb.Append(" RelayedAuthorisationData: ").Append(RelayedAuthorisationData).Append("\n"); sb.Append(" SchemeTraceId: ").Append(SchemeTraceId).Append("\n"); sb.Append(" SchemeUniqueTransactionId: ").Append(SchemeUniqueTransactionId).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); sb.Append("}\n"); @@ -312,6 +321,11 @@ public bool Equals(IssuedCard input) (this.SchemeUniqueTransactionId != null && this.SchemeUniqueTransactionId.Equals(input.SchemeUniqueTransactionId)) ) && + ( + this.ThreeDSecure == input.ThreeDSecure || + (this.ThreeDSecure != null && + this.ThreeDSecure.Equals(input.ThreeDSecure)) + ) && ( this.Type == input.Type || this.Type.Equals(input.Type) @@ -351,6 +365,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.SchemeUniqueTransactionId.GetHashCode(); } + if (this.ThreeDSecure != null) + { + hashCode = (hashCode * 59) + this.ThreeDSecure.GetHashCode(); + } hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ValidationFacts != null) { diff --git a/Adyen/Model/TransactionWebhooks/Resource.cs b/Adyen/Model/TransactionWebhooks/Resource.cs index d90729e37..4c51d2dfa 100644 --- a/Adyen/Model/TransactionWebhooks/Resource.cs +++ b/Adyen/Model/TransactionWebhooks/Resource.cs @@ -36,7 +36,7 @@ public partial class Resource : IEquatable, IValidatableObject /// Initializes a new instance of the class. /// /// The unique identifier of the balance platform.. - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**.. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**.. /// The ID of the resource.. public Resource(string balancePlatform = default(string), DateTime creationDate = default(DateTime), string id = default(string)) { @@ -53,9 +53,9 @@ public partial class Resource : IEquatable, IValidatableObject public string BalancePlatform { get; set; } /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. [DataMember(Name = "creationDate", EmitDefaultValue = false)] public DateTime CreationDate { get; set; } diff --git a/Adyen/Model/TransactionWebhooks/ThreeDSecure.cs b/Adyen/Model/TransactionWebhooks/ThreeDSecure.cs new file mode 100644 index 000000000..71b9254bb --- /dev/null +++ b/Adyen/Model/TransactionWebhooks/ThreeDSecure.cs @@ -0,0 +1,129 @@ +/* +* Transaction webhooks +* +* +* The version of the OpenAPI document: 4 +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; + +namespace Adyen.Model.TransactionWebhooks +{ + /// + /// ThreeDSecure + /// + [DataContract(Name = "ThreeDSecure")] + public partial class ThreeDSecure : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction identifier for the Access Control Server. + public ThreeDSecure(string acsTransactionId = default(string)) + { + this.AcsTransactionId = acsTransactionId; + } + + /// + /// The transaction identifier for the Access Control Server + /// + /// The transaction identifier for the Access Control Server + [DataMember(Name = "acsTransactionId", EmitDefaultValue = false)] + public string AcsTransactionId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecure {\n"); + sb.Append(" AcsTransactionId: ").Append(AcsTransactionId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as ThreeDSecure); + } + + /// + /// Returns true if ThreeDSecure instances are equal + /// + /// Instance of ThreeDSecure to be compared + /// Boolean + public bool Equals(ThreeDSecure input) + { + if (input == null) + { + return false; + } + return + ( + this.AcsTransactionId == input.AcsTransactionId || + (this.AcsTransactionId != null && + this.AcsTransactionId.Equals(input.AcsTransactionId)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.AcsTransactionId != null) + { + hashCode = (hashCode * 59) + this.AcsTransactionId.GetHashCode(); + } + return hashCode; + } + } + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/Adyen/Model/TransactionWebhooks/Transaction.cs b/Adyen/Model/TransactionWebhooks/Transaction.cs index 60ad7b697..9e0614204 100644 --- a/Adyen/Model/TransactionWebhooks/Transaction.cs +++ b/Adyen/Model/TransactionWebhooks/Transaction.cs @@ -73,7 +73,7 @@ protected Transaction() { } /// balanceAccount (required). /// The unique identifier of the balance platform. (required). /// The date the transaction was booked into the balance account. (required). - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**.. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**.. /// The `description` from the `/transfers` request.. /// The unique identifier of the transaction. (required). /// paymentInstrument. @@ -131,9 +131,9 @@ protected Transaction() { } public DateTime BookingDate { get; set; } /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. /// - /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. [DataMember(Name = "creationDate", EmitDefaultValue = false)] public DateTime CreationDate { get; set; } diff --git a/Adyen/Model/TransferWebhooks/AdditionalBankIdentification.cs b/Adyen/Model/TransferWebhooks/AdditionalBankIdentification.cs index 08e15d14c..a87e5399e 100644 --- a/Adyen/Model/TransferWebhooks/AdditionalBankIdentification.cs +++ b/Adyen/Model/TransferWebhooks/AdditionalBankIdentification.cs @@ -49,8 +49,20 @@ public enum TypeEnum /// Enum UsRoutingNumber for value: usRoutingNumber /// [EnumMember(Value = "usRoutingNumber")] - UsRoutingNumber = 2 + UsRoutingNumber = 2, + + /// + /// Enum AuBsbCode for value: auBsbCode + /// + [EnumMember(Value = "auBsbCode")] + AuBsbCode = 3, + /// + /// Enum CaRoutingNumber for value: caRoutingNumber + /// + [EnumMember(Value = "caRoutingNumber")] + CaRoutingNumber = 4 + } diff --git a/Adyen/Model/Transfers/AdditionalBankIdentification.cs b/Adyen/Model/Transfers/AdditionalBankIdentification.cs index fe6830f37..a25b56001 100644 --- a/Adyen/Model/Transfers/AdditionalBankIdentification.cs +++ b/Adyen/Model/Transfers/AdditionalBankIdentification.cs @@ -49,7 +49,19 @@ public enum TypeEnum /// Enum UsRoutingNumber for value: usRoutingNumber /// [EnumMember(Value = "usRoutingNumber")] - UsRoutingNumber = 2 + UsRoutingNumber = 2, + + /// + /// Enum AuBsbCode for value: auBsbCode + /// + [EnumMember(Value = "auBsbCode")] + AuBsbCode = 3, + + /// + /// Enum CaRoutingNumber for value: caRoutingNumber + /// + [EnumMember(Value = "caRoutingNumber")] + CaRoutingNumber = 4 } diff --git a/Adyen/NegativeBalanceWarningWebhooks/Client/ClientUtils.cs b/Adyen/NegativeBalanceWarningWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..252d7f6aa --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Client/ClientUtils.cs @@ -0,0 +1,289 @@ +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.NegativeBalanceWarningWebhooks.Models; +using Models = Adyen.NegativeBalanceWarningWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.NegativeBalanceWarningWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.NegativeBalanceCompensationWarningNotificationRequest.TypeEnum negativeBalanceCompensationWarningNotificationRequestTypeEnum) + return Models.NegativeBalanceCompensationWarningNotificationRequest.TypeEnum.ToJsonValue(negativeBalanceCompensationWarningNotificationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Client/HmacKeyToken.cs b/Adyen/NegativeBalanceWarningWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..34c6b7946 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/NegativeBalanceWarningWebhooks/Client/HostConfiguration.cs b/Adyen/NegativeBalanceWarningWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..1ee6df8d3 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,132 @@ +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.NegativeBalanceWarningWebhooks.Client; +using Adyen.NegativeBalanceWarningWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.NegativeBalanceWarningWebhooks.Client +{ + /// + /// Provides hosting configuration for NegativeBalanceWarningWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new NegativeBalanceCompensationWarningNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new NegativeBalanceCompensationWarningNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddNegativeBalanceWarningWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/NegativeBalanceWarningWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..0e41ca1d9 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.NegativeBalanceWarningWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/NegativeBalanceWarningWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/NegativeBalanceWarningWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..ca3cc0cd9 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.NegativeBalanceWarningWebhooks; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the NegativeBalanceWarningWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureNegativeBalanceWarningWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddNegativeBalanceWarningWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/NegativeBalanceWarningWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..b0c5d9ba8 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen NegativeBalanceWarningWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddNegativeBalanceWarningWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddNegativeBalanceWarningWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Handlers/NegativeBalanceWarningWebhooksHandler.cs b/Adyen/NegativeBalanceWarningWebhooks/Handlers/NegativeBalanceWarningWebhooksHandler.cs new file mode 100644 index 000000000..0ab7b7073 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Handlers/NegativeBalanceWarningWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.NegativeBalanceWarningWebhooks.Client; +using Adyen.NegativeBalanceWarningWebhooks.Models; + +namespace Adyen.NegativeBalanceWarningWebhooks.Handlers +{ + /// + /// Interface for deserializing NegativeBalanceWarningWebhooks webhooks or verify its HMAC signature. + /// + public interface INegativeBalanceWarningWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.NegativeBalanceWarningWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + NegativeBalanceCompensationWarningNotificationRequest? DeserializeNegativeBalanceCompensationWarningNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize NegativeBalanceWarningWebhooks or verify the HMAC signature of the webhook. + /// + public partial class NegativeBalanceWarningWebhooksHandler : INegativeBalanceWarningWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.NegativeBalanceWarningWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing NegativeBalanceWarningWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public NegativeBalanceWarningWebhooksHandler(Adyen.NegativeBalanceWarningWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public NegativeBalanceCompensationWarningNotificationRequest? DeserializeNegativeBalanceCompensationWarningNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Models/Amount.cs b/Adyen/NegativeBalanceWarningWebhooks/Models/Amount.cs new file mode 100644 index 000000000..172047586 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationData.cs b/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationData.cs new file mode 100644 index 000000000..ef5b16cdf --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationData.cs @@ -0,0 +1,364 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Models +{ + /// + /// NegativeBalanceCompensationWarningNotificationData. + /// + public partial class NegativeBalanceCompensationWarningNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// amount + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + /// The balance account ID of the account that will be used to compensate the balance account whose balance is negative. + /// The date the balance for the account became negative. + /// The date when a compensation transfer to the account is scheduled to happen. + [JsonConstructor] + public NegativeBalanceCompensationWarningNotificationData(Option accountHolder = default, Option amount = default, Option balancePlatform = default, Option creationDate = default, Option id = default, Option liableBalanceAccountId = default, Option negativeBalanceSince = default, Option scheduledCompensationAt = default) + { + _AccountHolderOption = accountHolder; + _AmountOption = amount; + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + _LiableBalanceAccountIdOption = liableBalanceAccountId; + _NegativeBalanceSinceOption = negativeBalanceSince; + _ScheduledCompensationAtOption = scheduledCompensationAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NegativeBalanceCompensationWarningNotificationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LiableBalanceAccountIdOption { get; private set; } + + /// + /// The balance account ID of the account that will be used to compensate the balance account whose balance is negative. + /// + /// The balance account ID of the account that will be used to compensate the balance account whose balance is negative. + [JsonPropertyName("liableBalanceAccountId")] + public string? LiableBalanceAccountId { get { return this._LiableBalanceAccountIdOption; } set { this._LiableBalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NegativeBalanceSinceOption { get; private set; } + + /// + /// The date the balance for the account became negative. + /// + /// The date the balance for the account became negative. + [JsonPropertyName("negativeBalanceSince")] + public DateTimeOffset? NegativeBalanceSince { get { return this._NegativeBalanceSinceOption; } set { this._NegativeBalanceSinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScheduledCompensationAtOption { get; private set; } + + /// + /// The date when a compensation transfer to the account is scheduled to happen. + /// + /// The date when a compensation transfer to the account is scheduled to happen. + [JsonPropertyName("scheduledCompensationAt")] + public DateTimeOffset? ScheduledCompensationAt { get { return this._ScheduledCompensationAtOption; } set { this._ScheduledCompensationAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NegativeBalanceCompensationWarningNotificationData {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LiableBalanceAccountId: ").Append(LiableBalanceAccountId).Append("\n"); + sb.Append(" NegativeBalanceSince: ").Append(NegativeBalanceSince).Append("\n"); + sb.Append(" ScheduledCompensationAt: ").Append(ScheduledCompensationAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NegativeBalanceCompensationWarningNotificationDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NegativeBalanceSince. + /// + public static string NegativeBalanceSinceFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ScheduledCompensationAt. + /// + public static string ScheduledCompensationAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NegativeBalanceCompensationWarningNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option amount = default; + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + Option liableBalanceAccountId = default; + Option negativeBalanceSince = default; + Option scheduledCompensationAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "liableBalanceAccountId": + liableBalanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "negativeBalanceSince": + negativeBalanceSince = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "scheduledCompensationAt": + scheduledCompensationAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new NegativeBalanceCompensationWarningNotificationData(accountHolder, amount, balancePlatform, creationDate, id, liableBalanceAccountId, negativeBalanceSince, scheduledCompensationAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NegativeBalanceCompensationWarningNotificationData negativeBalanceCompensationWarningNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, negativeBalanceCompensationWarningNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NegativeBalanceCompensationWarningNotificationData negativeBalanceCompensationWarningNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (negativeBalanceCompensationWarningNotificationData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, negativeBalanceCompensationWarningNotificationData.AccountHolder, jsonSerializerOptions); + } + if (negativeBalanceCompensationWarningNotificationData._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, negativeBalanceCompensationWarningNotificationData.Amount, jsonSerializerOptions); + } + if (negativeBalanceCompensationWarningNotificationData._BalancePlatformOption.IsSet) + if (negativeBalanceCompensationWarningNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", negativeBalanceCompensationWarningNotificationData.BalancePlatform); + + if (negativeBalanceCompensationWarningNotificationData._CreationDateOption.IsSet) + writer.WriteString("creationDate", negativeBalanceCompensationWarningNotificationData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (negativeBalanceCompensationWarningNotificationData._IdOption.IsSet) + if (negativeBalanceCompensationWarningNotificationData.Id != null) + writer.WriteString("id", negativeBalanceCompensationWarningNotificationData.Id); + + if (negativeBalanceCompensationWarningNotificationData._LiableBalanceAccountIdOption.IsSet) + if (negativeBalanceCompensationWarningNotificationData.LiableBalanceAccountId != null) + writer.WriteString("liableBalanceAccountId", negativeBalanceCompensationWarningNotificationData.LiableBalanceAccountId); + + if (negativeBalanceCompensationWarningNotificationData._NegativeBalanceSinceOption.IsSet) + writer.WriteString("negativeBalanceSince", negativeBalanceCompensationWarningNotificationData._NegativeBalanceSinceOption.Value!.Value.ToString(NegativeBalanceSinceFormat)); + + if (negativeBalanceCompensationWarningNotificationData._ScheduledCompensationAtOption.IsSet) + writer.WriteString("scheduledCompensationAt", negativeBalanceCompensationWarningNotificationData._ScheduledCompensationAtOption.Value!.Value.ToString(ScheduledCompensationAtFormat)); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationRequest.cs b/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationRequest.cs new file mode 100644 index 000000000..dec7c15cf --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Models/NegativeBalanceCompensationWarningNotificationRequest.cs @@ -0,0 +1,336 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Models +{ + /// + /// NegativeBalanceCompensationWarningNotificationRequest. + /// + public partial class NegativeBalanceCompensationWarningNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public NegativeBalanceCompensationWarningNotificationRequest(NegativeBalanceCompensationWarningNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NegativeBalanceCompensationWarningNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformNegativeBalanceCompensationWarningScheduled - balancePlatform.negativeBalanceCompensationWarning.scheduled + /// + public static readonly TypeEnum BalancePlatformNegativeBalanceCompensationWarningScheduled = new("balancePlatform.negativeBalanceCompensationWarning.scheduled"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.negativeBalanceCompensationWarning.scheduled" => TypeEnum.BalancePlatformNegativeBalanceCompensationWarningScheduled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformNegativeBalanceCompensationWarningScheduled) + return "balancePlatform.negativeBalanceCompensationWarning.scheduled"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public NegativeBalanceCompensationWarningNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NegativeBalanceCompensationWarningNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NegativeBalanceCompensationWarningNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NegativeBalanceCompensationWarningNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NegativeBalanceCompensationWarningNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class NegativeBalanceCompensationWarningNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class NegativeBalanceCompensationWarningNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NegativeBalanceCompensationWarningNotificationRequest.", nameof(type)); + + return new NegativeBalanceCompensationWarningNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NegativeBalanceCompensationWarningNotificationRequest negativeBalanceCompensationWarningNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, negativeBalanceCompensationWarningNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NegativeBalanceCompensationWarningNotificationRequest negativeBalanceCompensationWarningNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, negativeBalanceCompensationWarningNotificationRequest.Data, jsonSerializerOptions); + if (negativeBalanceCompensationWarningNotificationRequest.Environment != null) + writer.WriteString("environment", negativeBalanceCompensationWarningNotificationRequest.Environment); + + if (negativeBalanceCompensationWarningNotificationRequest.Type != null) + { + string? typeRawValue = NegativeBalanceCompensationWarningNotificationRequest.TypeEnum.ToJsonValue(negativeBalanceCompensationWarningNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (negativeBalanceCompensationWarningNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", negativeBalanceCompensationWarningNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Models/Resource.cs b/Adyen/NegativeBalanceWarningWebhooks/Models/Resource.cs new file mode 100644 index 000000000..fcd1a1e6e --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/NegativeBalanceWarningWebhooks/Models/ResourceReference.cs b/Adyen/NegativeBalanceWarningWebhooks/Models/ResourceReference.cs new file mode 100644 index 000000000..0e8ce0ae6 --- /dev/null +++ b/Adyen/NegativeBalanceWarningWebhooks/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Negative balance compensation warning + * + * Adyen sends webhooks to inform you about balance accounts whose balance has been negative for 20 or more days. If you do not transfer funds to that balance account to cover the negative balance before the scheduled compensation date, a transfer is made from your liable balance account on that date. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.NegativeBalanceWarningWebhooks.Client; + +namespace Adyen.NegativeBalanceWarningWebhooks.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/Payment/Client/ApiKeyToken.cs b/Adyen/Payment/Client/ApiKeyToken.cs new file mode 100644 index 000000000..fad6451b2 --- /dev/null +++ b/Adyen/Payment/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Payment.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Payment/Client/ClientUtils.cs b/Adyen/Payment/Client/ClientUtils.cs new file mode 100644 index 000000000..73f0cf9b1 --- /dev/null +++ b/Adyen/Payment/Client/ClientUtils.cs @@ -0,0 +1,427 @@ +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Payment.Models; +using Models = Adyen.Payment.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Payment.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AccountInfo.AccountAgeIndicatorEnum accountInfoAccountAgeIndicatorEnum) + return Models.AccountInfo.AccountAgeIndicatorEnum.ToJsonValue(accountInfoAccountAgeIndicatorEnum); + if (obj is Models.AccountInfo.AccountChangeIndicatorEnum accountInfoAccountChangeIndicatorEnum) + return Models.AccountInfo.AccountChangeIndicatorEnum.ToJsonValue(accountInfoAccountChangeIndicatorEnum); + if (obj is Models.AccountInfo.AccountTypeEnum accountInfoAccountTypeEnum) + return Models.AccountInfo.AccountTypeEnum.ToJsonValue(accountInfoAccountTypeEnum); + if (obj is Models.AccountInfo.DeliveryAddressUsageIndicatorEnum accountInfoDeliveryAddressUsageIndicatorEnum) + return Models.AccountInfo.DeliveryAddressUsageIndicatorEnum.ToJsonValue(accountInfoDeliveryAddressUsageIndicatorEnum); + if (obj is Models.AccountInfo.PasswordChangeIndicatorEnum accountInfoPasswordChangeIndicatorEnum) + return Models.AccountInfo.PasswordChangeIndicatorEnum.ToJsonValue(accountInfoPasswordChangeIndicatorEnum); + if (obj is Models.AccountInfo.PaymentAccountIndicatorEnum accountInfoPaymentAccountIndicatorEnum) + return Models.AccountInfo.PaymentAccountIndicatorEnum.ToJsonValue(accountInfoPaymentAccountIndicatorEnum); + if (obj is Models.AcctInfo.ChAccAgeIndEnum acctInfoChAccAgeIndEnum) + return Models.AcctInfo.ChAccAgeIndEnum.ToJsonValue(acctInfoChAccAgeIndEnum); + if (obj is Models.AcctInfo.ChAccChangeIndEnum acctInfoChAccChangeIndEnum) + return Models.AcctInfo.ChAccChangeIndEnum.ToJsonValue(acctInfoChAccChangeIndEnum); + if (obj is Models.AcctInfo.ChAccPwChangeIndEnum acctInfoChAccPwChangeIndEnum) + return Models.AcctInfo.ChAccPwChangeIndEnum.ToJsonValue(acctInfoChAccPwChangeIndEnum); + if (obj is Models.AcctInfo.PaymentAccIndEnum acctInfoPaymentAccIndEnum) + return Models.AcctInfo.PaymentAccIndEnum.ToJsonValue(acctInfoPaymentAccIndEnum); + if (obj is Models.AcctInfo.ShipAddressUsageIndEnum acctInfoShipAddressUsageIndEnum) + return Models.AcctInfo.ShipAddressUsageIndEnum.ToJsonValue(acctInfoShipAddressUsageIndEnum); + if (obj is Models.AcctInfo.ShipNameIndicatorEnum acctInfoShipNameIndicatorEnum) + return Models.AcctInfo.ShipNameIndicatorEnum.ToJsonValue(acctInfoShipNameIndicatorEnum); + if (obj is Models.AcctInfo.SuspiciousAccActivityEnum acctInfoSuspiciousAccActivityEnum) + return Models.AcctInfo.SuspiciousAccActivityEnum.ToJsonValue(acctInfoSuspiciousAccActivityEnum); + if (obj is Models.AdditionalData3DSecure.ChallengeWindowSizeEnum additionalData3DSecureChallengeWindowSizeEnum) + return Models.AdditionalData3DSecure.ChallengeWindowSizeEnum.ToJsonValue(additionalData3DSecureChallengeWindowSizeEnum); + if (obj is Models.AdditionalDataCommon.IndustryUsageEnum additionalDataCommonIndustryUsageEnum) + return Models.AdditionalDataCommon.IndustryUsageEnum.ToJsonValue(additionalDataCommonIndustryUsageEnum); + if (obj is Models.DeviceRenderOptions.SdkInterfaceEnum deviceRenderOptionsSdkInterfaceEnum) + return Models.DeviceRenderOptions.SdkInterfaceEnum.ToJsonValue(deviceRenderOptionsSdkInterfaceEnum); + if (obj is Models.DeviceRenderOptions.SdkUiTypeEnum deviceRenderOptionsSdkUiTypeEnum) + return DeviceRenderOptions.SdkUiTypeEnum.ToJsonValue(deviceRenderOptionsSdkUiTypeEnum); + if (obj is Models.Installments.PlanEnum installmentsPlanEnum) + return Models.Installments.PlanEnum.ToJsonValue(installmentsPlanEnum); + if (obj is Models.Mandate.FrequencyEnum mandateFrequencyEnum) + return Models.Mandate.FrequencyEnum.ToJsonValue(mandateFrequencyEnum); + if (obj is Models.Mandate.AmountRuleEnum mandateAmountRuleEnum) + return Models.Mandate.AmountRuleEnum.ToJsonValue(mandateAmountRuleEnum); + if (obj is Models.Mandate.BillingAttemptsRuleEnum mandateBillingAttemptsRuleEnum) + return Models.Mandate.BillingAttemptsRuleEnum.ToJsonValue(mandateBillingAttemptsRuleEnum); + if (obj is Models.MerchantRiskIndicator.DeliveryAddressIndicatorEnum merchantRiskIndicatorDeliveryAddressIndicatorEnum) + return Models.MerchantRiskIndicator.DeliveryAddressIndicatorEnum.ToJsonValue(merchantRiskIndicatorDeliveryAddressIndicatorEnum); + if (obj is Models.MerchantRiskIndicator.DeliveryTimeframeEnum merchantRiskIndicatorDeliveryTimeframeEnum) + return Models.MerchantRiskIndicator.DeliveryTimeframeEnum.ToJsonValue(merchantRiskIndicatorDeliveryTimeframeEnum); + if (obj is Models.ModificationResult.ResponseEnum modificationResultResponseEnum) + return Models.ModificationResult.ResponseEnum.ToJsonValue(modificationResultResponseEnum); + if (obj is Models.PaymentRequest.EntityTypeEnum paymentRequestEntityTypeEnum) + return Models.PaymentRequest.EntityTypeEnum.ToJsonValue(paymentRequestEntityTypeEnum); + if (obj is Models.PaymentRequest.FundingSourceEnum paymentRequestFundingSourceEnum) + return Models.PaymentRequest.FundingSourceEnum.ToJsonValue(paymentRequestFundingSourceEnum); + if (obj is Models.PaymentRequest.RecurringProcessingModelEnum paymentRequestRecurringProcessingModelEnum) + return Models.PaymentRequest.RecurringProcessingModelEnum.ToJsonValue(paymentRequestRecurringProcessingModelEnum); + if (obj is Models.PaymentRequest.ShopperInteractionEnum paymentRequestShopperInteractionEnum) + return Models.PaymentRequest.ShopperInteractionEnum.ToJsonValue(paymentRequestShopperInteractionEnum); + if (obj is Models.PaymentRequest3d.RecurringProcessingModelEnum paymentRequest3dRecurringProcessingModelEnum) + return Models.PaymentRequest3d.RecurringProcessingModelEnum.ToJsonValue(paymentRequest3dRecurringProcessingModelEnum); + if (obj is Models.PaymentRequest3d.ShopperInteractionEnum paymentRequest3dShopperInteractionEnum) + return Models.PaymentRequest3d.ShopperInteractionEnum.ToJsonValue(paymentRequest3dShopperInteractionEnum); + if (obj is Models.PaymentRequest3ds2.RecurringProcessingModelEnum paymentRequest3ds2RecurringProcessingModelEnum) + return Models.PaymentRequest3ds2.RecurringProcessingModelEnum.ToJsonValue(paymentRequest3ds2RecurringProcessingModelEnum); + if (obj is Models.PaymentRequest3ds2.ShopperInteractionEnum paymentRequest3ds2ShopperInteractionEnum) + return Models.PaymentRequest3ds2.ShopperInteractionEnum.ToJsonValue(paymentRequest3ds2ShopperInteractionEnum); + if (obj is Models.PaymentResult.ResultCodeEnum paymentResultResultCodeEnum) + return Models.PaymentResult.ResultCodeEnum.ToJsonValue(paymentResultResultCodeEnum); + if (obj is Models.PlatformChargebackLogic.BehaviorEnum platformChargebackLogicBehaviorEnum) + return Models.PlatformChargebackLogic.BehaviorEnum.ToJsonValue(platformChargebackLogicBehaviorEnum); + if (obj is Models.Recurring.ContractEnum recurringContractEnum) + return Models.Recurring.ContractEnum.ToJsonValue(recurringContractEnum); + if (obj is Models.Recurring.TokenServiceEnum recurringTokenServiceEnum) + return Models.Recurring.TokenServiceEnum.ToJsonValue(recurringTokenServiceEnum); + if (obj is Models.ResponseAdditionalDataCard.CardProductIdEnum responseAdditionalDataCardCardProductIdEnum) + return Models.ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCardCardProductIdEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudResultTypeEnum responseAdditionalDataCommonFraudResultTypeEnum) + return Models.ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommonFraudResultTypeEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum responseAdditionalDataCommonFraudRiskLevelEnum) + return Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommonFraudRiskLevelEnum); + if (obj is Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum responseAdditionalDataCommonRecurringProcessingModelEnum) + return Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommonRecurringProcessingModelEnum); + if (obj is Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum responseAdditionalDataCommonTokenizationStoreOperationTypeEnum) + return Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommonTokenizationStoreOperationTypeEnum); + if (obj is Models.SecureRemoteCommerceCheckoutData.SchemeEnum secureRemoteCommerceCheckoutDataSchemeEnum) + return Models.SecureRemoteCommerceCheckoutData.SchemeEnum.ToJsonValue(secureRemoteCommerceCheckoutDataSchemeEnum); + if (obj is Models.Split.TypeEnum splitTypeEnum) + return Models.Split.TypeEnum.ToJsonValue(splitTypeEnum); + if (obj is Models.ThreeDS2RequestData.AcctTypeEnum threeDS2RequestDataAcctTypeEnum) + return Models.ThreeDS2RequestData.AcctTypeEnum.ToJsonValue(threeDS2RequestDataAcctTypeEnum); + if (obj is Models.ThreeDS2RequestData.AddrMatchEnum threeDS2RequestDataAddrMatchEnum) + return Models.ThreeDS2RequestData.AddrMatchEnum.ToJsonValue(threeDS2RequestDataAddrMatchEnum); + if (obj is Models.ThreeDS2RequestData.ChallengeIndicatorEnum threeDS2RequestDataChallengeIndicatorEnum) + return Models.ThreeDS2RequestData.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestDataChallengeIndicatorEnum); + if (obj is Models.ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum threeDS2RequestDataThreeDSRequestorChallengeIndEnum) + return Models.ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestDataThreeDSRequestorChallengeIndEnum); + if (obj is Models.ThreeDS2RequestData.TransTypeEnum threeDS2RequestDataTransTypeEnum) + return Models.ThreeDS2RequestData.TransTypeEnum.ToJsonValue(threeDS2RequestDataTransTypeEnum); + if (obj is Models.ThreeDS2RequestData.TransactionTypeEnum threeDS2RequestDataTransactionTypeEnum) + return Models.ThreeDS2RequestData.TransactionTypeEnum.ToJsonValue(threeDS2RequestDataTransactionTypeEnum); + if (obj is Models.ThreeDS2Result.ChallengeCancelEnum threeDS2ResultChallengeCancelEnum) + return Models.ThreeDS2Result.ChallengeCancelEnum.ToJsonValue(threeDS2ResultChallengeCancelEnum); + if (obj is Models.ThreeDS2Result.ExemptionIndicatorEnum threeDS2ResultExemptionIndicatorEnum) + return Models.ThreeDS2Result.ExemptionIndicatorEnum.ToJsonValue(threeDS2ResultExemptionIndicatorEnum); + if (obj is Models.ThreeDS2Result.ThreeDSRequestorChallengeIndEnum threeDS2ResultThreeDSRequestorChallengeIndEnum) + return Models.ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2ResultThreeDSRequestorChallengeIndEnum); + if (obj is Models.ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum threeDSRequestorAuthenticationInfoThreeDSReqAuthMethodEnum) + return Models.ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.ToJsonValue(threeDSRequestorAuthenticationInfoThreeDSReqAuthMethodEnum); + if (obj is Models.ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum threeDSRequestorPriorAuthenticationInfoThreeDSReqPriorAuthMethodEnum) + return Models.ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.ToJsonValue(threeDSRequestorPriorAuthenticationInfoThreeDSReqPriorAuthMethodEnum); + if (obj is Models.ThreeDSecureData.AuthenticationResponseEnum threeDSecureDataAuthenticationResponseEnum) + return Models.ThreeDSecureData.AuthenticationResponseEnum.ToJsonValue(threeDSecureDataAuthenticationResponseEnum); + if (obj is Models.ThreeDSecureData.ChallengeCancelEnum threeDSecureDataChallengeCancelEnum) + return Models.ThreeDSecureData.ChallengeCancelEnum.ToJsonValue(threeDSecureDataChallengeCancelEnum); + if (obj is Models.ThreeDSecureData.DirectoryResponseEnum threeDSecureDataDirectoryResponseEnum) + return Models.ThreeDSecureData.DirectoryResponseEnum.ToJsonValue(threeDSecureDataDirectoryResponseEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Payment/Client/HostConfiguration.cs b/Adyen/Payment/Client/HostConfiguration.cs new file mode 100644 index 000000000..3f749346a --- /dev/null +++ b/Adyen/Payment/Client/HostConfiguration.cs @@ -0,0 +1,211 @@ +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Payment.Services; +using Adyen.Payment.Client; +using Adyen.Payment.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Payment.Client +{ + /// + /// Provides hosting configuration for Payment + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/Payment/v68"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountInfoJsonConverter()); + _jsonOptions.Converters.Add(new AcctInfoJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalData3DSecureJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataAirlineJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataCarRentalJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataCommonJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataLevel23JsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataLodgingJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataModificationsJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataOpenInvoiceJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataOpiJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRatepayJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRetryJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRiskJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataRiskStandaloneJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataSubMerchantJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataTemporaryServicesJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalDataWalletsJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AdjustAuthorisationRequestJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new ApplicationInfoJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationResultRequestJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationResultResponseJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountJsonConverter()); + _jsonOptions.Converters.Add(new BrowserInfoJsonConverter()); + _jsonOptions.Converters.Add(new CancelOrRefundRequestJsonConverter()); + _jsonOptions.Converters.Add(new CancelRequestJsonConverter()); + _jsonOptions.Converters.Add(new CaptureRequestJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CommonFieldJsonConverter()); + _jsonOptions.Converters.Add(new DeviceRenderOptionsJsonConverter()); + _jsonOptions.Converters.Add(new DonationRequestJsonConverter()); + _jsonOptions.Converters.Add(new ExternalPlatformJsonConverter()); + _jsonOptions.Converters.Add(new ForexQuoteJsonConverter()); + _jsonOptions.Converters.Add(new FraudCheckResultJsonConverter()); + _jsonOptions.Converters.Add(new FraudCheckResultWrapperJsonConverter()); + _jsonOptions.Converters.Add(new FraudResultJsonConverter()); + _jsonOptions.Converters.Add(new FundDestinationJsonConverter()); + _jsonOptions.Converters.Add(new FundSourceJsonConverter()); + _jsonOptions.Converters.Add(new InstallmentsJsonConverter()); + _jsonOptions.Converters.Add(new MandateJsonConverter()); + _jsonOptions.Converters.Add(new MerchantDeviceJsonConverter()); + _jsonOptions.Converters.Add(new MerchantRiskIndicatorJsonConverter()); + _jsonOptions.Converters.Add(new ModificationResultJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRequestJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRequest3dJsonConverter()); + _jsonOptions.Converters.Add(new PaymentRequest3ds2JsonConverter()); + _jsonOptions.Converters.Add(new PaymentResultJsonConverter()); + _jsonOptions.Converters.Add(new PhoneJsonConverter()); + _jsonOptions.Converters.Add(new PlatformChargebackLogicJsonConverter()); + _jsonOptions.Converters.Add(new RecurringJsonConverter()); + _jsonOptions.Converters.Add(new RefundRequestJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalData3DSecureJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataBillingAddressJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCardJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCommonJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataDomesticErrorJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataInstallmentsJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataNetworkTokensJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataOpiJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSepaJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSwishJsonConverter()); + _jsonOptions.Converters.Add(new SDKEphemPubKeyJsonConverter()); + _jsonOptions.Converters.Add(new SecureRemoteCommerceCheckoutDataJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new ShopperInteractionDeviceJsonConverter()); + _jsonOptions.Converters.Add(new SplitJsonConverter()); + _jsonOptions.Converters.Add(new SplitAmountJsonConverter()); + _jsonOptions.Converters.Add(new SubMerchantJsonConverter()); + _jsonOptions.Converters.Add(new TechnicalCancelRequestJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS1ResultJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2RequestDataJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2ResultJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2ResultRequestJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDS2ResultResponseJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSRequestorAuthenticationInfoJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSRequestorPriorAuthenticationInfoJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSecureDataJsonConverter()); + _jsonOptions.Converters.Add(new VoidPendingRefundRequestJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddPaymentHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Payment/Client/JsonSerializerOptionsProvider.cs b/Adyen/Payment/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..fb3cb953b --- /dev/null +++ b/Adyen/Payment/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Payment.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Payment/Extensions/HostBuilderExtensions.cs b/Adyen/Payment/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..1b601ccfb --- /dev/null +++ b/Adyen/Payment/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Payment; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Payment API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigurePayment(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddPaymentHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Payment/Extensions/ServiceCollectionExtensions.cs b/Adyen/Payment/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..b14cc5014 --- /dev/null +++ b/Adyen/Payment/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Payment API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddPaymentServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddPaymentHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Payment/Models/AccountInfo.cs b/Adyen/Payment/Models/AccountInfo.cs new file mode 100644 index 000000000..9b66a8995 --- /dev/null +++ b/Adyen/Payment/Models/AccountInfo.cs @@ -0,0 +1,1407 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AccountInfo. + /// + public partial class AccountInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Date when the shopper's account was last changed. + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Date when the shopper's account was created. + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// Number of attempts the shopper tried to add a card to their account in the last day. + /// Date the selected delivery address was first used. + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Shopper's home phone number (including the country code). + /// Shopper's mobile phone number (including the country code). + /// Date when the shopper last changed their password. + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + /// Date this payment method was added to the shopper's account. + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// Number of successful purchases in the last six months. + /// Whether suspicious activity was recorded on this account. + /// Shopper's work phone number (including the country code). + [JsonConstructor] + public AccountInfo(Option accountAgeIndicator = default, Option accountChangeDate = default, Option accountChangeIndicator = default, Option accountCreationDate = default, Option accountType = default, Option addCardAttemptsDay = default, Option deliveryAddressUsageDate = default, Option deliveryAddressUsageIndicator = default, Option homePhone = default, Option mobilePhone = default, Option passwordChangeDate = default, Option passwordChangeIndicator = default, Option pastTransactionsDay = default, Option pastTransactionsYear = default, Option paymentAccountAge = default, Option paymentAccountIndicator = default, Option purchasesLast6Months = default, Option suspiciousActivity = default, Option workPhone = default) + { + _AccountAgeIndicatorOption = accountAgeIndicator; + _AccountChangeDateOption = accountChangeDate; + _AccountChangeIndicatorOption = accountChangeIndicator; + _AccountCreationDateOption = accountCreationDate; + _AccountTypeOption = accountType; + _AddCardAttemptsDayOption = addCardAttemptsDay; + _DeliveryAddressUsageDateOption = deliveryAddressUsageDate; + _DeliveryAddressUsageIndicatorOption = deliveryAddressUsageIndicator; + _HomePhoneOption = homePhone; + _MobilePhoneOption = mobilePhone; + _PasswordChangeDateOption = passwordChangeDate; + _PasswordChangeIndicatorOption = passwordChangeIndicator; + _PastTransactionsDayOption = pastTransactionsDay; + _PastTransactionsYearOption = pastTransactionsYear; + _PaymentAccountAgeOption = paymentAccountAge; + _PaymentAccountIndicatorOption = paymentAccountIndicator; + _PurchasesLast6MonthsOption = purchasesLast6Months; + _SuspiciousActivityOption = suspiciousActivity; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountInfo() + { + } + + partial void OnCreated(); + + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(AccountAgeIndicatorEnumJsonConverter))] + public class AccountAgeIndicatorEnum : IEnum + { + /// + /// Returns the value of the AccountAgeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// AccountAgeIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly AccountAgeIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// AccountAgeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly AccountAgeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// AccountAgeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly AccountAgeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// AccountAgeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly AccountAgeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// AccountAgeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly AccountAgeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private AccountAgeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountAgeIndicatorEnum?(string? value) => value == null ? null : new AccountAgeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountAgeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(AccountAgeIndicatorEnum? left, AccountAgeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountAgeIndicatorEnum? left, AccountAgeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountAgeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountAgeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => AccountAgeIndicatorEnum.NotApplicable, + "thisTransaction" => AccountAgeIndicatorEnum.ThisTransaction, + "lessThan30Days" => AccountAgeIndicatorEnum.LessThan30Days, + "from30To60Days" => AccountAgeIndicatorEnum.From30To60Days, + "moreThan60Days" => AccountAgeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountAgeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == AccountAgeIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == AccountAgeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == AccountAgeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == AccountAgeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == AccountAgeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing AccountAgeIndicatorEnum. + /// + public class AccountAgeIndicatorEnumJsonConverter : JsonConverter + { + public override AccountAgeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountAgeIndicatorEnum.FromStringOrDefault(value) ?? new AccountAgeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountAgeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountAgeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountAgeIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this shopper account was created in the merchant's environment. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("accountAgeIndicator")] + public AccountAgeIndicatorEnum? AccountAgeIndicator { get { return this._AccountAgeIndicatorOption; } set { this._AccountAgeIndicatorOption = new(value); } } + + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(AccountChangeIndicatorEnumJsonConverter))] + public class AccountChangeIndicatorEnum : IEnum + { + /// + /// Returns the value of the AccountChangeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// AccountChangeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly AccountChangeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// AccountChangeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly AccountChangeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// AccountChangeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly AccountChangeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// AccountChangeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly AccountChangeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private AccountChangeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountChangeIndicatorEnum?(string? value) => value == null ? null : new AccountChangeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountChangeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(AccountChangeIndicatorEnum? left, AccountChangeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountChangeIndicatorEnum? left, AccountChangeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountChangeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountChangeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "thisTransaction" => AccountChangeIndicatorEnum.ThisTransaction, + "lessThan30Days" => AccountChangeIndicatorEnum.LessThan30Days, + "from30To60Days" => AccountChangeIndicatorEnum.From30To60Days, + "moreThan60Days" => AccountChangeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountChangeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == AccountChangeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == AccountChangeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == AccountChangeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == AccountChangeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing AccountChangeIndicatorEnum. + /// + public class AccountChangeIndicatorEnumJsonConverter : JsonConverter + { + public override AccountChangeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountChangeIndicatorEnum.FromStringOrDefault(value) ?? new AccountChangeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountChangeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountChangeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountChangeIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since the shopper's account was last updated. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("accountChangeIndicator")] + public AccountChangeIndicatorEnum? AccountChangeIndicator { get { return this._AccountChangeIndicatorOption; } set { this._AccountChangeIndicatorOption = new(value); } } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.NotApplicable - notApplicable + /// + public static readonly AccountTypeEnum NotApplicable = new("notApplicable"); + + /// + /// AccountTypeEnum.Credit - credit + /// + public static readonly AccountTypeEnum Credit = new("credit"); + + /// + /// AccountTypeEnum.Debit - debit + /// + public static readonly AccountTypeEnum Debit = new("debit"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => AccountTypeEnum.NotApplicable, + "credit" => AccountTypeEnum.Credit, + "debit" => AccountTypeEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.NotApplicable) + return "notApplicable"; + + if (value == AccountTypeEnum.Credit) + return "credit"; + + if (value == AccountTypeEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Allowed values: * notApplicable * credit * debit + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(DeliveryAddressUsageIndicatorEnumJsonConverter))] + public class DeliveryAddressUsageIndicatorEnum : IEnum + { + /// + /// Returns the value of the DeliveryAddressUsageIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryAddressUsageIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly DeliveryAddressUsageIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// DeliveryAddressUsageIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// DeliveryAddressUsageIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// DeliveryAddressUsageIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly DeliveryAddressUsageIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private DeliveryAddressUsageIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryAddressUsageIndicatorEnum?(string? value) => value == null ? null : new DeliveryAddressUsageIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryAddressUsageIndicatorEnum? option) => option?.Value; + + public static bool operator ==(DeliveryAddressUsageIndicatorEnum? left, DeliveryAddressUsageIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryAddressUsageIndicatorEnum? left, DeliveryAddressUsageIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryAddressUsageIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryAddressUsageIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "thisTransaction" => DeliveryAddressUsageIndicatorEnum.ThisTransaction, + "lessThan30Days" => DeliveryAddressUsageIndicatorEnum.LessThan30Days, + "from30To60Days" => DeliveryAddressUsageIndicatorEnum.From30To60Days, + "moreThan60Days" => DeliveryAddressUsageIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryAddressUsageIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryAddressUsageIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == DeliveryAddressUsageIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == DeliveryAddressUsageIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == DeliveryAddressUsageIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryAddressUsageIndicatorEnum. + /// + public class DeliveryAddressUsageIndicatorEnumJsonConverter : JsonConverter + { + public override DeliveryAddressUsageIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryAddressUsageIndicatorEnum.FromStringOrDefault(value) ?? new DeliveryAddressUsageIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryAddressUsageIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryAddressUsageIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressUsageIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this delivery address was first used. Allowed values: * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("deliveryAddressUsageIndicator")] + public DeliveryAddressUsageIndicatorEnum? DeliveryAddressUsageIndicator { get { return this._DeliveryAddressUsageIndicatorOption; } set { this._DeliveryAddressUsageIndicatorOption = new(value); } } + + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(PasswordChangeIndicatorEnumJsonConverter))] + public class PasswordChangeIndicatorEnum : IEnum + { + /// + /// Returns the value of the PasswordChangeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// PasswordChangeIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly PasswordChangeIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// PasswordChangeIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly PasswordChangeIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// PasswordChangeIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly PasswordChangeIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// PasswordChangeIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly PasswordChangeIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// PasswordChangeIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly PasswordChangeIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private PasswordChangeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PasswordChangeIndicatorEnum?(string? value) => value == null ? null : new PasswordChangeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PasswordChangeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(PasswordChangeIndicatorEnum? left, PasswordChangeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PasswordChangeIndicatorEnum? left, PasswordChangeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PasswordChangeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PasswordChangeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => PasswordChangeIndicatorEnum.NotApplicable, + "thisTransaction" => PasswordChangeIndicatorEnum.ThisTransaction, + "lessThan30Days" => PasswordChangeIndicatorEnum.LessThan30Days, + "from30To60Days" => PasswordChangeIndicatorEnum.From30To60Days, + "moreThan60Days" => PasswordChangeIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PasswordChangeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == PasswordChangeIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == PasswordChangeIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == PasswordChangeIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == PasswordChangeIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == PasswordChangeIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing PasswordChangeIndicatorEnum. + /// + public class PasswordChangeIndicatorEnumJsonConverter : JsonConverter + { + public override PasswordChangeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PasswordChangeIndicatorEnum.FromStringOrDefault(value) ?? new PasswordChangeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PasswordChangeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PasswordChangeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordChangeIndicatorOption { get; private set; } + + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator when the shopper has changed their password. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("passwordChangeIndicator")] + public PasswordChangeIndicatorEnum? PasswordChangeIndicator { get { return this._PasswordChangeIndicatorOption; } set { this._PasswordChangeIndicatorOption = new(value); } } + + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonConverter(typeof(PaymentAccountIndicatorEnumJsonConverter))] + public class PaymentAccountIndicatorEnum : IEnum + { + /// + /// Returns the value of the PaymentAccountIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentAccountIndicatorEnum.NotApplicable - notApplicable + /// + public static readonly PaymentAccountIndicatorEnum NotApplicable = new("notApplicable"); + + /// + /// PaymentAccountIndicatorEnum.ThisTransaction - thisTransaction + /// + public static readonly PaymentAccountIndicatorEnum ThisTransaction = new("thisTransaction"); + + /// + /// PaymentAccountIndicatorEnum.LessThan30Days - lessThan30Days + /// + public static readonly PaymentAccountIndicatorEnum LessThan30Days = new("lessThan30Days"); + + /// + /// PaymentAccountIndicatorEnum.From30To60Days - from30To60Days + /// + public static readonly PaymentAccountIndicatorEnum From30To60Days = new("from30To60Days"); + + /// + /// PaymentAccountIndicatorEnum.MoreThan60Days - moreThan60Days + /// + public static readonly PaymentAccountIndicatorEnum MoreThan60Days = new("moreThan60Days"); + + private PaymentAccountIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentAccountIndicatorEnum?(string? value) => value == null ? null : new PaymentAccountIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentAccountIndicatorEnum? option) => option?.Value; + + public static bool operator ==(PaymentAccountIndicatorEnum? left, PaymentAccountIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentAccountIndicatorEnum? left, PaymentAccountIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentAccountIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentAccountIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "notApplicable" => PaymentAccountIndicatorEnum.NotApplicable, + "thisTransaction" => PaymentAccountIndicatorEnum.ThisTransaction, + "lessThan30Days" => PaymentAccountIndicatorEnum.LessThan30Days, + "from30To60Days" => PaymentAccountIndicatorEnum.From30To60Days, + "moreThan60Days" => PaymentAccountIndicatorEnum.MoreThan60Days, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentAccountIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == PaymentAccountIndicatorEnum.NotApplicable) + return "notApplicable"; + + if (value == PaymentAccountIndicatorEnum.ThisTransaction) + return "thisTransaction"; + + if (value == PaymentAccountIndicatorEnum.LessThan30Days) + return "lessThan30Days"; + + if (value == PaymentAccountIndicatorEnum.From30To60Days) + return "from30To60Days"; + + if (value == PaymentAccountIndicatorEnum.MoreThan60Days) + return "moreThan60Days"; + + return null; + } + + /// + /// JsonConverter for writing PaymentAccountIndicatorEnum. + /// + public class PaymentAccountIndicatorEnumJsonConverter : JsonConverter + { + public override PaymentAccountIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentAccountIndicatorEnum.FromStringOrDefault(value) ?? new PaymentAccountIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentAccountIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentAccountIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountIndicatorOption { get; private set; } + + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + /// + /// Indicator for the length of time since this payment method was added to this shopper's account. Allowed values: * notApplicable * thisTransaction * lessThan30Days * from30To60Days * moreThan60Days + [JsonPropertyName("paymentAccountIndicator")] + public PaymentAccountIndicatorEnum? PaymentAccountIndicator { get { return this._PaymentAccountIndicatorOption; } set { this._PaymentAccountIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountChangeDateOption { get; private set; } + + /// + /// Date when the shopper's account was last changed. + /// + /// Date when the shopper's account was last changed. + [JsonPropertyName("accountChangeDate")] + public DateTimeOffset? AccountChangeDate { get { return this._AccountChangeDateOption; } set { this._AccountChangeDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountCreationDateOption { get; private set; } + + /// + /// Date when the shopper's account was created. + /// + /// Date when the shopper's account was created. + [JsonPropertyName("accountCreationDate")] + public DateTimeOffset? AccountCreationDate { get { return this._AccountCreationDateOption; } set { this._AccountCreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddCardAttemptsDayOption { get; private set; } + + /// + /// Number of attempts the shopper tried to add a card to their account in the last day. + /// + /// Number of attempts the shopper tried to add a card to their account in the last day. + [JsonPropertyName("addCardAttemptsDay")] + public int? AddCardAttemptsDay { get { return this._AddCardAttemptsDayOption; } set { this._AddCardAttemptsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressUsageDateOption { get; private set; } + + /// + /// Date the selected delivery address was first used. + /// + /// Date the selected delivery address was first used. + [JsonPropertyName("deliveryAddressUsageDate")] + public DateTimeOffset? DeliveryAddressUsageDate { get { return this._DeliveryAddressUsageDateOption; } set { this._DeliveryAddressUsageDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// Shopper's home phone number (including the country code). + /// + /// Shopper's home phone number (including the country code). + [JsonPropertyName("homePhone")] + [Obsolete("Deprecated since Adyen Payment API v68. Use `ThreeDS2RequestData.homePhone` instead.")] + public string? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// Shopper's mobile phone number (including the country code). + /// + /// Shopper's mobile phone number (including the country code). + [JsonPropertyName("mobilePhone")] + [Obsolete("Deprecated since Adyen Payment API v68. Use `ThreeDS2RequestData.mobilePhone` instead.")] + public string? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PasswordChangeDateOption { get; private set; } + + /// + /// Date when the shopper last changed their password. + /// + /// Date when the shopper last changed their password. + [JsonPropertyName("passwordChangeDate")] + public DateTimeOffset? PasswordChangeDate { get { return this._PasswordChangeDateOption; } set { this._PasswordChangeDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PastTransactionsDayOption { get; private set; } + + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past 24 hours. + [JsonPropertyName("pastTransactionsDay")] + public int? PastTransactionsDay { get { return this._PastTransactionsDayOption; } set { this._PastTransactionsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PastTransactionsYearOption { get; private set; } + + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + /// + /// Number of all transactions (successful and abandoned) from this shopper in the past year. + [JsonPropertyName("pastTransactionsYear")] + public int? PastTransactionsYear { get { return this._PastTransactionsYearOption; } set { this._PastTransactionsYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountAgeOption { get; private set; } + + /// + /// Date this payment method was added to the shopper's account. + /// + /// Date this payment method was added to the shopper's account. + [JsonPropertyName("paymentAccountAge")] + public DateTimeOffset? PaymentAccountAge { get { return this._PaymentAccountAgeOption; } set { this._PaymentAccountAgeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurchasesLast6MonthsOption { get; private set; } + + /// + /// Number of successful purchases in the last six months. + /// + /// Number of successful purchases in the last six months. + [JsonPropertyName("purchasesLast6Months")] + public int? PurchasesLast6Months { get { return this._PurchasesLast6MonthsOption; } set { this._PurchasesLast6MonthsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuspiciousActivityOption { get; private set; } + + /// + /// Whether suspicious activity was recorded on this account. + /// + /// Whether suspicious activity was recorded on this account. + [JsonPropertyName("suspiciousActivity")] + public bool? SuspiciousActivity { get { return this._SuspiciousActivityOption; } set { this._SuspiciousActivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// Shopper's work phone number (including the country code). + /// + /// Shopper's work phone number (including the country code). + [JsonPropertyName("workPhone")] + [Obsolete("Deprecated since Adyen Payment API v68. Use `ThreeDS2RequestData.workPhone` instead.")] + public string? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountInfo {\n"); + sb.Append(" AccountAgeIndicator: ").Append(AccountAgeIndicator).Append("\n"); + sb.Append(" AccountChangeDate: ").Append(AccountChangeDate).Append("\n"); + sb.Append(" AccountChangeIndicator: ").Append(AccountChangeIndicator).Append("\n"); + sb.Append(" AccountCreationDate: ").Append(AccountCreationDate).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" AddCardAttemptsDay: ").Append(AddCardAttemptsDay).Append("\n"); + sb.Append(" DeliveryAddressUsageDate: ").Append(DeliveryAddressUsageDate).Append("\n"); + sb.Append(" DeliveryAddressUsageIndicator: ").Append(DeliveryAddressUsageIndicator).Append("\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" PasswordChangeDate: ").Append(PasswordChangeDate).Append("\n"); + sb.Append(" PasswordChangeIndicator: ").Append(PasswordChangeIndicator).Append("\n"); + sb.Append(" PastTransactionsDay: ").Append(PastTransactionsDay).Append("\n"); + sb.Append(" PastTransactionsYear: ").Append(PastTransactionsYear).Append("\n"); + sb.Append(" PaymentAccountAge: ").Append(PaymentAccountAge).Append("\n"); + sb.Append(" PaymentAccountIndicator: ").Append(PaymentAccountIndicator).Append("\n"); + sb.Append(" PurchasesLast6Months: ").Append(PurchasesLast6Months).Append("\n"); + sb.Append(" SuspiciousActivity: ").Append(SuspiciousActivity).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountInfoJsonConverter : JsonConverter + { + /// + /// The format to use to serialize AccountChangeDate. + /// + public static string AccountChangeDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize AccountCreationDate. + /// + public static string AccountCreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DeliveryAddressUsageDate. + /// + public static string DeliveryAddressUsageDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize PasswordChangeDate. + /// + public static string PasswordChangeDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize PaymentAccountAge. + /// + public static string PaymentAccountAgeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountAgeIndicator = default; + Option accountChangeDate = default; + Option accountChangeIndicator = default; + Option accountCreationDate = default; + Option accountType = default; + Option addCardAttemptsDay = default; + Option deliveryAddressUsageDate = default; + Option deliveryAddressUsageIndicator = default; + Option homePhone = default; + Option mobilePhone = default; + Option passwordChangeDate = default; + Option passwordChangeIndicator = default; + Option pastTransactionsDay = default; + Option pastTransactionsYear = default; + Option paymentAccountAge = default; + Option paymentAccountIndicator = default; + Option purchasesLast6Months = default; + Option suspiciousActivity = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountAgeIndicator": + string? accountAgeIndicatorRawValue = utf8JsonReader.GetString(); + accountAgeIndicator = new Option(AccountInfo.AccountAgeIndicatorEnum.FromStringOrDefault(accountAgeIndicatorRawValue)); + break; + case "accountChangeDate": + accountChangeDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "accountChangeIndicator": + string? accountChangeIndicatorRawValue = utf8JsonReader.GetString(); + accountChangeIndicator = new Option(AccountInfo.AccountChangeIndicatorEnum.FromStringOrDefault(accountChangeIndicatorRawValue)); + break; + case "accountCreationDate": + accountCreationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(AccountInfo.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "addCardAttemptsDay": + addCardAttemptsDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "deliveryAddressUsageDate": + deliveryAddressUsageDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deliveryAddressUsageIndicator": + string? deliveryAddressUsageIndicatorRawValue = utf8JsonReader.GetString(); + deliveryAddressUsageIndicator = new Option(AccountInfo.DeliveryAddressUsageIndicatorEnum.FromStringOrDefault(deliveryAddressUsageIndicatorRawValue)); + break; + case "homePhone": + homePhone = new Option(utf8JsonReader.GetString()!); + break; + case "mobilePhone": + mobilePhone = new Option(utf8JsonReader.GetString()!); + break; + case "passwordChangeDate": + passwordChangeDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "passwordChangeIndicator": + string? passwordChangeIndicatorRawValue = utf8JsonReader.GetString(); + passwordChangeIndicator = new Option(AccountInfo.PasswordChangeIndicatorEnum.FromStringOrDefault(passwordChangeIndicatorRawValue)); + break; + case "pastTransactionsDay": + pastTransactionsDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "pastTransactionsYear": + pastTransactionsYear = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "paymentAccountAge": + paymentAccountAge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "paymentAccountIndicator": + string? paymentAccountIndicatorRawValue = utf8JsonReader.GetString(); + paymentAccountIndicator = new Option(AccountInfo.PaymentAccountIndicatorEnum.FromStringOrDefault(paymentAccountIndicatorRawValue)); + break; + case "purchasesLast6Months": + purchasesLast6Months = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "suspiciousActivity": + suspiciousActivity = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "workPhone": + workPhone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AccountInfo(accountAgeIndicator, accountChangeDate, accountChangeIndicator, accountCreationDate, accountType, addCardAttemptsDay, deliveryAddressUsageDate, deliveryAddressUsageIndicator, homePhone, mobilePhone, passwordChangeDate, passwordChangeIndicator, pastTransactionsDay, pastTransactionsYear, paymentAccountAge, paymentAccountIndicator, purchasesLast6Months, suspiciousActivity, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountInfo accountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountInfo accountInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountInfo._AccountAgeIndicatorOption.IsSet && accountInfo.AccountAgeIndicator != null) + { + string? accountAgeIndicatorRawValue = AccountInfo.AccountAgeIndicatorEnum.ToJsonValue(accountInfo._AccountAgeIndicatorOption.Value!.Value); + writer.WriteString("accountAgeIndicator", accountAgeIndicatorRawValue); + } + + if (accountInfo._AccountChangeDateOption.IsSet) + writer.WriteString("accountChangeDate", accountInfo._AccountChangeDateOption.Value!.Value.ToString(AccountChangeDateFormat)); + + if (accountInfo._AccountChangeIndicatorOption.IsSet && accountInfo.AccountChangeIndicator != null) + { + string? accountChangeIndicatorRawValue = AccountInfo.AccountChangeIndicatorEnum.ToJsonValue(accountInfo._AccountChangeIndicatorOption.Value!.Value); + writer.WriteString("accountChangeIndicator", accountChangeIndicatorRawValue); + } + + if (accountInfo._AccountCreationDateOption.IsSet) + writer.WriteString("accountCreationDate", accountInfo._AccountCreationDateOption.Value!.Value.ToString(AccountCreationDateFormat)); + + if (accountInfo._AccountTypeOption.IsSet && accountInfo.AccountType != null) + { + string? accountTypeRawValue = AccountInfo.AccountTypeEnum.ToJsonValue(accountInfo._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (accountInfo._AddCardAttemptsDayOption.IsSet) + writer.WriteNumber("addCardAttemptsDay", accountInfo._AddCardAttemptsDayOption.Value!.Value); + + if (accountInfo._DeliveryAddressUsageDateOption.IsSet) + writer.WriteString("deliveryAddressUsageDate", accountInfo._DeliveryAddressUsageDateOption.Value!.Value.ToString(DeliveryAddressUsageDateFormat)); + + if (accountInfo._DeliveryAddressUsageIndicatorOption.IsSet && accountInfo.DeliveryAddressUsageIndicator != null) + { + string? deliveryAddressUsageIndicatorRawValue = AccountInfo.DeliveryAddressUsageIndicatorEnum.ToJsonValue(accountInfo._DeliveryAddressUsageIndicatorOption.Value!.Value); + writer.WriteString("deliveryAddressUsageIndicator", deliveryAddressUsageIndicatorRawValue); + } + + if (accountInfo._HomePhoneOption.IsSet) + if (accountInfo.HomePhone != null) + writer.WriteString("homePhone", accountInfo.HomePhone); + + if (accountInfo._MobilePhoneOption.IsSet) + if (accountInfo.MobilePhone != null) + writer.WriteString("mobilePhone", accountInfo.MobilePhone); + + if (accountInfo._PasswordChangeDateOption.IsSet) + writer.WriteString("passwordChangeDate", accountInfo._PasswordChangeDateOption.Value!.Value.ToString(PasswordChangeDateFormat)); + + if (accountInfo._PasswordChangeIndicatorOption.IsSet && accountInfo.PasswordChangeIndicator != null) + { + string? passwordChangeIndicatorRawValue = AccountInfo.PasswordChangeIndicatorEnum.ToJsonValue(accountInfo._PasswordChangeIndicatorOption.Value!.Value); + writer.WriteString("passwordChangeIndicator", passwordChangeIndicatorRawValue); + } + + if (accountInfo._PastTransactionsDayOption.IsSet) + writer.WriteNumber("pastTransactionsDay", accountInfo._PastTransactionsDayOption.Value!.Value); + + if (accountInfo._PastTransactionsYearOption.IsSet) + writer.WriteNumber("pastTransactionsYear", accountInfo._PastTransactionsYearOption.Value!.Value); + + if (accountInfo._PaymentAccountAgeOption.IsSet) + writer.WriteString("paymentAccountAge", accountInfo._PaymentAccountAgeOption.Value!.Value.ToString(PaymentAccountAgeFormat)); + + if (accountInfo._PaymentAccountIndicatorOption.IsSet && accountInfo.PaymentAccountIndicator != null) + { + string? paymentAccountIndicatorRawValue = AccountInfo.PaymentAccountIndicatorEnum.ToJsonValue(accountInfo._PaymentAccountIndicatorOption.Value!.Value); + writer.WriteString("paymentAccountIndicator", paymentAccountIndicatorRawValue); + } + + if (accountInfo._PurchasesLast6MonthsOption.IsSet) + writer.WriteNumber("purchasesLast6Months", accountInfo._PurchasesLast6MonthsOption.Value!.Value); + + if (accountInfo._SuspiciousActivityOption.IsSet) + writer.WriteBoolean("suspiciousActivity", accountInfo._SuspiciousActivityOption.Value!.Value); + + if (accountInfo._WorkPhoneOption.IsSet) + if (accountInfo.WorkPhone != null) + writer.WriteString("workPhone", accountInfo.WorkPhone); + } + } +} diff --git a/Adyen/Payment/Models/AcctInfo.cs b/Adyen/Payment/Models/AcctInfo.cs new file mode 100644 index 000000000..781106e91 --- /dev/null +++ b/Adyen/Payment/Models/AcctInfo.cs @@ -0,0 +1,1423 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AcctInfo. + /// + public partial class AcctInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + [JsonConstructor] + public AcctInfo(Option chAccAgeInd = default, Option chAccChange = default, Option chAccChangeInd = default, Option chAccPwChange = default, Option chAccPwChangeInd = default, Option chAccString = default, Option nbPurchaseAccount = default, Option paymentAccAge = default, Option paymentAccInd = default, Option provisionAttemptsDay = default, Option shipAddressUsage = default, Option shipAddressUsageInd = default, Option shipNameIndicator = default, Option suspiciousAccActivity = default, Option txnActivityDay = default, Option txnActivityYear = default) + { + _ChAccAgeIndOption = chAccAgeInd; + _ChAccChangeOption = chAccChange; + _ChAccChangeIndOption = chAccChangeInd; + _ChAccPwChangeOption = chAccPwChange; + _ChAccPwChangeIndOption = chAccPwChangeInd; + _ChAccStringOption = chAccString; + _NbPurchaseAccountOption = nbPurchaseAccount; + _PaymentAccAgeOption = paymentAccAge; + _PaymentAccIndOption = paymentAccInd; + _ProvisionAttemptsDayOption = provisionAttemptsDay; + _ShipAddressUsageOption = shipAddressUsage; + _ShipAddressUsageIndOption = shipAddressUsageInd; + _ShipNameIndicatorOption = shipNameIndicator; + _SuspiciousAccActivityOption = suspiciousAccActivity; + _TxnActivityDayOption = txnActivityDay; + _TxnActivityYearOption = txnActivityYear; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AcctInfo() + { + } + + partial void OnCreated(); + + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(ChAccAgeIndEnumJsonConverter))] + public class ChAccAgeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccAgeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccAgeIndEnum._01 - 01 + /// + public static readonly ChAccAgeIndEnum _01 = new("01"); + + /// + /// ChAccAgeIndEnum._02 - 02 + /// + public static readonly ChAccAgeIndEnum _02 = new("02"); + + /// + /// ChAccAgeIndEnum._03 - 03 + /// + public static readonly ChAccAgeIndEnum _03 = new("03"); + + /// + /// ChAccAgeIndEnum._04 - 04 + /// + public static readonly ChAccAgeIndEnum _04 = new("04"); + + /// + /// ChAccAgeIndEnum._05 - 05 + /// + public static readonly ChAccAgeIndEnum _05 = new("05"); + + private ChAccAgeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccAgeIndEnum?(string? value) => value == null ? null : new ChAccAgeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccAgeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccAgeIndEnum? left, ChAccAgeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccAgeIndEnum? left, ChAccAgeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccAgeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccAgeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccAgeIndEnum._01, + "02" => ChAccAgeIndEnum._02, + "03" => ChAccAgeIndEnum._03, + "04" => ChAccAgeIndEnum._04, + "05" => ChAccAgeIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccAgeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccAgeIndEnum._01) + return "01"; + + if (value == ChAccAgeIndEnum._02) + return "02"; + + if (value == ChAccAgeIndEnum._03) + return "03"; + + if (value == ChAccAgeIndEnum._04) + return "04"; + + if (value == ChAccAgeIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChAccAgeIndEnum. + /// + public class ChAccAgeIndEnumJsonConverter : JsonConverter + { + public override ChAccAgeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccAgeIndEnum.FromStringOrDefault(value) ?? new ChAccAgeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccAgeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccAgeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccAgeIndOption { get; private set; } + + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Length of time that the cardholder has had the account with the 3DS Requestor. Allowed values: * **01** — No account * **02** — Created during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("chAccAgeInd")] + public ChAccAgeIndEnum? ChAccAgeInd { get { return this._ChAccAgeIndOption; } set { this._ChAccAgeIndOption = new(value); } } + + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonConverter(typeof(ChAccChangeIndEnumJsonConverter))] + public class ChAccChangeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccChangeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccChangeIndEnum._01 - 01 + /// + public static readonly ChAccChangeIndEnum _01 = new("01"); + + /// + /// ChAccChangeIndEnum._02 - 02 + /// + public static readonly ChAccChangeIndEnum _02 = new("02"); + + /// + /// ChAccChangeIndEnum._03 - 03 + /// + public static readonly ChAccChangeIndEnum _03 = new("03"); + + /// + /// ChAccChangeIndEnum._04 - 04 + /// + public static readonly ChAccChangeIndEnum _04 = new("04"); + + private ChAccChangeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccChangeIndEnum?(string? value) => value == null ? null : new ChAccChangeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccChangeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccChangeIndEnum? left, ChAccChangeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccChangeIndEnum? left, ChAccChangeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccChangeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccChangeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccChangeIndEnum._01, + "02" => ChAccChangeIndEnum._02, + "03" => ChAccChangeIndEnum._03, + "04" => ChAccChangeIndEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccChangeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccChangeIndEnum._01) + return "01"; + + if (value == ChAccChangeIndEnum._02) + return "02"; + + if (value == ChAccChangeIndEnum._03) + return "03"; + + if (value == ChAccChangeIndEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ChAccChangeIndEnum. + /// + public class ChAccChangeIndEnumJsonConverter : JsonConverter + { + public override ChAccChangeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccChangeIndEnum.FromStringOrDefault(value) ?? new ChAccChangeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccChangeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccChangeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccChangeIndOption { get; private set; } + + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Length of time since the cardholder’s account information with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Allowed values: * **01** — Changed during this transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonPropertyName("chAccChangeInd")] + public ChAccChangeIndEnum? ChAccChangeInd { get { return this._ChAccChangeIndOption; } set { this._ChAccChangeIndOption = new(value); } } + + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(ChAccPwChangeIndEnumJsonConverter))] + public class ChAccPwChangeIndEnum : IEnum + { + /// + /// Returns the value of the ChAccPwChangeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ChAccPwChangeIndEnum._01 - 01 + /// + public static readonly ChAccPwChangeIndEnum _01 = new("01"); + + /// + /// ChAccPwChangeIndEnum._02 - 02 + /// + public static readonly ChAccPwChangeIndEnum _02 = new("02"); + + /// + /// ChAccPwChangeIndEnum._03 - 03 + /// + public static readonly ChAccPwChangeIndEnum _03 = new("03"); + + /// + /// ChAccPwChangeIndEnum._04 - 04 + /// + public static readonly ChAccPwChangeIndEnum _04 = new("04"); + + /// + /// ChAccPwChangeIndEnum._05 - 05 + /// + public static readonly ChAccPwChangeIndEnum _05 = new("05"); + + private ChAccPwChangeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChAccPwChangeIndEnum?(string? value) => value == null ? null : new ChAccPwChangeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChAccPwChangeIndEnum? option) => option?.Value; + + public static bool operator ==(ChAccPwChangeIndEnum? left, ChAccPwChangeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChAccPwChangeIndEnum? left, ChAccPwChangeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChAccPwChangeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChAccPwChangeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChAccPwChangeIndEnum._01, + "02" => ChAccPwChangeIndEnum._02, + "03" => ChAccPwChangeIndEnum._03, + "04" => ChAccPwChangeIndEnum._04, + "05" => ChAccPwChangeIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChAccPwChangeIndEnum? value) + { + if (value == null) + return null; + + if (value == ChAccPwChangeIndEnum._01) + return "01"; + + if (value == ChAccPwChangeIndEnum._02) + return "02"; + + if (value == ChAccPwChangeIndEnum._03) + return "03"; + + if (value == ChAccPwChangeIndEnum._04) + return "04"; + + if (value == ChAccPwChangeIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChAccPwChangeIndEnum. + /// + public class ChAccPwChangeIndEnumJsonConverter : JsonConverter + { + public override ChAccPwChangeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChAccPwChangeIndEnum.FromStringOrDefault(value) ?? new ChAccPwChangeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChAccPwChangeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChAccPwChangeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccPwChangeIndOption { get; private set; } + + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time since the cardholder’s account with the 3DS Requestor had a password change or account reset. Allowed values: * **01** — No change * **02** — Changed during this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("chAccPwChangeInd")] + public ChAccPwChangeIndEnum? ChAccPwChangeInd { get { return this._ChAccPwChangeIndOption; } set { this._ChAccPwChangeIndOption = new(value); } } + + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonConverter(typeof(PaymentAccIndEnumJsonConverter))] + public class PaymentAccIndEnum : IEnum + { + /// + /// Returns the value of the PaymentAccIndEnum. + /// + public string? Value { get; set; } + + /// + /// PaymentAccIndEnum._01 - 01 + /// + public static readonly PaymentAccIndEnum _01 = new("01"); + + /// + /// PaymentAccIndEnum._02 - 02 + /// + public static readonly PaymentAccIndEnum _02 = new("02"); + + /// + /// PaymentAccIndEnum._03 - 03 + /// + public static readonly PaymentAccIndEnum _03 = new("03"); + + /// + /// PaymentAccIndEnum._04 - 04 + /// + public static readonly PaymentAccIndEnum _04 = new("04"); + + /// + /// PaymentAccIndEnum._05 - 05 + /// + public static readonly PaymentAccIndEnum _05 = new("05"); + + private PaymentAccIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PaymentAccIndEnum?(string? value) => value == null ? null : new PaymentAccIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PaymentAccIndEnum? option) => option?.Value; + + public static bool operator ==(PaymentAccIndEnum? left, PaymentAccIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PaymentAccIndEnum? left, PaymentAccIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PaymentAccIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PaymentAccIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => PaymentAccIndEnum._01, + "02" => PaymentAccIndEnum._02, + "03" => PaymentAccIndEnum._03, + "04" => PaymentAccIndEnum._04, + "05" => PaymentAccIndEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PaymentAccIndEnum? value) + { + if (value == null) + return null; + + if (value == PaymentAccIndEnum._01) + return "01"; + + if (value == PaymentAccIndEnum._02) + return "02"; + + if (value == PaymentAccIndEnum._03) + return "03"; + + if (value == PaymentAccIndEnum._04) + return "04"; + + if (value == PaymentAccIndEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing PaymentAccIndEnum. + /// + public class PaymentAccIndEnumJsonConverter : JsonConverter + { + public override PaymentAccIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PaymentAccIndEnum.FromStringOrDefault(value) ?? new PaymentAccIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PaymentAccIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PaymentAccIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccIndOption { get; private set; } + + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + /// + /// Indicates the length of time that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Allowed values: * **01** — No account (guest checkout) * **02** — During this transaction * **03** — Less than 30 days * **04** — 30–60 days * **05** — More than 60 days + [JsonPropertyName("paymentAccInd")] + public PaymentAccIndEnum? PaymentAccInd { get { return this._PaymentAccIndOption; } set { this._PaymentAccIndOption = new(value); } } + + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonConverter(typeof(ShipAddressUsageIndEnumJsonConverter))] + public class ShipAddressUsageIndEnum : IEnum + { + /// + /// Returns the value of the ShipAddressUsageIndEnum. + /// + public string? Value { get; set; } + + /// + /// ShipAddressUsageIndEnum._01 - 01 + /// + public static readonly ShipAddressUsageIndEnum _01 = new("01"); + + /// + /// ShipAddressUsageIndEnum._02 - 02 + /// + public static readonly ShipAddressUsageIndEnum _02 = new("02"); + + /// + /// ShipAddressUsageIndEnum._03 - 03 + /// + public static readonly ShipAddressUsageIndEnum _03 = new("03"); + + /// + /// ShipAddressUsageIndEnum._04 - 04 + /// + public static readonly ShipAddressUsageIndEnum _04 = new("04"); + + private ShipAddressUsageIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShipAddressUsageIndEnum?(string? value) => value == null ? null : new ShipAddressUsageIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShipAddressUsageIndEnum? option) => option?.Value; + + public static bool operator ==(ShipAddressUsageIndEnum? left, ShipAddressUsageIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShipAddressUsageIndEnum? left, ShipAddressUsageIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShipAddressUsageIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShipAddressUsageIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ShipAddressUsageIndEnum._01, + "02" => ShipAddressUsageIndEnum._02, + "03" => ShipAddressUsageIndEnum._03, + "04" => ShipAddressUsageIndEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShipAddressUsageIndEnum? value) + { + if (value == null) + return null; + + if (value == ShipAddressUsageIndEnum._01) + return "01"; + + if (value == ShipAddressUsageIndEnum._02) + return "02"; + + if (value == ShipAddressUsageIndEnum._03) + return "03"; + + if (value == ShipAddressUsageIndEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ShipAddressUsageIndEnum. + /// + public class ShipAddressUsageIndEnumJsonConverter : JsonConverter + { + public override ShipAddressUsageIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShipAddressUsageIndEnum.FromStringOrDefault(value) ?? new ShipAddressUsageIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShipAddressUsageIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShipAddressUsageIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipAddressUsageIndOption { get; private set; } + + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + /// + /// Indicates when the shipping address used for this transaction was first used with the 3DS Requestor. Allowed values: * **01** — This transaction * **02** — Less than 30 days * **03** — 30–60 days * **04** — More than 60 days + [JsonPropertyName("shipAddressUsageInd")] + public ShipAddressUsageIndEnum? ShipAddressUsageInd { get { return this._ShipAddressUsageIndOption; } set { this._ShipAddressUsageIndOption = new(value); } } + + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + [JsonConverter(typeof(ShipNameIndicatorEnumJsonConverter))] + public class ShipNameIndicatorEnum : IEnum + { + /// + /// Returns the value of the ShipNameIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ShipNameIndicatorEnum._01 - 01 + /// + public static readonly ShipNameIndicatorEnum _01 = new("01"); + + /// + /// ShipNameIndicatorEnum._02 - 02 + /// + public static readonly ShipNameIndicatorEnum _02 = new("02"); + + private ShipNameIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShipNameIndicatorEnum?(string? value) => value == null ? null : new ShipNameIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShipNameIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ShipNameIndicatorEnum? left, ShipNameIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShipNameIndicatorEnum? left, ShipNameIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShipNameIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShipNameIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ShipNameIndicatorEnum._01, + "02" => ShipNameIndicatorEnum._02, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShipNameIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ShipNameIndicatorEnum._01) + return "01"; + + if (value == ShipNameIndicatorEnum._02) + return "02"; + + return null; + } + + /// + /// JsonConverter for writing ShipNameIndicatorEnum. + /// + public class ShipNameIndicatorEnumJsonConverter : JsonConverter + { + public override ShipNameIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShipNameIndicatorEnum.FromStringOrDefault(value) ?? new ShipNameIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShipNameIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShipNameIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipNameIndicatorOption { get; private set; } + + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + /// + /// Indicates if the Cardholder Name on the account is identical to the shipping Name used for this transaction. Allowed values: * **01** — Account Name identical to shipping Name * **02** — Account Name different to shipping Name + [JsonPropertyName("shipNameIndicator")] + public ShipNameIndicatorEnum? ShipNameIndicator { get { return this._ShipNameIndicatorOption; } set { this._ShipNameIndicatorOption = new(value); } } + + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + [JsonConverter(typeof(SuspiciousAccActivityEnumJsonConverter))] + public class SuspiciousAccActivityEnum : IEnum + { + /// + /// Returns the value of the SuspiciousAccActivityEnum. + /// + public string? Value { get; set; } + + /// + /// SuspiciousAccActivityEnum._01 - 01 + /// + public static readonly SuspiciousAccActivityEnum _01 = new("01"); + + /// + /// SuspiciousAccActivityEnum._02 - 02 + /// + public static readonly SuspiciousAccActivityEnum _02 = new("02"); + + private SuspiciousAccActivityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SuspiciousAccActivityEnum?(string? value) => value == null ? null : new SuspiciousAccActivityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SuspiciousAccActivityEnum? option) => option?.Value; + + public static bool operator ==(SuspiciousAccActivityEnum? left, SuspiciousAccActivityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SuspiciousAccActivityEnum? left, SuspiciousAccActivityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SuspiciousAccActivityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SuspiciousAccActivityEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => SuspiciousAccActivityEnum._01, + "02" => SuspiciousAccActivityEnum._02, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SuspiciousAccActivityEnum? value) + { + if (value == null) + return null; + + if (value == SuspiciousAccActivityEnum._01) + return "01"; + + if (value == SuspiciousAccActivityEnum._02) + return "02"; + + return null; + } + + /// + /// JsonConverter for writing SuspiciousAccActivityEnum. + /// + public class SuspiciousAccActivityEnumJsonConverter : JsonConverter + { + public override SuspiciousAccActivityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SuspiciousAccActivityEnum.FromStringOrDefault(value) ?? new SuspiciousAccActivityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SuspiciousAccActivityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SuspiciousAccActivityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SuspiciousAccActivityOption { get; private set; } + + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + /// + /// Indicates whether the 3DS Requestor has experienced suspicious activity (including previous fraud) on the cardholder account. Allowed values: * **01** — No suspicious activity has been observed * **02** — Suspicious activity has been observed + [JsonPropertyName("suspiciousAccActivity")] + public SuspiciousAccActivityEnum? SuspiciousAccActivity { get { return this._SuspiciousAccActivityOption; } set { this._SuspiciousAccActivityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccChangeOption { get; private set; } + + /// + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + /// + /// Date that the cardholder’s account with the 3DS Requestor was last changed, including Billing or Shipping address, new payment account, or new user(s) added. Format: **YYYYMMDD** + [JsonPropertyName("chAccChange")] + public string? ChAccChange { get { return this._ChAccChangeOption; } set { this._ChAccChangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccPwChangeOption { get; private set; } + + /// + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + /// + /// Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Format: **YYYYMMDD** + [JsonPropertyName("chAccPwChange")] + public string? ChAccPwChange { get { return this._ChAccPwChangeOption; } set { this._ChAccPwChangeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChAccStringOption { get; private set; } + + /// + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// Date that the cardholder opened the account with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("chAccString")] + public string? ChAccString { get { return this._ChAccStringOption; } set { this._ChAccStringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NbPurchaseAccountOption { get; private set; } + + /// + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + /// + /// Number of purchases with this cardholder account during the previous six months. Max length: 4 characters. + [JsonPropertyName("nbPurchaseAccount")] + public string? NbPurchaseAccount { get { return this._NbPurchaseAccountOption; } set { this._NbPurchaseAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccAgeOption { get; private set; } + + /// + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// String that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("paymentAccAge")] + public string? PaymentAccAge { get { return this._PaymentAccAgeOption; } set { this._PaymentAccAgeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProvisionAttemptsDayOption { get; private set; } + + /// + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + /// + /// Number of Add Card attempts in the last 24 hours. Max length: 3 characters. + [JsonPropertyName("provisionAttemptsDay")] + public string? ProvisionAttemptsDay { get { return this._ProvisionAttemptsDayOption; } set { this._ProvisionAttemptsDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipAddressUsageOption { get; private set; } + + /// + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + /// + /// String when the shipping address used for this transaction was first used with the 3DS Requestor. Format: **YYYYMMDD** + [JsonPropertyName("shipAddressUsage")] + public string? ShipAddressUsage { get { return this._ShipAddressUsageOption; } set { this._ShipAddressUsageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TxnActivityDayOption { get; private set; } + + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours. Max length: 3 characters. + [JsonPropertyName("txnActivityDay")] + public string? TxnActivityDay { get { return this._TxnActivityDayOption; } set { this._TxnActivityDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TxnActivityYearOption { get; private set; } + + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + /// + /// Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year. Max length: 3 characters. + [JsonPropertyName("txnActivityYear")] + public string? TxnActivityYear { get { return this._TxnActivityYearOption; } set { this._TxnActivityYearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AcctInfo {\n"); + sb.Append(" ChAccAgeInd: ").Append(ChAccAgeInd).Append("\n"); + sb.Append(" ChAccChange: ").Append(ChAccChange).Append("\n"); + sb.Append(" ChAccChangeInd: ").Append(ChAccChangeInd).Append("\n"); + sb.Append(" ChAccPwChange: ").Append(ChAccPwChange).Append("\n"); + sb.Append(" ChAccPwChangeInd: ").Append(ChAccPwChangeInd).Append("\n"); + sb.Append(" ChAccString: ").Append(ChAccString).Append("\n"); + sb.Append(" NbPurchaseAccount: ").Append(NbPurchaseAccount).Append("\n"); + sb.Append(" PaymentAccAge: ").Append(PaymentAccAge).Append("\n"); + sb.Append(" PaymentAccInd: ").Append(PaymentAccInd).Append("\n"); + sb.Append(" ProvisionAttemptsDay: ").Append(ProvisionAttemptsDay).Append("\n"); + sb.Append(" ShipAddressUsage: ").Append(ShipAddressUsage).Append("\n"); + sb.Append(" ShipAddressUsageInd: ").Append(ShipAddressUsageInd).Append("\n"); + sb.Append(" ShipNameIndicator: ").Append(ShipNameIndicator).Append("\n"); + sb.Append(" SuspiciousAccActivity: ").Append(SuspiciousAccActivity).Append("\n"); + sb.Append(" TxnActivityDay: ").Append(TxnActivityDay).Append("\n"); + sb.Append(" TxnActivityYear: ").Append(TxnActivityYear).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // TxnActivityDay (string) maxLength + if (this.TxnActivityDay != null && this.TxnActivityDay.Length > 3) + { + yield return new ValidationResult("Invalid value for TxnActivityDay, length must be less than 3.", new [] { "TxnActivityDay" }); + } + + // TxnActivityYear (string) maxLength + if (this.TxnActivityYear != null && this.TxnActivityYear.Length > 3) + { + yield return new ValidationResult("Invalid value for TxnActivityYear, length must be less than 3.", new [] { "TxnActivityYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AcctInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AcctInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option chAccAgeInd = default; + Option chAccChange = default; + Option chAccChangeInd = default; + Option chAccPwChange = default; + Option chAccPwChangeInd = default; + Option chAccString = default; + Option nbPurchaseAccount = default; + Option paymentAccAge = default; + Option paymentAccInd = default; + Option provisionAttemptsDay = default; + Option shipAddressUsage = default; + Option shipAddressUsageInd = default; + Option shipNameIndicator = default; + Option suspiciousAccActivity = default; + Option txnActivityDay = default; + Option txnActivityYear = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "chAccAgeInd": + string? chAccAgeIndRawValue = utf8JsonReader.GetString(); + chAccAgeInd = new Option(AcctInfo.ChAccAgeIndEnum.FromStringOrDefault(chAccAgeIndRawValue)); + break; + case "chAccChange": + chAccChange = new Option(utf8JsonReader.GetString()!); + break; + case "chAccChangeInd": + string? chAccChangeIndRawValue = utf8JsonReader.GetString(); + chAccChangeInd = new Option(AcctInfo.ChAccChangeIndEnum.FromStringOrDefault(chAccChangeIndRawValue)); + break; + case "chAccPwChange": + chAccPwChange = new Option(utf8JsonReader.GetString()!); + break; + case "chAccPwChangeInd": + string? chAccPwChangeIndRawValue = utf8JsonReader.GetString(); + chAccPwChangeInd = new Option(AcctInfo.ChAccPwChangeIndEnum.FromStringOrDefault(chAccPwChangeIndRawValue)); + break; + case "chAccString": + chAccString = new Option(utf8JsonReader.GetString()!); + break; + case "nbPurchaseAccount": + nbPurchaseAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccAge": + paymentAccAge = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccInd": + string? paymentAccIndRawValue = utf8JsonReader.GetString(); + paymentAccInd = new Option(AcctInfo.PaymentAccIndEnum.FromStringOrDefault(paymentAccIndRawValue)); + break; + case "provisionAttemptsDay": + provisionAttemptsDay = new Option(utf8JsonReader.GetString()!); + break; + case "shipAddressUsage": + shipAddressUsage = new Option(utf8JsonReader.GetString()!); + break; + case "shipAddressUsageInd": + string? shipAddressUsageIndRawValue = utf8JsonReader.GetString(); + shipAddressUsageInd = new Option(AcctInfo.ShipAddressUsageIndEnum.FromStringOrDefault(shipAddressUsageIndRawValue)); + break; + case "shipNameIndicator": + string? shipNameIndicatorRawValue = utf8JsonReader.GetString(); + shipNameIndicator = new Option(AcctInfo.ShipNameIndicatorEnum.FromStringOrDefault(shipNameIndicatorRawValue)); + break; + case "suspiciousAccActivity": + string? suspiciousAccActivityRawValue = utf8JsonReader.GetString(); + suspiciousAccActivity = new Option(AcctInfo.SuspiciousAccActivityEnum.FromStringOrDefault(suspiciousAccActivityRawValue)); + break; + case "txnActivityDay": + txnActivityDay = new Option(utf8JsonReader.GetString()!); + break; + case "txnActivityYear": + txnActivityYear = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AcctInfo(chAccAgeInd, chAccChange, chAccChangeInd, chAccPwChange, chAccPwChangeInd, chAccString, nbPurchaseAccount, paymentAccAge, paymentAccInd, provisionAttemptsDay, shipAddressUsage, shipAddressUsageInd, shipNameIndicator, suspiciousAccActivity, txnActivityDay, txnActivityYear); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AcctInfo acctInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, acctInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AcctInfo acctInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (acctInfo._ChAccAgeIndOption.IsSet && acctInfo.ChAccAgeInd != null) + { + string? chAccAgeIndRawValue = AcctInfo.ChAccAgeIndEnum.ToJsonValue(acctInfo._ChAccAgeIndOption.Value!.Value); + writer.WriteString("chAccAgeInd", chAccAgeIndRawValue); + } + + if (acctInfo._ChAccChangeOption.IsSet) + if (acctInfo.ChAccChange != null) + writer.WriteString("chAccChange", acctInfo.ChAccChange); + + if (acctInfo._ChAccChangeIndOption.IsSet && acctInfo.ChAccChangeInd != null) + { + string? chAccChangeIndRawValue = AcctInfo.ChAccChangeIndEnum.ToJsonValue(acctInfo._ChAccChangeIndOption.Value!.Value); + writer.WriteString("chAccChangeInd", chAccChangeIndRawValue); + } + + if (acctInfo._ChAccPwChangeOption.IsSet) + if (acctInfo.ChAccPwChange != null) + writer.WriteString("chAccPwChange", acctInfo.ChAccPwChange); + + if (acctInfo._ChAccPwChangeIndOption.IsSet && acctInfo.ChAccPwChangeInd != null) + { + string? chAccPwChangeIndRawValue = AcctInfo.ChAccPwChangeIndEnum.ToJsonValue(acctInfo._ChAccPwChangeIndOption.Value!.Value); + writer.WriteString("chAccPwChangeInd", chAccPwChangeIndRawValue); + } + + if (acctInfo._ChAccStringOption.IsSet) + if (acctInfo.ChAccString != null) + writer.WriteString("chAccString", acctInfo.ChAccString); + + if (acctInfo._NbPurchaseAccountOption.IsSet) + if (acctInfo.NbPurchaseAccount != null) + writer.WriteString("nbPurchaseAccount", acctInfo.NbPurchaseAccount); + + if (acctInfo._PaymentAccAgeOption.IsSet) + if (acctInfo.PaymentAccAge != null) + writer.WriteString("paymentAccAge", acctInfo.PaymentAccAge); + + if (acctInfo._PaymentAccIndOption.IsSet && acctInfo.PaymentAccInd != null) + { + string? paymentAccIndRawValue = AcctInfo.PaymentAccIndEnum.ToJsonValue(acctInfo._PaymentAccIndOption.Value!.Value); + writer.WriteString("paymentAccInd", paymentAccIndRawValue); + } + + if (acctInfo._ProvisionAttemptsDayOption.IsSet) + if (acctInfo.ProvisionAttemptsDay != null) + writer.WriteString("provisionAttemptsDay", acctInfo.ProvisionAttemptsDay); + + if (acctInfo._ShipAddressUsageOption.IsSet) + if (acctInfo.ShipAddressUsage != null) + writer.WriteString("shipAddressUsage", acctInfo.ShipAddressUsage); + + if (acctInfo._ShipAddressUsageIndOption.IsSet && acctInfo.ShipAddressUsageInd != null) + { + string? shipAddressUsageIndRawValue = AcctInfo.ShipAddressUsageIndEnum.ToJsonValue(acctInfo._ShipAddressUsageIndOption.Value!.Value); + writer.WriteString("shipAddressUsageInd", shipAddressUsageIndRawValue); + } + + if (acctInfo._ShipNameIndicatorOption.IsSet && acctInfo.ShipNameIndicator != null) + { + string? shipNameIndicatorRawValue = AcctInfo.ShipNameIndicatorEnum.ToJsonValue(acctInfo._ShipNameIndicatorOption.Value!.Value); + writer.WriteString("shipNameIndicator", shipNameIndicatorRawValue); + } + + if (acctInfo._SuspiciousAccActivityOption.IsSet && acctInfo.SuspiciousAccActivity != null) + { + string? suspiciousAccActivityRawValue = AcctInfo.SuspiciousAccActivityEnum.ToJsonValue(acctInfo._SuspiciousAccActivityOption.Value!.Value); + writer.WriteString("suspiciousAccActivity", suspiciousAccActivityRawValue); + } + + if (acctInfo._TxnActivityDayOption.IsSet) + if (acctInfo.TxnActivityDay != null) + writer.WriteString("txnActivityDay", acctInfo.TxnActivityDay); + + if (acctInfo._TxnActivityYearOption.IsSet) + if (acctInfo.TxnActivityYear != null) + writer.WriteString("txnActivityYear", acctInfo.TxnActivityYear); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalData3DSecure.cs b/Adyen/Payment/Models/AdditionalData3DSecure.cs new file mode 100644 index 000000000..ff2f363f6 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalData3DSecure.cs @@ -0,0 +1,435 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalData3DSecure. + /// + public partial class AdditionalData3DSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + [JsonConstructor] + public AdditionalData3DSecure(Option allow3DS2 = default, Option challengeWindowSize = default, Option executeThreeD = default, Option mpiImplementationType = default, Option scaExemption = default, Option threeDSVersion = default) + { + _Allow3DS2Option = allow3DS2; + _ChallengeWindowSizeOption = challengeWindowSize; + _ExecuteThreeDOption = executeThreeD; + _MpiImplementationTypeOption = mpiImplementationType; + _ScaExemptionOption = scaExemption; + _ThreeDSVersionOption = threeDSVersion; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalData3DSecure() + { + } + + partial void OnCreated(); + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonConverter(typeof(ChallengeWindowSizeEnumJsonConverter))] + public class ChallengeWindowSizeEnum : IEnum + { + /// + /// Returns the value of the ChallengeWindowSizeEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeWindowSizeEnum._01 - 01 + /// + public static readonly ChallengeWindowSizeEnum _01 = new("01"); + + /// + /// ChallengeWindowSizeEnum._02 - 02 + /// + public static readonly ChallengeWindowSizeEnum _02 = new("02"); + + /// + /// ChallengeWindowSizeEnum._03 - 03 + /// + public static readonly ChallengeWindowSizeEnum _03 = new("03"); + + /// + /// ChallengeWindowSizeEnum._04 - 04 + /// + public static readonly ChallengeWindowSizeEnum _04 = new("04"); + + /// + /// ChallengeWindowSizeEnum._05 - 05 + /// + public static readonly ChallengeWindowSizeEnum _05 = new("05"); + + private ChallengeWindowSizeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeWindowSizeEnum?(string? value) => value == null ? null : new ChallengeWindowSizeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeWindowSizeEnum? option) => option?.Value; + + public static bool operator ==(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeWindowSizeEnum? left, ChallengeWindowSizeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeWindowSizeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeWindowSizeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeWindowSizeEnum._01, + "02" => ChallengeWindowSizeEnum._02, + "03" => ChallengeWindowSizeEnum._03, + "04" => ChallengeWindowSizeEnum._04, + "05" => ChallengeWindowSizeEnum._05, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeWindowSizeEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeWindowSizeEnum._01) + return "01"; + + if (value == ChallengeWindowSizeEnum._02) + return "02"; + + if (value == ChallengeWindowSizeEnum._03) + return "03"; + + if (value == ChallengeWindowSizeEnum._04) + return "04"; + + if (value == ChallengeWindowSizeEnum._05) + return "05"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeWindowSizeEnum. + /// + public class ChallengeWindowSizeEnumJsonConverter : JsonConverter + { + public override ChallengeWindowSizeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeWindowSizeEnum.FromStringOrDefault(value) ?? new ChallengeWindowSizeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeWindowSizeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeWindowSizeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeWindowSizeOption { get; private set; } + + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + /// + /// Dimensions of the 3DS2 challenge window to be displayed to the cardholder. Possible values: * **01** - size of 250x400 * **02** - size of 390x400 * **03** - size of 500x600 * **04** - size of 600x400 * **05** - Fullscreen + [JsonPropertyName("challengeWindowSize")] + public ChallengeWindowSizeEnum? ChallengeWindowSize { get { return this._ChallengeWindowSizeOption; } set { this._ChallengeWindowSizeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Allow3DS2Option { get; private set; } + + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + /// + /// Indicates if you are able to process 3D Secure 2 transactions natively on your payment page. Send this parameter when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/online-payments/3d-secure/native-3ds2). > This parameter only indicates readiness to support native 3D Secure 2 authentication. To specify if you _want_ to perform 3D Secure, use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) or send the `executeThreeD` parameter. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen selects redirect or native authentication based on your configuration to optimize authorization rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen offers redirect 3D Secure 2 authentication instead, based on your configuration. + [JsonPropertyName("allow3DS2")] + public string? Allow3DS2 { get { return this._Allow3DS2Option; } set { this._Allow3DS2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecuteThreeDOption { get; private set; } + + /// + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + /// + /// Indicates if you want to perform 3D Secure authentication on a transaction. > Alternatively, you can use [Dynamic 3D Secure](/risk-management/dynamic-3d-secure) to configure rules for applying 3D Secure. Possible values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. Note that this setting results in refusals if the issuer mandates 3D Secure because of the PSD2 directive or other, national regulations. + [JsonPropertyName("executeThreeD")] + public string? ExecuteThreeD { get { return this._ExecuteThreeDOption; } set { this._ExecuteThreeDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiImplementationTypeOption { get; private set; } + + /// + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + /// + /// In case of Secure+, this field must be set to **CUPSecurePlus**. + [JsonPropertyName("mpiImplementationType")] + public string? MpiImplementationType { get { return this._MpiImplementationTypeOption; } set { this._MpiImplementationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaExemptionOption { get; private set; } + + /// + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// + /// Indicates the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + [JsonPropertyName("scaExemption")] + public string? ScaExemption { get { return this._ScaExemptionOption; } set { this._ScaExemptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + /// + /// Indicates your preference for the 3D Secure version. > If you use this parameter, you override the checks from Adyen's Authentication Engine. We recommend to use this field only if you have an extensive knowledge of 3D Secure. Possible values: * **2.1.0**: Apply 3D Secure version 2.1.0. * **2.2.0**: Apply 3D Secure version 2.2.0. If the issuer does not support version 2.2.0, we will fall back to 2.1.0. The following rules apply: * If you prefer 2.1.0 or 2.2.0 but we receive a negative `transStatus` in the `ARes`, we will apply the fallback policy configured in your account. * If you the BIN is not enrolled, you will receive an error. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalData3DSecure {\n"); + sb.Append(" Allow3DS2: ").Append(Allow3DS2).Append("\n"); + sb.Append(" ChallengeWindowSize: ").Append(ChallengeWindowSize).Append("\n"); + sb.Append(" ExecuteThreeD: ").Append(ExecuteThreeD).Append("\n"); + sb.Append(" MpiImplementationType: ").Append(MpiImplementationType).Append("\n"); + sb.Append(" ScaExemption: ").Append(ScaExemption).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalData3DSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalData3DSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allow3DS2 = default; + Option challengeWindowSize = default; + Option executeThreeD = default; + Option mpiImplementationType = default; + Option scaExemption = default; + Option threeDSVersion = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allow3DS2": + allow3DS2 = new Option(utf8JsonReader.GetString()!); + break; + case "challengeWindowSize": + string? challengeWindowSizeRawValue = utf8JsonReader.GetString(); + challengeWindowSize = new Option(AdditionalData3DSecure.ChallengeWindowSizeEnum.FromStringOrDefault(challengeWindowSizeRawValue)); + break; + case "executeThreeD": + executeThreeD = new Option(utf8JsonReader.GetString()!); + break; + case "mpiImplementationType": + mpiImplementationType = new Option(utf8JsonReader.GetString()!); + break; + case "scaExemption": + scaExemption = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalData3DSecure(allow3DS2, challengeWindowSize, executeThreeD, mpiImplementationType, scaExemption, threeDSVersion); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalData3DSecure additionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalData3DSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalData3DSecure additionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalData3DSecure._Allow3DS2Option.IsSet) + if (additionalData3DSecure.Allow3DS2 != null) + writer.WriteString("allow3DS2", additionalData3DSecure.Allow3DS2); + + if (additionalData3DSecure._ChallengeWindowSizeOption.IsSet && additionalData3DSecure.ChallengeWindowSize != null) + { + string? challengeWindowSizeRawValue = AdditionalData3DSecure.ChallengeWindowSizeEnum.ToJsonValue(additionalData3DSecure._ChallengeWindowSizeOption.Value!.Value); + writer.WriteString("challengeWindowSize", challengeWindowSizeRawValue); + } + + if (additionalData3DSecure._ExecuteThreeDOption.IsSet) + if (additionalData3DSecure.ExecuteThreeD != null) + writer.WriteString("executeThreeD", additionalData3DSecure.ExecuteThreeD); + + if (additionalData3DSecure._MpiImplementationTypeOption.IsSet) + if (additionalData3DSecure.MpiImplementationType != null) + writer.WriteString("mpiImplementationType", additionalData3DSecure.MpiImplementationType); + + if (additionalData3DSecure._ScaExemptionOption.IsSet) + if (additionalData3DSecure.ScaExemption != null) + writer.WriteString("scaExemption", additionalData3DSecure.ScaExemption); + + if (additionalData3DSecure._ThreeDSVersionOption.IsSet) + if (additionalData3DSecure.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", additionalData3DSecure.ThreeDSVersion); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataAirline.cs b/Adyen/Payment/Models/AdditionalDataAirline.cs new file mode 100644 index 000000000..bef0ac01a --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataAirline.cs @@ -0,0 +1,871 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataAirline. + /// + public partial class AdditionalDataAirline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + [JsonConstructor] + public AdditionalDataAirline(string airlinePassengerName, Option airlineAgencyInvoiceNumber = default, Option airlineAgencyPlanName = default, Option airlineAirlineCode = default, Option airlineAirlineDesignatorCode = default, Option airlineBoardingFee = default, Option airlineComputerizedReservationSystem = default, Option airlineCustomerReferenceNumber = default, Option airlineDocumentType = default, Option airlineFlightDate = default, Option airlineIssueDate = default, Option airlineLegCarrierCode = default, Option airlineLegClassOfTravel = default, Option airlineLegDateOfTravel = default, Option airlineLegDepartAirport = default, Option airlineLegDepartTax = default, Option airlineLegDestinationCode = default, Option airlineLegFareBaseCode = default, Option airlineLegFlightNumber = default, Option airlineLegStopOverCode = default, Option airlinePassengerDateOfBirth = default, Option airlinePassengerFirstName = default, Option airlinePassengerLastName = default, Option airlinePassengerPhoneNumber = default, Option airlinePassengerTravellerType = default, Option airlineTicketIssueAddress = default, Option airlineTicketNumber = default, Option airlineTravelAgencyCode = default, Option airlineTravelAgencyName = default) + { + AirlinePassengerName = airlinePassengerName; + _AirlineAgencyInvoiceNumberOption = airlineAgencyInvoiceNumber; + _AirlineAgencyPlanNameOption = airlineAgencyPlanName; + _AirlineAirlineCodeOption = airlineAirlineCode; + _AirlineAirlineDesignatorCodeOption = airlineAirlineDesignatorCode; + _AirlineBoardingFeeOption = airlineBoardingFee; + _AirlineComputerizedReservationSystemOption = airlineComputerizedReservationSystem; + _AirlineCustomerReferenceNumberOption = airlineCustomerReferenceNumber; + _AirlineDocumentTypeOption = airlineDocumentType; + _AirlineFlightDateOption = airlineFlightDate; + _AirlineIssueDateOption = airlineIssueDate; + _AirlineLegCarrierCodeOption = airlineLegCarrierCode; + _AirlineLegClassOfTravelOption = airlineLegClassOfTravel; + _AirlineLegDateOfTravelOption = airlineLegDateOfTravel; + _AirlineLegDepartAirportOption = airlineLegDepartAirport; + _AirlineLegDepartTaxOption = airlineLegDepartTax; + _AirlineLegDestinationCodeOption = airlineLegDestinationCode; + _AirlineLegFareBaseCodeOption = airlineLegFareBaseCode; + _AirlineLegFlightNumberOption = airlineLegFlightNumber; + _AirlineLegStopOverCodeOption = airlineLegStopOverCode; + _AirlinePassengerDateOfBirthOption = airlinePassengerDateOfBirth; + _AirlinePassengerFirstNameOption = airlinePassengerFirstName; + _AirlinePassengerLastNameOption = airlinePassengerLastName; + _AirlinePassengerPhoneNumberOption = airlinePassengerPhoneNumber; + _AirlinePassengerTravellerTypeOption = airlinePassengerTravellerType; + _AirlineTicketIssueAddressOption = airlineTicketIssueAddress; + _AirlineTicketNumberOption = airlineTicketNumber; + _AirlineTravelAgencyCodeOption = airlineTravelAgencyCode; + _AirlineTravelAgencyNameOption = airlineTravelAgencyName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataAirline() + { + } + + partial void OnCreated(); + + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + /// + /// The passenger's name, initials, and title. * Format: last name + first name or initials + title * Example: *FLYER / MARY MS* * minLength: 1 character * maxLength: 20 characters * If you send more than 20 characters, the name is truncated * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.passenger_name")] + public string AirlinePassengerName { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAgencyInvoiceNumberOption { get; private set; } + + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + /// + /// The reference number for the invoice, issued by the agency. * Encoding: ASCII * minLength: 1 character * maxLength: 6 characters + [JsonPropertyName("airline.agency_invoice_number")] + public string? AirlineAgencyInvoiceNumber { get { return this._AirlineAgencyInvoiceNumberOption; } set { this._AirlineAgencyInvoiceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAgencyPlanNameOption { get; private set; } + + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + /// + /// The two-letter agency plan identifier. * Encoding: ASCII * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("airline.agency_plan_name")] + public string? AirlineAgencyPlanName { get { return this._AirlineAgencyPlanNameOption; } set { this._AirlineAgencyPlanNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAirlineCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-digit accounting code (PAX) that identifies the carrier. * Format: IATA 3-digit accounting code (PAX) * Example: KLM = 074 * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.airline_code")] + public string? AirlineAirlineCode { get { return this._AirlineAirlineCodeOption; } set { this._AirlineAirlineCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineAirlineDesignatorCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. * Encoding: ASCII * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.airline_designator_code")] + public string? AirlineAirlineDesignatorCode { get { return this._AirlineAirlineDesignatorCodeOption; } set { this._AirlineAirlineDesignatorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineBoardingFeeOption { get; private set; } + + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + /// + /// The amount charged for boarding the plane, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 character * maxLength: 18 characters + [JsonPropertyName("airline.boarding_fee")] + public string? AirlineBoardingFee { get { return this._AirlineBoardingFeeOption; } set { this._AirlineBoardingFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineComputerizedReservationSystemOption { get; private set; } + + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + /// + /// The [CRS](https://en.wikipedia.org/wiki/Computer_reservation_system) used to make the reservation and purchase the ticket. * Encoding: ASCII * minLength: 4 characters * maxLength: 4 characters + [JsonPropertyName("airline.computerized_reservation_system")] + public string? AirlineComputerizedReservationSystem { get { return this._AirlineComputerizedReservationSystemOption; } set { this._AirlineComputerizedReservationSystemOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineCustomerReferenceNumberOption { get; private set; } + + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + /// + /// The alphanumeric customer reference number. * Encoding: ASCII * maxLength: 20 characters * If you send more than 20 characters, the customer reference number is truncated * Must not be all spaces + [JsonPropertyName("airline.customer_reference_number")] + public string? AirlineCustomerReferenceNumber { get { return this._AirlineCustomerReferenceNumberOption; } set { this._AirlineCustomerReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineDocumentTypeOption { get; private set; } + + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + /// + /// A code that identifies the type of item bought. The description of the code can appear on credit card statements. * Encoding: ASCII * Example: Passenger ticket = 01 * minLength: 2 characters * maxLength: 2 characters + [JsonPropertyName("airline.document_type")] + public string? AirlineDocumentType { get { return this._AirlineDocumentTypeOption; } set { this._AirlineDocumentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineFlightDateOption { get; private set; } + + /// + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + /// + /// The flight departure date. Local time `(HH:mm)` is optional. * Date format: `yyyy-MM-dd` * Date and time format: `yyyy-MM-dd HH:mm` * minLength: 10 characters * maxLength: 16 characters + [JsonPropertyName("airline.flight_date")] + public string? AirlineFlightDate { get { return this._AirlineFlightDateOption; } set { this._AirlineFlightDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineIssueDateOption { get; private set; } + + /// + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + /// + /// The date that the ticket was issued to the passenger. * minLength: 6 characters * maxLength: 6 characters * Date format: YYMMDD + [JsonPropertyName("airline.issue_date")] + public string? AirlineIssueDate { get { return this._AirlineIssueDateOption; } set { this._AirlineIssueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegCarrierCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 2-letter accounting code (PAX) that identifies the carrier. This field is required if the airline data includes leg details. * Example: KLM = KL * minLength: 2 characters * maxLength: 2 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.carrier_code")] + public string? AirlineLegCarrierCode { get { return this._AirlineLegCarrierCodeOption; } set { this._AirlineLegCarrierCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegClassOfTravelOption { get; private set; } + + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + /// + /// A one-letter travel class identifier. The following are common: * F: first class * J: business class * Y: economy class * W: premium economy * Encoding: ASCII * minLength: 1 character * maxLength: 1 character * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.class_of_travel")] + public string? AirlineLegClassOfTravel { get { return this._AirlineLegClassOfTravelOption; } set { this._AirlineLegClassOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDateOfTravelOption { get; private set; } + + /// + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + /// + /// Date and time of travel in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd HH:mm`. * Encoding: ASCII * minLength: 16 characters * maxLength: 16 characters + [JsonPropertyName("airline.leg.date_of_travel")] + public string? AirlineLegDateOfTravel { get { return this._AirlineLegDateOfTravelOption; } set { this._AirlineLegDateOfTravelOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDepartAirportOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) three-letter airport code of the departure airport. This field is required if the airline data includes leg details. * Encoding: ASCII * Example: Amsterdam = AMS * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.depart_airport")] + public string? AirlineLegDepartAirport { get { return this._AirlineLegDepartAirportOption; } set { this._AirlineLegDepartAirportOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDepartTaxOption { get; private set; } + + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + /// + /// The amount of [departure tax](https://en.wikipedia.org/wiki/Departure_tax) charged, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Encoding: Numeric * minLength: 1 * maxLength: 12 * Must not be all zeros. + [JsonPropertyName("airline.leg.depart_tax")] + public string? AirlineLegDepartTax { get { return this._AirlineLegDepartTaxOption; } set { this._AirlineLegDepartTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegDestinationCodeOption { get; private set; } + + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [IATA](https://www.iata.org/services/pages/codes.aspx) 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. * Example: Amsterdam = AMS * Encoding: ASCII * minLength: 3 characters * maxLength: 3 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.destination_code")] + public string? AirlineLegDestinationCode { get { return this._AirlineLegDestinationCodeOption; } set { this._AirlineLegDestinationCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegFareBaseCodeOption { get; private set; } + + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// + /// The [fare basis code](https://en.wikipedia.org/wiki/Fare_basis_code), alphanumeric. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.fare_base_code")] + public string? AirlineLegFareBaseCode { get { return this._AirlineLegFareBaseCodeOption; } set { this._AirlineLegFareBaseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegFlightNumberOption { get; private set; } + + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + /// + /// The flight identifier. * minLength: 1 character * maxLength: 5 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.leg.flight_number")] + public string? AirlineLegFlightNumber { get { return this._AirlineLegFlightNumberOption; } set { this._AirlineLegFlightNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineLegStopOverCodeOption { get; private set; } + + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + /// + /// A one-letter code that indicates whether the passenger is entitled to make a stopover. Can be a space, O if the passenger is entitled to make a stopover, or X if they are not. * Encoding: ASCII * minLength: 1 character * maxLength: 1 character + [JsonPropertyName("airline.leg.stop_over_code")] + public string? AirlineLegStopOverCode { get { return this._AirlineLegStopOverCodeOption; } set { this._AirlineLegStopOverCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerDateOfBirthOption { get; private set; } + + /// + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + /// + /// The passenger's date of birth. Date format: `yyyy-MM-dd` * minLength: 10 * maxLength: 10 + [JsonPropertyName("airline.passenger.date_of_birth")] + public string? AirlinePassengerDateOfBirth { get { return this._AirlinePassengerDateOfBirthOption; } set { this._AirlinePassengerDateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerFirstNameOption { get; private set; } + + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's first name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("airline.passenger.first_name")] + public string? AirlinePassengerFirstName { get { return this._AirlinePassengerFirstNameOption; } set { this._AirlinePassengerFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerLastNameOption { get; private set; } + + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + /// + /// The passenger's last name. > This field is required if the airline data includes passenger details or leg details. * Encoding: ASCII + [JsonPropertyName("airline.passenger.last_name")] + public string? AirlinePassengerLastName { get { return this._AirlinePassengerLastNameOption; } set { this._AirlinePassengerLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerPhoneNumberOption { get; private set; } + + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + /// + /// The passenger's phone number, including country code. This is an alphanumeric field that can include the '+' and '-' signs. * Encoding: ASCII * minLength: 3 characters * maxLength: 30 characters + [JsonPropertyName("airline.passenger.phone_number")] + public string? AirlinePassengerPhoneNumber { get { return this._AirlinePassengerPhoneNumberOption; } set { this._AirlinePassengerPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlinePassengerTravellerTypeOption { get; private set; } + + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + /// + /// The IATA passenger type code (PTC). * Encoding: ASCII * minLength: 3 characters * maxLength: 6 characters + [JsonPropertyName("airline.passenger.traveller_type")] + public string? AirlinePassengerTravellerType { get { return this._AirlinePassengerTravellerTypeOption; } set { this._AirlinePassengerTravellerTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTicketIssueAddressOption { get; private set; } + + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + /// + /// The address of the organization that issued the ticket. * minLength: 0 characters * maxLength: 16 characters + [JsonPropertyName("airline.ticket_issue_address")] + public string? AirlineTicketIssueAddress { get { return this._AirlineTicketIssueAddressOption; } set { this._AirlineTicketIssueAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTicketNumberOption { get; private set; } + + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + /// + /// The ticket's unique identifier. * minLength: 1 character * maxLength: 15 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.ticket_number")] + public string? AirlineTicketNumber { get { return this._AirlineTicketNumberOption; } set { this._AirlineTicketNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTravelAgencyCodeOption { get; private set; } + + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + /// + /// The unique identifier from IATA or ARC for the travel agency that issues the ticket. * Encoding: ASCII * minLength: 1 character * maxLength: 8 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.travel_agency_code")] + public string? AirlineTravelAgencyCode { get { return this._AirlineTravelAgencyCodeOption; } set { this._AirlineTravelAgencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineTravelAgencyNameOption { get; private set; } + + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + /// + /// The name of the travel agency. * Encoding: ASCII * minLength: 1 character * maxLength: 25 characters * Must not be all spaces * Must not be all zeros. + [JsonPropertyName("airline.travel_agency_name")] + public string? AirlineTravelAgencyName { get { return this._AirlineTravelAgencyNameOption; } set { this._AirlineTravelAgencyNameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataAirline {\n"); + sb.Append(" AirlinePassengerName: ").Append(AirlinePassengerName).Append("\n"); + sb.Append(" AirlineAgencyInvoiceNumber: ").Append(AirlineAgencyInvoiceNumber).Append("\n"); + sb.Append(" AirlineAgencyPlanName: ").Append(AirlineAgencyPlanName).Append("\n"); + sb.Append(" AirlineAirlineCode: ").Append(AirlineAirlineCode).Append("\n"); + sb.Append(" AirlineAirlineDesignatorCode: ").Append(AirlineAirlineDesignatorCode).Append("\n"); + sb.Append(" AirlineBoardingFee: ").Append(AirlineBoardingFee).Append("\n"); + sb.Append(" AirlineComputerizedReservationSystem: ").Append(AirlineComputerizedReservationSystem).Append("\n"); + sb.Append(" AirlineCustomerReferenceNumber: ").Append(AirlineCustomerReferenceNumber).Append("\n"); + sb.Append(" AirlineDocumentType: ").Append(AirlineDocumentType).Append("\n"); + sb.Append(" AirlineFlightDate: ").Append(AirlineFlightDate).Append("\n"); + sb.Append(" AirlineIssueDate: ").Append(AirlineIssueDate).Append("\n"); + sb.Append(" AirlineLegCarrierCode: ").Append(AirlineLegCarrierCode).Append("\n"); + sb.Append(" AirlineLegClassOfTravel: ").Append(AirlineLegClassOfTravel).Append("\n"); + sb.Append(" AirlineLegDateOfTravel: ").Append(AirlineLegDateOfTravel).Append("\n"); + sb.Append(" AirlineLegDepartAirport: ").Append(AirlineLegDepartAirport).Append("\n"); + sb.Append(" AirlineLegDepartTax: ").Append(AirlineLegDepartTax).Append("\n"); + sb.Append(" AirlineLegDestinationCode: ").Append(AirlineLegDestinationCode).Append("\n"); + sb.Append(" AirlineLegFareBaseCode: ").Append(AirlineLegFareBaseCode).Append("\n"); + sb.Append(" AirlineLegFlightNumber: ").Append(AirlineLegFlightNumber).Append("\n"); + sb.Append(" AirlineLegStopOverCode: ").Append(AirlineLegStopOverCode).Append("\n"); + sb.Append(" AirlinePassengerDateOfBirth: ").Append(AirlinePassengerDateOfBirth).Append("\n"); + sb.Append(" AirlinePassengerFirstName: ").Append(AirlinePassengerFirstName).Append("\n"); + sb.Append(" AirlinePassengerLastName: ").Append(AirlinePassengerLastName).Append("\n"); + sb.Append(" AirlinePassengerPhoneNumber: ").Append(AirlinePassengerPhoneNumber).Append("\n"); + sb.Append(" AirlinePassengerTravellerType: ").Append(AirlinePassengerTravellerType).Append("\n"); + sb.Append(" AirlineTicketIssueAddress: ").Append(AirlineTicketIssueAddress).Append("\n"); + sb.Append(" AirlineTicketNumber: ").Append(AirlineTicketNumber).Append("\n"); + sb.Append(" AirlineTravelAgencyCode: ").Append(AirlineTravelAgencyCode).Append("\n"); + sb.Append(" AirlineTravelAgencyName: ").Append(AirlineTravelAgencyName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataAirlineJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataAirline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option airlinePassengerName = default; + Option airlineAgencyInvoiceNumber = default; + Option airlineAgencyPlanName = default; + Option airlineAirlineCode = default; + Option airlineAirlineDesignatorCode = default; + Option airlineBoardingFee = default; + Option airlineComputerizedReservationSystem = default; + Option airlineCustomerReferenceNumber = default; + Option airlineDocumentType = default; + Option airlineFlightDate = default; + Option airlineIssueDate = default; + Option airlineLegCarrierCode = default; + Option airlineLegClassOfTravel = default; + Option airlineLegDateOfTravel = default; + Option airlineLegDepartAirport = default; + Option airlineLegDepartTax = default; + Option airlineLegDestinationCode = default; + Option airlineLegFareBaseCode = default; + Option airlineLegFlightNumber = default; + Option airlineLegStopOverCode = default; + Option airlinePassengerDateOfBirth = default; + Option airlinePassengerFirstName = default; + Option airlinePassengerLastName = default; + Option airlinePassengerPhoneNumber = default; + Option airlinePassengerTravellerType = default; + Option airlineTicketIssueAddress = default; + Option airlineTicketNumber = default; + Option airlineTravelAgencyCode = default; + Option airlineTravelAgencyName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "airline.passenger_name": + airlinePassengerName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.agency_invoice_number": + airlineAgencyInvoiceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.agency_plan_name": + airlineAgencyPlanName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.airline_code": + airlineAirlineCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.airline_designator_code": + airlineAirlineDesignatorCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.boarding_fee": + airlineBoardingFee = new Option(utf8JsonReader.GetString()!); + break; + case "airline.computerized_reservation_system": + airlineComputerizedReservationSystem = new Option(utf8JsonReader.GetString()!); + break; + case "airline.customer_reference_number": + airlineCustomerReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.document_type": + airlineDocumentType = new Option(utf8JsonReader.GetString()!); + break; + case "airline.flight_date": + airlineFlightDate = new Option(utf8JsonReader.GetString()!); + break; + case "airline.issue_date": + airlineIssueDate = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.carrier_code": + airlineLegCarrierCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.class_of_travel": + airlineLegClassOfTravel = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.date_of_travel": + airlineLegDateOfTravel = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.depart_airport": + airlineLegDepartAirport = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.depart_tax": + airlineLegDepartTax = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.destination_code": + airlineLegDestinationCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.fare_base_code": + airlineLegFareBaseCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.flight_number": + airlineLegFlightNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.leg.stop_over_code": + airlineLegStopOverCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.date_of_birth": + airlinePassengerDateOfBirth = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.first_name": + airlinePassengerFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.last_name": + airlinePassengerLastName = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.phone_number": + airlinePassengerPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.passenger.traveller_type": + airlinePassengerTravellerType = new Option(utf8JsonReader.GetString()!); + break; + case "airline.ticket_issue_address": + airlineTicketIssueAddress = new Option(utf8JsonReader.GetString()!); + break; + case "airline.ticket_number": + airlineTicketNumber = new Option(utf8JsonReader.GetString()!); + break; + case "airline.travel_agency_code": + airlineTravelAgencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "airline.travel_agency_name": + airlineTravelAgencyName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!airlinePassengerName.IsSet) + throw new ArgumentException("Property is required for class AdditionalDataAirline.", nameof(airlinePassengerName)); + + return new AdditionalDataAirline(airlinePassengerName.Value!, airlineAgencyInvoiceNumber, airlineAgencyPlanName, airlineAirlineCode, airlineAirlineDesignatorCode, airlineBoardingFee, airlineComputerizedReservationSystem, airlineCustomerReferenceNumber, airlineDocumentType, airlineFlightDate, airlineIssueDate, airlineLegCarrierCode, airlineLegClassOfTravel, airlineLegDateOfTravel, airlineLegDepartAirport, airlineLegDepartTax, airlineLegDestinationCode, airlineLegFareBaseCode, airlineLegFlightNumber, airlineLegStopOverCode, airlinePassengerDateOfBirth, airlinePassengerFirstName, airlinePassengerLastName, airlinePassengerPhoneNumber, airlinePassengerTravellerType, airlineTicketIssueAddress, airlineTicketNumber, airlineTravelAgencyCode, airlineTravelAgencyName); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataAirline additionalDataAirline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataAirline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataAirline additionalDataAirline, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataAirline.AirlinePassengerName != null) + writer.WriteString("airline.passenger_name", additionalDataAirline.AirlinePassengerName); + + if (additionalDataAirline._AirlineAgencyInvoiceNumberOption.IsSet) + if (additionalDataAirline.AirlineAgencyInvoiceNumber != null) + writer.WriteString("airline.agency_invoice_number", additionalDataAirline.AirlineAgencyInvoiceNumber); + + if (additionalDataAirline._AirlineAgencyPlanNameOption.IsSet) + if (additionalDataAirline.AirlineAgencyPlanName != null) + writer.WriteString("airline.agency_plan_name", additionalDataAirline.AirlineAgencyPlanName); + + if (additionalDataAirline._AirlineAirlineCodeOption.IsSet) + if (additionalDataAirline.AirlineAirlineCode != null) + writer.WriteString("airline.airline_code", additionalDataAirline.AirlineAirlineCode); + + if (additionalDataAirline._AirlineAirlineDesignatorCodeOption.IsSet) + if (additionalDataAirline.AirlineAirlineDesignatorCode != null) + writer.WriteString("airline.airline_designator_code", additionalDataAirline.AirlineAirlineDesignatorCode); + + if (additionalDataAirline._AirlineBoardingFeeOption.IsSet) + if (additionalDataAirline.AirlineBoardingFee != null) + writer.WriteString("airline.boarding_fee", additionalDataAirline.AirlineBoardingFee); + + if (additionalDataAirline._AirlineComputerizedReservationSystemOption.IsSet) + if (additionalDataAirline.AirlineComputerizedReservationSystem != null) + writer.WriteString("airline.computerized_reservation_system", additionalDataAirline.AirlineComputerizedReservationSystem); + + if (additionalDataAirline._AirlineCustomerReferenceNumberOption.IsSet) + if (additionalDataAirline.AirlineCustomerReferenceNumber != null) + writer.WriteString("airline.customer_reference_number", additionalDataAirline.AirlineCustomerReferenceNumber); + + if (additionalDataAirline._AirlineDocumentTypeOption.IsSet) + if (additionalDataAirline.AirlineDocumentType != null) + writer.WriteString("airline.document_type", additionalDataAirline.AirlineDocumentType); + + if (additionalDataAirline._AirlineFlightDateOption.IsSet) + if (additionalDataAirline.AirlineFlightDate != null) + writer.WriteString("airline.flight_date", additionalDataAirline.AirlineFlightDate); + + if (additionalDataAirline._AirlineIssueDateOption.IsSet) + if (additionalDataAirline.AirlineIssueDate != null) + writer.WriteString("airline.issue_date", additionalDataAirline.AirlineIssueDate); + + if (additionalDataAirline._AirlineLegCarrierCodeOption.IsSet) + if (additionalDataAirline.AirlineLegCarrierCode != null) + writer.WriteString("airline.leg.carrier_code", additionalDataAirline.AirlineLegCarrierCode); + + if (additionalDataAirline._AirlineLegClassOfTravelOption.IsSet) + if (additionalDataAirline.AirlineLegClassOfTravel != null) + writer.WriteString("airline.leg.class_of_travel", additionalDataAirline.AirlineLegClassOfTravel); + + if (additionalDataAirline._AirlineLegDateOfTravelOption.IsSet) + if (additionalDataAirline.AirlineLegDateOfTravel != null) + writer.WriteString("airline.leg.date_of_travel", additionalDataAirline.AirlineLegDateOfTravel); + + if (additionalDataAirline._AirlineLegDepartAirportOption.IsSet) + if (additionalDataAirline.AirlineLegDepartAirport != null) + writer.WriteString("airline.leg.depart_airport", additionalDataAirline.AirlineLegDepartAirport); + + if (additionalDataAirline._AirlineLegDepartTaxOption.IsSet) + if (additionalDataAirline.AirlineLegDepartTax != null) + writer.WriteString("airline.leg.depart_tax", additionalDataAirline.AirlineLegDepartTax); + + if (additionalDataAirline._AirlineLegDestinationCodeOption.IsSet) + if (additionalDataAirline.AirlineLegDestinationCode != null) + writer.WriteString("airline.leg.destination_code", additionalDataAirline.AirlineLegDestinationCode); + + if (additionalDataAirline._AirlineLegFareBaseCodeOption.IsSet) + if (additionalDataAirline.AirlineLegFareBaseCode != null) + writer.WriteString("airline.leg.fare_base_code", additionalDataAirline.AirlineLegFareBaseCode); + + if (additionalDataAirline._AirlineLegFlightNumberOption.IsSet) + if (additionalDataAirline.AirlineLegFlightNumber != null) + writer.WriteString("airline.leg.flight_number", additionalDataAirline.AirlineLegFlightNumber); + + if (additionalDataAirline._AirlineLegStopOverCodeOption.IsSet) + if (additionalDataAirline.AirlineLegStopOverCode != null) + writer.WriteString("airline.leg.stop_over_code", additionalDataAirline.AirlineLegStopOverCode); + + if (additionalDataAirline._AirlinePassengerDateOfBirthOption.IsSet) + if (additionalDataAirline.AirlinePassengerDateOfBirth != null) + writer.WriteString("airline.passenger.date_of_birth", additionalDataAirline.AirlinePassengerDateOfBirth); + + if (additionalDataAirline._AirlinePassengerFirstNameOption.IsSet) + if (additionalDataAirline.AirlinePassengerFirstName != null) + writer.WriteString("airline.passenger.first_name", additionalDataAirline.AirlinePassengerFirstName); + + if (additionalDataAirline._AirlinePassengerLastNameOption.IsSet) + if (additionalDataAirline.AirlinePassengerLastName != null) + writer.WriteString("airline.passenger.last_name", additionalDataAirline.AirlinePassengerLastName); + + if (additionalDataAirline._AirlinePassengerPhoneNumberOption.IsSet) + if (additionalDataAirline.AirlinePassengerPhoneNumber != null) + writer.WriteString("airline.passenger.phone_number", additionalDataAirline.AirlinePassengerPhoneNumber); + + if (additionalDataAirline._AirlinePassengerTravellerTypeOption.IsSet) + if (additionalDataAirline.AirlinePassengerTravellerType != null) + writer.WriteString("airline.passenger.traveller_type", additionalDataAirline.AirlinePassengerTravellerType); + + if (additionalDataAirline._AirlineTicketIssueAddressOption.IsSet) + if (additionalDataAirline.AirlineTicketIssueAddress != null) + writer.WriteString("airline.ticket_issue_address", additionalDataAirline.AirlineTicketIssueAddress); + + if (additionalDataAirline._AirlineTicketNumberOption.IsSet) + if (additionalDataAirline.AirlineTicketNumber != null) + writer.WriteString("airline.ticket_number", additionalDataAirline.AirlineTicketNumber); + + if (additionalDataAirline._AirlineTravelAgencyCodeOption.IsSet) + if (additionalDataAirline.AirlineTravelAgencyCode != null) + writer.WriteString("airline.travel_agency_code", additionalDataAirline.AirlineTravelAgencyCode); + + if (additionalDataAirline._AirlineTravelAgencyNameOption.IsSet) + if (additionalDataAirline.AirlineTravelAgencyName != null) + writer.WriteString("airline.travel_agency_name", additionalDataAirline.AirlineTravelAgencyName); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataCarRental.cs b/Adyen/Payment/Models/AdditionalDataCarRental.cs new file mode 100644 index 000000000..f1609e992 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataCarRental.cs @@ -0,0 +1,727 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataCarRental. + /// + public partial class AdditionalDataCarRental : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The pick-up date. * Date format: `yyyyMMdd` + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + [JsonConstructor] + public AdditionalDataCarRental(Option carRentalCheckOutDate = default, Option carRentalCustomerServiceTollFreeNumber = default, Option carRentalDaysRented = default, Option carRentalFuelCharges = default, Option carRentalInsuranceCharges = default, Option carRentalLocationCity = default, Option carRentalLocationCountry = default, Option carRentalLocationStateProvince = default, Option carRentalNoShowIndicator = default, Option carRentalOneWayDropOffCharges = default, Option carRentalRate = default, Option carRentalRateIndicator = default, Option carRentalRentalAgreementNumber = default, Option carRentalRentalClassId = default, Option carRentalRenterName = default, Option carRentalReturnCity = default, Option carRentalReturnCountry = default, Option carRentalReturnDate = default, Option carRentalReturnLocationId = default, Option carRentalReturnStateProvince = default, Option carRentalTaxExemptIndicator = default, Option travelEntertainmentAuthDataDuration = default, Option travelEntertainmentAuthDataMarket = default) + { + _CarRentalCheckOutDateOption = carRentalCheckOutDate; + _CarRentalCustomerServiceTollFreeNumberOption = carRentalCustomerServiceTollFreeNumber; + _CarRentalDaysRentedOption = carRentalDaysRented; + _CarRentalFuelChargesOption = carRentalFuelCharges; + _CarRentalInsuranceChargesOption = carRentalInsuranceCharges; + _CarRentalLocationCityOption = carRentalLocationCity; + _CarRentalLocationCountryOption = carRentalLocationCountry; + _CarRentalLocationStateProvinceOption = carRentalLocationStateProvince; + _CarRentalNoShowIndicatorOption = carRentalNoShowIndicator; + _CarRentalOneWayDropOffChargesOption = carRentalOneWayDropOffCharges; + _CarRentalRateOption = carRentalRate; + _CarRentalRateIndicatorOption = carRentalRateIndicator; + _CarRentalRentalAgreementNumberOption = carRentalRentalAgreementNumber; + _CarRentalRentalClassIdOption = carRentalRentalClassId; + _CarRentalRenterNameOption = carRentalRenterName; + _CarRentalReturnCityOption = carRentalReturnCity; + _CarRentalReturnCountryOption = carRentalReturnCountry; + _CarRentalReturnDateOption = carRentalReturnDate; + _CarRentalReturnLocationIdOption = carRentalReturnLocationId; + _CarRentalReturnStateProvinceOption = carRentalReturnStateProvince; + _CarRentalTaxExemptIndicatorOption = carRentalTaxExemptIndicator; + _TravelEntertainmentAuthDataDurationOption = travelEntertainmentAuthDataDuration; + _TravelEntertainmentAuthDataMarketOption = travelEntertainmentAuthDataMarket; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataCarRental() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalCheckOutDateOption { get; private set; } + + /// + /// The pick-up date. * Date format: `yyyyMMdd` + /// + /// The pick-up date. * Date format: `yyyyMMdd` + [JsonPropertyName("carRental.checkOutDate")] + public string? CarRentalCheckOutDate { get { return this._CarRentalCheckOutDateOption; } set { this._CarRentalCheckOutDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalCustomerServiceTollFreeNumberOption { get; private set; } + + /// + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + /// + /// The customer service phone number of the car rental company. * Format: Alphanumeric * maxLength: 17 * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - *Must not be all zeros. + [JsonPropertyName("carRental.customerServiceTollFreeNumber")] + public string? CarRentalCustomerServiceTollFreeNumber { get { return this._CarRentalCustomerServiceTollFreeNumberOption; } set { this._CarRentalCustomerServiceTollFreeNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalDaysRentedOption { get; private set; } + + /// + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + /// + /// Number of days for which the car is being rented. * Format: Numeric * maxLength: 4 * Must not be all spaces + [JsonPropertyName("carRental.daysRented")] + public string? CarRentalDaysRented { get { return this._CarRentalDaysRentedOption; } set { this._CarRentalDaysRentedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalFuelChargesOption { get; private set; } + + /// + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + /// + /// Any fuel charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 + [JsonPropertyName("carRental.fuelCharges")] + public string? CarRentalFuelCharges { get { return this._CarRentalFuelChargesOption; } set { this._CarRentalFuelChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalInsuranceChargesOption { get; private set; } + + /// + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + /// + /// Any insurance charges associated with the rental, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Numeric * maxLength: 12 * Must not be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.insuranceCharges")] + public string? CarRentalInsuranceCharges { get { return this._CarRentalInsuranceChargesOption; } set { this._CarRentalInsuranceChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationCityOption { get; private set; } + + /// + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The city where the car is rented. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.locationCity")] + public string? CarRentalLocationCity { get { return this._CarRentalLocationCityOption; } set { this._CarRentalLocationCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationCountryOption { get; private set; } + + /// + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// + /// The country where the car is rented, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + [JsonPropertyName("carRental.locationCountry")] + public string? CarRentalLocationCountry { get { return this._CarRentalLocationCountryOption; } set { this._CarRentalLocationCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalLocationStateProvinceOption { get; private set; } + + /// + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The state or province where the car is rented. * Format: Alphanumeric * maxLength: 2 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.locationStateProvince")] + public string? CarRentalLocationStateProvince { get { return this._CarRentalLocationStateProvinceOption; } set { this._CarRentalLocationStateProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalNoShowIndicatorOption { get; private set; } + + /// + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + /// + /// Indicates if the customer didn't pick up their rental car. * Y - Customer did not pick up their car * N - Not applicable + [JsonPropertyName("carRental.noShowIndicator")] + public string? CarRentalNoShowIndicator { get { return this._CarRentalNoShowIndicatorOption; } set { this._CarRentalNoShowIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalOneWayDropOffChargesOption { get; private set; } + + /// + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + /// + /// The charge for not returning a car to the original rental location, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 12 + [JsonPropertyName("carRental.oneWayDropOffCharges")] + public string? CarRentalOneWayDropOffCharges { get { return this._CarRentalOneWayDropOffChargesOption; } set { this._CarRentalOneWayDropOffChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRateOption { get; private set; } + + /// + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + /// + /// The daily rental rate, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: Alphanumeric * maxLength: 12 + [JsonPropertyName("carRental.rate")] + public string? CarRentalRate { get { return this._CarRentalRateOption; } set { this._CarRentalRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRateIndicatorOption { get; private set; } + + /// + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + /// + /// Specifies whether the given rate is applied daily or weekly. * D - Daily rate * W - Weekly rate + [JsonPropertyName("carRental.rateIndicator")] + public string? CarRentalRateIndicator { get { return this._CarRentalRateIndicatorOption; } set { this._CarRentalRateIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRentalAgreementNumberOption { get; private set; } + + /// + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The rental agreement number for the car rental. * Format: Alphanumeric * maxLength: 9 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.rentalAgreementNumber")] + public string? CarRentalRentalAgreementNumber { get { return this._CarRentalRentalAgreementNumberOption; } set { this._CarRentalRentalAgreementNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRentalClassIdOption { get; private set; } + + /// + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The classification of the rental car. * Format: Alphanumeric * maxLength: 4 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.rentalClassId")] + public string? CarRentalRentalClassId { get { return this._CarRentalRentalClassIdOption; } set { this._CarRentalRentalClassIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalRenterNameOption { get; private set; } + + /// + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The name of the person renting the car. * Format: Alphanumeric * maxLength: 26 * If you send more than 26 characters, the name is truncated * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.renterName")] + public string? CarRentalRenterName { get { return this._CarRentalRenterNameOption; } set { this._CarRentalRenterNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnCityOption { get; private set; } + + /// + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The city where the car must be returned. * Format: Alphanumeric * maxLength: 18 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnCity")] + public string? CarRentalReturnCity { get { return this._CarRentalReturnCityOption; } set { this._CarRentalReturnCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnCountryOption { get; private set; } + + /// + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + /// + /// The country where the car must be returned, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. * Format: Alphanumeric * maxLength: 2 + [JsonPropertyName("carRental.returnCountry")] + public string? CarRentalReturnCountry { get { return this._CarRentalReturnCountryOption; } set { this._CarRentalReturnCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnDateOption { get; private set; } + + /// + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + /// + /// The last date to return the car by. * Date format: `yyyyMMdd` * maxLength: 8 + [JsonPropertyName("carRental.returnDate")] + public string? CarRentalReturnDate { get { return this._CarRentalReturnDateOption; } set { this._CarRentalReturnDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnLocationIdOption { get; private set; } + + /// + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The agency code, phone number, or address abbreviation * Format: Alphanumeric * maxLength: 10 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnLocationId")] + public string? CarRentalReturnLocationId { get { return this._CarRentalReturnLocationIdOption; } set { this._CarRentalReturnLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalReturnStateProvinceOption { get; private set; } + + /// + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + /// + /// The state or province where the car must be returned. * Format: Alphanumeric * maxLength: 3 * Must not start with a space or be all spaces *Must not be all zeros. + [JsonPropertyName("carRental.returnStateProvince")] + public string? CarRentalReturnStateProvince { get { return this._CarRentalReturnStateProvinceOption; } set { this._CarRentalReturnStateProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarRentalTaxExemptIndicatorOption { get; private set; } + + /// + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + /// + /// Indicates if the goods or services were tax-exempt, or if tax was not paid on them. Values: * Y - Goods or services were tax exempt * N - Tax was not collected + [JsonPropertyName("carRental.taxExemptIndicator")] + public string? CarRentalTaxExemptIndicator { get { return this._CarRentalTaxExemptIndicatorOption; } set { this._CarRentalTaxExemptIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataDurationOption { get; private set; } + + /// + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + /// + /// Number of days the car is rented for. This should be included in the auth message. * Format: Numeric * maxLength: 4 + [JsonPropertyName("travelEntertainmentAuthData.duration")] + public string? TravelEntertainmentAuthDataDuration { get { return this._TravelEntertainmentAuthDataDurationOption; } set { this._TravelEntertainmentAuthDataDurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataMarketOption { get; private set; } + + /// + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + /// + /// Indicates what market-specific dataset will be submitted or is being submitted. Value should be 'A' for car rental. This should be included in the auth message. * Format: Alphanumeric * maxLength: 1 + [JsonPropertyName("travelEntertainmentAuthData.market")] + public string? TravelEntertainmentAuthDataMarket { get { return this._TravelEntertainmentAuthDataMarketOption; } set { this._TravelEntertainmentAuthDataMarketOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataCarRental {\n"); + sb.Append(" CarRentalCheckOutDate: ").Append(CarRentalCheckOutDate).Append("\n"); + sb.Append(" CarRentalCustomerServiceTollFreeNumber: ").Append(CarRentalCustomerServiceTollFreeNumber).Append("\n"); + sb.Append(" CarRentalDaysRented: ").Append(CarRentalDaysRented).Append("\n"); + sb.Append(" CarRentalFuelCharges: ").Append(CarRentalFuelCharges).Append("\n"); + sb.Append(" CarRentalInsuranceCharges: ").Append(CarRentalInsuranceCharges).Append("\n"); + sb.Append(" CarRentalLocationCity: ").Append(CarRentalLocationCity).Append("\n"); + sb.Append(" CarRentalLocationCountry: ").Append(CarRentalLocationCountry).Append("\n"); + sb.Append(" CarRentalLocationStateProvince: ").Append(CarRentalLocationStateProvince).Append("\n"); + sb.Append(" CarRentalNoShowIndicator: ").Append(CarRentalNoShowIndicator).Append("\n"); + sb.Append(" CarRentalOneWayDropOffCharges: ").Append(CarRentalOneWayDropOffCharges).Append("\n"); + sb.Append(" CarRentalRate: ").Append(CarRentalRate).Append("\n"); + sb.Append(" CarRentalRateIndicator: ").Append(CarRentalRateIndicator).Append("\n"); + sb.Append(" CarRentalRentalAgreementNumber: ").Append(CarRentalRentalAgreementNumber).Append("\n"); + sb.Append(" CarRentalRentalClassId: ").Append(CarRentalRentalClassId).Append("\n"); + sb.Append(" CarRentalRenterName: ").Append(CarRentalRenterName).Append("\n"); + sb.Append(" CarRentalReturnCity: ").Append(CarRentalReturnCity).Append("\n"); + sb.Append(" CarRentalReturnCountry: ").Append(CarRentalReturnCountry).Append("\n"); + sb.Append(" CarRentalReturnDate: ").Append(CarRentalReturnDate).Append("\n"); + sb.Append(" CarRentalReturnLocationId: ").Append(CarRentalReturnLocationId).Append("\n"); + sb.Append(" CarRentalReturnStateProvince: ").Append(CarRentalReturnStateProvince).Append("\n"); + sb.Append(" CarRentalTaxExemptIndicator: ").Append(CarRentalTaxExemptIndicator).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataDuration: ").Append(TravelEntertainmentAuthDataDuration).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataMarket: ").Append(TravelEntertainmentAuthDataMarket).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataCarRentalJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataCarRental Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option carRentalCheckOutDate = default; + Option carRentalCustomerServiceTollFreeNumber = default; + Option carRentalDaysRented = default; + Option carRentalFuelCharges = default; + Option carRentalInsuranceCharges = default; + Option carRentalLocationCity = default; + Option carRentalLocationCountry = default; + Option carRentalLocationStateProvince = default; + Option carRentalNoShowIndicator = default; + Option carRentalOneWayDropOffCharges = default; + Option carRentalRate = default; + Option carRentalRateIndicator = default; + Option carRentalRentalAgreementNumber = default; + Option carRentalRentalClassId = default; + Option carRentalRenterName = default; + Option carRentalReturnCity = default; + Option carRentalReturnCountry = default; + Option carRentalReturnDate = default; + Option carRentalReturnLocationId = default; + Option carRentalReturnStateProvince = default; + Option carRentalTaxExemptIndicator = default; + Option travelEntertainmentAuthDataDuration = default; + Option travelEntertainmentAuthDataMarket = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "carRental.checkOutDate": + carRentalCheckOutDate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.customerServiceTollFreeNumber": + carRentalCustomerServiceTollFreeNumber = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.daysRented": + carRentalDaysRented = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.fuelCharges": + carRentalFuelCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.insuranceCharges": + carRentalInsuranceCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationCity": + carRentalLocationCity = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationCountry": + carRentalLocationCountry = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.locationStateProvince": + carRentalLocationStateProvince = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.noShowIndicator": + carRentalNoShowIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.oneWayDropOffCharges": + carRentalOneWayDropOffCharges = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rate": + carRentalRate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rateIndicator": + carRentalRateIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rentalAgreementNumber": + carRentalRentalAgreementNumber = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.rentalClassId": + carRentalRentalClassId = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.renterName": + carRentalRenterName = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnCity": + carRentalReturnCity = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnCountry": + carRentalReturnCountry = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnDate": + carRentalReturnDate = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnLocationId": + carRentalReturnLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.returnStateProvince": + carRentalReturnStateProvince = new Option(utf8JsonReader.GetString()!); + break; + case "carRental.taxExemptIndicator": + carRentalTaxExemptIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.duration": + travelEntertainmentAuthDataDuration = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.market": + travelEntertainmentAuthDataMarket = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataCarRental(carRentalCheckOutDate, carRentalCustomerServiceTollFreeNumber, carRentalDaysRented, carRentalFuelCharges, carRentalInsuranceCharges, carRentalLocationCity, carRentalLocationCountry, carRentalLocationStateProvince, carRentalNoShowIndicator, carRentalOneWayDropOffCharges, carRentalRate, carRentalRateIndicator, carRentalRentalAgreementNumber, carRentalRentalClassId, carRentalRenterName, carRentalReturnCity, carRentalReturnCountry, carRentalReturnDate, carRentalReturnLocationId, carRentalReturnStateProvince, carRentalTaxExemptIndicator, travelEntertainmentAuthDataDuration, travelEntertainmentAuthDataMarket); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataCarRental additionalDataCarRental, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataCarRental, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataCarRental additionalDataCarRental, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataCarRental._CarRentalCheckOutDateOption.IsSet) + if (additionalDataCarRental.CarRentalCheckOutDate != null) + writer.WriteString("carRental.checkOutDate", additionalDataCarRental.CarRentalCheckOutDate); + + if (additionalDataCarRental._CarRentalCustomerServiceTollFreeNumberOption.IsSet) + if (additionalDataCarRental.CarRentalCustomerServiceTollFreeNumber != null) + writer.WriteString("carRental.customerServiceTollFreeNumber", additionalDataCarRental.CarRentalCustomerServiceTollFreeNumber); + + if (additionalDataCarRental._CarRentalDaysRentedOption.IsSet) + if (additionalDataCarRental.CarRentalDaysRented != null) + writer.WriteString("carRental.daysRented", additionalDataCarRental.CarRentalDaysRented); + + if (additionalDataCarRental._CarRentalFuelChargesOption.IsSet) + if (additionalDataCarRental.CarRentalFuelCharges != null) + writer.WriteString("carRental.fuelCharges", additionalDataCarRental.CarRentalFuelCharges); + + if (additionalDataCarRental._CarRentalInsuranceChargesOption.IsSet) + if (additionalDataCarRental.CarRentalInsuranceCharges != null) + writer.WriteString("carRental.insuranceCharges", additionalDataCarRental.CarRentalInsuranceCharges); + + if (additionalDataCarRental._CarRentalLocationCityOption.IsSet) + if (additionalDataCarRental.CarRentalLocationCity != null) + writer.WriteString("carRental.locationCity", additionalDataCarRental.CarRentalLocationCity); + + if (additionalDataCarRental._CarRentalLocationCountryOption.IsSet) + if (additionalDataCarRental.CarRentalLocationCountry != null) + writer.WriteString("carRental.locationCountry", additionalDataCarRental.CarRentalLocationCountry); + + if (additionalDataCarRental._CarRentalLocationStateProvinceOption.IsSet) + if (additionalDataCarRental.CarRentalLocationStateProvince != null) + writer.WriteString("carRental.locationStateProvince", additionalDataCarRental.CarRentalLocationStateProvince); + + if (additionalDataCarRental._CarRentalNoShowIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalNoShowIndicator != null) + writer.WriteString("carRental.noShowIndicator", additionalDataCarRental.CarRentalNoShowIndicator); + + if (additionalDataCarRental._CarRentalOneWayDropOffChargesOption.IsSet) + if (additionalDataCarRental.CarRentalOneWayDropOffCharges != null) + writer.WriteString("carRental.oneWayDropOffCharges", additionalDataCarRental.CarRentalOneWayDropOffCharges); + + if (additionalDataCarRental._CarRentalRateOption.IsSet) + if (additionalDataCarRental.CarRentalRate != null) + writer.WriteString("carRental.rate", additionalDataCarRental.CarRentalRate); + + if (additionalDataCarRental._CarRentalRateIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalRateIndicator != null) + writer.WriteString("carRental.rateIndicator", additionalDataCarRental.CarRentalRateIndicator); + + if (additionalDataCarRental._CarRentalRentalAgreementNumberOption.IsSet) + if (additionalDataCarRental.CarRentalRentalAgreementNumber != null) + writer.WriteString("carRental.rentalAgreementNumber", additionalDataCarRental.CarRentalRentalAgreementNumber); + + if (additionalDataCarRental._CarRentalRentalClassIdOption.IsSet) + if (additionalDataCarRental.CarRentalRentalClassId != null) + writer.WriteString("carRental.rentalClassId", additionalDataCarRental.CarRentalRentalClassId); + + if (additionalDataCarRental._CarRentalRenterNameOption.IsSet) + if (additionalDataCarRental.CarRentalRenterName != null) + writer.WriteString("carRental.renterName", additionalDataCarRental.CarRentalRenterName); + + if (additionalDataCarRental._CarRentalReturnCityOption.IsSet) + if (additionalDataCarRental.CarRentalReturnCity != null) + writer.WriteString("carRental.returnCity", additionalDataCarRental.CarRentalReturnCity); + + if (additionalDataCarRental._CarRentalReturnCountryOption.IsSet) + if (additionalDataCarRental.CarRentalReturnCountry != null) + writer.WriteString("carRental.returnCountry", additionalDataCarRental.CarRentalReturnCountry); + + if (additionalDataCarRental._CarRentalReturnDateOption.IsSet) + if (additionalDataCarRental.CarRentalReturnDate != null) + writer.WriteString("carRental.returnDate", additionalDataCarRental.CarRentalReturnDate); + + if (additionalDataCarRental._CarRentalReturnLocationIdOption.IsSet) + if (additionalDataCarRental.CarRentalReturnLocationId != null) + writer.WriteString("carRental.returnLocationId", additionalDataCarRental.CarRentalReturnLocationId); + + if (additionalDataCarRental._CarRentalReturnStateProvinceOption.IsSet) + if (additionalDataCarRental.CarRentalReturnStateProvince != null) + writer.WriteString("carRental.returnStateProvince", additionalDataCarRental.CarRentalReturnStateProvince); + + if (additionalDataCarRental._CarRentalTaxExemptIndicatorOption.IsSet) + if (additionalDataCarRental.CarRentalTaxExemptIndicator != null) + writer.WriteString("carRental.taxExemptIndicator", additionalDataCarRental.CarRentalTaxExemptIndicator); + + if (additionalDataCarRental._TravelEntertainmentAuthDataDurationOption.IsSet) + if (additionalDataCarRental.TravelEntertainmentAuthDataDuration != null) + writer.WriteString("travelEntertainmentAuthData.duration", additionalDataCarRental.TravelEntertainmentAuthDataDuration); + + if (additionalDataCarRental._TravelEntertainmentAuthDataMarketOption.IsSet) + if (additionalDataCarRental.TravelEntertainmentAuthDataMarket != null) + writer.WriteString("travelEntertainmentAuthData.market", additionalDataCarRental.TravelEntertainmentAuthDataMarket); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataCommon.cs b/Adyen/Payment/Models/AdditionalDataCommon.cs new file mode 100644 index 000000000..73748ec92 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataCommon.cs @@ -0,0 +1,783 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataCommon. + /// + public partial class AdditionalDataCommon : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + [JsonConstructor] + public AdditionalDataCommon(Option requestedTestAcquirerResponseCode = default, Option requestedTestErrorResponseCode = default, Option allowPartialAuth = default, Option authorisationType = default, Option autoRescue = default, Option customRoutingFlag = default, Option industryUsage = default, Option manualCapture = default, Option maxDaysToRescue = default, Option networkTxReference = default, Option overwriteBrand = default, Option subMerchantCity = default, Option subMerchantCountry = default, Option subMerchantEmail = default, Option subMerchantID = default, Option subMerchantName = default, Option subMerchantPhoneNumber = default, Option subMerchantPostalCode = default, Option subMerchantState = default, Option subMerchantStreet = default, Option subMerchantTaxId = default) + { + _RequestedTestAcquirerResponseCodeOption = requestedTestAcquirerResponseCode; + _RequestedTestErrorResponseCodeOption = requestedTestErrorResponseCode; + _AllowPartialAuthOption = allowPartialAuth; + _AuthorisationTypeOption = authorisationType; + _AutoRescueOption = autoRescue; + _CustomRoutingFlagOption = customRoutingFlag; + _IndustryUsageOption = industryUsage; + _ManualCaptureOption = manualCapture; + _MaxDaysToRescueOption = maxDaysToRescue; + _NetworkTxReferenceOption = networkTxReference; + _OverwriteBrandOption = overwriteBrand; + _SubMerchantCityOption = subMerchantCity; + _SubMerchantCountryOption = subMerchantCountry; + _SubMerchantEmailOption = subMerchantEmail; + _SubMerchantIDOption = subMerchantID; + _SubMerchantNameOption = subMerchantName; + _SubMerchantPhoneNumberOption = subMerchantPhoneNumber; + _SubMerchantPostalCodeOption = subMerchantPostalCode; + _SubMerchantStateOption = subMerchantState; + _SubMerchantStreetOption = subMerchantStreet; + _SubMerchantTaxIdOption = subMerchantTaxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataCommon() + { + } + + partial void OnCreated(); + + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + [JsonConverter(typeof(IndustryUsageEnumJsonConverter))] + public class IndustryUsageEnum : IEnum + { + /// + /// Returns the value of the IndustryUsageEnum. + /// + public string? Value { get; set; } + + /// + /// IndustryUsageEnum.NoShow - NoShow + /// + public static readonly IndustryUsageEnum NoShow = new("NoShow"); + + /// + /// IndustryUsageEnum.DelayedCharge - DelayedCharge + /// + public static readonly IndustryUsageEnum DelayedCharge = new("DelayedCharge"); + + private IndustryUsageEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator IndustryUsageEnum?(string? value) => value == null ? null : new IndustryUsageEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(IndustryUsageEnum? option) => option?.Value; + + public static bool operator ==(IndustryUsageEnum? left, IndustryUsageEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(IndustryUsageEnum? left, IndustryUsageEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is IndustryUsageEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static IndustryUsageEnum? FromStringOrDefault(string value) + { + return value switch { + "NoShow" => IndustryUsageEnum.NoShow, + "DelayedCharge" => IndustryUsageEnum.DelayedCharge, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(IndustryUsageEnum? value) + { + if (value == null) + return null; + + if (value == IndustryUsageEnum.NoShow) + return "NoShow"; + + if (value == IndustryUsageEnum.DelayedCharge) + return "DelayedCharge"; + + return null; + } + + /// + /// JsonConverter for writing IndustryUsageEnum. + /// + public class IndustryUsageEnumJsonConverter : JsonConverter + { + public override IndustryUsageEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : IndustryUsageEnum.FromStringOrDefault(value) ?? new IndustryUsageEnum(value); + } + + public override void Write(Utf8JsonWriter writer, IndustryUsageEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(IndustryUsageEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IndustryUsageOption { get; private set; } + + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + /// + /// In case of [asynchronous authorisation adjustment](https://docs.adyen.com/online-payments/adjust-authorisation#adjust-authorisation), this field denotes why the additional payment is made. Possible values: * **NoShow**: An incremental charge is carried out because of a no-show for a guaranteed reservation. * **DelayedCharge**: An incremental charge is carried out to process an additional payment after the original services have been rendered and the respective payment has been processed. + [JsonPropertyName("industryUsage")] + public IndustryUsageEnum? IndustryUsage { get { return this._IndustryUsageOption; } set { this._IndustryUsageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedTestAcquirerResponseCodeOption { get; private set; } + + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + /// + /// Triggers test scenarios that allow to replicate certain acquirer response codes. See [Testing result codes and refusal reasons](https://docs.adyen.com/development-resources/testing/result-codes/) to learn about the possible values, and the `refusalReason` values you can trigger. + [JsonPropertyName("RequestedTestAcquirerResponseCode")] + public string? RequestedTestAcquirerResponseCode { get { return this._RequestedTestAcquirerResponseCodeOption; } set { this._RequestedTestAcquirerResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestedTestErrorResponseCodeOption { get; private set; } + + /// + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + /// + /// Triggers test scenarios that allow to replicate certain communication errors. Allowed values: * **NO_CONNECTION_AVAILABLE** – There wasn't a connection available to service the outgoing communication. This is a transient, retriable error since no messaging could be initiated to an issuing system (or third-party acquiring system). Therefore, the header Transient-Error: true is returned in the response. A subsequent request using the same idempotency key will be processed as if it was the first request. * **IOEXCEPTION_RECEIVED** – Something went wrong during transmission of the message or receiving the response. This is a classified as non-transient because the message could have been received by the issuing party and been acted upon. No transient error header is returned. If using idempotency, the (error) response is stored as the final result for the idempotency key. Subsequent messages with the same idempotency key not be processed beyond returning the stored response. + [JsonPropertyName("RequestedTestErrorResponseCode")] + public string? RequestedTestErrorResponseCode { get { return this._RequestedTestErrorResponseCodeOption; } set { this._RequestedTestErrorResponseCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllowPartialAuthOption { get; private set; } + + /// + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + /// + /// Set to true to authorise a part of the requested amount in case the cardholder does not have enough funds on their account. If a payment was partially authorised, the response includes resultCode: PartiallyAuthorised and the authorised amount in additionalData.authorisedAmountValue. To enable this functionality, contact our Support Team. + [JsonPropertyName("allowPartialAuth")] + public string? AllowPartialAuth { get { return this._AllowPartialAuthOption; } set { this._AllowPartialAuthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTypeOption { get; private set; } + + /// + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + /// + /// Flags a card payment request for either pre-authorisation or final authorisation. For more information, refer to [Authorisation types](https://docs.adyen.com/online-payments/adjust-authorisation#authorisation-types). Allowed values: * **PreAuth** – flags the payment request to be handled as a pre-authorisation. * **FinalAuth** – flags the payment request to be handled as a final authorisation. + [JsonPropertyName("authorisationType")] + public string? AuthorisationType { get { return this._AuthorisationTypeOption; } set { this._AuthorisationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AutoRescueOption { get; private set; } + + /// + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + /// + /// Set to **true** to enable [Auto Rescue](https://docs.adyen.com/online-payments/auto-rescue/) for a transaction. Use the `maxDaysToRescue` to specify a rescue window. + [JsonPropertyName("autoRescue")] + public string? AutoRescue { get { return this._AutoRescueOption; } set { this._AutoRescueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CustomRoutingFlagOption { get; private set; } + + /// + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// Allows you to determine or override the acquirer account that should be used for the transaction. If you need to process a payment with an acquirer different from a default one, you can set up a corresponding configuration on the Adyen payments platform. Then you can pass a custom routing flag in a payment request's additional data to target a specific acquirer. To enable this functionality, contact [Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("customRoutingFlag")] + public string? CustomRoutingFlag { get { return this._CustomRoutingFlagOption; } set { this._CustomRoutingFlagOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ManualCaptureOption { get; private set; } + + /// + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + /// + /// Set to **true** to require [manual capture](https://docs.adyen.com/online-payments/capture) for the transaction. + [JsonPropertyName("manualCapture")] + public string? ManualCapture { get { return this._ManualCaptureOption; } set { this._ManualCaptureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxDaysToRescueOption { get; private set; } + + /// + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + /// + /// The rescue window for a transaction, in days, when `autoRescue` is set to **true**. You can specify a value between 1 and 48. * For [cards](https://docs.adyen.com/online-payments/auto-rescue/cards/), the default is one calendar month. * For [SEPA](https://docs.adyen.com/online-payments/auto-rescue/sepa/), the default is 42 days. + [JsonPropertyName("maxDaysToRescue")] + public string? MaxDaysToRescue { get { return this._MaxDaysToRescueOption; } set { this._MaxDaysToRescueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + /// + /// Allows you to link the transaction to the original or previous one in a subscription/card-on-file chain. This field is required for token-based transactions where Adyen does not tokenize the card. Transaction identifier from card schemes, for example, Mastercard Trace ID or the Visa Transaction ID. Submit the original transaction ID of the contract in your payment request if you are not tokenizing card details with Adyen and are making a merchant-initiated transaction (MIT) for subsequent charges. Make sure you are sending `shopperInteraction` **ContAuth** and `recurringProcessingModel` **Subscription** or **UnscheduledCardOnFile** to ensure that the transaction is classified as MIT. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OverwriteBrandOption { get; private set; } + + /// + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + /// + /// Boolean indicator that can be optionally used for performing debit transactions on combo cards (for example, combo cards in Brazil). This is not mandatory but we recommend that you set this to true if you want to use the `selectedBrand` value to specify how to process the transaction. + [JsonPropertyName("overwriteBrand")] + public string? OverwriteBrand { get { return this._OverwriteBrandOption; } set { this._OverwriteBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantCityOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the city of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 13 characters. + [JsonPropertyName("subMerchantCity")] + public string? SubMerchantCity { get { return this._SubMerchantCityOption; } set { this._SubMerchantCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantCountryOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the three-letter country code of the actual merchant's address. * Format: alpha-numeric. * Fixed length: 3 characters. + [JsonPropertyName("subMerchantCountry")] + public string? SubMerchantCountry { get { return this._SubMerchantCountryOption; } set { this._SubMerchantCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantEmailOption { get; private set; } + + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + [JsonPropertyName("subMerchantEmail")] + public string? SubMerchantEmail { get { return this._SubMerchantEmailOption; } set { this._SubMerchantEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantIDOption { get; private set; } + + /// + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + /// + /// This field contains an identifier of the actual merchant when a transaction is submitted via a payment facilitator. The payment facilitator must send in this unique ID. A unique identifier per submerchant that is required if the transaction is performed by a registered payment facilitator. * Format: alpha-numeric. * Fixed length: 15 characters. + [JsonPropertyName("subMerchantID")] + public string? SubMerchantID { get { return this._SubMerchantIDOption; } set { this._SubMerchantIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantNameOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the name of the actual merchant. * Format: alpha-numeric. * Maximum length: 22 characters. + [JsonPropertyName("subMerchantName")] + public string? SubMerchantName { get { return this._SubMerchantNameOption; } set { this._SubMerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantPhoneNumberOption { get; private set; } + + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + /// + /// This field is required for transactions performed by registered payment facilitators. This field contains the phone number of the sub-merchant.* Format: Alphanumeric * Maximum length: 20 characters + [JsonPropertyName("subMerchantPhoneNumber")] + public string? SubMerchantPhoneNumber { get { return this._SubMerchantPhoneNumberOption; } set { this._SubMerchantPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantPostalCodeOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the postal code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 10 characters. + [JsonPropertyName("subMerchantPostalCode")] + public string? SubMerchantPostalCode { get { return this._SubMerchantPostalCodeOption; } set { this._SubMerchantPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantStateOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator, and if applicable to the country. This field must contain the state code of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 3 characters. + [JsonPropertyName("subMerchantState")] + public string? SubMerchantState { get { return this._SubMerchantStateOption; } set { this._SubMerchantStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantStreetOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the street of the actual merchant's address. * Format: alpha-numeric. * Maximum length: 60 characters. + [JsonPropertyName("subMerchantStreet")] + public string? SubMerchantStreet { get { return this._SubMerchantStreetOption; } set { this._SubMerchantStreetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantTaxIdOption { get; private set; } + + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + /// + /// This field is required if the transaction is performed by a registered payment facilitator. This field must contain the tax ID of the actual merchant. * Format: alpha-numeric. * Fixed length: 11 or 14 characters. + [JsonPropertyName("subMerchantTaxId")] + public string? SubMerchantTaxId { get { return this._SubMerchantTaxIdOption; } set { this._SubMerchantTaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataCommon {\n"); + sb.Append(" RequestedTestAcquirerResponseCode: ").Append(RequestedTestAcquirerResponseCode).Append("\n"); + sb.Append(" RequestedTestErrorResponseCode: ").Append(RequestedTestErrorResponseCode).Append("\n"); + sb.Append(" AllowPartialAuth: ").Append(AllowPartialAuth).Append("\n"); + sb.Append(" AuthorisationType: ").Append(AuthorisationType).Append("\n"); + sb.Append(" AutoRescue: ").Append(AutoRescue).Append("\n"); + sb.Append(" CustomRoutingFlag: ").Append(CustomRoutingFlag).Append("\n"); + sb.Append(" IndustryUsage: ").Append(IndustryUsage).Append("\n"); + sb.Append(" ManualCapture: ").Append(ManualCapture).Append("\n"); + sb.Append(" MaxDaysToRescue: ").Append(MaxDaysToRescue).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OverwriteBrand: ").Append(OverwriteBrand).Append("\n"); + sb.Append(" SubMerchantCity: ").Append(SubMerchantCity).Append("\n"); + sb.Append(" SubMerchantCountry: ").Append(SubMerchantCountry).Append("\n"); + sb.Append(" SubMerchantEmail: ").Append(SubMerchantEmail).Append("\n"); + sb.Append(" SubMerchantID: ").Append(SubMerchantID).Append("\n"); + sb.Append(" SubMerchantName: ").Append(SubMerchantName).Append("\n"); + sb.Append(" SubMerchantPhoneNumber: ").Append(SubMerchantPhoneNumber).Append("\n"); + sb.Append(" SubMerchantPostalCode: ").Append(SubMerchantPostalCode).Append("\n"); + sb.Append(" SubMerchantState: ").Append(SubMerchantState).Append("\n"); + sb.Append(" SubMerchantStreet: ").Append(SubMerchantStreet).Append("\n"); + sb.Append(" SubMerchantTaxId: ").Append(SubMerchantTaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataCommonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataCommon Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requestedTestAcquirerResponseCode = default; + Option requestedTestErrorResponseCode = default; + Option allowPartialAuth = default; + Option authorisationType = default; + Option autoRescue = default; + Option customRoutingFlag = default; + Option industryUsage = default; + Option manualCapture = default; + Option maxDaysToRescue = default; + Option networkTxReference = default; + Option overwriteBrand = default; + Option subMerchantCity = default; + Option subMerchantCountry = default; + Option subMerchantEmail = default; + Option subMerchantID = default; + Option subMerchantName = default; + Option subMerchantPhoneNumber = default; + Option subMerchantPostalCode = default; + Option subMerchantState = default; + Option subMerchantStreet = default; + Option subMerchantTaxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "RequestedTestAcquirerResponseCode": + requestedTestAcquirerResponseCode = new Option(utf8JsonReader.GetString()!); + break; + case "RequestedTestErrorResponseCode": + requestedTestErrorResponseCode = new Option(utf8JsonReader.GetString()!); + break; + case "allowPartialAuth": + allowPartialAuth = new Option(utf8JsonReader.GetString()!); + break; + case "authorisationType": + authorisationType = new Option(utf8JsonReader.GetString()!); + break; + case "autoRescue": + autoRescue = new Option(utf8JsonReader.GetString()!); + break; + case "customRoutingFlag": + customRoutingFlag = new Option(utf8JsonReader.GetString()!); + break; + case "industryUsage": + string? industryUsageRawValue = utf8JsonReader.GetString(); + industryUsage = new Option(AdditionalDataCommon.IndustryUsageEnum.FromStringOrDefault(industryUsageRawValue)); + break; + case "manualCapture": + manualCapture = new Option(utf8JsonReader.GetString()!); + break; + case "maxDaysToRescue": + maxDaysToRescue = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "overwriteBrand": + overwriteBrand = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantCity": + subMerchantCity = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantCountry": + subMerchantCountry = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantEmail": + subMerchantEmail = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantID": + subMerchantID = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantName": + subMerchantName = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantPhoneNumber": + subMerchantPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantPostalCode": + subMerchantPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantState": + subMerchantState = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantStreet": + subMerchantStreet = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchantTaxId": + subMerchantTaxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataCommon(requestedTestAcquirerResponseCode, requestedTestErrorResponseCode, allowPartialAuth, authorisationType, autoRescue, customRoutingFlag, industryUsage, manualCapture, maxDaysToRescue, networkTxReference, overwriteBrand, subMerchantCity, subMerchantCountry, subMerchantEmail, subMerchantID, subMerchantName, subMerchantPhoneNumber, subMerchantPostalCode, subMerchantState, subMerchantStreet, subMerchantTaxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataCommon additionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataCommon, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataCommon additionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataCommon._RequestedTestAcquirerResponseCodeOption.IsSet) + if (additionalDataCommon.RequestedTestAcquirerResponseCode != null) + writer.WriteString("RequestedTestAcquirerResponseCode", additionalDataCommon.RequestedTestAcquirerResponseCode); + + if (additionalDataCommon._RequestedTestErrorResponseCodeOption.IsSet) + if (additionalDataCommon.RequestedTestErrorResponseCode != null) + writer.WriteString("RequestedTestErrorResponseCode", additionalDataCommon.RequestedTestErrorResponseCode); + + if (additionalDataCommon._AllowPartialAuthOption.IsSet) + if (additionalDataCommon.AllowPartialAuth != null) + writer.WriteString("allowPartialAuth", additionalDataCommon.AllowPartialAuth); + + if (additionalDataCommon._AuthorisationTypeOption.IsSet) + if (additionalDataCommon.AuthorisationType != null) + writer.WriteString("authorisationType", additionalDataCommon.AuthorisationType); + + if (additionalDataCommon._AutoRescueOption.IsSet) + if (additionalDataCommon.AutoRescue != null) + writer.WriteString("autoRescue", additionalDataCommon.AutoRescue); + + if (additionalDataCommon._CustomRoutingFlagOption.IsSet) + if (additionalDataCommon.CustomRoutingFlag != null) + writer.WriteString("customRoutingFlag", additionalDataCommon.CustomRoutingFlag); + + if (additionalDataCommon._IndustryUsageOption.IsSet && additionalDataCommon.IndustryUsage != null) + { + string? industryUsageRawValue = AdditionalDataCommon.IndustryUsageEnum.ToJsonValue(additionalDataCommon._IndustryUsageOption.Value!.Value); + writer.WriteString("industryUsage", industryUsageRawValue); + } + + if (additionalDataCommon._ManualCaptureOption.IsSet) + if (additionalDataCommon.ManualCapture != null) + writer.WriteString("manualCapture", additionalDataCommon.ManualCapture); + + if (additionalDataCommon._MaxDaysToRescueOption.IsSet) + if (additionalDataCommon.MaxDaysToRescue != null) + writer.WriteString("maxDaysToRescue", additionalDataCommon.MaxDaysToRescue); + + if (additionalDataCommon._NetworkTxReferenceOption.IsSet) + if (additionalDataCommon.NetworkTxReference != null) + writer.WriteString("networkTxReference", additionalDataCommon.NetworkTxReference); + + if (additionalDataCommon._OverwriteBrandOption.IsSet) + if (additionalDataCommon.OverwriteBrand != null) + writer.WriteString("overwriteBrand", additionalDataCommon.OverwriteBrand); + + if (additionalDataCommon._SubMerchantCityOption.IsSet) + if (additionalDataCommon.SubMerchantCity != null) + writer.WriteString("subMerchantCity", additionalDataCommon.SubMerchantCity); + + if (additionalDataCommon._SubMerchantCountryOption.IsSet) + if (additionalDataCommon.SubMerchantCountry != null) + writer.WriteString("subMerchantCountry", additionalDataCommon.SubMerchantCountry); + + if (additionalDataCommon._SubMerchantEmailOption.IsSet) + if (additionalDataCommon.SubMerchantEmail != null) + writer.WriteString("subMerchantEmail", additionalDataCommon.SubMerchantEmail); + + if (additionalDataCommon._SubMerchantIDOption.IsSet) + if (additionalDataCommon.SubMerchantID != null) + writer.WriteString("subMerchantID", additionalDataCommon.SubMerchantID); + + if (additionalDataCommon._SubMerchantNameOption.IsSet) + if (additionalDataCommon.SubMerchantName != null) + writer.WriteString("subMerchantName", additionalDataCommon.SubMerchantName); + + if (additionalDataCommon._SubMerchantPhoneNumberOption.IsSet) + if (additionalDataCommon.SubMerchantPhoneNumber != null) + writer.WriteString("subMerchantPhoneNumber", additionalDataCommon.SubMerchantPhoneNumber); + + if (additionalDataCommon._SubMerchantPostalCodeOption.IsSet) + if (additionalDataCommon.SubMerchantPostalCode != null) + writer.WriteString("subMerchantPostalCode", additionalDataCommon.SubMerchantPostalCode); + + if (additionalDataCommon._SubMerchantStateOption.IsSet) + if (additionalDataCommon.SubMerchantState != null) + writer.WriteString("subMerchantState", additionalDataCommon.SubMerchantState); + + if (additionalDataCommon._SubMerchantStreetOption.IsSet) + if (additionalDataCommon.SubMerchantStreet != null) + writer.WriteString("subMerchantStreet", additionalDataCommon.SubMerchantStreet); + + if (additionalDataCommon._SubMerchantTaxIdOption.IsSet) + if (additionalDataCommon.SubMerchantTaxId != null) + writer.WriteString("subMerchantTaxId", additionalDataCommon.SubMerchantTaxId); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataLevel23.cs b/Adyen/Payment/Models/AdditionalDataLevel23.cs new file mode 100644 index 000000000..c94233d13 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataLevel23.cs @@ -0,0 +1,577 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataLevel23. + /// + public partial class AdditionalDataLevel23 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + [JsonConstructor] + public AdditionalDataLevel23(Option enhancedSchemeDataCustomerReference = default, Option enhancedSchemeDataDestinationCountryCode = default, Option enhancedSchemeDataDestinationPostalCode = default, Option enhancedSchemeDataDestinationStateProvinceCode = default, Option enhancedSchemeDataDutyAmount = default, Option enhancedSchemeDataFreightAmount = default, Option enhancedSchemeDataItemDetailLineItemNrCommodityCode = default, Option enhancedSchemeDataItemDetailLineItemNrDescription = default, Option enhancedSchemeDataItemDetailLineItemNrDiscountAmount = default, Option enhancedSchemeDataItemDetailLineItemNrProductCode = default, Option enhancedSchemeDataItemDetailLineItemNrQuantity = default, Option enhancedSchemeDataItemDetailLineItemNrTotalAmount = default, Option enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = default, Option enhancedSchemeDataItemDetailLineItemNrUnitPrice = default, Option enhancedSchemeDataOrderDate = default, Option enhancedSchemeDataShipFromPostalCode = default, Option enhancedSchemeDataTotalTaxAmount = default) + { + _EnhancedSchemeDataCustomerReferenceOption = enhancedSchemeDataCustomerReference; + _EnhancedSchemeDataDestinationCountryCodeOption = enhancedSchemeDataDestinationCountryCode; + _EnhancedSchemeDataDestinationPostalCodeOption = enhancedSchemeDataDestinationPostalCode; + _EnhancedSchemeDataDestinationStateProvinceCodeOption = enhancedSchemeDataDestinationStateProvinceCode; + _EnhancedSchemeDataDutyAmountOption = enhancedSchemeDataDutyAmount; + _EnhancedSchemeDataFreightAmountOption = enhancedSchemeDataFreightAmount; + _EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption = enhancedSchemeDataItemDetailLineItemNrCommodityCode; + _EnhancedSchemeDataItemDetailLineItemNrDescriptionOption = enhancedSchemeDataItemDetailLineItemNrDescription; + _EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption = enhancedSchemeDataItemDetailLineItemNrDiscountAmount; + _EnhancedSchemeDataItemDetailLineItemNrProductCodeOption = enhancedSchemeDataItemDetailLineItemNrProductCode; + _EnhancedSchemeDataItemDetailLineItemNrQuantityOption = enhancedSchemeDataItemDetailLineItemNrQuantity; + _EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption = enhancedSchemeDataItemDetailLineItemNrTotalAmount; + _EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption = enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure; + _EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption = enhancedSchemeDataItemDetailLineItemNrUnitPrice; + _EnhancedSchemeDataOrderDateOption = enhancedSchemeDataOrderDate; + _EnhancedSchemeDataShipFromPostalCodeOption = enhancedSchemeDataShipFromPostalCode; + _EnhancedSchemeDataTotalTaxAmountOption = enhancedSchemeDataTotalTaxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataLevel23() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataCustomerReferenceOption { get; private set; } + + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The reference number to identify the customer and their order. * Encoding: ASCII * Max length: 25 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.customerReference")] + public string? EnhancedSchemeDataCustomerReference { get { return this._EnhancedSchemeDataCustomerReferenceOption; } set { this._EnhancedSchemeDataCustomerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationCountryCodeOption { get; private set; } + + /// + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + /// + /// The three-letter [ISO 3166-1 alpha-3 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) for the destination address. * Encoding: ASCII * Fixed length: 3 characters + [JsonPropertyName("enhancedSchemeData.destinationCountryCode")] + public string? EnhancedSchemeDataDestinationCountryCode { get { return this._EnhancedSchemeDataDestinationCountryCodeOption; } set { this._EnhancedSchemeDataDestinationCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationPostalCodeOption { get; private set; } + + /// + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// + /// The postal code of the destination address. * Encoding: ASCII * Max length: 10 characters * Must not start with a space. * For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + [JsonPropertyName("enhancedSchemeData.destinationPostalCode")] + public string? EnhancedSchemeDataDestinationPostalCode { get { return this._EnhancedSchemeDataDestinationPostalCodeOption; } set { this._EnhancedSchemeDataDestinationPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDestinationStateProvinceCodeOption { get; private set; } + + /// + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + /// + /// The state or province code of the destination address. * Encoding: ASCII * Max length: 3 characters * Must not start with a space. + [JsonPropertyName("enhancedSchemeData.destinationStateProvinceCode")] + public string? EnhancedSchemeDataDestinationStateProvinceCode { get { return this._EnhancedSchemeDataDestinationStateProvinceCodeOption; } set { this._EnhancedSchemeDataDestinationStateProvinceCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataDutyAmountOption { get; private set; } + + /// + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The duty tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.dutyAmount")] + public string? EnhancedSchemeDataDutyAmount { get { return this._EnhancedSchemeDataDutyAmountOption; } set { this._EnhancedSchemeDataDutyAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataFreightAmountOption { get; private set; } + + /// + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The shipping amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.freightAmount")] + public string? EnhancedSchemeDataFreightAmount { get { return this._EnhancedSchemeDataFreightAmountOption; } set { this._EnhancedSchemeDataFreightAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption { get; private set; } + + /// + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The code that identifies the item in a standardized commodity coding scheme. There are different commodity coding schemes: * [UNSPSC commodity codes](https://www.unspsc.org/) * [HS commodity codes](https://www.wcoomd.org/en/topics/nomenclature/overview.aspx) * [NAICS commodity codes](https://www.census.gov/naics/) * [NAPCS commodity codes](https://www.census.gov/naics/napcs/) * Encoding: ASCII * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].commodityCode")] + public string? EnhancedSchemeDataItemDetailLineItemNrCommodityCode { get { return this._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrDescriptionOption { get; private set; } + + /// + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// A description of the item, that provides details about the purchase. For Visa transactions with level 3 ESD, the description must not be the same or very similar to your merchant name, or, consist only of common words like \"product\", or \"service\". * Encoding: ASCII * Max length: 26 characters * Must not be a single character. * Must not be blank. * Must not be all special characters. * Must not be blank. * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].description")] + public string? EnhancedSchemeDataItemDetailLineItemNrDescription { get { return this._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption { get; private set; } + + /// + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + /// + /// The discount amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].discountAmount")] + public string? EnhancedSchemeDataItemDetailLineItemNrDiscountAmount { get { return this._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrProductCodeOption { get; private set; } + + /// + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The product code. Must be a unique product code associated with the item or service. This can be your unique code for the item, or the manufacturer's product code. * Encoding: ASCII. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].productCode")] + public string? EnhancedSchemeDataItemDetailLineItemNrProductCode { get { return this._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrQuantityOption { get; private set; } + + /// + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + /// + /// The number of items. Must be an integer greater than zero. * Encoding: Numeric * Max length: 12 characters * Must not start with a space or be all spaces. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].quantity")] + public string? EnhancedSchemeDataItemDetailLineItemNrQuantity { get { return this._EnhancedSchemeDataItemDetailLineItemNrQuantityOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrQuantityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption { get; private set; } + + /// + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The total amount for the line item, in [minor units](https://docs.adyen.com/development-resources/currency-codes). See [Amount requirements for level 2/3 ESD](https://docs.adyen.com//payment-methods/cards/enhanced-scheme-data/l2-l3#amount-requirements) to learn more about how to calculate the line item total. * For example, 2000 means USD 20.00. * Max length: 12 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].totalAmount")] + public string? EnhancedSchemeDataItemDetailLineItemNrTotalAmount { get { return this._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption { get; private set; } + + /// + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + /// + /// The unit of measurement for an item. * Encoding: ASCII * Max length: 3 characters * Must not start with a space or be all spaces. * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure")] + public string? EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure { get { return this._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption { get; private set; } + + /// + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + /// + /// The unit price in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.itemDetailLine[itemNr].unitPrice")] + public string? EnhancedSchemeDataItemDetailLineItemNrUnitPrice { get { return this._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption; } set { this._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataOrderDateOption { get; private set; } + + /// + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + /// + /// The order date. * Format: `ddMMyy` * Encoding: ASCII * Max length: 6 characters + [JsonPropertyName("enhancedSchemeData.orderDate")] + public string? EnhancedSchemeDataOrderDate { get { return this._EnhancedSchemeDataOrderDateOption; } set { this._EnhancedSchemeDataOrderDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataShipFromPostalCodeOption { get; private set; } + + /// + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + /// + /// The postal code of the address where the item is shipped from. * Encoding: ASCII * Max length: 10 characters * Must not start with a space or be all spaces. * Must not be all zeros.For the US, it must be in five or nine digits format. For example, 10001 or 10001-0000. * For Canada, it must be in 6 digits format. For example, M4B 1G5. + [JsonPropertyName("enhancedSchemeData.shipFromPostalCode")] + public string? EnhancedSchemeDataShipFromPostalCode { get { return this._EnhancedSchemeDataShipFromPostalCodeOption; } set { this._EnhancedSchemeDataShipFromPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTotalTaxAmountOption { get; private set; } + + /// + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + /// + /// The amount of state or provincial [tax included in the total transaction amount](https://docs.adyen.com/payment-methods/cards/enhanced-scheme-data/l2-l3#requirements-to-send-level-2-3-esd), in [minor units](https://docs.adyen.com/development-resources/currency-codes). * For example, 2000 means USD 20.00. * Encoding: Numeric * Max length: 12 characters * For L2 data: must not be all zeroes. * For L3 data: can be zero. + [JsonPropertyName("enhancedSchemeData.totalTaxAmount")] + public string? EnhancedSchemeDataTotalTaxAmount { get { return this._EnhancedSchemeDataTotalTaxAmountOption; } set { this._EnhancedSchemeDataTotalTaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataLevel23 {\n"); + sb.Append(" EnhancedSchemeDataCustomerReference: ").Append(EnhancedSchemeDataCustomerReference).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationCountryCode: ").Append(EnhancedSchemeDataDestinationCountryCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationPostalCode: ").Append(EnhancedSchemeDataDestinationPostalCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDestinationStateProvinceCode: ").Append(EnhancedSchemeDataDestinationStateProvinceCode).Append("\n"); + sb.Append(" EnhancedSchemeDataDutyAmount: ").Append(EnhancedSchemeDataDutyAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataFreightAmount: ").Append(EnhancedSchemeDataFreightAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrCommodityCode: ").Append(EnhancedSchemeDataItemDetailLineItemNrCommodityCode).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrDescription: ").Append(EnhancedSchemeDataItemDetailLineItemNrDescription).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrDiscountAmount: ").Append(EnhancedSchemeDataItemDetailLineItemNrDiscountAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrProductCode: ").Append(EnhancedSchemeDataItemDetailLineItemNrProductCode).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrQuantity: ").Append(EnhancedSchemeDataItemDetailLineItemNrQuantity).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrTotalAmount: ").Append(EnhancedSchemeDataItemDetailLineItemNrTotalAmount).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure: ").Append(EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure).Append("\n"); + sb.Append(" EnhancedSchemeDataItemDetailLineItemNrUnitPrice: ").Append(EnhancedSchemeDataItemDetailLineItemNrUnitPrice).Append("\n"); + sb.Append(" EnhancedSchemeDataOrderDate: ").Append(EnhancedSchemeDataOrderDate).Append("\n"); + sb.Append(" EnhancedSchemeDataShipFromPostalCode: ").Append(EnhancedSchemeDataShipFromPostalCode).Append("\n"); + sb.Append(" EnhancedSchemeDataTotalTaxAmount: ").Append(EnhancedSchemeDataTotalTaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataLevel23JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataLevel23 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enhancedSchemeDataCustomerReference = default; + Option enhancedSchemeDataDestinationCountryCode = default; + Option enhancedSchemeDataDestinationPostalCode = default; + Option enhancedSchemeDataDestinationStateProvinceCode = default; + Option enhancedSchemeDataDutyAmount = default; + Option enhancedSchemeDataFreightAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrCommodityCode = default; + Option enhancedSchemeDataItemDetailLineItemNrDescription = default; + Option enhancedSchemeDataItemDetailLineItemNrDiscountAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrProductCode = default; + Option enhancedSchemeDataItemDetailLineItemNrQuantity = default; + Option enhancedSchemeDataItemDetailLineItemNrTotalAmount = default; + Option enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = default; + Option enhancedSchemeDataItemDetailLineItemNrUnitPrice = default; + Option enhancedSchemeDataOrderDate = default; + Option enhancedSchemeDataShipFromPostalCode = default; + Option enhancedSchemeDataTotalTaxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enhancedSchemeData.customerReference": + enhancedSchemeDataCustomerReference = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationCountryCode": + enhancedSchemeDataDestinationCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationPostalCode": + enhancedSchemeDataDestinationPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.destinationStateProvinceCode": + enhancedSchemeDataDestinationStateProvinceCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.dutyAmount": + enhancedSchemeDataDutyAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.freightAmount": + enhancedSchemeDataFreightAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].commodityCode": + enhancedSchemeDataItemDetailLineItemNrCommodityCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].description": + enhancedSchemeDataItemDetailLineItemNrDescription = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].discountAmount": + enhancedSchemeDataItemDetailLineItemNrDiscountAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].productCode": + enhancedSchemeDataItemDetailLineItemNrProductCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].quantity": + enhancedSchemeDataItemDetailLineItemNrQuantity = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].totalAmount": + enhancedSchemeDataItemDetailLineItemNrTotalAmount = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure": + enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.itemDetailLine[itemNr].unitPrice": + enhancedSchemeDataItemDetailLineItemNrUnitPrice = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.orderDate": + enhancedSchemeDataOrderDate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.shipFromPostalCode": + enhancedSchemeDataShipFromPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.totalTaxAmount": + enhancedSchemeDataTotalTaxAmount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataLevel23(enhancedSchemeDataCustomerReference, enhancedSchemeDataDestinationCountryCode, enhancedSchemeDataDestinationPostalCode, enhancedSchemeDataDestinationStateProvinceCode, enhancedSchemeDataDutyAmount, enhancedSchemeDataFreightAmount, enhancedSchemeDataItemDetailLineItemNrCommodityCode, enhancedSchemeDataItemDetailLineItemNrDescription, enhancedSchemeDataItemDetailLineItemNrDiscountAmount, enhancedSchemeDataItemDetailLineItemNrProductCode, enhancedSchemeDataItemDetailLineItemNrQuantity, enhancedSchemeDataItemDetailLineItemNrTotalAmount, enhancedSchemeDataItemDetailLineItemNrUnitOfMeasure, enhancedSchemeDataItemDetailLineItemNrUnitPrice, enhancedSchemeDataOrderDate, enhancedSchemeDataShipFromPostalCode, enhancedSchemeDataTotalTaxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataLevel23 additionalDataLevel23, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataLevel23, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataLevel23 additionalDataLevel23, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataLevel23._EnhancedSchemeDataCustomerReferenceOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataCustomerReference != null) + writer.WriteString("enhancedSchemeData.customerReference", additionalDataLevel23.EnhancedSchemeDataCustomerReference); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationCountryCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationCountryCode != null) + writer.WriteString("enhancedSchemeData.destinationCountryCode", additionalDataLevel23.EnhancedSchemeDataDestinationCountryCode); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationPostalCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationPostalCode != null) + writer.WriteString("enhancedSchemeData.destinationPostalCode", additionalDataLevel23.EnhancedSchemeDataDestinationPostalCode); + + if (additionalDataLevel23._EnhancedSchemeDataDestinationStateProvinceCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDestinationStateProvinceCode != null) + writer.WriteString("enhancedSchemeData.destinationStateProvinceCode", additionalDataLevel23.EnhancedSchemeDataDestinationStateProvinceCode); + + if (additionalDataLevel23._EnhancedSchemeDataDutyAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataDutyAmount != null) + writer.WriteString("enhancedSchemeData.dutyAmount", additionalDataLevel23.EnhancedSchemeDataDutyAmount); + + if (additionalDataLevel23._EnhancedSchemeDataFreightAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataFreightAmount != null) + writer.WriteString("enhancedSchemeData.freightAmount", additionalDataLevel23.EnhancedSchemeDataFreightAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrCommodityCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrCommodityCode != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].commodityCode", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrCommodityCode); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrDescriptionOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDescription != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].description", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDescription); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrDiscountAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDiscountAmount != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].discountAmount", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrDiscountAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrProductCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrProductCode != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].productCode", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrProductCode); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrQuantityOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrQuantity != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].quantity", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrQuantity); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrTotalAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrTotalAmount != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].totalAmount", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrTotalAmount); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasureOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].unitOfMeasure", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitOfMeasure); + + if (additionalDataLevel23._EnhancedSchemeDataItemDetailLineItemNrUnitPriceOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitPrice != null) + writer.WriteString("enhancedSchemeData.itemDetailLine[itemNr].unitPrice", additionalDataLevel23.EnhancedSchemeDataItemDetailLineItemNrUnitPrice); + + if (additionalDataLevel23._EnhancedSchemeDataOrderDateOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataOrderDate != null) + writer.WriteString("enhancedSchemeData.orderDate", additionalDataLevel23.EnhancedSchemeDataOrderDate); + + if (additionalDataLevel23._EnhancedSchemeDataShipFromPostalCodeOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataShipFromPostalCode != null) + writer.WriteString("enhancedSchemeData.shipFromPostalCode", additionalDataLevel23.EnhancedSchemeDataShipFromPostalCode); + + if (additionalDataLevel23._EnhancedSchemeDataTotalTaxAmountOption.IsSet) + if (additionalDataLevel23.EnhancedSchemeDataTotalTaxAmount != null) + writer.WriteString("enhancedSchemeData.totalTaxAmount", additionalDataLevel23.EnhancedSchemeDataTotalTaxAmount); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataLodging.cs b/Adyen/Payment/Models/AdditionalDataLodging.cs new file mode 100644 index 000000000..b6e6c2f2c --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataLodging.cs @@ -0,0 +1,577 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataLodging. + /// + public partial class AdditionalDataLodging : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + [JsonConstructor] + public AdditionalDataLodging(Option lodgingSpecialProgramCode = default, Option lodgingCheckInDate = default, Option lodgingCheckOutDate = default, Option lodgingCustomerServiceTollFreeNumber = default, Option lodgingFireSafetyActIndicator = default, Option lodgingFolioCashAdvances = default, Option lodgingFolioNumber = default, Option lodgingFoodBeverageCharges = default, Option lodgingNoShowIndicator = default, Option lodgingPrepaidExpenses = default, Option lodgingPropertyPhoneNumber = default, Option lodgingRoom1NumberOfNights = default, Option lodgingRoom1Rate = default, Option lodgingTotalRoomTax = default, Option lodgingTotalTax = default, Option travelEntertainmentAuthDataDuration = default, Option travelEntertainmentAuthDataMarket = default) + { + _LodgingSpecialProgramCodeOption = lodgingSpecialProgramCode; + _LodgingCheckInDateOption = lodgingCheckInDate; + _LodgingCheckOutDateOption = lodgingCheckOutDate; + _LodgingCustomerServiceTollFreeNumberOption = lodgingCustomerServiceTollFreeNumber; + _LodgingFireSafetyActIndicatorOption = lodgingFireSafetyActIndicator; + _LodgingFolioCashAdvancesOption = lodgingFolioCashAdvances; + _LodgingFolioNumberOption = lodgingFolioNumber; + _LodgingFoodBeverageChargesOption = lodgingFoodBeverageCharges; + _LodgingNoShowIndicatorOption = lodgingNoShowIndicator; + _LodgingPrepaidExpensesOption = lodgingPrepaidExpenses; + _LodgingPropertyPhoneNumberOption = lodgingPropertyPhoneNumber; + _LodgingRoom1NumberOfNightsOption = lodgingRoom1NumberOfNights; + _LodgingRoom1RateOption = lodgingRoom1Rate; + _LodgingTotalRoomTaxOption = lodgingTotalRoomTax; + _LodgingTotalTaxOption = lodgingTotalTax; + _TravelEntertainmentAuthDataDurationOption = travelEntertainmentAuthDataDuration; + _TravelEntertainmentAuthDataMarketOption = travelEntertainmentAuthDataMarket; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataLodging() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingSpecialProgramCodeOption { get; private set; } + + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + /// + /// A code that corresponds to the category of lodging charges for the payment. Possible values: * 1: Lodging * 2: No show reservation * 3: Advanced deposit + [JsonPropertyName("lodging.SpecialProgramCode")] + public string? LodgingSpecialProgramCode { get { return this._LodgingSpecialProgramCodeOption; } set { this._LodgingSpecialProgramCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCheckInDateOption { get; private set; } + + /// + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// + /// The arrival date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + [JsonPropertyName("lodging.checkInDate")] + public string? LodgingCheckInDate { get { return this._LodgingCheckInDateOption; } set { this._LodgingCheckInDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCheckOutDateOption { get; private set; } + + /// + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + /// + /// The departure date. * Date format: **yyyyMmDd**. For example, for 2023 April 22, **20230422**. + [JsonPropertyName("lodging.checkOutDate")] + public string? LodgingCheckOutDate { get { return this._LodgingCheckOutDateOption; } set { this._LodgingCheckOutDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingCustomerServiceTollFreeNumberOption { get; private set; } + + /// + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// + /// The toll-free phone number for the lodging. * Format: numeric * Max length: 17 characters. * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + [JsonPropertyName("lodging.customerServiceTollFreeNumber")] + public string? LodgingCustomerServiceTollFreeNumber { get { return this._LodgingCustomerServiceTollFreeNumberOption; } set { this._LodgingCustomerServiceTollFreeNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFireSafetyActIndicatorOption { get; private set; } + + /// + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + /// + /// Identifies that the facility complies with the Hotel and Motel Fire Safety Act of 1990. Must be 'Y' or 'N'. * Format: alphabetic * Max length: 1 character + [JsonPropertyName("lodging.fireSafetyActIndicator")] + public string? LodgingFireSafetyActIndicator { get { return this._LodgingFireSafetyActIndicatorOption; } set { this._LodgingFireSafetyActIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFolioCashAdvancesOption { get; private set; } + + /// + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// + /// The folio cash advances, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.folioCashAdvances")] + public string? LodgingFolioCashAdvances { get { return this._LodgingFolioCashAdvancesOption; } set { this._LodgingFolioCashAdvancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFolioNumberOption { get; private set; } + + /// + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + /// + /// The card acceptor’s internal invoice or billing ID reference number. * Max length: 25 characters * Must not start with a space * Must not contain any special characters * Must not be all zeros. + [JsonPropertyName("lodging.folioNumber")] + public string? LodgingFolioNumber { get { return this._LodgingFolioNumberOption; } set { this._LodgingFolioNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingFoodBeverageChargesOption { get; private set; } + + /// + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + /// + /// Any charges for food and beverages associated with the booking, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.foodBeverageCharges")] + public string? LodgingFoodBeverageCharges { get { return this._LodgingFoodBeverageChargesOption; } set { this._LodgingFoodBeverageChargesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingNoShowIndicatorOption { get; private set; } + + /// + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + /// + /// Indicates if the customer didn't check in for their booking. Possible values: * **Y**: the customer didn't check in * **N**: the customer checked in + [JsonPropertyName("lodging.noShowIndicator")] + public string? LodgingNoShowIndicator { get { return this._LodgingNoShowIndicatorOption; } set { this._LodgingNoShowIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingPrepaidExpensesOption { get; private set; } + + /// + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + /// + /// The prepaid expenses for the booking. * Format: numeric * Max length: 12 characters + [JsonPropertyName("lodging.prepaidExpenses")] + public string? LodgingPrepaidExpenses { get { return this._LodgingPrepaidExpensesOption; } set { this._LodgingPrepaidExpensesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingPropertyPhoneNumberOption { get; private set; } + + /// + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + /// + /// The lodging property location's phone number. * Format: numeric * Min length: 10 characters * Max length: 17 characters * For US and CA numbers must be 10 characters in length * Must not start with a space * Must not contain any special characters such as + or - * Must not be all zeros. + [JsonPropertyName("lodging.propertyPhoneNumber")] + public string? LodgingPropertyPhoneNumber { get { return this._LodgingPropertyPhoneNumberOption; } set { this._LodgingPropertyPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingRoom1NumberOfNightsOption { get; private set; } + + /// + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + /// + /// The total number of nights the room is booked for. * Format: numeric * Must be a number between 0 and 99 * Max length: 4 characters + [JsonPropertyName("lodging.room1.numberOfNights")] + public string? LodgingRoom1NumberOfNights { get { return this._LodgingRoom1NumberOfNightsOption; } set { this._LodgingRoom1NumberOfNightsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingRoom1RateOption { get; private set; } + + /// + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The rate for the room, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.room1.rate")] + public string? LodgingRoom1Rate { get { return this._LodgingRoom1RateOption; } set { this._LodgingRoom1RateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingTotalRoomTaxOption { get; private set; } + + /// + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The total room tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.totalRoomTax")] + public string? LodgingTotalRoomTax { get { return this._LodgingTotalRoomTaxOption; } set { this._LodgingTotalRoomTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LodgingTotalTaxOption { get; private set; } + + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). * Format: numeric * Max length: 12 characters * Must not be a negative number + [JsonPropertyName("lodging.totalTax")] + public string? LodgingTotalTax { get { return this._LodgingTotalTaxOption; } set { this._LodgingTotalTaxOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataDurationOption { get; private set; } + + /// + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + /// + /// The number of nights. This should be included in the auth message. * Format: numeric * Max length: 4 characters + [JsonPropertyName("travelEntertainmentAuthData.duration")] + public string? TravelEntertainmentAuthDataDuration { get { return this._TravelEntertainmentAuthDataDurationOption; } set { this._TravelEntertainmentAuthDataDurationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TravelEntertainmentAuthDataMarketOption { get; private set; } + + /// + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + /// + /// Indicates what market-specific dataset will be submitted. Must be 'H' for Hotel. This should be included in the auth message. * Format: alphanumeric * Max length: 1 character + [JsonPropertyName("travelEntertainmentAuthData.market")] + public string? TravelEntertainmentAuthDataMarket { get { return this._TravelEntertainmentAuthDataMarketOption; } set { this._TravelEntertainmentAuthDataMarketOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataLodging {\n"); + sb.Append(" LodgingSpecialProgramCode: ").Append(LodgingSpecialProgramCode).Append("\n"); + sb.Append(" LodgingCheckInDate: ").Append(LodgingCheckInDate).Append("\n"); + sb.Append(" LodgingCheckOutDate: ").Append(LodgingCheckOutDate).Append("\n"); + sb.Append(" LodgingCustomerServiceTollFreeNumber: ").Append(LodgingCustomerServiceTollFreeNumber).Append("\n"); + sb.Append(" LodgingFireSafetyActIndicator: ").Append(LodgingFireSafetyActIndicator).Append("\n"); + sb.Append(" LodgingFolioCashAdvances: ").Append(LodgingFolioCashAdvances).Append("\n"); + sb.Append(" LodgingFolioNumber: ").Append(LodgingFolioNumber).Append("\n"); + sb.Append(" LodgingFoodBeverageCharges: ").Append(LodgingFoodBeverageCharges).Append("\n"); + sb.Append(" LodgingNoShowIndicator: ").Append(LodgingNoShowIndicator).Append("\n"); + sb.Append(" LodgingPrepaidExpenses: ").Append(LodgingPrepaidExpenses).Append("\n"); + sb.Append(" LodgingPropertyPhoneNumber: ").Append(LodgingPropertyPhoneNumber).Append("\n"); + sb.Append(" LodgingRoom1NumberOfNights: ").Append(LodgingRoom1NumberOfNights).Append("\n"); + sb.Append(" LodgingRoom1Rate: ").Append(LodgingRoom1Rate).Append("\n"); + sb.Append(" LodgingTotalRoomTax: ").Append(LodgingTotalRoomTax).Append("\n"); + sb.Append(" LodgingTotalTax: ").Append(LodgingTotalTax).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataDuration: ").Append(TravelEntertainmentAuthDataDuration).Append("\n"); + sb.Append(" TravelEntertainmentAuthDataMarket: ").Append(TravelEntertainmentAuthDataMarket).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataLodgingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataLodging Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lodgingSpecialProgramCode = default; + Option lodgingCheckInDate = default; + Option lodgingCheckOutDate = default; + Option lodgingCustomerServiceTollFreeNumber = default; + Option lodgingFireSafetyActIndicator = default; + Option lodgingFolioCashAdvances = default; + Option lodgingFolioNumber = default; + Option lodgingFoodBeverageCharges = default; + Option lodgingNoShowIndicator = default; + Option lodgingPrepaidExpenses = default; + Option lodgingPropertyPhoneNumber = default; + Option lodgingRoom1NumberOfNights = default; + Option lodgingRoom1Rate = default; + Option lodgingTotalRoomTax = default; + Option lodgingTotalTax = default; + Option travelEntertainmentAuthDataDuration = default; + Option travelEntertainmentAuthDataMarket = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "lodging.SpecialProgramCode": + lodgingSpecialProgramCode = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.checkInDate": + lodgingCheckInDate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.checkOutDate": + lodgingCheckOutDate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.customerServiceTollFreeNumber": + lodgingCustomerServiceTollFreeNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.fireSafetyActIndicator": + lodgingFireSafetyActIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.folioCashAdvances": + lodgingFolioCashAdvances = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.folioNumber": + lodgingFolioNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.foodBeverageCharges": + lodgingFoodBeverageCharges = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.noShowIndicator": + lodgingNoShowIndicator = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.prepaidExpenses": + lodgingPrepaidExpenses = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.propertyPhoneNumber": + lodgingPropertyPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.room1.numberOfNights": + lodgingRoom1NumberOfNights = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.room1.rate": + lodgingRoom1Rate = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.totalRoomTax": + lodgingTotalRoomTax = new Option(utf8JsonReader.GetString()!); + break; + case "lodging.totalTax": + lodgingTotalTax = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.duration": + travelEntertainmentAuthDataDuration = new Option(utf8JsonReader.GetString()!); + break; + case "travelEntertainmentAuthData.market": + travelEntertainmentAuthDataMarket = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataLodging(lodgingSpecialProgramCode, lodgingCheckInDate, lodgingCheckOutDate, lodgingCustomerServiceTollFreeNumber, lodgingFireSafetyActIndicator, lodgingFolioCashAdvances, lodgingFolioNumber, lodgingFoodBeverageCharges, lodgingNoShowIndicator, lodgingPrepaidExpenses, lodgingPropertyPhoneNumber, lodgingRoom1NumberOfNights, lodgingRoom1Rate, lodgingTotalRoomTax, lodgingTotalTax, travelEntertainmentAuthDataDuration, travelEntertainmentAuthDataMarket); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataLodging additionalDataLodging, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataLodging, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataLodging additionalDataLodging, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataLodging._LodgingSpecialProgramCodeOption.IsSet) + if (additionalDataLodging.LodgingSpecialProgramCode != null) + writer.WriteString("lodging.SpecialProgramCode", additionalDataLodging.LodgingSpecialProgramCode); + + if (additionalDataLodging._LodgingCheckInDateOption.IsSet) + if (additionalDataLodging.LodgingCheckInDate != null) + writer.WriteString("lodging.checkInDate", additionalDataLodging.LodgingCheckInDate); + + if (additionalDataLodging._LodgingCheckOutDateOption.IsSet) + if (additionalDataLodging.LodgingCheckOutDate != null) + writer.WriteString("lodging.checkOutDate", additionalDataLodging.LodgingCheckOutDate); + + if (additionalDataLodging._LodgingCustomerServiceTollFreeNumberOption.IsSet) + if (additionalDataLodging.LodgingCustomerServiceTollFreeNumber != null) + writer.WriteString("lodging.customerServiceTollFreeNumber", additionalDataLodging.LodgingCustomerServiceTollFreeNumber); + + if (additionalDataLodging._LodgingFireSafetyActIndicatorOption.IsSet) + if (additionalDataLodging.LodgingFireSafetyActIndicator != null) + writer.WriteString("lodging.fireSafetyActIndicator", additionalDataLodging.LodgingFireSafetyActIndicator); + + if (additionalDataLodging._LodgingFolioCashAdvancesOption.IsSet) + if (additionalDataLodging.LodgingFolioCashAdvances != null) + writer.WriteString("lodging.folioCashAdvances", additionalDataLodging.LodgingFolioCashAdvances); + + if (additionalDataLodging._LodgingFolioNumberOption.IsSet) + if (additionalDataLodging.LodgingFolioNumber != null) + writer.WriteString("lodging.folioNumber", additionalDataLodging.LodgingFolioNumber); + + if (additionalDataLodging._LodgingFoodBeverageChargesOption.IsSet) + if (additionalDataLodging.LodgingFoodBeverageCharges != null) + writer.WriteString("lodging.foodBeverageCharges", additionalDataLodging.LodgingFoodBeverageCharges); + + if (additionalDataLodging._LodgingNoShowIndicatorOption.IsSet) + if (additionalDataLodging.LodgingNoShowIndicator != null) + writer.WriteString("lodging.noShowIndicator", additionalDataLodging.LodgingNoShowIndicator); + + if (additionalDataLodging._LodgingPrepaidExpensesOption.IsSet) + if (additionalDataLodging.LodgingPrepaidExpenses != null) + writer.WriteString("lodging.prepaidExpenses", additionalDataLodging.LodgingPrepaidExpenses); + + if (additionalDataLodging._LodgingPropertyPhoneNumberOption.IsSet) + if (additionalDataLodging.LodgingPropertyPhoneNumber != null) + writer.WriteString("lodging.propertyPhoneNumber", additionalDataLodging.LodgingPropertyPhoneNumber); + + if (additionalDataLodging._LodgingRoom1NumberOfNightsOption.IsSet) + if (additionalDataLodging.LodgingRoom1NumberOfNights != null) + writer.WriteString("lodging.room1.numberOfNights", additionalDataLodging.LodgingRoom1NumberOfNights); + + if (additionalDataLodging._LodgingRoom1RateOption.IsSet) + if (additionalDataLodging.LodgingRoom1Rate != null) + writer.WriteString("lodging.room1.rate", additionalDataLodging.LodgingRoom1Rate); + + if (additionalDataLodging._LodgingTotalRoomTaxOption.IsSet) + if (additionalDataLodging.LodgingTotalRoomTax != null) + writer.WriteString("lodging.totalRoomTax", additionalDataLodging.LodgingTotalRoomTax); + + if (additionalDataLodging._LodgingTotalTaxOption.IsSet) + if (additionalDataLodging.LodgingTotalTax != null) + writer.WriteString("lodging.totalTax", additionalDataLodging.LodgingTotalTax); + + if (additionalDataLodging._TravelEntertainmentAuthDataDurationOption.IsSet) + if (additionalDataLodging.TravelEntertainmentAuthDataDuration != null) + writer.WriteString("travelEntertainmentAuthData.duration", additionalDataLodging.TravelEntertainmentAuthDataDuration); + + if (additionalDataLodging._TravelEntertainmentAuthDataMarketOption.IsSet) + if (additionalDataLodging.TravelEntertainmentAuthDataMarket != null) + writer.WriteString("travelEntertainmentAuthData.market", additionalDataLodging.TravelEntertainmentAuthDataMarket); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataModifications.cs b/Adyen/Payment/Models/AdditionalDataModifications.cs new file mode 100644 index 000000000..e5fff8fcb --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataModifications.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataModifications. + /// + public partial class AdditionalDataModifications : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// This is the installment option selected by the shopper. It is required only if specified by the user. + [JsonConstructor] + public AdditionalDataModifications(Option installmentPaymentDataSelectedInstallmentOption = default) + { + _InstallmentPaymentDataSelectedInstallmentOptionOption = installmentPaymentDataSelectedInstallmentOption; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataModifications() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataSelectedInstallmentOptionOption { get; private set; } + + /// + /// This is the installment option selected by the shopper. It is required only if specified by the user. + /// + /// This is the installment option selected by the shopper. It is required only if specified by the user. + [JsonPropertyName("installmentPaymentData.selectedInstallmentOption")] + public string? InstallmentPaymentDataSelectedInstallmentOption { get { return this._InstallmentPaymentDataSelectedInstallmentOptionOption; } set { this._InstallmentPaymentDataSelectedInstallmentOptionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataModifications {\n"); + sb.Append(" InstallmentPaymentDataSelectedInstallmentOption: ").Append(InstallmentPaymentDataSelectedInstallmentOption).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataModificationsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataModifications Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option installmentPaymentDataSelectedInstallmentOption = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "installmentPaymentData.selectedInstallmentOption": + installmentPaymentDataSelectedInstallmentOption = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataModifications(installmentPaymentDataSelectedInstallmentOption); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataModifications additionalDataModifications, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataModifications, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataModifications additionalDataModifications, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataModifications._InstallmentPaymentDataSelectedInstallmentOptionOption.IsSet) + if (additionalDataModifications.InstallmentPaymentDataSelectedInstallmentOption != null) + writer.WriteString("installmentPaymentData.selectedInstallmentOption", additionalDataModifications.InstallmentPaymentDataSelectedInstallmentOption); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataOpenInvoice.cs b/Adyen/Payment/Models/AdditionalDataOpenInvoice.cs new file mode 100644 index 000000000..708e01170 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataOpenInvoice.cs @@ -0,0 +1,602 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataOpenInvoice. + /// + public partial class AdditionalDataOpenInvoice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// The three-character ISO currency code. + /// A text description of the product the invoice line refers to. + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + /// The VAT due for one item in the invoice line, represented in minor units. + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + /// The number of units purchased of a specific product. + /// Name of the shipping company handling the the return shipment. + /// The tracking number for the return of the shipment. + /// URI where the customer can track the return of their shipment. + /// Name of the shipping company handling the delivery. + /// Shipping method. + /// The tracking number for the shipment. + /// URI where the customer can track their shipment. + [JsonConstructor] + public AdditionalDataOpenInvoice(Option openinvoicedataMerchantData = default, Option openinvoicedataNumberOfLines = default, Option openinvoicedataRecipientFirstName = default, Option openinvoicedataRecipientLastName = default, Option openinvoicedataLineItemNrCurrencyCode = default, Option openinvoicedataLineItemNrDescription = default, Option openinvoicedataLineItemNrItemAmount = default, Option openinvoicedataLineItemNrItemId = default, Option openinvoicedataLineItemNrItemVatAmount = default, Option openinvoicedataLineItemNrItemVatPercentage = default, Option openinvoicedataLineItemNrNumberOfItems = default, Option openinvoicedataLineItemNrReturnShippingCompany = default, Option openinvoicedataLineItemNrReturnTrackingNumber = default, Option openinvoicedataLineItemNrReturnTrackingUri = default, Option openinvoicedataLineItemNrShippingCompany = default, Option openinvoicedataLineItemNrShippingMethod = default, Option openinvoicedataLineItemNrTrackingNumber = default, Option openinvoicedataLineItemNrTrackingUri = default) + { + _OpeninvoicedataMerchantDataOption = openinvoicedataMerchantData; + _OpeninvoicedataNumberOfLinesOption = openinvoicedataNumberOfLines; + _OpeninvoicedataRecipientFirstNameOption = openinvoicedataRecipientFirstName; + _OpeninvoicedataRecipientLastNameOption = openinvoicedataRecipientLastName; + _OpeninvoicedataLineItemNrCurrencyCodeOption = openinvoicedataLineItemNrCurrencyCode; + _OpeninvoicedataLineItemNrDescriptionOption = openinvoicedataLineItemNrDescription; + _OpeninvoicedataLineItemNrItemAmountOption = openinvoicedataLineItemNrItemAmount; + _OpeninvoicedataLineItemNrItemIdOption = openinvoicedataLineItemNrItemId; + _OpeninvoicedataLineItemNrItemVatAmountOption = openinvoicedataLineItemNrItemVatAmount; + _OpeninvoicedataLineItemNrItemVatPercentageOption = openinvoicedataLineItemNrItemVatPercentage; + _OpeninvoicedataLineItemNrNumberOfItemsOption = openinvoicedataLineItemNrNumberOfItems; + _OpeninvoicedataLineItemNrReturnShippingCompanyOption = openinvoicedataLineItemNrReturnShippingCompany; + _OpeninvoicedataLineItemNrReturnTrackingNumberOption = openinvoicedataLineItemNrReturnTrackingNumber; + _OpeninvoicedataLineItemNrReturnTrackingUriOption = openinvoicedataLineItemNrReturnTrackingUri; + _OpeninvoicedataLineItemNrShippingCompanyOption = openinvoicedataLineItemNrShippingCompany; + _OpeninvoicedataLineItemNrShippingMethodOption = openinvoicedataLineItemNrShippingMethod; + _OpeninvoicedataLineItemNrTrackingNumberOption = openinvoicedataLineItemNrTrackingNumber; + _OpeninvoicedataLineItemNrTrackingUriOption = openinvoicedataLineItemNrTrackingUri; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataOpenInvoice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataMerchantDataOption { get; private set; } + + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + /// + /// Holds different merchant data points like product, purchase, customer, and so on. It takes data in a Base64 encoded string. The `merchantData` parameter needs to be added to the `openinvoicedata` signature at the end. Since the field is optional, if it's not included it does not impact computing the merchant signature. Applies only to Klarna. You can contact Klarna for the format and structure of the string. + [JsonPropertyName("openinvoicedata.merchantData")] + public string? OpeninvoicedataMerchantData { get { return this._OpeninvoicedataMerchantDataOption; } set { this._OpeninvoicedataMerchantDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataNumberOfLinesOption { get; private set; } + + /// + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + /// + /// The number of invoice lines included in `openinvoicedata`. There needs to be at least one line, so `numberOfLines` needs to be at least 1. + [JsonPropertyName("openinvoicedata.numberOfLines")] + public string? OpeninvoicedataNumberOfLines { get { return this._OpeninvoicedataNumberOfLinesOption; } set { this._OpeninvoicedataNumberOfLinesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataRecipientFirstNameOption { get; private set; } + + /// + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// + /// First name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + [JsonPropertyName("openinvoicedata.recipientFirstName")] + public string? OpeninvoicedataRecipientFirstName { get { return this._OpeninvoicedataRecipientFirstNameOption; } set { this._OpeninvoicedataRecipientFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataRecipientLastNameOption { get; private set; } + + /// + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + /// + /// Last name of the recipient. If the delivery address and the billing address are different, specify the `recipientFirstName` and `recipientLastName` to share the delivery address with Klarna. Otherwise, only the billing address is shared with Klarna. + [JsonPropertyName("openinvoicedata.recipientLastName")] + public string? OpeninvoicedataRecipientLastName { get { return this._OpeninvoicedataRecipientLastNameOption; } set { this._OpeninvoicedataRecipientLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrCurrencyCodeOption { get; private set; } + + /// + /// The three-character ISO currency code. + /// + /// The three-character ISO currency code. + [JsonPropertyName("openinvoicedataLine[itemNr].currencyCode")] + public string? OpeninvoicedataLineItemNrCurrencyCode { get { return this._OpeninvoicedataLineItemNrCurrencyCodeOption; } set { this._OpeninvoicedataLineItemNrCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrDescriptionOption { get; private set; } + + /// + /// A text description of the product the invoice line refers to. + /// + /// A text description of the product the invoice line refers to. + [JsonPropertyName("openinvoicedataLine[itemNr].description")] + public string? OpeninvoicedataLineItemNrDescription { get { return this._OpeninvoicedataLineItemNrDescriptionOption; } set { this._OpeninvoicedataLineItemNrDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemAmountOption { get; private set; } + + /// + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + /// + /// The price for one item in the invoice line, represented in minor units. The due amount for the item, VAT excluded. + [JsonPropertyName("openinvoicedataLine[itemNr].itemAmount")] + public string? OpeninvoicedataLineItemNrItemAmount { get { return this._OpeninvoicedataLineItemNrItemAmountOption; } set { this._OpeninvoicedataLineItemNrItemAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemIdOption { get; private set; } + + /// + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + /// + /// A unique id for this item. Required for RatePay if the description of each item is not unique. + [JsonPropertyName("openinvoicedataLine[itemNr].itemId")] + public string? OpeninvoicedataLineItemNrItemId { get { return this._OpeninvoicedataLineItemNrItemIdOption; } set { this._OpeninvoicedataLineItemNrItemIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemVatAmountOption { get; private set; } + + /// + /// The VAT due for one item in the invoice line, represented in minor units. + /// + /// The VAT due for one item in the invoice line, represented in minor units. + [JsonPropertyName("openinvoicedataLine[itemNr].itemVatAmount")] + public string? OpeninvoicedataLineItemNrItemVatAmount { get { return this._OpeninvoicedataLineItemNrItemVatAmountOption; } set { this._OpeninvoicedataLineItemNrItemVatAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrItemVatPercentageOption { get; private set; } + + /// + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + /// + /// The VAT percentage for one item in the invoice line, represented in minor units. For example, 19% VAT is specified as 1900. + [JsonPropertyName("openinvoicedataLine[itemNr].itemVatPercentage")] + public string? OpeninvoicedataLineItemNrItemVatPercentage { get { return this._OpeninvoicedataLineItemNrItemVatPercentageOption; } set { this._OpeninvoicedataLineItemNrItemVatPercentageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrNumberOfItemsOption { get; private set; } + + /// + /// The number of units purchased of a specific product. + /// + /// The number of units purchased of a specific product. + [JsonPropertyName("openinvoicedataLine[itemNr].numberOfItems")] + public string? OpeninvoicedataLineItemNrNumberOfItems { get { return this._OpeninvoicedataLineItemNrNumberOfItemsOption; } set { this._OpeninvoicedataLineItemNrNumberOfItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnShippingCompanyOption { get; private set; } + + /// + /// Name of the shipping company handling the the return shipment. + /// + /// Name of the shipping company handling the the return shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnShippingCompany")] + public string? OpeninvoicedataLineItemNrReturnShippingCompany { get { return this._OpeninvoicedataLineItemNrReturnShippingCompanyOption; } set { this._OpeninvoicedataLineItemNrReturnShippingCompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnTrackingNumberOption { get; private set; } + + /// + /// The tracking number for the return of the shipment. + /// + /// The tracking number for the return of the shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnTrackingNumber")] + public string? OpeninvoicedataLineItemNrReturnTrackingNumber { get { return this._OpeninvoicedataLineItemNrReturnTrackingNumberOption; } set { this._OpeninvoicedataLineItemNrReturnTrackingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrReturnTrackingUriOption { get; private set; } + + /// + /// URI where the customer can track the return of their shipment. + /// + /// URI where the customer can track the return of their shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].returnTrackingUri")] + public string? OpeninvoicedataLineItemNrReturnTrackingUri { get { return this._OpeninvoicedataLineItemNrReturnTrackingUriOption; } set { this._OpeninvoicedataLineItemNrReturnTrackingUriOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrShippingCompanyOption { get; private set; } + + /// + /// Name of the shipping company handling the delivery. + /// + /// Name of the shipping company handling the delivery. + [JsonPropertyName("openinvoicedataLine[itemNr].shippingCompany")] + public string? OpeninvoicedataLineItemNrShippingCompany { get { return this._OpeninvoicedataLineItemNrShippingCompanyOption; } set { this._OpeninvoicedataLineItemNrShippingCompanyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrShippingMethodOption { get; private set; } + + /// + /// Shipping method. + /// + /// Shipping method. + [JsonPropertyName("openinvoicedataLine[itemNr].shippingMethod")] + public string? OpeninvoicedataLineItemNrShippingMethod { get { return this._OpeninvoicedataLineItemNrShippingMethodOption; } set { this._OpeninvoicedataLineItemNrShippingMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrTrackingNumberOption { get; private set; } + + /// + /// The tracking number for the shipment. + /// + /// The tracking number for the shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].trackingNumber")] + public string? OpeninvoicedataLineItemNrTrackingNumber { get { return this._OpeninvoicedataLineItemNrTrackingNumberOption; } set { this._OpeninvoicedataLineItemNrTrackingNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpeninvoicedataLineItemNrTrackingUriOption { get; private set; } + + /// + /// URI where the customer can track their shipment. + /// + /// URI where the customer can track their shipment. + [JsonPropertyName("openinvoicedataLine[itemNr].trackingUri")] + public string? OpeninvoicedataLineItemNrTrackingUri { get { return this._OpeninvoicedataLineItemNrTrackingUriOption; } set { this._OpeninvoicedataLineItemNrTrackingUriOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataOpenInvoice {\n"); + sb.Append(" OpeninvoicedataMerchantData: ").Append(OpeninvoicedataMerchantData).Append("\n"); + sb.Append(" OpeninvoicedataNumberOfLines: ").Append(OpeninvoicedataNumberOfLines).Append("\n"); + sb.Append(" OpeninvoicedataRecipientFirstName: ").Append(OpeninvoicedataRecipientFirstName).Append("\n"); + sb.Append(" OpeninvoicedataRecipientLastName: ").Append(OpeninvoicedataRecipientLastName).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrCurrencyCode: ").Append(OpeninvoicedataLineItemNrCurrencyCode).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrDescription: ").Append(OpeninvoicedataLineItemNrDescription).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemAmount: ").Append(OpeninvoicedataLineItemNrItemAmount).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemId: ").Append(OpeninvoicedataLineItemNrItemId).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemVatAmount: ").Append(OpeninvoicedataLineItemNrItemVatAmount).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrItemVatPercentage: ").Append(OpeninvoicedataLineItemNrItemVatPercentage).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrNumberOfItems: ").Append(OpeninvoicedataLineItemNrNumberOfItems).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnShippingCompany: ").Append(OpeninvoicedataLineItemNrReturnShippingCompany).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnTrackingNumber: ").Append(OpeninvoicedataLineItemNrReturnTrackingNumber).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrReturnTrackingUri: ").Append(OpeninvoicedataLineItemNrReturnTrackingUri).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrShippingCompany: ").Append(OpeninvoicedataLineItemNrShippingCompany).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrShippingMethod: ").Append(OpeninvoicedataLineItemNrShippingMethod).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrTrackingNumber: ").Append(OpeninvoicedataLineItemNrTrackingNumber).Append("\n"); + sb.Append(" OpeninvoicedataLineItemNrTrackingUri: ").Append(OpeninvoicedataLineItemNrTrackingUri).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataOpenInvoiceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataOpenInvoice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option openinvoicedataMerchantData = default; + Option openinvoicedataNumberOfLines = default; + Option openinvoicedataRecipientFirstName = default; + Option openinvoicedataRecipientLastName = default; + Option openinvoicedataLineItemNrCurrencyCode = default; + Option openinvoicedataLineItemNrDescription = default; + Option openinvoicedataLineItemNrItemAmount = default; + Option openinvoicedataLineItemNrItemId = default; + Option openinvoicedataLineItemNrItemVatAmount = default; + Option openinvoicedataLineItemNrItemVatPercentage = default; + Option openinvoicedataLineItemNrNumberOfItems = default; + Option openinvoicedataLineItemNrReturnShippingCompany = default; + Option openinvoicedataLineItemNrReturnTrackingNumber = default; + Option openinvoicedataLineItemNrReturnTrackingUri = default; + Option openinvoicedataLineItemNrShippingCompany = default; + Option openinvoicedataLineItemNrShippingMethod = default; + Option openinvoicedataLineItemNrTrackingNumber = default; + Option openinvoicedataLineItemNrTrackingUri = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "openinvoicedata.merchantData": + openinvoicedataMerchantData = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.numberOfLines": + openinvoicedataNumberOfLines = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.recipientFirstName": + openinvoicedataRecipientFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedata.recipientLastName": + openinvoicedataRecipientLastName = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].currencyCode": + openinvoicedataLineItemNrCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].description": + openinvoicedataLineItemNrDescription = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemAmount": + openinvoicedataLineItemNrItemAmount = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemId": + openinvoicedataLineItemNrItemId = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemVatAmount": + openinvoicedataLineItemNrItemVatAmount = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].itemVatPercentage": + openinvoicedataLineItemNrItemVatPercentage = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].numberOfItems": + openinvoicedataLineItemNrNumberOfItems = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnShippingCompany": + openinvoicedataLineItemNrReturnShippingCompany = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnTrackingNumber": + openinvoicedataLineItemNrReturnTrackingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].returnTrackingUri": + openinvoicedataLineItemNrReturnTrackingUri = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].shippingCompany": + openinvoicedataLineItemNrShippingCompany = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].shippingMethod": + openinvoicedataLineItemNrShippingMethod = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].trackingNumber": + openinvoicedataLineItemNrTrackingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "openinvoicedataLine[itemNr].trackingUri": + openinvoicedataLineItemNrTrackingUri = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataOpenInvoice(openinvoicedataMerchantData, openinvoicedataNumberOfLines, openinvoicedataRecipientFirstName, openinvoicedataRecipientLastName, openinvoicedataLineItemNrCurrencyCode, openinvoicedataLineItemNrDescription, openinvoicedataLineItemNrItemAmount, openinvoicedataLineItemNrItemId, openinvoicedataLineItemNrItemVatAmount, openinvoicedataLineItemNrItemVatPercentage, openinvoicedataLineItemNrNumberOfItems, openinvoicedataLineItemNrReturnShippingCompany, openinvoicedataLineItemNrReturnTrackingNumber, openinvoicedataLineItemNrReturnTrackingUri, openinvoicedataLineItemNrShippingCompany, openinvoicedataLineItemNrShippingMethod, openinvoicedataLineItemNrTrackingNumber, openinvoicedataLineItemNrTrackingUri); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataOpenInvoice additionalDataOpenInvoice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataOpenInvoice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataOpenInvoice additionalDataOpenInvoice, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataOpenInvoice._OpeninvoicedataMerchantDataOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataMerchantData != null) + writer.WriteString("openinvoicedata.merchantData", additionalDataOpenInvoice.OpeninvoicedataMerchantData); + + if (additionalDataOpenInvoice._OpeninvoicedataNumberOfLinesOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataNumberOfLines != null) + writer.WriteString("openinvoicedata.numberOfLines", additionalDataOpenInvoice.OpeninvoicedataNumberOfLines); + + if (additionalDataOpenInvoice._OpeninvoicedataRecipientFirstNameOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataRecipientFirstName != null) + writer.WriteString("openinvoicedata.recipientFirstName", additionalDataOpenInvoice.OpeninvoicedataRecipientFirstName); + + if (additionalDataOpenInvoice._OpeninvoicedataRecipientLastNameOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataRecipientLastName != null) + writer.WriteString("openinvoicedata.recipientLastName", additionalDataOpenInvoice.OpeninvoicedataRecipientLastName); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrCurrencyCodeOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrCurrencyCode != null) + writer.WriteString("openinvoicedataLine[itemNr].currencyCode", additionalDataOpenInvoice.OpeninvoicedataLineItemNrCurrencyCode); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrDescriptionOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrDescription != null) + writer.WriteString("openinvoicedataLine[itemNr].description", additionalDataOpenInvoice.OpeninvoicedataLineItemNrDescription); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemAmountOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemAmount != null) + writer.WriteString("openinvoicedataLine[itemNr].itemAmount", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemAmount); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemIdOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemId != null) + writer.WriteString("openinvoicedataLine[itemNr].itemId", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemId); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemVatAmountOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatAmount != null) + writer.WriteString("openinvoicedataLine[itemNr].itemVatAmount", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatAmount); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrItemVatPercentageOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatPercentage != null) + writer.WriteString("openinvoicedataLine[itemNr].itemVatPercentage", additionalDataOpenInvoice.OpeninvoicedataLineItemNrItemVatPercentage); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrNumberOfItemsOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrNumberOfItems != null) + writer.WriteString("openinvoicedataLine[itemNr].numberOfItems", additionalDataOpenInvoice.OpeninvoicedataLineItemNrNumberOfItems); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnShippingCompanyOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnShippingCompany != null) + writer.WriteString("openinvoicedataLine[itemNr].returnShippingCompany", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnShippingCompany); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnTrackingNumberOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingNumber != null) + writer.WriteString("openinvoicedataLine[itemNr].returnTrackingNumber", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingNumber); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrReturnTrackingUriOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingUri != null) + writer.WriteString("openinvoicedataLine[itemNr].returnTrackingUri", additionalDataOpenInvoice.OpeninvoicedataLineItemNrReturnTrackingUri); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrShippingCompanyOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingCompany != null) + writer.WriteString("openinvoicedataLine[itemNr].shippingCompany", additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingCompany); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrShippingMethodOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingMethod != null) + writer.WriteString("openinvoicedataLine[itemNr].shippingMethod", additionalDataOpenInvoice.OpeninvoicedataLineItemNrShippingMethod); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrTrackingNumberOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingNumber != null) + writer.WriteString("openinvoicedataLine[itemNr].trackingNumber", additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingNumber); + + if (additionalDataOpenInvoice._OpeninvoicedataLineItemNrTrackingUriOption.IsSet) + if (additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingUri != null) + writer.WriteString("openinvoicedataLine[itemNr].trackingUri", additionalDataOpenInvoice.OpeninvoicedataLineItemNrTrackingUri); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataOpi.cs b/Adyen/Payment/Models/AdditionalDataOpi.cs new file mode 100644 index 000000000..67dc87a04 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataOpi.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataOpi. + /// + public partial class AdditionalDataOpi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonConstructor] + public AdditionalDataOpi(Option opiIncludeTransToken = default) + { + _OpiIncludeTransTokenOption = opiIncludeTransToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataOpi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiIncludeTransTokenOption { get; private set; } + + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + /// + /// Optional boolean indicator. Set to **true** if you want an ecommerce transaction to return an `opi.transToken` as additional data in the response. You can store this Oracle Payment Interface token in your Oracle Opera database. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonPropertyName("opi.includeTransToken")] + public string? OpiIncludeTransToken { get { return this._OpiIncludeTransTokenOption; } set { this._OpiIncludeTransTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataOpi {\n"); + sb.Append(" OpiIncludeTransToken: ").Append(OpiIncludeTransToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataOpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataOpi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option opiIncludeTransToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "opi.includeTransToken": + opiIncludeTransToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataOpi(opiIncludeTransToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataOpi additionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataOpi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataOpi additionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataOpi._OpiIncludeTransTokenOption.IsSet) + if (additionalDataOpi.OpiIncludeTransToken != null) + writer.WriteString("opi.includeTransToken", additionalDataOpi.OpiIncludeTransToken); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataRatepay.cs b/Adyen/Payment/Models/AdditionalDataRatepay.cs new file mode 100644 index 000000000..f4b4892ce --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataRatepay.cs @@ -0,0 +1,352 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataRatepay. + /// + public partial class AdditionalDataRatepay : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Amount the customer has to pay each month. + /// Interest rate of this installment. + /// Amount of the last installment. + /// Calendar day of the first payment. + /// Date the merchant delivered the goods to the customer. + /// Date by which the customer must settle the payment. + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + /// Identification name or number for the invoice, defined by the merchant. + [JsonConstructor] + public AdditionalDataRatepay(Option ratepayInstallmentAmount = default, Option ratepayInterestRate = default, Option ratepayLastInstallmentAmount = default, Option ratepayPaymentFirstday = default, Option ratepaydataDeliveryDate = default, Option ratepaydataDueDate = default, Option ratepaydataInvoiceDate = default, Option ratepaydataInvoiceId = default) + { + _RatepayInstallmentAmountOption = ratepayInstallmentAmount; + _RatepayInterestRateOption = ratepayInterestRate; + _RatepayLastInstallmentAmountOption = ratepayLastInstallmentAmount; + _RatepayPaymentFirstdayOption = ratepayPaymentFirstday; + _RatepaydataDeliveryDateOption = ratepaydataDeliveryDate; + _RatepaydataDueDateOption = ratepaydataDueDate; + _RatepaydataInvoiceDateOption = ratepaydataInvoiceDate; + _RatepaydataInvoiceIdOption = ratepaydataInvoiceId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRatepay() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayInstallmentAmountOption { get; private set; } + + /// + /// Amount the customer has to pay each month. + /// + /// Amount the customer has to pay each month. + [JsonPropertyName("ratepay.installmentAmount")] + public string? RatepayInstallmentAmount { get { return this._RatepayInstallmentAmountOption; } set { this._RatepayInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayInterestRateOption { get; private set; } + + /// + /// Interest rate of this installment. + /// + /// Interest rate of this installment. + [JsonPropertyName("ratepay.interestRate")] + public string? RatepayInterestRate { get { return this._RatepayInterestRateOption; } set { this._RatepayInterestRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayLastInstallmentAmountOption { get; private set; } + + /// + /// Amount of the last installment. + /// + /// Amount of the last installment. + [JsonPropertyName("ratepay.lastInstallmentAmount")] + public string? RatepayLastInstallmentAmount { get { return this._RatepayLastInstallmentAmountOption; } set { this._RatepayLastInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepayPaymentFirstdayOption { get; private set; } + + /// + /// Calendar day of the first payment. + /// + /// Calendar day of the first payment. + [JsonPropertyName("ratepay.paymentFirstday")] + public string? RatepayPaymentFirstday { get { return this._RatepayPaymentFirstdayOption; } set { this._RatepayPaymentFirstdayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataDeliveryDateOption { get; private set; } + + /// + /// Date the merchant delivered the goods to the customer. + /// + /// Date the merchant delivered the goods to the customer. + [JsonPropertyName("ratepaydata.deliveryDate")] + public string? RatepaydataDeliveryDate { get { return this._RatepaydataDeliveryDateOption; } set { this._RatepaydataDeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataDueDateOption { get; private set; } + + /// + /// Date by which the customer must settle the payment. + /// + /// Date by which the customer must settle the payment. + [JsonPropertyName("ratepaydata.dueDate")] + public string? RatepaydataDueDate { get { return this._RatepaydataDueDateOption; } set { this._RatepaydataDueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataInvoiceDateOption { get; private set; } + + /// + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + /// + /// Invoice date, defined by the merchant. If not included, the invoice date is set to the delivery date. + [JsonPropertyName("ratepaydata.invoiceDate")] + public string? RatepaydataInvoiceDate { get { return this._RatepaydataInvoiceDateOption; } set { this._RatepaydataInvoiceDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RatepaydataInvoiceIdOption { get; private set; } + + /// + /// Identification name or number for the invoice, defined by the merchant. + /// + /// Identification name or number for the invoice, defined by the merchant. + [JsonPropertyName("ratepaydata.invoiceId")] + public string? RatepaydataInvoiceId { get { return this._RatepaydataInvoiceIdOption; } set { this._RatepaydataInvoiceIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRatepay {\n"); + sb.Append(" RatepayInstallmentAmount: ").Append(RatepayInstallmentAmount).Append("\n"); + sb.Append(" RatepayInterestRate: ").Append(RatepayInterestRate).Append("\n"); + sb.Append(" RatepayLastInstallmentAmount: ").Append(RatepayLastInstallmentAmount).Append("\n"); + sb.Append(" RatepayPaymentFirstday: ").Append(RatepayPaymentFirstday).Append("\n"); + sb.Append(" RatepaydataDeliveryDate: ").Append(RatepaydataDeliveryDate).Append("\n"); + sb.Append(" RatepaydataDueDate: ").Append(RatepaydataDueDate).Append("\n"); + sb.Append(" RatepaydataInvoiceDate: ").Append(RatepaydataInvoiceDate).Append("\n"); + sb.Append(" RatepaydataInvoiceId: ").Append(RatepaydataInvoiceId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRatepayJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRatepay Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option ratepayInstallmentAmount = default; + Option ratepayInterestRate = default; + Option ratepayLastInstallmentAmount = default; + Option ratepayPaymentFirstday = default; + Option ratepaydataDeliveryDate = default; + Option ratepaydataDueDate = default; + Option ratepaydataInvoiceDate = default; + Option ratepaydataInvoiceId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "ratepay.installmentAmount": + ratepayInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.interestRate": + ratepayInterestRate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.lastInstallmentAmount": + ratepayLastInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "ratepay.paymentFirstday": + ratepayPaymentFirstday = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.deliveryDate": + ratepaydataDeliveryDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.dueDate": + ratepaydataDueDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.invoiceDate": + ratepaydataInvoiceDate = new Option(utf8JsonReader.GetString()!); + break; + case "ratepaydata.invoiceId": + ratepaydataInvoiceId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRatepay(ratepayInstallmentAmount, ratepayInterestRate, ratepayLastInstallmentAmount, ratepayPaymentFirstday, ratepaydataDeliveryDate, ratepaydataDueDate, ratepaydataInvoiceDate, ratepaydataInvoiceId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRatepay additionalDataRatepay, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRatepay, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRatepay additionalDataRatepay, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRatepay._RatepayInstallmentAmountOption.IsSet) + if (additionalDataRatepay.RatepayInstallmentAmount != null) + writer.WriteString("ratepay.installmentAmount", additionalDataRatepay.RatepayInstallmentAmount); + + if (additionalDataRatepay._RatepayInterestRateOption.IsSet) + if (additionalDataRatepay.RatepayInterestRate != null) + writer.WriteString("ratepay.interestRate", additionalDataRatepay.RatepayInterestRate); + + if (additionalDataRatepay._RatepayLastInstallmentAmountOption.IsSet) + if (additionalDataRatepay.RatepayLastInstallmentAmount != null) + writer.WriteString("ratepay.lastInstallmentAmount", additionalDataRatepay.RatepayLastInstallmentAmount); + + if (additionalDataRatepay._RatepayPaymentFirstdayOption.IsSet) + if (additionalDataRatepay.RatepayPaymentFirstday != null) + writer.WriteString("ratepay.paymentFirstday", additionalDataRatepay.RatepayPaymentFirstday); + + if (additionalDataRatepay._RatepaydataDeliveryDateOption.IsSet) + if (additionalDataRatepay.RatepaydataDeliveryDate != null) + writer.WriteString("ratepaydata.deliveryDate", additionalDataRatepay.RatepaydataDeliveryDate); + + if (additionalDataRatepay._RatepaydataDueDateOption.IsSet) + if (additionalDataRatepay.RatepaydataDueDate != null) + writer.WriteString("ratepaydata.dueDate", additionalDataRatepay.RatepaydataDueDate); + + if (additionalDataRatepay._RatepaydataInvoiceDateOption.IsSet) + if (additionalDataRatepay.RatepaydataInvoiceDate != null) + writer.WriteString("ratepaydata.invoiceDate", additionalDataRatepay.RatepaydataInvoiceDate); + + if (additionalDataRatepay._RatepaydataInvoiceIdOption.IsSet) + if (additionalDataRatepay.RatepaydataInvoiceId != null) + writer.WriteString("ratepaydata.invoiceId", additionalDataRatepay.RatepaydataInvoiceId); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataRetry.cs b/Adyen/Payment/Models/AdditionalDataRetry.cs new file mode 100644 index 000000000..0796574fc --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataRetry.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataRetry. + /// + public partial class AdditionalDataRetry : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonConstructor] + public AdditionalDataRetry(Option retryChainAttemptNumber = default, Option retryOrderAttemptNumber = default, Option retrySkipRetry = default) + { + _RetryChainAttemptNumberOption = retryChainAttemptNumber; + _RetryOrderAttemptNumberOption = retryOrderAttemptNumber; + _RetrySkipRetryOption = retrySkipRetry; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRetry() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetryChainAttemptNumberOption { get; private set; } + + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The number of times the transaction (not order) has been retried between different payment service providers. For instance, the `chainAttemptNumber` set to 2 means that this transaction has been recently tried on another provider before being sent to Adyen. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.chainAttemptNumber")] + public string? RetryChainAttemptNumber { get { return this._RetryChainAttemptNumberOption; } set { this._RetryChainAttemptNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetryOrderAttemptNumberOption { get; private set; } + + /// + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The index of the attempt to bill a particular order, which is identified by the `merchantOrderReference` field. For example, if a recurring transaction fails and is retried one day later, then the order number for these attempts would be 1 and 2, respectively. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.orderAttemptNumber")] + public string? RetryOrderAttemptNumber { get { return this._RetryOrderAttemptNumberOption; } set { this._RetryOrderAttemptNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RetrySkipRetryOption { get; private set; } + + /// + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + /// + /// The Boolean value indicating whether Adyen should skip or retry this transaction, if possible. > If you submit `retry.chainAttemptNumber`, `retry.orderAttemptNumber`, and `retry.skipRetry` values, we also recommend you provide the `merchantOrderReference` to facilitate linking payment attempts together. + [JsonPropertyName("retry.skipRetry")] + public string? RetrySkipRetry { get { return this._RetrySkipRetryOption; } set { this._RetrySkipRetryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRetry {\n"); + sb.Append(" RetryChainAttemptNumber: ").Append(RetryChainAttemptNumber).Append("\n"); + sb.Append(" RetryOrderAttemptNumber: ").Append(RetryOrderAttemptNumber).Append("\n"); + sb.Append(" RetrySkipRetry: ").Append(RetrySkipRetry).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRetryJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRetry Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option retryChainAttemptNumber = default; + Option retryOrderAttemptNumber = default; + Option retrySkipRetry = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "retry.chainAttemptNumber": + retryChainAttemptNumber = new Option(utf8JsonReader.GetString()!); + break; + case "retry.orderAttemptNumber": + retryOrderAttemptNumber = new Option(utf8JsonReader.GetString()!); + break; + case "retry.skipRetry": + retrySkipRetry = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRetry(retryChainAttemptNumber, retryOrderAttemptNumber, retrySkipRetry); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRetry additionalDataRetry, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRetry, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRetry additionalDataRetry, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRetry._RetryChainAttemptNumberOption.IsSet) + if (additionalDataRetry.RetryChainAttemptNumber != null) + writer.WriteString("retry.chainAttemptNumber", additionalDataRetry.RetryChainAttemptNumber); + + if (additionalDataRetry._RetryOrderAttemptNumberOption.IsSet) + if (additionalDataRetry.RetryOrderAttemptNumber != null) + writer.WriteString("retry.orderAttemptNumber", additionalDataRetry.RetryOrderAttemptNumber); + + if (additionalDataRetry._RetrySkipRetryOption.IsSet) + if (additionalDataRetry.RetrySkipRetry != null) + writer.WriteString("retry.skipRetry", additionalDataRetry.RetrySkipRetry); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataRisk.cs b/Adyen/Payment/Models/AdditionalDataRisk.cs new file mode 100644 index 000000000..f3ecaa225 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataRisk.cs @@ -0,0 +1,677 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataRisk. + /// + public partial class AdditionalDataRisk : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// Brand of the item. + /// Category of the item. + /// Color of the item. + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// ID of the item. + /// Manufacturer of the item. + /// A text description of the product the invoice line refers to. + /// Quantity of the item purchased. + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// Size of the item. + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + /// Code of the promotion. + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + /// Name of the promotion. + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + [JsonConstructor] + public AdditionalDataRisk(Option riskdataCustomFieldName = default, Option riskdataBasketItemItemNrAmountPerItem = default, Option riskdataBasketItemItemNrBrand = default, Option riskdataBasketItemItemNrCategory = default, Option riskdataBasketItemItemNrColor = default, Option riskdataBasketItemItemNrCurrency = default, Option riskdataBasketItemItemNrItemID = default, Option riskdataBasketItemItemNrManufacturer = default, Option riskdataBasketItemItemNrProductTitle = default, Option riskdataBasketItemItemNrQuantity = default, Option riskdataBasketItemItemNrReceiverEmail = default, Option riskdataBasketItemItemNrSize = default, Option riskdataBasketItemItemNrSku = default, Option riskdataBasketItemItemNrUpc = default, Option riskdataPromotionsPromotionItemNrPromotionCode = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountAmount = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = default, Option riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = default, Option riskdataPromotionsPromotionItemNrPromotionName = default, Option riskdataRiskProfileReference = default, Option riskdataSkipRisk = default) + { + _RiskdataCustomFieldNameOption = riskdataCustomFieldName; + _RiskdataBasketItemItemNrAmountPerItemOption = riskdataBasketItemItemNrAmountPerItem; + _RiskdataBasketItemItemNrBrandOption = riskdataBasketItemItemNrBrand; + _RiskdataBasketItemItemNrCategoryOption = riskdataBasketItemItemNrCategory; + _RiskdataBasketItemItemNrColorOption = riskdataBasketItemItemNrColor; + _RiskdataBasketItemItemNrCurrencyOption = riskdataBasketItemItemNrCurrency; + _RiskdataBasketItemItemNrItemIDOption = riskdataBasketItemItemNrItemID; + _RiskdataBasketItemItemNrManufacturerOption = riskdataBasketItemItemNrManufacturer; + _RiskdataBasketItemItemNrProductTitleOption = riskdataBasketItemItemNrProductTitle; + _RiskdataBasketItemItemNrQuantityOption = riskdataBasketItemItemNrQuantity; + _RiskdataBasketItemItemNrReceiverEmailOption = riskdataBasketItemItemNrReceiverEmail; + _RiskdataBasketItemItemNrSizeOption = riskdataBasketItemItemNrSize; + _RiskdataBasketItemItemNrSkuOption = riskdataBasketItemItemNrSku; + _RiskdataBasketItemItemNrUpcOption = riskdataBasketItemItemNrUpc; + _RiskdataPromotionsPromotionItemNrPromotionCodeOption = riskdataPromotionsPromotionItemNrPromotionCode; + _RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption = riskdataPromotionsPromotionItemNrPromotionDiscountAmount; + _RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption = riskdataPromotionsPromotionItemNrPromotionDiscountCurrency; + _RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption = riskdataPromotionsPromotionItemNrPromotionDiscountPercentage; + _RiskdataPromotionsPromotionItemNrPromotionNameOption = riskdataPromotionsPromotionItemNrPromotionName; + _RiskdataRiskProfileReferenceOption = riskdataRiskProfileReference; + _RiskdataSkipRiskOption = riskdataSkipRisk; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRisk() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataCustomFieldNameOption { get; private set; } + + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + /// + /// The data for your custom risk field. For more information, refer to [Create custom risk fields](https://docs.adyen.com/risk-management/configure-custom-risk-rules#step-1-create-custom-risk-fields). + [JsonPropertyName("riskdata.[customFieldName]")] + public string? RiskdataCustomFieldName { get { return this._RiskdataCustomFieldNameOption; } set { this._RiskdataCustomFieldNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrAmountPerItemOption { get; private set; } + + /// + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The price of item in the basket, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("riskdata.basket.item[itemNr].amountPerItem")] + public string? RiskdataBasketItemItemNrAmountPerItem { get { return this._RiskdataBasketItemItemNrAmountPerItemOption; } set { this._RiskdataBasketItemItemNrAmountPerItemOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrBrandOption { get; private set; } + + /// + /// Brand of the item. + /// + /// Brand of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].brand")] + public string? RiskdataBasketItemItemNrBrand { get { return this._RiskdataBasketItemItemNrBrandOption; } set { this._RiskdataBasketItemItemNrBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrCategoryOption { get; private set; } + + /// + /// Category of the item. + /// + /// Category of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].category")] + public string? RiskdataBasketItemItemNrCategory { get { return this._RiskdataBasketItemItemNrCategoryOption; } set { this._RiskdataBasketItemItemNrCategoryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrColorOption { get; private set; } + + /// + /// Color of the item. + /// + /// Color of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].color")] + public string? RiskdataBasketItemItemNrColor { get { return this._RiskdataBasketItemItemNrColorOption; } set { this._RiskdataBasketItemItemNrColorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrCurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("riskdata.basket.item[itemNr].currency")] + public string? RiskdataBasketItemItemNrCurrency { get { return this._RiskdataBasketItemItemNrCurrencyOption; } set { this._RiskdataBasketItemItemNrCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrItemIDOption { get; private set; } + + /// + /// ID of the item. + /// + /// ID of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].itemID")] + public string? RiskdataBasketItemItemNrItemID { get { return this._RiskdataBasketItemItemNrItemIDOption; } set { this._RiskdataBasketItemItemNrItemIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrManufacturerOption { get; private set; } + + /// + /// Manufacturer of the item. + /// + /// Manufacturer of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].manufacturer")] + public string? RiskdataBasketItemItemNrManufacturer { get { return this._RiskdataBasketItemItemNrManufacturerOption; } set { this._RiskdataBasketItemItemNrManufacturerOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrProductTitleOption { get; private set; } + + /// + /// A text description of the product the invoice line refers to. + /// + /// A text description of the product the invoice line refers to. + [JsonPropertyName("riskdata.basket.item[itemNr].productTitle")] + public string? RiskdataBasketItemItemNrProductTitle { get { return this._RiskdataBasketItemItemNrProductTitleOption; } set { this._RiskdataBasketItemItemNrProductTitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrQuantityOption { get; private set; } + + /// + /// Quantity of the item purchased. + /// + /// Quantity of the item purchased. + [JsonPropertyName("riskdata.basket.item[itemNr].quantity")] + public string? RiskdataBasketItemItemNrQuantity { get { return this._RiskdataBasketItemItemNrQuantityOption; } set { this._RiskdataBasketItemItemNrQuantityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrReceiverEmailOption { get; private set; } + + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + /// + /// Email associated with the given product in the basket (usually in electronic gift cards). + [JsonPropertyName("riskdata.basket.item[itemNr].receiverEmail")] + public string? RiskdataBasketItemItemNrReceiverEmail { get { return this._RiskdataBasketItemItemNrReceiverEmailOption; } set { this._RiskdataBasketItemItemNrReceiverEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrSizeOption { get; private set; } + + /// + /// Size of the item. + /// + /// Size of the item. + [JsonPropertyName("riskdata.basket.item[itemNr].size")] + public string? RiskdataBasketItemItemNrSize { get { return this._RiskdataBasketItemItemNrSizeOption; } set { this._RiskdataBasketItemItemNrSizeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrSkuOption { get; private set; } + + /// + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + /// + /// [Stock keeping unit](https://en.wikipedia.org/wiki/Stock_keeping_unit). + [JsonPropertyName("riskdata.basket.item[itemNr].sku")] + public string? RiskdataBasketItemItemNrSku { get { return this._RiskdataBasketItemItemNrSkuOption; } set { this._RiskdataBasketItemItemNrSkuOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataBasketItemItemNrUpcOption { get; private set; } + + /// + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + /// + /// [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code). + [JsonPropertyName("riskdata.basket.item[itemNr].upc")] + public string? RiskdataBasketItemItemNrUpc { get { return this._RiskdataBasketItemItemNrUpcOption; } set { this._RiskdataBasketItemItemNrUpcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionCodeOption { get; private set; } + + /// + /// Code of the promotion. + /// + /// Code of the promotion. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionCode")] + public string? RiskdataPromotionsPromotionItemNrPromotionCode { get { return this._RiskdataPromotionsPromotionItemNrPromotionCodeOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption { get; private set; } + + /// + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The discount amount of the promotion, represented in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountAmount")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountAmount { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + /// + /// The three-character [ISO currency code](https://en.wikipedia.org/wiki/ISO_4217). + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountCurrency")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption { get; private set; } + + /// + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + /// + /// Promotion's percentage discount. It is represented in percentage value and there is no need to include the '%' sign. e.g. for a promotion discount of 30%, the value of the field should be 30. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionDiscountPercentage")] + public string? RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage { get { return this._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataPromotionsPromotionItemNrPromotionNameOption { get; private set; } + + /// + /// Name of the promotion. + /// + /// Name of the promotion. + [JsonPropertyName("riskdata.promotions.promotion[itemNr].promotionName")] + public string? RiskdataPromotionsPromotionItemNrPromotionName { get { return this._RiskdataPromotionsPromotionItemNrPromotionNameOption; } set { this._RiskdataPromotionsPromotionItemNrPromotionNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataRiskProfileReferenceOption { get; private set; } + + /// + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + /// + /// Reference number of the risk profile that you want to apply to the payment. If not provided or left blank, the merchant-level account's default risk profile will be applied to the payment. For more information, see [dynamically assign a risk profile to a payment](https://docs.adyen.com/risk-management/create-and-use-risk-profiles#dynamically-assign-a-risk-profile-to-a-payment). + [JsonPropertyName("riskdata.riskProfileReference")] + public string? RiskdataRiskProfileReference { get { return this._RiskdataRiskProfileReferenceOption; } set { this._RiskdataRiskProfileReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskdataSkipRiskOption { get; private set; } + + /// + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + /// + /// If this parameter is provided with the value **true**, risk checks for the payment request are skipped and the transaction will not get a risk score. + [JsonPropertyName("riskdata.skipRisk")] + public string? RiskdataSkipRisk { get { return this._RiskdataSkipRiskOption; } set { this._RiskdataSkipRiskOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRisk {\n"); + sb.Append(" RiskdataCustomFieldName: ").Append(RiskdataCustomFieldName).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrAmountPerItem: ").Append(RiskdataBasketItemItemNrAmountPerItem).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrBrand: ").Append(RiskdataBasketItemItemNrBrand).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrCategory: ").Append(RiskdataBasketItemItemNrCategory).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrColor: ").Append(RiskdataBasketItemItemNrColor).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrCurrency: ").Append(RiskdataBasketItemItemNrCurrency).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrItemID: ").Append(RiskdataBasketItemItemNrItemID).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrManufacturer: ").Append(RiskdataBasketItemItemNrManufacturer).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrProductTitle: ").Append(RiskdataBasketItemItemNrProductTitle).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrQuantity: ").Append(RiskdataBasketItemItemNrQuantity).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrReceiverEmail: ").Append(RiskdataBasketItemItemNrReceiverEmail).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrSize: ").Append(RiskdataBasketItemItemNrSize).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrSku: ").Append(RiskdataBasketItemItemNrSku).Append("\n"); + sb.Append(" RiskdataBasketItemItemNrUpc: ").Append(RiskdataBasketItemItemNrUpc).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionCode: ").Append(RiskdataPromotionsPromotionItemNrPromotionCode).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountAmount: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountAmount).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage: ").Append(RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage).Append("\n"); + sb.Append(" RiskdataPromotionsPromotionItemNrPromotionName: ").Append(RiskdataPromotionsPromotionItemNrPromotionName).Append("\n"); + sb.Append(" RiskdataRiskProfileReference: ").Append(RiskdataRiskProfileReference).Append("\n"); + sb.Append(" RiskdataSkipRisk: ").Append(RiskdataSkipRisk).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRiskJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRisk Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option riskdataCustomFieldName = default; + Option riskdataBasketItemItemNrAmountPerItem = default; + Option riskdataBasketItemItemNrBrand = default; + Option riskdataBasketItemItemNrCategory = default; + Option riskdataBasketItemItemNrColor = default; + Option riskdataBasketItemItemNrCurrency = default; + Option riskdataBasketItemItemNrItemID = default; + Option riskdataBasketItemItemNrManufacturer = default; + Option riskdataBasketItemItemNrProductTitle = default; + Option riskdataBasketItemItemNrQuantity = default; + Option riskdataBasketItemItemNrReceiverEmail = default; + Option riskdataBasketItemItemNrSize = default; + Option riskdataBasketItemItemNrSku = default; + Option riskdataBasketItemItemNrUpc = default; + Option riskdataPromotionsPromotionItemNrPromotionCode = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountAmount = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = default; + Option riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = default; + Option riskdataPromotionsPromotionItemNrPromotionName = default; + Option riskdataRiskProfileReference = default; + Option riskdataSkipRisk = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "riskdata.[customFieldName]": + riskdataCustomFieldName = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].amountPerItem": + riskdataBasketItemItemNrAmountPerItem = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].brand": + riskdataBasketItemItemNrBrand = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].category": + riskdataBasketItemItemNrCategory = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].color": + riskdataBasketItemItemNrColor = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].currency": + riskdataBasketItemItemNrCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].itemID": + riskdataBasketItemItemNrItemID = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].manufacturer": + riskdataBasketItemItemNrManufacturer = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].productTitle": + riskdataBasketItemItemNrProductTitle = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].quantity": + riskdataBasketItemItemNrQuantity = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].receiverEmail": + riskdataBasketItemItemNrReceiverEmail = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].size": + riskdataBasketItemItemNrSize = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].sku": + riskdataBasketItemItemNrSku = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.basket.item[itemNr].upc": + riskdataBasketItemItemNrUpc = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionCode": + riskdataPromotionsPromotionItemNrPromotionCode = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountAmount": + riskdataPromotionsPromotionItemNrPromotionDiscountAmount = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountCurrency": + riskdataPromotionsPromotionItemNrPromotionDiscountCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionDiscountPercentage": + riskdataPromotionsPromotionItemNrPromotionDiscountPercentage = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.promotions.promotion[itemNr].promotionName": + riskdataPromotionsPromotionItemNrPromotionName = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.riskProfileReference": + riskdataRiskProfileReference = new Option(utf8JsonReader.GetString()!); + break; + case "riskdata.skipRisk": + riskdataSkipRisk = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRisk(riskdataCustomFieldName, riskdataBasketItemItemNrAmountPerItem, riskdataBasketItemItemNrBrand, riskdataBasketItemItemNrCategory, riskdataBasketItemItemNrColor, riskdataBasketItemItemNrCurrency, riskdataBasketItemItemNrItemID, riskdataBasketItemItemNrManufacturer, riskdataBasketItemItemNrProductTitle, riskdataBasketItemItemNrQuantity, riskdataBasketItemItemNrReceiverEmail, riskdataBasketItemItemNrSize, riskdataBasketItemItemNrSku, riskdataBasketItemItemNrUpc, riskdataPromotionsPromotionItemNrPromotionCode, riskdataPromotionsPromotionItemNrPromotionDiscountAmount, riskdataPromotionsPromotionItemNrPromotionDiscountCurrency, riskdataPromotionsPromotionItemNrPromotionDiscountPercentage, riskdataPromotionsPromotionItemNrPromotionName, riskdataRiskProfileReference, riskdataSkipRisk); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRisk additionalDataRisk, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRisk, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRisk additionalDataRisk, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRisk._RiskdataCustomFieldNameOption.IsSet) + if (additionalDataRisk.RiskdataCustomFieldName != null) + writer.WriteString("riskdata.[customFieldName]", additionalDataRisk.RiskdataCustomFieldName); + + if (additionalDataRisk._RiskdataBasketItemItemNrAmountPerItemOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrAmountPerItem != null) + writer.WriteString("riskdata.basket.item[itemNr].amountPerItem", additionalDataRisk.RiskdataBasketItemItemNrAmountPerItem); + + if (additionalDataRisk._RiskdataBasketItemItemNrBrandOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrBrand != null) + writer.WriteString("riskdata.basket.item[itemNr].brand", additionalDataRisk.RiskdataBasketItemItemNrBrand); + + if (additionalDataRisk._RiskdataBasketItemItemNrCategoryOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrCategory != null) + writer.WriteString("riskdata.basket.item[itemNr].category", additionalDataRisk.RiskdataBasketItemItemNrCategory); + + if (additionalDataRisk._RiskdataBasketItemItemNrColorOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrColor != null) + writer.WriteString("riskdata.basket.item[itemNr].color", additionalDataRisk.RiskdataBasketItemItemNrColor); + + if (additionalDataRisk._RiskdataBasketItemItemNrCurrencyOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrCurrency != null) + writer.WriteString("riskdata.basket.item[itemNr].currency", additionalDataRisk.RiskdataBasketItemItemNrCurrency); + + if (additionalDataRisk._RiskdataBasketItemItemNrItemIDOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrItemID != null) + writer.WriteString("riskdata.basket.item[itemNr].itemID", additionalDataRisk.RiskdataBasketItemItemNrItemID); + + if (additionalDataRisk._RiskdataBasketItemItemNrManufacturerOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrManufacturer != null) + writer.WriteString("riskdata.basket.item[itemNr].manufacturer", additionalDataRisk.RiskdataBasketItemItemNrManufacturer); + + if (additionalDataRisk._RiskdataBasketItemItemNrProductTitleOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrProductTitle != null) + writer.WriteString("riskdata.basket.item[itemNr].productTitle", additionalDataRisk.RiskdataBasketItemItemNrProductTitle); + + if (additionalDataRisk._RiskdataBasketItemItemNrQuantityOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrQuantity != null) + writer.WriteString("riskdata.basket.item[itemNr].quantity", additionalDataRisk.RiskdataBasketItemItemNrQuantity); + + if (additionalDataRisk._RiskdataBasketItemItemNrReceiverEmailOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrReceiverEmail != null) + writer.WriteString("riskdata.basket.item[itemNr].receiverEmail", additionalDataRisk.RiskdataBasketItemItemNrReceiverEmail); + + if (additionalDataRisk._RiskdataBasketItemItemNrSizeOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrSize != null) + writer.WriteString("riskdata.basket.item[itemNr].size", additionalDataRisk.RiskdataBasketItemItemNrSize); + + if (additionalDataRisk._RiskdataBasketItemItemNrSkuOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrSku != null) + writer.WriteString("riskdata.basket.item[itemNr].sku", additionalDataRisk.RiskdataBasketItemItemNrSku); + + if (additionalDataRisk._RiskdataBasketItemItemNrUpcOption.IsSet) + if (additionalDataRisk.RiskdataBasketItemItemNrUpc != null) + writer.WriteString("riskdata.basket.item[itemNr].upc", additionalDataRisk.RiskdataBasketItemItemNrUpc); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionCodeOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionCode != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionCode", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionCode); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountAmountOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountAmount != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountAmount", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountAmount); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountCurrencyOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountCurrency", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountCurrency); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionDiscountPercentageOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionDiscountPercentage", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionDiscountPercentage); + + if (additionalDataRisk._RiskdataPromotionsPromotionItemNrPromotionNameOption.IsSet) + if (additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionName != null) + writer.WriteString("riskdata.promotions.promotion[itemNr].promotionName", additionalDataRisk.RiskdataPromotionsPromotionItemNrPromotionName); + + if (additionalDataRisk._RiskdataRiskProfileReferenceOption.IsSet) + if (additionalDataRisk.RiskdataRiskProfileReference != null) + writer.WriteString("riskdata.riskProfileReference", additionalDataRisk.RiskdataRiskProfileReference); + + if (additionalDataRisk._RiskdataSkipRiskOption.IsSet) + if (additionalDataRisk.RiskdataSkipRisk != null) + writer.WriteString("riskdata.skipRisk", additionalDataRisk.RiskdataSkipRisk); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataRiskStandalone.cs b/Adyen/Payment/Models/AdditionalDataRiskStandalone.cs new file mode 100644 index 000000000..1e3f42762 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataRiskStandalone.cs @@ -0,0 +1,527 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataRiskStandalone. + /// + public partial class AdditionalDataRiskStandalone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + /// Shopper's email. + /// Shopper's first name. + /// Shopper's last name. + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + /// Shopper's phone number. + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + /// Unique transaction ID of the payment. + /// Raw AVS result received from the acquirer, where available. Example: D + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + /// Raw CVC result received from the acquirer, where available. Example: 1 + /// Unique identifier or token for the shopper's card details. + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// Required for PayPal payments only. The only supported value is: **paypal**. + [JsonConstructor] + public AdditionalDataRiskStandalone(Option payPalCountryCode = default, Option payPalEmailId = default, Option payPalFirstName = default, Option payPalLastName = default, Option payPalPayerId = default, Option payPalPhone = default, Option payPalProtectionEligibility = default, Option payPalTransactionId = default, Option avsResultRaw = default, Option bin = default, Option cvcResultRaw = default, Option riskToken = default, Option threeDAuthenticated = default, Option threeDOffered = default, Option tokenDataType = default) + { + _PayPalCountryCodeOption = payPalCountryCode; + _PayPalEmailIdOption = payPalEmailId; + _PayPalFirstNameOption = payPalFirstName; + _PayPalLastNameOption = payPalLastName; + _PayPalPayerIdOption = payPalPayerId; + _PayPalPhoneOption = payPalPhone; + _PayPalProtectionEligibilityOption = payPalProtectionEligibility; + _PayPalTransactionIdOption = payPalTransactionId; + _AvsResultRawOption = avsResultRaw; + _BinOption = bin; + _CvcResultRawOption = cvcResultRaw; + _RiskTokenOption = riskToken; + _ThreeDAuthenticatedOption = threeDAuthenticated; + _ThreeDOfferedOption = threeDOffered; + _TokenDataTypeOption = tokenDataType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataRiskStandalone() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalCountryCodeOption { get; private set; } + + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + /// + /// Shopper's country of residence in the form of ISO standard 3166 2-character country codes. + [JsonPropertyName("PayPal.CountryCode")] + public string? PayPalCountryCode { get { return this._PayPalCountryCodeOption; } set { this._PayPalCountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalEmailIdOption { get; private set; } + + /// + /// Shopper's email. + /// + /// Shopper's email. + [JsonPropertyName("PayPal.EmailId")] + public string? PayPalEmailId { get { return this._PayPalEmailIdOption; } set { this._PayPalEmailIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalFirstNameOption { get; private set; } + + /// + /// Shopper's first name. + /// + /// Shopper's first name. + [JsonPropertyName("PayPal.FirstName")] + public string? PayPalFirstName { get { return this._PayPalFirstNameOption; } set { this._PayPalFirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalLastNameOption { get; private set; } + + /// + /// Shopper's last name. + /// + /// Shopper's last name. + [JsonPropertyName("PayPal.LastName")] + public string? PayPalLastName { get { return this._PayPalLastNameOption; } set { this._PayPalLastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalPayerIdOption { get; private set; } + + /// + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + /// + /// Unique PayPal Customer Account identification number. Character length and limitations: 13 single-byte alphanumeric characters. + [JsonPropertyName("PayPal.PayerId")] + public string? PayPalPayerId { get { return this._PayPalPayerIdOption; } set { this._PayPalPayerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalPhoneOption { get; private set; } + + /// + /// Shopper's phone number. + /// + /// Shopper's phone number. + [JsonPropertyName("PayPal.Phone")] + public string? PayPalPhone { get { return this._PayPalPhoneOption; } set { this._PayPalPhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalProtectionEligibilityOption { get; private set; } + + /// + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + /// + /// Allowed values: * **Eligible** — Merchant is protected by PayPal's Seller Protection Policy for Unauthorized Payments and Item Not Received. * **PartiallyEligible** — Merchant is protected by PayPal's Seller Protection Policy for Item Not Received. * **Ineligible** — Merchant is not protected under the Seller Protection Policy. + [JsonPropertyName("PayPal.ProtectionEligibility")] + public string? PayPalProtectionEligibility { get { return this._PayPalProtectionEligibilityOption; } set { this._PayPalProtectionEligibilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayPalTransactionIdOption { get; private set; } + + /// + /// Unique transaction ID of the payment. + /// + /// Unique transaction ID of the payment. + [JsonPropertyName("PayPal.TransactionId")] + public string? PayPalTransactionId { get { return this._PayPalTransactionIdOption; } set { this._PayPalTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultRawOption { get; private set; } + + /// + /// Raw AVS result received from the acquirer, where available. Example: D + /// + /// Raw AVS result received from the acquirer, where available. Example: D + [JsonPropertyName("avsResultRaw")] + public string? AvsResultRaw { get { return this._AvsResultRawOption; } set { this._AvsResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BinOption { get; private set; } + + /// + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + /// + /// The Bank Identification Number of a credit card, which is the first six digits of a card number. Required for [tokenized card request](https://docs.adyen.com/online-payments/tokenization). + [JsonPropertyName("bin")] + public string? Bin { get { return this._BinOption; } set { this._BinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultRawOption { get; private set; } + + /// + /// Raw CVC result received from the acquirer, where available. Example: 1 + /// + /// Raw CVC result received from the acquirer, where available. Example: 1 + [JsonPropertyName("cvcResultRaw")] + public string? CvcResultRaw { get { return this._CvcResultRawOption; } set { this._CvcResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskTokenOption { get; private set; } + + /// + /// Unique identifier or token for the shopper's card details. + /// + /// Unique identifier or token for the shopper's card details. + [JsonPropertyName("riskToken")] + public string? RiskToken { get { return this._RiskTokenOption; } set { this._RiskTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + [JsonPropertyName("threeDAuthenticated")] + public string? ThreeDAuthenticated { get { return this._ThreeDAuthenticatedOption; } set { this._ThreeDAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + [JsonPropertyName("threeDOffered")] + public string? ThreeDOffered { get { return this._ThreeDOfferedOption; } set { this._ThreeDOfferedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenDataTypeOption { get; private set; } + + /// + /// Required for PayPal payments only. The only supported value is: **paypal**. + /// + /// Required for PayPal payments only. The only supported value is: **paypal**. + [JsonPropertyName("tokenDataType")] + public string? TokenDataType { get { return this._TokenDataTypeOption; } set { this._TokenDataTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataRiskStandalone {\n"); + sb.Append(" PayPalCountryCode: ").Append(PayPalCountryCode).Append("\n"); + sb.Append(" PayPalEmailId: ").Append(PayPalEmailId).Append("\n"); + sb.Append(" PayPalFirstName: ").Append(PayPalFirstName).Append("\n"); + sb.Append(" PayPalLastName: ").Append(PayPalLastName).Append("\n"); + sb.Append(" PayPalPayerId: ").Append(PayPalPayerId).Append("\n"); + sb.Append(" PayPalPhone: ").Append(PayPalPhone).Append("\n"); + sb.Append(" PayPalProtectionEligibility: ").Append(PayPalProtectionEligibility).Append("\n"); + sb.Append(" PayPalTransactionId: ").Append(PayPalTransactionId).Append("\n"); + sb.Append(" AvsResultRaw: ").Append(AvsResultRaw).Append("\n"); + sb.Append(" Bin: ").Append(Bin).Append("\n"); + sb.Append(" CvcResultRaw: ").Append(CvcResultRaw).Append("\n"); + sb.Append(" RiskToken: ").Append(RiskToken).Append("\n"); + sb.Append(" ThreeDAuthenticated: ").Append(ThreeDAuthenticated).Append("\n"); + sb.Append(" ThreeDOffered: ").Append(ThreeDOffered).Append("\n"); + sb.Append(" TokenDataType: ").Append(TokenDataType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataRiskStandaloneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataRiskStandalone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option payPalCountryCode = default; + Option payPalEmailId = default; + Option payPalFirstName = default; + Option payPalLastName = default; + Option payPalPayerId = default; + Option payPalPhone = default; + Option payPalProtectionEligibility = default; + Option payPalTransactionId = default; + Option avsResultRaw = default; + Option bin = default; + Option cvcResultRaw = default; + Option riskToken = default; + Option threeDAuthenticated = default; + Option threeDOffered = default; + Option tokenDataType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "PayPal.CountryCode": + payPalCountryCode = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.EmailId": + payPalEmailId = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.FirstName": + payPalFirstName = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.LastName": + payPalLastName = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.PayerId": + payPalPayerId = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.Phone": + payPalPhone = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.ProtectionEligibility": + payPalProtectionEligibility = new Option(utf8JsonReader.GetString()!); + break; + case "PayPal.TransactionId": + payPalTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "avsResultRaw": + avsResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "bin": + bin = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResultRaw": + cvcResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "riskToken": + riskToken = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticated": + threeDAuthenticated = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOffered": + threeDOffered = new Option(utf8JsonReader.GetString()!); + break; + case "tokenDataType": + tokenDataType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataRiskStandalone(payPalCountryCode, payPalEmailId, payPalFirstName, payPalLastName, payPalPayerId, payPalPhone, payPalProtectionEligibility, payPalTransactionId, avsResultRaw, bin, cvcResultRaw, riskToken, threeDAuthenticated, threeDOffered, tokenDataType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataRiskStandalone additionalDataRiskStandalone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataRiskStandalone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataRiskStandalone additionalDataRiskStandalone, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataRiskStandalone._PayPalCountryCodeOption.IsSet) + if (additionalDataRiskStandalone.PayPalCountryCode != null) + writer.WriteString("PayPal.CountryCode", additionalDataRiskStandalone.PayPalCountryCode); + + if (additionalDataRiskStandalone._PayPalEmailIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalEmailId != null) + writer.WriteString("PayPal.EmailId", additionalDataRiskStandalone.PayPalEmailId); + + if (additionalDataRiskStandalone._PayPalFirstNameOption.IsSet) + if (additionalDataRiskStandalone.PayPalFirstName != null) + writer.WriteString("PayPal.FirstName", additionalDataRiskStandalone.PayPalFirstName); + + if (additionalDataRiskStandalone._PayPalLastNameOption.IsSet) + if (additionalDataRiskStandalone.PayPalLastName != null) + writer.WriteString("PayPal.LastName", additionalDataRiskStandalone.PayPalLastName); + + if (additionalDataRiskStandalone._PayPalPayerIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalPayerId != null) + writer.WriteString("PayPal.PayerId", additionalDataRiskStandalone.PayPalPayerId); + + if (additionalDataRiskStandalone._PayPalPhoneOption.IsSet) + if (additionalDataRiskStandalone.PayPalPhone != null) + writer.WriteString("PayPal.Phone", additionalDataRiskStandalone.PayPalPhone); + + if (additionalDataRiskStandalone._PayPalProtectionEligibilityOption.IsSet) + if (additionalDataRiskStandalone.PayPalProtectionEligibility != null) + writer.WriteString("PayPal.ProtectionEligibility", additionalDataRiskStandalone.PayPalProtectionEligibility); + + if (additionalDataRiskStandalone._PayPalTransactionIdOption.IsSet) + if (additionalDataRiskStandalone.PayPalTransactionId != null) + writer.WriteString("PayPal.TransactionId", additionalDataRiskStandalone.PayPalTransactionId); + + if (additionalDataRiskStandalone._AvsResultRawOption.IsSet) + if (additionalDataRiskStandalone.AvsResultRaw != null) + writer.WriteString("avsResultRaw", additionalDataRiskStandalone.AvsResultRaw); + + if (additionalDataRiskStandalone._BinOption.IsSet) + if (additionalDataRiskStandalone.Bin != null) + writer.WriteString("bin", additionalDataRiskStandalone.Bin); + + if (additionalDataRiskStandalone._CvcResultRawOption.IsSet) + if (additionalDataRiskStandalone.CvcResultRaw != null) + writer.WriteString("cvcResultRaw", additionalDataRiskStandalone.CvcResultRaw); + + if (additionalDataRiskStandalone._RiskTokenOption.IsSet) + if (additionalDataRiskStandalone.RiskToken != null) + writer.WriteString("riskToken", additionalDataRiskStandalone.RiskToken); + + if (additionalDataRiskStandalone._ThreeDAuthenticatedOption.IsSet) + if (additionalDataRiskStandalone.ThreeDAuthenticated != null) + writer.WriteString("threeDAuthenticated", additionalDataRiskStandalone.ThreeDAuthenticated); + + if (additionalDataRiskStandalone._ThreeDOfferedOption.IsSet) + if (additionalDataRiskStandalone.ThreeDOffered != null) + writer.WriteString("threeDOffered", additionalDataRiskStandalone.ThreeDOffered); + + if (additionalDataRiskStandalone._TokenDataTypeOption.IsSet) + if (additionalDataRiskStandalone.TokenDataType != null) + writer.WriteString("tokenDataType", additionalDataRiskStandalone.TokenDataType); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataSubMerchant.cs b/Adyen/Payment/Models/AdditionalDataSubMerchant.cs new file mode 100644 index 000000000..86d371ef3 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataSubMerchant.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataSubMerchant. + /// + public partial class AdditionalDataSubMerchant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonConstructor] + public AdditionalDataSubMerchant(Option subMerchantNumberOfSubSellers = default, Option subMerchantSubSellerSubSellerNrCity = default, Option subMerchantSubSellerSubSellerNrCountry = default, Option subMerchantSubSellerSubSellerNrEmail = default, Option subMerchantSubSellerSubSellerNrId = default, Option subMerchantSubSellerSubSellerNrMcc = default, Option subMerchantSubSellerSubSellerNrName = default, Option subMerchantSubSellerSubSellerNrPhoneNumber = default, Option subMerchantSubSellerSubSellerNrPostalCode = default, Option subMerchantSubSellerSubSellerNrState = default, Option subMerchantSubSellerSubSellerNrStreet = default, Option subMerchantSubSellerSubSellerNrTaxId = default) + { + _SubMerchantNumberOfSubSellersOption = subMerchantNumberOfSubSellers; + _SubMerchantSubSellerSubSellerNrCityOption = subMerchantSubSellerSubSellerNrCity; + _SubMerchantSubSellerSubSellerNrCountryOption = subMerchantSubSellerSubSellerNrCountry; + _SubMerchantSubSellerSubSellerNrEmailOption = subMerchantSubSellerSubSellerNrEmail; + _SubMerchantSubSellerSubSellerNrIdOption = subMerchantSubSellerSubSellerNrId; + _SubMerchantSubSellerSubSellerNrMccOption = subMerchantSubSellerSubSellerNrMcc; + _SubMerchantSubSellerSubSellerNrNameOption = subMerchantSubSellerSubSellerNrName; + _SubMerchantSubSellerSubSellerNrPhoneNumberOption = subMerchantSubSellerSubSellerNrPhoneNumber; + _SubMerchantSubSellerSubSellerNrPostalCodeOption = subMerchantSubSellerSubSellerNrPostalCode; + _SubMerchantSubSellerSubSellerNrStateOption = subMerchantSubSellerSubSellerNrState; + _SubMerchantSubSellerSubSellerNrStreetOption = subMerchantSubSellerSubSellerNrStreet; + _SubMerchantSubSellerSubSellerNrTaxIdOption = subMerchantSubSellerSubSellerNrTaxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataSubMerchant() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantNumberOfSubSellersOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + /// + /// Required for transactions performed by registered payment facilitators. Indicates the number of sub-merchants contained in the request. For example, **3**. + [JsonPropertyName("subMerchant.numberOfSubSellers")] + public string? SubMerchantNumberOfSubSellers { get { return this._SubMerchantNumberOfSubSellersOption; } set { this._SubMerchantNumberOfSubSellersOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrCityOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// + /// Required for transactions performed by registered payment facilitators. The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].city")] + public string? SubMerchantSubSellerSubSellerNrCity { get { return this._SubMerchantSubSellerSubSellerNrCityOption; } set { this._SubMerchantSubSellerSubSellerNrCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrCountryOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// + /// Required for transactions performed by registered payment facilitators. The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].country")] + public string? SubMerchantSubSellerSubSellerNrCountry { get { return this._SubMerchantSubSellerSubSellerNrCountryOption; } set { this._SubMerchantSubSellerSubSellerNrCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrEmailOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + /// + /// Required for transactions performed by registered payment facilitators. The email address of the sub-merchant. * Format: Alphanumeric * Maximum length: 40 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].email")] + public string? SubMerchantSubSellerSubSellerNrEmail { get { return this._SubMerchantSubSellerSubSellerNrEmailOption; } set { this._SubMerchantSubSellerSubSellerNrEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrIdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + /// + /// Required for transactions performed by registered payment facilitators. A unique identifier that you create for the sub-merchant, used by schemes to identify the sub-merchant. * Format: Alphanumeric * Maximum length: 15 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].id")] + public string? SubMerchantSubSellerSubSellerNrId { get { return this._SubMerchantSubSellerSubSellerNrIdOption; } set { this._SubMerchantSubSellerSubSellerNrIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrMccOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// Required for transactions performed by registered payment facilitators. The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("subMerchant.subSeller[subSellerNr].mcc")] + public string? SubMerchantSubSellerSubSellerNrMcc { get { return this._SubMerchantSubSellerSubSellerNrMccOption; } set { this._SubMerchantSubSellerSubSellerNrMccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrNameOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// Required for transactions performed by registered payment facilitators. The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. Exception: for acquirers in Brazil, this value does not overwrite the shopper statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].name")] + public string? SubMerchantSubSellerSubSellerNrName { get { return this._SubMerchantSubSellerSubSellerNrNameOption; } set { this._SubMerchantSubSellerSubSellerNrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrPhoneNumberOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + /// + /// Required for transactions performed by registered payment facilitators. The phone number of the sub-merchant. * Format: Alphanumeric and special characters * Maximum length: 20 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].phoneNumber")] + public string? SubMerchantSubSellerSubSellerNrPhoneNumber { get { return this._SubMerchantSubSellerSubSellerNrPhoneNumberOption; } set { this._SubMerchantSubSellerSubSellerNrPhoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrPostalCodeOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + /// + /// Required for transactions performed by registered payment facilitators. The postal code of the sub-merchant's address, without dashes. * Format: Numeric * Fixed length: 8 digits + [JsonPropertyName("subMerchant.subSeller[subSellerNr].postalCode")] + public string? SubMerchantSubSellerSubSellerNrPostalCode { get { return this._SubMerchantSubSellerSubSellerNrPostalCodeOption; } set { this._SubMerchantSubSellerSubSellerNrPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrStateOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + /// + /// Required for transactions performed by registered payment facilitators. The state code of the sub-merchant's address, if applicable to the country. * Format: Alphanumeric * Maximum length: 2 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].state")] + public string? SubMerchantSubSellerSubSellerNrState { get { return this._SubMerchantSubSellerSubSellerNrStateOption; } set { this._SubMerchantSubSellerSubSellerNrStateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrStreetOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + /// + /// Required for transactions performed by registered payment facilitators. The street name and house number of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 60 characters + [JsonPropertyName("subMerchant.subSeller[subSellerNr].street")] + public string? SubMerchantSubSellerSubSellerNrStreet { get { return this._SubMerchantSubSellerSubSellerNrStreetOption; } set { this._SubMerchantSubSellerSubSellerNrStreetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantSubSellerSubSellerNrTaxIdOption { get; private set; } + + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// + /// Required for transactions performed by registered payment facilitators. The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonPropertyName("subMerchant.subSeller[subSellerNr].taxId")] + public string? SubMerchantSubSellerSubSellerNrTaxId { get { return this._SubMerchantSubSellerSubSellerNrTaxIdOption; } set { this._SubMerchantSubSellerSubSellerNrTaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataSubMerchant {\n"); + sb.Append(" SubMerchantNumberOfSubSellers: ").Append(SubMerchantNumberOfSubSellers).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrCity: ").Append(SubMerchantSubSellerSubSellerNrCity).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrCountry: ").Append(SubMerchantSubSellerSubSellerNrCountry).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrEmail: ").Append(SubMerchantSubSellerSubSellerNrEmail).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrId: ").Append(SubMerchantSubSellerSubSellerNrId).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrMcc: ").Append(SubMerchantSubSellerSubSellerNrMcc).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrName: ").Append(SubMerchantSubSellerSubSellerNrName).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrPhoneNumber: ").Append(SubMerchantSubSellerSubSellerNrPhoneNumber).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrPostalCode: ").Append(SubMerchantSubSellerSubSellerNrPostalCode).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrState: ").Append(SubMerchantSubSellerSubSellerNrState).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrStreet: ").Append(SubMerchantSubSellerSubSellerNrStreet).Append("\n"); + sb.Append(" SubMerchantSubSellerSubSellerNrTaxId: ").Append(SubMerchantSubSellerSubSellerNrTaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataSubMerchantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataSubMerchant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option subMerchantNumberOfSubSellers = default; + Option subMerchantSubSellerSubSellerNrCity = default; + Option subMerchantSubSellerSubSellerNrCountry = default; + Option subMerchantSubSellerSubSellerNrEmail = default; + Option subMerchantSubSellerSubSellerNrId = default; + Option subMerchantSubSellerSubSellerNrMcc = default; + Option subMerchantSubSellerSubSellerNrName = default; + Option subMerchantSubSellerSubSellerNrPhoneNumber = default; + Option subMerchantSubSellerSubSellerNrPostalCode = default; + Option subMerchantSubSellerSubSellerNrState = default; + Option subMerchantSubSellerSubSellerNrStreet = default; + Option subMerchantSubSellerSubSellerNrTaxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "subMerchant.numberOfSubSellers": + subMerchantNumberOfSubSellers = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].city": + subMerchantSubSellerSubSellerNrCity = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].country": + subMerchantSubSellerSubSellerNrCountry = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].email": + subMerchantSubSellerSubSellerNrEmail = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].id": + subMerchantSubSellerSubSellerNrId = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].mcc": + subMerchantSubSellerSubSellerNrMcc = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].name": + subMerchantSubSellerSubSellerNrName = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].phoneNumber": + subMerchantSubSellerSubSellerNrPhoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].postalCode": + subMerchantSubSellerSubSellerNrPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].state": + subMerchantSubSellerSubSellerNrState = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].street": + subMerchantSubSellerSubSellerNrStreet = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant.subSeller[subSellerNr].taxId": + subMerchantSubSellerSubSellerNrTaxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataSubMerchant(subMerchantNumberOfSubSellers, subMerchantSubSellerSubSellerNrCity, subMerchantSubSellerSubSellerNrCountry, subMerchantSubSellerSubSellerNrEmail, subMerchantSubSellerSubSellerNrId, subMerchantSubSellerSubSellerNrMcc, subMerchantSubSellerSubSellerNrName, subMerchantSubSellerSubSellerNrPhoneNumber, subMerchantSubSellerSubSellerNrPostalCode, subMerchantSubSellerSubSellerNrState, subMerchantSubSellerSubSellerNrStreet, subMerchantSubSellerSubSellerNrTaxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataSubMerchant additionalDataSubMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataSubMerchant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataSubMerchant additionalDataSubMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataSubMerchant._SubMerchantNumberOfSubSellersOption.IsSet) + if (additionalDataSubMerchant.SubMerchantNumberOfSubSellers != null) + writer.WriteString("subMerchant.numberOfSubSellers", additionalDataSubMerchant.SubMerchantNumberOfSubSellers); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrCityOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCity != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].city", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCity); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrCountryOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCountry != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].country", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrCountry); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrEmailOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrEmail != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].email", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrEmail); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrIdOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrId != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].id", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrId); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrMccOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrMcc != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].mcc", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrMcc); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrNameOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrName != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].name", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrName); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrPhoneNumberOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPhoneNumber != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].phoneNumber", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPhoneNumber); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrPostalCodeOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPostalCode != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].postalCode", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrPostalCode); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrStateOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrState != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].state", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrState); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrStreetOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrStreet != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].street", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrStreet); + + if (additionalDataSubMerchant._SubMerchantSubSellerSubSellerNrTaxIdOption.IsSet) + if (additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrTaxId != null) + writer.WriteString("subMerchant.subSeller[subSellerNr].taxId", additionalDataSubMerchant.SubMerchantSubSellerSubSellerNrTaxId); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataTemporaryServices.cs b/Adyen/Payment/Models/AdditionalDataTemporaryServices.cs new file mode 100644 index 000000000..6181c278e --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataTemporaryServices.cs @@ -0,0 +1,377 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataTemporaryServices. + /// + public partial class AdditionalDataTemporaryServices : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + [JsonConstructor] + public AdditionalDataTemporaryServices(Option enhancedSchemeDataCustomerReference = default, Option enhancedSchemeDataEmployeeName = default, Option enhancedSchemeDataJobDescription = default, Option enhancedSchemeDataRegularHoursRate = default, Option enhancedSchemeDataRegularHoursWorked = default, Option enhancedSchemeDataRequestName = default, Option enhancedSchemeDataTempStartDate = default, Option enhancedSchemeDataTempWeekEnding = default, Option enhancedSchemeDataTotalTaxAmount = default) + { + _EnhancedSchemeDataCustomerReferenceOption = enhancedSchemeDataCustomerReference; + _EnhancedSchemeDataEmployeeNameOption = enhancedSchemeDataEmployeeName; + _EnhancedSchemeDataJobDescriptionOption = enhancedSchemeDataJobDescription; + _EnhancedSchemeDataRegularHoursRateOption = enhancedSchemeDataRegularHoursRate; + _EnhancedSchemeDataRegularHoursWorkedOption = enhancedSchemeDataRegularHoursWorked; + _EnhancedSchemeDataRequestNameOption = enhancedSchemeDataRequestName; + _EnhancedSchemeDataTempStartDateOption = enhancedSchemeDataTempStartDate; + _EnhancedSchemeDataTempWeekEndingOption = enhancedSchemeDataTempWeekEnding; + _EnhancedSchemeDataTotalTaxAmountOption = enhancedSchemeDataTotalTaxAmount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataTemporaryServices() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataCustomerReferenceOption { get; private set; } + + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + /// + /// The customer code, if supplied by a customer. * Encoding: ASCII * maxLength: 25 + [JsonPropertyName("enhancedSchemeData.customerReference")] + public string? EnhancedSchemeDataCustomerReference { get { return this._EnhancedSchemeDataCustomerReferenceOption; } set { this._EnhancedSchemeDataCustomerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataEmployeeNameOption { get; private set; } + + /// + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + /// + /// The name or ID of the person working in a temporary capacity. * maxLength: 40. * Must not be all spaces. *Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.employeeName")] + public string? EnhancedSchemeDataEmployeeName { get { return this._EnhancedSchemeDataEmployeeNameOption; } set { this._EnhancedSchemeDataEmployeeNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataJobDescriptionOption { get; private set; } + + /// + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + /// + /// The job description of the person working in a temporary capacity. * maxLength: 40 * Must not be all spaces. *Must not be all zeros. + [JsonPropertyName("enhancedSchemeData.jobDescription")] + public string? EnhancedSchemeDataJobDescription { get { return this._EnhancedSchemeDataJobDescriptionOption; } set { this._EnhancedSchemeDataJobDescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRegularHoursRateOption { get; private set; } + + /// + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + /// + /// The amount paid for regular hours worked, [minor units](https://docs.adyen.com/development-resources/currency-codes). * maxLength: 7 * Must not be empty * Can be all zeros + [JsonPropertyName("enhancedSchemeData.regularHoursRate")] + public string? EnhancedSchemeDataRegularHoursRate { get { return this._EnhancedSchemeDataRegularHoursRateOption; } set { this._EnhancedSchemeDataRegularHoursRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRegularHoursWorkedOption { get; private set; } + + /// + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + /// + /// The hours worked. * maxLength: 7 * Must not be empty * Can be all zeros + [JsonPropertyName("enhancedSchemeData.regularHoursWorked")] + public string? EnhancedSchemeDataRegularHoursWorked { get { return this._EnhancedSchemeDataRegularHoursWorkedOption; } set { this._EnhancedSchemeDataRegularHoursWorkedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataRequestNameOption { get; private set; } + + /// + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + /// + /// The name of the person requesting temporary services. * maxLength: 40 * Must not be all zeros * Must not be all spaces + [JsonPropertyName("enhancedSchemeData.requestName")] + public string? EnhancedSchemeDataRequestName { get { return this._EnhancedSchemeDataRequestNameOption; } set { this._EnhancedSchemeDataRequestNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTempStartDateOption { get; private set; } + + /// + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + /// + /// The billing period start date. * Format: ddMMyy * maxLength: 6 + [JsonPropertyName("enhancedSchemeData.tempStartDate")] + public string? EnhancedSchemeDataTempStartDate { get { return this._EnhancedSchemeDataTempStartDateOption; } set { this._EnhancedSchemeDataTempStartDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTempWeekEndingOption { get; private set; } + + /// + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + /// + /// The billing period end date. * Format: ddMMyy * maxLength: 6 + [JsonPropertyName("enhancedSchemeData.tempWeekEnding")] + public string? EnhancedSchemeDataTempWeekEnding { get { return this._EnhancedSchemeDataTempWeekEndingOption; } set { this._EnhancedSchemeDataTempWeekEndingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EnhancedSchemeDataTotalTaxAmountOption { get; private set; } + + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + /// + /// The total tax amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). For example, 2000 means USD 20.00 * maxLength: 12 + [JsonPropertyName("enhancedSchemeData.totalTaxAmount")] + public string? EnhancedSchemeDataTotalTaxAmount { get { return this._EnhancedSchemeDataTotalTaxAmountOption; } set { this._EnhancedSchemeDataTotalTaxAmountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataTemporaryServices {\n"); + sb.Append(" EnhancedSchemeDataCustomerReference: ").Append(EnhancedSchemeDataCustomerReference).Append("\n"); + sb.Append(" EnhancedSchemeDataEmployeeName: ").Append(EnhancedSchemeDataEmployeeName).Append("\n"); + sb.Append(" EnhancedSchemeDataJobDescription: ").Append(EnhancedSchemeDataJobDescription).Append("\n"); + sb.Append(" EnhancedSchemeDataRegularHoursRate: ").Append(EnhancedSchemeDataRegularHoursRate).Append("\n"); + sb.Append(" EnhancedSchemeDataRegularHoursWorked: ").Append(EnhancedSchemeDataRegularHoursWorked).Append("\n"); + sb.Append(" EnhancedSchemeDataRequestName: ").Append(EnhancedSchemeDataRequestName).Append("\n"); + sb.Append(" EnhancedSchemeDataTempStartDate: ").Append(EnhancedSchemeDataTempStartDate).Append("\n"); + sb.Append(" EnhancedSchemeDataTempWeekEnding: ").Append(EnhancedSchemeDataTempWeekEnding).Append("\n"); + sb.Append(" EnhancedSchemeDataTotalTaxAmount: ").Append(EnhancedSchemeDataTotalTaxAmount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataTemporaryServicesJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataTemporaryServices Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option enhancedSchemeDataCustomerReference = default; + Option enhancedSchemeDataEmployeeName = default; + Option enhancedSchemeDataJobDescription = default; + Option enhancedSchemeDataRegularHoursRate = default; + Option enhancedSchemeDataRegularHoursWorked = default; + Option enhancedSchemeDataRequestName = default; + Option enhancedSchemeDataTempStartDate = default; + Option enhancedSchemeDataTempWeekEnding = default; + Option enhancedSchemeDataTotalTaxAmount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "enhancedSchemeData.customerReference": + enhancedSchemeDataCustomerReference = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.employeeName": + enhancedSchemeDataEmployeeName = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.jobDescription": + enhancedSchemeDataJobDescription = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.regularHoursRate": + enhancedSchemeDataRegularHoursRate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.regularHoursWorked": + enhancedSchemeDataRegularHoursWorked = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.requestName": + enhancedSchemeDataRequestName = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.tempStartDate": + enhancedSchemeDataTempStartDate = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.tempWeekEnding": + enhancedSchemeDataTempWeekEnding = new Option(utf8JsonReader.GetString()!); + break; + case "enhancedSchemeData.totalTaxAmount": + enhancedSchemeDataTotalTaxAmount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataTemporaryServices(enhancedSchemeDataCustomerReference, enhancedSchemeDataEmployeeName, enhancedSchemeDataJobDescription, enhancedSchemeDataRegularHoursRate, enhancedSchemeDataRegularHoursWorked, enhancedSchemeDataRequestName, enhancedSchemeDataTempStartDate, enhancedSchemeDataTempWeekEnding, enhancedSchemeDataTotalTaxAmount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataTemporaryServices additionalDataTemporaryServices, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataTemporaryServices, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataTemporaryServices additionalDataTemporaryServices, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataTemporaryServices._EnhancedSchemeDataCustomerReferenceOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataCustomerReference != null) + writer.WriteString("enhancedSchemeData.customerReference", additionalDataTemporaryServices.EnhancedSchemeDataCustomerReference); + + if (additionalDataTemporaryServices._EnhancedSchemeDataEmployeeNameOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataEmployeeName != null) + writer.WriteString("enhancedSchemeData.employeeName", additionalDataTemporaryServices.EnhancedSchemeDataEmployeeName); + + if (additionalDataTemporaryServices._EnhancedSchemeDataJobDescriptionOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataJobDescription != null) + writer.WriteString("enhancedSchemeData.jobDescription", additionalDataTemporaryServices.EnhancedSchemeDataJobDescription); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRegularHoursRateOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursRate != null) + writer.WriteString("enhancedSchemeData.regularHoursRate", additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursRate); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRegularHoursWorkedOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursWorked != null) + writer.WriteString("enhancedSchemeData.regularHoursWorked", additionalDataTemporaryServices.EnhancedSchemeDataRegularHoursWorked); + + if (additionalDataTemporaryServices._EnhancedSchemeDataRequestNameOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataRequestName != null) + writer.WriteString("enhancedSchemeData.requestName", additionalDataTemporaryServices.EnhancedSchemeDataRequestName); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTempStartDateOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTempStartDate != null) + writer.WriteString("enhancedSchemeData.tempStartDate", additionalDataTemporaryServices.EnhancedSchemeDataTempStartDate); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTempWeekEndingOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTempWeekEnding != null) + writer.WriteString("enhancedSchemeData.tempWeekEnding", additionalDataTemporaryServices.EnhancedSchemeDataTempWeekEnding); + + if (additionalDataTemporaryServices._EnhancedSchemeDataTotalTaxAmountOption.IsSet) + if (additionalDataTemporaryServices.EnhancedSchemeDataTotalTaxAmount != null) + writer.WriteString("enhancedSchemeData.totalTaxAmount", additionalDataTemporaryServices.EnhancedSchemeDataTotalTaxAmount); + } + } +} diff --git a/Adyen/Payment/Models/AdditionalDataWallets.cs b/Adyen/Payment/Models/AdditionalDataWallets.cs new file mode 100644 index 000000000..8420ed7c6 --- /dev/null +++ b/Adyen/Payment/Models/AdditionalDataWallets.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdditionalDataWallets. + /// + public partial class AdditionalDataWallets : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Android Pay token retrieved from the SDK. + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + /// The Apple Pay token retrieved from the SDK. + /// The Google Pay token retrieved from the SDK. + /// The Samsung Pay token retrieved from the SDK. + /// The Visa Checkout Call ID retrieved from the SDK. + [JsonConstructor] + public AdditionalDataWallets(Option androidpayToken = default, Option masterpassTransactionId = default, Option paymentToken = default, Option paywithgoogleToken = default, Option samsungpayToken = default, Option visacheckoutCallId = default) + { + _AndroidpayTokenOption = androidpayToken; + _MasterpassTransactionIdOption = masterpassTransactionId; + _PaymentTokenOption = paymentToken; + _PaywithgoogleTokenOption = paywithgoogleToken; + _SamsungpayTokenOption = samsungpayToken; + _VisacheckoutCallIdOption = visacheckoutCallId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalDataWallets() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AndroidpayTokenOption { get; private set; } + + /// + /// The Android Pay token retrieved from the SDK. + /// + /// The Android Pay token retrieved from the SDK. + [JsonPropertyName("androidpay.token")] + public string? AndroidpayToken { get { return this._AndroidpayTokenOption; } set { this._AndroidpayTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MasterpassTransactionIdOption { get; private set; } + + /// + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + /// + /// The Mastercard Masterpass Transaction ID retrieved from the SDK. + [JsonPropertyName("masterpass.transactionId")] + public string? MasterpassTransactionId { get { return this._MasterpassTransactionIdOption; } set { this._MasterpassTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentTokenOption { get; private set; } + + /// + /// The Apple Pay token retrieved from the SDK. + /// + /// The Apple Pay token retrieved from the SDK. + [JsonPropertyName("payment.token")] + public string? PaymentToken { get { return this._PaymentTokenOption; } set { this._PaymentTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaywithgoogleTokenOption { get; private set; } + + /// + /// The Google Pay token retrieved from the SDK. + /// + /// The Google Pay token retrieved from the SDK. + [JsonPropertyName("paywithgoogle.token")] + public string? PaywithgoogleToken { get { return this._PaywithgoogleTokenOption; } set { this._PaywithgoogleTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SamsungpayTokenOption { get; private set; } + + /// + /// The Samsung Pay token retrieved from the SDK. + /// + /// The Samsung Pay token retrieved from the SDK. + [JsonPropertyName("samsungpay.token")] + public string? SamsungpayToken { get { return this._SamsungpayTokenOption; } set { this._SamsungpayTokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisacheckoutCallIdOption { get; private set; } + + /// + /// The Visa Checkout Call ID retrieved from the SDK. + /// + /// The Visa Checkout Call ID retrieved from the SDK. + [JsonPropertyName("visacheckout.callId")] + public string? VisacheckoutCallId { get { return this._VisacheckoutCallIdOption; } set { this._VisacheckoutCallIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalDataWallets {\n"); + sb.Append(" AndroidpayToken: ").Append(AndroidpayToken).Append("\n"); + sb.Append(" MasterpassTransactionId: ").Append(MasterpassTransactionId).Append("\n"); + sb.Append(" PaymentToken: ").Append(PaymentToken).Append("\n"); + sb.Append(" PaywithgoogleToken: ").Append(PaywithgoogleToken).Append("\n"); + sb.Append(" SamsungpayToken: ").Append(SamsungpayToken).Append("\n"); + sb.Append(" VisacheckoutCallId: ").Append(VisacheckoutCallId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalDataWalletsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalDataWallets Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option androidpayToken = default; + Option masterpassTransactionId = default; + Option paymentToken = default; + Option paywithgoogleToken = default; + Option samsungpayToken = default; + Option visacheckoutCallId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "androidpay.token": + androidpayToken = new Option(utf8JsonReader.GetString()!); + break; + case "masterpass.transactionId": + masterpassTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "payment.token": + paymentToken = new Option(utf8JsonReader.GetString()!); + break; + case "paywithgoogle.token": + paywithgoogleToken = new Option(utf8JsonReader.GetString()!); + break; + case "samsungpay.token": + samsungpayToken = new Option(utf8JsonReader.GetString()!); + break; + case "visacheckout.callId": + visacheckoutCallId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AdditionalDataWallets(androidpayToken, masterpassTransactionId, paymentToken, paywithgoogleToken, samsungpayToken, visacheckoutCallId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalDataWallets additionalDataWallets, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalDataWallets, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalDataWallets additionalDataWallets, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalDataWallets._AndroidpayTokenOption.IsSet) + if (additionalDataWallets.AndroidpayToken != null) + writer.WriteString("androidpay.token", additionalDataWallets.AndroidpayToken); + + if (additionalDataWallets._MasterpassTransactionIdOption.IsSet) + if (additionalDataWallets.MasterpassTransactionId != null) + writer.WriteString("masterpass.transactionId", additionalDataWallets.MasterpassTransactionId); + + if (additionalDataWallets._PaymentTokenOption.IsSet) + if (additionalDataWallets.PaymentToken != null) + writer.WriteString("payment.token", additionalDataWallets.PaymentToken); + + if (additionalDataWallets._PaywithgoogleTokenOption.IsSet) + if (additionalDataWallets.PaywithgoogleToken != null) + writer.WriteString("paywithgoogle.token", additionalDataWallets.PaywithgoogleToken); + + if (additionalDataWallets._SamsungpayTokenOption.IsSet) + if (additionalDataWallets.SamsungpayToken != null) + writer.WriteString("samsungpay.token", additionalDataWallets.SamsungpayToken); + + if (additionalDataWallets._VisacheckoutCallIdOption.IsSet) + if (additionalDataWallets.VisacheckoutCallId != null) + writer.WriteString("visacheckout.callId", additionalDataWallets.VisacheckoutCallId); + } + } +} diff --git a/Adyen/Payment/Models/Address.cs b/Adyen/Payment/Models/Address.cs new file mode 100644 index 000000000..186866882 --- /dev/null +++ b/Adyen/Payment/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/Payment/Models/AdjustAuthorisationRequest.cs b/Adyen/Payment/Models/AdjustAuthorisationRequest.cs new file mode 100644 index 000000000..0aba247ec --- /dev/null +++ b/Adyen/Payment/Models/AdjustAuthorisationRequest.cs @@ -0,0 +1,411 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AdjustAuthorisationRequest. + /// + public partial class AdjustAuthorisationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// modificationAmount + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// mpiData + /// The original merchant reference to cancel. + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public AdjustAuthorisationRequest(string merchantAccount, Amount modificationAmount, string originalReference, Option?> additionalData = default, Option mpiData = default, Option originalMerchantReference = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + ModificationAmount = modificationAmount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdjustAuthorisationRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount ModificationAmount { get; set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdjustAuthorisationRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdjustAuthorisationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdjustAuthorisationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option modificationAmount = default; + Option originalReference = default; + Option?> additionalData = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class AdjustAuthorisationRequest.", nameof(merchantAccount)); + + if (!modificationAmount.IsSet) + throw new ArgumentException("Property is required for class AdjustAuthorisationRequest.", nameof(modificationAmount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class AdjustAuthorisationRequest.", nameof(originalReference)); + + return new AdjustAuthorisationRequest(merchantAccount.Value!, modificationAmount.Value!, originalReference.Value!, additionalData, mpiData, originalMerchantReference, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdjustAuthorisationRequest adjustAuthorisationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, adjustAuthorisationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdjustAuthorisationRequest adjustAuthorisationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (adjustAuthorisationRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", adjustAuthorisationRequest.MerchantAccount); + + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, adjustAuthorisationRequest.ModificationAmount, jsonSerializerOptions); + if (adjustAuthorisationRequest.OriginalReference != null) + writer.WriteString("originalReference", adjustAuthorisationRequest.OriginalReference); + + if (adjustAuthorisationRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, adjustAuthorisationRequest.AdditionalData, jsonSerializerOptions); + } + if (adjustAuthorisationRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, adjustAuthorisationRequest.MpiData, jsonSerializerOptions); + } + if (adjustAuthorisationRequest._OriginalMerchantReferenceOption.IsSet) + if (adjustAuthorisationRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", adjustAuthorisationRequest.OriginalMerchantReference); + + if (adjustAuthorisationRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, adjustAuthorisationRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (adjustAuthorisationRequest._ReferenceOption.IsSet) + if (adjustAuthorisationRequest.Reference != null) + writer.WriteString("reference", adjustAuthorisationRequest.Reference); + + if (adjustAuthorisationRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, adjustAuthorisationRequest.Splits, jsonSerializerOptions); + } + if (adjustAuthorisationRequest._TenderReferenceOption.IsSet) + if (adjustAuthorisationRequest.TenderReference != null) + writer.WriteString("tenderReference", adjustAuthorisationRequest.TenderReference); + + if (adjustAuthorisationRequest._UniqueTerminalIdOption.IsSet) + if (adjustAuthorisationRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", adjustAuthorisationRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/Amount.cs b/Adyen/Payment/Models/Amount.cs new file mode 100644 index 000000000..d4bc91565 --- /dev/null +++ b/Adyen/Payment/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Payment/Models/ApplicationInfo.cs b/Adyen/Payment/Models/ApplicationInfo.cs new file mode 100644 index 000000000..49dc90a7a --- /dev/null +++ b/Adyen/Payment/Models/ApplicationInfo.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ApplicationInfo. + /// + public partial class ApplicationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// adyenLibrary + /// adyenPaymentSource + /// externalPlatform + /// merchantApplication + /// merchantDevice + /// shopperInteractionDevice + [JsonConstructor] + public ApplicationInfo(Option adyenLibrary = default, Option adyenPaymentSource = default, Option externalPlatform = default, Option merchantApplication = default, Option merchantDevice = default, Option shopperInteractionDevice = default) + { + _AdyenLibraryOption = adyenLibrary; + _AdyenPaymentSourceOption = adyenPaymentSource; + _ExternalPlatformOption = externalPlatform; + _MerchantApplicationOption = merchantApplication; + _MerchantDeviceOption = merchantDevice; + _ShopperInteractionDeviceOption = shopperInteractionDevice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApplicationInfo() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenLibraryOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("adyenLibrary")] + public CommonField? AdyenLibrary { get { return this._AdyenLibraryOption; } set { this._AdyenLibraryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdyenPaymentSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("adyenPaymentSource")] + public CommonField? AdyenPaymentSource { get { return this._AdyenPaymentSourceOption; } set { this._AdyenPaymentSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalPlatformOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalPlatform")] + public ExternalPlatform? ExternalPlatform { get { return this._ExternalPlatformOption; } set { this._ExternalPlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantApplicationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantApplication")] + public CommonField? MerchantApplication { get { return this._MerchantApplicationOption; } set { this._MerchantApplicationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantDevice")] + public MerchantDevice? MerchantDevice { get { return this._MerchantDeviceOption; } set { this._MerchantDeviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionDeviceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperInteractionDevice")] + public ShopperInteractionDevice? ShopperInteractionDevice { get { return this._ShopperInteractionDeviceOption; } set { this._ShopperInteractionDeviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApplicationInfo {\n"); + sb.Append(" AdyenLibrary: ").Append(AdyenLibrary).Append("\n"); + sb.Append(" AdyenPaymentSource: ").Append(AdyenPaymentSource).Append("\n"); + sb.Append(" ExternalPlatform: ").Append(ExternalPlatform).Append("\n"); + sb.Append(" MerchantApplication: ").Append(MerchantApplication).Append("\n"); + sb.Append(" MerchantDevice: ").Append(MerchantDevice).Append("\n"); + sb.Append(" ShopperInteractionDevice: ").Append(ShopperInteractionDevice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApplicationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApplicationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option adyenLibrary = default; + Option adyenPaymentSource = default; + Option externalPlatform = default; + Option merchantApplication = default; + Option merchantDevice = default; + Option shopperInteractionDevice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "adyenLibrary": + adyenLibrary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "adyenPaymentSource": + adyenPaymentSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalPlatform": + externalPlatform = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantApplication": + merchantApplication = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantDevice": + merchantDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperInteractionDevice": + shopperInteractionDevice = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ApplicationInfo(adyenLibrary, adyenPaymentSource, externalPlatform, merchantApplication, merchantDevice, shopperInteractionDevice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApplicationInfo applicationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, applicationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApplicationInfo applicationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (applicationInfo._AdyenLibraryOption.IsSet) + { + writer.WritePropertyName("adyenLibrary"); + JsonSerializer.Serialize(writer, applicationInfo.AdyenLibrary, jsonSerializerOptions); + } + if (applicationInfo._AdyenPaymentSourceOption.IsSet) + { + writer.WritePropertyName("adyenPaymentSource"); + JsonSerializer.Serialize(writer, applicationInfo.AdyenPaymentSource, jsonSerializerOptions); + } + if (applicationInfo._ExternalPlatformOption.IsSet) + { + writer.WritePropertyName("externalPlatform"); + JsonSerializer.Serialize(writer, applicationInfo.ExternalPlatform, jsonSerializerOptions); + } + if (applicationInfo._MerchantApplicationOption.IsSet) + { + writer.WritePropertyName("merchantApplication"); + JsonSerializer.Serialize(writer, applicationInfo.MerchantApplication, jsonSerializerOptions); + } + if (applicationInfo._MerchantDeviceOption.IsSet) + { + writer.WritePropertyName("merchantDevice"); + JsonSerializer.Serialize(writer, applicationInfo.MerchantDevice, jsonSerializerOptions); + } + if (applicationInfo._ShopperInteractionDeviceOption.IsSet) + { + writer.WritePropertyName("shopperInteractionDevice"); + JsonSerializer.Serialize(writer, applicationInfo.ShopperInteractionDevice, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/AuthenticationResultRequest.cs b/Adyen/Payment/Models/AuthenticationResultRequest.cs new file mode 100644 index 000000000..ca5d2617c --- /dev/null +++ b/Adyen/Payment/Models/AuthenticationResultRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AuthenticationResultRequest. + /// + public partial class AuthenticationResultRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which the authentication was processed. + /// The pspReference identifier for the transaction. + [JsonConstructor] + public AuthenticationResultRequest(string merchantAccount, string pspReference) + { + MerchantAccount = merchantAccount; + PspReference = pspReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationResultRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which the authentication was processed. + /// + /// The merchant account identifier, with which the authentication was processed. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The pspReference identifier for the transaction. + /// + /// The pspReference identifier for the transaction. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationResultRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationResultRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationResultRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option pspReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class AuthenticationResultRequest.", nameof(merchantAccount)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class AuthenticationResultRequest.", nameof(pspReference)); + + return new AuthenticationResultRequest(merchantAccount.Value!, pspReference.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationResultRequest authenticationResultRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationResultRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationResultRequest authenticationResultRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationResultRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", authenticationResultRequest.MerchantAccount); + + if (authenticationResultRequest.PspReference != null) + writer.WriteString("pspReference", authenticationResultRequest.PspReference); + } + } +} diff --git a/Adyen/Payment/Models/AuthenticationResultResponse.cs b/Adyen/Payment/Models/AuthenticationResultResponse.cs new file mode 100644 index 000000000..7d45b2f35 --- /dev/null +++ b/Adyen/Payment/Models/AuthenticationResultResponse.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// AuthenticationResultResponse. + /// + public partial class AuthenticationResultResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// threeDS1Result + /// threeDS2Result + [JsonConstructor] + public AuthenticationResultResponse(Option threeDS1Result = default, Option threeDS2Result = default) + { + _ThreeDS1ResultOption = threeDS1Result; + _ThreeDS2ResultOption = threeDS2Result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationResultResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS1ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS1Result")] + public ThreeDS1Result? ThreeDS1Result { get { return this._ThreeDS1ResultOption; } set { this._ThreeDS1ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2Result")] + public ThreeDS2Result? ThreeDS2Result { get { return this._ThreeDS2ResultOption; } set { this._ThreeDS2ResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationResultResponse {\n"); + sb.Append(" ThreeDS1Result: ").Append(ThreeDS1Result).Append("\n"); + sb.Append(" ThreeDS2Result: ").Append(ThreeDS2Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationResultResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationResultResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDS1Result = default; + Option threeDS2Result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDS1Result": + threeDS1Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2Result": + threeDS2Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new AuthenticationResultResponse(threeDS1Result, threeDS2Result); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationResultResponse authenticationResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationResultResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationResultResponse authenticationResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationResultResponse._ThreeDS1ResultOption.IsSet) + { + writer.WritePropertyName("threeDS1Result"); + JsonSerializer.Serialize(writer, authenticationResultResponse.ThreeDS1Result, jsonSerializerOptions); + } + if (authenticationResultResponse._ThreeDS2ResultOption.IsSet) + { + writer.WritePropertyName("threeDS2Result"); + JsonSerializer.Serialize(writer, authenticationResultResponse.ThreeDS2Result, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/BankAccount.cs b/Adyen/Payment/Models/BankAccount.cs new file mode 100644 index 000000000..27060bc82 --- /dev/null +++ b/Adyen/Payment/Models/BankAccount.cs @@ -0,0 +1,377 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// BankAccount. + /// + public partial class BankAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The bank city. + /// The location id of the bank. The field value is `nil` in most cases. + /// The name of the bank. + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// The bank account holder's tax ID. + [JsonConstructor] + public BankAccount(Option bankAccountNumber = default, Option bankCity = default, Option bankLocationId = default, Option bankName = default, Option bic = default, Option countryCode = default, Option iban = default, Option ownerName = default, Option taxId = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankCityOption = bankCity; + _BankLocationIdOption = bankLocationId; + _BankNameOption = bankName; + _BicOption = bic; + _CountryCodeOption = countryCode; + _IbanOption = iban; + _OwnerNameOption = ownerName; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccount() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCityOption { get; private set; } + + /// + /// The bank city. + /// + /// The bank city. + [JsonPropertyName("bankCity")] + public string? BankCity { get { return this._BankCityOption; } set { this._BankCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The location id of the bank. The field value is `nil` in most cases. + /// + /// The location id of the bank. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankNameOption { get; private set; } + + /// + /// The name of the bank. + /// + /// The name of the bank. + [JsonPropertyName("bankName")] + public string? BankName { get { return this._BankNameOption; } set { this._BankNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The bank account holder's tax ID. + /// + /// The bank account holder's tax ID. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccount {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankCity: ").Append(BankCity).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" BankName: ").Append(BankName).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankCity = default; + Option bankLocationId = default; + Option bankName = default; + Option bic = default; + Option countryCode = default; + Option iban = default; + Option ownerName = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCity": + bankCity = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "bankName": + bankName = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BankAccount(bankAccountNumber, bankCity, bankLocationId, bankName, bic, countryCode, iban, ownerName, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccount._BankAccountNumberOption.IsSet) + if (bankAccount.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", bankAccount.BankAccountNumber); + + if (bankAccount._BankCityOption.IsSet) + if (bankAccount.BankCity != null) + writer.WriteString("bankCity", bankAccount.BankCity); + + if (bankAccount._BankLocationIdOption.IsSet) + if (bankAccount.BankLocationId != null) + writer.WriteString("bankLocationId", bankAccount.BankLocationId); + + if (bankAccount._BankNameOption.IsSet) + if (bankAccount.BankName != null) + writer.WriteString("bankName", bankAccount.BankName); + + if (bankAccount._BicOption.IsSet) + if (bankAccount.Bic != null) + writer.WriteString("bic", bankAccount.Bic); + + if (bankAccount._CountryCodeOption.IsSet) + if (bankAccount.CountryCode != null) + writer.WriteString("countryCode", bankAccount.CountryCode); + + if (bankAccount._IbanOption.IsSet) + if (bankAccount.Iban != null) + writer.WriteString("iban", bankAccount.Iban); + + if (bankAccount._OwnerNameOption.IsSet) + if (bankAccount.OwnerName != null) + writer.WriteString("ownerName", bankAccount.OwnerName); + + if (bankAccount._TaxIdOption.IsSet) + if (bankAccount.TaxId != null) + writer.WriteString("taxId", bankAccount.TaxId); + } + } +} diff --git a/Adyen/Payment/Models/BrowserInfo.cs b/Adyen/Payment/Models/BrowserInfo.cs new file mode 100644 index 000000000..987b886e2 --- /dev/null +++ b/Adyen/Payment/Models/BrowserInfo.cs @@ -0,0 +1,330 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// BrowserInfo. + /// + public partial class BrowserInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The accept header value of the shopper's browser. + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + /// Boolean value indicating if the shopper's browser is able to execute Java. + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + /// The total height of the shopper's device screen in pixels. + /// The total width of the shopper's device screen in pixels. + /// Time difference between UTC time and the shopper's browser local time, in minutes. + /// The user agent value of the shopper's browser. + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. (default to true) + [JsonConstructor] + public BrowserInfo(string acceptHeader, int colorDepth, bool javaEnabled, string language, int screenHeight, int screenWidth, int timeZoneOffset, string userAgent, Option javaScriptEnabled = default) + { + AcceptHeader = acceptHeader; + ColorDepth = colorDepth; + JavaEnabled = javaEnabled; + Language = language; + ScreenHeight = screenHeight; + ScreenWidth = screenWidth; + TimeZoneOffset = timeZoneOffset; + UserAgent = userAgent; + _JavaScriptEnabledOption = javaScriptEnabled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BrowserInfo() + { + } + + partial void OnCreated(); + + /// + /// The accept header value of the shopper's browser. + /// + /// The accept header value of the shopper's browser. + [JsonPropertyName("acceptHeader")] + public string AcceptHeader { get; set; } + + /// + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + /// + /// The color depth of the shopper's browser in bits per pixel. This should be obtained by using the browser's `screen.colorDepth` property. Accepted values: 1, 4, 8, 15, 16, 24, 30, 32 or 48 bit color depth. + [JsonPropertyName("colorDepth")] + public int ColorDepth { get; set; } + + /// + /// Boolean value indicating if the shopper's browser is able to execute Java. + /// + /// Boolean value indicating if the shopper's browser is able to execute Java. + [JsonPropertyName("javaEnabled")] + public bool JavaEnabled { get; set; } + + /// + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + /// + /// The `navigator.language` value of the shopper's browser (as defined in IETF BCP 47). + [JsonPropertyName("language")] + public string Language { get; set; } + + /// + /// The total height of the shopper's device screen in pixels. + /// + /// The total height of the shopper's device screen in pixels. + [JsonPropertyName("screenHeight")] + public int ScreenHeight { get; set; } + + /// + /// The total width of the shopper's device screen in pixels. + /// + /// The total width of the shopper's device screen in pixels. + [JsonPropertyName("screenWidth")] + public int ScreenWidth { get; set; } + + /// + /// Time difference between UTC time and the shopper's browser local time, in minutes. + /// + /// Time difference between UTC time and the shopper's browser local time, in minutes. + [JsonPropertyName("timeZoneOffset")] + public int TimeZoneOffset { get; set; } + + /// + /// The user agent value of the shopper's browser. + /// + /// The user agent value of the shopper's browser. + [JsonPropertyName("userAgent")] + public string UserAgent { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _JavaScriptEnabledOption { get; private set; } + + /// + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. + /// + /// Boolean value indicating if the shopper's browser is able to execute JavaScript. A default 'true' value is assumed if the field is not present. + [JsonPropertyName("javaScriptEnabled")] + public bool? JavaScriptEnabled { get { return this._JavaScriptEnabledOption; } set { this._JavaScriptEnabledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BrowserInfo {\n"); + sb.Append(" AcceptHeader: ").Append(AcceptHeader).Append("\n"); + sb.Append(" ColorDepth: ").Append(ColorDepth).Append("\n"); + sb.Append(" JavaEnabled: ").Append(JavaEnabled).Append("\n"); + sb.Append(" Language: ").Append(Language).Append("\n"); + sb.Append(" ScreenHeight: ").Append(ScreenHeight).Append("\n"); + sb.Append(" ScreenWidth: ").Append(ScreenWidth).Append("\n"); + sb.Append(" TimeZoneOffset: ").Append(TimeZoneOffset).Append("\n"); + sb.Append(" UserAgent: ").Append(UserAgent).Append("\n"); + sb.Append(" JavaScriptEnabled: ").Append(JavaScriptEnabled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BrowserInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BrowserInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acceptHeader = default; + Option colorDepth = default; + Option javaEnabled = default; + Option language = default; + Option screenHeight = default; + Option screenWidth = default; + Option timeZoneOffset = default; + Option userAgent = default; + Option javaScriptEnabled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acceptHeader": + acceptHeader = new Option(utf8JsonReader.GetString()!); + break; + case "colorDepth": + colorDepth = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "javaEnabled": + javaEnabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "language": + language = new Option(utf8JsonReader.GetString()!); + break; + case "screenHeight": + screenHeight = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "screenWidth": + screenWidth = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "timeZoneOffset": + timeZoneOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "userAgent": + userAgent = new Option(utf8JsonReader.GetString()!); + break; + case "javaScriptEnabled": + javaScriptEnabled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!acceptHeader.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(acceptHeader)); + + if (!colorDepth.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(colorDepth)); + + if (!javaEnabled.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(javaEnabled)); + + if (!language.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(language)); + + if (!screenHeight.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(screenHeight)); + + if (!screenWidth.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(screenWidth)); + + if (!timeZoneOffset.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(timeZoneOffset)); + + if (!userAgent.IsSet) + throw new ArgumentException("Property is required for class BrowserInfo.", nameof(userAgent)); + + return new BrowserInfo(acceptHeader.Value!, colorDepth.Value!.Value!, javaEnabled.Value!.Value!, language.Value!, screenHeight.Value!.Value!, screenWidth.Value!.Value!, timeZoneOffset.Value!.Value!, userAgent.Value!, javaScriptEnabled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BrowserInfo browserInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, browserInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BrowserInfo browserInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (browserInfo.AcceptHeader != null) + writer.WriteString("acceptHeader", browserInfo.AcceptHeader); + + writer.WriteNumber("colorDepth", browserInfo.ColorDepth); + + writer.WriteBoolean("javaEnabled", browserInfo.JavaEnabled); + + if (browserInfo.Language != null) + writer.WriteString("language", browserInfo.Language); + + writer.WriteNumber("screenHeight", browserInfo.ScreenHeight); + + writer.WriteNumber("screenWidth", browserInfo.ScreenWidth); + + writer.WriteNumber("timeZoneOffset", browserInfo.TimeZoneOffset); + + if (browserInfo.UserAgent != null) + writer.WriteString("userAgent", browserInfo.UserAgent); + + if (browserInfo._JavaScriptEnabledOption.IsSet) + writer.WriteBoolean("javaScriptEnabled", browserInfo._JavaScriptEnabledOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/CancelOrRefundRequest.cs b/Adyen/Payment/Models/CancelOrRefundRequest.cs new file mode 100644 index 000000000..47e92b07d --- /dev/null +++ b/Adyen/Payment/Models/CancelOrRefundRequest.cs @@ -0,0 +1,367 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// CancelOrRefundRequest. + /// + public partial class CancelOrRefundRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// mpiData + /// The original merchant reference to cancel. + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public CancelOrRefundRequest(string merchantAccount, string originalReference, Option?> additionalData = default, Option mpiData = default, Option originalMerchantReference = default, Option platformChargebackLogic = default, Option reference = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CancelOrRefundRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CancelOrRefundRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CancelOrRefundRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CancelOrRefundRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option originalReference = default; + Option?> additionalData = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CancelOrRefundRequest.", nameof(merchantAccount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class CancelOrRefundRequest.", nameof(originalReference)); + + return new CancelOrRefundRequest(merchantAccount.Value!, originalReference.Value!, additionalData, mpiData, originalMerchantReference, platformChargebackLogic, reference, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CancelOrRefundRequest cancelOrRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cancelOrRefundRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CancelOrRefundRequest cancelOrRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (cancelOrRefundRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", cancelOrRefundRequest.MerchantAccount); + + if (cancelOrRefundRequest.OriginalReference != null) + writer.WriteString("originalReference", cancelOrRefundRequest.OriginalReference); + + if (cancelOrRefundRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, cancelOrRefundRequest.AdditionalData, jsonSerializerOptions); + } + if (cancelOrRefundRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, cancelOrRefundRequest.MpiData, jsonSerializerOptions); + } + if (cancelOrRefundRequest._OriginalMerchantReferenceOption.IsSet) + if (cancelOrRefundRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", cancelOrRefundRequest.OriginalMerchantReference); + + if (cancelOrRefundRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, cancelOrRefundRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (cancelOrRefundRequest._ReferenceOption.IsSet) + if (cancelOrRefundRequest.Reference != null) + writer.WriteString("reference", cancelOrRefundRequest.Reference); + + if (cancelOrRefundRequest._TenderReferenceOption.IsSet) + if (cancelOrRefundRequest.TenderReference != null) + writer.WriteString("tenderReference", cancelOrRefundRequest.TenderReference); + + if (cancelOrRefundRequest._UniqueTerminalIdOption.IsSet) + if (cancelOrRefundRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", cancelOrRefundRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/CancelRequest.cs b/Adyen/Payment/Models/CancelRequest.cs new file mode 100644 index 000000000..721e4dcc5 --- /dev/null +++ b/Adyen/Payment/Models/CancelRequest.cs @@ -0,0 +1,393 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// CancelRequest. + /// + public partial class CancelRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// mpiData + /// The original merchant reference to cancel. + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public CancelRequest(string merchantAccount, string originalReference, Option?> additionalData = default, Option mpiData = default, Option originalMerchantReference = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CancelRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CancelRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CancelRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CancelRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option originalReference = default; + Option?> additionalData = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CancelRequest.", nameof(merchantAccount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class CancelRequest.", nameof(originalReference)); + + return new CancelRequest(merchantAccount.Value!, originalReference.Value!, additionalData, mpiData, originalMerchantReference, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CancelRequest cancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cancelRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CancelRequest cancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (cancelRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", cancelRequest.MerchantAccount); + + if (cancelRequest.OriginalReference != null) + writer.WriteString("originalReference", cancelRequest.OriginalReference); + + if (cancelRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, cancelRequest.AdditionalData, jsonSerializerOptions); + } + if (cancelRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, cancelRequest.MpiData, jsonSerializerOptions); + } + if (cancelRequest._OriginalMerchantReferenceOption.IsSet) + if (cancelRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", cancelRequest.OriginalMerchantReference); + + if (cancelRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, cancelRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (cancelRequest._ReferenceOption.IsSet) + if (cancelRequest.Reference != null) + writer.WriteString("reference", cancelRequest.Reference); + + if (cancelRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, cancelRequest.Splits, jsonSerializerOptions); + } + if (cancelRequest._TenderReferenceOption.IsSet) + if (cancelRequest.TenderReference != null) + writer.WriteString("tenderReference", cancelRequest.TenderReference); + + if (cancelRequest._UniqueTerminalIdOption.IsSet) + if (cancelRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", cancelRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/CaptureRequest.cs b/Adyen/Payment/Models/CaptureRequest.cs new file mode 100644 index 000000000..3338e73a5 --- /dev/null +++ b/Adyen/Payment/Models/CaptureRequest.cs @@ -0,0 +1,411 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// CaptureRequest. + /// + public partial class CaptureRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// modificationAmount + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// mpiData + /// The original merchant reference to cancel. + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public CaptureRequest(string merchantAccount, Amount modificationAmount, string originalReference, Option?> additionalData = default, Option mpiData = default, Option originalMerchantReference = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + ModificationAmount = modificationAmount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CaptureRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount ModificationAmount { get; set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CaptureRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CaptureRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CaptureRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option modificationAmount = default; + Option originalReference = default; + Option?> additionalData = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CaptureRequest.", nameof(merchantAccount)); + + if (!modificationAmount.IsSet) + throw new ArgumentException("Property is required for class CaptureRequest.", nameof(modificationAmount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class CaptureRequest.", nameof(originalReference)); + + return new CaptureRequest(merchantAccount.Value!, modificationAmount.Value!, originalReference.Value!, additionalData, mpiData, originalMerchantReference, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CaptureRequest captureRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, captureRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CaptureRequest captureRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (captureRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", captureRequest.MerchantAccount); + + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, captureRequest.ModificationAmount, jsonSerializerOptions); + if (captureRequest.OriginalReference != null) + writer.WriteString("originalReference", captureRequest.OriginalReference); + + if (captureRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, captureRequest.AdditionalData, jsonSerializerOptions); + } + if (captureRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, captureRequest.MpiData, jsonSerializerOptions); + } + if (captureRequest._OriginalMerchantReferenceOption.IsSet) + if (captureRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", captureRequest.OriginalMerchantReference); + + if (captureRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, captureRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (captureRequest._ReferenceOption.IsSet) + if (captureRequest.Reference != null) + writer.WriteString("reference", captureRequest.Reference); + + if (captureRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, captureRequest.Splits, jsonSerializerOptions); + } + if (captureRequest._TenderReferenceOption.IsSet) + if (captureRequest.TenderReference != null) + writer.WriteString("tenderReference", captureRequest.TenderReference); + + if (captureRequest._UniqueTerminalIdOption.IsSet) + if (captureRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", captureRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/Card.cs b/Adyen/Payment/Models/Card.cs new file mode 100644 index 000000000..01c6b6119 --- /dev/null +++ b/Adyen/Payment/Models/Card.cs @@ -0,0 +1,448 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// The card expiry year. Format: 4 digits. For example: 2020 + /// The name of the cardholder, as printed on the card. + /// The issue number of the card (for some UK debit cards only). + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// The month component of the start date (for some UK debit cards only). + /// The year component of the start date (for some UK debit cards only). + [JsonConstructor] + public Card(Option cvc = default, Option expiryMonth = default, Option expiryYear = default, Option holderName = default, Option issueNumber = default, Option number = default, Option startMonth = default, Option startYear = default) + { + _CvcOption = cvc; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _HolderNameOption = holderName; + _IssueNumberOption = issueNumber; + _NumberOption = number; + _StartMonthOption = startMonth; + _StartYearOption = startYear; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the cardholder, as printed on the card. + /// + /// The name of the cardholder, as printed on the card. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueNumberOption { get; private set; } + + /// + /// The issue number of the card (for some UK debit cards only). + /// + /// The issue number of the card (for some UK debit cards only). + [JsonPropertyName("issueNumber")] + public string? IssueNumber { get { return this._IssueNumberOption; } set { this._IssueNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartMonthOption { get; private set; } + + /// + /// The month component of the start date (for some UK debit cards only). + /// + /// The month component of the start date (for some UK debit cards only). + [JsonPropertyName("startMonth")] + public string? StartMonth { get { return this._StartMonthOption; } set { this._StartMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartYearOption { get; private set; } + + /// + /// The year component of the start date (for some UK debit cards only). + /// + /// The year component of the start date (for some UK debit cards only). + [JsonPropertyName("startYear")] + public string? StartYear { get { return this._StartYearOption; } set { this._StartYearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" IssueNumber: ").Append(IssueNumber).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" StartMonth: ").Append(StartMonth).Append("\n"); + sb.Append(" StartYear: ").Append(StartYear).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Cvc (string) maxLength + if (this.Cvc != null && this.Cvc.Length > 20) + { + yield return new ValidationResult("Invalid value for Cvc, length must be less than 20.", new [] { "Cvc" }); + } + + // Cvc (string) minLength + if (this.Cvc != null && this.Cvc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cvc, length must be greater than 1.", new [] { "Cvc" }); + } + + // ExpiryMonth (string) maxLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be less than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryMonth (string) minLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be greater than 1.", new [] { "ExpiryMonth" }); + } + + // ExpiryYear (string) maxLength + if (this.ExpiryYear != null && this.ExpiryYear.Length > 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be less than 4.", new [] { "ExpiryYear" }); + } + + // ExpiryYear (string) minLength + if (this.ExpiryYear != null && this.ExpiryYear.Length < 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be greater than 4.", new [] { "ExpiryYear" }); + } + + // HolderName (string) maxLength + if (this.HolderName != null && this.HolderName.Length > 50) + { + yield return new ValidationResult("Invalid value for HolderName, length must be less than 50.", new [] { "HolderName" }); + } + + // HolderName (string) minLength + if (this.HolderName != null && this.HolderName.Length < 1) + { + yield return new ValidationResult("Invalid value for HolderName, length must be greater than 1.", new [] { "HolderName" }); + } + + // IssueNumber (string) maxLength + if (this.IssueNumber != null && this.IssueNumber.Length > 2) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be less than 2.", new [] { "IssueNumber" }); + } + + // IssueNumber (string) minLength + if (this.IssueNumber != null && this.IssueNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be greater than 1.", new [] { "IssueNumber" }); + } + + // Number (string) maxLength + if (this.Number != null && this.Number.Length > 19) + { + yield return new ValidationResult("Invalid value for Number, length must be less than 19.", new [] { "Number" }); + } + + // Number (string) minLength + if (this.Number != null && this.Number.Length < 4) + { + yield return new ValidationResult("Invalid value for Number, length must be greater than 4.", new [] { "Number" }); + } + + // StartMonth (string) maxLength + if (this.StartMonth != null && this.StartMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be less than 2.", new [] { "StartMonth" }); + } + + // StartMonth (string) minLength + if (this.StartMonth != null && this.StartMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be greater than 1.", new [] { "StartMonth" }); + } + + // StartYear (string) maxLength + if (this.StartYear != null && this.StartYear.Length > 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be less than 4.", new [] { "StartYear" }); + } + + // StartYear (string) minLength + if (this.StartYear != null && this.StartYear.Length < 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be greater than 4.", new [] { "StartYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cvc = default; + Option expiryMonth = default; + Option expiryYear = default; + Option holderName = default; + Option issueNumber = default; + Option number = default; + Option startMonth = default; + Option startYear = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "issueNumber": + issueNumber = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "startMonth": + startMonth = new Option(utf8JsonReader.GetString()!); + break; + case "startYear": + startYear = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Card(cvc, expiryMonth, expiryYear, holderName, issueNumber, number, startMonth, startYear); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + if (card._CvcOption.IsSet) + if (card.Cvc != null) + writer.WriteString("cvc", card.Cvc); + + if (card._ExpiryMonthOption.IsSet) + if (card.ExpiryMonth != null) + writer.WriteString("expiryMonth", card.ExpiryMonth); + + if (card._ExpiryYearOption.IsSet) + if (card.ExpiryYear != null) + writer.WriteString("expiryYear", card.ExpiryYear); + + if (card._HolderNameOption.IsSet) + if (card.HolderName != null) + writer.WriteString("holderName", card.HolderName); + + if (card._IssueNumberOption.IsSet) + if (card.IssueNumber != null) + writer.WriteString("issueNumber", card.IssueNumber); + + if (card._NumberOption.IsSet) + if (card.Number != null) + writer.WriteString("number", card.Number); + + if (card._StartMonthOption.IsSet) + if (card.StartMonth != null) + writer.WriteString("startMonth", card.StartMonth); + + if (card._StartYearOption.IsSet) + if (card.StartYear != null) + writer.WriteString("startYear", card.StartYear); + } + } +} diff --git a/Adyen/Payment/Models/CommonField.cs b/Adyen/Payment/Models/CommonField.cs new file mode 100644 index 000000000..15f3e0aa4 --- /dev/null +++ b/Adyen/Payment/Models/CommonField.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// CommonField. + /// + public partial class CommonField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Name of the field. For example, Name of External Platform. + /// Version of the field. For example, Version of External Platform. + [JsonConstructor] + public CommonField(Option name = default, Option version = default) + { + _NameOption = name; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CommonField() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Name of the field. For example, Name of External Platform. + /// + /// Name of the field. For example, Name of External Platform. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// Version of the field. For example, Version of External Platform. + /// + /// Version of the field. For example, Version of External Platform. + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CommonField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CommonFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CommonField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CommonField(name, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CommonField commonField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, commonField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CommonField commonField, JsonSerializerOptions jsonSerializerOptions) + { + + if (commonField._NameOption.IsSet) + if (commonField.Name != null) + writer.WriteString("name", commonField.Name); + + if (commonField._VersionOption.IsSet) + if (commonField.Version != null) + writer.WriteString("version", commonField.Version); + } + } +} diff --git a/Adyen/Payment/Models/DeviceRenderOptions.cs b/Adyen/Payment/Models/DeviceRenderOptions.cs new file mode 100644 index 000000000..7a1a8c2e7 --- /dev/null +++ b/Adyen/Payment/Models/DeviceRenderOptions.cs @@ -0,0 +1,448 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// DeviceRenderOptions. + /// + public partial class DeviceRenderOptions : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Supported SDK interface types. Allowed values: * native * html * both (default to SdkInterfaceEnum.Both) + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + [JsonConstructor] + public DeviceRenderOptions(Option sdkInterface = default, Option?> sdkUiType = default) + { + _SdkInterfaceOption = sdkInterface; + _SdkUiTypeOption = sdkUiType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DeviceRenderOptions() + { + } + + partial void OnCreated(); + + /// + /// Supported SDK interface types. Allowed values: * native * html * both + /// + /// Supported SDK interface types. Allowed values: * native * html * both + [JsonConverter(typeof(SdkInterfaceEnumJsonConverter))] + public class SdkInterfaceEnum : IEnum + { + /// + /// Returns the value of the SdkInterfaceEnum. + /// + public string? Value { get; set; } + + /// + /// SdkInterfaceEnum.Native - native + /// + public static readonly SdkInterfaceEnum Native = new("native"); + + /// + /// SdkInterfaceEnum.Html - html + /// + public static readonly SdkInterfaceEnum Html = new("html"); + + /// + /// SdkInterfaceEnum.Both - both + /// + public static readonly SdkInterfaceEnum Both = new("both"); + + private SdkInterfaceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SdkInterfaceEnum?(string? value) => value == null ? null : new SdkInterfaceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SdkInterfaceEnum? option) => option?.Value; + + public static bool operator ==(SdkInterfaceEnum? left, SdkInterfaceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SdkInterfaceEnum? left, SdkInterfaceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SdkInterfaceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SdkInterfaceEnum? FromStringOrDefault(string value) + { + return value switch { + "native" => SdkInterfaceEnum.Native, + "html" => SdkInterfaceEnum.Html, + "both" => SdkInterfaceEnum.Both, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SdkInterfaceEnum? value) + { + if (value == null) + return null; + + if (value == SdkInterfaceEnum.Native) + return "native"; + + if (value == SdkInterfaceEnum.Html) + return "html"; + + if (value == SdkInterfaceEnum.Both) + return "both"; + + return null; + } + + /// + /// JsonConverter for writing SdkInterfaceEnum. + /// + public class SdkInterfaceEnumJsonConverter : JsonConverter + { + public override SdkInterfaceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SdkInterfaceEnum.FromStringOrDefault(value) ?? new SdkInterfaceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SdkInterfaceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SdkInterfaceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkInterfaceOption { get; private set; } + + /// + /// Supported SDK interface types. Allowed values: * native * html * both + /// + /// Supported SDK interface types. Allowed values: * native * html * both + [JsonPropertyName("sdkInterface")] + public SdkInterfaceEnum? SdkInterface { get { return this._SdkInterfaceOption; } set { this._SdkInterfaceOption = new(value); } } + + /// + /// Defines SdkUiType. + /// + [JsonConverter(typeof(SdkUiTypeEnumJsonConverter))] + public class SdkUiTypeEnum : IEnum + { + /// + /// Returns the value of the SdkUiTypeEnum. + /// + public string? Value { get; set; } + + /// + /// SdkUiTypeEnum.MultiSelect - multiSelect + /// + public static readonly SdkUiTypeEnum MultiSelect = new("multiSelect"); + + /// + /// SdkUiTypeEnum.OtherHtml - otherHtml + /// + public static readonly SdkUiTypeEnum OtherHtml = new("otherHtml"); + + /// + /// SdkUiTypeEnum.OutOfBand - outOfBand + /// + public static readonly SdkUiTypeEnum OutOfBand = new("outOfBand"); + + /// + /// SdkUiTypeEnum.SingleSelect - singleSelect + /// + public static readonly SdkUiTypeEnum SingleSelect = new("singleSelect"); + + /// + /// SdkUiTypeEnum.Text - text + /// + public static readonly SdkUiTypeEnum Text = new("text"); + + private SdkUiTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SdkUiTypeEnum?(string? value) => value == null ? null : new SdkUiTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SdkUiTypeEnum? option) => option?.Value; + + public static bool operator ==(SdkUiTypeEnum? left, SdkUiTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SdkUiTypeEnum? left, SdkUiTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SdkUiTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SdkUiTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "multiSelect" => SdkUiTypeEnum.MultiSelect, + "otherHtml" => SdkUiTypeEnum.OtherHtml, + "outOfBand" => SdkUiTypeEnum.OutOfBand, + "singleSelect" => SdkUiTypeEnum.SingleSelect, + "text" => SdkUiTypeEnum.Text, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SdkUiTypeEnum? value) + { + if (value == null) + return null; + + if (value == SdkUiTypeEnum.MultiSelect) + return "multiSelect"; + + if (value == SdkUiTypeEnum.OtherHtml) + return "otherHtml"; + + if (value == SdkUiTypeEnum.OutOfBand) + return "outOfBand"; + + if (value == SdkUiTypeEnum.SingleSelect) + return "singleSelect"; + + if (value == SdkUiTypeEnum.Text) + return "text"; + + return null; + } + + /// + /// JsonConverter for writing SdkUiTypeEnum. + /// + public class SdkUiTypeEnumJsonConverter : JsonConverter + { + public override SdkUiTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SdkUiTypeEnum.FromStringOrDefault(value) ?? new SdkUiTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SdkUiTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SdkUiTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SdkUiTypeOption { get; private set; } + + /// + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + /// + /// UI types supported for displaying specific challenges. Allowed values: * text * singleSelect * outOfBand * otherHtml * multiSelect + [JsonPropertyName("sdkUiType")] + public List? SdkUiType { get { return this._SdkUiTypeOption; } set { this._SdkUiTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeviceRenderOptions {\n"); + sb.Append(" SdkInterface: ").Append(SdkInterface).Append("\n"); + sb.Append(" SdkUiType: ").Append(SdkUiType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeviceRenderOptionsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DeviceRenderOptions Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sdkInterface = default; + Option?> sdkUiType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sdkInterface": + string? sdkInterfaceRawValue = utf8JsonReader.GetString(); + sdkInterface = new Option(DeviceRenderOptions.SdkInterfaceEnum.FromStringOrDefault(sdkInterfaceRawValue)); + break; + case "sdkUiType": + sdkUiType = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new DeviceRenderOptions(sdkInterface, sdkUiType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeviceRenderOptions deviceRenderOptions, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, deviceRenderOptions, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeviceRenderOptions deviceRenderOptions, JsonSerializerOptions jsonSerializerOptions) + { + + if (deviceRenderOptions._SdkInterfaceOption.IsSet && deviceRenderOptions.SdkInterface != null) + { + string? sdkInterfaceRawValue = DeviceRenderOptions.SdkInterfaceEnum.ToJsonValue(deviceRenderOptions._SdkInterfaceOption.Value!.Value); + writer.WriteString("sdkInterface", sdkInterfaceRawValue); + } + + if (deviceRenderOptions._SdkUiTypeOption.IsSet) + { + writer.WritePropertyName("sdkUiType"); + JsonSerializer.Serialize(writer, deviceRenderOptions.SdkUiType, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/DonationRequest.cs b/Adyen/Payment/Models/DonationRequest.cs new file mode 100644 index 000000000..fe62b4e3f --- /dev/null +++ b/Adyen/Payment/Models/DonationRequest.cs @@ -0,0 +1,284 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// DonationRequest. + /// + public partial class DonationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Adyen account name of the charity. + /// The merchant account that is used to process the payment. + /// modificationAmount + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonConstructor] + public DonationRequest(string donationAccount, string merchantAccount, Amount modificationAmount, Option originalReference = default, Option platformChargebackLogic = default, Option reference = default) + { + DonationAccount = donationAccount; + MerchantAccount = merchantAccount; + ModificationAmount = modificationAmount; + _OriginalReferenceOption = originalReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DonationRequest() + { + } + + partial void OnCreated(); + + /// + /// The Adyen account name of the charity. + /// + /// The Adyen account name of the charity. + [JsonPropertyName("donationAccount")] + public string DonationAccount { get; set; } + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount ModificationAmount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalReferenceOption { get; private set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string? OriginalReference { get { return this._OriginalReferenceOption; } set { this._OriginalReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DonationRequest {\n"); + sb.Append(" DonationAccount: ").Append(DonationAccount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DonationRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DonationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option donationAccount = default; + Option merchantAccount = default; + Option modificationAmount = default; + Option originalReference = default; + Option platformChargebackLogic = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "donationAccount": + donationAccount = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!donationAccount.IsSet) + throw new ArgumentException("Property is required for class DonationRequest.", nameof(donationAccount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class DonationRequest.", nameof(merchantAccount)); + + if (!modificationAmount.IsSet) + throw new ArgumentException("Property is required for class DonationRequest.", nameof(modificationAmount)); + + return new DonationRequest(donationAccount.Value!, merchantAccount.Value!, modificationAmount.Value!, originalReference, platformChargebackLogic, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DonationRequest donationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, donationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DonationRequest donationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (donationRequest.DonationAccount != null) + writer.WriteString("donationAccount", donationRequest.DonationAccount); + + if (donationRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", donationRequest.MerchantAccount); + + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, donationRequest.ModificationAmount, jsonSerializerOptions); + if (donationRequest._OriginalReferenceOption.IsSet) + if (donationRequest.OriginalReference != null) + writer.WriteString("originalReference", donationRequest.OriginalReference); + + if (donationRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, donationRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (donationRequest._ReferenceOption.IsSet) + if (donationRequest.Reference != null) + writer.WriteString("reference", donationRequest.Reference); + } + } +} diff --git a/Adyen/Payment/Models/ExternalPlatform.cs b/Adyen/Payment/Models/ExternalPlatform.cs new file mode 100644 index 000000000..3a0a2ec9b --- /dev/null +++ b/Adyen/Payment/Models/ExternalPlatform.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ExternalPlatform. + /// + public partial class ExternalPlatform : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// External platform integrator. + /// Name of the field. For example, Name of External Platform. + /// Version of the field. For example, Version of External Platform. + [JsonConstructor] + public ExternalPlatform(Option integrator = default, Option name = default, Option version = default) + { + _IntegratorOption = integrator; + _NameOption = name; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExternalPlatform() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IntegratorOption { get; private set; } + + /// + /// External platform integrator. + /// + /// External platform integrator. + [JsonPropertyName("integrator")] + public string? Integrator { get { return this._IntegratorOption; } set { this._IntegratorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// Name of the field. For example, Name of External Platform. + /// + /// Name of the field. For example, Name of External Platform. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// Version of the field. For example, Version of External Platform. + /// + /// Version of the field. For example, Version of External Platform. + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExternalPlatform {\n"); + sb.Append(" Integrator: ").Append(Integrator).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExternalPlatformJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExternalPlatform Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option integrator = default; + Option name = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "integrator": + integrator = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExternalPlatform(integrator, name, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExternalPlatform externalPlatform, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, externalPlatform, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExternalPlatform externalPlatform, JsonSerializerOptions jsonSerializerOptions) + { + + if (externalPlatform._IntegratorOption.IsSet) + if (externalPlatform.Integrator != null) + writer.WriteString("integrator", externalPlatform.Integrator); + + if (externalPlatform._NameOption.IsSet) + if (externalPlatform.Name != null) + writer.WriteString("name", externalPlatform.Name); + + if (externalPlatform._VersionOption.IsSet) + if (externalPlatform.Version != null) + writer.WriteString("version", externalPlatform.Version); + } + } +} diff --git a/Adyen/Payment/Models/ForexQuote.cs b/Adyen/Payment/Models/ForexQuote.cs new file mode 100644 index 000000000..54f272156 --- /dev/null +++ b/Adyen/Payment/Models/ForexQuote.cs @@ -0,0 +1,444 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ForexQuote. + /// + public partial class ForexQuote : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The base points. + /// The date until which the forex quote is valid. + /// The account name. + /// The account type. + /// baseAmount + /// buy + /// interbank + /// The reference assigned to the forex quote request. + /// sell + /// The signature to validate the integrity. + /// The source of the forex quote. + /// The type of forex. + [JsonConstructor] + public ForexQuote(int basePoints, DateTimeOffset validTill, Option account = default, Option accountType = default, Option baseAmount = default, Option buy = default, Option interbank = default, Option reference = default, Option sell = default, Option signature = default, Option source = default, Option type = default) + { + BasePoints = basePoints; + ValidTill = validTill; + _AccountOption = account; + _AccountTypeOption = accountType; + _BaseAmountOption = baseAmount; + _BuyOption = buy; + _InterbankOption = interbank; + _ReferenceOption = reference; + _SellOption = sell; + _SignatureOption = signature; + _SourceOption = source; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ForexQuote() + { + } + + partial void OnCreated(); + + /// + /// The base points. + /// + /// The base points. + [JsonPropertyName("basePoints")] + public int BasePoints { get; set; } + + /// + /// The date until which the forex quote is valid. + /// + /// The date until which the forex quote is valid. + [JsonPropertyName("validTill")] + public DateTimeOffset ValidTill { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountOption { get; private set; } + + /// + /// The account name. + /// + /// The account name. + [JsonPropertyName("account")] + public string? Account { get { return this._AccountOption; } set { this._AccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The account type. + /// + /// The account type. + [JsonPropertyName("accountType")] + public string? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BaseAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("baseAmount")] + public Amount? BaseAmount { get { return this._BaseAmountOption; } set { this._BaseAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BuyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("buy")] + public Amount? Buy { get { return this._BuyOption; } set { this._BuyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InterbankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("interbank")] + public Amount? Interbank { get { return this._InterbankOption; } set { this._InterbankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference assigned to the forex quote request. + /// + /// The reference assigned to the forex quote request. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SellOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sell")] + public Amount? Sell { get { return this._SellOption; } set { this._SellOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SignatureOption { get; private set; } + + /// + /// The signature to validate the integrity. + /// + /// The signature to validate the integrity. + [JsonPropertyName("signature")] + public string? Signature { get { return this._SignatureOption; } set { this._SignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SourceOption { get; private set; } + + /// + /// The source of the forex quote. + /// + /// The source of the forex quote. + [JsonPropertyName("source")] + public string? Source { get { return this._SourceOption; } set { this._SourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of forex. + /// + /// The type of forex. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ForexQuote {\n"); + sb.Append(" BasePoints: ").Append(BasePoints).Append("\n"); + sb.Append(" ValidTill: ").Append(ValidTill).Append("\n"); + sb.Append(" Account: ").Append(Account).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" BaseAmount: ").Append(BaseAmount).Append("\n"); + sb.Append(" Buy: ").Append(Buy).Append("\n"); + sb.Append(" Interbank: ").Append(Interbank).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Sell: ").Append(Sell).Append("\n"); + sb.Append(" Signature: ").Append(Signature).Append("\n"); + sb.Append(" Source: ").Append(Source).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ForexQuoteJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ValidTill. + /// + public static string ValidTillFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ForexQuote Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option basePoints = default; + Option validTill = default; + Option account = default; + Option accountType = default; + Option baseAmount = default; + Option buy = default; + Option interbank = default; + Option reference = default; + Option sell = default; + Option signature = default; + Option source = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "basePoints": + basePoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "validTill": + validTill = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "account": + account = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + accountType = new Option(utf8JsonReader.GetString()!); + break; + case "baseAmount": + baseAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "buy": + buy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "interbank": + interbank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "sell": + sell = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "signature": + signature = new Option(utf8JsonReader.GetString()!); + break; + case "source": + source = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!basePoints.IsSet) + throw new ArgumentException("Property is required for class ForexQuote.", nameof(basePoints)); + + if (!validTill.IsSet) + throw new ArgumentException("Property is required for class ForexQuote.", nameof(validTill)); + + return new ForexQuote(basePoints.Value!.Value!, validTill.Value!.Value!, account, accountType, baseAmount, buy, interbank, reference, sell, signature, source, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ForexQuote forexQuote, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, forexQuote, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ForexQuote forexQuote, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("basePoints", forexQuote.BasePoints); + + writer.WriteString("validTill", forexQuote.ValidTill.ToString(ValidTillFormat)); + + if (forexQuote._AccountOption.IsSet) + if (forexQuote.Account != null) + writer.WriteString("account", forexQuote.Account); + + if (forexQuote._AccountTypeOption.IsSet) + if (forexQuote.AccountType != null) + writer.WriteString("accountType", forexQuote.AccountType); + + if (forexQuote._BaseAmountOption.IsSet) + { + writer.WritePropertyName("baseAmount"); + JsonSerializer.Serialize(writer, forexQuote.BaseAmount, jsonSerializerOptions); + } + if (forexQuote._BuyOption.IsSet) + { + writer.WritePropertyName("buy"); + JsonSerializer.Serialize(writer, forexQuote.Buy, jsonSerializerOptions); + } + if (forexQuote._InterbankOption.IsSet) + { + writer.WritePropertyName("interbank"); + JsonSerializer.Serialize(writer, forexQuote.Interbank, jsonSerializerOptions); + } + if (forexQuote._ReferenceOption.IsSet) + if (forexQuote.Reference != null) + writer.WriteString("reference", forexQuote.Reference); + + if (forexQuote._SellOption.IsSet) + { + writer.WritePropertyName("sell"); + JsonSerializer.Serialize(writer, forexQuote.Sell, jsonSerializerOptions); + } + if (forexQuote._SignatureOption.IsSet) + if (forexQuote.Signature != null) + writer.WriteString("signature", forexQuote.Signature); + + if (forexQuote._SourceOption.IsSet) + if (forexQuote.Source != null) + writer.WriteString("source", forexQuote.Source); + + if (forexQuote._TypeOption.IsSet) + if (forexQuote.Type != null) + writer.WriteString("type", forexQuote.Type); + } + } +} diff --git a/Adyen/Payment/Models/FraudCheckResult.cs b/Adyen/Payment/Models/FraudCheckResult.cs new file mode 100644 index 000000000..65e72f8c1 --- /dev/null +++ b/Adyen/Payment/Models/FraudCheckResult.cs @@ -0,0 +1,209 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// FraudCheckResult. + /// + public partial class FraudCheckResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The fraud score generated by the risk check. + /// The ID of the risk check. + /// The name of the risk check. + [JsonConstructor] + public FraudCheckResult(int accountScore, int checkId, string name) + { + AccountScore = accountScore; + CheckId = checkId; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudCheckResult() + { + } + + partial void OnCreated(); + + /// + /// The fraud score generated by the risk check. + /// + /// The fraud score generated by the risk check. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// The ID of the risk check. + /// + /// The ID of the risk check. + [JsonPropertyName("checkId")] + public int CheckId { get; set; } + + /// + /// The name of the risk check. + /// + /// The name of the risk check. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudCheckResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" CheckId: ").Append(CheckId).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudCheckResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option checkId = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "checkId": + checkId = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(accountScore)); + + if (!checkId.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(checkId)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(name)); + + return new FraudCheckResult(accountScore.Value!.Value!, checkId.Value!.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudCheckResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudCheckResult.AccountScore); + + writer.WriteNumber("checkId", fraudCheckResult.CheckId); + + if (fraudCheckResult.Name != null) + writer.WriteString("name", fraudCheckResult.Name); + } + } +} diff --git a/Adyen/Payment/Models/FraudCheckResultWrapper.cs b/Adyen/Payment/Models/FraudCheckResultWrapper.cs new file mode 100644 index 000000000..f83543ff7 --- /dev/null +++ b/Adyen/Payment/Models/FraudCheckResultWrapper.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// FraudCheckResultWrapper. + /// + public partial class FraudCheckResultWrapper : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// fraudCheckResult + [JsonConstructor] + public FraudCheckResultWrapper(Option fraudCheckResult = default) + { + _FraudCheckResultOption = fraudCheckResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudCheckResultWrapper() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudCheckResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("FraudCheckResult")] + public FraudCheckResult? FraudCheckResult { get { return this._FraudCheckResultOption; } set { this._FraudCheckResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudCheckResultWrapper {\n"); + sb.Append(" FraudCheckResult: ").Append(FraudCheckResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudCheckResultWrapperJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudCheckResultWrapper Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option fraudCheckResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "FraudCheckResult": + fraudCheckResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new FraudCheckResultWrapper(fraudCheckResult); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudCheckResultWrapper fraudCheckResultWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudCheckResultWrapper, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudCheckResultWrapper fraudCheckResultWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + if (fraudCheckResultWrapper._FraudCheckResultOption.IsSet) + { + writer.WritePropertyName("FraudCheckResult"); + JsonSerializer.Serialize(writer, fraudCheckResultWrapper.FraudCheckResult, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/FraudResult.cs b/Adyen/Payment/Models/FraudResult.cs new file mode 100644 index 000000000..3b138f341 --- /dev/null +++ b/Adyen/Payment/Models/FraudResult.cs @@ -0,0 +1,197 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// FraudResult. + /// + public partial class FraudResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The total fraud score generated by the risk checks. + /// The result of the individual risk checks. + [JsonConstructor] + public FraudResult(int accountScore, Option?> results = default) + { + AccountScore = accountScore; + _ResultsOption = results; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudResult() + { + } + + partial void OnCreated(); + + /// + /// The total fraud score generated by the risk checks. + /// + /// The total fraud score generated by the risk checks. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ResultsOption { get; private set; } + + /// + /// The result of the individual risk checks. + /// + /// The result of the individual risk checks. + [JsonPropertyName("results")] + public List? Results { get { return this._ResultsOption; } set { this._ResultsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" Results: ").Append(Results).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option?> results = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "results": + results = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudResult.", nameof(accountScore)); + + return new FraudResult(accountScore.Value!.Value!, results); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudResult.AccountScore); + + if (fraudResult._ResultsOption.IsSet) + { + writer.WritePropertyName("results"); + JsonSerializer.Serialize(writer, fraudResult.Results, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/FundDestination.cs b/Adyen/Payment/Models/FundDestination.cs new file mode 100644 index 000000000..dd0f3d7e9 --- /dev/null +++ b/Adyen/Payment/Models/FundDestination.cs @@ -0,0 +1,428 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// FundDestination. + /// + public partial class FundDestination : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Bank Account Number of the recipient + /// a map of name/value pairs for passing in additional/industry-specific data + /// billingAddress + /// card + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// the email address of the person + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// subMerchant + /// the telephone number of the person + /// The purpose of a digital wallet transaction. + [JsonConstructor] + public FundDestination(Option iBAN = default, Option?> additionalData = default, Option billingAddress = default, Option card = default, Option selectedRecurringDetailReference = default, Option shopperEmail = default, Option shopperName = default, Option shopperReference = default, Option subMerchant = default, Option telephoneNumber = default, Option walletPurpose = default) + { + _IBANOption = iBAN; + _AdditionalDataOption = additionalData; + _BillingAddressOption = billingAddress; + _CardOption = card; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _SubMerchantOption = subMerchant; + _TelephoneNumberOption = telephoneNumber; + _WalletPurposeOption = walletPurpose; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FundDestination() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IBANOption { get; private set; } + + /// + /// Bank Account Number of the recipient + /// + /// Bank Account Number of the recipient + [JsonPropertyName("IBAN")] + public string? IBAN { get { return this._IBANOption; } set { this._IBANOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// a map of name/value pairs for passing in additional/industry-specific data + /// + /// a map of name/value pairs for passing in additional/industry-specific data + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// the email address of the person + /// + /// the email address of the person + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubMerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("subMerchant")] + public SubMerchant? SubMerchant { get { return this._SubMerchantOption; } set { this._SubMerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// the telephone number of the person + /// + /// the telephone number of the person + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WalletPurposeOption { get; private set; } + + /// + /// The purpose of a digital wallet transaction. + /// + /// The purpose of a digital wallet transaction. + [JsonPropertyName("walletPurpose")] + public string? WalletPurpose { get { return this._WalletPurposeOption; } set { this._WalletPurposeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FundDestination {\n"); + sb.Append(" IBAN: ").Append(IBAN).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" SubMerchant: ").Append(SubMerchant).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" WalletPurpose: ").Append(WalletPurpose).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FundDestinationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FundDestination Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iBAN = default; + Option?> additionalData = default; + Option billingAddress = default; + Option card = default; + Option selectedRecurringDetailReference = default; + Option shopperEmail = default; + Option shopperName = default; + Option shopperReference = default; + Option subMerchant = default; + Option telephoneNumber = default; + Option walletPurpose = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "IBAN": + iBAN = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "subMerchant": + subMerchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "walletPurpose": + walletPurpose = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new FundDestination(iBAN, additionalData, billingAddress, card, selectedRecurringDetailReference, shopperEmail, shopperName, shopperReference, subMerchant, telephoneNumber, walletPurpose); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FundDestination fundDestination, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fundDestination, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FundDestination fundDestination, JsonSerializerOptions jsonSerializerOptions) + { + + if (fundDestination._IBANOption.IsSet) + if (fundDestination.IBAN != null) + writer.WriteString("IBAN", fundDestination.IBAN); + + if (fundDestination._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, fundDestination.AdditionalData, jsonSerializerOptions); + } + if (fundDestination._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, fundDestination.BillingAddress, jsonSerializerOptions); + } + if (fundDestination._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, fundDestination.Card, jsonSerializerOptions); + } + if (fundDestination._SelectedRecurringDetailReferenceOption.IsSet) + if (fundDestination.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", fundDestination.SelectedRecurringDetailReference); + + if (fundDestination._ShopperEmailOption.IsSet) + if (fundDestination.ShopperEmail != null) + writer.WriteString("shopperEmail", fundDestination.ShopperEmail); + + if (fundDestination._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, fundDestination.ShopperName, jsonSerializerOptions); + } + if (fundDestination._ShopperReferenceOption.IsSet) + if (fundDestination.ShopperReference != null) + writer.WriteString("shopperReference", fundDestination.ShopperReference); + + if (fundDestination._SubMerchantOption.IsSet) + { + writer.WritePropertyName("subMerchant"); + JsonSerializer.Serialize(writer, fundDestination.SubMerchant, jsonSerializerOptions); + } + if (fundDestination._TelephoneNumberOption.IsSet) + if (fundDestination.TelephoneNumber != null) + writer.WriteString("telephoneNumber", fundDestination.TelephoneNumber); + + if (fundDestination._WalletPurposeOption.IsSet) + if (fundDestination.WalletPurpose != null) + writer.WriteString("walletPurpose", fundDestination.WalletPurpose); + } + } +} diff --git a/Adyen/Payment/Models/FundSource.cs b/Adyen/Payment/Models/FundSource.cs new file mode 100644 index 000000000..ec332fc74 --- /dev/null +++ b/Adyen/Payment/Models/FundSource.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// FundSource. + /// + public partial class FundSource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A map of name-value pairs for passing additional or industry-specific data. + /// billingAddress + /// card + /// Email address of the person. + /// shopperName + /// Phone number of the person + [JsonConstructor] + public FundSource(Option?> additionalData = default, Option billingAddress = default, Option card = default, Option shopperEmail = default, Option shopperName = default, Option telephoneNumber = default) + { + _AdditionalDataOption = additionalData; + _BillingAddressOption = billingAddress; + _CardOption = card; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FundSource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// A map of name-value pairs for passing additional or industry-specific data. + /// + /// A map of name-value pairs for passing additional or industry-specific data. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// Email address of the person. + /// + /// Email address of the person. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// Phone number of the person + /// + /// Phone number of the person + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FundSource {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FundSourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FundSource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option billingAddress = default; + Option card = default; + Option shopperEmail = default; + Option shopperName = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new FundSource(additionalData, billingAddress, card, shopperEmail, shopperName, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FundSource fundSource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fundSource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FundSource fundSource, JsonSerializerOptions jsonSerializerOptions) + { + + if (fundSource._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, fundSource.AdditionalData, jsonSerializerOptions); + } + if (fundSource._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, fundSource.BillingAddress, jsonSerializerOptions); + } + if (fundSource._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, fundSource.Card, jsonSerializerOptions); + } + if (fundSource._ShopperEmailOption.IsSet) + if (fundSource.ShopperEmail != null) + writer.WriteString("shopperEmail", fundSource.ShopperEmail); + + if (fundSource._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, fundSource.ShopperName, jsonSerializerOptions); + } + if (fundSource._TelephoneNumberOption.IsSet) + if (fundSource.TelephoneNumber != null) + writer.WriteString("telephoneNumber", fundSource.TelephoneNumber); + } + } +} diff --git a/Adyen/Payment/Models/Installments.cs b/Adyen/Payment/Models/Installments.cs new file mode 100644 index 000000000..ee2024cfc --- /dev/null +++ b/Adyen/Payment/Models/Installments.cs @@ -0,0 +1,397 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Installments. + /// + public partial class Installments : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonConstructor] + public Installments(int value, Option extra = default, Option plan = default) + { + Value = value; + _ExtraOption = extra; + _PlanOption = plan; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Installments() + { + } + + partial void OnCreated(); + + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonConverter(typeof(PlanEnumJsonConverter))] + public class PlanEnum : IEnum + { + /// + /// Returns the value of the PlanEnum. + /// + public string? Value { get; set; } + + /// + /// PlanEnum.Bonus - bonus + /// + public static readonly PlanEnum Bonus = new("bonus"); + + /// + /// PlanEnum.BuynowPaylater - buynow_paylater + /// + public static readonly PlanEnum BuynowPaylater = new("buynow_paylater"); + + /// + /// PlanEnum.InteresRefundPrctg - interes_refund_prctg + /// + public static readonly PlanEnum InteresRefundPrctg = new("interes_refund_prctg"); + + /// + /// PlanEnum.InterestBonus - interest_bonus + /// + public static readonly PlanEnum InterestBonus = new("interest_bonus"); + + /// + /// PlanEnum.NointeresRefundPrctg - nointeres_refund_prctg + /// + public static readonly PlanEnum NointeresRefundPrctg = new("nointeres_refund_prctg"); + + /// + /// PlanEnum.NointerestBonus - nointerest_bonus + /// + public static readonly PlanEnum NointerestBonus = new("nointerest_bonus"); + + /// + /// PlanEnum.RefundPrctg - refund_prctg + /// + public static readonly PlanEnum RefundPrctg = new("refund_prctg"); + + /// + /// PlanEnum.Regular - regular + /// + public static readonly PlanEnum Regular = new("regular"); + + /// + /// PlanEnum.Revolving - revolving + /// + public static readonly PlanEnum Revolving = new("revolving"); + + /// + /// PlanEnum.WithInterest - with_interest + /// + public static readonly PlanEnum WithInterest = new("with_interest"); + + private PlanEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlanEnum?(string? value) => value == null ? null : new PlanEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlanEnum? option) => option?.Value; + + public static bool operator ==(PlanEnum? left, PlanEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlanEnum? left, PlanEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlanEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlanEnum? FromStringOrDefault(string value) + { + return value switch { + "bonus" => PlanEnum.Bonus, + "buynow_paylater" => PlanEnum.BuynowPaylater, + "interes_refund_prctg" => PlanEnum.InteresRefundPrctg, + "interest_bonus" => PlanEnum.InterestBonus, + "nointeres_refund_prctg" => PlanEnum.NointeresRefundPrctg, + "nointerest_bonus" => PlanEnum.NointerestBonus, + "refund_prctg" => PlanEnum.RefundPrctg, + "regular" => PlanEnum.Regular, + "revolving" => PlanEnum.Revolving, + "with_interest" => PlanEnum.WithInterest, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlanEnum? value) + { + if (value == null) + return null; + + if (value == PlanEnum.Bonus) + return "bonus"; + + if (value == PlanEnum.BuynowPaylater) + return "buynow_paylater"; + + if (value == PlanEnum.InteresRefundPrctg) + return "interes_refund_prctg"; + + if (value == PlanEnum.InterestBonus) + return "interest_bonus"; + + if (value == PlanEnum.NointeresRefundPrctg) + return "nointeres_refund_prctg"; + + if (value == PlanEnum.NointerestBonus) + return "nointerest_bonus"; + + if (value == PlanEnum.RefundPrctg) + return "refund_prctg"; + + if (value == PlanEnum.Regular) + return "regular"; + + if (value == PlanEnum.Revolving) + return "revolving"; + + if (value == PlanEnum.WithInterest) + return "with_interest"; + + return null; + } + + /// + /// JsonConverter for writing PlanEnum. + /// + public class PlanEnumJsonConverter : JsonConverter + { + public override PlanEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlanEnum.FromStringOrDefault(value) ?? new PlanEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlanEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlanEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlanOption { get; private set; } + + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + /// + /// The installment plan, used for [card installments in Japan](https://docs.adyen.com/payment-methods/cards/credit-card-installments#make-a-payment-japan). and [Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico). By default, this is set to **regular**. + [JsonPropertyName("plan")] + public PlanEnum? Plan { get { return this._PlanOption; } set { this._PlanOption = new(value); } } + + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + /// + /// Defines the number of installments. Usually, the maximum allowed number of installments is capped. For example, it may not be possible to split a payment in more than 24 installments. The acquirer sets this upper limit, so its value may vary. This value can be zero for Installments processed in Mexico. + [JsonPropertyName("value")] + public int Value { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraOption { get; private set; } + + /// + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + /// + /// Defines the bonus percentage, refund percentage or if the transaction is Buy now Pay later. Used for [card installments in Mexico](https://docs.adyen.com/payment-methods/cards/credit-card-installments/#getting-paid-mexico) + [JsonPropertyName("extra")] + public int? Extra { get { return this._ExtraOption; } set { this._ExtraOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Installments {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Extra: ").Append(Extra).Append("\n"); + sb.Append(" Plan: ").Append(Plan).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InstallmentsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Installments Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option value = default; + Option extra = default; + Option plan = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "extra": + extra = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "plan": + string? planRawValue = utf8JsonReader.GetString(); + plan = new Option(Installments.PlanEnum.FromStringOrDefault(planRawValue)); + break; + default: + break; + } + } + } + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Installments.", nameof(value)); + + return new Installments(value.Value!.Value!, extra, plan); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Installments installments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, installments, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Installments installments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("value", installments.Value); + + if (installments._ExtraOption.IsSet) + writer.WriteNumber("extra", installments._ExtraOption.Value!.Value); + + if (installments._PlanOption.IsSet && installments.Plan != null) + { + string? planRawValue = Installments.PlanEnum.ToJsonValue(installments._PlanOption.Value!.Value); + writer.WriteString("plan", planRawValue); + } + } + } +} diff --git a/Adyen/Payment/Models/Mandate.cs b/Adyen/Payment/Models/Mandate.cs new file mode 100644 index 000000000..f35c3ef04 --- /dev/null +++ b/Adyen/Payment/Models/Mandate.cs @@ -0,0 +1,743 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Mandate. + /// + public partial class Mandate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The billing amount (in minor units) of the recurring transactions. + /// End date of the billing plan, in YYYY-MM-DD format. + /// The frequency with which a shopper should be charged. Possible values: **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + /// The number of transactions that can be performed within the given frequency. + /// The message shown by UPI to the shopper on the approval screen. + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + [JsonConstructor] + public Mandate(string amount, string endsAt, FrequencyEnum frequency, Option amountRule = default, Option billingAttemptsRule = default, Option billingDay = default, Option count = default, Option remarks = default, Option startsAt = default) + { + Amount = amount; + EndsAt = endsAt; + Frequency = frequency; + _AmountRuleOption = amountRule; + _BillingAttemptsRuleOption = billingAttemptsRule; + _BillingDayOption = billingDay; + _CountOption = count; + _RemarksOption = remarks; + _StartsAtOption = startsAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Mandate() + { + } + + partial void OnCreated(); + + /// + /// The frequency with which a shopper should be charged. Possible values: **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// + /// The frequency with which a shopper should be charged. Possible values: **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + [JsonConverter(typeof(FrequencyEnumJsonConverter))] + public class FrequencyEnum : IEnum + { + /// + /// Returns the value of the FrequencyEnum. + /// + public string? Value { get; set; } + + /// + /// FrequencyEnum.Adhoc - adhoc + /// + public static readonly FrequencyEnum Adhoc = new("adhoc"); + + /// + /// FrequencyEnum.Daily - daily + /// + public static readonly FrequencyEnum Daily = new("daily"); + + /// + /// FrequencyEnum.Weekly - weekly + /// + public static readonly FrequencyEnum Weekly = new("weekly"); + + /// + /// FrequencyEnum.BiWeekly - biWeekly + /// + public static readonly FrequencyEnum BiWeekly = new("biWeekly"); + + /// + /// FrequencyEnum.Monthly - monthly + /// + public static readonly FrequencyEnum Monthly = new("monthly"); + + /// + /// FrequencyEnum.Quarterly - quarterly + /// + public static readonly FrequencyEnum Quarterly = new("quarterly"); + + /// + /// FrequencyEnum.HalfYearly - halfYearly + /// + public static readonly FrequencyEnum HalfYearly = new("halfYearly"); + + /// + /// FrequencyEnum.Yearly - yearly + /// + public static readonly FrequencyEnum Yearly = new("yearly"); + + private FrequencyEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FrequencyEnum?(string? value) => value == null ? null : new FrequencyEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FrequencyEnum? option) => option?.Value; + + public static bool operator ==(FrequencyEnum? left, FrequencyEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FrequencyEnum? left, FrequencyEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FrequencyEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FrequencyEnum? FromStringOrDefault(string value) + { + return value switch { + "adhoc" => FrequencyEnum.Adhoc, + "daily" => FrequencyEnum.Daily, + "weekly" => FrequencyEnum.Weekly, + "biWeekly" => FrequencyEnum.BiWeekly, + "monthly" => FrequencyEnum.Monthly, + "quarterly" => FrequencyEnum.Quarterly, + "halfYearly" => FrequencyEnum.HalfYearly, + "yearly" => FrequencyEnum.Yearly, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FrequencyEnum? value) + { + if (value == null) + return null; + + if (value == FrequencyEnum.Adhoc) + return "adhoc"; + + if (value == FrequencyEnum.Daily) + return "daily"; + + if (value == FrequencyEnum.Weekly) + return "weekly"; + + if (value == FrequencyEnum.BiWeekly) + return "biWeekly"; + + if (value == FrequencyEnum.Monthly) + return "monthly"; + + if (value == FrequencyEnum.Quarterly) + return "quarterly"; + + if (value == FrequencyEnum.HalfYearly) + return "halfYearly"; + + if (value == FrequencyEnum.Yearly) + return "yearly"; + + return null; + } + + /// + /// JsonConverter for writing FrequencyEnum. + /// + public class FrequencyEnumJsonConverter : JsonConverter + { + public override FrequencyEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FrequencyEnum.FromStringOrDefault(value) ?? new FrequencyEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FrequencyEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FrequencyEnum.ToJsonValue(value)); + } + } + } + + /// + /// The frequency with which a shopper should be charged. Possible values: **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + /// + /// The frequency with which a shopper should be charged. Possible values: **daily**, **weekly**, **biWeekly**, **monthly**, **quarterly**, **halfYearly**, **yearly**. + [JsonPropertyName("frequency")] + public FrequencyEnum Frequency { get; set; } + + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + [JsonConverter(typeof(AmountRuleEnumJsonConverter))] + public class AmountRuleEnum : IEnum + { + /// + /// Returns the value of the AmountRuleEnum. + /// + public string? Value { get; set; } + + /// + /// AmountRuleEnum.Max - max + /// + public static readonly AmountRuleEnum Max = new("max"); + + /// + /// AmountRuleEnum.Exact - exact + /// + public static readonly AmountRuleEnum Exact = new("exact"); + + private AmountRuleEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AmountRuleEnum?(string? value) => value == null ? null : new AmountRuleEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AmountRuleEnum? option) => option?.Value; + + public static bool operator ==(AmountRuleEnum? left, AmountRuleEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AmountRuleEnum? left, AmountRuleEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AmountRuleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AmountRuleEnum? FromStringOrDefault(string value) + { + return value switch { + "max" => AmountRuleEnum.Max, + "exact" => AmountRuleEnum.Exact, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AmountRuleEnum? value) + { + if (value == null) + return null; + + if (value == AmountRuleEnum.Max) + return "max"; + + if (value == AmountRuleEnum.Exact) + return "exact"; + + return null; + } + + /// + /// JsonConverter for writing AmountRuleEnum. + /// + public class AmountRuleEnumJsonConverter : JsonConverter + { + public override AmountRuleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AmountRuleEnum.FromStringOrDefault(value) ?? new AmountRuleEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AmountRuleEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AmountRuleEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountRuleOption { get; private set; } + + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + /// + /// The limitation rule of the billing amount. Possible values: * **max**: The transaction amount can not exceed the `amount`. * **exact**: The transaction amount should be the same as the `amount`. + [JsonPropertyName("amountRule")] + public AmountRuleEnum? AmountRule { get { return this._AmountRuleOption; } set { this._AmountRuleOption = new(value); } } + + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + [JsonConverter(typeof(BillingAttemptsRuleEnumJsonConverter))] + public class BillingAttemptsRuleEnum : IEnum + { + /// + /// Returns the value of the BillingAttemptsRuleEnum. + /// + public string? Value { get; set; } + + /// + /// BillingAttemptsRuleEnum.On - on + /// + public static readonly BillingAttemptsRuleEnum On = new("on"); + + /// + /// BillingAttemptsRuleEnum.Before - before + /// + public static readonly BillingAttemptsRuleEnum Before = new("before"); + + /// + /// BillingAttemptsRuleEnum.After - after + /// + public static readonly BillingAttemptsRuleEnum After = new("after"); + + private BillingAttemptsRuleEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BillingAttemptsRuleEnum?(string? value) => value == null ? null : new BillingAttemptsRuleEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BillingAttemptsRuleEnum? option) => option?.Value; + + public static bool operator ==(BillingAttemptsRuleEnum? left, BillingAttemptsRuleEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BillingAttemptsRuleEnum? left, BillingAttemptsRuleEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BillingAttemptsRuleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BillingAttemptsRuleEnum? FromStringOrDefault(string value) + { + return value switch { + "on" => BillingAttemptsRuleEnum.On, + "before" => BillingAttemptsRuleEnum.Before, + "after" => BillingAttemptsRuleEnum.After, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BillingAttemptsRuleEnum? value) + { + if (value == null) + return null; + + if (value == BillingAttemptsRuleEnum.On) + return "on"; + + if (value == BillingAttemptsRuleEnum.Before) + return "before"; + + if (value == BillingAttemptsRuleEnum.After) + return "after"; + + return null; + } + + /// + /// JsonConverter for writing BillingAttemptsRuleEnum. + /// + public class BillingAttemptsRuleEnumJsonConverter : JsonConverter + { + public override BillingAttemptsRuleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BillingAttemptsRuleEnum.FromStringOrDefault(value) ?? new BillingAttemptsRuleEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BillingAttemptsRuleEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BillingAttemptsRuleEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAttemptsRuleOption { get; private set; } + + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + /// + /// The rule to specify the period, within which the recurring debit can happen, relative to the mandate recurring date. Possible values: * **on**: On a specific date. * **before**: Before and on a specific date. * **after**: On and after a specific date. + [JsonPropertyName("billingAttemptsRule")] + public BillingAttemptsRuleEnum? BillingAttemptsRule { get { return this._BillingAttemptsRuleOption; } set { this._BillingAttemptsRuleOption = new(value); } } + + /// + /// The billing amount (in minor units) of the recurring transactions. + /// + /// The billing amount (in minor units) of the recurring transactions. + [JsonPropertyName("amount")] + public string Amount { get; set; } + + /// + /// End date of the billing plan, in YYYY-MM-DD format. + /// + /// End date of the billing plan, in YYYY-MM-DD format. + [JsonPropertyName("endsAt")] + public string EndsAt { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingDayOption { get; private set; } + + /// + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + /// + /// The number of the day, on which the recurring debit can happen. Should be within the same calendar month as the mandate recurring date. Possible values: 1-31 based on the `frequency`. + [JsonPropertyName("billingDay")] + public string? BillingDay { get { return this._BillingDayOption; } set { this._BillingDayOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountOption { get; private set; } + + /// + /// The number of transactions that can be performed within the given frequency. + /// + /// The number of transactions that can be performed within the given frequency. + [JsonPropertyName("count")] + public string? Count { get { return this._CountOption; } set { this._CountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RemarksOption { get; private set; } + + /// + /// The message shown by UPI to the shopper on the approval screen. + /// + /// The message shown by UPI to the shopper on the approval screen. + [JsonPropertyName("remarks")] + public string? Remarks { get { return this._RemarksOption; } set { this._RemarksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartsAtOption { get; private set; } + + /// + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + /// + /// Start date of the billing plan, in YYYY-MM-DD format. By default, the transaction date. + [JsonPropertyName("startsAt")] + public string? StartsAt { get { return this._StartsAtOption; } set { this._StartsAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Mandate {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" EndsAt: ").Append(EndsAt).Append("\n"); + sb.Append(" Frequency: ").Append(Frequency).Append("\n"); + sb.Append(" AmountRule: ").Append(AmountRule).Append("\n"); + sb.Append(" BillingAttemptsRule: ").Append(BillingAttemptsRule).Append("\n"); + sb.Append(" BillingDay: ").Append(BillingDay).Append("\n"); + sb.Append(" Count: ").Append(Count).Append("\n"); + sb.Append(" Remarks: ").Append(Remarks).Append("\n"); + sb.Append(" StartsAt: ").Append(StartsAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MandateJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Mandate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option endsAt = default; + Option frequency = default; + Option amountRule = default; + Option billingAttemptsRule = default; + Option billingDay = default; + Option count = default; + Option remarks = default; + Option startsAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(utf8JsonReader.GetString()!); + break; + case "endsAt": + endsAt = new Option(utf8JsonReader.GetString()!); + break; + case "frequency": + string? frequencyRawValue = utf8JsonReader.GetString(); + frequency = new Option(Mandate.FrequencyEnum.FromStringOrDefault(frequencyRawValue)); + break; + case "amountRule": + string? amountRuleRawValue = utf8JsonReader.GetString(); + amountRule = new Option(Mandate.AmountRuleEnum.FromStringOrDefault(amountRuleRawValue)); + break; + case "billingAttemptsRule": + string? billingAttemptsRuleRawValue = utf8JsonReader.GetString(); + billingAttemptsRule = new Option(Mandate.BillingAttemptsRuleEnum.FromStringOrDefault(billingAttemptsRuleRawValue)); + break; + case "billingDay": + billingDay = new Option(utf8JsonReader.GetString()!); + break; + case "count": + count = new Option(utf8JsonReader.GetString()!); + break; + case "remarks": + remarks = new Option(utf8JsonReader.GetString()!); + break; + case "startsAt": + startsAt = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(amount)); + + if (!endsAt.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(endsAt)); + + if (!frequency.IsSet) + throw new ArgumentException("Property is required for class Mandate.", nameof(frequency)); + + return new Mandate(amount.Value!, endsAt.Value!, frequency.Value!.Value!, amountRule, billingAttemptsRule, billingDay, count, remarks, startsAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Mandate mandate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, mandate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Mandate mandate, JsonSerializerOptions jsonSerializerOptions) + { + + if (mandate.Amount != null) + writer.WriteString("amount", mandate.Amount); + + if (mandate.EndsAt != null) + writer.WriteString("endsAt", mandate.EndsAt); + + if (mandate.Frequency != null) + { + string? frequencyRawValue = Mandate.FrequencyEnum.ToJsonValue(mandate.Frequency); + writer.WriteString("frequency", frequencyRawValue); + } + + if (mandate._AmountRuleOption.IsSet && mandate.AmountRule != null) + { + string? amountRuleRawValue = Mandate.AmountRuleEnum.ToJsonValue(mandate._AmountRuleOption.Value!.Value); + writer.WriteString("amountRule", amountRuleRawValue); + } + + if (mandate._BillingAttemptsRuleOption.IsSet && mandate.BillingAttemptsRule != null) + { + string? billingAttemptsRuleRawValue = Mandate.BillingAttemptsRuleEnum.ToJsonValue(mandate._BillingAttemptsRuleOption.Value!.Value); + writer.WriteString("billingAttemptsRule", billingAttemptsRuleRawValue); + } + + if (mandate._BillingDayOption.IsSet) + if (mandate.BillingDay != null) + writer.WriteString("billingDay", mandate.BillingDay); + + if (mandate._CountOption.IsSet) + if (mandate.Count != null) + writer.WriteString("count", mandate.Count); + + if (mandate._RemarksOption.IsSet) + if (mandate.Remarks != null) + writer.WriteString("remarks", mandate.Remarks); + + if (mandate._StartsAtOption.IsSet) + if (mandate.StartsAt != null) + writer.WriteString("startsAt", mandate.StartsAt); + } + } +} diff --git a/Adyen/Payment/Models/MerchantDevice.cs b/Adyen/Payment/Models/MerchantDevice.cs new file mode 100644 index 000000000..dc74efd3b --- /dev/null +++ b/Adyen/Payment/Models/MerchantDevice.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// MerchantDevice. + /// + public partial class MerchantDevice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Operating system running on the merchant device. + /// Version of the operating system on the merchant device. + /// Merchant device reference. + [JsonConstructor] + public MerchantDevice(Option os = default, Option osVersion = default, Option reference = default) + { + _OsOption = os; + _OsVersionOption = osVersion; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantDevice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsOption { get; private set; } + + /// + /// Operating system running on the merchant device. + /// + /// Operating system running on the merchant device. + [JsonPropertyName("os")] + public string? Os { get { return this._OsOption; } set { this._OsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsVersionOption { get; private set; } + + /// + /// Version of the operating system on the merchant device. + /// + /// Version of the operating system on the merchant device. + [JsonPropertyName("osVersion")] + public string? OsVersion { get { return this._OsVersionOption; } set { this._OsVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Merchant device reference. + /// + /// Merchant device reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantDevice {\n"); + sb.Append(" Os: ").Append(Os).Append("\n"); + sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantDeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantDevice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option os = default; + Option osVersion = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "os": + os = new Option(utf8JsonReader.GetString()!); + break; + case "osVersion": + osVersion = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantDevice(os, osVersion, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantDevice merchantDevice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantDevice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantDevice merchantDevice, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantDevice._OsOption.IsSet) + if (merchantDevice.Os != null) + writer.WriteString("os", merchantDevice.Os); + + if (merchantDevice._OsVersionOption.IsSet) + if (merchantDevice.OsVersion != null) + writer.WriteString("osVersion", merchantDevice.OsVersion); + + if (merchantDevice._ReferenceOption.IsSet) + if (merchantDevice.Reference != null) + writer.WriteString("reference", merchantDevice.Reference); + } + } +} diff --git a/Adyen/Payment/Models/MerchantRiskIndicator.cs b/Adyen/Payment/Models/MerchantRiskIndicator.cs new file mode 100644 index 000000000..81d2833af --- /dev/null +++ b/Adyen/Payment/Models/MerchantRiskIndicator.cs @@ -0,0 +1,784 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// MerchantRiskIndicator. + /// + public partial class MerchantRiskIndicator : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Whether the chosen delivery address is identical to the billing address. + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// The delivery email address (for digital goods). + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// giftCardAmount + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + /// For pre-order purchases, the expected date this product will be available to the shopper. + /// Indicator for whether this transaction is for pre-ordering a product. + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + /// Indicator for whether the shopper has already purchased the same items in the past. + /// Indicates whether the cardholder is reordering previously purchased merchandise. + /// Indicates shipping method chosen for the transaction. + [JsonConstructor] + public MerchantRiskIndicator(Option addressMatch = default, Option deliveryAddressIndicator = default, Option deliveryEmail = default, Option deliveryEmailAddress = default, Option deliveryTimeframe = default, Option giftCardAmount = default, Option giftCardCount = default, Option giftCardCurr = default, Option preOrderDate = default, Option preOrderPurchase = default, Option preOrderPurchaseInd = default, Option reorderItems = default, Option reorderItemsInd = default, Option shipIndicator = default) + { + _AddressMatchOption = addressMatch; + _DeliveryAddressIndicatorOption = deliveryAddressIndicator; + _DeliveryEmailOption = deliveryEmail; + _DeliveryEmailAddressOption = deliveryEmailAddress; + _DeliveryTimeframeOption = deliveryTimeframe; + _GiftCardAmountOption = giftCardAmount; + _GiftCardCountOption = giftCardCount; + _GiftCardCurrOption = giftCardCurr; + _PreOrderDateOption = preOrderDate; + _PreOrderPurchaseOption = preOrderPurchase; + _PreOrderPurchaseIndOption = preOrderPurchaseInd; + _ReorderItemsOption = reorderItems; + _ReorderItemsIndOption = reorderItemsInd; + _ShipIndicatorOption = shipIndicator; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantRiskIndicator() + { + } + + partial void OnCreated(); + + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + [JsonConverter(typeof(DeliveryAddressIndicatorEnumJsonConverter))] + public class DeliveryAddressIndicatorEnum : IEnum + { + /// + /// Returns the value of the DeliveryAddressIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryAddressIndicatorEnum.ShipToBillingAddress - shipToBillingAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToBillingAddress = new("shipToBillingAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToVerifiedAddress - shipToVerifiedAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToVerifiedAddress = new("shipToVerifiedAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToNewAddress - shipToNewAddress + /// + public static readonly DeliveryAddressIndicatorEnum ShipToNewAddress = new("shipToNewAddress"); + + /// + /// DeliveryAddressIndicatorEnum.ShipToStore - shipToStore + /// + public static readonly DeliveryAddressIndicatorEnum ShipToStore = new("shipToStore"); + + /// + /// DeliveryAddressIndicatorEnum.DigitalGoods - digitalGoods + /// + public static readonly DeliveryAddressIndicatorEnum DigitalGoods = new("digitalGoods"); + + /// + /// DeliveryAddressIndicatorEnum.GoodsNotShipped - goodsNotShipped + /// + public static readonly DeliveryAddressIndicatorEnum GoodsNotShipped = new("goodsNotShipped"); + + /// + /// DeliveryAddressIndicatorEnum.Other - other + /// + public static readonly DeliveryAddressIndicatorEnum Other = new("other"); + + private DeliveryAddressIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryAddressIndicatorEnum?(string? value) => value == null ? null : new DeliveryAddressIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryAddressIndicatorEnum? option) => option?.Value; + + public static bool operator ==(DeliveryAddressIndicatorEnum? left, DeliveryAddressIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryAddressIndicatorEnum? left, DeliveryAddressIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryAddressIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryAddressIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "shipToBillingAddress" => DeliveryAddressIndicatorEnum.ShipToBillingAddress, + "shipToVerifiedAddress" => DeliveryAddressIndicatorEnum.ShipToVerifiedAddress, + "shipToNewAddress" => DeliveryAddressIndicatorEnum.ShipToNewAddress, + "shipToStore" => DeliveryAddressIndicatorEnum.ShipToStore, + "digitalGoods" => DeliveryAddressIndicatorEnum.DigitalGoods, + "goodsNotShipped" => DeliveryAddressIndicatorEnum.GoodsNotShipped, + "other" => DeliveryAddressIndicatorEnum.Other, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryAddressIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryAddressIndicatorEnum.ShipToBillingAddress) + return "shipToBillingAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToVerifiedAddress) + return "shipToVerifiedAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToNewAddress) + return "shipToNewAddress"; + + if (value == DeliveryAddressIndicatorEnum.ShipToStore) + return "shipToStore"; + + if (value == DeliveryAddressIndicatorEnum.DigitalGoods) + return "digitalGoods"; + + if (value == DeliveryAddressIndicatorEnum.GoodsNotShipped) + return "goodsNotShipped"; + + if (value == DeliveryAddressIndicatorEnum.Other) + return "other"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryAddressIndicatorEnum. + /// + public class DeliveryAddressIndicatorEnumJsonConverter : JsonConverter + { + public override DeliveryAddressIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryAddressIndicatorEnum.FromStringOrDefault(value) ?? new DeliveryAddressIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryAddressIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryAddressIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressIndicatorOption { get; private set; } + + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + /// + /// Indicator regarding the delivery address. Allowed values: * `shipToBillingAddress` * `shipToVerifiedAddress` * `shipToNewAddress` * `shipToStore` * `digitalGoods` * `goodsNotShipped` * `other` + [JsonPropertyName("deliveryAddressIndicator")] + public DeliveryAddressIndicatorEnum? DeliveryAddressIndicator { get { return this._DeliveryAddressIndicatorOption; } set { this._DeliveryAddressIndicatorOption = new(value); } } + + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + [JsonConverter(typeof(DeliveryTimeframeEnumJsonConverter))] + public class DeliveryTimeframeEnum : IEnum + { + /// + /// Returns the value of the DeliveryTimeframeEnum. + /// + public string? Value { get; set; } + + /// + /// DeliveryTimeframeEnum.ElectronicDelivery - electronicDelivery + /// + public static readonly DeliveryTimeframeEnum ElectronicDelivery = new("electronicDelivery"); + + /// + /// DeliveryTimeframeEnum.SameDayShipping - sameDayShipping + /// + public static readonly DeliveryTimeframeEnum SameDayShipping = new("sameDayShipping"); + + /// + /// DeliveryTimeframeEnum.OvernightShipping - overnightShipping + /// + public static readonly DeliveryTimeframeEnum OvernightShipping = new("overnightShipping"); + + /// + /// DeliveryTimeframeEnum.TwoOrMoreDaysShipping - twoOrMoreDaysShipping + /// + public static readonly DeliveryTimeframeEnum TwoOrMoreDaysShipping = new("twoOrMoreDaysShipping"); + + private DeliveryTimeframeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DeliveryTimeframeEnum?(string? value) => value == null ? null : new DeliveryTimeframeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DeliveryTimeframeEnum? option) => option?.Value; + + public static bool operator ==(DeliveryTimeframeEnum? left, DeliveryTimeframeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DeliveryTimeframeEnum? left, DeliveryTimeframeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DeliveryTimeframeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DeliveryTimeframeEnum? FromStringOrDefault(string value) + { + return value switch { + "electronicDelivery" => DeliveryTimeframeEnum.ElectronicDelivery, + "sameDayShipping" => DeliveryTimeframeEnum.SameDayShipping, + "overnightShipping" => DeliveryTimeframeEnum.OvernightShipping, + "twoOrMoreDaysShipping" => DeliveryTimeframeEnum.TwoOrMoreDaysShipping, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DeliveryTimeframeEnum? value) + { + if (value == null) + return null; + + if (value == DeliveryTimeframeEnum.ElectronicDelivery) + return "electronicDelivery"; + + if (value == DeliveryTimeframeEnum.SameDayShipping) + return "sameDayShipping"; + + if (value == DeliveryTimeframeEnum.OvernightShipping) + return "overnightShipping"; + + if (value == DeliveryTimeframeEnum.TwoOrMoreDaysShipping) + return "twoOrMoreDaysShipping"; + + return null; + } + + /// + /// JsonConverter for writing DeliveryTimeframeEnum. + /// + public class DeliveryTimeframeEnumJsonConverter : JsonConverter + { + public override DeliveryTimeframeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DeliveryTimeframeEnum.FromStringOrDefault(value) ?? new DeliveryTimeframeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DeliveryTimeframeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DeliveryTimeframeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryTimeframeOption { get; private set; } + + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + /// + /// The estimated delivery time for the shopper to receive the goods. Allowed values: * `electronicDelivery` * `sameDayShipping` * `overnightShipping` * `twoOrMoreDaysShipping` + [JsonPropertyName("deliveryTimeframe")] + public DeliveryTimeframeEnum? DeliveryTimeframe { get { return this._DeliveryTimeframeOption; } set { this._DeliveryTimeframeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressMatchOption { get; private set; } + + /// + /// Whether the chosen delivery address is identical to the billing address. + /// + /// Whether the chosen delivery address is identical to the billing address. + [JsonPropertyName("addressMatch")] + public bool? AddressMatch { get { return this._AddressMatchOption; } set { this._AddressMatchOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryEmailOption { get; private set; } + + /// + /// The delivery email address (for digital goods). + /// + /// The delivery email address (for digital goods). + [JsonPropertyName("deliveryEmail")] + [Obsolete("Deprecated since Adyen Payment API v68. Use `deliveryEmailAddress` instead.")] + public string? DeliveryEmail { get { return this._DeliveryEmailOption; } set { this._DeliveryEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryEmailAddressOption { get; private set; } + + /// + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + /// + /// For Electronic delivery, the email address to which the merchandise was delivered. Maximum length: 254 characters. + [JsonPropertyName("deliveryEmailAddress")] + public string? DeliveryEmailAddress { get { return this._DeliveryEmailAddressOption; } set { this._DeliveryEmailAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("giftCardAmount")] + public Amount? GiftCardAmount { get { return this._GiftCardAmountOption; } set { this._GiftCardAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardCountOption { get; private set; } + + /// + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + /// + /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. + [JsonPropertyName("giftCardCount")] + public int? GiftCardCount { get { return this._GiftCardCountOption; } set { this._GiftCardCountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _GiftCardCurrOption { get; private set; } + + /// + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + /// + /// For prepaid or gift card purchase, [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) three-digit currency code of the gift card, other than those listed in Table A.5 of the EMVCo 3D Secure Protocol and Core Functions Specification. + [JsonPropertyName("giftCardCurr")] + public string? GiftCardCurr { get { return this._GiftCardCurrOption; } set { this._GiftCardCurrOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderDateOption { get; private set; } + + /// + /// For pre-order purchases, the expected date this product will be available to the shopper. + /// + /// For pre-order purchases, the expected date this product will be available to the shopper. + [JsonPropertyName("preOrderDate")] + public DateTimeOffset? PreOrderDate { get { return this._PreOrderDateOption; } set { this._PreOrderDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderPurchaseOption { get; private set; } + + /// + /// Indicator for whether this transaction is for pre-ordering a product. + /// + /// Indicator for whether this transaction is for pre-ordering a product. + [JsonPropertyName("preOrderPurchase")] + public bool? PreOrderPurchase { get { return this._PreOrderPurchaseOption; } set { this._PreOrderPurchaseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PreOrderPurchaseIndOption { get; private set; } + + /// + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + /// + /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. + [JsonPropertyName("preOrderPurchaseInd")] + public string? PreOrderPurchaseInd { get { return this._PreOrderPurchaseIndOption; } set { this._PreOrderPurchaseIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReorderItemsOption { get; private set; } + + /// + /// Indicator for whether the shopper has already purchased the same items in the past. + /// + /// Indicator for whether the shopper has already purchased the same items in the past. + [JsonPropertyName("reorderItems")] + public bool? ReorderItems { get { return this._ReorderItemsOption; } set { this._ReorderItemsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReorderItemsIndOption { get; private set; } + + /// + /// Indicates whether the cardholder is reordering previously purchased merchandise. + /// + /// Indicates whether the cardholder is reordering previously purchased merchandise. + [JsonPropertyName("reorderItemsInd")] + public string? ReorderItemsInd { get { return this._ReorderItemsIndOption; } set { this._ReorderItemsIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShipIndicatorOption { get; private set; } + + /// + /// Indicates shipping method chosen for the transaction. + /// + /// Indicates shipping method chosen for the transaction. + [JsonPropertyName("shipIndicator")] + public string? ShipIndicator { get { return this._ShipIndicatorOption; } set { this._ShipIndicatorOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantRiskIndicator {\n"); + sb.Append(" AddressMatch: ").Append(AddressMatch).Append("\n"); + sb.Append(" DeliveryAddressIndicator: ").Append(DeliveryAddressIndicator).Append("\n"); + sb.Append(" DeliveryEmail: ").Append(DeliveryEmail).Append("\n"); + sb.Append(" DeliveryEmailAddress: ").Append(DeliveryEmailAddress).Append("\n"); + sb.Append(" DeliveryTimeframe: ").Append(DeliveryTimeframe).Append("\n"); + sb.Append(" GiftCardAmount: ").Append(GiftCardAmount).Append("\n"); + sb.Append(" GiftCardCount: ").Append(GiftCardCount).Append("\n"); + sb.Append(" GiftCardCurr: ").Append(GiftCardCurr).Append("\n"); + sb.Append(" PreOrderDate: ").Append(PreOrderDate).Append("\n"); + sb.Append(" PreOrderPurchase: ").Append(PreOrderPurchase).Append("\n"); + sb.Append(" PreOrderPurchaseInd: ").Append(PreOrderPurchaseInd).Append("\n"); + sb.Append(" ReorderItems: ").Append(ReorderItems).Append("\n"); + sb.Append(" ReorderItemsInd: ").Append(ReorderItemsInd).Append("\n"); + sb.Append(" ShipIndicator: ").Append(ShipIndicator).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeliveryEmailAddress (string) maxLength + if (this.DeliveryEmailAddress != null && this.DeliveryEmailAddress.Length > 254) + { + yield return new ValidationResult("Invalid value for DeliveryEmailAddress, length must be less than 254.", new [] { "DeliveryEmailAddress" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantRiskIndicatorJsonConverter : JsonConverter + { + /// + /// The format to use to serialize PreOrderDate. + /// + public static string PreOrderDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantRiskIndicator Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option addressMatch = default; + Option deliveryAddressIndicator = default; + Option deliveryEmail = default; + Option deliveryEmailAddress = default; + Option deliveryTimeframe = default; + Option giftCardAmount = default; + Option giftCardCount = default; + Option giftCardCurr = default; + Option preOrderDate = default; + Option preOrderPurchase = default; + Option preOrderPurchaseInd = default; + Option reorderItems = default; + Option reorderItemsInd = default; + Option shipIndicator = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "addressMatch": + addressMatch = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "deliveryAddressIndicator": + string? deliveryAddressIndicatorRawValue = utf8JsonReader.GetString(); + deliveryAddressIndicator = new Option(MerchantRiskIndicator.DeliveryAddressIndicatorEnum.FromStringOrDefault(deliveryAddressIndicatorRawValue)); + break; + case "deliveryEmail": + deliveryEmail = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryEmailAddress": + deliveryEmailAddress = new Option(utf8JsonReader.GetString()!); + break; + case "deliveryTimeframe": + string? deliveryTimeframeRawValue = utf8JsonReader.GetString(); + deliveryTimeframe = new Option(MerchantRiskIndicator.DeliveryTimeframeEnum.FromStringOrDefault(deliveryTimeframeRawValue)); + break; + case "giftCardAmount": + giftCardAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "giftCardCount": + giftCardCount = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "giftCardCurr": + giftCardCurr = new Option(utf8JsonReader.GetString()!); + break; + case "preOrderDate": + preOrderDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "preOrderPurchase": + preOrderPurchase = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "preOrderPurchaseInd": + preOrderPurchaseInd = new Option(utf8JsonReader.GetString()!); + break; + case "reorderItems": + reorderItems = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "reorderItemsInd": + reorderItemsInd = new Option(utf8JsonReader.GetString()!); + break; + case "shipIndicator": + shipIndicator = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantRiskIndicator(addressMatch, deliveryAddressIndicator, deliveryEmail, deliveryEmailAddress, deliveryTimeframe, giftCardAmount, giftCardCount, giftCardCurr, preOrderDate, preOrderPurchase, preOrderPurchaseInd, reorderItems, reorderItemsInd, shipIndicator); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantRiskIndicator merchantRiskIndicator, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantRiskIndicator, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantRiskIndicator merchantRiskIndicator, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantRiskIndicator._AddressMatchOption.IsSet) + writer.WriteBoolean("addressMatch", merchantRiskIndicator._AddressMatchOption.Value!.Value); + + if (merchantRiskIndicator._DeliveryAddressIndicatorOption.IsSet && merchantRiskIndicator.DeliveryAddressIndicator != null) + { + string? deliveryAddressIndicatorRawValue = MerchantRiskIndicator.DeliveryAddressIndicatorEnum.ToJsonValue(merchantRiskIndicator._DeliveryAddressIndicatorOption.Value!.Value); + writer.WriteString("deliveryAddressIndicator", deliveryAddressIndicatorRawValue); + } + + if (merchantRiskIndicator._DeliveryEmailOption.IsSet) + if (merchantRiskIndicator.DeliveryEmail != null) + writer.WriteString("deliveryEmail", merchantRiskIndicator.DeliveryEmail); + + if (merchantRiskIndicator._DeliveryEmailAddressOption.IsSet) + if (merchantRiskIndicator.DeliveryEmailAddress != null) + writer.WriteString("deliveryEmailAddress", merchantRiskIndicator.DeliveryEmailAddress); + + if (merchantRiskIndicator._DeliveryTimeframeOption.IsSet && merchantRiskIndicator.DeliveryTimeframe != null) + { + string? deliveryTimeframeRawValue = MerchantRiskIndicator.DeliveryTimeframeEnum.ToJsonValue(merchantRiskIndicator._DeliveryTimeframeOption.Value!.Value); + writer.WriteString("deliveryTimeframe", deliveryTimeframeRawValue); + } + + if (merchantRiskIndicator._GiftCardAmountOption.IsSet) + { + writer.WritePropertyName("giftCardAmount"); + JsonSerializer.Serialize(writer, merchantRiskIndicator.GiftCardAmount, jsonSerializerOptions); + } + if (merchantRiskIndicator._GiftCardCountOption.IsSet) + writer.WriteNumber("giftCardCount", merchantRiskIndicator._GiftCardCountOption.Value!.Value); + + if (merchantRiskIndicator._GiftCardCurrOption.IsSet) + if (merchantRiskIndicator.GiftCardCurr != null) + writer.WriteString("giftCardCurr", merchantRiskIndicator.GiftCardCurr); + + if (merchantRiskIndicator._PreOrderDateOption.IsSet) + writer.WriteString("preOrderDate", merchantRiskIndicator._PreOrderDateOption.Value!.Value.ToString(PreOrderDateFormat)); + + if (merchantRiskIndicator._PreOrderPurchaseOption.IsSet) + writer.WriteBoolean("preOrderPurchase", merchantRiskIndicator._PreOrderPurchaseOption.Value!.Value); + + if (merchantRiskIndicator._PreOrderPurchaseIndOption.IsSet) + if (merchantRiskIndicator.PreOrderPurchaseInd != null) + writer.WriteString("preOrderPurchaseInd", merchantRiskIndicator.PreOrderPurchaseInd); + + if (merchantRiskIndicator._ReorderItemsOption.IsSet) + writer.WriteBoolean("reorderItems", merchantRiskIndicator._ReorderItemsOption.Value!.Value); + + if (merchantRiskIndicator._ReorderItemsIndOption.IsSet) + if (merchantRiskIndicator.ReorderItemsInd != null) + writer.WriteString("reorderItemsInd", merchantRiskIndicator.ReorderItemsInd); + + if (merchantRiskIndicator._ShipIndicatorOption.IsSet) + if (merchantRiskIndicator.ShipIndicator != null) + writer.WriteString("shipIndicator", merchantRiskIndicator.ShipIndicator); + } + } +} diff --git a/Adyen/Payment/Models/ModificationResult.cs b/Adyen/Payment/Models/ModificationResult.cs new file mode 100644 index 000000000..b5de58393 --- /dev/null +++ b/Adyen/Payment/Models/ModificationResult.cs @@ -0,0 +1,388 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ModificationResult. + /// + public partial class ModificationResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// Indicates if the modification request has been received for processing. + /// This field contains additional data, which may be returned in a particular modification response. + [JsonConstructor] + public ModificationResult(string pspReference, ResponseEnum response, Option?> additionalData = default) + { + PspReference = pspReference; + Response = response; + _AdditionalDataOption = additionalData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ModificationResult() + { + } + + partial void OnCreated(); + + /// + /// Indicates if the modification request has been received for processing. + /// + /// Indicates if the modification request has been received for processing. + [JsonConverter(typeof(ResponseEnumJsonConverter))] + public class ResponseEnum : IEnum + { + /// + /// Returns the value of the ResponseEnum. + /// + public string? Value { get; set; } + + /// + /// ResponseEnum.CaptureReceived - [capture-received] + /// + public static readonly ResponseEnum CaptureReceived = new("[capture-received]"); + + /// + /// ResponseEnum.CancelReceived - [cancel-received] + /// + public static readonly ResponseEnum CancelReceived = new("[cancel-received]"); + + /// + /// ResponseEnum.RefundReceived - [refund-received] + /// + public static readonly ResponseEnum RefundReceived = new("[refund-received]"); + + /// + /// ResponseEnum.CancelOrRefundReceived - [cancelOrRefund-received] + /// + public static readonly ResponseEnum CancelOrRefundReceived = new("[cancelOrRefund-received]"); + + /// + /// ResponseEnum.AdjustAuthorisationReceived - [adjustAuthorisation-received] + /// + public static readonly ResponseEnum AdjustAuthorisationReceived = new("[adjustAuthorisation-received]"); + + /// + /// ResponseEnum.DonationReceived - [donation-received] + /// + public static readonly ResponseEnum DonationReceived = new("[donation-received]"); + + /// + /// ResponseEnum.TechnicalCancelReceived - [technical-cancel-received] + /// + public static readonly ResponseEnum TechnicalCancelReceived = new("[technical-cancel-received]"); + + /// + /// ResponseEnum.VoidPendingRefundReceived - [voidPendingRefund-received] + /// + public static readonly ResponseEnum VoidPendingRefundReceived = new("[voidPendingRefund-received]"); + + /// + /// ResponseEnum.Authorised - Authorised + /// + public static readonly ResponseEnum Authorised = new("Authorised"); + + private ResponseEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResponseEnum?(string? value) => value == null ? null : new ResponseEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResponseEnum? option) => option?.Value; + + public static bool operator ==(ResponseEnum? left, ResponseEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResponseEnum? left, ResponseEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResponseEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResponseEnum? FromStringOrDefault(string value) + { + return value switch { + "[capture-received]" => ResponseEnum.CaptureReceived, + "[cancel-received]" => ResponseEnum.CancelReceived, + "[refund-received]" => ResponseEnum.RefundReceived, + "[cancelOrRefund-received]" => ResponseEnum.CancelOrRefundReceived, + "[adjustAuthorisation-received]" => ResponseEnum.AdjustAuthorisationReceived, + "[donation-received]" => ResponseEnum.DonationReceived, + "[technical-cancel-received]" => ResponseEnum.TechnicalCancelReceived, + "[voidPendingRefund-received]" => ResponseEnum.VoidPendingRefundReceived, + "Authorised" => ResponseEnum.Authorised, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResponseEnum? value) + { + if (value == null) + return null; + + if (value == ResponseEnum.CaptureReceived) + return "[capture-received]"; + + if (value == ResponseEnum.CancelReceived) + return "[cancel-received]"; + + if (value == ResponseEnum.RefundReceived) + return "[refund-received]"; + + if (value == ResponseEnum.CancelOrRefundReceived) + return "[cancelOrRefund-received]"; + + if (value == ResponseEnum.AdjustAuthorisationReceived) + return "[adjustAuthorisation-received]"; + + if (value == ResponseEnum.DonationReceived) + return "[donation-received]"; + + if (value == ResponseEnum.TechnicalCancelReceived) + return "[technical-cancel-received]"; + + if (value == ResponseEnum.VoidPendingRefundReceived) + return "[voidPendingRefund-received]"; + + if (value == ResponseEnum.Authorised) + return "Authorised"; + + return null; + } + + /// + /// JsonConverter for writing ResponseEnum. + /// + public class ResponseEnumJsonConverter : JsonConverter + { + public override ResponseEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResponseEnum.FromStringOrDefault(value) ?? new ResponseEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResponseEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResponseEnum.ToJsonValue(value)); + } + } + } + + /// + /// Indicates if the modification request has been received for processing. + /// + /// Indicates if the modification request has been received for processing. + [JsonPropertyName("response")] + public ResponseEnum Response { get; set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular modification response. + /// + /// This field contains additional data, which may be returned in a particular modification response. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModificationResult {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModificationResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ModificationResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option response = default; + Option?> additionalData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "response": + string? responseRawValue = utf8JsonReader.GetString(); + response = new Option(ModificationResult.ResponseEnum.FromStringOrDefault(responseRawValue)); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class ModificationResult.", nameof(pspReference)); + + if (!response.IsSet) + throw new ArgumentException("Property is required for class ModificationResult.", nameof(response)); + + return new ModificationResult(pspReference.Value!, response.Value!.Value!, additionalData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModificationResult modificationResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modificationResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ModificationResult modificationResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (modificationResult.PspReference != null) + writer.WriteString("pspReference", modificationResult.PspReference); + + if (modificationResult.Response != null) + { + string? responseRawValue = ModificationResult.ResponseEnum.ToJsonValue(modificationResult.Response); + writer.WriteString("response", responseRawValue); + } + + if (modificationResult._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, modificationResult.AdditionalData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/Name.cs b/Adyen/Payment/Models/Name.cs new file mode 100644 index 000000000..76a74b555 --- /dev/null +++ b/Adyen/Payment/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/Payment/Models/PaymentRequest.cs b/Adyen/Payment/Models/PaymentRequest.cs new file mode 100644 index 000000000..cbecd4fb3 --- /dev/null +++ b/Adyen/Payment/Models/PaymentRequest.cs @@ -0,0 +1,1979 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// PaymentRequest. + /// + public partial class PaymentRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// applicationInfo + /// bankAccount + /// billingAddress + /// browserInfo + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// card + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// dccQuote + /// deliveryAddress + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// The type of the entity the payment is processed for. + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// fundDestination + /// fundSource + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// installments + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// mandate + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// mpiData + /// The two-character country code of the shopper's nationality. + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// platformChargebackLogic + /// recurring + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// secureRemoteCommerceCheckoutData + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// A session ID used to identify a payment session. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The shopper's social security number. + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public PaymentRequest(Amount amount, string merchantAccount, string reference, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option applicationInfo = default, Option bankAccount = default, Option billingAddress = default, Option browserInfo = default, Option captureDelayHours = default, Option card = default, Option dateOfBirth = default, Option dccQuote = default, Option deliveryAddress = default, Option deliveryDate = default, Option deviceFingerprint = default, Option entityType = default, Option fraudOffset = default, Option fundDestination = default, Option fundSource = default, Option fundingSource = default, Option installments = default, Option?> localizedShopperStatement = default, Option mandate = default, Option mcc = default, Option merchantOrderReference = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option mpiData = default, Option nationality = default, Option orderReference = default, Option platformChargebackLogic = default, Option recurring = default, Option recurringProcessingModel = default, Option secureRemoteCommerceCheckoutData = default, Option selectedBrand = default, Option selectedRecurringDetailReference = default, Option sessionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option?> splits = default, Option store = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option totalsGroup = default, Option trustedShopper = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _ApplicationInfoOption = applicationInfo; + _BankAccountOption = bankAccount; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _CaptureDelayHoursOption = captureDelayHours; + _CardOption = card; + _DateOfBirthOption = dateOfBirth; + _DccQuoteOption = dccQuote; + _DeliveryAddressOption = deliveryAddress; + _DeliveryDateOption = deliveryDate; + _DeviceFingerprintOption = deviceFingerprint; + _EntityTypeOption = entityType; + _FraudOffsetOption = fraudOffset; + _FundDestinationOption = fundDestination; + _FundSourceOption = fundSource; + _FundingSourceOption = fundingSource; + _InstallmentsOption = installments; + _LocalizedShopperStatementOption = localizedShopperStatement; + _MandateOption = mandate; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _MpiDataOption = mpiData; + _NationalityOption = nationality; + _OrderReferenceOption = orderReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _RecurringOption = recurring; + _RecurringProcessingModelOption = recurringProcessingModel; + _SecureRemoteCommerceCheckoutDataOption = secureRemoteCommerceCheckoutData; + _SelectedBrandOption = selectedBrand; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _SessionIdOption = sessionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitsOption = splits; + _StoreOption = store; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TotalsGroupOption = totalsGroup; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of the entity the payment is processed for. + /// + /// The type of the entity the payment is processed for. + [JsonConverter(typeof(EntityTypeEnumJsonConverter))] + public class EntityTypeEnum : IEnum + { + /// + /// Returns the value of the EntityTypeEnum. + /// + public string? Value { get; set; } + + /// + /// EntityTypeEnum.NaturalPerson - NaturalPerson + /// + public static readonly EntityTypeEnum NaturalPerson = new("NaturalPerson"); + + /// + /// EntityTypeEnum.CompanyName - CompanyName + /// + public static readonly EntityTypeEnum CompanyName = new("CompanyName"); + + private EntityTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EntityTypeEnum?(string? value) => value == null ? null : new EntityTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EntityTypeEnum? option) => option?.Value; + + public static bool operator ==(EntityTypeEnum? left, EntityTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EntityTypeEnum? left, EntityTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EntityTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EntityTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "NaturalPerson" => EntityTypeEnum.NaturalPerson, + "CompanyName" => EntityTypeEnum.CompanyName, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EntityTypeEnum? value) + { + if (value == null) + return null; + + if (value == EntityTypeEnum.NaturalPerson) + return "NaturalPerson"; + + if (value == EntityTypeEnum.CompanyName) + return "CompanyName"; + + return null; + } + + /// + /// JsonConverter for writing EntityTypeEnum. + /// + public class EntityTypeEnumJsonConverter : JsonConverter + { + public override EntityTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EntityTypeEnum.FromStringOrDefault(value) ?? new EntityTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EntityTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EntityTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityTypeOption { get; private set; } + + /// + /// The type of the entity the payment is processed for. + /// + /// The type of the entity the payment is processed for. + [JsonPropertyName("entityType")] + public EntityTypeEnum? EntityType { get { return this._EntityTypeOption; } set { this._EntityTypeOption = new(value); } } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonConverter(typeof(FundingSourceEnumJsonConverter))] + public class FundingSourceEnum : IEnum + { + /// + /// Returns the value of the FundingSourceEnum. + /// + public string? Value { get; set; } + + /// + /// FundingSourceEnum.Credit - credit + /// + public static readonly FundingSourceEnum Credit = new("credit"); + + /// + /// FundingSourceEnum.Debit - debit + /// + public static readonly FundingSourceEnum Debit = new("debit"); + + private FundingSourceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FundingSourceEnum?(string? value) => value == null ? null : new FundingSourceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FundingSourceEnum? option) => option?.Value; + + public static bool operator ==(FundingSourceEnum? left, FundingSourceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FundingSourceEnum? left, FundingSourceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FundingSourceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FundingSourceEnum? FromStringOrDefault(string value) + { + return value switch { + "credit" => FundingSourceEnum.Credit, + "debit" => FundingSourceEnum.Debit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FundingSourceEnum? value) + { + if (value == null) + return null; + + if (value == FundingSourceEnum.Credit) + return "credit"; + + if (value == FundingSourceEnum.Debit) + return "debit"; + + return null; + } + + /// + /// JsonConverter for writing FundingSourceEnum. + /// + public class FundingSourceEnumJsonConverter : JsonConverter + { + public override FundingSourceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FundingSourceEnum.FromStringOrDefault(value) ?? new FundingSourceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FundingSourceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FundingSourceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + /// + /// The funding source that should be used when multiple sources are available. For Brazilian combo cards, by default the funding source is credit. To use debit, set this value to **debit**. + [JsonPropertyName("fundingSource")] + public FundingSourceEnum? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccount? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccQuoteOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccQuote")] + public ForexQuote? DccQuote { get { return this._DccQuoteOption; } set { this._DccQuoteOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryDateOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliveryDate")] + public DateTimeOffset? DeliveryDate { get { return this._DeliveryDateOption; } set { this._DeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundDestinationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundDestination")] + public FundDestination? FundDestination { get { return this._FundDestinationOption; } set { this._FundDestinationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundSource")] + public FundSource? FundSource { get { return this._FundSourceOption; } set { this._FundSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("installments")] + public Installments? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalizedShopperStatementOption { get; private set; } + + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + [JsonPropertyName("localizedShopperStatement")] + public Dictionary? LocalizedShopperStatement { get { return this._LocalizedShopperStatementOption; } set { this._LocalizedShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mandate")] + public Mandate? Mandate { get { return this._MandateOption; } set { this._MandateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NationalityOption { get; private set; } + + /// + /// The two-character country code of the shopper's nationality. + /// + /// The two-character country code of the shopper's nationality. + [JsonPropertyName("nationality")] + public string? Nationality { get { return this._NationalityOption; } set { this._NationalityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderReferenceOption { get; private set; } + + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + [JsonPropertyName("orderReference")] + public string? OrderReference { get { return this._OrderReferenceOption; } set { this._OrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SecureRemoteCommerceCheckoutDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("secureRemoteCommerceCheckoutData")] + public SecureRemoteCommerceCheckoutData? SecureRemoteCommerceCheckoutData { get { return this._SecureRemoteCommerceCheckoutDataOption; } set { this._SecureRemoteCommerceCheckoutDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionIdOption { get; private set; } + + /// + /// A session ID used to identify a payment session. + /// + /// A session ID used to identify a payment session. + [JsonPropertyName("sessionId")] + public string? SessionId { get { return this._SessionIdOption; } set { this._SessionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalsGroupOption { get; private set; } + + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + [JsonPropertyName("totalsGroup")] + public string? TotalsGroup { get { return this._TotalsGroupOption; } set { this._TotalsGroupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DccQuote: ").Append(DccQuote).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeliveryDate: ").Append(DeliveryDate).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" FundDestination: ").Append(FundDestination).Append("\n"); + sb.Append(" FundSource: ").Append(FundSource).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" LocalizedShopperStatement: ").Append(LocalizedShopperStatement).Append("\n"); + sb.Append(" Mandate: ").Append(Mandate).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" Nationality: ").Append(Nationality).Append("\n"); + sb.Append(" OrderReference: ").Append(OrderReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" SecureRemoteCommerceCheckoutData: ").Append(SecureRemoteCommerceCheckoutData).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" SessionId: ").Append(SessionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TotalsGroup: ").Append(TotalsGroup).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Nationality (string) maxLength + if (this.Nationality != null && this.Nationality.Length > 2) + { + yield return new ValidationResult("Invalid value for Nationality, length must be less than 2.", new [] { "Nationality" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + // TotalsGroup (string) maxLength + if (this.TotalsGroup != null && this.TotalsGroup.Length > 16) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be less than 16.", new [] { "TotalsGroup" }); + } + + // TotalsGroup (string) minLength + if (this.TotalsGroup != null && this.TotalsGroup.Length < 1) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be greater than 1.", new [] { "TotalsGroup" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliveryDate. + /// + public static string DeliveryDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option applicationInfo = default; + Option bankAccount = default; + Option billingAddress = default; + Option browserInfo = default; + Option captureDelayHours = default; + Option card = default; + Option dateOfBirth = default; + Option dccQuote = default; + Option deliveryAddress = default; + Option deliveryDate = default; + Option deviceFingerprint = default; + Option entityType = default; + Option fraudOffset = default; + Option fundDestination = default; + Option fundSource = default; + Option fundingSource = default; + Option installments = default; + Option?> localizedShopperStatement = default; + Option mandate = default; + Option mcc = default; + Option merchantOrderReference = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option mpiData = default; + Option nationality = default; + Option orderReference = default; + Option platformChargebackLogic = default; + Option recurring = default; + Option recurringProcessingModel = default; + Option secureRemoteCommerceCheckoutData = default; + Option selectedBrand = default; + Option selectedRecurringDetailReference = default; + Option sessionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option?> splits = default; + Option store = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option totalsGroup = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dccQuote": + dccQuote = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryDate": + deliveryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + entityType = new Option(PaymentRequest.EntityTypeEnum.FromStringOrDefault(entityTypeRawValue)); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "fundDestination": + fundDestination = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundSource": + fundSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fundingSource": + string? fundingSourceRawValue = utf8JsonReader.GetString(); + fundingSource = new Option(PaymentRequest.FundingSourceEnum.FromStringOrDefault(fundingSourceRawValue)); + break; + case "installments": + installments = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localizedShopperStatement": + localizedShopperStatement = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mandate": + mandate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "nationality": + nationality = new Option(utf8JsonReader.GetString()!); + break; + case "orderReference": + orderReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentRequest.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "secureRemoteCommerceCheckoutData": + secureRemoteCommerceCheckoutData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "sessionId": + sessionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PaymentRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "totalsGroup": + totalsGroup = new Option(utf8JsonReader.GetString()!); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest.", nameof(reference)); + + return new PaymentRequest(amount.Value!, merchantAccount.Value!, reference.Value!, accountInfo, additionalAmount, additionalData, applicationInfo, bankAccount, billingAddress, browserInfo, captureDelayHours, card, dateOfBirth, dccQuote, deliveryAddress, deliveryDate, deviceFingerprint, entityType, fraudOffset, fundDestination, fundSource, fundingSource, installments, localizedShopperStatement, mandate, mcc, merchantOrderReference, merchantRiskIndicator, metadata, mpiData, nationality, orderReference, platformChargebackLogic, recurring, recurringProcessingModel, secureRemoteCommerceCheckoutData, selectedBrand, selectedRecurringDetailReference, sessionId, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, splits, store, telephoneNumber, threeDS2RequestData, threeDSAuthenticationOnly, totalsGroup, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRequest paymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRequest paymentRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRequest.Amount, jsonSerializerOptions); + if (paymentRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRequest.MerchantAccount); + + if (paymentRequest.Reference != null) + writer.WriteString("reference", paymentRequest.Reference); + + if (paymentRequest._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, paymentRequest.AccountInfo, jsonSerializerOptions); + } + if (paymentRequest._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, paymentRequest.AdditionalAmount, jsonSerializerOptions); + } + if (paymentRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentRequest.AdditionalData, jsonSerializerOptions); + } + if (paymentRequest._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentRequest.ApplicationInfo, jsonSerializerOptions); + } + if (paymentRequest._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, paymentRequest.BankAccount, jsonSerializerOptions); + } + if (paymentRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentRequest.BillingAddress, jsonSerializerOptions); + } + if (paymentRequest._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, paymentRequest.BrowserInfo, jsonSerializerOptions); + } + if (paymentRequest._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentRequest._CaptureDelayHoursOption.Value!.Value); + + if (paymentRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, paymentRequest.Card, jsonSerializerOptions); + } + if (paymentRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentRequest._DccQuoteOption.IsSet) + { + writer.WritePropertyName("dccQuote"); + JsonSerializer.Serialize(writer, paymentRequest.DccQuote, jsonSerializerOptions); + } + if (paymentRequest._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentRequest.DeliveryAddress, jsonSerializerOptions); + } + if (paymentRequest._DeliveryDateOption.IsSet) + writer.WriteString("deliveryDate", paymentRequest._DeliveryDateOption.Value!.Value.ToString(DeliveryDateFormat)); + + if (paymentRequest._DeviceFingerprintOption.IsSet) + if (paymentRequest.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", paymentRequest.DeviceFingerprint); + + if (paymentRequest._EntityTypeOption.IsSet && paymentRequest.EntityType != null) + { + string? entityTypeRawValue = PaymentRequest.EntityTypeEnum.ToJsonValue(paymentRequest._EntityTypeOption.Value!.Value); + writer.WriteString("entityType", entityTypeRawValue); + } + + if (paymentRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", paymentRequest._FraudOffsetOption.Value!.Value); + + if (paymentRequest._FundDestinationOption.IsSet) + { + writer.WritePropertyName("fundDestination"); + JsonSerializer.Serialize(writer, paymentRequest.FundDestination, jsonSerializerOptions); + } + if (paymentRequest._FundSourceOption.IsSet) + { + writer.WritePropertyName("fundSource"); + JsonSerializer.Serialize(writer, paymentRequest.FundSource, jsonSerializerOptions); + } + if (paymentRequest._FundingSourceOption.IsSet && paymentRequest.FundingSource != null) + { + string? fundingSourceRawValue = PaymentRequest.FundingSourceEnum.ToJsonValue(paymentRequest._FundingSourceOption.Value!.Value); + writer.WriteString("fundingSource", fundingSourceRawValue); + } + + if (paymentRequest._InstallmentsOption.IsSet) + { + writer.WritePropertyName("installments"); + JsonSerializer.Serialize(writer, paymentRequest.Installments, jsonSerializerOptions); + } + if (paymentRequest._LocalizedShopperStatementOption.IsSet) + { + writer.WritePropertyName("localizedShopperStatement"); + JsonSerializer.Serialize(writer, paymentRequest.LocalizedShopperStatement, jsonSerializerOptions); + } + if (paymentRequest._MandateOption.IsSet) + { + writer.WritePropertyName("mandate"); + JsonSerializer.Serialize(writer, paymentRequest.Mandate, jsonSerializerOptions); + } + if (paymentRequest._MccOption.IsSet) + if (paymentRequest.Mcc != null) + writer.WriteString("mcc", paymentRequest.Mcc); + + if (paymentRequest._MerchantOrderReferenceOption.IsSet) + if (paymentRequest.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentRequest.MerchantOrderReference); + + if (paymentRequest._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, paymentRequest.MerchantRiskIndicator, jsonSerializerOptions); + } + if (paymentRequest._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentRequest.Metadata, jsonSerializerOptions); + } + if (paymentRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, paymentRequest.MpiData, jsonSerializerOptions); + } + if (paymentRequest._NationalityOption.IsSet) + if (paymentRequest.Nationality != null) + writer.WriteString("nationality", paymentRequest.Nationality); + + if (paymentRequest._OrderReferenceOption.IsSet) + if (paymentRequest.OrderReference != null) + writer.WriteString("orderReference", paymentRequest.OrderReference); + + if (paymentRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, paymentRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (paymentRequest._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, paymentRequest.Recurring, jsonSerializerOptions); + } + if (paymentRequest._RecurringProcessingModelOption.IsSet && paymentRequest.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentRequest.RecurringProcessingModelEnum.ToJsonValue(paymentRequest._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentRequest._SecureRemoteCommerceCheckoutDataOption.IsSet) + { + writer.WritePropertyName("secureRemoteCommerceCheckoutData"); + JsonSerializer.Serialize(writer, paymentRequest.SecureRemoteCommerceCheckoutData, jsonSerializerOptions); + } + if (paymentRequest._SelectedBrandOption.IsSet) + if (paymentRequest.SelectedBrand != null) + writer.WriteString("selectedBrand", paymentRequest.SelectedBrand); + + if (paymentRequest._SelectedRecurringDetailReferenceOption.IsSet) + if (paymentRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", paymentRequest.SelectedRecurringDetailReference); + + if (paymentRequest._SessionIdOption.IsSet) + if (paymentRequest.SessionId != null) + writer.WriteString("sessionId", paymentRequest.SessionId); + + if (paymentRequest._ShopperEmailOption.IsSet) + if (paymentRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentRequest.ShopperEmail); + + if (paymentRequest._ShopperIPOption.IsSet) + if (paymentRequest.ShopperIP != null) + writer.WriteString("shopperIP", paymentRequest.ShopperIP); + + if (paymentRequest._ShopperInteractionOption.IsSet && paymentRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PaymentRequest.ShopperInteractionEnum.ToJsonValue(paymentRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (paymentRequest._ShopperLocaleOption.IsSet) + if (paymentRequest.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentRequest.ShopperLocale); + + if (paymentRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentRequest.ShopperName, jsonSerializerOptions); + } + if (paymentRequest._ShopperReferenceOption.IsSet) + if (paymentRequest.ShopperReference != null) + writer.WriteString("shopperReference", paymentRequest.ShopperReference); + + if (paymentRequest._ShopperStatementOption.IsSet) + if (paymentRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentRequest.ShopperStatement); + + if (paymentRequest._SocialSecurityNumberOption.IsSet) + if (paymentRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentRequest.SocialSecurityNumber); + + if (paymentRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRequest.Splits, jsonSerializerOptions); + } + if (paymentRequest._StoreOption.IsSet) + if (paymentRequest.Store != null) + writer.WriteString("store", paymentRequest.Store); + + if (paymentRequest._TelephoneNumberOption.IsSet) + if (paymentRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentRequest.TelephoneNumber); + + if (paymentRequest._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentRequest.ThreeDS2RequestData, jsonSerializerOptions); + } + if (paymentRequest._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", paymentRequest._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (paymentRequest._TotalsGroupOption.IsSet) + if (paymentRequest.TotalsGroup != null) + writer.WriteString("totalsGroup", paymentRequest.TotalsGroup); + + if (paymentRequest._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", paymentRequest._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/PaymentRequest3d.cs b/Adyen/Payment/Models/PaymentRequest3d.cs new file mode 100644 index 000000000..c03e79dde --- /dev/null +++ b/Adyen/Payment/Models/PaymentRequest3d.cs @@ -0,0 +1,1538 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// PaymentRequest3d. + /// + public partial class PaymentRequest3d : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The payment session identifier returned by the card issuer. + /// The merchant account identifier, with which you want to process the transaction. + /// Payment authorisation response returned by the card issuer. The `paResponse` field holds the PaRes value received from the card issuer. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// amount + /// applicationInfo + /// billingAddress + /// browserInfo + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// dccQuote + /// deliveryAddress + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// installments + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// recurring + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// A session ID used to identify a payment session. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The shopper's social security number. + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public PaymentRequest3d(string md, string merchantAccount, string paResponse, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option amount = default, Option applicationInfo = default, Option billingAddress = default, Option browserInfo = default, Option captureDelayHours = default, Option dateOfBirth = default, Option dccQuote = default, Option deliveryAddress = default, Option deliveryDate = default, Option deviceFingerprint = default, Option fraudOffset = default, Option installments = default, Option?> localizedShopperStatement = default, Option mcc = default, Option merchantOrderReference = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option orderReference = default, Option recurring = default, Option recurringProcessingModel = default, Option reference = default, Option selectedBrand = default, Option selectedRecurringDetailReference = default, Option sessionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option?> splits = default, Option store = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDSAuthenticationOnly = default, Option totalsGroup = default, Option trustedShopper = default) + { + Md = md; + MerchantAccount = merchantAccount; + PaResponse = paResponse; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _AmountOption = amount; + _ApplicationInfoOption = applicationInfo; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _CaptureDelayHoursOption = captureDelayHours; + _DateOfBirthOption = dateOfBirth; + _DccQuoteOption = dccQuote; + _DeliveryAddressOption = deliveryAddress; + _DeliveryDateOption = deliveryDate; + _DeviceFingerprintOption = deviceFingerprint; + _FraudOffsetOption = fraudOffset; + _InstallmentsOption = installments; + _LocalizedShopperStatementOption = localizedShopperStatement; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _OrderReferenceOption = orderReference; + _RecurringOption = recurring; + _RecurringProcessingModelOption = recurringProcessingModel; + _ReferenceOption = reference; + _SelectedBrandOption = selectedBrand; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _SessionIdOption = sessionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitsOption = splits; + _StoreOption = store; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TotalsGroupOption = totalsGroup; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRequest3d() + { + } + + partial void OnCreated(); + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// The payment session identifier returned by the card issuer. + /// + /// The payment session identifier returned by the card issuer. + [JsonPropertyName("md")] + public string Md { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// Payment authorisation response returned by the card issuer. The `paResponse` field holds the PaRes value received from the card issuer. + /// + /// Payment authorisation response returned by the card issuer. The `paResponse` field holds the PaRes value received from the card issuer. + [JsonPropertyName("paResponse")] + public string PaResponse { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccQuoteOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccQuote")] + public ForexQuote? DccQuote { get { return this._DccQuoteOption; } set { this._DccQuoteOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryDateOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliveryDate")] + public DateTimeOffset? DeliveryDate { get { return this._DeliveryDateOption; } set { this._DeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("installments")] + public Installments? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalizedShopperStatementOption { get; private set; } + + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + [JsonPropertyName("localizedShopperStatement")] + public Dictionary? LocalizedShopperStatement { get { return this._LocalizedShopperStatementOption; } set { this._LocalizedShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderReferenceOption { get; private set; } + + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + [JsonPropertyName("orderReference")] + public string? OrderReference { get { return this._OrderReferenceOption; } set { this._OrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionIdOption { get; private set; } + + /// + /// A session ID used to identify a payment session. + /// + /// A session ID used to identify a payment session. + [JsonPropertyName("sessionId")] + public string? SessionId { get { return this._SessionIdOption; } set { this._SessionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalsGroupOption { get; private set; } + + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + [JsonPropertyName("totalsGroup")] + public string? TotalsGroup { get { return this._TotalsGroupOption; } set { this._TotalsGroupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRequest3d {\n"); + sb.Append(" Md: ").Append(Md).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaResponse: ").Append(PaResponse).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DccQuote: ").Append(DccQuote).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeliveryDate: ").Append(DeliveryDate).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" LocalizedShopperStatement: ").Append(LocalizedShopperStatement).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" OrderReference: ").Append(OrderReference).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" SessionId: ").Append(SessionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TotalsGroup: ").Append(TotalsGroup).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + // TotalsGroup (string) maxLength + if (this.TotalsGroup != null && this.TotalsGroup.Length > 16) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be less than 16.", new [] { "TotalsGroup" }); + } + + // TotalsGroup (string) minLength + if (this.TotalsGroup != null && this.TotalsGroup.Length < 1) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be greater than 1.", new [] { "TotalsGroup" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRequest3dJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliveryDate. + /// + public static string DeliveryDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRequest3d Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option md = default; + Option merchantAccount = default; + Option paResponse = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option amount = default; + Option applicationInfo = default; + Option billingAddress = default; + Option browserInfo = default; + Option captureDelayHours = default; + Option dateOfBirth = default; + Option dccQuote = default; + Option deliveryAddress = default; + Option deliveryDate = default; + Option deviceFingerprint = default; + Option fraudOffset = default; + Option installments = default; + Option?> localizedShopperStatement = default; + Option mcc = default; + Option merchantOrderReference = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option orderReference = default; + Option recurring = default; + Option recurringProcessingModel = default; + Option reference = default; + Option selectedBrand = default; + Option selectedRecurringDetailReference = default; + Option sessionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option?> splits = default; + Option store = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDSAuthenticationOnly = default; + Option totalsGroup = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "md": + md = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paResponse": + paResponse = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dccQuote": + dccQuote = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryDate": + deliveryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "installments": + installments = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localizedShopperStatement": + localizedShopperStatement = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderReference": + orderReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentRequest3d.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "sessionId": + sessionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PaymentRequest3d.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "totalsGroup": + totalsGroup = new Option(utf8JsonReader.GetString()!); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!md.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3d.", nameof(md)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3d.", nameof(merchantAccount)); + + if (!paResponse.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3d.", nameof(paResponse)); + + return new PaymentRequest3d(md.Value!, merchantAccount.Value!, paResponse.Value!, accountInfo, additionalAmount, additionalData, amount, applicationInfo, billingAddress, browserInfo, captureDelayHours, dateOfBirth, dccQuote, deliveryAddress, deliveryDate, deviceFingerprint, fraudOffset, installments, localizedShopperStatement, mcc, merchantOrderReference, merchantRiskIndicator, metadata, orderReference, recurring, recurringProcessingModel, reference, selectedBrand, selectedRecurringDetailReference, sessionId, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, splits, store, telephoneNumber, threeDS2RequestData, threeDSAuthenticationOnly, totalsGroup, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRequest3d paymentRequest3d, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRequest3d, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRequest3d paymentRequest3d, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentRequest3d.Md != null) + writer.WriteString("md", paymentRequest3d.Md); + + if (paymentRequest3d.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRequest3d.MerchantAccount); + + if (paymentRequest3d.PaResponse != null) + writer.WriteString("paResponse", paymentRequest3d.PaResponse); + + if (paymentRequest3d._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, paymentRequest3d.AccountInfo, jsonSerializerOptions); + } + if (paymentRequest3d._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, paymentRequest3d.AdditionalAmount, jsonSerializerOptions); + } + if (paymentRequest3d._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentRequest3d.AdditionalData, jsonSerializerOptions); + } + if (paymentRequest3d._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRequest3d.Amount, jsonSerializerOptions); + } + if (paymentRequest3d._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentRequest3d.ApplicationInfo, jsonSerializerOptions); + } + if (paymentRequest3d._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentRequest3d.BillingAddress, jsonSerializerOptions); + } + if (paymentRequest3d._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, paymentRequest3d.BrowserInfo, jsonSerializerOptions); + } + if (paymentRequest3d._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentRequest3d._CaptureDelayHoursOption.Value!.Value); + + if (paymentRequest3d._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentRequest3d._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentRequest3d._DccQuoteOption.IsSet) + { + writer.WritePropertyName("dccQuote"); + JsonSerializer.Serialize(writer, paymentRequest3d.DccQuote, jsonSerializerOptions); + } + if (paymentRequest3d._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentRequest3d.DeliveryAddress, jsonSerializerOptions); + } + if (paymentRequest3d._DeliveryDateOption.IsSet) + writer.WriteString("deliveryDate", paymentRequest3d._DeliveryDateOption.Value!.Value.ToString(DeliveryDateFormat)); + + if (paymentRequest3d._DeviceFingerprintOption.IsSet) + if (paymentRequest3d.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", paymentRequest3d.DeviceFingerprint); + + if (paymentRequest3d._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", paymentRequest3d._FraudOffsetOption.Value!.Value); + + if (paymentRequest3d._InstallmentsOption.IsSet) + { + writer.WritePropertyName("installments"); + JsonSerializer.Serialize(writer, paymentRequest3d.Installments, jsonSerializerOptions); + } + if (paymentRequest3d._LocalizedShopperStatementOption.IsSet) + { + writer.WritePropertyName("localizedShopperStatement"); + JsonSerializer.Serialize(writer, paymentRequest3d.LocalizedShopperStatement, jsonSerializerOptions); + } + if (paymentRequest3d._MccOption.IsSet) + if (paymentRequest3d.Mcc != null) + writer.WriteString("mcc", paymentRequest3d.Mcc); + + if (paymentRequest3d._MerchantOrderReferenceOption.IsSet) + if (paymentRequest3d.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentRequest3d.MerchantOrderReference); + + if (paymentRequest3d._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, paymentRequest3d.MerchantRiskIndicator, jsonSerializerOptions); + } + if (paymentRequest3d._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentRequest3d.Metadata, jsonSerializerOptions); + } + if (paymentRequest3d._OrderReferenceOption.IsSet) + if (paymentRequest3d.OrderReference != null) + writer.WriteString("orderReference", paymentRequest3d.OrderReference); + + if (paymentRequest3d._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, paymentRequest3d.Recurring, jsonSerializerOptions); + } + if (paymentRequest3d._RecurringProcessingModelOption.IsSet && paymentRequest3d.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentRequest3d.RecurringProcessingModelEnum.ToJsonValue(paymentRequest3d._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentRequest3d._ReferenceOption.IsSet) + if (paymentRequest3d.Reference != null) + writer.WriteString("reference", paymentRequest3d.Reference); + + if (paymentRequest3d._SelectedBrandOption.IsSet) + if (paymentRequest3d.SelectedBrand != null) + writer.WriteString("selectedBrand", paymentRequest3d.SelectedBrand); + + if (paymentRequest3d._SelectedRecurringDetailReferenceOption.IsSet) + if (paymentRequest3d.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", paymentRequest3d.SelectedRecurringDetailReference); + + if (paymentRequest3d._SessionIdOption.IsSet) + if (paymentRequest3d.SessionId != null) + writer.WriteString("sessionId", paymentRequest3d.SessionId); + + if (paymentRequest3d._ShopperEmailOption.IsSet) + if (paymentRequest3d.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentRequest3d.ShopperEmail); + + if (paymentRequest3d._ShopperIPOption.IsSet) + if (paymentRequest3d.ShopperIP != null) + writer.WriteString("shopperIP", paymentRequest3d.ShopperIP); + + if (paymentRequest3d._ShopperInteractionOption.IsSet && paymentRequest3d.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PaymentRequest3d.ShopperInteractionEnum.ToJsonValue(paymentRequest3d._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (paymentRequest3d._ShopperLocaleOption.IsSet) + if (paymentRequest3d.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentRequest3d.ShopperLocale); + + if (paymentRequest3d._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentRequest3d.ShopperName, jsonSerializerOptions); + } + if (paymentRequest3d._ShopperReferenceOption.IsSet) + if (paymentRequest3d.ShopperReference != null) + writer.WriteString("shopperReference", paymentRequest3d.ShopperReference); + + if (paymentRequest3d._ShopperStatementOption.IsSet) + if (paymentRequest3d.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentRequest3d.ShopperStatement); + + if (paymentRequest3d._SocialSecurityNumberOption.IsSet) + if (paymentRequest3d.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentRequest3d.SocialSecurityNumber); + + if (paymentRequest3d._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRequest3d.Splits, jsonSerializerOptions); + } + if (paymentRequest3d._StoreOption.IsSet) + if (paymentRequest3d.Store != null) + writer.WriteString("store", paymentRequest3d.Store); + + if (paymentRequest3d._TelephoneNumberOption.IsSet) + if (paymentRequest3d.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentRequest3d.TelephoneNumber); + + if (paymentRequest3d._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentRequest3d.ThreeDS2RequestData, jsonSerializerOptions); + } + if (paymentRequest3d._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", paymentRequest3d._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (paymentRequest3d._TotalsGroupOption.IsSet) + if (paymentRequest3d.TotalsGroup != null) + writer.WriteString("totalsGroup", paymentRequest3d.TotalsGroup); + + if (paymentRequest3d._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", paymentRequest3d._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/PaymentRequest3ds2.cs b/Adyen/Payment/Models/PaymentRequest3ds2.cs new file mode 100644 index 000000000..e76706425 --- /dev/null +++ b/Adyen/Payment/Models/PaymentRequest3ds2.cs @@ -0,0 +1,1536 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// PaymentRequest3ds2. + /// + public partial class PaymentRequest3ds2 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// accountInfo + /// additionalAmount + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// applicationInfo + /// billingAddress + /// browserInfo + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// dccQuote + /// deliveryAddress + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// installments + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// merchantRiskIndicator + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// recurring + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// A session ID used to identify a payment session. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// The shopper's social security number. + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// threeDS2RequestData + /// threeDS2Result + /// The ThreeDS2Token that was returned in the /authorise call. + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. (default to false) + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// Set to true if the payment should be routed to a trusted MID. + [JsonConstructor] + public PaymentRequest3ds2(Amount amount, string merchantAccount, string reference, Option accountInfo = default, Option additionalAmount = default, Option?> additionalData = default, Option applicationInfo = default, Option billingAddress = default, Option browserInfo = default, Option captureDelayHours = default, Option dateOfBirth = default, Option dccQuote = default, Option deliveryAddress = default, Option deliveryDate = default, Option deviceFingerprint = default, Option fraudOffset = default, Option installments = default, Option?> localizedShopperStatement = default, Option mcc = default, Option merchantOrderReference = default, Option merchantRiskIndicator = default, Option?> metadata = default, Option orderReference = default, Option recurring = default, Option recurringProcessingModel = default, Option selectedBrand = default, Option selectedRecurringDetailReference = default, Option sessionId = default, Option shopperEmail = default, Option shopperIP = default, Option shopperInteraction = default, Option shopperLocale = default, Option shopperName = default, Option shopperReference = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option?> splits = default, Option store = default, Option telephoneNumber = default, Option threeDS2RequestData = default, Option threeDS2Result = default, Option threeDS2Token = default, Option threeDSAuthenticationOnly = default, Option totalsGroup = default, Option trustedShopper = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + _AccountInfoOption = accountInfo; + _AdditionalAmountOption = additionalAmount; + _AdditionalDataOption = additionalData; + _ApplicationInfoOption = applicationInfo; + _BillingAddressOption = billingAddress; + _BrowserInfoOption = browserInfo; + _CaptureDelayHoursOption = captureDelayHours; + _DateOfBirthOption = dateOfBirth; + _DccQuoteOption = dccQuote; + _DeliveryAddressOption = deliveryAddress; + _DeliveryDateOption = deliveryDate; + _DeviceFingerprintOption = deviceFingerprint; + _FraudOffsetOption = fraudOffset; + _InstallmentsOption = installments; + _LocalizedShopperStatementOption = localizedShopperStatement; + _MccOption = mcc; + _MerchantOrderReferenceOption = merchantOrderReference; + _MerchantRiskIndicatorOption = merchantRiskIndicator; + _MetadataOption = metadata; + _OrderReferenceOption = orderReference; + _RecurringOption = recurring; + _RecurringProcessingModelOption = recurringProcessingModel; + _SelectedBrandOption = selectedBrand; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _SessionIdOption = sessionId; + _ShopperEmailOption = shopperEmail; + _ShopperIPOption = shopperIP; + _ShopperInteractionOption = shopperInteraction; + _ShopperLocaleOption = shopperLocale; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _SplitsOption = splits; + _StoreOption = store; + _TelephoneNumberOption = telephoneNumber; + _ThreeDS2RequestDataOption = threeDS2RequestData; + _ThreeDS2ResultOption = threeDS2Result; + _ThreeDS2TokenOption = threeDS2Token; + _ThreeDSAuthenticationOnlyOption = threeDSAuthenticationOnly; + _TotalsGroupOption = totalsGroup; + _TrustedShopperOption = trustedShopper; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentRequest3ds2() + { + } + + partial void OnCreated(); + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + /// + /// Defines a recurring payment type. Required when creating a token to store payment details or using stored payment details. Allowed values: * `Subscription` – A transaction for a fixed or variable amount, which follows a fixed schedule. * `CardOnFile` – With a card-on-file (CoF) transaction, card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. Any subscription not following a fixed schedule is also considered a card-on-file transaction. * `UnscheduledCardOnFile` – An unscheduled card-on-file (UCoF) transaction is a transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountInfo")] + public AccountInfo? AccountInfo { get { return this._AccountInfoOption; } set { this._AccountInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalAmount")] + public Amount? AdditionalAmount { get { return this._AdditionalAmountOption; } set { this._AdditionalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular payment request. The `additionalData` object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ApplicationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("applicationInfo")] + public ApplicationInfo? ApplicationInfo { get { return this._ApplicationInfoOption; } set { this._ApplicationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BrowserInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("browserInfo")] + public BrowserInfo? BrowserInfo { get { return this._BrowserInfoOption; } set { this._BrowserInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureDelayHoursOption { get; private set; } + + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + /// + /// The delay between the authorisation and scheduled auto-capture, specified in hours. + [JsonPropertyName("captureDelayHours")] + public int? CaptureDelayHours { get { return this._CaptureDelayHoursOption; } set { this._CaptureDelayHoursOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + /// + /// The shopper's date of birth. Format [ISO-8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DD + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccQuoteOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccQuote")] + public ForexQuote? DccQuote { get { return this._DccQuoteOption; } set { this._DccQuoteOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deliveryAddress")] + public Address? DeliveryAddress { get { return this._DeliveryAddressOption; } set { this._DeliveryAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeliveryDateOption { get; private set; } + + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + /// + /// The date and time the purchased goods should be delivered. Format [ISO 8601](https://www.w3.org/TR/NOTE-datetime): YYYY-MM-DDThh:mm:ss.sssTZD Example: 2017-07-17T13:42:40.428+01:00 + [JsonPropertyName("deliveryDate")] + public DateTimeOffset? DeliveryDate { get { return this._DeliveryDateOption; } set { this._DeliveryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceFingerprintOption { get; private set; } + + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + /// + /// A string containing the shopper's device fingerprint. For more information, refer to [Device fingerprinting](https://docs.adyen.com/risk-management/device-fingerprinting). + [JsonPropertyName("deviceFingerprint")] + public string? DeviceFingerprint { get { return this._DeviceFingerprintOption; } set { this._DeviceFingerprintOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("installments")] + public Installments? Installments { get { return this._InstallmentsOption; } set { this._InstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LocalizedShopperStatementOption { get; private set; } + + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + /// + /// The `localizedShopperStatement` field lets you use dynamic values for your shopper statement in a local character set. If not supplied, left empty, or for cross-border transactions, **shopperStatement** is used. Adyen currently supports the ja-Kana and ja-Hani character set for Visa, Mastercard and JCB payments in Japan using Japanese cards. This character set supports: * UTF-8 based Katakana, Kanji, capital letters, numbers and special characters. * Half-width or full-width characters. + [JsonPropertyName("localizedShopperStatement")] + public Dictionary? LocalizedShopperStatement { get { return this._LocalizedShopperStatementOption; } set { this._LocalizedShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + /// + /// The [merchant category code](https://en.wikipedia.org/wiki/Merchant_category_code) (MCC) is a four-digit number, which relates to a particular market segment. This code reflects the predominant activity that is conducted by the merchant. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOrderReferenceOption { get; private set; } + + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + /// + /// This reference allows linking multiple transactions to each other for reporting purposes (i.e. order auth-rate). The reference should be unique per billing cycle. The same merchant order reference should never be reused after the first authorised attempt. If used, this field should be supplied for all incoming authorisations. > We strongly recommend you send the `merchantOrderReference` value to benefit from linking payment requests when authorisation retries take place. In addition, we recommend you provide `retry.orderAttemptNumber`, `retry.chainAttemptNumber`, and `retry.skipRetry` values in `PaymentRequest.additionalData`. + [JsonPropertyName("merchantOrderReference")] + public string? MerchantOrderReference { get { return this._MerchantOrderReferenceOption; } set { this._MerchantOrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantRiskIndicatorOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantRiskIndicator")] + public MerchantRiskIndicator? MerchantRiskIndicator { get { return this._MerchantRiskIndicatorOption; } set { this._MerchantRiskIndicatorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + /// + /// Metadata consists of entries, each of which includes a key and a value. Limits: * Maximum 20 key-value pairs per request. When exceeding, the \"177\" error occurs: \"Metadata size exceeds limit\". * Maximum 20 characters per key. * Maximum 80 characters per value. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OrderReferenceOption { get; private set; } + + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + /// + /// When you are doing multiple partial (gift card) payments, this is the `pspReference` of the first payment. We use this to link the multiple payments to each other. As your own reference for linking multiple payments, use the `merchantOrderReference`instead. + [JsonPropertyName("orderReference")] + public string? OrderReference { get { return this._OrderReferenceOption; } set { this._OrderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + /// + /// Some payment methods require defining a value for this field to specify how to process the transaction. For the Bancontact payment method, it can be set to: * `maestro` (default), to be processed like a Maestro card, or * `bcmc`, to be processed like a Bancontact card. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SessionIdOption { get; private set; } + + /// + /// A session ID used to identify a payment session. + /// + /// A session ID used to identify a payment session. + [JsonPropertyName("sessionId")] + public string? SessionId { get { return this._SessionIdOption; } set { this._SessionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperIPOption { get; private set; } + + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The shopper's IP address. We recommend that you provide this data, as it is used in a number of risk checks (for instance, number of payment attempts or location-based checks). > Required for Visa and JCB transactions that require 3D Secure 2 authentication for all web and mobile integrations, if you did not include the `shopperEmail`. For native mobile integrations, the field is required to support cases where authentication is routed to the redirect flow. This field is also mandatory for some merchants depending on your business model. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("shopperIP")] + public string? ShopperIP { get { return this._ShopperIPOption; } set { this._ShopperIPOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperLocaleOption { get; private set; } + + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + /// + /// The combination of a language code and a country code to specify the language to be used in the payment. + [JsonPropertyName("shopperLocale")] + public string? ShopperLocale { get { return this._ShopperLocaleOption; } set { this._ShopperLocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + /// + /// The text to be shown on the shopper's bank statement. We recommend sending a maximum of 22 characters, otherwise banks might truncate the string. Allowed characters: **a-z**, **A-Z**, **0-9**, spaces, and special characters **. , ' _ - ? + * /_**. + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + /// + /// An array of objects specifying how the payment should be split when using either Adyen for Platforms for [marketplaces](https://docs.adyen.com/marketplaces/split-payments) or [platforms](https://docs.adyen.com/platforms/split-payments), or standalone [Issuing](https://docs.adyen.com/issuing/add-manage-funds#split). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + /// + /// Required for Adyen for Platforms integrations if you are a platform model. This is your [reference](https://docs.adyen.com/api-explorer/Management/3/post/merchants/(merchantId)/stores#request-reference) (on [balance platform](https://docs.adyen.com/platforms)) or the [storeReference](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccountHolder#request-accountHolderDetails-storeDetails-storeReference) (in the [classic integration](https://docs.adyen.com/classic-platforms/processing-payments/route-payment-to-store/#route-a-payment-to-a-store)) for the ecommerce or point-of-sale store that is processing the payment. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2RequestDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2RequestData")] + public ThreeDS2RequestData? ThreeDS2RequestData { get { return this._ThreeDS2RequestDataOption; } set { this._ThreeDS2RequestDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2Result")] + public ThreeDS2Result? ThreeDS2Result { get { return this._ThreeDS2ResultOption; } set { this._ThreeDS2ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2TokenOption { get; private set; } + + /// + /// The ThreeDS2Token that was returned in the /authorise call. + /// + /// The ThreeDS2Token that was returned in the /authorise call. + [JsonPropertyName("threeDS2Token")] + public string? ThreeDS2Token { get { return this._ThreeDS2TokenOption; } set { this._ThreeDS2TokenOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSAuthenticationOnlyOption { get; private set; } + + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + /// + /// Required to trigger the [authentication-only flow](https://docs.adyen.com/online-payments/3d-secure/authentication-only/). If set to **true**, you will only perform the 3D Secure 2 authentication, and will not proceed to the payment authorization.Default: **false**. + [JsonPropertyName("threeDSAuthenticationOnly")] + public bool? ThreeDSAuthenticationOnly { get { return this._ThreeDSAuthenticationOnlyOption; } set { this._ThreeDSAuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TotalsGroupOption { get; private set; } + + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + /// + /// The reference value to aggregate sales totals in reporting. When not specified, the store field is used (if available). + [JsonPropertyName("totalsGroup")] + public string? TotalsGroup { get { return this._TotalsGroupOption; } set { this._TotalsGroupOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrustedShopperOption { get; private set; } + + /// + /// Set to true if the payment should be routed to a trusted MID. + /// + /// Set to true if the payment should be routed to a trusted MID. + [JsonPropertyName("trustedShopper")] + public bool? TrustedShopper { get { return this._TrustedShopperOption; } set { this._TrustedShopperOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentRequest3ds2 {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" AccountInfo: ").Append(AccountInfo).Append("\n"); + sb.Append(" AdditionalAmount: ").Append(AdditionalAmount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" BrowserInfo: ").Append(BrowserInfo).Append("\n"); + sb.Append(" CaptureDelayHours: ").Append(CaptureDelayHours).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" DccQuote: ").Append(DccQuote).Append("\n"); + sb.Append(" DeliveryAddress: ").Append(DeliveryAddress).Append("\n"); + sb.Append(" DeliveryDate: ").Append(DeliveryDate).Append("\n"); + sb.Append(" DeviceFingerprint: ").Append(DeviceFingerprint).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" Installments: ").Append(Installments).Append("\n"); + sb.Append(" LocalizedShopperStatement: ").Append(LocalizedShopperStatement).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n"); + sb.Append(" MerchantRiskIndicator: ").Append(MerchantRiskIndicator).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" OrderReference: ").Append(OrderReference).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" SessionId: ").Append(SessionId).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperIP: ").Append(ShopperIP).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperLocale: ").Append(ShopperLocale).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append(" ThreeDS2RequestData: ").Append(ThreeDS2RequestData).Append("\n"); + sb.Append(" ThreeDS2Result: ").Append(ThreeDS2Result).Append("\n"); + sb.Append(" ThreeDS2Token: ").Append(ThreeDS2Token).Append("\n"); + sb.Append(" ThreeDSAuthenticationOnly: ").Append(ThreeDSAuthenticationOnly).Append("\n"); + sb.Append(" TotalsGroup: ").Append(TotalsGroup).Append("\n"); + sb.Append(" TrustedShopper: ").Append(TrustedShopper).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // DeviceFingerprint (string) maxLength + if (this.DeviceFingerprint != null && this.DeviceFingerprint.Length > 5000) + { + yield return new ValidationResult("Invalid value for DeviceFingerprint, length must be less than 5000.", new [] { "DeviceFingerprint" }); + } + + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + // TotalsGroup (string) maxLength + if (this.TotalsGroup != null && this.TotalsGroup.Length > 16) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be less than 16.", new [] { "TotalsGroup" }); + } + + // TotalsGroup (string) minLength + if (this.TotalsGroup != null && this.TotalsGroup.Length < 1) + { + yield return new ValidationResult("Invalid value for TotalsGroup, length must be greater than 1.", new [] { "TotalsGroup" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentRequest3ds2JsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize DeliveryDate. + /// + public static string DeliveryDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentRequest3ds2 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option accountInfo = default; + Option additionalAmount = default; + Option?> additionalData = default; + Option applicationInfo = default; + Option billingAddress = default; + Option browserInfo = default; + Option captureDelayHours = default; + Option dateOfBirth = default; + Option dccQuote = default; + Option deliveryAddress = default; + Option deliveryDate = default; + Option deviceFingerprint = default; + Option fraudOffset = default; + Option installments = default; + Option?> localizedShopperStatement = default; + Option mcc = default; + Option merchantOrderReference = default; + Option merchantRiskIndicator = default; + Option?> metadata = default; + Option orderReference = default; + Option recurring = default; + Option recurringProcessingModel = default; + Option selectedBrand = default; + Option selectedRecurringDetailReference = default; + Option sessionId = default; + Option shopperEmail = default; + Option shopperIP = default; + Option shopperInteraction = default; + Option shopperLocale = default; + Option shopperName = default; + Option shopperReference = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option?> splits = default; + Option store = default; + Option telephoneNumber = default; + Option threeDS2RequestData = default; + Option threeDS2Result = default; + Option threeDS2Token = default; + Option threeDSAuthenticationOnly = default; + Option totalsGroup = default; + Option trustedShopper = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "accountInfo": + accountInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalAmount": + additionalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "applicationInfo": + applicationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "browserInfo": + browserInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "captureDelayHours": + captureDelayHours = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dccQuote": + dccQuote = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryAddress": + deliveryAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "deliveryDate": + deliveryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "deviceFingerprint": + deviceFingerprint = new Option(utf8JsonReader.GetString()!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "installments": + installments = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "localizedShopperStatement": + localizedShopperStatement = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantOrderReference": + merchantOrderReference = new Option(utf8JsonReader.GetString()!); + break; + case "merchantRiskIndicator": + merchantRiskIndicator = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "orderReference": + orderReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(PaymentRequest3ds2.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "sessionId": + sessionId = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperIP": + shopperIP = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PaymentRequest3ds2.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperLocale": + shopperLocale = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + case "threeDS2RequestData": + threeDS2RequestData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2Result": + threeDS2Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDS2Token": + threeDS2Token = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSAuthenticationOnly": + threeDSAuthenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "totalsGroup": + totalsGroup = new Option(utf8JsonReader.GetString()!); + break; + case "trustedShopper": + trustedShopper = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3ds2.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3ds2.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PaymentRequest3ds2.", nameof(reference)); + + return new PaymentRequest3ds2(amount.Value!, merchantAccount.Value!, reference.Value!, accountInfo, additionalAmount, additionalData, applicationInfo, billingAddress, browserInfo, captureDelayHours, dateOfBirth, dccQuote, deliveryAddress, deliveryDate, deviceFingerprint, fraudOffset, installments, localizedShopperStatement, mcc, merchantOrderReference, merchantRiskIndicator, metadata, orderReference, recurring, recurringProcessingModel, selectedBrand, selectedRecurringDetailReference, sessionId, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, splits, store, telephoneNumber, threeDS2RequestData, threeDS2Result, threeDS2Token, threeDSAuthenticationOnly, totalsGroup, trustedShopper); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentRequest3ds2 paymentRequest3ds2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentRequest3ds2, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentRequest3ds2 paymentRequest3ds2, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.Amount, jsonSerializerOptions); + if (paymentRequest3ds2.MerchantAccount != null) + writer.WriteString("merchantAccount", paymentRequest3ds2.MerchantAccount); + + if (paymentRequest3ds2.Reference != null) + writer.WriteString("reference", paymentRequest3ds2.Reference); + + if (paymentRequest3ds2._AccountInfoOption.IsSet) + { + writer.WritePropertyName("accountInfo"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.AccountInfo, jsonSerializerOptions); + } + if (paymentRequest3ds2._AdditionalAmountOption.IsSet) + { + writer.WritePropertyName("additionalAmount"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.AdditionalAmount, jsonSerializerOptions); + } + if (paymentRequest3ds2._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.AdditionalData, jsonSerializerOptions); + } + if (paymentRequest3ds2._ApplicationInfoOption.IsSet) + { + writer.WritePropertyName("applicationInfo"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.ApplicationInfo, jsonSerializerOptions); + } + if (paymentRequest3ds2._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.BillingAddress, jsonSerializerOptions); + } + if (paymentRequest3ds2._BrowserInfoOption.IsSet) + { + writer.WritePropertyName("browserInfo"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.BrowserInfo, jsonSerializerOptions); + } + if (paymentRequest3ds2._CaptureDelayHoursOption.IsSet) + writer.WriteNumber("captureDelayHours", paymentRequest3ds2._CaptureDelayHoursOption.Value!.Value); + + if (paymentRequest3ds2._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", paymentRequest3ds2._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (paymentRequest3ds2._DccQuoteOption.IsSet) + { + writer.WritePropertyName("dccQuote"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.DccQuote, jsonSerializerOptions); + } + if (paymentRequest3ds2._DeliveryAddressOption.IsSet) + { + writer.WritePropertyName("deliveryAddress"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.DeliveryAddress, jsonSerializerOptions); + } + if (paymentRequest3ds2._DeliveryDateOption.IsSet) + writer.WriteString("deliveryDate", paymentRequest3ds2._DeliveryDateOption.Value!.Value.ToString(DeliveryDateFormat)); + + if (paymentRequest3ds2._DeviceFingerprintOption.IsSet) + if (paymentRequest3ds2.DeviceFingerprint != null) + writer.WriteString("deviceFingerprint", paymentRequest3ds2.DeviceFingerprint); + + if (paymentRequest3ds2._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", paymentRequest3ds2._FraudOffsetOption.Value!.Value); + + if (paymentRequest3ds2._InstallmentsOption.IsSet) + { + writer.WritePropertyName("installments"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.Installments, jsonSerializerOptions); + } + if (paymentRequest3ds2._LocalizedShopperStatementOption.IsSet) + { + writer.WritePropertyName("localizedShopperStatement"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.LocalizedShopperStatement, jsonSerializerOptions); + } + if (paymentRequest3ds2._MccOption.IsSet) + if (paymentRequest3ds2.Mcc != null) + writer.WriteString("mcc", paymentRequest3ds2.Mcc); + + if (paymentRequest3ds2._MerchantOrderReferenceOption.IsSet) + if (paymentRequest3ds2.MerchantOrderReference != null) + writer.WriteString("merchantOrderReference", paymentRequest3ds2.MerchantOrderReference); + + if (paymentRequest3ds2._MerchantRiskIndicatorOption.IsSet) + { + writer.WritePropertyName("merchantRiskIndicator"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.MerchantRiskIndicator, jsonSerializerOptions); + } + if (paymentRequest3ds2._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.Metadata, jsonSerializerOptions); + } + if (paymentRequest3ds2._OrderReferenceOption.IsSet) + if (paymentRequest3ds2.OrderReference != null) + writer.WriteString("orderReference", paymentRequest3ds2.OrderReference); + + if (paymentRequest3ds2._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.Recurring, jsonSerializerOptions); + } + if (paymentRequest3ds2._RecurringProcessingModelOption.IsSet && paymentRequest3ds2.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = PaymentRequest3ds2.RecurringProcessingModelEnum.ToJsonValue(paymentRequest3ds2._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (paymentRequest3ds2._SelectedBrandOption.IsSet) + if (paymentRequest3ds2.SelectedBrand != null) + writer.WriteString("selectedBrand", paymentRequest3ds2.SelectedBrand); + + if (paymentRequest3ds2._SelectedRecurringDetailReferenceOption.IsSet) + if (paymentRequest3ds2.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", paymentRequest3ds2.SelectedRecurringDetailReference); + + if (paymentRequest3ds2._SessionIdOption.IsSet) + if (paymentRequest3ds2.SessionId != null) + writer.WriteString("sessionId", paymentRequest3ds2.SessionId); + + if (paymentRequest3ds2._ShopperEmailOption.IsSet) + if (paymentRequest3ds2.ShopperEmail != null) + writer.WriteString("shopperEmail", paymentRequest3ds2.ShopperEmail); + + if (paymentRequest3ds2._ShopperIPOption.IsSet) + if (paymentRequest3ds2.ShopperIP != null) + writer.WriteString("shopperIP", paymentRequest3ds2.ShopperIP); + + if (paymentRequest3ds2._ShopperInteractionOption.IsSet && paymentRequest3ds2.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PaymentRequest3ds2.ShopperInteractionEnum.ToJsonValue(paymentRequest3ds2._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (paymentRequest3ds2._ShopperLocaleOption.IsSet) + if (paymentRequest3ds2.ShopperLocale != null) + writer.WriteString("shopperLocale", paymentRequest3ds2.ShopperLocale); + + if (paymentRequest3ds2._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.ShopperName, jsonSerializerOptions); + } + if (paymentRequest3ds2._ShopperReferenceOption.IsSet) + if (paymentRequest3ds2.ShopperReference != null) + writer.WriteString("shopperReference", paymentRequest3ds2.ShopperReference); + + if (paymentRequest3ds2._ShopperStatementOption.IsSet) + if (paymentRequest3ds2.ShopperStatement != null) + writer.WriteString("shopperStatement", paymentRequest3ds2.ShopperStatement); + + if (paymentRequest3ds2._SocialSecurityNumberOption.IsSet) + if (paymentRequest3ds2.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", paymentRequest3ds2.SocialSecurityNumber); + + if (paymentRequest3ds2._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.Splits, jsonSerializerOptions); + } + if (paymentRequest3ds2._StoreOption.IsSet) + if (paymentRequest3ds2.Store != null) + writer.WriteString("store", paymentRequest3ds2.Store); + + if (paymentRequest3ds2._TelephoneNumberOption.IsSet) + if (paymentRequest3ds2.TelephoneNumber != null) + writer.WriteString("telephoneNumber", paymentRequest3ds2.TelephoneNumber); + + if (paymentRequest3ds2._ThreeDS2RequestDataOption.IsSet) + { + writer.WritePropertyName("threeDS2RequestData"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.ThreeDS2RequestData, jsonSerializerOptions); + } + if (paymentRequest3ds2._ThreeDS2ResultOption.IsSet) + { + writer.WritePropertyName("threeDS2Result"); + JsonSerializer.Serialize(writer, paymentRequest3ds2.ThreeDS2Result, jsonSerializerOptions); + } + if (paymentRequest3ds2._ThreeDS2TokenOption.IsSet) + if (paymentRequest3ds2.ThreeDS2Token != null) + writer.WriteString("threeDS2Token", paymentRequest3ds2.ThreeDS2Token); + + if (paymentRequest3ds2._ThreeDSAuthenticationOnlyOption.IsSet) + writer.WriteBoolean("threeDSAuthenticationOnly", paymentRequest3ds2._ThreeDSAuthenticationOnlyOption.Value!.Value); + + if (paymentRequest3ds2._TotalsGroupOption.IsSet) + if (paymentRequest3ds2.TotalsGroup != null) + writer.WriteString("totalsGroup", paymentRequest3ds2.TotalsGroup); + + if (paymentRequest3ds2._TrustedShopperOption.IsSet) + writer.WriteBoolean("trustedShopper", paymentRequest3ds2._TrustedShopperOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/PaymentResult.cs b/Adyen/Payment/Models/PaymentResult.cs new file mode 100644 index 000000000..a9e824815 --- /dev/null +++ b/Adyen/Payment/Models/PaymentResult.cs @@ -0,0 +1,648 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// PaymentResult. + /// + public partial class PaymentResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// dccAmount + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// fraudResult + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + /// The payment session. + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConstructor] + public PaymentResult(Option?> additionalData = default, Option authCode = default, Option dccAmount = default, Option dccSignature = default, Option fraudResult = default, Option issuerUrl = default, Option md = default, Option paRequest = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default) + { + _AdditionalDataOption = additionalData; + _AuthCodeOption = authCode; + _DccAmountOption = dccAmount; + _DccSignatureOption = dccSignature; + _FraudResultOption = fraudResult; + _IssuerUrlOption = issuerUrl; + _MdOption = md; + _PaRequestOption = paRequest; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentResult() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.AuthenticationFinished - AuthenticationFinished + /// + public static readonly ResultCodeEnum AuthenticationFinished = new("AuthenticationFinished"); + + /// + /// ResultCodeEnum.AuthenticationNotRequired - AuthenticationNotRequired + /// + public static readonly ResultCodeEnum AuthenticationNotRequired = new("AuthenticationNotRequired"); + + /// + /// ResultCodeEnum.Authorised - Authorised + /// + public static readonly ResultCodeEnum Authorised = new("Authorised"); + + /// + /// ResultCodeEnum.Cancelled - Cancelled + /// + public static readonly ResultCodeEnum Cancelled = new("Cancelled"); + + /// + /// ResultCodeEnum.ChallengeShopper - ChallengeShopper + /// + public static readonly ResultCodeEnum ChallengeShopper = new("ChallengeShopper"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.IdentifyShopper - IdentifyShopper + /// + public static readonly ResultCodeEnum IdentifyShopper = new("IdentifyShopper"); + + /// + /// ResultCodeEnum.PartiallyAuthorised - PartiallyAuthorised + /// + public static readonly ResultCodeEnum PartiallyAuthorised = new("PartiallyAuthorised"); + + /// + /// ResultCodeEnum.Pending - Pending + /// + public static readonly ResultCodeEnum Pending = new("Pending"); + + /// + /// ResultCodeEnum.PresentToShopper - PresentToShopper + /// + public static readonly ResultCodeEnum PresentToShopper = new("PresentToShopper"); + + /// + /// ResultCodeEnum.Received - Received + /// + public static readonly ResultCodeEnum Received = new("Received"); + + /// + /// ResultCodeEnum.RedirectShopper - RedirectShopper + /// + public static readonly ResultCodeEnum RedirectShopper = new("RedirectShopper"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "AuthenticationFinished" => ResultCodeEnum.AuthenticationFinished, + "AuthenticationNotRequired" => ResultCodeEnum.AuthenticationNotRequired, + "Authorised" => ResultCodeEnum.Authorised, + "Cancelled" => ResultCodeEnum.Cancelled, + "ChallengeShopper" => ResultCodeEnum.ChallengeShopper, + "Error" => ResultCodeEnum.Error, + "IdentifyShopper" => ResultCodeEnum.IdentifyShopper, + "PartiallyAuthorised" => ResultCodeEnum.PartiallyAuthorised, + "Pending" => ResultCodeEnum.Pending, + "PresentToShopper" => ResultCodeEnum.PresentToShopper, + "Received" => ResultCodeEnum.Received, + "RedirectShopper" => ResultCodeEnum.RedirectShopper, + "Refused" => ResultCodeEnum.Refused, + "Success" => ResultCodeEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.AuthenticationFinished) + return "AuthenticationFinished"; + + if (value == ResultCodeEnum.AuthenticationNotRequired) + return "AuthenticationNotRequired"; + + if (value == ResultCodeEnum.Authorised) + return "Authorised"; + + if (value == ResultCodeEnum.Cancelled) + return "Cancelled"; + + if (value == ResultCodeEnum.ChallengeShopper) + return "ChallengeShopper"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.IdentifyShopper) + return "IdentifyShopper"; + + if (value == ResultCodeEnum.PartiallyAuthorised) + return "PartiallyAuthorised"; + + if (value == ResultCodeEnum.Pending) + return "Pending"; + + if (value == ResultCodeEnum.PresentToShopper) + return "PresentToShopper"; + + if (value == ResultCodeEnum.Received) + return "Received"; + + if (value == ResultCodeEnum.RedirectShopper) + return "RedirectShopper"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Success) + return "Success"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccAmount")] + public Amount? DccAmount { get { return this._DccAmountOption; } set { this._DccAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccSignatureOption { get; private set; } + + /// + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("dccSignature")] + public string? DccSignature { get { return this._DccSignatureOption; } set { this._DccSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerUrlOption { get; private set; } + + /// + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + /// + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + [JsonPropertyName("issuerUrl")] + public string? IssuerUrl { get { return this._IssuerUrlOption; } set { this._IssuerUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MdOption { get; private set; } + + /// + /// The payment session. + /// + /// The payment session. + [JsonPropertyName("md")] + public string? Md { get { return this._MdOption; } set { this._MdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaRequestOption { get; private set; } + + /// + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + /// + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + [JsonPropertyName("paRequest")] + public string? PaRequest { get { return this._PaRequestOption; } set { this._PaRequestOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentResult {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" DccAmount: ").Append(DccAmount).Append("\n"); + sb.Append(" DccSignature: ").Append(DccSignature).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" IssuerUrl: ").Append(IssuerUrl).Append("\n"); + sb.Append(" Md: ").Append(Md).Append("\n"); + sb.Append(" PaRequest: ").Append(PaRequest).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Md (string) maxLength + if (this.Md != null && this.Md.Length > 20000) + { + yield return new ValidationResult("Invalid value for Md, length must be less than 20000.", new [] { "Md" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option authCode = default; + Option dccAmount = default; + Option dccSignature = default; + Option fraudResult = default; + Option issuerUrl = default; + Option md = default; + Option paRequest = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "dccAmount": + dccAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dccSignature": + dccSignature = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "issuerUrl": + issuerUrl = new Option(utf8JsonReader.GetString()!); + break; + case "md": + md = new Option(utf8JsonReader.GetString()!); + break; + case "paRequest": + paRequest = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(PaymentResult.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + default: + break; + } + } + } + + + return new PaymentResult(additionalData, authCode, dccAmount, dccSignature, fraudResult, issuerUrl, md, paRequest, pspReference, refusalReason, resultCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentResult paymentResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentResult paymentResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentResult._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, paymentResult.AdditionalData, jsonSerializerOptions); + } + if (paymentResult._AuthCodeOption.IsSet) + if (paymentResult.AuthCode != null) + writer.WriteString("authCode", paymentResult.AuthCode); + + if (paymentResult._DccAmountOption.IsSet) + { + writer.WritePropertyName("dccAmount"); + JsonSerializer.Serialize(writer, paymentResult.DccAmount, jsonSerializerOptions); + } + if (paymentResult._DccSignatureOption.IsSet) + if (paymentResult.DccSignature != null) + writer.WriteString("dccSignature", paymentResult.DccSignature); + + if (paymentResult._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, paymentResult.FraudResult, jsonSerializerOptions); + } + if (paymentResult._IssuerUrlOption.IsSet) + if (paymentResult.IssuerUrl != null) + writer.WriteString("issuerUrl", paymentResult.IssuerUrl); + + if (paymentResult._MdOption.IsSet) + if (paymentResult.Md != null) + writer.WriteString("md", paymentResult.Md); + + if (paymentResult._PaRequestOption.IsSet) + if (paymentResult.PaRequest != null) + writer.WriteString("paRequest", paymentResult.PaRequest); + + if (paymentResult._PspReferenceOption.IsSet) + if (paymentResult.PspReference != null) + writer.WriteString("pspReference", paymentResult.PspReference); + + if (paymentResult._RefusalReasonOption.IsSet) + if (paymentResult.RefusalReason != null) + writer.WriteString("refusalReason", paymentResult.RefusalReason); + + if (paymentResult._ResultCodeOption.IsSet && paymentResult.ResultCode != null) + { + string? resultCodeRawValue = PaymentResult.ResultCodeEnum.ToJsonValue(paymentResult._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + } + } +} diff --git a/Adyen/Payment/Models/Phone.cs b/Adyen/Payment/Models/Phone.cs new file mode 100644 index 000000000..98c08b649 --- /dev/null +++ b/Adyen/Payment/Models/Phone.cs @@ -0,0 +1,220 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Phone. + /// + public partial class Phone : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Country code. Length: 1–3 digits. + /// Subscriber number. Length: 4-15 digits. + [JsonConstructor] + public Phone(Option cc = default, Option subscriber = default) + { + _CcOption = cc; + _SubscriberOption = subscriber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Phone() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CcOption { get; private set; } + + /// + /// Country code. Length: 1–3 digits. + /// + /// Country code. Length: 1–3 digits. + [JsonPropertyName("cc")] + public string? Cc { get { return this._CcOption; } set { this._CcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SubscriberOption { get; private set; } + + /// + /// Subscriber number. Length: 4-15 digits. + /// + /// Subscriber number. Length: 4-15 digits. + [JsonPropertyName("subscriber")] + public string? Subscriber { get { return this._SubscriberOption; } set { this._SubscriberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Phone {\n"); + sb.Append(" Cc: ").Append(Cc).Append("\n"); + sb.Append(" Subscriber: ").Append(Subscriber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Cc (string) maxLength + if (this.Cc != null && this.Cc.Length > 3) + { + yield return new ValidationResult("Invalid value for Cc, length must be less than 3.", new [] { "Cc" }); + } + + // Cc (string) minLength + if (this.Cc != null && this.Cc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cc, length must be greater than 1.", new [] { "Cc" }); + } + + // Subscriber (string) maxLength + if (this.Subscriber != null && this.Subscriber.Length > 15) + { + yield return new ValidationResult("Invalid value for Subscriber, length must be less than 15.", new [] { "Subscriber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PhoneJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Phone Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cc = default; + Option subscriber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cc": + cc = new Option(utf8JsonReader.GetString()!); + break; + case "subscriber": + subscriber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Phone(cc, subscriber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, phone, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Phone phone, JsonSerializerOptions jsonSerializerOptions) + { + + if (phone._CcOption.IsSet) + if (phone.Cc != null) + writer.WriteString("cc", phone.Cc); + + if (phone._SubscriberOption.IsSet) + if (phone.Subscriber != null) + writer.WriteString("subscriber", phone.Subscriber); + } + } +} diff --git a/Adyen/Payment/Models/PlatformChargebackLogic.cs b/Adyen/Payment/Models/PlatformChargebackLogic.cs new file mode 100644 index 000000000..0df048bef --- /dev/null +++ b/Adyen/Payment/Models/PlatformChargebackLogic.cs @@ -0,0 +1,342 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// PlatformChargebackLogic. + /// + public partial class PlatformChargebackLogic : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + [JsonConstructor] + public PlatformChargebackLogic(Option behavior = default, Option costAllocationAccount = default, Option targetAccount = default) + { + _BehaviorOption = behavior; + _CostAllocationAccountOption = costAllocationAccount; + _TargetAccountOption = targetAccount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformChargebackLogic() + { + } + + partial void OnCreated(); + + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonConverter(typeof(BehaviorEnumJsonConverter))] + public class BehaviorEnum : IEnum + { + /// + /// Returns the value of the BehaviorEnum. + /// + public string? Value { get; set; } + + /// + /// BehaviorEnum.DeductAccordingToSplitRatio - deductAccordingToSplitRatio + /// + public static readonly BehaviorEnum DeductAccordingToSplitRatio = new("deductAccordingToSplitRatio"); + + /// + /// BehaviorEnum.DeductFromLiableAccount - deductFromLiableAccount + /// + public static readonly BehaviorEnum DeductFromLiableAccount = new("deductFromLiableAccount"); + + /// + /// BehaviorEnum.DeductFromOneBalanceAccount - deductFromOneBalanceAccount + /// + public static readonly BehaviorEnum DeductFromOneBalanceAccount = new("deductFromOneBalanceAccount"); + + private BehaviorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator BehaviorEnum?(string? value) => value == null ? null : new BehaviorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(BehaviorEnum? option) => option?.Value; + + public static bool operator ==(BehaviorEnum? left, BehaviorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(BehaviorEnum? left, BehaviorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is BehaviorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static BehaviorEnum? FromStringOrDefault(string value) + { + return value switch { + "deductAccordingToSplitRatio" => BehaviorEnum.DeductAccordingToSplitRatio, + "deductFromLiableAccount" => BehaviorEnum.DeductFromLiableAccount, + "deductFromOneBalanceAccount" => BehaviorEnum.DeductFromOneBalanceAccount, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(BehaviorEnum? value) + { + if (value == null) + return null; + + if (value == BehaviorEnum.DeductAccordingToSplitRatio) + return "deductAccordingToSplitRatio"; + + if (value == BehaviorEnum.DeductFromLiableAccount) + return "deductFromLiableAccount"; + + if (value == BehaviorEnum.DeductFromOneBalanceAccount) + return "deductFromOneBalanceAccount"; + + return null; + } + + /// + /// JsonConverter for writing BehaviorEnum. + /// + public class BehaviorEnumJsonConverter : JsonConverter + { + public override BehaviorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : BehaviorEnum.FromStringOrDefault(value) ?? new BehaviorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, BehaviorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(BehaviorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BehaviorOption { get; private set; } + + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + /// + /// The method of handling the chargeback. Possible values: **deductFromLiableAccount**, **deductFromOneBalanceAccount**, **deductAccordingToSplitRatio**. + [JsonPropertyName("behavior")] + public BehaviorEnum? Behavior { get { return this._BehaviorOption; } set { this._BehaviorOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CostAllocationAccountOption { get; private set; } + + /// + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + /// + /// The unique identifier of the balance account to which the chargeback fees are booked. By default, the chargeback fees are booked to your liable balance account. + [JsonPropertyName("costAllocationAccount")] + public string? CostAllocationAccount { get { return this._CostAllocationAccountOption; } set { this._CostAllocationAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TargetAccountOption { get; private set; } + + /// + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + /// + /// The unique identifier of the balance account against which the disputed amount is booked. Required if `behavior` is **deductFromOneBalanceAccount**. + [JsonPropertyName("targetAccount")] + public string? TargetAccount { get { return this._TargetAccountOption; } set { this._TargetAccountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformChargebackLogic {\n"); + sb.Append(" Behavior: ").Append(Behavior).Append("\n"); + sb.Append(" CostAllocationAccount: ").Append(CostAllocationAccount).Append("\n"); + sb.Append(" TargetAccount: ").Append(TargetAccount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformChargebackLogicJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformChargebackLogic Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option behavior = default; + Option costAllocationAccount = default; + Option targetAccount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "behavior": + string? behaviorRawValue = utf8JsonReader.GetString(); + behavior = new Option(PlatformChargebackLogic.BehaviorEnum.FromStringOrDefault(behaviorRawValue)); + break; + case "costAllocationAccount": + costAllocationAccount = new Option(utf8JsonReader.GetString()!); + break; + case "targetAccount": + targetAccount = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PlatformChargebackLogic(behavior, costAllocationAccount, targetAccount); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformChargebackLogic platformChargebackLogic, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformChargebackLogic, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformChargebackLogic platformChargebackLogic, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformChargebackLogic._BehaviorOption.IsSet && platformChargebackLogic.Behavior != null) + { + string? behaviorRawValue = PlatformChargebackLogic.BehaviorEnum.ToJsonValue(platformChargebackLogic._BehaviorOption.Value!.Value); + writer.WriteString("behavior", behaviorRawValue); + } + + if (platformChargebackLogic._CostAllocationAccountOption.IsSet) + if (platformChargebackLogic.CostAllocationAccount != null) + writer.WriteString("costAllocationAccount", platformChargebackLogic.CostAllocationAccount); + + if (platformChargebackLogic._TargetAccountOption.IsSet) + if (platformChargebackLogic.TargetAccount != null) + writer.WriteString("targetAccount", platformChargebackLogic.TargetAccount); + } + } +} diff --git a/Adyen/Payment/Models/Recurring.cs b/Adyen/Payment/Models/Recurring.cs new file mode 100644 index 000000000..13635424a --- /dev/null +++ b/Adyen/Payment/Models/Recurring.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Recurring. + /// + public partial class Recurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// A descriptive name for this detail. + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// The name of the token service. + [JsonConstructor] + public Recurring(Option contract = default, Option recurringDetailName = default, Option recurringExpiry = default, Option recurringFrequency = default, Option tokenService = default) + { + _ContractOption = contract; + _RecurringDetailNameOption = recurringDetailName; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _TokenServiceOption = tokenService; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Recurring() + { + } + + partial void OnCreated(); + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonConverter(typeof(ContractEnumJsonConverter))] + public class ContractEnum : IEnum + { + /// + /// Returns the value of the ContractEnum. + /// + public string? Value { get; set; } + + /// + /// ContractEnum.ONECLICK - ONECLICK + /// + public static readonly ContractEnum ONECLICK = new("ONECLICK"); + + /// + /// ContractEnum.ONECLICKRECURRING - ONECLICK,RECURRING + /// + public static readonly ContractEnum ONECLICKRECURRING = new("ONECLICK,RECURRING"); + + /// + /// ContractEnum.RECURRING - RECURRING + /// + public static readonly ContractEnum RECURRING = new("RECURRING"); + + /// + /// ContractEnum.PAYOUT - PAYOUT + /// + public static readonly ContractEnum PAYOUT = new("PAYOUT"); + + /// + /// ContractEnum.EXTERNAL - EXTERNAL + /// + public static readonly ContractEnum EXTERNAL = new("EXTERNAL"); + + private ContractEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractEnum?(string? value) => value == null ? null : new ContractEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractEnum? option) => option?.Value; + + public static bool operator ==(ContractEnum? left, ContractEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractEnum? left, ContractEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractEnum? FromStringOrDefault(string value) + { + return value switch { + "ONECLICK" => ContractEnum.ONECLICK, + "ONECLICK,RECURRING" => ContractEnum.ONECLICKRECURRING, + "RECURRING" => ContractEnum.RECURRING, + "PAYOUT" => ContractEnum.PAYOUT, + "EXTERNAL" => ContractEnum.EXTERNAL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractEnum? value) + { + if (value == null) + return null; + + if (value == ContractEnum.ONECLICK) + return "ONECLICK"; + + if (value == ContractEnum.ONECLICKRECURRING) + return "ONECLICK,RECURRING"; + + if (value == ContractEnum.RECURRING) + return "RECURRING"; + + if (value == ContractEnum.PAYOUT) + return "PAYOUT"; + + if (value == ContractEnum.EXTERNAL) + return "EXTERNAL"; + + return null; + } + + /// + /// JsonConverter for writing ContractEnum. + /// + public class ContractEnumJsonConverter : JsonConverter + { + public override ContractEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractEnum.FromStringOrDefault(value) ?? new ContractEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonPropertyName("contract")] + public ContractEnum? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonConverter(typeof(TokenServiceEnumJsonConverter))] + public class TokenServiceEnum : IEnum + { + /// + /// Returns the value of the TokenServiceEnum. + /// + public string? Value { get; set; } + + /// + /// TokenServiceEnum.VISATOKENSERVICE - VISATOKENSERVICE + /// + public static readonly TokenServiceEnum VISATOKENSERVICE = new("VISATOKENSERVICE"); + + /// + /// TokenServiceEnum.MCTOKENSERVICE - MCTOKENSERVICE + /// + public static readonly TokenServiceEnum MCTOKENSERVICE = new("MCTOKENSERVICE"); + + /// + /// TokenServiceEnum.AMEXTOKENSERVICE - AMEXTOKENSERVICE + /// + public static readonly TokenServiceEnum AMEXTOKENSERVICE = new("AMEXTOKENSERVICE"); + + /// + /// TokenServiceEnum.TOKENSHARING - TOKEN_SHARING + /// + public static readonly TokenServiceEnum TOKENSHARING = new("TOKEN_SHARING"); + + private TokenServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenServiceEnum?(string? value) => value == null ? null : new TokenServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenServiceEnum? option) => option?.Value; + + public static bool operator ==(TokenServiceEnum? left, TokenServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenServiceEnum? left, TokenServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "VISATOKENSERVICE" => TokenServiceEnum.VISATOKENSERVICE, + "MCTOKENSERVICE" => TokenServiceEnum.MCTOKENSERVICE, + "AMEXTOKENSERVICE" => TokenServiceEnum.AMEXTOKENSERVICE, + "TOKEN_SHARING" => TokenServiceEnum.TOKENSHARING, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenServiceEnum? value) + { + if (value == null) + return null; + + if (value == TokenServiceEnum.VISATOKENSERVICE) + return "VISATOKENSERVICE"; + + if (value == TokenServiceEnum.MCTOKENSERVICE) + return "MCTOKENSERVICE"; + + if (value == TokenServiceEnum.AMEXTOKENSERVICE) + return "AMEXTOKENSERVICE"; + + if (value == TokenServiceEnum.TOKENSHARING) + return "TOKEN_SHARING"; + + return null; + } + + /// + /// JsonConverter for writing TokenServiceEnum. + /// + public class TokenServiceEnumJsonConverter : JsonConverter + { + public override TokenServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenServiceEnum.FromStringOrDefault(value) ?? new TokenServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenServiceOption { get; private set; } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonPropertyName("tokenService")] + public TokenServiceEnum? TokenService { get { return this._TokenServiceOption; } set { this._TokenServiceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailNameOption { get; private set; } + + /// + /// A descriptive name for this detail. + /// + /// A descriptive name for this detail. + [JsonPropertyName("recurringDetailName")] + public string? RecurringDetailName { get { return this._RecurringDetailNameOption; } set { this._RecurringDetailNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public DateTimeOffset? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Recurring {\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" TokenService: ").Append(TokenService).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RecurringExpiry. + /// + public static string RecurringExpiryFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Recurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contract = default; + Option recurringDetailName = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option tokenService = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contract": + string? contractRawValue = utf8JsonReader.GetString(); + contract = new Option(Recurring.ContractEnum.FromStringOrDefault(contractRawValue)); + break; + case "recurringDetailName": + recurringDetailName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "tokenService": + string? tokenServiceRawValue = utf8JsonReader.GetString(); + tokenService = new Option(Recurring.TokenServiceEnum.FromStringOrDefault(tokenServiceRawValue)); + break; + default: + break; + } + } + } + + + return new Recurring(contract, recurringDetailName, recurringExpiry, recurringFrequency, tokenService); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurring._ContractOption.IsSet && recurring.Contract != null) + { + string? contractRawValue = Recurring.ContractEnum.ToJsonValue(recurring._ContractOption.Value!.Value); + writer.WriteString("contract", contractRawValue); + } + + if (recurring._RecurringDetailNameOption.IsSet) + if (recurring.RecurringDetailName != null) + writer.WriteString("recurringDetailName", recurring.RecurringDetailName); + + if (recurring._RecurringExpiryOption.IsSet) + writer.WriteString("recurringExpiry", recurring._RecurringExpiryOption.Value!.Value.ToString(RecurringExpiryFormat)); + + if (recurring._RecurringFrequencyOption.IsSet) + if (recurring.RecurringFrequency != null) + writer.WriteString("recurringFrequency", recurring.RecurringFrequency); + + if (recurring._TokenServiceOption.IsSet && recurring.TokenService != null) + { + string? tokenServiceRawValue = Recurring.TokenServiceEnum.ToJsonValue(recurring._TokenServiceOption.Value!.Value); + writer.WriteString("tokenService", tokenServiceRawValue); + } + } + } +} diff --git a/Adyen/Payment/Models/RefundRequest.cs b/Adyen/Payment/Models/RefundRequest.cs new file mode 100644 index 000000000..a266de6d6 --- /dev/null +++ b/Adyen/Payment/Models/RefundRequest.cs @@ -0,0 +1,411 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// RefundRequest. + /// + public partial class RefundRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// modificationAmount + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// mpiData + /// The original merchant reference to cancel. + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public RefundRequest(string merchantAccount, Amount modificationAmount, string originalReference, Option?> additionalData = default, Option mpiData = default, Option originalMerchantReference = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + ModificationAmount = modificationAmount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RefundRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount ModificationAmount { get; set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RefundRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RefundRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RefundRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option modificationAmount = default; + Option originalReference = default; + Option?> additionalData = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class RefundRequest.", nameof(merchantAccount)); + + if (!modificationAmount.IsSet) + throw new ArgumentException("Property is required for class RefundRequest.", nameof(modificationAmount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class RefundRequest.", nameof(originalReference)); + + return new RefundRequest(merchantAccount.Value!, modificationAmount.Value!, originalReference.Value!, additionalData, mpiData, originalMerchantReference, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RefundRequest refundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, refundRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RefundRequest refundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (refundRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", refundRequest.MerchantAccount); + + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, refundRequest.ModificationAmount, jsonSerializerOptions); + if (refundRequest.OriginalReference != null) + writer.WriteString("originalReference", refundRequest.OriginalReference); + + if (refundRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, refundRequest.AdditionalData, jsonSerializerOptions); + } + if (refundRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, refundRequest.MpiData, jsonSerializerOptions); + } + if (refundRequest._OriginalMerchantReferenceOption.IsSet) + if (refundRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", refundRequest.OriginalMerchantReference); + + if (refundRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, refundRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (refundRequest._ReferenceOption.IsSet) + if (refundRequest.Reference != null) + writer.WriteString("reference", refundRequest.Reference); + + if (refundRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, refundRequest.Splits, jsonSerializerOptions); + } + if (refundRequest._TenderReferenceOption.IsSet) + if (refundRequest.TenderReference != null) + writer.WriteString("tenderReference", refundRequest.TenderReference); + + if (refundRequest._UniqueTerminalIdOption.IsSet) + if (refundRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", refundRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalData3DSecure.cs b/Adyen/Payment/Models/ResponseAdditionalData3DSecure.cs new file mode 100644 index 000000000..c7f34c614 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalData3DSecure.cs @@ -0,0 +1,276 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalData3DSecure. + /// + public partial class ResponseAdditionalData3DSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// The CAVV algorithm used. + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonConstructor] + public ResponseAdditionalData3DSecure(Option cardHolderInfo = default, Option cavv = default, Option cavvAlgorithm = default, Option scaExemptionRequested = default, Option threeds2CardEnrolled = default) + { + _CardHolderInfoOption = cardHolderInfo; + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _ScaExemptionRequestedOption = scaExemptionRequested; + _Threeds2CardEnrolledOption = threeds2CardEnrolled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalData3DSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderInfoOption { get; private set; } + + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + [JsonPropertyName("cardHolderInfo")] + public string? CardHolderInfo { get { return this._CardHolderInfoOption; } set { this._CardHolderInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + [JsonPropertyName("cavv")] + public string? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. + /// + /// The CAVV algorithm used. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaExemptionRequestedOption { get; private set; } + + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + [JsonPropertyName("scaExemptionRequested")] + public string? ScaExemptionRequested { get { return this._ScaExemptionRequestedOption; } set { this._ScaExemptionRequestedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Threeds2CardEnrolledOption { get; private set; } + + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonPropertyName("threeds2.cardEnrolled")] + public bool? Threeds2CardEnrolled { get { return this._Threeds2CardEnrolledOption; } set { this._Threeds2CardEnrolledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalData3DSecure {\n"); + sb.Append(" CardHolderInfo: ").Append(CardHolderInfo).Append("\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ScaExemptionRequested: ").Append(ScaExemptionRequested).Append("\n"); + sb.Append(" Threeds2CardEnrolled: ").Append(Threeds2CardEnrolled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalData3DSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalData3DSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardHolderInfo = default; + Option cavv = default; + Option cavvAlgorithm = default; + Option scaExemptionRequested = default; + Option threeds2CardEnrolled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardHolderInfo": + cardHolderInfo = new Option(utf8JsonReader.GetString()!); + break; + case "cavv": + cavv = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "scaExemptionRequested": + scaExemptionRequested = new Option(utf8JsonReader.GetString()!); + break; + case "threeds2.cardEnrolled": + threeds2CardEnrolled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalData3DSecure(cardHolderInfo, cavv, cavvAlgorithm, scaExemptionRequested, threeds2CardEnrolled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalData3DSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalData3DSecure._CardHolderInfoOption.IsSet) + if (responseAdditionalData3DSecure.CardHolderInfo != null) + writer.WriteString("cardHolderInfo", responseAdditionalData3DSecure.CardHolderInfo); + + if (responseAdditionalData3DSecure._CavvOption.IsSet) + if (responseAdditionalData3DSecure.Cavv != null) + writer.WriteString("cavv", responseAdditionalData3DSecure.Cavv); + + if (responseAdditionalData3DSecure._CavvAlgorithmOption.IsSet) + if (responseAdditionalData3DSecure.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", responseAdditionalData3DSecure.CavvAlgorithm); + + if (responseAdditionalData3DSecure._ScaExemptionRequestedOption.IsSet) + if (responseAdditionalData3DSecure.ScaExemptionRequested != null) + writer.WriteString("scaExemptionRequested", responseAdditionalData3DSecure.ScaExemptionRequested); + + if (responseAdditionalData3DSecure._Threeds2CardEnrolledOption.IsSet) + writer.WriteBoolean("threeds2.cardEnrolled", responseAdditionalData3DSecure._Threeds2CardEnrolledOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataBillingAddress.cs b/Adyen/Payment/Models/ResponseAdditionalDataBillingAddress.cs new file mode 100644 index 000000000..b04b3a9b2 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataBillingAddress.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataBillingAddress. + /// + public partial class ResponseAdditionalDataBillingAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The billing address city passed in the payment request. + /// The billing address country passed in the payment request. Example: NL + /// The billing address house number or name passed in the payment request. + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// The billing address state or province passed in the payment request. Example: NH + /// The billing address street passed in the payment request. + [JsonConstructor] + public ResponseAdditionalDataBillingAddress(Option billingAddressCity = default, Option billingAddressCountry = default, Option billingAddressHouseNumberOrName = default, Option billingAddressPostalCode = default, Option billingAddressStateOrProvince = default, Option billingAddressStreet = default) + { + _BillingAddressCityOption = billingAddressCity; + _BillingAddressCountryOption = billingAddressCountry; + _BillingAddressHouseNumberOrNameOption = billingAddressHouseNumberOrName; + _BillingAddressPostalCodeOption = billingAddressPostalCode; + _BillingAddressStateOrProvinceOption = billingAddressStateOrProvince; + _BillingAddressStreetOption = billingAddressStreet; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataBillingAddress() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCityOption { get; private set; } + + /// + /// The billing address city passed in the payment request. + /// + /// The billing address city passed in the payment request. + [JsonPropertyName("billingAddress.city")] + public string? BillingAddressCity { get { return this._BillingAddressCityOption; } set { this._BillingAddressCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCountryOption { get; private set; } + + /// + /// The billing address country passed in the payment request. Example: NL + /// + /// The billing address country passed in the payment request. Example: NL + [JsonPropertyName("billingAddress.country")] + public string? BillingAddressCountry { get { return this._BillingAddressCountryOption; } set { this._BillingAddressCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressHouseNumberOrNameOption { get; private set; } + + /// + /// The billing address house number or name passed in the payment request. + /// + /// The billing address house number or name passed in the payment request. + [JsonPropertyName("billingAddress.houseNumberOrName")] + public string? BillingAddressHouseNumberOrName { get { return this._BillingAddressHouseNumberOrNameOption; } set { this._BillingAddressHouseNumberOrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressPostalCodeOption { get; private set; } + + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + [JsonPropertyName("billingAddress.postalCode")] + public string? BillingAddressPostalCode { get { return this._BillingAddressPostalCodeOption; } set { this._BillingAddressPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStateOrProvinceOption { get; private set; } + + /// + /// The billing address state or province passed in the payment request. Example: NH + /// + /// The billing address state or province passed in the payment request. Example: NH + [JsonPropertyName("billingAddress.stateOrProvince")] + public string? BillingAddressStateOrProvince { get { return this._BillingAddressStateOrProvinceOption; } set { this._BillingAddressStateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStreetOption { get; private set; } + + /// + /// The billing address street passed in the payment request. + /// + /// The billing address street passed in the payment request. + [JsonPropertyName("billingAddress.street")] + public string? BillingAddressStreet { get { return this._BillingAddressStreetOption; } set { this._BillingAddressStreetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataBillingAddress {\n"); + sb.Append(" BillingAddressCity: ").Append(BillingAddressCity).Append("\n"); + sb.Append(" BillingAddressCountry: ").Append(BillingAddressCountry).Append("\n"); + sb.Append(" BillingAddressHouseNumberOrName: ").Append(BillingAddressHouseNumberOrName).Append("\n"); + sb.Append(" BillingAddressPostalCode: ").Append(BillingAddressPostalCode).Append("\n"); + sb.Append(" BillingAddressStateOrProvince: ").Append(BillingAddressStateOrProvince).Append("\n"); + sb.Append(" BillingAddressStreet: ").Append(BillingAddressStreet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataBillingAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataBillingAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddressCity = default; + Option billingAddressCountry = default; + Option billingAddressHouseNumberOrName = default; + Option billingAddressPostalCode = default; + Option billingAddressStateOrProvince = default; + Option billingAddressStreet = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress.city": + billingAddressCity = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.country": + billingAddressCountry = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.houseNumberOrName": + billingAddressHouseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.postalCode": + billingAddressPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.stateOrProvince": + billingAddressStateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.street": + billingAddressStreet = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataBillingAddress(billingAddressCity, billingAddressCountry, billingAddressHouseNumberOrName, billingAddressPostalCode, billingAddressStateOrProvince, billingAddressStreet); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataBillingAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataBillingAddress._BillingAddressCityOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCity != null) + writer.WriteString("billingAddress.city", responseAdditionalDataBillingAddress.BillingAddressCity); + + if (responseAdditionalDataBillingAddress._BillingAddressCountryOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCountry != null) + writer.WriteString("billingAddress.country", responseAdditionalDataBillingAddress.BillingAddressCountry); + + if (responseAdditionalDataBillingAddress._BillingAddressHouseNumberOrNameOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName != null) + writer.WriteString("billingAddress.houseNumberOrName", responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName); + + if (responseAdditionalDataBillingAddress._BillingAddressPostalCodeOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressPostalCode != null) + writer.WriteString("billingAddress.postalCode", responseAdditionalDataBillingAddress.BillingAddressPostalCode); + + if (responseAdditionalDataBillingAddress._BillingAddressStateOrProvinceOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStateOrProvince != null) + writer.WriteString("billingAddress.stateOrProvince", responseAdditionalDataBillingAddress.BillingAddressStateOrProvince); + + if (responseAdditionalDataBillingAddress._BillingAddressStreetOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStreet != null) + writer.WriteString("billingAddress.street", responseAdditionalDataBillingAddress.BillingAddressStreet); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataCard.cs b/Adyen/Payment/Models/ResponseAdditionalDataCard.cs new file mode 100644 index 000000000..456848f5f --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataCard.cs @@ -0,0 +1,564 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataCard. + /// + public partial class ResponseAdditionalDataCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// The cardholder name passed in the payment request. + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// The country where the card was issued. Example: US + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// The card payment method used for the transaction. Example: amex + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// The last four digits of a card number. > Returned only in case of a card payment. + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonConstructor] + public ResponseAdditionalDataCard(Option cardBin = default, Option cardHolderName = default, Option cardIssuingBank = default, Option cardIssuingCountry = default, Option cardIssuingCurrency = default, Option cardPaymentMethod = default, Option cardProductId = default, Option cardSummary = default, Option issuerBin = default) + { + _CardBinOption = cardBin; + _CardHolderNameOption = cardHolderName; + _CardIssuingBankOption = cardIssuingBank; + _CardIssuingCountryOption = cardIssuingCountry; + _CardIssuingCurrencyOption = cardIssuingCurrency; + _CardPaymentMethodOption = cardPaymentMethod; + _CardProductIdOption = cardProductId; + _CardSummaryOption = cardSummary; + _IssuerBinOption = issuerBin; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCard() + { + } + + partial void OnCreated(); + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonConverter(typeof(CardProductIdEnumJsonConverter))] + public class CardProductIdEnum : IEnum + { + /// + /// Returns the value of the CardProductIdEnum. + /// + public string? Value { get; set; } + + /// + /// CardProductIdEnum.A - A + /// + public static readonly CardProductIdEnum A = new("A"); + + /// + /// CardProductIdEnum.B - B + /// + public static readonly CardProductIdEnum B = new("B"); + + /// + /// CardProductIdEnum.C - C + /// + public static readonly CardProductIdEnum C = new("C"); + + /// + /// CardProductIdEnum.D - D + /// + public static readonly CardProductIdEnum D = new("D"); + + /// + /// CardProductIdEnum.F - F + /// + public static readonly CardProductIdEnum F = new("F"); + + /// + /// CardProductIdEnum.MCC - MCC + /// + public static readonly CardProductIdEnum MCC = new("MCC"); + + /// + /// CardProductIdEnum.MCE - MCE + /// + public static readonly CardProductIdEnum MCE = new("MCE"); + + /// + /// CardProductIdEnum.MCF - MCF + /// + public static readonly CardProductIdEnum MCF = new("MCF"); + + /// + /// CardProductIdEnum.MCG - MCG + /// + public static readonly CardProductIdEnum MCG = new("MCG"); + + /// + /// CardProductIdEnum.MCH - MCH + /// + public static readonly CardProductIdEnum MCH = new("MCH"); + + /// + /// CardProductIdEnum.MCI - MCI + /// + public static readonly CardProductIdEnum MCI = new("MCI"); + + private CardProductIdEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CardProductIdEnum?(string? value) => value == null ? null : new CardProductIdEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CardProductIdEnum? option) => option?.Value; + + public static bool operator ==(CardProductIdEnum? left, CardProductIdEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CardProductIdEnum? left, CardProductIdEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CardProductIdEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CardProductIdEnum? FromStringOrDefault(string value) + { + return value switch { + "A" => CardProductIdEnum.A, + "B" => CardProductIdEnum.B, + "C" => CardProductIdEnum.C, + "D" => CardProductIdEnum.D, + "F" => CardProductIdEnum.F, + "MCC" => CardProductIdEnum.MCC, + "MCE" => CardProductIdEnum.MCE, + "MCF" => CardProductIdEnum.MCF, + "MCG" => CardProductIdEnum.MCG, + "MCH" => CardProductIdEnum.MCH, + "MCI" => CardProductIdEnum.MCI, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CardProductIdEnum? value) + { + if (value == null) + return null; + + if (value == CardProductIdEnum.A) + return "A"; + + if (value == CardProductIdEnum.B) + return "B"; + + if (value == CardProductIdEnum.C) + return "C"; + + if (value == CardProductIdEnum.D) + return "D"; + + if (value == CardProductIdEnum.F) + return "F"; + + if (value == CardProductIdEnum.MCC) + return "MCC"; + + if (value == CardProductIdEnum.MCE) + return "MCE"; + + if (value == CardProductIdEnum.MCF) + return "MCF"; + + if (value == CardProductIdEnum.MCG) + return "MCG"; + + if (value == CardProductIdEnum.MCH) + return "MCH"; + + if (value == CardProductIdEnum.MCI) + return "MCI"; + + return null; + } + + /// + /// JsonConverter for writing CardProductIdEnum. + /// + public class CardProductIdEnumJsonConverter : JsonConverter + { + public override CardProductIdEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CardProductIdEnum.FromStringOrDefault(value) ?? new CardProductIdEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CardProductIdEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CardProductIdEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardProductIdOption { get; private set; } + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonPropertyName("cardProductId")] + public CardProductIdEnum? CardProductId { get { return this._CardProductIdOption; } set { this._CardProductIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardBinOption { get; private set; } + + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + [JsonPropertyName("cardBin")] + public string? CardBin { get { return this._CardBinOption; } set { this._CardBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderNameOption { get; private set; } + + /// + /// The cardholder name passed in the payment request. + /// + /// The cardholder name passed in the payment request. + [JsonPropertyName("cardHolderName")] + public string? CardHolderName { get { return this._CardHolderNameOption; } set { this._CardHolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingBankOption { get; private set; } + + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + [JsonPropertyName("cardIssuingBank")] + public string? CardIssuingBank { get { return this._CardIssuingBankOption; } set { this._CardIssuingBankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCountryOption { get; private set; } + + /// + /// The country where the card was issued. Example: US + /// + /// The country where the card was issued. Example: US + [JsonPropertyName("cardIssuingCountry")] + public string? CardIssuingCountry { get { return this._CardIssuingCountryOption; } set { this._CardIssuingCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCurrencyOption { get; private set; } + + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + [JsonPropertyName("cardIssuingCurrency")] + public string? CardIssuingCurrency { get { return this._CardIssuingCurrencyOption; } set { this._CardIssuingCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardPaymentMethodOption { get; private set; } + + /// + /// The card payment method used for the transaction. Example: amex + /// + /// The card payment method used for the transaction. Example: amex + [JsonPropertyName("cardPaymentMethod")] + public string? CardPaymentMethod { get { return this._CardPaymentMethodOption; } set { this._CardPaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardSummaryOption { get; private set; } + + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + [JsonPropertyName("cardSummary")] + public string? CardSummary { get { return this._CardSummaryOption; } set { this._CardSummaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerBinOption { get; private set; } + + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonPropertyName("issuerBin")] + public string? IssuerBin { get { return this._IssuerBinOption; } set { this._IssuerBinOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCard {\n"); + sb.Append(" CardBin: ").Append(CardBin).Append("\n"); + sb.Append(" CardHolderName: ").Append(CardHolderName).Append("\n"); + sb.Append(" CardIssuingBank: ").Append(CardIssuingBank).Append("\n"); + sb.Append(" CardIssuingCountry: ").Append(CardIssuingCountry).Append("\n"); + sb.Append(" CardIssuingCurrency: ").Append(CardIssuingCurrency).Append("\n"); + sb.Append(" CardPaymentMethod: ").Append(CardPaymentMethod).Append("\n"); + sb.Append(" CardProductId: ").Append(CardProductId).Append("\n"); + sb.Append(" CardSummary: ").Append(CardSummary).Append("\n"); + sb.Append(" IssuerBin: ").Append(IssuerBin).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardBin = default; + Option cardHolderName = default; + Option cardIssuingBank = default; + Option cardIssuingCountry = default; + Option cardIssuingCurrency = default; + Option cardPaymentMethod = default; + Option cardProductId = default; + Option cardSummary = default; + Option issuerBin = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardBin": + cardBin = new Option(utf8JsonReader.GetString()!); + break; + case "cardHolderName": + cardHolderName = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingBank": + cardIssuingBank = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCountry": + cardIssuingCountry = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCurrency": + cardIssuingCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "cardPaymentMethod": + cardPaymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "cardProductId": + string? cardProductIdRawValue = utf8JsonReader.GetString(); + cardProductId = new Option(ResponseAdditionalDataCard.CardProductIdEnum.FromStringOrDefault(cardProductIdRawValue)); + break; + case "cardSummary": + cardSummary = new Option(utf8JsonReader.GetString()!); + break; + case "issuerBin": + issuerBin = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCard(cardBin, cardHolderName, cardIssuingBank, cardIssuingCountry, cardIssuingCurrency, cardPaymentMethod, cardProductId, cardSummary, issuerBin); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCard._CardBinOption.IsSet) + if (responseAdditionalDataCard.CardBin != null) + writer.WriteString("cardBin", responseAdditionalDataCard.CardBin); + + if (responseAdditionalDataCard._CardHolderNameOption.IsSet) + if (responseAdditionalDataCard.CardHolderName != null) + writer.WriteString("cardHolderName", responseAdditionalDataCard.CardHolderName); + + if (responseAdditionalDataCard._CardIssuingBankOption.IsSet) + if (responseAdditionalDataCard.CardIssuingBank != null) + writer.WriteString("cardIssuingBank", responseAdditionalDataCard.CardIssuingBank); + + if (responseAdditionalDataCard._CardIssuingCountryOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCountry != null) + writer.WriteString("cardIssuingCountry", responseAdditionalDataCard.CardIssuingCountry); + + if (responseAdditionalDataCard._CardIssuingCurrencyOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCurrency != null) + writer.WriteString("cardIssuingCurrency", responseAdditionalDataCard.CardIssuingCurrency); + + if (responseAdditionalDataCard._CardPaymentMethodOption.IsSet) + if (responseAdditionalDataCard.CardPaymentMethod != null) + writer.WriteString("cardPaymentMethod", responseAdditionalDataCard.CardPaymentMethod); + + if (responseAdditionalDataCard._CardProductIdOption.IsSet && responseAdditionalDataCard.CardProductId != null) + { + string? cardProductIdRawValue = ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCard._CardProductIdOption.Value!.Value); + writer.WriteString("cardProductId", cardProductIdRawValue); + } + + if (responseAdditionalDataCard._CardSummaryOption.IsSet) + if (responseAdditionalDataCard.CardSummary != null) + writer.WriteString("cardSummary", responseAdditionalDataCard.CardSummary); + + if (responseAdditionalDataCard._IssuerBinOption.IsSet) + if (responseAdditionalDataCard.IssuerBin != null) + writer.WriteString("issuerBin", responseAdditionalDataCard.IssuerBin); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataCommon.cs b/Adyen/Payment/Models/ResponseAdditionalDataCommon.cs new file mode 100644 index 000000000..bc3f7dea5 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataCommon.cs @@ -0,0 +1,2200 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataCommon. + /// + public partial class ResponseAdditionalDataCommon : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// The Adyen alias of the card. Example: H167852639363479 + /// The type of the card alias. Example: Default + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// Merchant ID known by the acquirer. + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// Raw AVS result received from the acquirer, where available. Example: D + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// Includes the co-branded card information. + /// The result of CVC verification. + /// The raw result of CVC verification. + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// Indicates if the payment is sent to manual review. + /// The fraud result properties of the payment. + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// Indicates if the card is used for business purposes only. + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// The reference provided for the transaction. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// The payment method used in the transaction. + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// Message to be displayed on the terminal. + /// The recurring contract types applicable to the transaction. + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// The reference that uniquely identifies the recurring transaction. + /// The provided reference of the shopper for a recurring transaction. + /// The processing model used for the recurring transaction. + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// The amount of the payment request. + /// The currency of the payment request. + /// The shopper interaction type of the payment request. Example: Ecommerce + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// The raw 3DS authentication result from the card issuer. Example: N + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// The 3D Secure 2 version. + /// The reference for the shopper that you sent when tokenizing the payment details. + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// The reference that uniquely identifies tokenized payment details. + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonConstructor] + public ResponseAdditionalDataCommon(Option acquirerAccountCode = default, Option acquirerCode = default, Option acquirerReference = default, Option alias = default, Option aliasType = default, Option authCode = default, Option authorisationMid = default, Option authorisedAmountCurrency = default, Option authorisedAmountValue = default, Option avsResult = default, Option avsResultRaw = default, Option bic = default, Option coBrandedWith = default, Option cvcResult = default, Option cvcResultRaw = default, Option dsTransID = default, Option eci = default, Option expiryDate = default, Option extraCostsCurrency = default, Option extraCostsValue = default, Option fraudCheckItemNrFraudCheckname = default, Option fraudManualReview = default, Option fraudResultType = default, Option fraudRiskLevel = default, Option fundingSource = default, Option fundsAvailability = default, Option inferredRefusalReason = default, Option isCardCommercial = default, Option issuerCountry = default, Option liabilityShift = default, Option mcBankNetReferenceNumber = default, Option merchantAdviceCode = default, Option merchantReference = default, Option networkTxReference = default, Option ownerName = default, Option paymentAccountReference = default, Option paymentMethod = default, Option paymentMethodVariant = default, Option payoutEligible = default, Option realtimeAccountUpdaterStatus = default, Option receiptFreeText = default, Option recurringContractTypes = default, Option recurringFirstPspReference = default, Option recurringRecurringDetailReference = default, Option recurringShopperReference = default, Option recurringProcessingModel = default, Option referred = default, Option refusalReasonRaw = default, Option requestAmount = default, Option requestCurrencyCode = default, Option shopperInteraction = default, Option shopperReference = default, Option terminalId = default, Option threeDAuthenticated = default, Option threeDAuthenticatedResponse = default, Option threeDOffered = default, Option threeDOfferedResponse = default, Option threeDSVersion = default, Option tokenizationShopperReference = default, Option tokenizationStoreOperationType = default, Option tokenizationStoredPaymentMethodId = default, Option visaTransactionId = default, Option xid = default) + { + _AcquirerAccountCodeOption = acquirerAccountCode; + _AcquirerCodeOption = acquirerCode; + _AcquirerReferenceOption = acquirerReference; + _AliasOption = alias; + _AliasTypeOption = aliasType; + _AuthCodeOption = authCode; + _AuthorisationMidOption = authorisationMid; + _AuthorisedAmountCurrencyOption = authorisedAmountCurrency; + _AuthorisedAmountValueOption = authorisedAmountValue; + _AvsResultOption = avsResult; + _AvsResultRawOption = avsResultRaw; + _BicOption = bic; + _CoBrandedWithOption = coBrandedWith; + _CvcResultOption = cvcResult; + _CvcResultRawOption = cvcResultRaw; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _ExpiryDateOption = expiryDate; + _ExtraCostsCurrencyOption = extraCostsCurrency; + _ExtraCostsValueOption = extraCostsValue; + _FraudCheckItemNrFraudChecknameOption = fraudCheckItemNrFraudCheckname; + _FraudManualReviewOption = fraudManualReview; + _FraudResultTypeOption = fraudResultType; + _FraudRiskLevelOption = fraudRiskLevel; + _FundingSourceOption = fundingSource; + _FundsAvailabilityOption = fundsAvailability; + _InferredRefusalReasonOption = inferredRefusalReason; + _IsCardCommercialOption = isCardCommercial; + _IssuerCountryOption = issuerCountry; + _LiabilityShiftOption = liabilityShift; + _McBankNetReferenceNumberOption = mcBankNetReferenceNumber; + _MerchantAdviceCodeOption = merchantAdviceCode; + _MerchantReferenceOption = merchantReference; + _NetworkTxReferenceOption = networkTxReference; + _OwnerNameOption = ownerName; + _PaymentAccountReferenceOption = paymentAccountReference; + _PaymentMethodOption = paymentMethod; + _PaymentMethodVariantOption = paymentMethodVariant; + _PayoutEligibleOption = payoutEligible; + _RealtimeAccountUpdaterStatusOption = realtimeAccountUpdaterStatus; + _ReceiptFreeTextOption = receiptFreeText; + _RecurringContractTypesOption = recurringContractTypes; + _RecurringFirstPspReferenceOption = recurringFirstPspReference; + _RecurringRecurringDetailReferenceOption = recurringRecurringDetailReference; + _RecurringShopperReferenceOption = recurringShopperReference; + _RecurringProcessingModelOption = recurringProcessingModel; + _ReferredOption = referred; + _RefusalReasonRawOption = refusalReasonRaw; + _RequestAmountOption = requestAmount; + _RequestCurrencyCodeOption = requestCurrencyCode; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _TerminalIdOption = terminalId; + _ThreeDAuthenticatedOption = threeDAuthenticated; + _ThreeDAuthenticatedResponseOption = threeDAuthenticatedResponse; + _ThreeDOfferedOption = threeDOffered; + _ThreeDOfferedResponseOption = threeDOfferedResponse; + _ThreeDSVersionOption = threeDSVersion; + _TokenizationShopperReferenceOption = tokenizationShopperReference; + _TokenizationStoreOperationTypeOption = tokenizationStoreOperationType; + _TokenizationStoredPaymentMethodIdOption = tokenizationStoredPaymentMethodId; + _VisaTransactionIdOption = visaTransactionId; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCommon() + { + } + + partial void OnCreated(); + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonConverter(typeof(FraudResultTypeEnumJsonConverter))] + public class FraudResultTypeEnum : IEnum + { + /// + /// Returns the value of the FraudResultTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FraudResultTypeEnum.GREEN - GREEN + /// + public static readonly FraudResultTypeEnum GREEN = new("GREEN"); + + /// + /// FraudResultTypeEnum.FRAUD - FRAUD + /// + public static readonly FraudResultTypeEnum FRAUD = new("FRAUD"); + + private FraudResultTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudResultTypeEnum?(string? value) => value == null ? null : new FraudResultTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudResultTypeEnum? option) => option?.Value; + + public static bool operator ==(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudResultTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudResultTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "GREEN" => FraudResultTypeEnum.GREEN, + "FRAUD" => FraudResultTypeEnum.FRAUD, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudResultTypeEnum? value) + { + if (value == null) + return null; + + if (value == FraudResultTypeEnum.GREEN) + return "GREEN"; + + if (value == FraudResultTypeEnum.FRAUD) + return "FRAUD"; + + return null; + } + + /// + /// JsonConverter for writing FraudResultTypeEnum. + /// + public class FraudResultTypeEnumJsonConverter : JsonConverter + { + public override FraudResultTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudResultTypeEnum.FromStringOrDefault(value) ?? new FraudResultTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudResultTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudResultTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultTypeOption { get; private set; } + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonPropertyName("fraudResultType")] + public FraudResultTypeEnum? FraudResultType { get { return this._FraudResultTypeOption; } set { this._FraudResultTypeOption = new(value); } } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonConverter(typeof(FraudRiskLevelEnumJsonConverter))] + public class FraudRiskLevelEnum : IEnum + { + /// + /// Returns the value of the FraudRiskLevelEnum. + /// + public string? Value { get; set; } + + /// + /// FraudRiskLevelEnum.VeryLow - veryLow + /// + public static readonly FraudRiskLevelEnum VeryLow = new("veryLow"); + + /// + /// FraudRiskLevelEnum.Low - low + /// + public static readonly FraudRiskLevelEnum Low = new("low"); + + /// + /// FraudRiskLevelEnum.Medium - medium + /// + public static readonly FraudRiskLevelEnum Medium = new("medium"); + + /// + /// FraudRiskLevelEnum.High - high + /// + public static readonly FraudRiskLevelEnum High = new("high"); + + /// + /// FraudRiskLevelEnum.VeryHigh - veryHigh + /// + public static readonly FraudRiskLevelEnum VeryHigh = new("veryHigh"); + + private FraudRiskLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudRiskLevelEnum?(string? value) => value == null ? null : new FraudRiskLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudRiskLevelEnum? option) => option?.Value; + + public static bool operator ==(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudRiskLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudRiskLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "veryLow" => FraudRiskLevelEnum.VeryLow, + "low" => FraudRiskLevelEnum.Low, + "medium" => FraudRiskLevelEnum.Medium, + "high" => FraudRiskLevelEnum.High, + "veryHigh" => FraudRiskLevelEnum.VeryHigh, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudRiskLevelEnum? value) + { + if (value == null) + return null; + + if (value == FraudRiskLevelEnum.VeryLow) + return "veryLow"; + + if (value == FraudRiskLevelEnum.Low) + return "low"; + + if (value == FraudRiskLevelEnum.Medium) + return "medium"; + + if (value == FraudRiskLevelEnum.High) + return "high"; + + if (value == FraudRiskLevelEnum.VeryHigh) + return "veryHigh"; + + return null; + } + + /// + /// JsonConverter for writing FraudRiskLevelEnum. + /// + public class FraudRiskLevelEnumJsonConverter : JsonConverter + { + public override FraudRiskLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudRiskLevelEnum.FromStringOrDefault(value) ?? new FraudRiskLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudRiskLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudRiskLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudRiskLevelOption { get; private set; } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonPropertyName("fraudRiskLevel")] + public FraudRiskLevelEnum? FraudRiskLevel { get { return this._FraudRiskLevelOption; } set { this._FraudRiskLevelOption = new(value); } } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonConverter(typeof(TokenizationStoreOperationTypeEnumJsonConverter))] + public class TokenizationStoreOperationTypeEnum : IEnum + { + /// + /// Returns the value of the TokenizationStoreOperationTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TokenizationStoreOperationTypeEnum.Created - created + /// + public static readonly TokenizationStoreOperationTypeEnum Created = new("created"); + + /// + /// TokenizationStoreOperationTypeEnum.Updated - updated + /// + public static readonly TokenizationStoreOperationTypeEnum Updated = new("updated"); + + /// + /// TokenizationStoreOperationTypeEnum.AlreadyExisting - alreadyExisting + /// + public static readonly TokenizationStoreOperationTypeEnum AlreadyExisting = new("alreadyExisting"); + + private TokenizationStoreOperationTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenizationStoreOperationTypeEnum?(string? value) => value == null ? null : new TokenizationStoreOperationTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenizationStoreOperationTypeEnum? option) => option?.Value; + + public static bool operator ==(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenizationStoreOperationTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenizationStoreOperationTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "created" => TokenizationStoreOperationTypeEnum.Created, + "updated" => TokenizationStoreOperationTypeEnum.Updated, + "alreadyExisting" => TokenizationStoreOperationTypeEnum.AlreadyExisting, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenizationStoreOperationTypeEnum? value) + { + if (value == null) + return null; + + if (value == TokenizationStoreOperationTypeEnum.Created) + return "created"; + + if (value == TokenizationStoreOperationTypeEnum.Updated) + return "updated"; + + if (value == TokenizationStoreOperationTypeEnum.AlreadyExisting) + return "alreadyExisting"; + + return null; + } + + /// + /// JsonConverter for writing TokenizationStoreOperationTypeEnum. + /// + public class TokenizationStoreOperationTypeEnumJsonConverter : JsonConverter + { + public override TokenizationStoreOperationTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenizationStoreOperationTypeEnum.FromStringOrDefault(value) ?? new TokenizationStoreOperationTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenizationStoreOperationTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenizationStoreOperationTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoreOperationTypeOption { get; private set; } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonPropertyName("tokenization.store.operationType")] + public TokenizationStoreOperationTypeEnum? TokenizationStoreOperationType { get { return this._TokenizationStoreOperationTypeOption; } set { this._TokenizationStoreOperationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerAccountCodeOption { get; private set; } + + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + [JsonPropertyName("acquirerAccountCode")] + public string? AcquirerAccountCode { get { return this._AcquirerAccountCodeOption; } set { this._AcquirerAccountCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerCodeOption { get; private set; } + + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + [JsonPropertyName("acquirerCode")] + public string? AcquirerCode { get { return this._AcquirerCodeOption; } set { this._AcquirerCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerReferenceOption { get; private set; } + + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + [JsonPropertyName("acquirerReference")] + public string? AcquirerReference { get { return this._AcquirerReferenceOption; } set { this._AcquirerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasOption { get; private set; } + + /// + /// The Adyen alias of the card. Example: H167852639363479 + /// + /// The Adyen alias of the card. Example: H167852639363479 + [JsonPropertyName("alias")] + public string? Alias { get { return this._AliasOption; } set { this._AliasOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasTypeOption { get; private set; } + + /// + /// The type of the card alias. Example: Default + /// + /// The type of the card alias. Example: Default + [JsonPropertyName("aliasType")] + public string? AliasType { get { return this._AliasTypeOption; } set { this._AliasTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationMidOption { get; private set; } + + /// + /// Merchant ID known by the acquirer. + /// + /// Merchant ID known by the acquirer. + [JsonPropertyName("authorisationMid")] + public string? AuthorisationMid { get { return this._AuthorisationMidOption; } set { this._AuthorisationMidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountCurrencyOption { get; private set; } + + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountCurrency")] + public string? AuthorisedAmountCurrency { get { return this._AuthorisedAmountCurrencyOption; } set { this._AuthorisedAmountCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountValueOption { get; private set; } + + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountValue")] + public string? AuthorisedAmountValue { get { return this._AuthorisedAmountValueOption; } set { this._AuthorisedAmountValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultOption { get; private set; } + + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + [JsonPropertyName("avsResult")] + public string? AvsResult { get { return this._AvsResultOption; } set { this._AvsResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultRawOption { get; private set; } + + /// + /// Raw AVS result received from the acquirer, where available. Example: D + /// + /// Raw AVS result received from the acquirer, where available. Example: D + [JsonPropertyName("avsResultRaw")] + public string? AvsResultRaw { get { return this._AvsResultRawOption; } set { this._AvsResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CoBrandedWithOption { get; private set; } + + /// + /// Includes the co-branded card information. + /// + /// Includes the co-branded card information. + [JsonPropertyName("coBrandedWith")] + public string? CoBrandedWith { get { return this._CoBrandedWithOption; } set { this._CoBrandedWithOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultOption { get; private set; } + + /// + /// The result of CVC verification. + /// + /// The result of CVC verification. + /* 1 Matches */ + [JsonPropertyName("cvcResult")] + public string? CvcResult { get { return this._CvcResultOption; } set { this._CvcResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultRawOption { get; private set; } + + /// + /// The raw result of CVC verification. + /// + /// The raw result of CVC verification. + /* M */ + [JsonPropertyName("cvcResultRaw")] + public string? CvcResultRaw { get { return this._CvcResultRawOption; } set { this._CvcResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryDateOption { get; private set; } + + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + [JsonPropertyName("expiryDate")] + public string? ExpiryDate { get { return this._ExpiryDateOption; } set { this._ExpiryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsCurrencyOption { get; private set; } + + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + [JsonPropertyName("extraCostsCurrency")] + public string? ExtraCostsCurrency { get { return this._ExtraCostsCurrencyOption; } set { this._ExtraCostsCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsValueOption { get; private set; } + + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + [JsonPropertyName("extraCostsValue")] + public string? ExtraCostsValue { get { return this._ExtraCostsValueOption; } set { this._ExtraCostsValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudCheckItemNrFraudChecknameOption { get; private set; } + + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + [JsonPropertyName("fraudCheck-[itemNr]-[FraudCheckname]")] + public string? FraudCheckItemNrFraudCheckname { get { return this._FraudCheckItemNrFraudChecknameOption; } set { this._FraudCheckItemNrFraudChecknameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudManualReviewOption { get; private set; } + + /// + /// Indicates if the payment is sent to manual review. + /// + /// Indicates if the payment is sent to manual review. + [JsonPropertyName("fraudManualReview")] + public string? FraudManualReview { get { return this._FraudManualReviewOption; } set { this._FraudManualReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + [JsonPropertyName("fundingSource")] + public string? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundsAvailabilityOption { get; private set; } + + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + [JsonPropertyName("fundsAvailability")] + public string? FundsAvailability { get { return this._FundsAvailabilityOption; } set { this._FundsAvailabilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InferredRefusalReasonOption { get; private set; } + + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + [JsonPropertyName("inferredRefusalReason")] + public string? InferredRefusalReason { get { return this._InferredRefusalReasonOption; } set { this._InferredRefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IsCardCommercialOption { get; private set; } + + /// + /// Indicates if the card is used for business purposes only. + /// + /// Indicates if the card is used for business purposes only. + [JsonPropertyName("isCardCommercial")] + public string? IsCardCommercial { get { return this._IsCardCommercialOption; } set { this._IsCardCommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + [JsonPropertyName("issuerCountry")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LiabilityShiftOption { get; private set; } + + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + [JsonPropertyName("liabilityShift")] + public string? LiabilityShift { get { return this._LiabilityShiftOption; } set { this._LiabilityShiftOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McBankNetReferenceNumberOption { get; private set; } + + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + [JsonPropertyName("mcBankNetReferenceNumber")] + public string? McBankNetReferenceNumber { get { return this._McBankNetReferenceNumberOption; } set { this._McBankNetReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAdviceCodeOption { get; private set; } + + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + [JsonPropertyName("merchantAdviceCode")] + public string? MerchantAdviceCode { get { return this._MerchantAdviceCodeOption; } set { this._MerchantAdviceCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The reference provided for the transaction. + /// + /// The reference provided for the transaction. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountReferenceOption { get; private set; } + + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + [JsonPropertyName("paymentAccountReference")] + public string? PaymentAccountReference { get { return this._PaymentAccountReferenceOption; } set { this._PaymentAccountReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// The payment method used in the transaction. + /// + /// The payment method used in the transaction. + [JsonPropertyName("paymentMethod")] + public string? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodVariantOption { get; private set; } + + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + [JsonPropertyName("paymentMethodVariant")] + public string? PaymentMethodVariant { get { return this._PaymentMethodVariantOption; } set { this._PaymentMethodVariantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayoutEligibleOption { get; private set; } + + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + [JsonPropertyName("payoutEligible")] + public string? PayoutEligible { get { return this._PayoutEligibleOption; } set { this._PayoutEligibleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RealtimeAccountUpdaterStatusOption { get; private set; } + + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + [JsonPropertyName("realtimeAccountUpdaterStatus")] + public string? RealtimeAccountUpdaterStatus { get { return this._RealtimeAccountUpdaterStatusOption; } set { this._RealtimeAccountUpdaterStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiptFreeTextOption { get; private set; } + + /// + /// Message to be displayed on the terminal. + /// + /// Message to be displayed on the terminal. + [JsonPropertyName("receiptFreeText")] + public string? ReceiptFreeText { get { return this._ReceiptFreeTextOption; } set { this._ReceiptFreeTextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringContractTypesOption { get; private set; } + + /// + /// The recurring contract types applicable to the transaction. + /// + /// The recurring contract types applicable to the transaction. + [JsonPropertyName("recurring.contractTypes")] + public string? RecurringContractTypes { get { return this._RecurringContractTypesOption; } set { this._RecurringContractTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFirstPspReferenceOption { get; private set; } + + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + [JsonPropertyName("recurring.firstPspReference")] + public string? RecurringFirstPspReference { get { return this._RecurringFirstPspReferenceOption; } set { this._RecurringFirstPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringRecurringDetailReferenceOption { get; private set; } + + /// + /// The reference that uniquely identifies the recurring transaction. + /// + /// The reference that uniquely identifies the recurring transaction. + [JsonPropertyName("recurring.recurringDetailReference")] + [Obsolete("Deprecated since Adyen Payment API v68. Use tokenization.storedPaymentMethodId instead.")] + public string? RecurringRecurringDetailReference { get { return this._RecurringRecurringDetailReferenceOption; } set { this._RecurringRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringShopperReferenceOption { get; private set; } + + /// + /// The provided reference of the shopper for a recurring transaction. + /// + /// The provided reference of the shopper for a recurring transaction. + [JsonPropertyName("recurring.shopperReference")] + [Obsolete("Deprecated since Adyen Payment API v68. Use tokenization.shopperReference instead.")] + public string? RecurringShopperReference { get { return this._RecurringShopperReferenceOption; } set { this._RecurringShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferredOption { get; private set; } + + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + [JsonPropertyName("referred")] + public string? Referred { get { return this._ReferredOption; } set { this._ReferredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonRawOption { get; private set; } + + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + [JsonPropertyName("refusalReasonRaw")] + public string? RefusalReasonRaw { get { return this._RefusalReasonRawOption; } set { this._RefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestAmountOption { get; private set; } + + /// + /// The amount of the payment request. + /// + /// The amount of the payment request. + [JsonPropertyName("requestAmount")] + public string? RequestAmount { get { return this._RequestAmountOption; } set { this._RequestAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestCurrencyCodeOption { get; private set; } + + /// + /// The currency of the payment request. + /// + /// The currency of the payment request. + [JsonPropertyName("requestCurrencyCode")] + public string? RequestCurrencyCode { get { return this._RequestCurrencyCodeOption; } set { this._RequestCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + [JsonPropertyName("shopperInteraction")] + public string? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + [JsonPropertyName("threeDAuthenticated")] + public string? ThreeDAuthenticated { get { return this._ThreeDAuthenticatedOption; } set { this._ThreeDAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedResponseOption { get; private set; } + + /// + /// The raw 3DS authentication result from the card issuer. Example: N + /// + /// The raw 3DS authentication result from the card issuer. Example: N + [JsonPropertyName("threeDAuthenticatedResponse")] + public string? ThreeDAuthenticatedResponse { get { return this._ThreeDAuthenticatedResponseOption; } set { this._ThreeDAuthenticatedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + [JsonPropertyName("threeDOffered")] + public string? ThreeDOffered { get { return this._ThreeDOfferedOption; } set { this._ThreeDOfferedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedResponseOption { get; private set; } + + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + [JsonPropertyName("threeDOfferedResponse")] + public string? ThreeDOfferedResponse { get { return this._ThreeDOfferedResponseOption; } set { this._ThreeDOfferedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The 3D Secure 2 version. + /// + /// The 3D Secure 2 version. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationShopperReferenceOption { get; private set; } + + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + [JsonPropertyName("tokenization.shopperReference")] + public string? TokenizationShopperReference { get { return this._TokenizationShopperReferenceOption; } set { this._TokenizationShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoredPaymentMethodIdOption { get; private set; } + + /// + /// The reference that uniquely identifies tokenized payment details. + /// + /// The reference that uniquely identifies tokenized payment details. + [JsonPropertyName("tokenization.storedPaymentMethodId")] + public string? TokenizationStoredPaymentMethodId { get { return this._TokenizationStoredPaymentMethodIdOption; } set { this._TokenizationStoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaTransactionIdOption { get; private set; } + + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + [JsonPropertyName("visaTransactionId")] + public string? VisaTransactionId { get { return this._VisaTransactionIdOption; } set { this._VisaTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonPropertyName("xid")] + public string? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCommon {\n"); + sb.Append(" AcquirerAccountCode: ").Append(AcquirerAccountCode).Append("\n"); + sb.Append(" AcquirerCode: ").Append(AcquirerCode).Append("\n"); + sb.Append(" AcquirerReference: ").Append(AcquirerReference).Append("\n"); + sb.Append(" Alias: ").Append(Alias).Append("\n"); + sb.Append(" AliasType: ").Append(AliasType).Append("\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" AuthorisationMid: ").Append(AuthorisationMid).Append("\n"); + sb.Append(" AuthorisedAmountCurrency: ").Append(AuthorisedAmountCurrency).Append("\n"); + sb.Append(" AuthorisedAmountValue: ").Append(AuthorisedAmountValue).Append("\n"); + sb.Append(" AvsResult: ").Append(AvsResult).Append("\n"); + sb.Append(" AvsResultRaw: ").Append(AvsResultRaw).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CoBrandedWith: ").Append(CoBrandedWith).Append("\n"); + sb.Append(" CvcResult: ").Append(CvcResult).Append("\n"); + sb.Append(" CvcResultRaw: ").Append(CvcResultRaw).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ExpiryDate: ").Append(ExpiryDate).Append("\n"); + sb.Append(" ExtraCostsCurrency: ").Append(ExtraCostsCurrency).Append("\n"); + sb.Append(" ExtraCostsValue: ").Append(ExtraCostsValue).Append("\n"); + sb.Append(" FraudCheckItemNrFraudCheckname: ").Append(FraudCheckItemNrFraudCheckname).Append("\n"); + sb.Append(" FraudManualReview: ").Append(FraudManualReview).Append("\n"); + sb.Append(" FraudResultType: ").Append(FraudResultType).Append("\n"); + sb.Append(" FraudRiskLevel: ").Append(FraudRiskLevel).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" FundsAvailability: ").Append(FundsAvailability).Append("\n"); + sb.Append(" InferredRefusalReason: ").Append(InferredRefusalReason).Append("\n"); + sb.Append(" IsCardCommercial: ").Append(IsCardCommercial).Append("\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append(" LiabilityShift: ").Append(LiabilityShift).Append("\n"); + sb.Append(" McBankNetReferenceNumber: ").Append(McBankNetReferenceNumber).Append("\n"); + sb.Append(" MerchantAdviceCode: ").Append(MerchantAdviceCode).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" PaymentAccountReference: ").Append(PaymentAccountReference).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PaymentMethodVariant: ").Append(PaymentMethodVariant).Append("\n"); + sb.Append(" PayoutEligible: ").Append(PayoutEligible).Append("\n"); + sb.Append(" RealtimeAccountUpdaterStatus: ").Append(RealtimeAccountUpdaterStatus).Append("\n"); + sb.Append(" ReceiptFreeText: ").Append(ReceiptFreeText).Append("\n"); + sb.Append(" RecurringContractTypes: ").Append(RecurringContractTypes).Append("\n"); + sb.Append(" RecurringFirstPspReference: ").Append(RecurringFirstPspReference).Append("\n"); + sb.Append(" RecurringRecurringDetailReference: ").Append(RecurringRecurringDetailReference).Append("\n"); + sb.Append(" RecurringShopperReference: ").Append(RecurringShopperReference).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" Referred: ").Append(Referred).Append("\n"); + sb.Append(" RefusalReasonRaw: ").Append(RefusalReasonRaw).Append("\n"); + sb.Append(" RequestAmount: ").Append(RequestAmount).Append("\n"); + sb.Append(" RequestCurrencyCode: ").Append(RequestCurrencyCode).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append(" ThreeDAuthenticated: ").Append(ThreeDAuthenticated).Append("\n"); + sb.Append(" ThreeDAuthenticatedResponse: ").Append(ThreeDAuthenticatedResponse).Append("\n"); + sb.Append(" ThreeDOffered: ").Append(ThreeDOffered).Append("\n"); + sb.Append(" ThreeDOfferedResponse: ").Append(ThreeDOfferedResponse).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append(" TokenizationShopperReference: ").Append(TokenizationShopperReference).Append("\n"); + sb.Append(" TokenizationStoreOperationType: ").Append(TokenizationStoreOperationType).Append("\n"); + sb.Append(" TokenizationStoredPaymentMethodId: ").Append(TokenizationStoredPaymentMethodId).Append("\n"); + sb.Append(" VisaTransactionId: ").Append(VisaTransactionId).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCommonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCommon Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerAccountCode = default; + Option acquirerCode = default; + Option acquirerReference = default; + Option alias = default; + Option aliasType = default; + Option authCode = default; + Option authorisationMid = default; + Option authorisedAmountCurrency = default; + Option authorisedAmountValue = default; + Option avsResult = default; + Option avsResultRaw = default; + Option bic = default; + Option coBrandedWith = default; + Option cvcResult = default; + Option cvcResultRaw = default; + Option dsTransID = default; + Option eci = default; + Option expiryDate = default; + Option extraCostsCurrency = default; + Option extraCostsValue = default; + Option fraudCheckItemNrFraudCheckname = default; + Option fraudManualReview = default; + Option fraudResultType = default; + Option fraudRiskLevel = default; + Option fundingSource = default; + Option fundsAvailability = default; + Option inferredRefusalReason = default; + Option isCardCommercial = default; + Option issuerCountry = default; + Option liabilityShift = default; + Option mcBankNetReferenceNumber = default; + Option merchantAdviceCode = default; + Option merchantReference = default; + Option networkTxReference = default; + Option ownerName = default; + Option paymentAccountReference = default; + Option paymentMethod = default; + Option paymentMethodVariant = default; + Option payoutEligible = default; + Option realtimeAccountUpdaterStatus = default; + Option receiptFreeText = default; + Option recurringContractTypes = default; + Option recurringFirstPspReference = default; + Option recurringRecurringDetailReference = default; + Option recurringShopperReference = default; + Option recurringProcessingModel = default; + Option referred = default; + Option refusalReasonRaw = default; + Option requestAmount = default; + Option requestCurrencyCode = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option terminalId = default; + Option threeDAuthenticated = default; + Option threeDAuthenticatedResponse = default; + Option threeDOffered = default; + Option threeDOfferedResponse = default; + Option threeDSVersion = default; + Option tokenizationShopperReference = default; + Option tokenizationStoreOperationType = default; + Option tokenizationStoredPaymentMethodId = default; + Option visaTransactionId = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerAccountCode": + acquirerAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerCode": + acquirerCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerReference": + acquirerReference = new Option(utf8JsonReader.GetString()!); + break; + case "alias": + alias = new Option(utf8JsonReader.GetString()!); + break; + case "aliasType": + aliasType = new Option(utf8JsonReader.GetString()!); + break; + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "authorisationMid": + authorisationMid = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountCurrency": + authorisedAmountCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountValue": + authorisedAmountValue = new Option(utf8JsonReader.GetString()!); + break; + case "avsResult": + avsResult = new Option(utf8JsonReader.GetString()!); + break; + case "avsResultRaw": + avsResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "coBrandedWith": + coBrandedWith = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResult": + cvcResult = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResultRaw": + cvcResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "expiryDate": + expiryDate = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsCurrency": + extraCostsCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsValue": + extraCostsValue = new Option(utf8JsonReader.GetString()!); + break; + case "fraudCheck-[itemNr]-[FraudCheckname]": + fraudCheckItemNrFraudCheckname = new Option(utf8JsonReader.GetString()!); + break; + case "fraudManualReview": + fraudManualReview = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResultType": + string? fraudResultTypeRawValue = utf8JsonReader.GetString(); + fraudResultType = new Option(ResponseAdditionalDataCommon.FraudResultTypeEnum.FromStringOrDefault(fraudResultTypeRawValue)); + break; + case "fraudRiskLevel": + string? fraudRiskLevelRawValue = utf8JsonReader.GetString(); + fraudRiskLevel = new Option(ResponseAdditionalDataCommon.FraudRiskLevelEnum.FromStringOrDefault(fraudRiskLevelRawValue)); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "fundsAvailability": + fundsAvailability = new Option(utf8JsonReader.GetString()!); + break; + case "inferredRefusalReason": + inferredRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "isCardCommercial": + isCardCommercial = new Option(utf8JsonReader.GetString()!); + break; + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + case "liabilityShift": + liabilityShift = new Option(utf8JsonReader.GetString()!); + break; + case "mcBankNetReferenceNumber": + mcBankNetReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAdviceCode": + merchantAdviceCode = new Option(utf8JsonReader.GetString()!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccountReference": + paymentAccountReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodVariant": + paymentMethodVariant = new Option(utf8JsonReader.GetString()!); + break; + case "payoutEligible": + payoutEligible = new Option(utf8JsonReader.GetString()!); + break; + case "realtimeAccountUpdaterStatus": + realtimeAccountUpdaterStatus = new Option(utf8JsonReader.GetString()!); + break; + case "receiptFreeText": + receiptFreeText = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.contractTypes": + recurringContractTypes = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.firstPspReference": + recurringFirstPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.recurringDetailReference": + recurringRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.shopperReference": + recurringShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(ResponseAdditionalDataCommon.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "referred": + referred = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReasonRaw": + refusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "requestAmount": + requestAmount = new Option(utf8JsonReader.GetString()!); + break; + case "requestCurrencyCode": + requestCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + shopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticated": + threeDAuthenticated = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticatedResponse": + threeDAuthenticatedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOffered": + threeDOffered = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOfferedResponse": + threeDOfferedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.shopperReference": + tokenizationShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.store.operationType": + string? tokenizationStoreOperationTypeRawValue = utf8JsonReader.GetString(); + tokenizationStoreOperationType = new Option(ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.FromStringOrDefault(tokenizationStoreOperationTypeRawValue)); + break; + case "tokenization.storedPaymentMethodId": + tokenizationStoredPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "visaTransactionId": + visaTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCommon(acquirerAccountCode, acquirerCode, acquirerReference, alias, aliasType, authCode, authorisationMid, authorisedAmountCurrency, authorisedAmountValue, avsResult, avsResultRaw, bic, coBrandedWith, cvcResult, cvcResultRaw, dsTransID, eci, expiryDate, extraCostsCurrency, extraCostsValue, fraudCheckItemNrFraudCheckname, fraudManualReview, fraudResultType, fraudRiskLevel, fundingSource, fundsAvailability, inferredRefusalReason, isCardCommercial, issuerCountry, liabilityShift, mcBankNetReferenceNumber, merchantAdviceCode, merchantReference, networkTxReference, ownerName, paymentAccountReference, paymentMethod, paymentMethodVariant, payoutEligible, realtimeAccountUpdaterStatus, receiptFreeText, recurringContractTypes, recurringFirstPspReference, recurringRecurringDetailReference, recurringShopperReference, recurringProcessingModel, referred, refusalReasonRaw, requestAmount, requestCurrencyCode, shopperInteraction, shopperReference, terminalId, threeDAuthenticated, threeDAuthenticatedResponse, threeDOffered, threeDOfferedResponse, threeDSVersion, tokenizationShopperReference, tokenizationStoreOperationType, tokenizationStoredPaymentMethodId, visaTransactionId, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCommon, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCommon._AcquirerAccountCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerAccountCode != null) + writer.WriteString("acquirerAccountCode", responseAdditionalDataCommon.AcquirerAccountCode); + + if (responseAdditionalDataCommon._AcquirerCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerCode != null) + writer.WriteString("acquirerCode", responseAdditionalDataCommon.AcquirerCode); + + if (responseAdditionalDataCommon._AcquirerReferenceOption.IsSet) + if (responseAdditionalDataCommon.AcquirerReference != null) + writer.WriteString("acquirerReference", responseAdditionalDataCommon.AcquirerReference); + + if (responseAdditionalDataCommon._AliasOption.IsSet) + if (responseAdditionalDataCommon.Alias != null) + writer.WriteString("alias", responseAdditionalDataCommon.Alias); + + if (responseAdditionalDataCommon._AliasTypeOption.IsSet) + if (responseAdditionalDataCommon.AliasType != null) + writer.WriteString("aliasType", responseAdditionalDataCommon.AliasType); + + if (responseAdditionalDataCommon._AuthCodeOption.IsSet) + if (responseAdditionalDataCommon.AuthCode != null) + writer.WriteString("authCode", responseAdditionalDataCommon.AuthCode); + + if (responseAdditionalDataCommon._AuthorisationMidOption.IsSet) + if (responseAdditionalDataCommon.AuthorisationMid != null) + writer.WriteString("authorisationMid", responseAdditionalDataCommon.AuthorisationMid); + + if (responseAdditionalDataCommon._AuthorisedAmountCurrencyOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountCurrency != null) + writer.WriteString("authorisedAmountCurrency", responseAdditionalDataCommon.AuthorisedAmountCurrency); + + if (responseAdditionalDataCommon._AuthorisedAmountValueOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountValue != null) + writer.WriteString("authorisedAmountValue", responseAdditionalDataCommon.AuthorisedAmountValue); + + if (responseAdditionalDataCommon._AvsResultOption.IsSet) + if (responseAdditionalDataCommon.AvsResult != null) + writer.WriteString("avsResult", responseAdditionalDataCommon.AvsResult); + + if (responseAdditionalDataCommon._AvsResultRawOption.IsSet) + if (responseAdditionalDataCommon.AvsResultRaw != null) + writer.WriteString("avsResultRaw", responseAdditionalDataCommon.AvsResultRaw); + + if (responseAdditionalDataCommon._BicOption.IsSet) + if (responseAdditionalDataCommon.Bic != null) + writer.WriteString("bic", responseAdditionalDataCommon.Bic); + + if (responseAdditionalDataCommon._CoBrandedWithOption.IsSet) + if (responseAdditionalDataCommon.CoBrandedWith != null) + writer.WriteString("coBrandedWith", responseAdditionalDataCommon.CoBrandedWith); + + if (responseAdditionalDataCommon._CvcResultOption.IsSet) + if (responseAdditionalDataCommon.CvcResult != null) + writer.WriteString("cvcResult", responseAdditionalDataCommon.CvcResult); + + if (responseAdditionalDataCommon._CvcResultRawOption.IsSet) + if (responseAdditionalDataCommon.CvcResultRaw != null) + writer.WriteString("cvcResultRaw", responseAdditionalDataCommon.CvcResultRaw); + + if (responseAdditionalDataCommon._DsTransIDOption.IsSet) + if (responseAdditionalDataCommon.DsTransID != null) + writer.WriteString("dsTransID", responseAdditionalDataCommon.DsTransID); + + if (responseAdditionalDataCommon._EciOption.IsSet) + if (responseAdditionalDataCommon.Eci != null) + writer.WriteString("eci", responseAdditionalDataCommon.Eci); + + if (responseAdditionalDataCommon._ExpiryDateOption.IsSet) + if (responseAdditionalDataCommon.ExpiryDate != null) + writer.WriteString("expiryDate", responseAdditionalDataCommon.ExpiryDate); + + if (responseAdditionalDataCommon._ExtraCostsCurrencyOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsCurrency != null) + writer.WriteString("extraCostsCurrency", responseAdditionalDataCommon.ExtraCostsCurrency); + + if (responseAdditionalDataCommon._ExtraCostsValueOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsValue != null) + writer.WriteString("extraCostsValue", responseAdditionalDataCommon.ExtraCostsValue); + + if (responseAdditionalDataCommon._FraudCheckItemNrFraudChecknameOption.IsSet) + if (responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname != null) + writer.WriteString("fraudCheck-[itemNr]-[FraudCheckname]", responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname); + + if (responseAdditionalDataCommon._FraudManualReviewOption.IsSet) + if (responseAdditionalDataCommon.FraudManualReview != null) + writer.WriteString("fraudManualReview", responseAdditionalDataCommon.FraudManualReview); + + if (responseAdditionalDataCommon._FraudResultTypeOption.IsSet && responseAdditionalDataCommon.FraudResultType != null) + { + string? fraudResultTypeRawValue = ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommon._FraudResultTypeOption.Value!.Value); + writer.WriteString("fraudResultType", fraudResultTypeRawValue); + } + + if (responseAdditionalDataCommon._FraudRiskLevelOption.IsSet && responseAdditionalDataCommon.FraudRiskLevel != null) + { + string? fraudRiskLevelRawValue = ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommon._FraudRiskLevelOption.Value!.Value); + writer.WriteString("fraudRiskLevel", fraudRiskLevelRawValue); + } + + if (responseAdditionalDataCommon._FundingSourceOption.IsSet) + if (responseAdditionalDataCommon.FundingSource != null) + writer.WriteString("fundingSource", responseAdditionalDataCommon.FundingSource); + + if (responseAdditionalDataCommon._FundsAvailabilityOption.IsSet) + if (responseAdditionalDataCommon.FundsAvailability != null) + writer.WriteString("fundsAvailability", responseAdditionalDataCommon.FundsAvailability); + + if (responseAdditionalDataCommon._InferredRefusalReasonOption.IsSet) + if (responseAdditionalDataCommon.InferredRefusalReason != null) + writer.WriteString("inferredRefusalReason", responseAdditionalDataCommon.InferredRefusalReason); + + if (responseAdditionalDataCommon._IsCardCommercialOption.IsSet) + if (responseAdditionalDataCommon.IsCardCommercial != null) + writer.WriteString("isCardCommercial", responseAdditionalDataCommon.IsCardCommercial); + + if (responseAdditionalDataCommon._IssuerCountryOption.IsSet) + if (responseAdditionalDataCommon.IssuerCountry != null) + writer.WriteString("issuerCountry", responseAdditionalDataCommon.IssuerCountry); + + if (responseAdditionalDataCommon._LiabilityShiftOption.IsSet) + if (responseAdditionalDataCommon.LiabilityShift != null) + writer.WriteString("liabilityShift", responseAdditionalDataCommon.LiabilityShift); + + if (responseAdditionalDataCommon._McBankNetReferenceNumberOption.IsSet) + if (responseAdditionalDataCommon.McBankNetReferenceNumber != null) + writer.WriteString("mcBankNetReferenceNumber", responseAdditionalDataCommon.McBankNetReferenceNumber); + + if (responseAdditionalDataCommon._MerchantAdviceCodeOption.IsSet) + if (responseAdditionalDataCommon.MerchantAdviceCode != null) + writer.WriteString("merchantAdviceCode", responseAdditionalDataCommon.MerchantAdviceCode); + + if (responseAdditionalDataCommon._MerchantReferenceOption.IsSet) + if (responseAdditionalDataCommon.MerchantReference != null) + writer.WriteString("merchantReference", responseAdditionalDataCommon.MerchantReference); + + if (responseAdditionalDataCommon._NetworkTxReferenceOption.IsSet) + if (responseAdditionalDataCommon.NetworkTxReference != null) + writer.WriteString("networkTxReference", responseAdditionalDataCommon.NetworkTxReference); + + if (responseAdditionalDataCommon._OwnerNameOption.IsSet) + if (responseAdditionalDataCommon.OwnerName != null) + writer.WriteString("ownerName", responseAdditionalDataCommon.OwnerName); + + if (responseAdditionalDataCommon._PaymentAccountReferenceOption.IsSet) + if (responseAdditionalDataCommon.PaymentAccountReference != null) + writer.WriteString("paymentAccountReference", responseAdditionalDataCommon.PaymentAccountReference); + + if (responseAdditionalDataCommon._PaymentMethodOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethod != null) + writer.WriteString("paymentMethod", responseAdditionalDataCommon.PaymentMethod); + + if (responseAdditionalDataCommon._PaymentMethodVariantOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethodVariant != null) + writer.WriteString("paymentMethodVariant", responseAdditionalDataCommon.PaymentMethodVariant); + + if (responseAdditionalDataCommon._PayoutEligibleOption.IsSet) + if (responseAdditionalDataCommon.PayoutEligible != null) + writer.WriteString("payoutEligible", responseAdditionalDataCommon.PayoutEligible); + + if (responseAdditionalDataCommon._RealtimeAccountUpdaterStatusOption.IsSet) + if (responseAdditionalDataCommon.RealtimeAccountUpdaterStatus != null) + writer.WriteString("realtimeAccountUpdaterStatus", responseAdditionalDataCommon.RealtimeAccountUpdaterStatus); + + if (responseAdditionalDataCommon._ReceiptFreeTextOption.IsSet) + if (responseAdditionalDataCommon.ReceiptFreeText != null) + writer.WriteString("receiptFreeText", responseAdditionalDataCommon.ReceiptFreeText); + + if (responseAdditionalDataCommon._RecurringContractTypesOption.IsSet) + if (responseAdditionalDataCommon.RecurringContractTypes != null) + writer.WriteString("recurring.contractTypes", responseAdditionalDataCommon.RecurringContractTypes); + + if (responseAdditionalDataCommon._RecurringFirstPspReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringFirstPspReference != null) + writer.WriteString("recurring.firstPspReference", responseAdditionalDataCommon.RecurringFirstPspReference); + + if (responseAdditionalDataCommon._RecurringRecurringDetailReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringRecurringDetailReference != null) + writer.WriteString("recurring.recurringDetailReference", responseAdditionalDataCommon.RecurringRecurringDetailReference); + + if (responseAdditionalDataCommon._RecurringShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringShopperReference != null) + writer.WriteString("recurring.shopperReference", responseAdditionalDataCommon.RecurringShopperReference); + + if (responseAdditionalDataCommon._RecurringProcessingModelOption.IsSet && responseAdditionalDataCommon.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommon._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (responseAdditionalDataCommon._ReferredOption.IsSet) + if (responseAdditionalDataCommon.Referred != null) + writer.WriteString("referred", responseAdditionalDataCommon.Referred); + + if (responseAdditionalDataCommon._RefusalReasonRawOption.IsSet) + if (responseAdditionalDataCommon.RefusalReasonRaw != null) + writer.WriteString("refusalReasonRaw", responseAdditionalDataCommon.RefusalReasonRaw); + + if (responseAdditionalDataCommon._RequestAmountOption.IsSet) + if (responseAdditionalDataCommon.RequestAmount != null) + writer.WriteString("requestAmount", responseAdditionalDataCommon.RequestAmount); + + if (responseAdditionalDataCommon._RequestCurrencyCodeOption.IsSet) + if (responseAdditionalDataCommon.RequestCurrencyCode != null) + writer.WriteString("requestCurrencyCode", responseAdditionalDataCommon.RequestCurrencyCode); + + if (responseAdditionalDataCommon._ShopperInteractionOption.IsSet) + if (responseAdditionalDataCommon.ShopperInteraction != null) + writer.WriteString("shopperInteraction", responseAdditionalDataCommon.ShopperInteraction); + + if (responseAdditionalDataCommon._ShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.ShopperReference != null) + writer.WriteString("shopperReference", responseAdditionalDataCommon.ShopperReference); + + if (responseAdditionalDataCommon._TerminalIdOption.IsSet) + if (responseAdditionalDataCommon.TerminalId != null) + writer.WriteString("terminalId", responseAdditionalDataCommon.TerminalId); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticated != null) + writer.WriteString("threeDAuthenticated", responseAdditionalDataCommon.ThreeDAuthenticated); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticatedResponse != null) + writer.WriteString("threeDAuthenticatedResponse", responseAdditionalDataCommon.ThreeDAuthenticatedResponse); + + if (responseAdditionalDataCommon._ThreeDOfferedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOffered != null) + writer.WriteString("threeDOffered", responseAdditionalDataCommon.ThreeDOffered); + + if (responseAdditionalDataCommon._ThreeDOfferedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOfferedResponse != null) + writer.WriteString("threeDOfferedResponse", responseAdditionalDataCommon.ThreeDOfferedResponse); + + if (responseAdditionalDataCommon._ThreeDSVersionOption.IsSet) + if (responseAdditionalDataCommon.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", responseAdditionalDataCommon.ThreeDSVersion); + + if (responseAdditionalDataCommon._TokenizationShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.TokenizationShopperReference != null) + writer.WriteString("tokenization.shopperReference", responseAdditionalDataCommon.TokenizationShopperReference); + + if (responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.IsSet && responseAdditionalDataCommon.TokenizationStoreOperationType != null) + { + string? tokenizationStoreOperationTypeRawValue = ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.Value!.Value); + writer.WriteString("tokenization.store.operationType", tokenizationStoreOperationTypeRawValue); + } + + if (responseAdditionalDataCommon._TokenizationStoredPaymentMethodIdOption.IsSet) + if (responseAdditionalDataCommon.TokenizationStoredPaymentMethodId != null) + writer.WriteString("tokenization.storedPaymentMethodId", responseAdditionalDataCommon.TokenizationStoredPaymentMethodId); + + if (responseAdditionalDataCommon._VisaTransactionIdOption.IsSet) + if (responseAdditionalDataCommon.VisaTransactionId != null) + writer.WriteString("visaTransactionId", responseAdditionalDataCommon.VisaTransactionId); + + if (responseAdditionalDataCommon._XidOption.IsSet) + if (responseAdditionalDataCommon.Xid != null) + writer.WriteString("xid", responseAdditionalDataCommon.Xid); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataDomesticError.cs b/Adyen/Payment/Models/ResponseAdditionalDataDomesticError.cs new file mode 100644 index 000000000..ae8e6a62f --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataDomesticError.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataDomesticError. + /// + public partial class ResponseAdditionalDataDomesticError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonConstructor] + public ResponseAdditionalDataDomesticError(Option domesticRefusalReasonRaw = default, Option domesticShopperAdvice = default) + { + _DomesticRefusalReasonRawOption = domesticRefusalReasonRaw; + _DomesticShopperAdviceOption = domesticShopperAdvice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataDomesticError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticRefusalReasonRawOption { get; private set; } + + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + [JsonPropertyName("domesticRefusalReasonRaw")] + public string? DomesticRefusalReasonRaw { get { return this._DomesticRefusalReasonRawOption; } set { this._DomesticRefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticShopperAdviceOption { get; private set; } + + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonPropertyName("domesticShopperAdvice")] + public string? DomesticShopperAdvice { get { return this._DomesticShopperAdviceOption; } set { this._DomesticShopperAdviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataDomesticError {\n"); + sb.Append(" DomesticRefusalReasonRaw: ").Append(DomesticRefusalReasonRaw).Append("\n"); + sb.Append(" DomesticShopperAdvice: ").Append(DomesticShopperAdvice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataDomesticErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataDomesticError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option domesticRefusalReasonRaw = default; + Option domesticShopperAdvice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domesticRefusalReasonRaw": + domesticRefusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "domesticShopperAdvice": + domesticShopperAdvice = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataDomesticError(domesticRefusalReasonRaw, domesticShopperAdvice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataDomesticError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataDomesticError._DomesticRefusalReasonRawOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticRefusalReasonRaw != null) + writer.WriteString("domesticRefusalReasonRaw", responseAdditionalDataDomesticError.DomesticRefusalReasonRaw); + + if (responseAdditionalDataDomesticError._DomesticShopperAdviceOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticShopperAdvice != null) + writer.WriteString("domesticShopperAdvice", responseAdditionalDataDomesticError.DomesticShopperAdvice); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataInstallments.cs b/Adyen/Payment/Models/ResponseAdditionalDataInstallments.cs new file mode 100644 index 000000000..1daab6523 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataInstallments.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataInstallments. + /// + public partial class ResponseAdditionalDataInstallments : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// Annual interest rate. + /// First Installment Amount in minor units. + /// Installment fee amount in minor units. + /// Interest rate for the installment period. + /// Maximum number of installments possible for this payment. + /// Minimum number of installments possible for this payment. + /// Total number of installments possible for this payment. + /// Subsequent Installment Amount in minor units. + /// Total amount in minor units. + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonConstructor] + public ResponseAdditionalDataInstallments(Option installmentPaymentDataInstallmentType = default, Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default, Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default, Option installmentPaymentDataOptionItemNrInstallmentFee = default, Option installmentPaymentDataOptionItemNrInterestRate = default, Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default, Option installmentPaymentDataOptionItemNrTotalAmountDue = default, Option installmentPaymentDataPaymentOptions = default, Option installmentsValue = default) + { + _InstallmentPaymentDataInstallmentTypeOption = installmentPaymentDataInstallmentType; + _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = installmentPaymentDataOptionItemNrAnnualPercentageRate; + _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = installmentPaymentDataOptionItemNrFirstInstallmentAmount; + _InstallmentPaymentDataOptionItemNrInstallmentFeeOption = installmentPaymentDataOptionItemNrInstallmentFee; + _InstallmentPaymentDataOptionItemNrInterestRateOption = installmentPaymentDataOptionItemNrInterestRate; + _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMaximumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMinimumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = installmentPaymentDataOptionItemNrSubsequentInstallmentAmount; + _InstallmentPaymentDataOptionItemNrTotalAmountDueOption = installmentPaymentDataOptionItemNrTotalAmountDue; + _InstallmentPaymentDataPaymentOptionsOption = installmentPaymentDataPaymentOptions; + _InstallmentsValueOption = installmentsValue; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataInstallments() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataInstallmentTypeOption { get; private set; } + + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + [JsonPropertyName("installmentPaymentData.installmentType")] + public string? InstallmentPaymentDataInstallmentType { get { return this._InstallmentPaymentDataInstallmentTypeOption; } set { this._InstallmentPaymentDataInstallmentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption { get; private set; } + + /// + /// Annual interest rate. + /// + /// Annual interest rate. + [JsonPropertyName("installmentPaymentData.option[itemNr].annualPercentageRate")] + public string? InstallmentPaymentDataOptionItemNrAnnualPercentageRate { get { return this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption; } set { this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption { get; private set; } + + /// + /// First Installment Amount in minor units. + /// + /// First Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].firstInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrFirstInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInstallmentFeeOption { get; private set; } + + /// + /// Installment fee amount in minor units. + /// + /// Installment fee amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].installmentFee")] + public string? InstallmentPaymentDataOptionItemNrInstallmentFee { get { return this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption; } set { this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInterestRateOption { get; private set; } + + /// + /// Interest rate for the installment period. + /// + /// Interest rate for the installment period. + [JsonPropertyName("installmentPaymentData.option[itemNr].interestRate")] + public string? InstallmentPaymentDataOptionItemNrInterestRate { get { return this._InstallmentPaymentDataOptionItemNrInterestRateOption; } set { this._InstallmentPaymentDataOptionItemNrInterestRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption { get; private set; } + + /// + /// Maximum number of installments possible for this payment. + /// + /// Maximum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].maximumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption { get; private set; } + + /// + /// Minimum number of installments possible for this payment. + /// + /// Minimum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].minimumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption { get; private set; } + + /// + /// Total number of installments possible for this payment. + /// + /// Total number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].numberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption { get; private set; } + + /// + /// Subsequent Installment Amount in minor units. + /// + /// Subsequent Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].subsequentInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrTotalAmountDueOption { get; private set; } + + /// + /// Total amount in minor units. + /// + /// Total amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].totalAmountDue")] + public string? InstallmentPaymentDataOptionItemNrTotalAmountDue { get { return this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption; } set { this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataPaymentOptionsOption { get; private set; } + + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + [JsonPropertyName("installmentPaymentData.paymentOptions")] + public string? InstallmentPaymentDataPaymentOptions { get { return this._InstallmentPaymentDataPaymentOptionsOption; } set { this._InstallmentPaymentDataPaymentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsValueOption { get; private set; } + + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonPropertyName("installments.value")] + public string? InstallmentsValue { get { return this._InstallmentsValueOption; } set { this._InstallmentsValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataInstallments {\n"); + sb.Append(" InstallmentPaymentDataInstallmentType: ").Append(InstallmentPaymentDataInstallmentType).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrAnnualPercentageRate: ").Append(InstallmentPaymentDataOptionItemNrAnnualPercentageRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrFirstInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrFirstInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInstallmentFee: ").Append(InstallmentPaymentDataOptionItemNrInstallmentFee).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInterestRate: ").Append(InstallmentPaymentDataOptionItemNrInterestRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrTotalAmountDue: ").Append(InstallmentPaymentDataOptionItemNrTotalAmountDue).Append("\n"); + sb.Append(" InstallmentPaymentDataPaymentOptions: ").Append(InstallmentPaymentDataPaymentOptions).Append("\n"); + sb.Append(" InstallmentsValue: ").Append(InstallmentsValue).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataInstallmentsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataInstallments Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option installmentPaymentDataInstallmentType = default; + Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default; + Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrInstallmentFee = default; + Option installmentPaymentDataOptionItemNrInterestRate = default; + Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrTotalAmountDue = default; + Option installmentPaymentDataPaymentOptions = default; + Option installmentsValue = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "installmentPaymentData.installmentType": + installmentPaymentDataInstallmentType = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].annualPercentageRate": + installmentPaymentDataOptionItemNrAnnualPercentageRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].firstInstallmentAmount": + installmentPaymentDataOptionItemNrFirstInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].installmentFee": + installmentPaymentDataOptionItemNrInstallmentFee = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].interestRate": + installmentPaymentDataOptionItemNrInterestRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].maximumNumberOfInstallments": + installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].minimumNumberOfInstallments": + installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].numberOfInstallments": + installmentPaymentDataOptionItemNrNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].subsequentInstallmentAmount": + installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].totalAmountDue": + installmentPaymentDataOptionItemNrTotalAmountDue = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.paymentOptions": + installmentPaymentDataPaymentOptions = new Option(utf8JsonReader.GetString()!); + break; + case "installments.value": + installmentsValue = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataInstallments(installmentPaymentDataInstallmentType, installmentPaymentDataOptionItemNrAnnualPercentageRate, installmentPaymentDataOptionItemNrFirstInstallmentAmount, installmentPaymentDataOptionItemNrInstallmentFee, installmentPaymentDataOptionItemNrInterestRate, installmentPaymentDataOptionItemNrMaximumNumberOfInstallments, installmentPaymentDataOptionItemNrMinimumNumberOfInstallments, installmentPaymentDataOptionItemNrNumberOfInstallments, installmentPaymentDataOptionItemNrSubsequentInstallmentAmount, installmentPaymentDataOptionItemNrTotalAmountDue, installmentPaymentDataPaymentOptions, installmentsValue); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataInstallments, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataInstallments._InstallmentPaymentDataInstallmentTypeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType != null) + writer.WriteString("installmentPaymentData.installmentType", responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].annualPercentageRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].firstInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInstallmentFeeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee != null) + writer.WriteString("installmentPaymentData.option[itemNr].installmentFee", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInterestRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].interestRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].maximumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].minimumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].numberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].subsequentInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrTotalAmountDueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue != null) + writer.WriteString("installmentPaymentData.option[itemNr].totalAmountDue", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataPaymentOptionsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions != null) + writer.WriteString("installmentPaymentData.paymentOptions", responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions); + + if (responseAdditionalDataInstallments._InstallmentsValueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentsValue != null) + writer.WriteString("installments.value", responseAdditionalDataInstallments.InstallmentsValue); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataNetworkTokens.cs b/Adyen/Payment/Models/ResponseAdditionalDataNetworkTokens.cs new file mode 100644 index 000000000..c818c1b83 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataNetworkTokens.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataNetworkTokens. + /// + public partial class ResponseAdditionalDataNetworkTokens : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether a network token is available for the specified card. + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// The last four digits of a network token. + [JsonConstructor] + public ResponseAdditionalDataNetworkTokens(Option networkTokenAvailable = default, Option networkTokenBin = default, Option networkTokenTokenSummary = default) + { + _NetworkTokenAvailableOption = networkTokenAvailable; + _NetworkTokenBinOption = networkTokenBin; + _NetworkTokenTokenSummaryOption = networkTokenTokenSummary; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataNetworkTokens() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenAvailableOption { get; private set; } + + /// + /// Indicates whether a network token is available for the specified card. + /// + /// Indicates whether a network token is available for the specified card. + [JsonPropertyName("networkToken.available")] + public string? NetworkTokenAvailable { get { return this._NetworkTokenAvailableOption; } set { this._NetworkTokenAvailableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenBinOption { get; private set; } + + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + [JsonPropertyName("networkToken.bin")] + public string? NetworkTokenBin { get { return this._NetworkTokenBinOption; } set { this._NetworkTokenBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenTokenSummaryOption { get; private set; } + + /// + /// The last four digits of a network token. + /// + /// The last four digits of a network token. + [JsonPropertyName("networkToken.tokenSummary")] + public string? NetworkTokenTokenSummary { get { return this._NetworkTokenTokenSummaryOption; } set { this._NetworkTokenTokenSummaryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataNetworkTokens {\n"); + sb.Append(" NetworkTokenAvailable: ").Append(NetworkTokenAvailable).Append("\n"); + sb.Append(" NetworkTokenBin: ").Append(NetworkTokenBin).Append("\n"); + sb.Append(" NetworkTokenTokenSummary: ").Append(NetworkTokenTokenSummary).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataNetworkTokensJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataNetworkTokens Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option networkTokenAvailable = default; + Option networkTokenBin = default; + Option networkTokenTokenSummary = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "networkToken.available": + networkTokenAvailable = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.bin": + networkTokenBin = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.tokenSummary": + networkTokenTokenSummary = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataNetworkTokens(networkTokenAvailable, networkTokenBin, networkTokenTokenSummary); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataNetworkTokens, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataNetworkTokens._NetworkTokenAvailableOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenAvailable != null) + writer.WriteString("networkToken.available", responseAdditionalDataNetworkTokens.NetworkTokenAvailable); + + if (responseAdditionalDataNetworkTokens._NetworkTokenBinOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenBin != null) + writer.WriteString("networkToken.bin", responseAdditionalDataNetworkTokens.NetworkTokenBin); + + if (responseAdditionalDataNetworkTokens._NetworkTokenTokenSummaryOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary != null) + writer.WriteString("networkToken.tokenSummary", responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataOpi.cs b/Adyen/Payment/Models/ResponseAdditionalDataOpi.cs new file mode 100644 index 000000000..8994f7a64 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataOpi.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataOpi. + /// + public partial class ResponseAdditionalDataOpi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonConstructor] + public ResponseAdditionalDataOpi(Option opiTransToken = default) + { + _OpiTransTokenOption = opiTransToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataOpi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiTransTokenOption { get; private set; } + + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonPropertyName("opi.transToken")] + public string? OpiTransToken { get { return this._OpiTransTokenOption; } set { this._OpiTransTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataOpi {\n"); + sb.Append(" OpiTransToken: ").Append(OpiTransToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataOpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataOpi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option opiTransToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "opi.transToken": + opiTransToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataOpi(opiTransToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataOpi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataOpi._OpiTransTokenOption.IsSet) + if (responseAdditionalDataOpi.OpiTransToken != null) + writer.WriteString("opi.transToken", responseAdditionalDataOpi.OpiTransToken); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataSepa.cs b/Adyen/Payment/Models/ResponseAdditionalDataSepa.cs new file mode 100644 index 000000000..22a4393e3 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataSepa.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataSepa. + /// + public partial class ResponseAdditionalDataSepa : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// Its value corresponds to the pspReference value of the transaction. + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonConstructor] + public ResponseAdditionalDataSepa(Option sepadirectdebitDateOfSignature = default, Option sepadirectdebitMandateId = default, Option sepadirectdebitSequenceType = default) + { + _SepadirectdebitDateOfSignatureOption = sepadirectdebitDateOfSignature; + _SepadirectdebitMandateIdOption = sepadirectdebitMandateId; + _SepadirectdebitSequenceTypeOption = sepadirectdebitSequenceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSepa() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitDateOfSignatureOption { get; private set; } + + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// + /// The transaction signature date. Format: yyyy-MM-dd + [JsonPropertyName("sepadirectdebit.dateOfSignature")] + public string? SepadirectdebitDateOfSignature { get { return this._SepadirectdebitDateOfSignatureOption; } set { this._SepadirectdebitDateOfSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitMandateIdOption { get; private set; } + + /// + /// Its value corresponds to the pspReference value of the transaction. + /// + /// Its value corresponds to the pspReference value of the transaction. + [JsonPropertyName("sepadirectdebit.mandateId")] + public string? SepadirectdebitMandateId { get { return this._SepadirectdebitMandateIdOption; } set { this._SepadirectdebitMandateIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitSequenceTypeOption { get; private set; } + + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonPropertyName("sepadirectdebit.sequenceType")] + public string? SepadirectdebitSequenceType { get { return this._SepadirectdebitSequenceTypeOption; } set { this._SepadirectdebitSequenceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSepa {\n"); + sb.Append(" SepadirectdebitDateOfSignature: ").Append(SepadirectdebitDateOfSignature).Append("\n"); + sb.Append(" SepadirectdebitMandateId: ").Append(SepadirectdebitMandateId).Append("\n"); + sb.Append(" SepadirectdebitSequenceType: ").Append(SepadirectdebitSequenceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSepaJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSepa Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sepadirectdebitDateOfSignature = default; + Option sepadirectdebitMandateId = default; + Option sepadirectdebitSequenceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sepadirectdebit.dateOfSignature": + sepadirectdebitDateOfSignature = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.mandateId": + sepadirectdebitMandateId = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.sequenceType": + sepadirectdebitSequenceType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSepa(sepadirectdebitDateOfSignature, sepadirectdebitMandateId, sepadirectdebitSequenceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSepa, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSepa._SepadirectdebitDateOfSignatureOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitDateOfSignature != null) + writer.WriteString("sepadirectdebit.dateOfSignature", responseAdditionalDataSepa.SepadirectdebitDateOfSignature); + + if (responseAdditionalDataSepa._SepadirectdebitMandateIdOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitMandateId != null) + writer.WriteString("sepadirectdebit.mandateId", responseAdditionalDataSepa.SepadirectdebitMandateId); + + if (responseAdditionalDataSepa._SepadirectdebitSequenceTypeOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitSequenceType != null) + writer.WriteString("sepadirectdebit.sequenceType", responseAdditionalDataSepa.SepadirectdebitSequenceType); + } + } +} diff --git a/Adyen/Payment/Models/ResponseAdditionalDataSwish.cs b/Adyen/Payment/Models/ResponseAdditionalDataSwish.cs new file mode 100644 index 000000000..f398580f8 --- /dev/null +++ b/Adyen/Payment/Models/ResponseAdditionalDataSwish.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ResponseAdditionalDataSwish. + /// + public partial class ResponseAdditionalDataSwish : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A Swish shopper's telephone number. + [JsonConstructor] + public ResponseAdditionalDataSwish(Option swishPayerAlias = default) + { + _SwishPayerAliasOption = swishPayerAlias; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSwish() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SwishPayerAliasOption { get; private set; } + + /// + /// A Swish shopper's telephone number. + /// + /// A Swish shopper's telephone number. + [JsonPropertyName("swish.payerAlias")] + public string? SwishPayerAlias { get { return this._SwishPayerAliasOption; } set { this._SwishPayerAliasOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSwish {\n"); + sb.Append(" SwishPayerAlias: ").Append(SwishPayerAlias).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSwishJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSwish Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option swishPayerAlias = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "swish.payerAlias": + swishPayerAlias = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSwish(swishPayerAlias); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSwish, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSwish._SwishPayerAliasOption.IsSet) + if (responseAdditionalDataSwish.SwishPayerAlias != null) + writer.WriteString("swish.payerAlias", responseAdditionalDataSwish.SwishPayerAlias); + } + } +} diff --git a/Adyen/Payment/Models/SDKEphemPubKey.cs b/Adyen/Payment/Models/SDKEphemPubKey.cs new file mode 100644 index 000000000..197a1e4a3 --- /dev/null +++ b/Adyen/Payment/Models/SDKEphemPubKey.cs @@ -0,0 +1,252 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// SDKEphemPubKey. + /// + public partial class SDKEphemPubKey : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + /// The `kty` value as received from the 3D Secure 2 SDK. + /// The `x` value as received from the 3D Secure 2 SDK. + /// The `y` value as received from the 3D Secure 2 SDK. + [JsonConstructor] + public SDKEphemPubKey(Option crv = default, Option kty = default, Option x = default, Option y = default) + { + _CrvOption = crv; + _KtyOption = kty; + _XOption = x; + _YOption = y; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SDKEphemPubKey() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CrvOption { get; private set; } + + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + /// + /// The `crv` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("crv")] + public string? Crv { get { return this._CrvOption; } set { this._CrvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _KtyOption { get; private set; } + + /// + /// The `kty` value as received from the 3D Secure 2 SDK. + /// + /// The `kty` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("kty")] + public string? Kty { get { return this._KtyOption; } set { this._KtyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XOption { get; private set; } + + /// + /// The `x` value as received from the 3D Secure 2 SDK. + /// + /// The `x` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("x")] + public string? X { get { return this._XOption; } set { this._XOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _YOption { get; private set; } + + /// + /// The `y` value as received from the 3D Secure 2 SDK. + /// + /// The `y` value as received from the 3D Secure 2 SDK. + [JsonPropertyName("y")] + public string? Y { get { return this._YOption; } set { this._YOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SDKEphemPubKey {\n"); + sb.Append(" Crv: ").Append(Crv).Append("\n"); + sb.Append(" Kty: ").Append(Kty).Append("\n"); + sb.Append(" X: ").Append(X).Append("\n"); + sb.Append(" Y: ").Append(Y).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SDKEphemPubKeyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SDKEphemPubKey Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option crv = default; + Option kty = default; + Option x = default; + Option y = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "crv": + crv = new Option(utf8JsonReader.GetString()!); + break; + case "kty": + kty = new Option(utf8JsonReader.GetString()!); + break; + case "x": + x = new Option(utf8JsonReader.GetString()!); + break; + case "y": + y = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SDKEphemPubKey(crv, kty, x, y); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SDKEphemPubKey sDKEphemPubKey, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sDKEphemPubKey, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SDKEphemPubKey sDKEphemPubKey, JsonSerializerOptions jsonSerializerOptions) + { + + if (sDKEphemPubKey._CrvOption.IsSet) + if (sDKEphemPubKey.Crv != null) + writer.WriteString("crv", sDKEphemPubKey.Crv); + + if (sDKEphemPubKey._KtyOption.IsSet) + if (sDKEphemPubKey.Kty != null) + writer.WriteString("kty", sDKEphemPubKey.Kty); + + if (sDKEphemPubKey._XOption.IsSet) + if (sDKEphemPubKey.X != null) + writer.WriteString("x", sDKEphemPubKey.X); + + if (sDKEphemPubKey._YOption.IsSet) + if (sDKEphemPubKey.Y != null) + writer.WriteString("y", sDKEphemPubKey.Y); + } + } +} diff --git a/Adyen/Payment/Models/SecureRemoteCommerceCheckoutData.cs b/Adyen/Payment/Models/SecureRemoteCommerceCheckoutData.cs new file mode 100644 index 000000000..418021feb --- /dev/null +++ b/Adyen/Payment/Models/SecureRemoteCommerceCheckoutData.cs @@ -0,0 +1,450 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// SecureRemoteCommerceCheckoutData. + /// + public partial class SecureRemoteCommerceCheckoutData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The Secure Remote Commerce checkout payload to process the payment with. + /// This is the unique identifier generated by SRC system to track and link SRC messages. Available within the present checkout session (e.g. received in an earlier API response during the present session). + /// The [card verification code](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#card-security-code-cvc-cvv-cid). + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'mc'. + /// The Secure Remote Commerce scheme. + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'visa'. + [JsonConstructor] + public SecureRemoteCommerceCheckoutData(Option checkoutPayload = default, Option correlationId = default, Option cvc = default, Option digitalCardId = default, Option scheme = default, Option tokenReference = default) + { + _CheckoutPayloadOption = checkoutPayload; + _CorrelationIdOption = correlationId; + _CvcOption = cvc; + _DigitalCardIdOption = digitalCardId; + _SchemeOption = scheme; + _TokenReferenceOption = tokenReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SecureRemoteCommerceCheckoutData() + { + } + + partial void OnCreated(); + + /// + /// The Secure Remote Commerce scheme. + /// + /// The Secure Remote Commerce scheme. + [JsonConverter(typeof(SchemeEnumJsonConverter))] + public class SchemeEnum : IEnum + { + /// + /// Returns the value of the SchemeEnum. + /// + public string? Value { get; set; } + + /// + /// SchemeEnum.Mc - mc + /// + public static readonly SchemeEnum Mc = new("mc"); + + /// + /// SchemeEnum.Visa - visa + /// + public static readonly SchemeEnum Visa = new("visa"); + + private SchemeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator SchemeEnum?(string? value) => value == null ? null : new SchemeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(SchemeEnum? option) => option?.Value; + + public static bool operator ==(SchemeEnum? left, SchemeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(SchemeEnum? left, SchemeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is SchemeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static SchemeEnum? FromStringOrDefault(string value) + { + return value switch { + "mc" => SchemeEnum.Mc, + "visa" => SchemeEnum.Visa, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(SchemeEnum? value) + { + if (value == null) + return null; + + if (value == SchemeEnum.Mc) + return "mc"; + + if (value == SchemeEnum.Visa) + return "visa"; + + return null; + } + + /// + /// JsonConverter for writing SchemeEnum. + /// + public class SchemeEnumJsonConverter : JsonConverter + { + public override SchemeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : SchemeEnum.FromStringOrDefault(value) ?? new SchemeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, SchemeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(SchemeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeOption { get; private set; } + + /// + /// The Secure Remote Commerce scheme. + /// + /// The Secure Remote Commerce scheme. + [JsonPropertyName("scheme")] + public SchemeEnum? Scheme { get { return this._SchemeOption; } set { this._SchemeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckoutPayloadOption { get; private set; } + + /// + /// The Secure Remote Commerce checkout payload to process the payment with. + /// + /// The Secure Remote Commerce checkout payload to process the payment with. + [JsonPropertyName("checkoutPayload")] + public string? CheckoutPayload { get { return this._CheckoutPayloadOption; } set { this._CheckoutPayloadOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CorrelationIdOption { get; private set; } + + /// + /// This is the unique identifier generated by SRC system to track and link SRC messages. Available within the present checkout session (e.g. received in an earlier API response during the present session). + /// + /// This is the unique identifier generated by SRC system to track and link SRC messages. Available within the present checkout session (e.g. received in an earlier API response during the present session). + [JsonPropertyName("correlationId")] + public string? CorrelationId { get { return this._CorrelationIdOption; } set { this._CorrelationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The [card verification code](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#card-security-code-cvc-cvv-cid). + /// + /// The [card verification code](https://docs.adyen.com/get-started-with-adyen/payment-glossary/#card-security-code-cvc-cvv-cid). + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DigitalCardIdOption { get; private set; } + + /// + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'mc'. + /// + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'mc'. + [JsonPropertyName("digitalCardId")] + public string? DigitalCardId { get { return this._DigitalCardIdOption; } set { this._DigitalCardIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenReferenceOption { get; private set; } + + /// + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'visa'. + /// + /// A unique identifier that represents the token associated with a card enrolled. Required for scheme 'visa'. + [JsonPropertyName("tokenReference")] + public string? TokenReference { get { return this._TokenReferenceOption; } set { this._TokenReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SecureRemoteCommerceCheckoutData {\n"); + sb.Append(" CheckoutPayload: ").Append(CheckoutPayload).Append("\n"); + sb.Append(" CorrelationId: ").Append(CorrelationId).Append("\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" DigitalCardId: ").Append(DigitalCardId).Append("\n"); + sb.Append(" Scheme: ").Append(Scheme).Append("\n"); + sb.Append(" TokenReference: ").Append(TokenReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // CheckoutPayload (string) maxLength + if (this.CheckoutPayload != null && this.CheckoutPayload.Length > 10000) + { + yield return new ValidationResult("Invalid value for CheckoutPayload, length must be less than 10000.", new [] { "CheckoutPayload" }); + } + + // CorrelationId (string) maxLength + if (this.CorrelationId != null && this.CorrelationId.Length > 40) + { + yield return new ValidationResult("Invalid value for CorrelationId, length must be less than 40.", new [] { "CorrelationId" }); + } + + // CorrelationId (string) minLength + if (this.CorrelationId != null && this.CorrelationId.Length < 1) + { + yield return new ValidationResult("Invalid value for CorrelationId, length must be greater than 1.", new [] { "CorrelationId" }); + } + + // Cvc (string) maxLength + if (this.Cvc != null && this.Cvc.Length > 20) + { + yield return new ValidationResult("Invalid value for Cvc, length must be less than 20.", new [] { "Cvc" }); + } + + // Cvc (string) minLength + if (this.Cvc != null && this.Cvc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cvc, length must be greater than 1.", new [] { "Cvc" }); + } + + // DigitalCardId (string) maxLength + if (this.DigitalCardId != null && this.DigitalCardId.Length > 80) + { + yield return new ValidationResult("Invalid value for DigitalCardId, length must be less than 80.", new [] { "DigitalCardId" }); + } + + // TokenReference (string) maxLength + if (this.TokenReference != null && this.TokenReference.Length > 80) + { + yield return new ValidationResult("Invalid value for TokenReference, length must be less than 80.", new [] { "TokenReference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SecureRemoteCommerceCheckoutDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SecureRemoteCommerceCheckoutData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkoutPayload = default; + Option correlationId = default; + Option cvc = default; + Option digitalCardId = default; + Option scheme = default; + Option tokenReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkoutPayload": + checkoutPayload = new Option(utf8JsonReader.GetString()!); + break; + case "correlationId": + correlationId = new Option(utf8JsonReader.GetString()!); + break; + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "digitalCardId": + digitalCardId = new Option(utf8JsonReader.GetString()!); + break; + case "scheme": + string? schemeRawValue = utf8JsonReader.GetString(); + scheme = new Option(SecureRemoteCommerceCheckoutData.SchemeEnum.FromStringOrDefault(schemeRawValue)); + break; + case "tokenReference": + tokenReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SecureRemoteCommerceCheckoutData(checkoutPayload, correlationId, cvc, digitalCardId, scheme, tokenReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SecureRemoteCommerceCheckoutData secureRemoteCommerceCheckoutData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, secureRemoteCommerceCheckoutData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SecureRemoteCommerceCheckoutData secureRemoteCommerceCheckoutData, JsonSerializerOptions jsonSerializerOptions) + { + + if (secureRemoteCommerceCheckoutData._CheckoutPayloadOption.IsSet) + if (secureRemoteCommerceCheckoutData.CheckoutPayload != null) + writer.WriteString("checkoutPayload", secureRemoteCommerceCheckoutData.CheckoutPayload); + + if (secureRemoteCommerceCheckoutData._CorrelationIdOption.IsSet) + if (secureRemoteCommerceCheckoutData.CorrelationId != null) + writer.WriteString("correlationId", secureRemoteCommerceCheckoutData.CorrelationId); + + if (secureRemoteCommerceCheckoutData._CvcOption.IsSet) + if (secureRemoteCommerceCheckoutData.Cvc != null) + writer.WriteString("cvc", secureRemoteCommerceCheckoutData.Cvc); + + if (secureRemoteCommerceCheckoutData._DigitalCardIdOption.IsSet) + if (secureRemoteCommerceCheckoutData.DigitalCardId != null) + writer.WriteString("digitalCardId", secureRemoteCommerceCheckoutData.DigitalCardId); + + if (secureRemoteCommerceCheckoutData._SchemeOption.IsSet && secureRemoteCommerceCheckoutData.Scheme != null) + { + string? schemeRawValue = SecureRemoteCommerceCheckoutData.SchemeEnum.ToJsonValue(secureRemoteCommerceCheckoutData._SchemeOption.Value!.Value); + writer.WriteString("scheme", schemeRawValue); + } + + if (secureRemoteCommerceCheckoutData._TokenReferenceOption.IsSet) + if (secureRemoteCommerceCheckoutData.TokenReference != null) + writer.WriteString("tokenReference", secureRemoteCommerceCheckoutData.TokenReference); + } + } +} diff --git a/Adyen/Payment/Models/ServiceError.cs b/Adyen/Payment/Models/ServiceError.cs new file mode 100644 index 000000000..e2d089040 --- /dev/null +++ b/Adyen/Payment/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Payment/Models/ShopperInteractionDevice.cs b/Adyen/Payment/Models/ShopperInteractionDevice.cs new file mode 100644 index 000000000..5c1da855c --- /dev/null +++ b/Adyen/Payment/Models/ShopperInteractionDevice.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ShopperInteractionDevice. + /// + public partial class ShopperInteractionDevice : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Locale on the shopper interaction device. + /// Operating system running on the shopper interaction device. + /// Version of the operating system on the shopper interaction device. + [JsonConstructor] + public ShopperInteractionDevice(Option locale = default, Option os = default, Option osVersion = default) + { + _LocaleOption = locale; + _OsOption = os; + _OsVersionOption = osVersion; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ShopperInteractionDevice() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LocaleOption { get; private set; } + + /// + /// Locale on the shopper interaction device. + /// + /// Locale on the shopper interaction device. + [JsonPropertyName("locale")] + public string? Locale { get { return this._LocaleOption; } set { this._LocaleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsOption { get; private set; } + + /// + /// Operating system running on the shopper interaction device. + /// + /// Operating system running on the shopper interaction device. + [JsonPropertyName("os")] + public string? Os { get { return this._OsOption; } set { this._OsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OsVersionOption { get; private set; } + + /// + /// Version of the operating system on the shopper interaction device. + /// + /// Version of the operating system on the shopper interaction device. + [JsonPropertyName("osVersion")] + public string? OsVersion { get { return this._OsVersionOption; } set { this._OsVersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShopperInteractionDevice {\n"); + sb.Append(" Locale: ").Append(Locale).Append("\n"); + sb.Append(" Os: ").Append(Os).Append("\n"); + sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ShopperInteractionDeviceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ShopperInteractionDevice Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option locale = default; + Option os = default; + Option osVersion = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "locale": + locale = new Option(utf8JsonReader.GetString()!); + break; + case "os": + os = new Option(utf8JsonReader.GetString()!); + break; + case "osVersion": + osVersion = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ShopperInteractionDevice(locale, os, osVersion); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ShopperInteractionDevice shopperInteractionDevice, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, shopperInteractionDevice, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ShopperInteractionDevice shopperInteractionDevice, JsonSerializerOptions jsonSerializerOptions) + { + + if (shopperInteractionDevice._LocaleOption.IsSet) + if (shopperInteractionDevice.Locale != null) + writer.WriteString("locale", shopperInteractionDevice.Locale); + + if (shopperInteractionDevice._OsOption.IsSet) + if (shopperInteractionDevice.Os != null) + writer.WriteString("os", shopperInteractionDevice.Os); + + if (shopperInteractionDevice._OsVersionOption.IsSet) + if (shopperInteractionDevice.OsVersion != null) + writer.WriteString("osVersion", shopperInteractionDevice.OsVersion); + } + } +} diff --git a/Adyen/Payment/Models/Split.cs b/Adyen/Payment/Models/Split.cs new file mode 100644 index 000000000..39ccb971a --- /dev/null +++ b/Adyen/Payment/Models/Split.cs @@ -0,0 +1,504 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// Split. + /// + public partial class Split : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + /// amount + /// Your description for the split item. + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + [JsonConstructor] + public Split(TypeEnum type, Option account = default, Option amount = default, Option description = default, Option reference = default) + { + Type = type; + _AccountOption = account; + _AmountOption = amount; + _DescriptionOption = description; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Split() + { + } + + partial void OnCreated(); + + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AcquiringFees - AcquiringFees + /// + public static readonly TypeEnum AcquiringFees = new("AcquiringFees"); + + /// + /// TypeEnum.AdyenCommission - AdyenCommission + /// + public static readonly TypeEnum AdyenCommission = new("AdyenCommission"); + + /// + /// TypeEnum.AdyenFees - AdyenFees + /// + public static readonly TypeEnum AdyenFees = new("AdyenFees"); + + /// + /// TypeEnum.AdyenMarkup - AdyenMarkup + /// + public static readonly TypeEnum AdyenMarkup = new("AdyenMarkup"); + + /// + /// TypeEnum.BalanceAccount - BalanceAccount + /// + public static readonly TypeEnum BalanceAccount = new("BalanceAccount"); + + /// + /// TypeEnum.Commission - Commission + /// + public static readonly TypeEnum Commission = new("Commission"); + + /// + /// TypeEnum.Default - Default + /// + public static readonly TypeEnum Default = new("Default"); + + /// + /// TypeEnum.Interchange - Interchange + /// + public static readonly TypeEnum Interchange = new("Interchange"); + + /// + /// TypeEnum.MarketPlace - MarketPlace + /// + public static readonly TypeEnum MarketPlace = new("MarketPlace"); + + /// + /// TypeEnum.PaymentFee - PaymentFee + /// + public static readonly TypeEnum PaymentFee = new("PaymentFee"); + + /// + /// TypeEnum.Remainder - Remainder + /// + public static readonly TypeEnum Remainder = new("Remainder"); + + /// + /// TypeEnum.SchemeFee - SchemeFee + /// + public static readonly TypeEnum SchemeFee = new("SchemeFee"); + + /// + /// TypeEnum.Surcharge - Surcharge + /// + public static readonly TypeEnum Surcharge = new("Surcharge"); + + /// + /// TypeEnum.Tip - Tip + /// + public static readonly TypeEnum Tip = new("Tip"); + + /// + /// TypeEnum.TopUp - TopUp + /// + public static readonly TypeEnum TopUp = new("TopUp"); + + /// + /// TypeEnum.VAT - VAT + /// + public static readonly TypeEnum VAT = new("VAT"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "AcquiringFees" => TypeEnum.AcquiringFees, + "AdyenCommission" => TypeEnum.AdyenCommission, + "AdyenFees" => TypeEnum.AdyenFees, + "AdyenMarkup" => TypeEnum.AdyenMarkup, + "BalanceAccount" => TypeEnum.BalanceAccount, + "Commission" => TypeEnum.Commission, + "Default" => TypeEnum.Default, + "Interchange" => TypeEnum.Interchange, + "MarketPlace" => TypeEnum.MarketPlace, + "PaymentFee" => TypeEnum.PaymentFee, + "Remainder" => TypeEnum.Remainder, + "SchemeFee" => TypeEnum.SchemeFee, + "Surcharge" => TypeEnum.Surcharge, + "Tip" => TypeEnum.Tip, + "TopUp" => TypeEnum.TopUp, + "VAT" => TypeEnum.VAT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AcquiringFees) + return "AcquiringFees"; + + if (value == TypeEnum.AdyenCommission) + return "AdyenCommission"; + + if (value == TypeEnum.AdyenFees) + return "AdyenFees"; + + if (value == TypeEnum.AdyenMarkup) + return "AdyenMarkup"; + + if (value == TypeEnum.BalanceAccount) + return "BalanceAccount"; + + if (value == TypeEnum.Commission) + return "Commission"; + + if (value == TypeEnum.Default) + return "Default"; + + if (value == TypeEnum.Interchange) + return "Interchange"; + + if (value == TypeEnum.MarketPlace) + return "MarketPlace"; + + if (value == TypeEnum.PaymentFee) + return "PaymentFee"; + + if (value == TypeEnum.Remainder) + return "Remainder"; + + if (value == TypeEnum.SchemeFee) + return "SchemeFee"; + + if (value == TypeEnum.Surcharge) + return "Surcharge"; + + if (value == TypeEnum.Tip) + return "Tip"; + + if (value == TypeEnum.TopUp) + return "TopUp"; + + if (value == TypeEnum.VAT) + return "VAT"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + /// + /// The part of the payment you want to book to the specified `account`. Possible values for the [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): * **BalanceAccount**: books part of the payment (specified in `amount`) to the specified `account`. * Transaction fees types that you can book to the specified `account`: * **AcquiringFees**: the aggregated amount of the interchange and scheme fees. * **PaymentFee**: the aggregated amount of all transaction fees. * **AdyenFees**: the aggregated amount of Adyen's commission and markup fees. * **AdyenCommission**: the transaction fees due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **AdyenMarkup**: the transaction fees due to Adyen under [Interchange ++ pricing](https://www.adyen.com/knowledge-hub/interchange-fees-explained). * **Interchange**: the fees paid to the issuer for each payment made with the card network. * **SchemeFee**: the fees paid to the card scheme for using their network. * **Commission**: your platform's commission on the payment (specified in `amount`), booked to your liable balance account. * **Remainder**: the amount left over after a currency conversion, booked to the specified `account`. * **TopUp**: allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. * **VAT**: the value-added tax charged on the payment, booked to your platforms liable balance account. * **Default**: in very specific use cases, allows you to book the specified `amount` to the specified `account`. For more information, contact Adyen support. Possible values for the [Classic Platforms integration](https://docs.adyen.com/classic-platforms): **Commission**, **Default**, **MarketPlace**, **PaymentFee**, **VAT**. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountOption { get; private set; } + + /// + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + /// + /// The unique identifier of the account to which the split amount is booked. Required if `type` is **MarketPlace** or **BalanceAccount**. * [Classic Platforms integration](https://docs.adyen.com/classic-platforms): The [`accountCode`](https://docs.adyen.com/api-explorer/Account/latest/post/updateAccount#request-accountCode) of the account to which the split amount is booked. * [Balance Platform](https://docs.adyen.com/adyen-for-platforms-model): The [`balanceAccountId`](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/balanceAccounts/_id_#path-id) of the account to which the split amount is booked. + [JsonPropertyName("account")] + public string? Account { get { return this._AccountOption; } set { this._AccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public SplitAmount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the split item. + /// + /// Your description for the split item. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + /// + /// Your unique reference for the part of the payment booked to the specified `account`. This is required if `type` is **MarketPlace** ([Classic Platforms integration](https://docs.adyen.com/classic-platforms)) or **BalanceAccount** ([Balance Platform](https://docs.adyen.com/adyen-for-platforms-model)). For the other types, we also recommend providing a **unique** reference so you can reconcile the split and the associated payment in the transaction overview and in the reports. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Split {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Account: ").Append(Account).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Split Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option account = default; + Option amount = default; + Option description = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Split.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "account": + account = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Split.", nameof(type)); + + return new Split(type.Value!.Value!, account, amount, description, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Split split, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, split, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Split split, JsonSerializerOptions jsonSerializerOptions) + { + + if (split.Type != null) + { + string? typeRawValue = Split.TypeEnum.ToJsonValue(split.Type); + writer.WriteString("type", typeRawValue); + } + + if (split._AccountOption.IsSet) + if (split.Account != null) + writer.WriteString("account", split.Account); + + if (split._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, split.Amount, jsonSerializerOptions); + } + if (split._DescriptionOption.IsSet) + if (split.Description != null) + writer.WriteString("description", split.Description); + + if (split._ReferenceOption.IsSet) + if (split.Reference != null) + writer.WriteString("reference", split.Reference); + } + } +} diff --git a/Adyen/Payment/Models/SplitAmount.cs b/Adyen/Payment/Models/SplitAmount.cs new file mode 100644 index 000000000..f01d7838f --- /dev/null +++ b/Adyen/Payment/Models/SplitAmount.cs @@ -0,0 +1,207 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// SplitAmount. + /// + public partial class SplitAmount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + [JsonConstructor] + public SplitAmount(long value, Option currency = default) + { + Value = value; + _CurrencyOption = currency; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SplitAmount() + { + } + + partial void OnCreated(); + + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The value of the split amount, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). By default, this is the original payment currency. + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SplitAmount {\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SplitAmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SplitAmount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option value = default; + Option currency = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!value.IsSet) + throw new ArgumentException("Property is required for class SplitAmount.", nameof(value)); + + return new SplitAmount(value.Value!.Value!, currency); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SplitAmount splitAmount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, splitAmount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SplitAmount splitAmount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("value", splitAmount.Value); + + if (splitAmount._CurrencyOption.IsSet) + if (splitAmount.Currency != null) + writer.WriteString("currency", splitAmount.Currency); + } + } +} diff --git a/Adyen/Payment/Models/SubMerchant.cs b/Adyen/Payment/Models/SubMerchant.cs new file mode 100644 index 000000000..f44052d93 --- /dev/null +++ b/Adyen/Payment/Models/SubMerchant.cs @@ -0,0 +1,277 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// SubMerchant. + /// + public partial class SubMerchant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonConstructor] + public SubMerchant(Option city = default, Option country = default, Option mcc = default, Option name = default, Option taxId = default) + { + _CityOption = city; + _CountryOption = country; + _MccOption = mcc; + _NameOption = name; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubMerchant() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + /// + /// The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + /// + /// The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + /// + /// The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + /// + /// The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + /// + /// The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubMerchant {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubMerchantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubMerchant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option mcc = default; + Option name = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new SubMerchant(city, country, mcc, name, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubMerchant subMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, subMerchant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubMerchant subMerchant, JsonSerializerOptions jsonSerializerOptions) + { + + if (subMerchant._CityOption.IsSet) + if (subMerchant.City != null) + writer.WriteString("city", subMerchant.City); + + if (subMerchant._CountryOption.IsSet) + if (subMerchant.Country != null) + writer.WriteString("country", subMerchant.Country); + + if (subMerchant._MccOption.IsSet) + if (subMerchant.Mcc != null) + writer.WriteString("mcc", subMerchant.Mcc); + + if (subMerchant._NameOption.IsSet) + if (subMerchant.Name != null) + writer.WriteString("name", subMerchant.Name); + + if (subMerchant._TaxIdOption.IsSet) + if (subMerchant.TaxId != null) + writer.WriteString("taxId", subMerchant.TaxId); + } + } +} diff --git a/Adyen/Payment/Models/TechnicalCancelRequest.cs b/Adyen/Payment/Models/TechnicalCancelRequest.cs new file mode 100644 index 000000000..ec014626d --- /dev/null +++ b/Adyen/Payment/Models/TechnicalCancelRequest.cs @@ -0,0 +1,393 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// TechnicalCancelRequest. + /// + public partial class TechnicalCancelRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// The original merchant reference to cancel. + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// modificationAmount + /// mpiData + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public TechnicalCancelRequest(string merchantAccount, string originalMerchantReference, Option?> additionalData = default, Option modificationAmount = default, Option mpiData = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + OriginalMerchantReference = originalMerchantReference; + _AdditionalDataOption = additionalData; + _ModificationAmountOption = modificationAmount; + _MpiDataOption = mpiData; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TechnicalCancelRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string OriginalMerchantReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount? ModificationAmount { get { return this._ModificationAmountOption; } set { this._ModificationAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TechnicalCancelRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TechnicalCancelRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TechnicalCancelRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option originalMerchantReference = default; + Option?> additionalData = default; + Option modificationAmount = default; + Option mpiData = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class TechnicalCancelRequest.", nameof(merchantAccount)); + + if (!originalMerchantReference.IsSet) + throw new ArgumentException("Property is required for class TechnicalCancelRequest.", nameof(originalMerchantReference)); + + return new TechnicalCancelRequest(merchantAccount.Value!, originalMerchantReference.Value!, additionalData, modificationAmount, mpiData, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TechnicalCancelRequest technicalCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, technicalCancelRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TechnicalCancelRequest technicalCancelRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (technicalCancelRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", technicalCancelRequest.MerchantAccount); + + if (technicalCancelRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", technicalCancelRequest.OriginalMerchantReference); + + if (technicalCancelRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, technicalCancelRequest.AdditionalData, jsonSerializerOptions); + } + if (technicalCancelRequest._ModificationAmountOption.IsSet) + { + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, technicalCancelRequest.ModificationAmount, jsonSerializerOptions); + } + if (technicalCancelRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, technicalCancelRequest.MpiData, jsonSerializerOptions); + } + if (technicalCancelRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, technicalCancelRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (technicalCancelRequest._ReferenceOption.IsSet) + if (technicalCancelRequest.Reference != null) + writer.WriteString("reference", technicalCancelRequest.Reference); + + if (technicalCancelRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, technicalCancelRequest.Splits, jsonSerializerOptions); + } + if (technicalCancelRequest._TenderReferenceOption.IsSet) + if (technicalCancelRequest.TenderReference != null) + writer.WriteString("tenderReference", technicalCancelRequest.TenderReference); + + if (technicalCancelRequest._UniqueTerminalIdOption.IsSet) + if (technicalCancelRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", technicalCancelRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDS1Result.cs b/Adyen/Payment/Models/ThreeDS1Result.cs new file mode 100644 index 000000000..e27cbe6a4 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDS1Result.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDS1Result. + /// + public partial class ThreeDS1Result : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The cardholder authentication value (base64 encoded). + /// The CAVV algorithm used. + /// 3D Secure Electronic Commerce Indicator (ECI). + /// The authentication response from the ACS. + /// Whether 3D Secure was offered or not. + /// A unique transaction identifier generated by the MPI on behalf of the merchant to identify the 3D Secure transaction, in `Base64` encoding. + [JsonConstructor] + public ThreeDS1Result(Option cavv = default, Option cavvAlgorithm = default, Option eci = default, Option threeDAuthenticatedResponse = default, Option threeDOfferedResponse = default, Option xid = default) + { + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _EciOption = eci; + _ThreeDAuthenticatedResponseOption = threeDAuthenticatedResponse; + _ThreeDOfferedResponseOption = threeDOfferedResponse; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS1Result() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The cardholder authentication value (base64 encoded). + /// + /// The cardholder authentication value (base64 encoded). + [JsonPropertyName("cavv")] + public string? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. + /// + /// The CAVV algorithm used. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// 3D Secure Electronic Commerce Indicator (ECI). + /// + /// 3D Secure Electronic Commerce Indicator (ECI). + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedResponseOption { get; private set; } + + /// + /// The authentication response from the ACS. + /// + /// The authentication response from the ACS. + [JsonPropertyName("threeDAuthenticatedResponse")] + public string? ThreeDAuthenticatedResponse { get { return this._ThreeDAuthenticatedResponseOption; } set { this._ThreeDAuthenticatedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedResponseOption { get; private set; } + + /// + /// Whether 3D Secure was offered or not. + /// + /// Whether 3D Secure was offered or not. + [JsonPropertyName("threeDOfferedResponse")] + public string? ThreeDOfferedResponse { get { return this._ThreeDOfferedResponseOption; } set { this._ThreeDOfferedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// A unique transaction identifier generated by the MPI on behalf of the merchant to identify the 3D Secure transaction, in `Base64` encoding. + /// + /// A unique transaction identifier generated by the MPI on behalf of the merchant to identify the 3D Secure transaction, in `Base64` encoding. + [JsonPropertyName("xid")] + public string? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS1Result {\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ThreeDAuthenticatedResponse: ").Append(ThreeDAuthenticatedResponse).Append("\n"); + sb.Append(" ThreeDOfferedResponse: ").Append(ThreeDOfferedResponse).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS1ResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS1Result Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cavv = default; + Option cavvAlgorithm = default; + Option eci = default; + Option threeDAuthenticatedResponse = default; + Option threeDOfferedResponse = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cavv": + cavv = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticatedResponse": + threeDAuthenticatedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOfferedResponse": + threeDOfferedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDS1Result(cavv, cavvAlgorithm, eci, threeDAuthenticatedResponse, threeDOfferedResponse, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS1Result threeDS1Result, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS1Result, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS1Result threeDS1Result, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS1Result._CavvOption.IsSet) + if (threeDS1Result.Cavv != null) + writer.WriteString("cavv", threeDS1Result.Cavv); + + if (threeDS1Result._CavvAlgorithmOption.IsSet) + if (threeDS1Result.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDS1Result.CavvAlgorithm); + + if (threeDS1Result._EciOption.IsSet) + if (threeDS1Result.Eci != null) + writer.WriteString("eci", threeDS1Result.Eci); + + if (threeDS1Result._ThreeDAuthenticatedResponseOption.IsSet) + if (threeDS1Result.ThreeDAuthenticatedResponse != null) + writer.WriteString("threeDAuthenticatedResponse", threeDS1Result.ThreeDAuthenticatedResponse); + + if (threeDS1Result._ThreeDOfferedResponseOption.IsSet) + if (threeDS1Result.ThreeDOfferedResponse != null) + writer.WriteString("threeDOfferedResponse", threeDS1Result.ThreeDOfferedResponse); + + if (threeDS1Result._XidOption.IsSet) + if (threeDS1Result.Xid != null) + writer.WriteString("xid", threeDS1Result.Xid); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDS2RequestData.cs b/Adyen/Payment/Models/ThreeDS2RequestData.cs new file mode 100644 index 000000000..3abbea484 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDS2RequestData.cs @@ -0,0 +1,1892 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDS2RequestData. + /// + public partial class ThreeDS2RequestData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + /// acctInfo + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. (default to false) + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// deviceRenderOptions + /// homePhone + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// mobilePhone + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// Indicates the type of payment for which an authentication is requested (message extension) + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// sdkEphemPubKey + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. (default to 60) + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + /// Completion indicator for the device fingerprinting. + /// Indicates the type of Authentication request. + /// threeDSRequestorAuthenticationInfo + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// threeDSRequestorPriorAuthenticationInfo + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// Identify the type of the transaction being authenticated. + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// workPhone + [JsonConstructor] + public ThreeDS2RequestData(string deviceChannel, Option acctInfo = default, Option acctType = default, Option acquirerBIN = default, Option acquirerMerchantID = default, Option addrMatch = default, Option authenticationOnly = default, Option challengeIndicator = default, Option deviceRenderOptions = default, Option homePhone = default, Option mcc = default, Option merchantName = default, Option messageVersion = default, Option mobilePhone = default, Option notificationURL = default, Option payTokenInd = default, Option paymentAuthenticationUseCase = default, Option purchaseInstalData = default, Option recurringExpiry = default, Option recurringFrequency = default, Option sdkAppID = default, Option sdkEncData = default, Option sdkEphemPubKey = default, Option sdkMaxTimeout = default, Option sdkReferenceNumber = default, Option sdkTransID = default, Option sdkVersion = default, Option threeDSCompInd = default, Option threeDSRequestorAuthenticationInd = default, Option threeDSRequestorAuthenticationInfo = default, Option threeDSRequestorChallengeInd = default, Option threeDSRequestorID = default, Option threeDSRequestorName = default, Option threeDSRequestorPriorAuthenticationInfo = default, Option threeDSRequestorURL = default, Option transType = default, Option transactionType = default, Option whiteListStatus = default, Option workPhone = default) + { + DeviceChannel = deviceChannel; + _AcctInfoOption = acctInfo; + _AcctTypeOption = acctType; + _AcquirerBINOption = acquirerBIN; + _AcquirerMerchantIDOption = acquirerMerchantID; + _AddrMatchOption = addrMatch; + _AuthenticationOnlyOption = authenticationOnly; + _ChallengeIndicatorOption = challengeIndicator; + _DeviceRenderOptionsOption = deviceRenderOptions; + _HomePhoneOption = homePhone; + _MccOption = mcc; + _MerchantNameOption = merchantName; + _MessageVersionOption = messageVersion; + _MobilePhoneOption = mobilePhone; + _NotificationURLOption = notificationURL; + _PayTokenIndOption = payTokenInd; + _PaymentAuthenticationUseCaseOption = paymentAuthenticationUseCase; + _PurchaseInstalDataOption = purchaseInstalData; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _SdkAppIDOption = sdkAppID; + _SdkEncDataOption = sdkEncData; + _SdkEphemPubKeyOption = sdkEphemPubKey; + _SdkMaxTimeoutOption = sdkMaxTimeout; + _SdkReferenceNumberOption = sdkReferenceNumber; + _SdkTransIDOption = sdkTransID; + _SdkVersionOption = sdkVersion; + _ThreeDSCompIndOption = threeDSCompInd; + _ThreeDSRequestorAuthenticationIndOption = threeDSRequestorAuthenticationInd; + _ThreeDSRequestorAuthenticationInfoOption = threeDSRequestorAuthenticationInfo; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _ThreeDSRequestorIDOption = threeDSRequestorID; + _ThreeDSRequestorNameOption = threeDSRequestorName; + _ThreeDSRequestorPriorAuthenticationInfoOption = threeDSRequestorPriorAuthenticationInfo; + _ThreeDSRequestorURLOption = threeDSRequestorURL; + _TransTypeOption = transType; + _TransactionTypeOption = transactionType; + _WhiteListStatusOption = whiteListStatus; + _WorkPhoneOption = workPhone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2RequestData() + { + } + + partial void OnCreated(); + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonConverter(typeof(AcctTypeEnumJsonConverter))] + public class AcctTypeEnum : IEnum + { + /// + /// Returns the value of the AcctTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AcctTypeEnum._01 - 01 + /// + public static readonly AcctTypeEnum _01 = new("01"); + + /// + /// AcctTypeEnum._02 - 02 + /// + public static readonly AcctTypeEnum _02 = new("02"); + + /// + /// AcctTypeEnum._03 - 03 + /// + public static readonly AcctTypeEnum _03 = new("03"); + + private AcctTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AcctTypeEnum?(string? value) => value == null ? null : new AcctTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AcctTypeEnum? option) => option?.Value; + + public static bool operator ==(AcctTypeEnum? left, AcctTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AcctTypeEnum? left, AcctTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AcctTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AcctTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => AcctTypeEnum._01, + "02" => AcctTypeEnum._02, + "03" => AcctTypeEnum._03, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AcctTypeEnum? value) + { + if (value == null) + return null; + + if (value == AcctTypeEnum._01) + return "01"; + + if (value == AcctTypeEnum._02) + return "02"; + + if (value == AcctTypeEnum._03) + return "03"; + + return null; + } + + /// + /// JsonConverter for writing AcctTypeEnum. + /// + public class AcctTypeEnumJsonConverter : JsonConverter + { + public override AcctTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AcctTypeEnum.FromStringOrDefault(value) ?? new AcctTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AcctTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AcctTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctTypeOption { get; private set; } + + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + /// + /// Indicates the type of account. For example, for a multi-account card product. Length: 2 characters. Allowed values: * **01** — Not applicable * **02** — Credit * **03** — Debit + [JsonPropertyName("acctType")] + public AcctTypeEnum? AcctType { get { return this._AcctTypeOption; } set { this._AcctTypeOption = new(value); } } + + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + [JsonConverter(typeof(AddrMatchEnumJsonConverter))] + public class AddrMatchEnum : IEnum + { + /// + /// Returns the value of the AddrMatchEnum. + /// + public string? Value { get; set; } + + /// + /// AddrMatchEnum.Y - Y + /// + public static readonly AddrMatchEnum Y = new("Y"); + + /// + /// AddrMatchEnum.N - N + /// + public static readonly AddrMatchEnum N = new("N"); + + private AddrMatchEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AddrMatchEnum?(string? value) => value == null ? null : new AddrMatchEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AddrMatchEnum? option) => option?.Value; + + public static bool operator ==(AddrMatchEnum? left, AddrMatchEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AddrMatchEnum? left, AddrMatchEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AddrMatchEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AddrMatchEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => AddrMatchEnum.Y, + "N" => AddrMatchEnum.N, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AddrMatchEnum? value) + { + if (value == null) + return null; + + if (value == AddrMatchEnum.Y) + return "Y"; + + if (value == AddrMatchEnum.N) + return "N"; + + return null; + } + + /// + /// JsonConverter for writing AddrMatchEnum. + /// + public class AddrMatchEnumJsonConverter : JsonConverter + { + public override AddrMatchEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AddrMatchEnum.FromStringOrDefault(value) ?? new AddrMatchEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AddrMatchEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AddrMatchEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddrMatchOption { get; private set; } + + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + /// + /// Indicates whether the cardholder shipping address and cardholder billing address are the same. Allowed values: * **Y** — Shipping address matches billing address. * **N** — Shipping address does not match billing address. + [JsonPropertyName("addrMatch")] + public AddrMatchEnum? AddrMatch { get { return this._AddrMatchOption; } set { this._AddrMatchOption = new(value); } } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonConverter(typeof(ChallengeIndicatorEnumJsonConverter))] + public class ChallengeIndicatorEnum : IEnum + { + /// + /// Returns the value of the ChallengeIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeIndicatorEnum.NoPreference - noPreference + /// + public static readonly ChallengeIndicatorEnum NoPreference = new("noPreference"); + + /// + /// ChallengeIndicatorEnum.RequestNoChallenge - requestNoChallenge + /// + public static readonly ChallengeIndicatorEnum RequestNoChallenge = new("requestNoChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallenge - requestChallenge + /// + public static readonly ChallengeIndicatorEnum RequestChallenge = new("requestChallenge"); + + /// + /// ChallengeIndicatorEnum.RequestChallengeAsMandate - requestChallengeAsMandate + /// + public static readonly ChallengeIndicatorEnum RequestChallengeAsMandate = new("requestChallengeAsMandate"); + + private ChallengeIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeIndicatorEnum?(string? value) => value == null ? null : new ChallengeIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeIndicatorEnum? left, ChallengeIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "noPreference" => ChallengeIndicatorEnum.NoPreference, + "requestNoChallenge" => ChallengeIndicatorEnum.RequestNoChallenge, + "requestChallenge" => ChallengeIndicatorEnum.RequestChallenge, + "requestChallengeAsMandate" => ChallengeIndicatorEnum.RequestChallengeAsMandate, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeIndicatorEnum.NoPreference) + return "noPreference"; + + if (value == ChallengeIndicatorEnum.RequestNoChallenge) + return "requestNoChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallenge) + return "requestChallenge"; + + if (value == ChallengeIndicatorEnum.RequestChallengeAsMandate) + return "requestChallengeAsMandate"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeIndicatorEnum. + /// + public class ChallengeIndicatorEnumJsonConverter : JsonConverter + { + public override ChallengeIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeIndicatorEnum.FromStringOrDefault(value) ?? new ChallengeIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeIndicatorOption { get; private set; } + + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + /// + /// Possibility to specify a preference for receiving a challenge from the issuer. Allowed values: * `noPreference` * `requestNoChallenge` * `requestChallenge` * `requestChallengeAsMandate` + [JsonPropertyName("challengeIndicator")] + [Obsolete("Deprecated since Adyen Payment API v68. Use `threeDSRequestorChallengeInd` instead.")] + public ChallengeIndicatorEnum? ChallengeIndicator { get { return this._ChallengeIndicatorOption; } set { this._ChallengeIndicatorOption = new(value); } } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonConverter(typeof(TransTypeEnumJsonConverter))] + public class TransTypeEnum : IEnum + { + /// + /// Returns the value of the TransTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransTypeEnum._01 - 01 + /// + public static readonly TransTypeEnum _01 = new("01"); + + /// + /// TransTypeEnum._03 - 03 + /// + public static readonly TransTypeEnum _03 = new("03"); + + /// + /// TransTypeEnum._10 - 10 + /// + public static readonly TransTypeEnum _10 = new("10"); + + /// + /// TransTypeEnum._11 - 11 + /// + public static readonly TransTypeEnum _11 = new("11"); + + /// + /// TransTypeEnum._28 - 28 + /// + public static readonly TransTypeEnum _28 = new("28"); + + private TransTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransTypeEnum?(string? value) => value == null ? null : new TransTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransTypeEnum? option) => option?.Value; + + public static bool operator ==(TransTypeEnum? left, TransTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransTypeEnum? left, TransTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => TransTypeEnum._01, + "03" => TransTypeEnum._03, + "10" => TransTypeEnum._10, + "11" => TransTypeEnum._11, + "28" => TransTypeEnum._28, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransTypeEnum._01) + return "01"; + + if (value == TransTypeEnum._03) + return "03"; + + if (value == TransTypeEnum._10) + return "10"; + + if (value == TransTypeEnum._11) + return "11"; + + if (value == TransTypeEnum._28) + return "28"; + + return null; + } + + /// + /// JsonConverter for writing TransTypeEnum. + /// + public class TransTypeEnumJsonConverter : JsonConverter + { + public override TransTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransTypeEnum.FromStringOrDefault(value) ?? new TransTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransTypeOption { get; private set; } + + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + /// + /// Identifies the type of transaction being authenticated. Length: 2 characters. Allowed values: * **01** — Goods/Service Purchase * **03** — Check Acceptance * **10** — Account Funding * **11** — Quasi-Cash Transaction * **28** — Prepaid Activation and Load + [JsonPropertyName("transType")] + public TransTypeEnum? TransType { get { return this._TransTypeOption; } set { this._TransTypeOption = new(value); } } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonConverter(typeof(TransactionTypeEnumJsonConverter))] + public class TransactionTypeEnum : IEnum + { + /// + /// Returns the value of the TransactionTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TransactionTypeEnum.GoodsOrServicePurchase - goodsOrServicePurchase + /// + public static readonly TransactionTypeEnum GoodsOrServicePurchase = new("goodsOrServicePurchase"); + + /// + /// TransactionTypeEnum.CheckAcceptance - checkAcceptance + /// + public static readonly TransactionTypeEnum CheckAcceptance = new("checkAcceptance"); + + /// + /// TransactionTypeEnum.AccountFunding - accountFunding + /// + public static readonly TransactionTypeEnum AccountFunding = new("accountFunding"); + + /// + /// TransactionTypeEnum.QuasiCashTransaction - quasiCashTransaction + /// + public static readonly TransactionTypeEnum QuasiCashTransaction = new("quasiCashTransaction"); + + /// + /// TransactionTypeEnum.PrepaidActivationAndLoad - prepaidActivationAndLoad + /// + public static readonly TransactionTypeEnum PrepaidActivationAndLoad = new("prepaidActivationAndLoad"); + + private TransactionTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TransactionTypeEnum?(string? value) => value == null ? null : new TransactionTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TransactionTypeEnum? option) => option?.Value; + + public static bool operator ==(TransactionTypeEnum? left, TransactionTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TransactionTypeEnum? left, TransactionTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TransactionTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TransactionTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "goodsOrServicePurchase" => TransactionTypeEnum.GoodsOrServicePurchase, + "checkAcceptance" => TransactionTypeEnum.CheckAcceptance, + "accountFunding" => TransactionTypeEnum.AccountFunding, + "quasiCashTransaction" => TransactionTypeEnum.QuasiCashTransaction, + "prepaidActivationAndLoad" => TransactionTypeEnum.PrepaidActivationAndLoad, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TransactionTypeEnum? value) + { + if (value == null) + return null; + + if (value == TransactionTypeEnum.GoodsOrServicePurchase) + return "goodsOrServicePurchase"; + + if (value == TransactionTypeEnum.CheckAcceptance) + return "checkAcceptance"; + + if (value == TransactionTypeEnum.AccountFunding) + return "accountFunding"; + + if (value == TransactionTypeEnum.QuasiCashTransaction) + return "quasiCashTransaction"; + + if (value == TransactionTypeEnum.PrepaidActivationAndLoad) + return "prepaidActivationAndLoad"; + + return null; + } + + /// + /// JsonConverter for writing TransactionTypeEnum. + /// + public class TransactionTypeEnumJsonConverter : JsonConverter + { + public override TransactionTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TransactionTypeEnum.FromStringOrDefault(value) ?? new TransactionTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TransactionTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TransactionTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionTypeOption { get; private set; } + + /// + /// Identify the type of the transaction being authenticated. + /// + /// Identify the type of the transaction being authenticated. + [JsonPropertyName("transactionType")] + public TransactionTypeEnum? TransactionType { get { return this._TransactionTypeOption; } set { this._TransactionTypeOption = new(value); } } + + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + /// + /// The environment of the shopper. Allowed values: * `app` * `browser` + [JsonPropertyName("deviceChannel")] + public string DeviceChannel { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcctInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("acctInfo")] + public AcctInfo? AcctInfo { get { return this._AcctInfoOption; } set { this._AcctInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerBINOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The acquiring BIN enrolled for 3D Secure 2. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerBIN")] + public string? AcquirerBIN { get { return this._AcquirerBINOption; } set { this._AcquirerBINOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerMerchantIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchantId that is enrolled for 3D Secure 2 by the merchant's acquirer. This string should match the value that you will use in the authorisation. Use 123456 on the Test platform. + [JsonPropertyName("acquirerMerchantID")] + public string? AcquirerMerchantID { get { return this._AcquirerMerchantIDOption; } set { this._AcquirerMerchantIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationOnlyOption { get; private set; } + + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + /// + /// If set to true, you will only perform the [3D Secure 2 authentication](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only), and not the payment authorisation. + [JsonPropertyName("authenticationOnly")] + [Obsolete("Deprecated since Adyen Payment API v50. Use `threeDSAuthenticationOnly` instead.")] + public bool? AuthenticationOnly { get { return this._AuthenticationOnlyOption; } set { this._AuthenticationOnlyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DeviceRenderOptionsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("deviceRenderOptions")] + public DeviceRenderOptions? DeviceRenderOptions { get { return this._DeviceRenderOptionsOption; } set { this._DeviceRenderOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HomePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("homePhone")] + public Phone? HomePhone { get { return this._HomePhoneOption; } set { this._HomePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + /// + /// Required for merchants that have been enrolled for 3D Secure 2 by another party than Adyen, mostly [authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The `mcc` is a four-digit code with which the previously given `acquirerMerchantID` is registered at the scheme. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). The merchant name that the issuer presents to the shopper if they get a challenge. We recommend to use the same value that you will use in the authorization. Maximum length is 40 characters. > Optional for a [full 3D Secure 2 integration](https://docs.adyen.com/online-payments/3d-secure/native-3ds2/api-integration). Use this field if you are enrolled for 3D Secure 2 with us and want to override the merchant name already configured on your account. + [JsonPropertyName("merchantName")] + public string? MerchantName { get { return this._MerchantNameOption; } set { this._MerchantNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + /// + /// The `messageVersion` value indicating the 3D Secure 2 protocol version. + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MobilePhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mobilePhone")] + public Phone? MobilePhone { get { return this._MobilePhoneOption; } set { this._MobilePhoneOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationURLOption { get; private set; } + + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + /// + /// URL to where the issuer should send the `CRes`. Required if you are not using components for `channel` **Web** or if you are using classic integration `deviceChannel` **browser**. + [JsonPropertyName("notificationURL")] + public string? NotificationURL { get { return this._NotificationURLOption; } set { this._NotificationURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayTokenIndOption { get; private set; } + + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + /// + /// Value **true** indicates that the transaction was de-tokenised prior to being received by the ACS. + [JsonPropertyName("payTokenInd")] + public bool? PayTokenInd { get { return this._PayTokenIndOption; } set { this._PayTokenIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAuthenticationUseCaseOption { get; private set; } + + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + /// + /// Indicates the type of payment for which an authentication is requested (message extension) + [JsonPropertyName("paymentAuthenticationUseCase")] + public string? PaymentAuthenticationUseCase { get { return this._PaymentAuthenticationUseCaseOption; } set { this._PaymentAuthenticationUseCaseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PurchaseInstalDataOption { get; private set; } + + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + /// + /// Indicates the maximum number of authorisations permitted for instalment payments. Length: 1–3 characters. + [JsonPropertyName("purchaseInstalData")] + public string? PurchaseInstalData { get { return this._PurchaseInstalDataOption; } set { this._PurchaseInstalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + /// + /// Date after which no further authorisations shall be performed. Format: YYYYMMDD + [JsonPropertyName("recurringExpiry")] + public string? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + /// + /// Indicates the minimum number of days between authorisations. Maximum length: 4 characters. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkAppIDOption { get; private set; } + + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// + /// The `sdkAppID` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + [JsonPropertyName("sdkAppID")] + public string? SdkAppID { get { return this._SdkAppIDOption; } set { this._SdkAppIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEncDataOption { get; private set; } + + /// + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + /// + /// The `sdkEncData` value as received from the 3D Secure 2 SDK. Required for `deviceChannel` set to **app**. + [JsonPropertyName("sdkEncData")] + public string? SdkEncData { get { return this._SdkEncDataOption; } set { this._SdkEncDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkEphemPubKeyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("sdkEphemPubKey")] + public SDKEphemPubKey? SdkEphemPubKey { get { return this._SdkEphemPubKeyOption; } set { this._SdkEphemPubKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkMaxTimeoutOption { get; private set; } + + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + /// + /// The maximum amount of time in minutes for the 3D Secure 2 authentication process. Optional and only for `deviceChannel` set to **app**. Defaults to **60** minutes. + [JsonPropertyName("sdkMaxTimeout")] + public int? SdkMaxTimeout { get { return this._SdkMaxTimeoutOption; } set { this._SdkMaxTimeoutOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkReferenceNumberOption { get; private set; } + + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// + /// The `sdkReferenceNumber` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkReferenceNumber")] + public string? SdkReferenceNumber { get { return this._SdkReferenceNumberOption; } set { this._SdkReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkTransIDOption { get; private set; } + + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + /// + /// The `sdkTransID` value as received from the 3D Secure 2 SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkTransID")] + public string? SdkTransID { get { return this._SdkTransIDOption; } set { this._SdkTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkVersionOption { get; private set; } + + /// + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + /// + /// Version of the 3D Secure 2 mobile SDK. Only for `deviceChannel` set to **app**. + [JsonPropertyName("sdkVersion")] + public string? SdkVersion { get { return this._SdkVersionOption; } set { this._SdkVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSCompIndOption { get; private set; } + + /// + /// Completion indicator for the device fingerprinting. + /// + /// Completion indicator for the device fingerprinting. + [JsonPropertyName("threeDSCompInd")] + public string? ThreeDSCompInd { get { return this._ThreeDSCompIndOption; } set { this._ThreeDSCompIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationIndOption { get; private set; } + + /// + /// Indicates the type of Authentication request. + /// + /// Indicates the type of Authentication request. + [JsonPropertyName("threeDSRequestorAuthenticationInd")] + public string? ThreeDSRequestorAuthenticationInd { get { return this._ThreeDSRequestorAuthenticationIndOption; } set { this._ThreeDSRequestorAuthenticationIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorAuthenticationInfo")] + public ThreeDSRequestorAuthenticationInfo? ThreeDSRequestorAuthenticationInfo { get { return this._ThreeDSRequestorAuthenticationInfoOption; } set { this._ThreeDSRequestorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorIDOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor identifier assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorID")] + public string? ThreeDSRequestorID { get { return this._ThreeDSRequestorIDOption; } set { this._ThreeDSRequestorIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorNameOption { get; private set; } + + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + /// + /// Required for [authentication-only integration](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only) for Visa. Unique 3D Secure requestor name assigned by the Directory Server when you enrol for 3D Secure 2. + [JsonPropertyName("threeDSRequestorName")] + public string? ThreeDSRequestorName { get { return this._ThreeDSRequestorNameOption; } set { this._ThreeDSRequestorNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorPriorAuthenticationInfoOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSRequestorPriorAuthenticationInfo")] + public ThreeDSRequestorPriorAuthenticationInfo? ThreeDSRequestorPriorAuthenticationInfo { get { return this._ThreeDSRequestorPriorAuthenticationInfoOption; } set { this._ThreeDSRequestorPriorAuthenticationInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorURLOption { get; private set; } + + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + /// + /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. + [JsonPropertyName("threeDSRequestorURL")] + public string? ThreeDSRequestorURL { get { return this._ThreeDSRequestorURLOption; } set { this._ThreeDSRequestorURLOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WhiteListStatusOption { get; private set; } + + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + /// + /// The `whiteListStatus` value returned from a previous 3D Secure 2 transaction, only applicable for 3D Secure 2 protocol version 2.2.0. + [JsonPropertyName("whiteListStatus")] + public string? WhiteListStatus { get { return this._WhiteListStatusOption; } set { this._WhiteListStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WorkPhoneOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("workPhone")] + public Phone? WorkPhone { get { return this._WorkPhoneOption; } set { this._WorkPhoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2RequestData {\n"); + sb.Append(" DeviceChannel: ").Append(DeviceChannel).Append("\n"); + sb.Append(" AcctInfo: ").Append(AcctInfo).Append("\n"); + sb.Append(" AcctType: ").Append(AcctType).Append("\n"); + sb.Append(" AcquirerBIN: ").Append(AcquirerBIN).Append("\n"); + sb.Append(" AcquirerMerchantID: ").Append(AcquirerMerchantID).Append("\n"); + sb.Append(" AddrMatch: ").Append(AddrMatch).Append("\n"); + sb.Append(" AuthenticationOnly: ").Append(AuthenticationOnly).Append("\n"); + sb.Append(" ChallengeIndicator: ").Append(ChallengeIndicator).Append("\n"); + sb.Append(" DeviceRenderOptions: ").Append(DeviceRenderOptions).Append("\n"); + sb.Append(" HomePhone: ").Append(HomePhone).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantName: ").Append(MerchantName).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" MobilePhone: ").Append(MobilePhone).Append("\n"); + sb.Append(" NotificationURL: ").Append(NotificationURL).Append("\n"); + sb.Append(" PayTokenInd: ").Append(PayTokenInd).Append("\n"); + sb.Append(" PaymentAuthenticationUseCase: ").Append(PaymentAuthenticationUseCase).Append("\n"); + sb.Append(" PurchaseInstalData: ").Append(PurchaseInstalData).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" SdkAppID: ").Append(SdkAppID).Append("\n"); + sb.Append(" SdkEncData: ").Append(SdkEncData).Append("\n"); + sb.Append(" SdkEphemPubKey: ").Append(SdkEphemPubKey).Append("\n"); + sb.Append(" SdkMaxTimeout: ").Append(SdkMaxTimeout).Append("\n"); + sb.Append(" SdkReferenceNumber: ").Append(SdkReferenceNumber).Append("\n"); + sb.Append(" SdkTransID: ").Append(SdkTransID).Append("\n"); + sb.Append(" SdkVersion: ").Append(SdkVersion).Append("\n"); + sb.Append(" ThreeDSCompInd: ").Append(ThreeDSCompInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInd: ").Append(ThreeDSRequestorAuthenticationInd).Append("\n"); + sb.Append(" ThreeDSRequestorAuthenticationInfo: ").Append(ThreeDSRequestorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" ThreeDSRequestorID: ").Append(ThreeDSRequestorID).Append("\n"); + sb.Append(" ThreeDSRequestorName: ").Append(ThreeDSRequestorName).Append("\n"); + sb.Append(" ThreeDSRequestorPriorAuthenticationInfo: ").Append(ThreeDSRequestorPriorAuthenticationInfo).Append("\n"); + sb.Append(" ThreeDSRequestorURL: ").Append(ThreeDSRequestorURL).Append("\n"); + sb.Append(" TransType: ").Append(TransType).Append("\n"); + sb.Append(" TransactionType: ").Append(TransactionType).Append("\n"); + sb.Append(" WhiteListStatus: ").Append(WhiteListStatus).Append("\n"); + sb.Append(" WorkPhone: ").Append(WorkPhone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // PurchaseInstalData (string) maxLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length > 3) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be less than 3.", new [] { "PurchaseInstalData" }); + } + + // PurchaseInstalData (string) minLength + if (this.PurchaseInstalData != null && this.PurchaseInstalData.Length < 1) + { + yield return new ValidationResult("Invalid value for PurchaseInstalData, length must be greater than 1.", new [] { "PurchaseInstalData" }); + } + + // RecurringFrequency (string) maxLength + if (this.RecurringFrequency != null && this.RecurringFrequency.Length > 4) + { + yield return new ValidationResult("Invalid value for RecurringFrequency, length must be less than 4.", new [] { "RecurringFrequency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2RequestDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2RequestData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option deviceChannel = default; + Option acctInfo = default; + Option acctType = default; + Option acquirerBIN = default; + Option acquirerMerchantID = default; + Option addrMatch = default; + Option authenticationOnly = default; + Option challengeIndicator = default; + Option deviceRenderOptions = default; + Option homePhone = default; + Option mcc = default; + Option merchantName = default; + Option messageVersion = default; + Option mobilePhone = default; + Option notificationURL = default; + Option payTokenInd = default; + Option paymentAuthenticationUseCase = default; + Option purchaseInstalData = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option sdkAppID = default; + Option sdkEncData = default; + Option sdkEphemPubKey = default; + Option sdkMaxTimeout = default; + Option sdkReferenceNumber = default; + Option sdkTransID = default; + Option sdkVersion = default; + Option threeDSCompInd = default; + Option threeDSRequestorAuthenticationInd = default; + Option threeDSRequestorAuthenticationInfo = default; + Option threeDSRequestorChallengeInd = default; + Option threeDSRequestorID = default; + Option threeDSRequestorName = default; + Option threeDSRequestorPriorAuthenticationInfo = default; + Option threeDSRequestorURL = default; + Option transType = default; + Option transactionType = default; + Option whiteListStatus = default; + Option workPhone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "deviceChannel": + deviceChannel = new Option(utf8JsonReader.GetString()!); + break; + case "acctInfo": + acctInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "acctType": + string? acctTypeRawValue = utf8JsonReader.GetString(); + acctType = new Option(ThreeDS2RequestData.AcctTypeEnum.FromStringOrDefault(acctTypeRawValue)); + break; + case "acquirerBIN": + acquirerBIN = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerMerchantID": + acquirerMerchantID = new Option(utf8JsonReader.GetString()!); + break; + case "addrMatch": + string? addrMatchRawValue = utf8JsonReader.GetString(); + addrMatch = new Option(ThreeDS2RequestData.AddrMatchEnum.FromStringOrDefault(addrMatchRawValue)); + break; + case "authenticationOnly": + authenticationOnly = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "challengeIndicator": + string? challengeIndicatorRawValue = utf8JsonReader.GetString(); + challengeIndicator = new Option(ThreeDS2RequestData.ChallengeIndicatorEnum.FromStringOrDefault(challengeIndicatorRawValue)); + break; + case "deviceRenderOptions": + deviceRenderOptions = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "homePhone": + homePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantName": + merchantName = new Option(utf8JsonReader.GetString()!); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "mobilePhone": + mobilePhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notificationURL": + notificationURL = new Option(utf8JsonReader.GetString()!); + break; + case "payTokenInd": + payTokenInd = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "paymentAuthenticationUseCase": + paymentAuthenticationUseCase = new Option(utf8JsonReader.GetString()!); + break; + case "purchaseInstalData": + purchaseInstalData = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(utf8JsonReader.GetString()!); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "sdkAppID": + sdkAppID = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEncData": + sdkEncData = new Option(utf8JsonReader.GetString()!); + break; + case "sdkEphemPubKey": + sdkEphemPubKey = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sdkMaxTimeout": + sdkMaxTimeout = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "sdkReferenceNumber": + sdkReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sdkTransID": + sdkTransID = new Option(utf8JsonReader.GetString()!); + break; + case "sdkVersion": + sdkVersion = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSCompInd": + threeDSCompInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInd": + threeDSRequestorAuthenticationInd = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorAuthenticationInfo": + threeDSRequestorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "threeDSRequestorID": + threeDSRequestorID = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorName": + threeDSRequestorName = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorPriorAuthenticationInfo": + threeDSRequestorPriorAuthenticationInfo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threeDSRequestorURL": + threeDSRequestorURL = new Option(utf8JsonReader.GetString()!); + break; + case "transType": + string? transTypeRawValue = utf8JsonReader.GetString(); + transType = new Option(ThreeDS2RequestData.TransTypeEnum.FromStringOrDefault(transTypeRawValue)); + break; + case "transactionType": + string? transactionTypeRawValue = utf8JsonReader.GetString(); + transactionType = new Option(ThreeDS2RequestData.TransactionTypeEnum.FromStringOrDefault(transactionTypeRawValue)); + break; + case "whiteListStatus": + whiteListStatus = new Option(utf8JsonReader.GetString()!); + break; + case "workPhone": + workPhone = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!deviceChannel.IsSet) + throw new ArgumentException("Property is required for class ThreeDS2RequestData.", nameof(deviceChannel)); + + return new ThreeDS2RequestData(deviceChannel.Value!, acctInfo, acctType, acquirerBIN, acquirerMerchantID, addrMatch, authenticationOnly, challengeIndicator, deviceRenderOptions, homePhone, mcc, merchantName, messageVersion, mobilePhone, notificationURL, payTokenInd, paymentAuthenticationUseCase, purchaseInstalData, recurringExpiry, recurringFrequency, sdkAppID, sdkEncData, sdkEphemPubKey, sdkMaxTimeout, sdkReferenceNumber, sdkTransID, sdkVersion, threeDSCompInd, threeDSRequestorAuthenticationInd, threeDSRequestorAuthenticationInfo, threeDSRequestorChallengeInd, threeDSRequestorID, threeDSRequestorName, threeDSRequestorPriorAuthenticationInfo, threeDSRequestorURL, transType, transactionType, whiteListStatus, workPhone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2RequestData threeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2RequestData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2RequestData threeDS2RequestData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2RequestData.DeviceChannel != null) + writer.WriteString("deviceChannel", threeDS2RequestData.DeviceChannel); + + if (threeDS2RequestData._AcctInfoOption.IsSet) + { + writer.WritePropertyName("acctInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.AcctInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._AcctTypeOption.IsSet && threeDS2RequestData.AcctType != null) + { + string? acctTypeRawValue = ThreeDS2RequestData.AcctTypeEnum.ToJsonValue(threeDS2RequestData._AcctTypeOption.Value!.Value); + writer.WriteString("acctType", acctTypeRawValue); + } + + if (threeDS2RequestData._AcquirerBINOption.IsSet) + if (threeDS2RequestData.AcquirerBIN != null) + writer.WriteString("acquirerBIN", threeDS2RequestData.AcquirerBIN); + + if (threeDS2RequestData._AcquirerMerchantIDOption.IsSet) + if (threeDS2RequestData.AcquirerMerchantID != null) + writer.WriteString("acquirerMerchantID", threeDS2RequestData.AcquirerMerchantID); + + if (threeDS2RequestData._AddrMatchOption.IsSet && threeDS2RequestData.AddrMatch != null) + { + string? addrMatchRawValue = ThreeDS2RequestData.AddrMatchEnum.ToJsonValue(threeDS2RequestData._AddrMatchOption.Value!.Value); + writer.WriteString("addrMatch", addrMatchRawValue); + } + + if (threeDS2RequestData._AuthenticationOnlyOption.IsSet) + writer.WriteBoolean("authenticationOnly", threeDS2RequestData._AuthenticationOnlyOption.Value!.Value); + + if (threeDS2RequestData._ChallengeIndicatorOption.IsSet && threeDS2RequestData.ChallengeIndicator != null) + { + string? challengeIndicatorRawValue = ThreeDS2RequestData.ChallengeIndicatorEnum.ToJsonValue(threeDS2RequestData._ChallengeIndicatorOption.Value!.Value); + writer.WriteString("challengeIndicator", challengeIndicatorRawValue); + } + + if (threeDS2RequestData._DeviceRenderOptionsOption.IsSet) + { + writer.WritePropertyName("deviceRenderOptions"); + JsonSerializer.Serialize(writer, threeDS2RequestData.DeviceRenderOptions, jsonSerializerOptions); + } + if (threeDS2RequestData._HomePhoneOption.IsSet) + { + writer.WritePropertyName("homePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.HomePhone, jsonSerializerOptions); + } + if (threeDS2RequestData._MccOption.IsSet) + if (threeDS2RequestData.Mcc != null) + writer.WriteString("mcc", threeDS2RequestData.Mcc); + + if (threeDS2RequestData._MerchantNameOption.IsSet) + if (threeDS2RequestData.MerchantName != null) + writer.WriteString("merchantName", threeDS2RequestData.MerchantName); + + if (threeDS2RequestData._MessageVersionOption.IsSet) + if (threeDS2RequestData.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2RequestData.MessageVersion); + + if (threeDS2RequestData._MobilePhoneOption.IsSet) + { + writer.WritePropertyName("mobilePhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.MobilePhone, jsonSerializerOptions); + } + if (threeDS2RequestData._NotificationURLOption.IsSet) + if (threeDS2RequestData.NotificationURL != null) + writer.WriteString("notificationURL", threeDS2RequestData.NotificationURL); + + if (threeDS2RequestData._PayTokenIndOption.IsSet) + writer.WriteBoolean("payTokenInd", threeDS2RequestData._PayTokenIndOption.Value!.Value); + + if (threeDS2RequestData._PaymentAuthenticationUseCaseOption.IsSet) + if (threeDS2RequestData.PaymentAuthenticationUseCase != null) + writer.WriteString("paymentAuthenticationUseCase", threeDS2RequestData.PaymentAuthenticationUseCase); + + if (threeDS2RequestData._PurchaseInstalDataOption.IsSet) + if (threeDS2RequestData.PurchaseInstalData != null) + writer.WriteString("purchaseInstalData", threeDS2RequestData.PurchaseInstalData); + + if (threeDS2RequestData._RecurringExpiryOption.IsSet) + if (threeDS2RequestData.RecurringExpiry != null) + writer.WriteString("recurringExpiry", threeDS2RequestData.RecurringExpiry); + + if (threeDS2RequestData._RecurringFrequencyOption.IsSet) + if (threeDS2RequestData.RecurringFrequency != null) + writer.WriteString("recurringFrequency", threeDS2RequestData.RecurringFrequency); + + if (threeDS2RequestData._SdkAppIDOption.IsSet) + if (threeDS2RequestData.SdkAppID != null) + writer.WriteString("sdkAppID", threeDS2RequestData.SdkAppID); + + if (threeDS2RequestData._SdkEncDataOption.IsSet) + if (threeDS2RequestData.SdkEncData != null) + writer.WriteString("sdkEncData", threeDS2RequestData.SdkEncData); + + if (threeDS2RequestData._SdkEphemPubKeyOption.IsSet) + { + writer.WritePropertyName("sdkEphemPubKey"); + JsonSerializer.Serialize(writer, threeDS2RequestData.SdkEphemPubKey, jsonSerializerOptions); + } + if (threeDS2RequestData._SdkMaxTimeoutOption.IsSet) + writer.WriteNumber("sdkMaxTimeout", threeDS2RequestData._SdkMaxTimeoutOption.Value!.Value); + + if (threeDS2RequestData._SdkReferenceNumberOption.IsSet) + if (threeDS2RequestData.SdkReferenceNumber != null) + writer.WriteString("sdkReferenceNumber", threeDS2RequestData.SdkReferenceNumber); + + if (threeDS2RequestData._SdkTransIDOption.IsSet) + if (threeDS2RequestData.SdkTransID != null) + writer.WriteString("sdkTransID", threeDS2RequestData.SdkTransID); + + if (threeDS2RequestData._SdkVersionOption.IsSet) + if (threeDS2RequestData.SdkVersion != null) + writer.WriteString("sdkVersion", threeDS2RequestData.SdkVersion); + + if (threeDS2RequestData._ThreeDSCompIndOption.IsSet) + if (threeDS2RequestData.ThreeDSCompInd != null) + writer.WriteString("threeDSCompInd", threeDS2RequestData.ThreeDSCompInd); + + if (threeDS2RequestData._ThreeDSRequestorAuthenticationIndOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorAuthenticationInd != null) + writer.WriteString("threeDSRequestorAuthenticationInd", threeDS2RequestData.ThreeDSRequestorAuthenticationInd); + + if (threeDS2RequestData._ThreeDSRequestorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.ThreeDSRequestorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._ThreeDSRequestorChallengeIndOption.IsSet && threeDS2RequestData.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = ThreeDS2RequestData.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2RequestData._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (threeDS2RequestData._ThreeDSRequestorIDOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorID != null) + writer.WriteString("threeDSRequestorID", threeDS2RequestData.ThreeDSRequestorID); + + if (threeDS2RequestData._ThreeDSRequestorNameOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorName != null) + writer.WriteString("threeDSRequestorName", threeDS2RequestData.ThreeDSRequestorName); + + if (threeDS2RequestData._ThreeDSRequestorPriorAuthenticationInfoOption.IsSet) + { + writer.WritePropertyName("threeDSRequestorPriorAuthenticationInfo"); + JsonSerializer.Serialize(writer, threeDS2RequestData.ThreeDSRequestorPriorAuthenticationInfo, jsonSerializerOptions); + } + if (threeDS2RequestData._ThreeDSRequestorURLOption.IsSet) + if (threeDS2RequestData.ThreeDSRequestorURL != null) + writer.WriteString("threeDSRequestorURL", threeDS2RequestData.ThreeDSRequestorURL); + + if (threeDS2RequestData._TransTypeOption.IsSet && threeDS2RequestData.TransType != null) + { + string? transTypeRawValue = ThreeDS2RequestData.TransTypeEnum.ToJsonValue(threeDS2RequestData._TransTypeOption.Value!.Value); + writer.WriteString("transType", transTypeRawValue); + } + + if (threeDS2RequestData._TransactionTypeOption.IsSet && threeDS2RequestData.TransactionType != null) + { + string? transactionTypeRawValue = ThreeDS2RequestData.TransactionTypeEnum.ToJsonValue(threeDS2RequestData._TransactionTypeOption.Value!.Value); + writer.WriteString("transactionType", transactionTypeRawValue); + } + + if (threeDS2RequestData._WhiteListStatusOption.IsSet) + if (threeDS2RequestData.WhiteListStatus != null) + writer.WriteString("whiteListStatus", threeDS2RequestData.WhiteListStatus); + + if (threeDS2RequestData._WorkPhoneOption.IsSet) + { + writer.WritePropertyName("workPhone"); + JsonSerializer.Serialize(writer, threeDS2RequestData.WorkPhone, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/ThreeDS2Result.cs b/Adyen/Payment/Models/ThreeDS2Result.cs new file mode 100644 index 000000000..7cb2fe0e5 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDS2Result.cs @@ -0,0 +1,919 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDS2Result. + /// + public partial class ThreeDS2Result : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + /// The `eci` value as defined in the 3D Secure 2 specification. + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// The `timestamp` value of the 3D Secure 2 authentication. + /// The `transStatus` value as defined in the 3D Secure 2 specification. + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + [JsonConstructor] + public ThreeDS2Result(Option authenticationValue = default, Option cavvAlgorithm = default, Option challengeCancel = default, Option dsTransID = default, Option eci = default, Option exemptionIndicator = default, Option messageVersion = default, Option riskScore = default, Option threeDSRequestorChallengeInd = default, Option threeDSServerTransID = default, Option timestamp = default, Option transStatus = default, Option transStatusReason = default, Option whiteListStatus = default) + { + _AuthenticationValueOption = authenticationValue; + _CavvAlgorithmOption = cavvAlgorithm; + _ChallengeCancelOption = challengeCancel; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _ExemptionIndicatorOption = exemptionIndicator; + _MessageVersionOption = messageVersion; + _RiskScoreOption = riskScore; + _ThreeDSRequestorChallengeIndOption = threeDSRequestorChallengeInd; + _ThreeDSServerTransIDOption = threeDSServerTransID; + _TimestampOption = timestamp; + _TransStatusOption = transStatus; + _TransStatusReasonOption = transStatusReason; + _WhiteListStatusOption = whiteListStatus; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2Result() + { + } + + partial void OnCreated(); + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonConverter(typeof(ChallengeCancelEnumJsonConverter))] + public class ChallengeCancelEnum : IEnum + { + /// + /// Returns the value of the ChallengeCancelEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeCancelEnum._01 - 01 + /// + public static readonly ChallengeCancelEnum _01 = new("01"); + + /// + /// ChallengeCancelEnum._02 - 02 + /// + public static readonly ChallengeCancelEnum _02 = new("02"); + + /// + /// ChallengeCancelEnum._03 - 03 + /// + public static readonly ChallengeCancelEnum _03 = new("03"); + + /// + /// ChallengeCancelEnum._04 - 04 + /// + public static readonly ChallengeCancelEnum _04 = new("04"); + + /// + /// ChallengeCancelEnum._05 - 05 + /// + public static readonly ChallengeCancelEnum _05 = new("05"); + + /// + /// ChallengeCancelEnum._06 - 06 + /// + public static readonly ChallengeCancelEnum _06 = new("06"); + + /// + /// ChallengeCancelEnum._07 - 07 + /// + public static readonly ChallengeCancelEnum _07 = new("07"); + + private ChallengeCancelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeCancelEnum?(string? value) => value == null ? null : new ChallengeCancelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeCancelEnum? option) => option?.Value; + + public static bool operator ==(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeCancelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeCancelEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeCancelEnum._01, + "02" => ChallengeCancelEnum._02, + "03" => ChallengeCancelEnum._03, + "04" => ChallengeCancelEnum._04, + "05" => ChallengeCancelEnum._05, + "06" => ChallengeCancelEnum._06, + "07" => ChallengeCancelEnum._07, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeCancelEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeCancelEnum._01) + return "01"; + + if (value == ChallengeCancelEnum._02) + return "02"; + + if (value == ChallengeCancelEnum._03) + return "03"; + + if (value == ChallengeCancelEnum._04) + return "04"; + + if (value == ChallengeCancelEnum._05) + return "05"; + + if (value == ChallengeCancelEnum._06) + return "06"; + + if (value == ChallengeCancelEnum._07) + return "07"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeCancelEnum. + /// + public class ChallengeCancelEnumJsonConverter : JsonConverter + { + public override ChallengeCancelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeCancelEnum.FromStringOrDefault(value) ?? new ChallengeCancelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeCancelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeCancelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeCancelOption { get; private set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonPropertyName("challengeCancel")] + public ChallengeCancelEnum? ChallengeCancel { get { return this._ChallengeCancelOption; } set { this._ChallengeCancelOption = new(value); } } + + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + [JsonConverter(typeof(ExemptionIndicatorEnumJsonConverter))] + public class ExemptionIndicatorEnum : IEnum + { + /// + /// Returns the value of the ExemptionIndicatorEnum. + /// + public string? Value { get; set; } + + /// + /// ExemptionIndicatorEnum.LowValue - lowValue + /// + public static readonly ExemptionIndicatorEnum LowValue = new("lowValue"); + + /// + /// ExemptionIndicatorEnum.SecureCorporate - secureCorporate + /// + public static readonly ExemptionIndicatorEnum SecureCorporate = new("secureCorporate"); + + /// + /// ExemptionIndicatorEnum.TrustedBeneficiary - trustedBeneficiary + /// + public static readonly ExemptionIndicatorEnum TrustedBeneficiary = new("trustedBeneficiary"); + + /// + /// ExemptionIndicatorEnum.TransactionRiskAnalysis - transactionRiskAnalysis + /// + public static readonly ExemptionIndicatorEnum TransactionRiskAnalysis = new("transactionRiskAnalysis"); + + private ExemptionIndicatorEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ExemptionIndicatorEnum?(string? value) => value == null ? null : new ExemptionIndicatorEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ExemptionIndicatorEnum? option) => option?.Value; + + public static bool operator ==(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ExemptionIndicatorEnum? left, ExemptionIndicatorEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ExemptionIndicatorEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ExemptionIndicatorEnum? FromStringOrDefault(string value) + { + return value switch { + "lowValue" => ExemptionIndicatorEnum.LowValue, + "secureCorporate" => ExemptionIndicatorEnum.SecureCorporate, + "trustedBeneficiary" => ExemptionIndicatorEnum.TrustedBeneficiary, + "transactionRiskAnalysis" => ExemptionIndicatorEnum.TransactionRiskAnalysis, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ExemptionIndicatorEnum? value) + { + if (value == null) + return null; + + if (value == ExemptionIndicatorEnum.LowValue) + return "lowValue"; + + if (value == ExemptionIndicatorEnum.SecureCorporate) + return "secureCorporate"; + + if (value == ExemptionIndicatorEnum.TrustedBeneficiary) + return "trustedBeneficiary"; + + if (value == ExemptionIndicatorEnum.TransactionRiskAnalysis) + return "transactionRiskAnalysis"; + + return null; + } + + /// + /// JsonConverter for writing ExemptionIndicatorEnum. + /// + public class ExemptionIndicatorEnumJsonConverter : JsonConverter + { + public override ExemptionIndicatorEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ExemptionIndicatorEnum.FromStringOrDefault(value) ?? new ExemptionIndicatorEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ExemptionIndicatorEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ExemptionIndicatorEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExemptionIndicatorOption { get; private set; } + + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + /// + /// Indicates the exemption type that was applied by the issuer to the authentication, if exemption applied. Allowed values: * `lowValue` * `secureCorporate` * `trustedBeneficiary` * `transactionRiskAnalysis` + [JsonPropertyName("exemptionIndicator")] + public ExemptionIndicatorEnum? ExemptionIndicator { get { return this._ExemptionIndicatorOption; } set { this._ExemptionIndicatorOption = new(value); } } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonConverter(typeof(ThreeDSRequestorChallengeIndEnumJsonConverter))] + public class ThreeDSRequestorChallengeIndEnum : IEnum + { + /// + /// Returns the value of the ThreeDSRequestorChallengeIndEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSRequestorChallengeIndEnum._01 - 01 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _01 = new("01"); + + /// + /// ThreeDSRequestorChallengeIndEnum._02 - 02 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _02 = new("02"); + + /// + /// ThreeDSRequestorChallengeIndEnum._03 - 03 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _03 = new("03"); + + /// + /// ThreeDSRequestorChallengeIndEnum._04 - 04 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _04 = new("04"); + + /// + /// ThreeDSRequestorChallengeIndEnum._05 - 05 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _05 = new("05"); + + /// + /// ThreeDSRequestorChallengeIndEnum._06 - 06 + /// + public static readonly ThreeDSRequestorChallengeIndEnum _06 = new("06"); + + private ThreeDSRequestorChallengeIndEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSRequestorChallengeIndEnum?(string? value) => value == null ? null : new ThreeDSRequestorChallengeIndEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSRequestorChallengeIndEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSRequestorChallengeIndEnum? left, ThreeDSRequestorChallengeIndEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSRequestorChallengeIndEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSRequestorChallengeIndEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSRequestorChallengeIndEnum._01, + "02" => ThreeDSRequestorChallengeIndEnum._02, + "03" => ThreeDSRequestorChallengeIndEnum._03, + "04" => ThreeDSRequestorChallengeIndEnum._04, + "05" => ThreeDSRequestorChallengeIndEnum._05, + "06" => ThreeDSRequestorChallengeIndEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSRequestorChallengeIndEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSRequestorChallengeIndEnum._01) + return "01"; + + if (value == ThreeDSRequestorChallengeIndEnum._02) + return "02"; + + if (value == ThreeDSRequestorChallengeIndEnum._03) + return "03"; + + if (value == ThreeDSRequestorChallengeIndEnum._04) + return "04"; + + if (value == ThreeDSRequestorChallengeIndEnum._05) + return "05"; + + if (value == ThreeDSRequestorChallengeIndEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSRequestorChallengeIndEnum. + /// + public class ThreeDSRequestorChallengeIndEnumJsonConverter : JsonConverter + { + public override ThreeDSRequestorChallengeIndEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(value) ?? new ThreeDSRequestorChallengeIndEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorChallengeIndEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSRequestorChallengeIndEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSRequestorChallengeIndOption { get; private set; } + + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + /// + /// Indicates whether a challenge is requested for this transaction. Possible values: * **01** — No preference * **02** — No challenge requested * **03** — Challenge requested (3DS Requestor preference) * **04** — Challenge requested (Mandate) * **05** — No challenge (transactional risk analysis is already performed) * **06** — Data Only + [JsonPropertyName("threeDSRequestorChallengeInd")] + public ThreeDSRequestorChallengeIndEnum? ThreeDSRequestorChallengeInd { get { return this._ThreeDSRequestorChallengeIndOption; } set { this._ThreeDSRequestorChallengeIndOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationValueOption { get; private set; } + + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + /// + /// The `authenticationValue` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("authenticationValue")] + public string? AuthenticationValue { get { return this._AuthenticationValueOption; } set { this._AuthenticationValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + /// + /// The algorithm used by the ACS to calculate the authentication value, only for Cartes Bancaires integrations. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + /// + /// The `dsTransID` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The `eci` value as defined in the 3D Secure 2 specification. + /// + /// The `eci` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageVersionOption { get; private set; } + + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + /// + /// The `messageVersion` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("messageVersion")] + public string? MessageVersion { get { return this._MessageVersionOption; } set { this._MessageVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + /// + /// Risk score calculated by Cartes Bancaires Directory Server (DS). + [JsonPropertyName("riskScore")] + public string? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSServerTransIDOption { get; private set; } + + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + /// + /// The `threeDSServerTransID` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("threeDSServerTransID")] + public string? ThreeDSServerTransID { get { return this._ThreeDSServerTransIDOption; } set { this._ThreeDSServerTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// The `timestamp` value of the 3D Secure 2 authentication. + /// + /// The `timestamp` value of the 3D Secure 2 authentication. + [JsonPropertyName("timestamp")] + public string? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusOption { get; private set; } + + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. + /// + /// The `transStatus` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("transStatus")] + public string? TransStatus { get { return this._TransStatusOption; } set { this._TransStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonPropertyName("transStatusReason")] + public string? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _WhiteListStatusOption { get; private set; } + + /// + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + /// + /// The `whiteListStatus` value as defined in the 3D Secure 2 specification. + [JsonPropertyName("whiteListStatus")] + public string? WhiteListStatus { get { return this._WhiteListStatusOption; } set { this._WhiteListStatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2Result {\n"); + sb.Append(" AuthenticationValue: ").Append(AuthenticationValue).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ChallengeCancel: ").Append(ChallengeCancel).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ExemptionIndicator: ").Append(ExemptionIndicator).Append("\n"); + sb.Append(" MessageVersion: ").Append(MessageVersion).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" ThreeDSRequestorChallengeInd: ").Append(ThreeDSRequestorChallengeInd).Append("\n"); + sb.Append(" ThreeDSServerTransID: ").Append(ThreeDSServerTransID).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" TransStatus: ").Append(TransStatus).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append(" WhiteListStatus: ").Append(WhiteListStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2ResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2Result Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationValue = default; + Option cavvAlgorithm = default; + Option challengeCancel = default; + Option dsTransID = default; + Option eci = default; + Option exemptionIndicator = default; + Option messageVersion = default; + Option riskScore = default; + Option threeDSRequestorChallengeInd = default; + Option threeDSServerTransID = default; + Option timestamp = default; + Option transStatus = default; + Option transStatusReason = default; + Option whiteListStatus = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationValue": + authenticationValue = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "challengeCancel": + string? challengeCancelRawValue = utf8JsonReader.GetString(); + challengeCancel = new Option(ThreeDS2Result.ChallengeCancelEnum.FromStringOrDefault(challengeCancelRawValue)); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "exemptionIndicator": + string? exemptionIndicatorRawValue = utf8JsonReader.GetString(); + exemptionIndicator = new Option(ThreeDS2Result.ExemptionIndicatorEnum.FromStringOrDefault(exemptionIndicatorRawValue)); + break; + case "messageVersion": + messageVersion = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSRequestorChallengeInd": + string? threeDSRequestorChallengeIndRawValue = utf8JsonReader.GetString(); + threeDSRequestorChallengeInd = new Option(ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.FromStringOrDefault(threeDSRequestorChallengeIndRawValue)); + break; + case "threeDSServerTransID": + threeDSServerTransID = new Option(utf8JsonReader.GetString()!); + break; + case "timestamp": + timestamp = new Option(utf8JsonReader.GetString()!); + break; + case "transStatus": + transStatus = new Option(utf8JsonReader.GetString()!); + break; + case "transStatusReason": + transStatusReason = new Option(utf8JsonReader.GetString()!); + break; + case "whiteListStatus": + whiteListStatus = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDS2Result(authenticationValue, cavvAlgorithm, challengeCancel, dsTransID, eci, exemptionIndicator, messageVersion, riskScore, threeDSRequestorChallengeInd, threeDSServerTransID, timestamp, transStatus, transStatusReason, whiteListStatus); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2Result threeDS2Result, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2Result, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2Result threeDS2Result, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2Result._AuthenticationValueOption.IsSet) + if (threeDS2Result.AuthenticationValue != null) + writer.WriteString("authenticationValue", threeDS2Result.AuthenticationValue); + + if (threeDS2Result._CavvAlgorithmOption.IsSet) + if (threeDS2Result.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDS2Result.CavvAlgorithm); + + if (threeDS2Result._ChallengeCancelOption.IsSet && threeDS2Result.ChallengeCancel != null) + { + string? challengeCancelRawValue = ThreeDS2Result.ChallengeCancelEnum.ToJsonValue(threeDS2Result._ChallengeCancelOption.Value!.Value); + writer.WriteString("challengeCancel", challengeCancelRawValue); + } + + if (threeDS2Result._DsTransIDOption.IsSet) + if (threeDS2Result.DsTransID != null) + writer.WriteString("dsTransID", threeDS2Result.DsTransID); + + if (threeDS2Result._EciOption.IsSet) + if (threeDS2Result.Eci != null) + writer.WriteString("eci", threeDS2Result.Eci); + + if (threeDS2Result._ExemptionIndicatorOption.IsSet && threeDS2Result.ExemptionIndicator != null) + { + string? exemptionIndicatorRawValue = ThreeDS2Result.ExemptionIndicatorEnum.ToJsonValue(threeDS2Result._ExemptionIndicatorOption.Value!.Value); + writer.WriteString("exemptionIndicator", exemptionIndicatorRawValue); + } + + if (threeDS2Result._MessageVersionOption.IsSet) + if (threeDS2Result.MessageVersion != null) + writer.WriteString("messageVersion", threeDS2Result.MessageVersion); + + if (threeDS2Result._RiskScoreOption.IsSet) + if (threeDS2Result.RiskScore != null) + writer.WriteString("riskScore", threeDS2Result.RiskScore); + + if (threeDS2Result._ThreeDSRequestorChallengeIndOption.IsSet && threeDS2Result.ThreeDSRequestorChallengeInd != null) + { + string? threeDSRequestorChallengeIndRawValue = ThreeDS2Result.ThreeDSRequestorChallengeIndEnum.ToJsonValue(threeDS2Result._ThreeDSRequestorChallengeIndOption.Value!.Value); + writer.WriteString("threeDSRequestorChallengeInd", threeDSRequestorChallengeIndRawValue); + } + + if (threeDS2Result._ThreeDSServerTransIDOption.IsSet) + if (threeDS2Result.ThreeDSServerTransID != null) + writer.WriteString("threeDSServerTransID", threeDS2Result.ThreeDSServerTransID); + + if (threeDS2Result._TimestampOption.IsSet) + if (threeDS2Result.Timestamp != null) + writer.WriteString("timestamp", threeDS2Result.Timestamp); + + if (threeDS2Result._TransStatusOption.IsSet) + if (threeDS2Result.TransStatus != null) + writer.WriteString("transStatus", threeDS2Result.TransStatus); + + if (threeDS2Result._TransStatusReasonOption.IsSet) + if (threeDS2Result.TransStatusReason != null) + writer.WriteString("transStatusReason", threeDS2Result.TransStatusReason); + + if (threeDS2Result._WhiteListStatusOption.IsSet) + if (threeDS2Result.WhiteListStatus != null) + writer.WriteString("whiteListStatus", threeDS2Result.WhiteListStatus); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDS2ResultRequest.cs b/Adyen/Payment/Models/ThreeDS2ResultRequest.cs new file mode 100644 index 000000000..b19578e14 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDS2ResultRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDS2ResultRequest. + /// + public partial class ThreeDS2ResultRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The pspReference returned in the /authorise call. + [JsonConstructor] + public ThreeDS2ResultRequest(string merchantAccount, string pspReference) + { + MerchantAccount = merchantAccount; + PspReference = pspReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2ResultRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The pspReference returned in the /authorise call. + /// + /// The pspReference returned in the /authorise call. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2ResultRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2ResultRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2ResultRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option pspReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class ThreeDS2ResultRequest.", nameof(merchantAccount)); + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class ThreeDS2ResultRequest.", nameof(pspReference)); + + return new ThreeDS2ResultRequest(merchantAccount.Value!, pspReference.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2ResultRequest threeDS2ResultRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2ResultRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2ResultRequest threeDS2ResultRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2ResultRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", threeDS2ResultRequest.MerchantAccount); + + if (threeDS2ResultRequest.PspReference != null) + writer.WriteString("pspReference", threeDS2ResultRequest.PspReference); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDS2ResultResponse.cs b/Adyen/Payment/Models/ThreeDS2ResultResponse.cs new file mode 100644 index 000000000..a303ed539 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDS2ResultResponse.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDS2ResultResponse. + /// + public partial class ThreeDS2ResultResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// threeDS2Result + [JsonConstructor] + public ThreeDS2ResultResponse(Option threeDS2Result = default) + { + _ThreeDS2ResultOption = threeDS2Result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDS2ResultResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDS2ResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDS2Result")] + public ThreeDS2Result? ThreeDS2Result { get { return this._ThreeDS2ResultOption; } set { this._ThreeDS2ResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDS2ResultResponse {\n"); + sb.Append(" ThreeDS2Result: ").Append(ThreeDS2Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDS2ResultResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDS2ResultResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDS2Result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDS2Result": + threeDS2Result = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ThreeDS2ResultResponse(threeDS2Result); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDS2ResultResponse threeDS2ResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDS2ResultResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDS2ResultResponse threeDS2ResultResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDS2ResultResponse._ThreeDS2ResultOption.IsSet) + { + writer.WritePropertyName("threeDS2Result"); + JsonSerializer.Serialize(writer, threeDS2ResultResponse.ThreeDS2Result, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/ThreeDSRequestorAuthenticationInfo.cs b/Adyen/Payment/Models/ThreeDSRequestorAuthenticationInfo.cs new file mode 100644 index 000000000..e84b85f07 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDSRequestorAuthenticationInfo.cs @@ -0,0 +1,381 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDSRequestorAuthenticationInfo. + /// + public partial class ThreeDSRequestorAuthenticationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + [JsonConstructor] + public ThreeDSRequestorAuthenticationInfo(Option threeDSReqAuthData = default, Option threeDSReqAuthMethod = default, Option threeDSReqAuthTimestamp = default) + { + _ThreeDSReqAuthDataOption = threeDSReqAuthData; + _ThreeDSReqAuthMethodOption = threeDSReqAuthMethod; + _ThreeDSReqAuthTimestampOption = threeDSReqAuthTimestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSRequestorAuthenticationInfo() + { + } + + partial void OnCreated(); + + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + [JsonConverter(typeof(ThreeDSReqAuthMethodEnumJsonConverter))] + public class ThreeDSReqAuthMethodEnum : IEnum + { + /// + /// Returns the value of the ThreeDSReqAuthMethodEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSReqAuthMethodEnum._01 - 01 + /// + public static readonly ThreeDSReqAuthMethodEnum _01 = new("01"); + + /// + /// ThreeDSReqAuthMethodEnum._02 - 02 + /// + public static readonly ThreeDSReqAuthMethodEnum _02 = new("02"); + + /// + /// ThreeDSReqAuthMethodEnum._03 - 03 + /// + public static readonly ThreeDSReqAuthMethodEnum _03 = new("03"); + + /// + /// ThreeDSReqAuthMethodEnum._04 - 04 + /// + public static readonly ThreeDSReqAuthMethodEnum _04 = new("04"); + + /// + /// ThreeDSReqAuthMethodEnum._05 - 05 + /// + public static readonly ThreeDSReqAuthMethodEnum _05 = new("05"); + + /// + /// ThreeDSReqAuthMethodEnum._06 - 06 + /// + public static readonly ThreeDSReqAuthMethodEnum _06 = new("06"); + + private ThreeDSReqAuthMethodEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSReqAuthMethodEnum?(string? value) => value == null ? null : new ThreeDSReqAuthMethodEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSReqAuthMethodEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSReqAuthMethodEnum? left, ThreeDSReqAuthMethodEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSReqAuthMethodEnum? left, ThreeDSReqAuthMethodEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSReqAuthMethodEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSReqAuthMethodEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSReqAuthMethodEnum._01, + "02" => ThreeDSReqAuthMethodEnum._02, + "03" => ThreeDSReqAuthMethodEnum._03, + "04" => ThreeDSReqAuthMethodEnum._04, + "05" => ThreeDSReqAuthMethodEnum._05, + "06" => ThreeDSReqAuthMethodEnum._06, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSReqAuthMethodEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSReqAuthMethodEnum._01) + return "01"; + + if (value == ThreeDSReqAuthMethodEnum._02) + return "02"; + + if (value == ThreeDSReqAuthMethodEnum._03) + return "03"; + + if (value == ThreeDSReqAuthMethodEnum._04) + return "04"; + + if (value == ThreeDSReqAuthMethodEnum._05) + return "05"; + + if (value == ThreeDSReqAuthMethodEnum._06) + return "06"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSReqAuthMethodEnum. + /// + public class ThreeDSReqAuthMethodEnumJsonConverter : JsonConverter + { + public override ThreeDSReqAuthMethodEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSReqAuthMethodEnum.FromStringOrDefault(value) ?? new ThreeDSReqAuthMethodEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSReqAuthMethodEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSReqAuthMethodEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthMethodOption { get; private set; } + + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + /// + /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Allowed values: * **01** — No 3DS Requestor authentication occurred (for example, cardholder “logged in” as guest). * **02** — Login to the cardholder account at the 3DS Requestor system using 3DS Requestor’s own credentials. * **03** — Login to the cardholder account at the 3DS Requestor system using federated ID. * **04** — Login to the cardholder account at the 3DS Requestor system using issuer credentials. * **05** — Login to the cardholder account at the 3DS Requestor system using third-party authentication. * **06** — Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. + [JsonPropertyName("threeDSReqAuthMethod")] + public ThreeDSReqAuthMethodEnum? ThreeDSReqAuthMethod { get { return this._ThreeDSReqAuthMethodOption; } set { this._ThreeDSReqAuthMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthDataOption { get; private set; } + + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + [JsonPropertyName("threeDSReqAuthData")] + public string? ThreeDSReqAuthData { get { return this._ThreeDSReqAuthDataOption; } set { this._ThreeDSReqAuthDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqAuthTimestampOption { get; private set; } + + /// + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + /// + /// Date and time in UTC of the cardholder authentication. Format: YYYYMMDDHHMM + [JsonPropertyName("threeDSReqAuthTimestamp")] + public string? ThreeDSReqAuthTimestamp { get { return this._ThreeDSReqAuthTimestampOption; } set { this._ThreeDSReqAuthTimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSRequestorAuthenticationInfo {\n"); + sb.Append(" ThreeDSReqAuthData: ").Append(ThreeDSReqAuthData).Append("\n"); + sb.Append(" ThreeDSReqAuthMethod: ").Append(ThreeDSReqAuthMethod).Append("\n"); + sb.Append(" ThreeDSReqAuthTimestamp: ").Append(ThreeDSReqAuthTimestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ThreeDSReqAuthTimestamp (string) maxLength + if (this.ThreeDSReqAuthTimestamp != null && this.ThreeDSReqAuthTimestamp.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqAuthTimestamp, length must be less than 12.", new [] { "ThreeDSReqAuthTimestamp" }); + } + + // ThreeDSReqAuthTimestamp (string) minLength + if (this.ThreeDSReqAuthTimestamp != null && this.ThreeDSReqAuthTimestamp.Length < 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqAuthTimestamp, length must be greater than 12.", new [] { "ThreeDSReqAuthTimestamp" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSRequestorAuthenticationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSRequestorAuthenticationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDSReqAuthData = default; + Option threeDSReqAuthMethod = default; + Option threeDSReqAuthTimestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDSReqAuthData": + threeDSReqAuthData = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqAuthMethod": + string? threeDSReqAuthMethodRawValue = utf8JsonReader.GetString(); + threeDSReqAuthMethod = new Option(ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.FromStringOrDefault(threeDSReqAuthMethodRawValue)); + break; + case "threeDSReqAuthTimestamp": + threeDSReqAuthTimestamp = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSRequestorAuthenticationInfo(threeDSReqAuthData, threeDSReqAuthMethod, threeDSReqAuthTimestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorAuthenticationInfo threeDSRequestorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSRequestorAuthenticationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSRequestorAuthenticationInfo threeDSRequestorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthDataOption.IsSet) + if (threeDSRequestorAuthenticationInfo.ThreeDSReqAuthData != null) + writer.WriteString("threeDSReqAuthData", threeDSRequestorAuthenticationInfo.ThreeDSReqAuthData); + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthMethodOption.IsSet && threeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethod != null) + { + string? threeDSReqAuthMethodRawValue = ThreeDSRequestorAuthenticationInfo.ThreeDSReqAuthMethodEnum.ToJsonValue(threeDSRequestorAuthenticationInfo._ThreeDSReqAuthMethodOption.Value!.Value); + writer.WriteString("threeDSReqAuthMethod", threeDSReqAuthMethodRawValue); + } + + if (threeDSRequestorAuthenticationInfo._ThreeDSReqAuthTimestampOption.IsSet) + if (threeDSRequestorAuthenticationInfo.ThreeDSReqAuthTimestamp != null) + writer.WriteString("threeDSReqAuthTimestamp", threeDSRequestorAuthenticationInfo.ThreeDSReqAuthTimestamp); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDSRequestorPriorAuthenticationInfo.cs b/Adyen/Payment/Models/ThreeDSRequestorPriorAuthenticationInfo.cs new file mode 100644 index 000000000..992f7f5f0 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDSRequestorPriorAuthenticationInfo.cs @@ -0,0 +1,400 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDSRequestorPriorAuthenticationInfo. + /// + public partial class ThreeDSRequestorPriorAuthenticationInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + [JsonConstructor] + public ThreeDSRequestorPriorAuthenticationInfo(Option threeDSReqPriorAuthData = default, Option threeDSReqPriorAuthMethod = default, Option threeDSReqPriorAuthTimestamp = default, Option threeDSReqPriorRef = default) + { + _ThreeDSReqPriorAuthDataOption = threeDSReqPriorAuthData; + _ThreeDSReqPriorAuthMethodOption = threeDSReqPriorAuthMethod; + _ThreeDSReqPriorAuthTimestampOption = threeDSReqPriorAuthTimestamp; + _ThreeDSReqPriorRefOption = threeDSReqPriorRef; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSRequestorPriorAuthenticationInfo() + { + } + + partial void OnCreated(); + + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + [JsonConverter(typeof(ThreeDSReqPriorAuthMethodEnumJsonConverter))] + public class ThreeDSReqPriorAuthMethodEnum : IEnum + { + /// + /// Returns the value of the ThreeDSReqPriorAuthMethodEnum. + /// + public string? Value { get; set; } + + /// + /// ThreeDSReqPriorAuthMethodEnum._01 - 01 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _01 = new("01"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._02 - 02 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _02 = new("02"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._03 - 03 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _03 = new("03"); + + /// + /// ThreeDSReqPriorAuthMethodEnum._04 - 04 + /// + public static readonly ThreeDSReqPriorAuthMethodEnum _04 = new("04"); + + private ThreeDSReqPriorAuthMethodEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ThreeDSReqPriorAuthMethodEnum?(string? value) => value == null ? null : new ThreeDSReqPriorAuthMethodEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ThreeDSReqPriorAuthMethodEnum? option) => option?.Value; + + public static bool operator ==(ThreeDSReqPriorAuthMethodEnum? left, ThreeDSReqPriorAuthMethodEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ThreeDSReqPriorAuthMethodEnum? left, ThreeDSReqPriorAuthMethodEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ThreeDSReqPriorAuthMethodEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ThreeDSReqPriorAuthMethodEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ThreeDSReqPriorAuthMethodEnum._01, + "02" => ThreeDSReqPriorAuthMethodEnum._02, + "03" => ThreeDSReqPriorAuthMethodEnum._03, + "04" => ThreeDSReqPriorAuthMethodEnum._04, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ThreeDSReqPriorAuthMethodEnum? value) + { + if (value == null) + return null; + + if (value == ThreeDSReqPriorAuthMethodEnum._01) + return "01"; + + if (value == ThreeDSReqPriorAuthMethodEnum._02) + return "02"; + + if (value == ThreeDSReqPriorAuthMethodEnum._03) + return "03"; + + if (value == ThreeDSReqPriorAuthMethodEnum._04) + return "04"; + + return null; + } + + /// + /// JsonConverter for writing ThreeDSReqPriorAuthMethodEnum. + /// + public class ThreeDSReqPriorAuthMethodEnumJsonConverter : JsonConverter + { + public override ThreeDSReqPriorAuthMethodEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ThreeDSReqPriorAuthMethodEnum.FromStringOrDefault(value) ?? new ThreeDSReqPriorAuthMethodEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ThreeDSReqPriorAuthMethodEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ThreeDSReqPriorAuthMethodEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthMethodOption { get; private set; } + + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + /// + /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. Allowed values: * **01** — Frictionless authentication occurred by ACS. * **02** — Cardholder challenge occurred by ACS. * **03** — AVS verified. * **04** — Other issuer methods. + [JsonPropertyName("threeDSReqPriorAuthMethod")] + public ThreeDSReqPriorAuthMethodEnum? ThreeDSReqPriorAuthMethod { get { return this._ThreeDSReqPriorAuthMethodOption; } set { this._ThreeDSReqPriorAuthMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthDataOption { get; private set; } + + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + /// + /// Data that documents and supports a specific authentication process. Maximum length: 2048 bytes. + [JsonPropertyName("threeDSReqPriorAuthData")] + public string? ThreeDSReqPriorAuthData { get { return this._ThreeDSReqPriorAuthDataOption; } set { this._ThreeDSReqPriorAuthDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorAuthTimestampOption { get; private set; } + + /// + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + /// + /// Date and time in UTC of the prior cardholder authentication. Format: YYYYMMDDHHMM + [JsonPropertyName("threeDSReqPriorAuthTimestamp")] + public string? ThreeDSReqPriorAuthTimestamp { get { return this._ThreeDSReqPriorAuthTimestampOption; } set { this._ThreeDSReqPriorAuthTimestampOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSReqPriorRefOption { get; private set; } + + /// + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + /// + /// This data element provides additional information to the ACS to determine the best approach for handing a request. This data element contains an ACS Transaction ID for a prior authenticated transaction. For example, the first recurring transaction that was authenticated with the cardholder. Length: 30 characters. + [JsonPropertyName("threeDSReqPriorRef")] + public string? ThreeDSReqPriorRef { get { return this._ThreeDSReqPriorRefOption; } set { this._ThreeDSReqPriorRefOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSRequestorPriorAuthenticationInfo {\n"); + sb.Append(" ThreeDSReqPriorAuthData: ").Append(ThreeDSReqPriorAuthData).Append("\n"); + sb.Append(" ThreeDSReqPriorAuthMethod: ").Append(ThreeDSReqPriorAuthMethod).Append("\n"); + sb.Append(" ThreeDSReqPriorAuthTimestamp: ").Append(ThreeDSReqPriorAuthTimestamp).Append("\n"); + sb.Append(" ThreeDSReqPriorRef: ").Append(ThreeDSReqPriorRef).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ThreeDSReqPriorAuthTimestamp (string) maxLength + if (this.ThreeDSReqPriorAuthTimestamp != null && this.ThreeDSReqPriorAuthTimestamp.Length > 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorAuthTimestamp, length must be less than 12.", new [] { "ThreeDSReqPriorAuthTimestamp" }); + } + + // ThreeDSReqPriorAuthTimestamp (string) minLength + if (this.ThreeDSReqPriorAuthTimestamp != null && this.ThreeDSReqPriorAuthTimestamp.Length < 12) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorAuthTimestamp, length must be greater than 12.", new [] { "ThreeDSReqPriorAuthTimestamp" }); + } + + // ThreeDSReqPriorRef (string) maxLength + if (this.ThreeDSReqPriorRef != null && this.ThreeDSReqPriorRef.Length > 36) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorRef, length must be less than 36.", new [] { "ThreeDSReqPriorRef" }); + } + + // ThreeDSReqPriorRef (string) minLength + if (this.ThreeDSReqPriorRef != null && this.ThreeDSReqPriorRef.Length < 36) + { + yield return new ValidationResult("Invalid value for ThreeDSReqPriorRef, length must be greater than 36.", new [] { "ThreeDSReqPriorRef" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSRequestorPriorAuthenticationInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSRequestorPriorAuthenticationInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option threeDSReqPriorAuthData = default; + Option threeDSReqPriorAuthMethod = default; + Option threeDSReqPriorAuthTimestamp = default; + Option threeDSReqPriorRef = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "threeDSReqPriorAuthData": + threeDSReqPriorAuthData = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqPriorAuthMethod": + string? threeDSReqPriorAuthMethodRawValue = utf8JsonReader.GetString(); + threeDSReqPriorAuthMethod = new Option(ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.FromStringOrDefault(threeDSReqPriorAuthMethodRawValue)); + break; + case "threeDSReqPriorAuthTimestamp": + threeDSReqPriorAuthTimestamp = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSReqPriorRef": + threeDSReqPriorRef = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSRequestorPriorAuthenticationInfo(threeDSReqPriorAuthData, threeDSReqPriorAuthMethod, threeDSReqPriorAuthTimestamp, threeDSReqPriorRef); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSRequestorPriorAuthenticationInfo threeDSRequestorPriorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSRequestorPriorAuthenticationInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSRequestorPriorAuthenticationInfo threeDSRequestorPriorAuthenticationInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthDataOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthData != null) + writer.WriteString("threeDSReqPriorAuthData", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthData); + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthMethodOption.IsSet && threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethod != null) + { + string? threeDSReqPriorAuthMethodRawValue = ThreeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthMethodEnum.ToJsonValue(threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthMethodOption.Value!.Value); + writer.WriteString("threeDSReqPriorAuthMethod", threeDSReqPriorAuthMethodRawValue); + } + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorAuthTimestampOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthTimestamp != null) + writer.WriteString("threeDSReqPriorAuthTimestamp", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorAuthTimestamp); + + if (threeDSRequestorPriorAuthenticationInfo._ThreeDSReqPriorRefOption.IsSet) + if (threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorRef != null) + writer.WriteString("threeDSReqPriorRef", threeDSRequestorPriorAuthenticationInfo.ThreeDSReqPriorRef); + } + } +} diff --git a/Adyen/Payment/Models/ThreeDSecureData.cs b/Adyen/Payment/Models/ThreeDSecureData.cs new file mode 100644 index 000000000..e28c87f11 --- /dev/null +++ b/Adyen/Payment/Models/ThreeDSecureData.cs @@ -0,0 +1,891 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// ThreeDSecureData. + /// + public partial class ThreeDSecureData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + /// The CAVV algorithm used. Include this only for 3D Secure 1. + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + /// The electronic commerce indicator. + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + /// The version of the 3D Secure protocol. + /// Network token authentication verification value (TAVV). The network token cryptogram. + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + [JsonConstructor] + public ThreeDSecureData(Option authenticationResponse = default, Option cavv = default, Option cavvAlgorithm = default, Option challengeCancel = default, Option directoryResponse = default, Option dsTransID = default, Option eci = default, Option riskScore = default, Option threeDSVersion = default, Option tokenAuthenticationVerificationValue = default, Option transStatusReason = default, Option xid = default) + { + _AuthenticationResponseOption = authenticationResponse; + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _ChallengeCancelOption = challengeCancel; + _DirectoryResponseOption = directoryResponse; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _RiskScoreOption = riskScore; + _ThreeDSVersionOption = threeDSVersion; + _TokenAuthenticationVerificationValueOption = tokenAuthenticationVerificationValue; + _TransStatusReasonOption = transStatusReason; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSecureData() + { + } + + partial void OnCreated(); + + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + [JsonConverter(typeof(AuthenticationResponseEnumJsonConverter))] + public class AuthenticationResponseEnum : IEnum + { + /// + /// Returns the value of the AuthenticationResponseEnum. + /// + public string? Value { get; set; } + + /// + /// AuthenticationResponseEnum.Y - Y + /// + public static readonly AuthenticationResponseEnum Y = new("Y"); + + /// + /// AuthenticationResponseEnum.N - N + /// + public static readonly AuthenticationResponseEnum N = new("N"); + + /// + /// AuthenticationResponseEnum.U - U + /// + public static readonly AuthenticationResponseEnum U = new("U"); + + /// + /// AuthenticationResponseEnum.A - A + /// + public static readonly AuthenticationResponseEnum A = new("A"); + + private AuthenticationResponseEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AuthenticationResponseEnum?(string? value) => value == null ? null : new AuthenticationResponseEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AuthenticationResponseEnum? option) => option?.Value; + + public static bool operator ==(AuthenticationResponseEnum? left, AuthenticationResponseEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AuthenticationResponseEnum? left, AuthenticationResponseEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AuthenticationResponseEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AuthenticationResponseEnum? FromStringOrDefault(string value) + { + return value switch { + "Y" => AuthenticationResponseEnum.Y, + "N" => AuthenticationResponseEnum.N, + "U" => AuthenticationResponseEnum.U, + "A" => AuthenticationResponseEnum.A, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AuthenticationResponseEnum? value) + { + if (value == null) + return null; + + if (value == AuthenticationResponseEnum.Y) + return "Y"; + + if (value == AuthenticationResponseEnum.N) + return "N"; + + if (value == AuthenticationResponseEnum.U) + return "U"; + + if (value == AuthenticationResponseEnum.A) + return "A"; + + return null; + } + + /// + /// JsonConverter for writing AuthenticationResponseEnum. + /// + public class AuthenticationResponseEnumJsonConverter : JsonConverter + { + public override AuthenticationResponseEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AuthenticationResponseEnum.FromStringOrDefault(value) ?? new AuthenticationResponseEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AuthenticationResponseEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AuthenticationResponseEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthenticationResponseOption { get; private set; } + + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + /// + /// In 3D Secure 2, this is the `transStatus` from the challenge result. If the transaction was frictionless, omit this parameter. + [JsonPropertyName("authenticationResponse")] + public AuthenticationResponseEnum? AuthenticationResponse { get { return this._AuthenticationResponseOption; } set { this._AuthenticationResponseOption = new(value); } } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonConverter(typeof(ChallengeCancelEnumJsonConverter))] + public class ChallengeCancelEnum : IEnum + { + /// + /// Returns the value of the ChallengeCancelEnum. + /// + public string? Value { get; set; } + + /// + /// ChallengeCancelEnum._01 - 01 + /// + public static readonly ChallengeCancelEnum _01 = new("01"); + + /// + /// ChallengeCancelEnum._02 - 02 + /// + public static readonly ChallengeCancelEnum _02 = new("02"); + + /// + /// ChallengeCancelEnum._03 - 03 + /// + public static readonly ChallengeCancelEnum _03 = new("03"); + + /// + /// ChallengeCancelEnum._04 - 04 + /// + public static readonly ChallengeCancelEnum _04 = new("04"); + + /// + /// ChallengeCancelEnum._05 - 05 + /// + public static readonly ChallengeCancelEnum _05 = new("05"); + + /// + /// ChallengeCancelEnum._06 - 06 + /// + public static readonly ChallengeCancelEnum _06 = new("06"); + + /// + /// ChallengeCancelEnum._07 - 07 + /// + public static readonly ChallengeCancelEnum _07 = new("07"); + + private ChallengeCancelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ChallengeCancelEnum?(string? value) => value == null ? null : new ChallengeCancelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ChallengeCancelEnum? option) => option?.Value; + + public static bool operator ==(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ChallengeCancelEnum? left, ChallengeCancelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ChallengeCancelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ChallengeCancelEnum? FromStringOrDefault(string value) + { + return value switch { + "01" => ChallengeCancelEnum._01, + "02" => ChallengeCancelEnum._02, + "03" => ChallengeCancelEnum._03, + "04" => ChallengeCancelEnum._04, + "05" => ChallengeCancelEnum._05, + "06" => ChallengeCancelEnum._06, + "07" => ChallengeCancelEnum._07, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ChallengeCancelEnum? value) + { + if (value == null) + return null; + + if (value == ChallengeCancelEnum._01) + return "01"; + + if (value == ChallengeCancelEnum._02) + return "02"; + + if (value == ChallengeCancelEnum._03) + return "03"; + + if (value == ChallengeCancelEnum._04) + return "04"; + + if (value == ChallengeCancelEnum._05) + return "05"; + + if (value == ChallengeCancelEnum._06) + return "06"; + + if (value == ChallengeCancelEnum._07) + return "07"; + + return null; + } + + /// + /// JsonConverter for writing ChallengeCancelEnum. + /// + public class ChallengeCancelEnumJsonConverter : JsonConverter + { + public override ChallengeCancelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ChallengeCancelEnum.FromStringOrDefault(value) ?? new ChallengeCancelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ChallengeCancelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ChallengeCancelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ChallengeCancelOption { get; private set; } + + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + /// + /// Indicator informing the Access Control Server (ACS) and the Directory Server (DS) that the authentication has been cancelled. For possible values, refer to [3D Secure API reference](https://docs.adyen.com/online-payments/3d-secure/api-reference#mpidata). + [JsonPropertyName("challengeCancel")] + public ChallengeCancelEnum? ChallengeCancel { get { return this._ChallengeCancelOption; } set { this._ChallengeCancelOption = new(value); } } + + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + [JsonConverter(typeof(DirectoryResponseEnumJsonConverter))] + public class DirectoryResponseEnum : IEnum + { + /// + /// Returns the value of the DirectoryResponseEnum. + /// + public string? Value { get; set; } + + /// + /// DirectoryResponseEnum.A - A + /// + public static readonly DirectoryResponseEnum A = new("A"); + + /// + /// DirectoryResponseEnum.C - C + /// + public static readonly DirectoryResponseEnum C = new("C"); + + /// + /// DirectoryResponseEnum.D - D + /// + public static readonly DirectoryResponseEnum D = new("D"); + + /// + /// DirectoryResponseEnum.I - I + /// + public static readonly DirectoryResponseEnum I = new("I"); + + /// + /// DirectoryResponseEnum.N - N + /// + public static readonly DirectoryResponseEnum N = new("N"); + + /// + /// DirectoryResponseEnum.R - R + /// + public static readonly DirectoryResponseEnum R = new("R"); + + /// + /// DirectoryResponseEnum.U - U + /// + public static readonly DirectoryResponseEnum U = new("U"); + + /// + /// DirectoryResponseEnum.Y - Y + /// + public static readonly DirectoryResponseEnum Y = new("Y"); + + private DirectoryResponseEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DirectoryResponseEnum?(string? value) => value == null ? null : new DirectoryResponseEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DirectoryResponseEnum? option) => option?.Value; + + public static bool operator ==(DirectoryResponseEnum? left, DirectoryResponseEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DirectoryResponseEnum? left, DirectoryResponseEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DirectoryResponseEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DirectoryResponseEnum? FromStringOrDefault(string value) + { + return value switch { + "A" => DirectoryResponseEnum.A, + "C" => DirectoryResponseEnum.C, + "D" => DirectoryResponseEnum.D, + "I" => DirectoryResponseEnum.I, + "N" => DirectoryResponseEnum.N, + "R" => DirectoryResponseEnum.R, + "U" => DirectoryResponseEnum.U, + "Y" => DirectoryResponseEnum.Y, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DirectoryResponseEnum? value) + { + if (value == null) + return null; + + if (value == DirectoryResponseEnum.A) + return "A"; + + if (value == DirectoryResponseEnum.C) + return "C"; + + if (value == DirectoryResponseEnum.D) + return "D"; + + if (value == DirectoryResponseEnum.I) + return "I"; + + if (value == DirectoryResponseEnum.N) + return "N"; + + if (value == DirectoryResponseEnum.R) + return "R"; + + if (value == DirectoryResponseEnum.U) + return "U"; + + if (value == DirectoryResponseEnum.Y) + return "Y"; + + return null; + } + + /// + /// JsonConverter for writing DirectoryResponseEnum. + /// + public class DirectoryResponseEnumJsonConverter : JsonConverter + { + public override DirectoryResponseEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DirectoryResponseEnum.FromStringOrDefault(value) ?? new DirectoryResponseEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DirectoryResponseEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DirectoryResponseEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectoryResponseOption { get; private set; } + + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + /// + /// In 3D Secure 2, this is the `transStatus` from the `ARes`. + [JsonPropertyName("directoryResponse")] + public DirectoryResponseEnum? DirectoryResponse { get { return this._DirectoryResponseOption; } set { this._DirectoryResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + /// + /// The cardholder authentication value (base64 encoded, 20 bytes in a decoded form). + [JsonPropertyName("cavv")] + public byte[]? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. Include this only for 3D Secure 1. + /// + /// The CAVV algorithm used. Include this only for 3D Secure 1. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The electronic commerce indicator. + /// + /// The electronic commerce indicator. + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RiskScoreOption { get; private set; } + + /// + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + /// + /// Risk score calculated by Directory Server (DS). Required for Cartes Bancaires integrations. + [JsonPropertyName("riskScore")] + public string? RiskScore { get { return this._RiskScoreOption; } set { this._RiskScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The version of the 3D Secure protocol. + /// + /// The version of the 3D Secure protocol. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenAuthenticationVerificationValueOption { get; private set; } + + /// + /// Network token authentication verification value (TAVV). The network token cryptogram. + /// + /// Network token authentication verification value (TAVV). The network token cryptogram. + [JsonPropertyName("tokenAuthenticationVerificationValue")] + public byte[]? TokenAuthenticationVerificationValue { get { return this._TokenAuthenticationVerificationValueOption; } set { this._TokenAuthenticationVerificationValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransStatusReasonOption { get; private set; } + + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + /// + /// Provides information on why the `transStatus` field has the specified value. For possible values, refer to [our docs](https://docs.adyen.com/online-payments/3d-secure/api-reference#possible-transstatusreason-values). + [JsonPropertyName("transStatusReason")] + public string? TransStatusReason { get { return this._TransStatusReasonOption; } set { this._TransStatusReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + /// + /// Supported for 3D Secure 1. The transaction identifier (Base64-encoded, 20 bytes in a decoded form). + [JsonPropertyName("xid")] + public byte[]? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecureData {\n"); + sb.Append(" AuthenticationResponse: ").Append(AuthenticationResponse).Append("\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ChallengeCancel: ").Append(ChallengeCancel).Append("\n"); + sb.Append(" DirectoryResponse: ").Append(DirectoryResponse).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" RiskScore: ").Append(RiskScore).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append(" TokenAuthenticationVerificationValue: ").Append(TokenAuthenticationVerificationValue).Append("\n"); + sb.Append(" TransStatusReason: ").Append(TransStatusReason).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSecureDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSecureData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authenticationResponse = default; + Option cavv = default; + Option cavvAlgorithm = default; + Option challengeCancel = default; + Option directoryResponse = default; + Option dsTransID = default; + Option eci = default; + Option riskScore = default; + Option threeDSVersion = default; + Option tokenAuthenticationVerificationValue = default; + Option transStatusReason = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authenticationResponse": + string? authenticationResponseRawValue = utf8JsonReader.GetString(); + authenticationResponse = new Option(ThreeDSecureData.AuthenticationResponseEnum.FromStringOrDefault(authenticationResponseRawValue)); + break; + case "cavv": + cavv = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "challengeCancel": + string? challengeCancelRawValue = utf8JsonReader.GetString(); + challengeCancel = new Option(ThreeDSecureData.ChallengeCancelEnum.FromStringOrDefault(challengeCancelRawValue)); + break; + case "directoryResponse": + string? directoryResponseRawValue = utf8JsonReader.GetString(); + directoryResponse = new Option(ThreeDSecureData.DirectoryResponseEnum.FromStringOrDefault(directoryResponseRawValue)); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "riskScore": + riskScore = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + case "tokenAuthenticationVerificationValue": + tokenAuthenticationVerificationValue = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transStatusReason": + transStatusReason = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ThreeDSecureData(authenticationResponse, cavv, cavvAlgorithm, challengeCancel, directoryResponse, dsTransID, eci, riskScore, threeDSVersion, tokenAuthenticationVerificationValue, transStatusReason, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSecureData threeDSecureData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSecureData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSecureData threeDSecureData, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSecureData._AuthenticationResponseOption.IsSet && threeDSecureData.AuthenticationResponse != null) + { + string? authenticationResponseRawValue = ThreeDSecureData.AuthenticationResponseEnum.ToJsonValue(threeDSecureData._AuthenticationResponseOption.Value!.Value); + writer.WriteString("authenticationResponse", authenticationResponseRawValue); + } + + if (threeDSecureData._CavvOption.IsSet) + { + writer.WritePropertyName("cavv"); + JsonSerializer.Serialize(writer, threeDSecureData.Cavv, jsonSerializerOptions); + } + if (threeDSecureData._CavvAlgorithmOption.IsSet) + if (threeDSecureData.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", threeDSecureData.CavvAlgorithm); + + if (threeDSecureData._ChallengeCancelOption.IsSet && threeDSecureData.ChallengeCancel != null) + { + string? challengeCancelRawValue = ThreeDSecureData.ChallengeCancelEnum.ToJsonValue(threeDSecureData._ChallengeCancelOption.Value!.Value); + writer.WriteString("challengeCancel", challengeCancelRawValue); + } + + if (threeDSecureData._DirectoryResponseOption.IsSet && threeDSecureData.DirectoryResponse != null) + { + string? directoryResponseRawValue = ThreeDSecureData.DirectoryResponseEnum.ToJsonValue(threeDSecureData._DirectoryResponseOption.Value!.Value); + writer.WriteString("directoryResponse", directoryResponseRawValue); + } + + if (threeDSecureData._DsTransIDOption.IsSet) + if (threeDSecureData.DsTransID != null) + writer.WriteString("dsTransID", threeDSecureData.DsTransID); + + if (threeDSecureData._EciOption.IsSet) + if (threeDSecureData.Eci != null) + writer.WriteString("eci", threeDSecureData.Eci); + + if (threeDSecureData._RiskScoreOption.IsSet) + if (threeDSecureData.RiskScore != null) + writer.WriteString("riskScore", threeDSecureData.RiskScore); + + if (threeDSecureData._ThreeDSVersionOption.IsSet) + if (threeDSecureData.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", threeDSecureData.ThreeDSVersion); + + if (threeDSecureData._TokenAuthenticationVerificationValueOption.IsSet) + { + writer.WritePropertyName("tokenAuthenticationVerificationValue"); + JsonSerializer.Serialize(writer, threeDSecureData.TokenAuthenticationVerificationValue, jsonSerializerOptions); + } + if (threeDSecureData._TransStatusReasonOption.IsSet) + if (threeDSecureData.TransStatusReason != null) + writer.WriteString("transStatusReason", threeDSecureData.TransStatusReason); + + if (threeDSecureData._XidOption.IsSet) + { + writer.WritePropertyName("xid"); + JsonSerializer.Serialize(writer, threeDSecureData.Xid, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payment/Models/VoidPendingRefundRequest.cs b/Adyen/Payment/Models/VoidPendingRefundRequest.cs new file mode 100644 index 000000000..422dc0f2f --- /dev/null +++ b/Adyen/Payment/Models/VoidPendingRefundRequest.cs @@ -0,0 +1,423 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payment.Client; + +namespace Adyen.Payment.Models +{ + /// + /// VoidPendingRefundRequest. + /// + public partial class VoidPendingRefundRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account that is used to process the payment. + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// modificationAmount + /// mpiData + /// The original merchant reference to cancel. + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// platformChargebackLogic + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonConstructor] + public VoidPendingRefundRequest(string merchantAccount, Option?> additionalData = default, Option modificationAmount = default, Option mpiData = default, Option originalMerchantReference = default, Option originalReference = default, Option platformChargebackLogic = default, Option reference = default, Option?> splits = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + _AdditionalDataOption = additionalData; + _ModificationAmountOption = modificationAmount; + _MpiDataOption = mpiData; + _OriginalMerchantReferenceOption = originalMerchantReference; + _OriginalReferenceOption = originalReference; + _PlatformChargebackLogicOption = platformChargebackLogic; + _ReferenceOption = reference; + _SplitsOption = splits; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public VoidPendingRefundRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account that is used to process the payment. + /// + /// The merchant account that is used to process the payment. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be required for a particular modification request. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("modificationAmount")] + public Amount? ModificationAmount { get { return this._ModificationAmountOption; } set { this._ModificationAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MpiDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("mpiData")] + public ThreeDSecureData? MpiData { get { return this._MpiDataOption; } set { this._MpiDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalMerchantReferenceOption { get; private set; } + + /// + /// The original merchant reference to cancel. + /// + /// The original merchant reference to cancel. + [JsonPropertyName("originalMerchantReference")] + public string? OriginalMerchantReference { get { return this._OriginalMerchantReferenceOption; } set { this._OriginalMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalReferenceOption { get; private set; } + + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + /// + /// The original pspReference of the payment to modify. This reference is returned in: * authorisation response * authorisation notification + [JsonPropertyName("originalReference")] + public string? OriginalReference { get { return this._OriginalReferenceOption; } set { this._OriginalReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformChargebackLogicOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("platformChargebackLogic")] + public PlatformChargebackLogic? PlatformChargebackLogic { get { return this._PlatformChargebackLogicOption; } set { this._PlatformChargebackLogicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _SplitsOption { get; private set; } + + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + /// + /// An array of objects specifying how the amount should be split between accounts when using Adyen for Platforms. For more information, see how to split payments for [platforms](https://docs.adyen.com/platforms/automatic-split-configuration/). + [JsonPropertyName("splits")] + public List? Splits { get { return this._SplitsOption; } set { this._SplitsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + /// + /// The transaction reference provided by the PED. For point-of-sale integrations only. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + /// + /// Unique terminal ID for the PED that originally processed the request. For point-of-sale integrations only. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VoidPendingRefundRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ModificationAmount: ").Append(ModificationAmount).Append("\n"); + sb.Append(" MpiData: ").Append(MpiData).Append("\n"); + sb.Append(" OriginalMerchantReference: ").Append(OriginalMerchantReference).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" PlatformChargebackLogic: ").Append(PlatformChargebackLogic).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Splits: ").Append(Splits).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VoidPendingRefundRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override VoidPendingRefundRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> additionalData = default; + Option modificationAmount = default; + Option mpiData = default; + Option originalMerchantReference = default; + Option originalReference = default; + Option platformChargebackLogic = default; + Option reference = default; + Option?> splits = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "modificationAmount": + modificationAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mpiData": + mpiData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalMerchantReference": + originalMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformChargebackLogic": + platformChargebackLogic = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "splits": + splits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class VoidPendingRefundRequest.", nameof(merchantAccount)); + + return new VoidPendingRefundRequest(merchantAccount.Value!, additionalData, modificationAmount, mpiData, originalMerchantReference, originalReference, platformChargebackLogic, reference, splits, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VoidPendingRefundRequest voidPendingRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, voidPendingRefundRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VoidPendingRefundRequest voidPendingRefundRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (voidPendingRefundRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", voidPendingRefundRequest.MerchantAccount); + + if (voidPendingRefundRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, voidPendingRefundRequest.AdditionalData, jsonSerializerOptions); + } + if (voidPendingRefundRequest._ModificationAmountOption.IsSet) + { + writer.WritePropertyName("modificationAmount"); + JsonSerializer.Serialize(writer, voidPendingRefundRequest.ModificationAmount, jsonSerializerOptions); + } + if (voidPendingRefundRequest._MpiDataOption.IsSet) + { + writer.WritePropertyName("mpiData"); + JsonSerializer.Serialize(writer, voidPendingRefundRequest.MpiData, jsonSerializerOptions); + } + if (voidPendingRefundRequest._OriginalMerchantReferenceOption.IsSet) + if (voidPendingRefundRequest.OriginalMerchantReference != null) + writer.WriteString("originalMerchantReference", voidPendingRefundRequest.OriginalMerchantReference); + + if (voidPendingRefundRequest._OriginalReferenceOption.IsSet) + if (voidPendingRefundRequest.OriginalReference != null) + writer.WriteString("originalReference", voidPendingRefundRequest.OriginalReference); + + if (voidPendingRefundRequest._PlatformChargebackLogicOption.IsSet) + { + writer.WritePropertyName("platformChargebackLogic"); + JsonSerializer.Serialize(writer, voidPendingRefundRequest.PlatformChargebackLogic, jsonSerializerOptions); + } + if (voidPendingRefundRequest._ReferenceOption.IsSet) + if (voidPendingRefundRequest.Reference != null) + writer.WriteString("reference", voidPendingRefundRequest.Reference); + + if (voidPendingRefundRequest._SplitsOption.IsSet) + { + writer.WritePropertyName("splits"); + JsonSerializer.Serialize(writer, voidPendingRefundRequest.Splits, jsonSerializerOptions); + } + if (voidPendingRefundRequest._TenderReferenceOption.IsSet) + if (voidPendingRefundRequest.TenderReference != null) + writer.WriteString("tenderReference", voidPendingRefundRequest.TenderReference); + + if (voidPendingRefundRequest._UniqueTerminalIdOption.IsSet) + if (voidPendingRefundRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", voidPendingRefundRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/Payment/Services/ModificationsService.cs b/Adyen/Payment/Services/ModificationsService.cs new file mode 100644 index 000000000..913d28d87 --- /dev/null +++ b/Adyen/Payment/Services/ModificationsService.cs @@ -0,0 +1,3650 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Payment.Client; +using Adyen.Payment.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Payment.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IModificationsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ModificationsServiceEvents Events { get; } + + /// + /// Change the authorised amount + /// + /// + /// Allows you to increase or decrease the authorised amount after the initial authorisation has taken place. This functionality enables for example tipping, improving the chances your authorisation will be valid, or charging the shopper when they have already left the merchant premises. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). > If you have a [newer integration](https://docs.adyen.com/online-payments), and are doing: > * [Asynchronous adjustments](https://docs.adyen.com/online-payments/adjust-authorisation#asynchronous-or-synchronous-adjustment), use the [`/payments/{paymentPspReference}/amountUpdates`](https://docs.adyen.com/api-explorer/#/CheckoutService/v67/post/payments/{paymentPspReference}/amountUpdates) endpoint on Checkout API. > * [Synchronous adjustments](https://docs.adyen.com/online-payments/adjust-authorisation#asynchronous-or-synchronous-adjustment), use this endpoint. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task AdjustAuthorisationAsync(AdjustAuthorisationRequest adjustAuthorisationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel an authorisation + /// + /// + /// Cancels the authorisation hold on a payment, returning a unique reference for this request. You can cancel payments after authorisation only for payment methods that support distinct authorisations and captures. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/cancels) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CancelAsync(CancelRequest cancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel or refund a payment + /// + /// + /// Cancels a payment if it has not been captured yet, or refunds it if it has already been captured. This is useful when it is not certain if the payment has been captured or not (for example, when using auto-capture). Do not use this endpoint for payments that involve: * [Multiple partial captures](https://docs.adyen.com/online-payments/capture). * [Split data](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information) either at time of payment or capture for Adyen for Platforms. Instead, check if the payment has been captured and make a corresponding [`/refund`](https://docs.adyen.com/api-explorer/#/Payment/refund) or [`/cancel`](https://docs.adyen.com/api-explorer/#/Payment/cancel) call. For more information, refer to [Cancel or refund](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel-or-refund). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/reversals) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CancelOrRefundAsync(CancelOrRefundRequest cancelOrRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Capture an authorisation + /// + /// + /// Captures the authorisation hold on a payment, returning a unique reference for this request. Usually the full authorisation amount is captured, however it's also possible to capture a smaller amount, which results in cancelling the remaining authorisation balance. Payment methods that are captured automatically after authorisation don't need to be captured. However, submitting a capture request on these transactions will not result in double charges. If immediate or delayed auto-capture is enabled, calling the capture method is not necessary. For more information refer to [Capture](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/capture). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/captures`](https://docs.adyen.com/api-explorer/#/CheckoutService/v67/post/payments/{paymentPspReference}/captures) endpoint on Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CaptureAsync(CaptureRequest captureRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a donation + /// + /// + /// Schedules a new payment to be created (including a new authorisation request) for the specified donation using the payment details of the original payment. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/donations`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/donations) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + [Obsolete("")] + Task DonateAsync(DonationRequest donationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Refund a captured payment + /// + /// + /// Refunds a payment that has previously been captured, returning a unique reference for this request. Refunding can be done on the full captured amount or a partial amount. Multiple (partial) refunds will be accepted as long as their sum doesn't exceed the captured amount. Payments which have been authorised, but not captured, cannot be refunded, use the /cancel method instead. Some payment methods/gateways do not support partial/multiple refunds. A margin above the captured limit can be configured to cover shipping/handling costs. For more information, refer to [Refund](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/refund). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/refunds`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/refunds) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task RefundAsync(RefundRequest refundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel an authorisation using your reference + /// + /// + /// This endpoint allows you to cancel a payment if you do not have the PSP reference of the original payment request available. In your call, refer to the original payment by using the `reference` that you specified in your payment request. For more information, see [Technical cancel](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel#technical-cancel). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/cancels) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task TechnicalCancelAsync(TechnicalCancelRequest technicalCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel an in-person refund + /// + /// + /// This endpoint allows you to cancel an unreferenced refund request before it has been completed. In your call, you can refer to the original refund request either by using the `tenderReference`, or the `pspReference`. We recommend implementing based on the `tenderReference`, as this is generated for both offline and online transactions. For more information, refer to [Cancel an unreferenced refund](https://docs.adyen.com/point-of-sale/refund-payment/cancel-unreferenced). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task VoidPendingRefundAsync(VoidPendingRefundRequest voidPendingRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAdjustAuthorisationApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICancelApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICancelOrRefundApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICaptureApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDonateApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRefundApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ITechnicalCancelApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IVoidPendingRefundApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ModificationsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAdjustAuthorisation; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAdjustAuthorisation; + + internal void ExecuteOnAdjustAuthorisation(ModificationsService.AdjustAuthorisationApiResponse apiResponse) + { + OnAdjustAuthorisation?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAdjustAuthorisation(Exception exception) + { + OnErrorAdjustAuthorisation?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancel; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancel; + + internal void ExecuteOnCancel(ModificationsService.CancelApiResponse apiResponse) + { + OnCancel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancel(Exception exception) + { + OnErrorCancel?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelOrRefund; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelOrRefund; + + internal void ExecuteOnCancelOrRefund(ModificationsService.CancelOrRefundApiResponse apiResponse) + { + OnCancelOrRefund?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelOrRefund(Exception exception) + { + OnErrorCancelOrRefund?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCapture; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCapture; + + internal void ExecuteOnCapture(ModificationsService.CaptureApiResponse apiResponse) + { + OnCapture?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCapture(Exception exception) + { + OnErrorCapture?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDonate; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDonate; + + internal void ExecuteOnDonate(ModificationsService.DonateApiResponse apiResponse) + { + OnDonate?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDonate(Exception exception) + { + OnErrorDonate?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRefund; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRefund; + + internal void ExecuteOnRefund(ModificationsService.RefundApiResponse apiResponse) + { + OnRefund?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRefund(Exception exception) + { + OnErrorRefund?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnTechnicalCancel; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorTechnicalCancel; + + internal void ExecuteOnTechnicalCancel(ModificationsService.TechnicalCancelApiResponse apiResponse) + { + OnTechnicalCancel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTechnicalCancel(Exception exception) + { + OnErrorTechnicalCancel?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnVoidPendingRefund; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorVoidPendingRefund; + + internal void ExecuteOnVoidPendingRefund(ModificationsService.VoidPendingRefundApiResponse apiResponse) + { + OnVoidPendingRefund?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorVoidPendingRefund(Exception exception) + { + OnErrorVoidPendingRefund?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ModificationsService : IModificationsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ModificationsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ModificationsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ModificationsServiceEvents modificationsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = modificationsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Change the authorised amount Allows you to increase or decrease the authorised amount after the initial authorisation has taken place. This functionality enables for example tipping, improving the chances your authorisation will be valid, or charging the shopper when they have already left the merchant premises. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). > If you have a [newer integration](https://docs.adyen.com/online-payments), and are doing: > * [Asynchronous adjustments](https://docs.adyen.com/online-payments/adjust-authorisation#asynchronous-or-synchronous-adjustment), use the [`/payments/{paymentPspReference}/amountUpdates`](https://docs.adyen.com/api-explorer/#/CheckoutService/v67/post/payments/{paymentPspReference}/amountUpdates) endpoint on Checkout API. > * [Synchronous adjustments](https://docs.adyen.com/online-payments/adjust-authorisation#asynchronous-or-synchronous-adjustment), use this endpoint. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AdjustAuthorisationAsync(AdjustAuthorisationRequest adjustAuthorisationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/adjustAuthorisation" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/adjustAuthorisation"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (adjustAuthorisationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(adjustAuthorisationRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AdjustAuthorisationApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/adjustAuthorisation", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAdjustAuthorisation(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAdjustAuthorisation(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AdjustAuthorisationApiResponse : Adyen.Core.Client.ApiResponse, IAdjustAuthorisationApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AdjustAuthorisationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AdjustAuthorisationApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel an authorisation Cancels the authorisation hold on a payment, returning a unique reference for this request. You can cancel payments after authorisation only for payment methods that support distinct authorisations and captures. For more information, refer to [Cancel](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/cancels) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelAsync(CancelRequest cancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cancel"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (cancelRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(cancelRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancel(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancel(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelApiResponse : Adyen.Core.Client.ApiResponse, ICancelApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel or refund a payment Cancels a payment if it has not been captured yet, or refunds it if it has already been captured. This is useful when it is not certain if the payment has been captured or not (for example, when using auto-capture). Do not use this endpoint for payments that involve: * [Multiple partial captures](https://docs.adyen.com/online-payments/capture). * [Split data](https://docs.adyen.com/classic-platforms/processing-payments#providing-split-information) either at time of payment or capture for Adyen for Platforms. Instead, check if the payment has been captured and make a corresponding [`/refund`](https://docs.adyen.com/api-explorer/#/Payment/refund) or [`/cancel`](https://docs.adyen.com/api-explorer/#/Payment/cancel) call. For more information, refer to [Cancel or refund](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel-or-refund). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/reversals`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/reversals) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelOrRefundAsync(CancelOrRefundRequest cancelOrRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cancelOrRefund" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/cancelOrRefund"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (cancelOrRefundRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(cancelOrRefundRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelOrRefundApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/cancelOrRefund", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelOrRefund(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelOrRefund(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelOrRefundApiResponse : Adyen.Core.Client.ApiResponse, ICancelOrRefundApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrRefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelOrRefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Capture an authorisation Captures the authorisation hold on a payment, returning a unique reference for this request. Usually the full authorisation amount is captured, however it's also possible to capture a smaller amount, which results in cancelling the remaining authorisation balance. Payment methods that are captured automatically after authorisation don't need to be captured. However, submitting a capture request on these transactions will not result in double charges. If immediate or delayed auto-capture is enabled, calling the capture method is not necessary. For more information refer to [Capture](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/capture). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/captures`](https://docs.adyen.com/api-explorer/#/CheckoutService/v67/post/payments/{paymentPspReference}/captures) endpoint on Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CaptureAsync(CaptureRequest captureRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/capture" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/capture"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (captureRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(captureRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CaptureApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/capture", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCapture(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCapture(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CaptureApiResponse : Adyen.Core.Client.ApiResponse, ICaptureApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CaptureApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CaptureApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a donation Schedules a new payment to be created (including a new authorisation request) for the specified donation using the payment details of the original payment. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/donations`](https://docs.adyen.com/api-explorer/#/CheckoutService/latest/post/donations) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DonateAsync(DonationRequest donationRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/donate" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/donate"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (donationRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(donationRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DonateApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/donate", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDonate(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDonate(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DonateApiResponse : Adyen.Core.Client.ApiResponse, IDonateApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DonateApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Refund a captured payment Refunds a payment that has previously been captured, returning a unique reference for this request. Refunding can be done on the full captured amount or a partial amount. Multiple (partial) refunds will be accepted as long as their sum doesn't exceed the captured amount. Payments which have been authorised, but not captured, cannot be refunded, use the /cancel method instead. Some payment methods/gateways do not support partial/multiple refunds. A margin above the captured limit can be configured to cover shipping/handling costs. For more information, refer to [Refund](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/refund). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/{paymentPspReference}/refunds`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/{paymentPspReference}/refunds) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RefundAsync(RefundRequest refundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/refund" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/refund"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (refundRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(refundRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RefundApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/refund", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRefund(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRefund(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RefundApiResponse : Adyen.Core.Client.ApiResponse, IRefundApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel an authorisation using your reference This endpoint allows you to cancel a payment if you do not have the PSP reference of the original payment request available. In your call, refer to the original payment by using the `reference` that you specified in your payment request. For more information, see [Technical cancel](https://docs.adyen.com/online-payments/classic-integrations/modify-payments/cancel#technical-cancel). > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/cancels`](https://docs.adyen.com/api-explorer/#/CheckoutService/cancels) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task TechnicalCancelAsync(TechnicalCancelRequest technicalCancelRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/technicalCancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/technicalCancel"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (technicalCancelRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(technicalCancelRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TechnicalCancelApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/technicalCancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnTechnicalCancel(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorTechnicalCancel(exception); + throw; + } + } + + /// + /// The . + /// + public partial class TechnicalCancelApiResponse : Adyen.Core.Client.ApiResponse, ITechnicalCancelApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TechnicalCancelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TechnicalCancelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel an in-person refund This endpoint allows you to cancel an unreferenced refund request before it has been completed. In your call, you can refer to the original refund request either by using the `tenderReference`, or the `pspReference`. We recommend implementing based on the `tenderReference`, as this is generated for both offline and online transactions. For more information, refer to [Cancel an unreferenced refund](https://docs.adyen.com/point-of-sale/refund-payment/cancel-unreferenced). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task VoidPendingRefundAsync(VoidPendingRefundRequest voidPendingRefundRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/voidPendingRefund" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/voidPendingRefund"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (voidPendingRefundRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(voidPendingRefundRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + VoidPendingRefundApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/voidPendingRefund", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnVoidPendingRefund(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorVoidPendingRefund(exception); + throw; + } + } + + /// + /// The . + /// + public partial class VoidPendingRefundApiResponse : Adyen.Core.Client.ApiResponse, IVoidPendingRefundApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public VoidPendingRefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public VoidPendingRefundApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ModificationResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ModificationResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Payment/Services/PaymentsService.cs b/Adyen/Payment/Services/PaymentsService.cs new file mode 100644 index 000000000..7c49423ea --- /dev/null +++ b/Adyen/Payment/Services/PaymentsService.cs @@ -0,0 +1,2317 @@ +// +/* + * Adyen Payment API + * + * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Payment.Client; +using Adyen.Payment.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Payment.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentsServiceEvents Events { get; } + + /// + /// Create an authorisation + /// + /// + /// Creates a payment with a unique reference (`pspReference`) and attempts to obtain an authorisation hold. For cards, this amount can be captured or cancelled later. Non-card payment methods typically don't support this and will automatically capture as part of the authorisation. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task AuthoriseAsync(PaymentRequest paymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Complete a 3DS authorisation + /// + /// + /// For an authenticated 3D Secure session, completes the payment authorisation. This endpoint must receive the `md` and `paResponse` parameters that you get from the card issuer after a shopper pays via 3D Secure. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce/3d-secure). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/details`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/details) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task Authorise3dAsync(PaymentRequest3d paymentRequest3d, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Complete a 3DS2 authorisation + /// + /// + /// For an authenticated 3D Secure 2 session, completes the payment authorisation. This endpoint must receive the `threeDS2Token` and `threeDS2Result` parameters. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce/3d-secure). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/details`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/details) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task Authorise3ds2Async(PaymentRequest3ds2 paymentRequest3ds2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the 3DS authentication result + /// + /// + /// Return the authentication result after doing a 3D Secure authentication only. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task GetAuthenticationResultAsync(AuthenticationResultRequest authenticationResultRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get the 3DS2 authentication result + /// + /// + /// Retrieves the `threeDS2Result` after doing a 3D Secure 2 authentication only. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task Retrieve3ds2ResultAsync(ThreeDS2ResultRequest threeDS2ResultRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IAuthoriseApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IAuthorise3dApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IAuthorise3ds2ApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAuthenticationResultApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRetrieve3ds2ResultApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAuthorise; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAuthorise; + + internal void ExecuteOnAuthorise(PaymentsService.AuthoriseApiResponse apiResponse) + { + OnAuthorise?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAuthorise(Exception exception) + { + OnErrorAuthorise?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAuthorise3d; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAuthorise3d; + + internal void ExecuteOnAuthorise3d(PaymentsService.Authorise3dApiResponse apiResponse) + { + OnAuthorise3d?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAuthorise3d(Exception exception) + { + OnErrorAuthorise3d?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnAuthorise3ds2; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorAuthorise3ds2; + + internal void ExecuteOnAuthorise3ds2(PaymentsService.Authorise3ds2ApiResponse apiResponse) + { + OnAuthorise3ds2?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAuthorise3ds2(Exception exception) + { + OnErrorAuthorise3ds2?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAuthenticationResult; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAuthenticationResult; + + internal void ExecuteOnGetAuthenticationResult(PaymentsService.GetAuthenticationResultApiResponse apiResponse) + { + OnGetAuthenticationResult?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAuthenticationResult(Exception exception) + { + OnErrorGetAuthenticationResult?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRetrieve3ds2Result; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRetrieve3ds2Result; + + internal void ExecuteOnRetrieve3ds2Result(PaymentsService.Retrieve3ds2ResultApiResponse apiResponse) + { + OnRetrieve3ds2Result?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRetrieve3ds2Result(Exception exception) + { + OnErrorRetrieve3ds2Result?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentsService : IPaymentsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentsServiceEvents paymentsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create an authorisation Creates a payment with a unique reference (`pspReference`) and attempts to obtain an authorisation hold. For cards, this amount can be captured or cancelled later. Non-card payment methods typically don't support this and will automatically capture as part of the authorisation. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task AuthoriseAsync(PaymentRequest paymentRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/authorise" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/authorise"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + AuthoriseApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/authorise", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAuthorise(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAuthorise(exception); + throw; + } + } + + /// + /// The . + /// + public partial class AuthoriseApiResponse : Adyen.Core.Client.ApiResponse, IAuthoriseApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AuthoriseApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public AuthoriseApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.PaymentResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.PaymentResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Complete a 3DS authorisation For an authenticated 3D Secure session, completes the payment authorisation. This endpoint must receive the `md` and `paResponse` parameters that you get from the card issuer after a shopper pays via 3D Secure. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce/3d-secure). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/details`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/details) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task Authorise3dAsync(PaymentRequest3d paymentRequest3d, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/authorise3d" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/authorise3d"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentRequest3d as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentRequest3d, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + Authorise3dApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/authorise3d", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAuthorise3d(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAuthorise3d(exception); + throw; + } + } + + /// + /// The . + /// + public partial class Authorise3dApiResponse : Adyen.Core.Client.ApiResponse, IAuthorise3dApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Authorise3dApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Authorise3dApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.PaymentResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.PaymentResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Complete a 3DS2 authorisation For an authenticated 3D Secure 2 session, completes the payment authorisation. This endpoint must receive the `threeDS2Token` and `threeDS2Result` parameters. > This endpoint is part of our [classic API integration](https://docs.adyen.com/online-payments/classic-integrations/api-integration-ecommerce/3d-secure). If using a [newer integration](https://docs.adyen.com/online-payments), use the [`/payments/details`](https://docs.adyen.com/api-explorer/#/CheckoutService/payments/details) endpoint under Checkout API instead. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task Authorise3ds2Async(PaymentRequest3ds2 paymentRequest3ds2, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/authorise3ds2" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/authorise3ds2"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (paymentRequest3ds2 as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(paymentRequest3ds2, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + Authorise3ds2ApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/authorise3ds2", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnAuthorise3ds2(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorAuthorise3ds2(exception); + throw; + } + } + + /// + /// The . + /// + public partial class Authorise3ds2ApiResponse : Adyen.Core.Client.ApiResponse, IAuthorise3ds2ApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Authorise3ds2ApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Authorise3ds2ApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.PaymentResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.PaymentResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the 3DS authentication result Return the authentication result after doing a 3D Secure authentication only. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAuthenticationResultAsync(AuthenticationResultRequest authenticationResultRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/getAuthenticationResult" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/getAuthenticationResult"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (authenticationResultRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(authenticationResultRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAuthenticationResultApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/getAuthenticationResult", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAuthenticationResult(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAuthenticationResult(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAuthenticationResultApiResponse : Adyen.Core.Client.ApiResponse, IGetAuthenticationResultApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAuthenticationResultApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAuthenticationResultApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.AuthenticationResultResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.AuthenticationResultResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get the 3DS2 authentication result Retrieves the `threeDS2Result` after doing a 3D Secure 2 authentication only. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task Retrieve3ds2ResultAsync(ThreeDS2ResultRequest threeDS2ResultRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/retrieve3ds2Result" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/retrieve3ds2Result"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (threeDS2ResultRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(threeDS2ResultRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + Retrieve3ds2ResultApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/retrieve3ds2Result", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRetrieve3ds2Result(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRetrieve3ds2Result(exception); + throw; + } + } + + /// + /// The . + /// + public partial class Retrieve3ds2ResultApiResponse : Adyen.Core.Client.ApiResponse, IRetrieve3ds2ResultApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Retrieve3ds2ResultApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public Retrieve3ds2ResultApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payment.Models.ThreeDS2ResultResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payment.Models.ThreeDS2ResultResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payment.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payment.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payment.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payment.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payment.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payment.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/PaymentsApp/Client/ApiKeyToken.cs b/Adyen/PaymentsApp/Client/ApiKeyToken.cs new file mode 100644 index 000000000..0db02396b --- /dev/null +++ b/Adyen/PaymentsApp/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.PaymentsApp.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/PaymentsApp/Client/ClientUtils.cs b/Adyen/PaymentsApp/Client/ClientUtils.cs new file mode 100644 index 000000000..5d31ff6d9 --- /dev/null +++ b/Adyen/PaymentsApp/Client/ClientUtils.cs @@ -0,0 +1,313 @@ +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.PaymentsApp.Models; +using Models = Adyen.PaymentsApp.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.PaymentsApp.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/PaymentsApp/Client/HostConfiguration.cs b/Adyen/PaymentsApp/Client/HostConfiguration.cs new file mode 100644 index 000000000..3fe096f79 --- /dev/null +++ b/Adyen/PaymentsApp/Client/HostConfiguration.cs @@ -0,0 +1,134 @@ +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.PaymentsApp.Services; +using Adyen.PaymentsApp.Client; +using Adyen.PaymentsApp.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.PaymentsApp.Client +{ + /// + /// Provides hosting configuration for PaymentsApp + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://management-live.adyen.com/v1"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new BoardingTokenRequestJsonConverter()); + _jsonOptions.Converters.Add(new BoardingTokenResponseJsonConverter()); + _jsonOptions.Converters.Add(new DefaultErrorResponseEntityJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new PaymentsAppDtoJsonConverter()); + _jsonOptions.Converters.Add(new PaymentsAppResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddPaymentsAppHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/PaymentsApp/Client/JsonSerializerOptionsProvider.cs b/Adyen/PaymentsApp/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..c9b0f9db9 --- /dev/null +++ b/Adyen/PaymentsApp/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.PaymentsApp.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/PaymentsApp/Extensions/HostBuilderExtensions.cs b/Adyen/PaymentsApp/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..ceaebe0cb --- /dev/null +++ b/Adyen/PaymentsApp/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.PaymentsApp; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the PaymentsApp API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigurePaymentsApp(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddPaymentsAppHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/PaymentsApp/Extensions/ServiceCollectionExtensions.cs b/Adyen/PaymentsApp/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..735333762 --- /dev/null +++ b/Adyen/PaymentsApp/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen PaymentsApp API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddPaymentsAppServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddPaymentsAppHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/PaymentsApp/Models/BoardingTokenRequest.cs b/Adyen/PaymentsApp/Models/BoardingTokenRequest.cs new file mode 100644 index 000000000..137ed48da --- /dev/null +++ b/Adyen/PaymentsApp/Models/BoardingTokenRequest.cs @@ -0,0 +1,171 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// BoardingTokenRequest. + /// + public partial class BoardingTokenRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The boardingToken request token. + [JsonConstructor] + public BoardingTokenRequest(string boardingRequestToken) + { + BoardingRequestToken = boardingRequestToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BoardingTokenRequest() + { + } + + partial void OnCreated(); + + /// + /// The boardingToken request token. + /// + /// The boardingToken request token. + [JsonPropertyName("boardingRequestToken")] + public string BoardingRequestToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BoardingTokenRequest {\n"); + sb.Append(" BoardingRequestToken: ").Append(BoardingRequestToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BoardingTokenRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BoardingTokenRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option boardingRequestToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "boardingRequestToken": + boardingRequestToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!boardingRequestToken.IsSet) + throw new ArgumentException("Property is required for class BoardingTokenRequest.", nameof(boardingRequestToken)); + + return new BoardingTokenRequest(boardingRequestToken.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BoardingTokenRequest boardingTokenRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, boardingTokenRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BoardingTokenRequest boardingTokenRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (boardingTokenRequest.BoardingRequestToken != null) + writer.WriteString("boardingRequestToken", boardingTokenRequest.BoardingRequestToken); + } + } +} diff --git a/Adyen/PaymentsApp/Models/BoardingTokenResponse.cs b/Adyen/PaymentsApp/Models/BoardingTokenResponse.cs new file mode 100644 index 000000000..e43c8ffe2 --- /dev/null +++ b/Adyen/PaymentsApp/Models/BoardingTokenResponse.cs @@ -0,0 +1,191 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// BoardingTokenResponse. + /// + public partial class BoardingTokenResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The boarding token that allows the Payments App to board. + /// The unique identifier of the Payments App instance. + [JsonConstructor] + public BoardingTokenResponse(string boardingToken, string installationId) + { + BoardingToken = boardingToken; + InstallationId = installationId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BoardingTokenResponse() + { + } + + partial void OnCreated(); + + /// + /// The boarding token that allows the Payments App to board. + /// + /// The boarding token that allows the Payments App to board. + [JsonPropertyName("boardingToken")] + public string BoardingToken { get; set; } + + /// + /// The unique identifier of the Payments App instance. + /// + /// The unique identifier of the Payments App instance. + [JsonPropertyName("installationId")] + public string InstallationId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BoardingTokenResponse {\n"); + sb.Append(" BoardingToken: ").Append(BoardingToken).Append("\n"); + sb.Append(" InstallationId: ").Append(InstallationId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BoardingTokenResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BoardingTokenResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option boardingToken = default; + Option installationId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "boardingToken": + boardingToken = new Option(utf8JsonReader.GetString()!); + break; + case "installationId": + installationId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!boardingToken.IsSet) + throw new ArgumentException("Property is required for class BoardingTokenResponse.", nameof(boardingToken)); + + if (!installationId.IsSet) + throw new ArgumentException("Property is required for class BoardingTokenResponse.", nameof(installationId)); + + return new BoardingTokenResponse(boardingToken.Value!, installationId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BoardingTokenResponse boardingTokenResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, boardingTokenResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BoardingTokenResponse boardingTokenResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (boardingTokenResponse.BoardingToken != null) + writer.WriteString("boardingToken", boardingTokenResponse.BoardingToken); + + if (boardingTokenResponse.InstallationId != null) + writer.WriteString("installationId", boardingTokenResponse.InstallationId); + } + } +} diff --git a/Adyen/PaymentsApp/Models/DefaultErrorResponseEntity.cs b/Adyen/PaymentsApp/Models/DefaultErrorResponseEntity.cs new file mode 100644 index 000000000..e583ed2ae --- /dev/null +++ b/Adyen/PaymentsApp/Models/DefaultErrorResponseEntity.cs @@ -0,0 +1,352 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// Standardized error response following RFC-7807 format. + /// + public partial class DefaultErrorResponseEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// Unique business error code. + /// A URI that identifies the specific occurrence of the problem if applicable. + /// Array of fields with validation errors when applicable. + /// The unique reference for the request. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonConstructor] + public DefaultErrorResponseEntity(Option detail = default, Option errorCode = default, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option status = default, Option title = default, Option type = default) + { + _DetailOption = detail; + _ErrorCodeOption = errorCode; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _StatusOption = status; + _TitleOption = title; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefaultErrorResponseEntity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailOption { get; private set; } + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string? Detail { get { return this._DetailOption; } set { this._DetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// Unique business error code. + /// + /// Unique business error code. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Array of fields with validation errors when applicable. + /// + /// Array of fields with validation errors when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// The unique reference for the request. + /// + /// The unique reference for the request. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefaultErrorResponseEntity {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefaultErrorResponseEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefaultErrorResponseEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option status = default; + Option title = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DefaultErrorResponseEntity(detail, errorCode, instance, invalidFields, requestId, status, title, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defaultErrorResponseEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (defaultErrorResponseEntity._DetailOption.IsSet) + if (defaultErrorResponseEntity.Detail != null) + writer.WriteString("detail", defaultErrorResponseEntity.Detail); + + if (defaultErrorResponseEntity._ErrorCodeOption.IsSet) + if (defaultErrorResponseEntity.ErrorCode != null) + writer.WriteString("errorCode", defaultErrorResponseEntity.ErrorCode); + + if (defaultErrorResponseEntity._InstanceOption.IsSet) + if (defaultErrorResponseEntity.Instance != null) + writer.WriteString("instance", defaultErrorResponseEntity.Instance); + + if (defaultErrorResponseEntity._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, defaultErrorResponseEntity.InvalidFields, jsonSerializerOptions); + } + if (defaultErrorResponseEntity._RequestIdOption.IsSet) + if (defaultErrorResponseEntity.RequestId != null) + writer.WriteString("requestId", defaultErrorResponseEntity.RequestId); + + if (defaultErrorResponseEntity._StatusOption.IsSet) + writer.WriteNumber("status", defaultErrorResponseEntity._StatusOption.Value!.Value); + + if (defaultErrorResponseEntity._TitleOption.IsSet) + if (defaultErrorResponseEntity.Title != null) + writer.WriteString("title", defaultErrorResponseEntity.Title); + + if (defaultErrorResponseEntity._TypeOption.IsSet) + if (defaultErrorResponseEntity.Type != null) + writer.WriteString("type", defaultErrorResponseEntity.Type); + } + } +} diff --git a/Adyen/PaymentsApp/Models/InvalidField.cs b/Adyen/PaymentsApp/Models/InvalidField.cs new file mode 100644 index 000000000..a2674bbc8 --- /dev/null +++ b/Adyen/PaymentsApp/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The field that has an invalid value. + /// The invalid value. + /// Description of the validation error. + [JsonConstructor] + public InvalidField(string name, string value, string message) + { + Name = name; + Value = value; + Message = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option value = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + return new InvalidField(name.Value!, value.Value!, message.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + } + } +} diff --git a/Adyen/PaymentsApp/Models/PaymentsAppDto.cs b/Adyen/PaymentsApp/Models/PaymentsAppDto.cs new file mode 100644 index 000000000..eb28206c9 --- /dev/null +++ b/Adyen/PaymentsApp/Models/PaymentsAppDto.cs @@ -0,0 +1,236 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// PaymentsAppDto. + /// + public partial class PaymentsAppDto : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the Payments App instance. + /// The account code associated with the Payments App instance. + /// The status of the Payments App instance. + /// The store code associated with the Payments App instance. + [JsonConstructor] + public PaymentsAppDto(string installationId, string merchantAccountCode, string status, Option merchantStoreCode = default) + { + InstallationId = installationId; + MerchantAccountCode = merchantAccountCode; + Status = status; + _MerchantStoreCodeOption = merchantStoreCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentsAppDto() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the Payments App instance. + /// + /// The unique identifier of the Payments App instance. + [JsonPropertyName("installationId")] + public string InstallationId { get; set; } + + /// + /// The account code associated with the Payments App instance. + /// + /// The account code associated with the Payments App instance. + [JsonPropertyName("merchantAccountCode")] + public string MerchantAccountCode { get; set; } + + /// + /// The status of the Payments App instance. + /// + /// The status of the Payments App instance. + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantStoreCodeOption { get; private set; } + + /// + /// The store code associated with the Payments App instance. + /// + /// The store code associated with the Payments App instance. + [JsonPropertyName("merchantStoreCode")] + public string? MerchantStoreCode { get { return this._MerchantStoreCodeOption; } set { this._MerchantStoreCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentsAppDto {\n"); + sb.Append(" InstallationId: ").Append(InstallationId).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" MerchantStoreCode: ").Append(MerchantStoreCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentsAppDtoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentsAppDto Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option installationId = default; + Option merchantAccountCode = default; + Option status = default; + Option merchantStoreCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "installationId": + installationId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + case "merchantStoreCode": + merchantStoreCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!installationId.IsSet) + throw new ArgumentException("Property is required for class PaymentsAppDto.", nameof(installationId)); + + if (!merchantAccountCode.IsSet) + throw new ArgumentException("Property is required for class PaymentsAppDto.", nameof(merchantAccountCode)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class PaymentsAppDto.", nameof(status)); + + return new PaymentsAppDto(installationId.Value!, merchantAccountCode.Value!, status.Value!, merchantStoreCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentsAppDto paymentsAppDto, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentsAppDto, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentsAppDto paymentsAppDto, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentsAppDto.InstallationId != null) + writer.WriteString("installationId", paymentsAppDto.InstallationId); + + if (paymentsAppDto.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", paymentsAppDto.MerchantAccountCode); + + if (paymentsAppDto.Status != null) + writer.WriteString("status", paymentsAppDto.Status); + + if (paymentsAppDto._MerchantStoreCodeOption.IsSet) + if (paymentsAppDto.MerchantStoreCode != null) + writer.WriteString("merchantStoreCode", paymentsAppDto.MerchantStoreCode); + } + } +} diff --git a/Adyen/PaymentsApp/Models/PaymentsAppResponse.cs b/Adyen/PaymentsApp/Models/PaymentsAppResponse.cs new file mode 100644 index 000000000..9c8e57a82 --- /dev/null +++ b/Adyen/PaymentsApp/Models/PaymentsAppResponse.cs @@ -0,0 +1,171 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PaymentsApp.Client; + +namespace Adyen.PaymentsApp.Models +{ + /// + /// PaymentsAppResponse. + /// + public partial class PaymentsAppResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of Payments Apps. + [JsonConstructor] + public PaymentsAppResponse(List paymentsApps) + { + PaymentsApps = paymentsApps; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentsAppResponse() + { + } + + partial void OnCreated(); + + /// + /// List of Payments Apps. + /// + /// List of Payments Apps. + [JsonPropertyName("paymentsApps")] + public List PaymentsApps { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentsAppResponse {\n"); + sb.Append(" PaymentsApps: ").Append(PaymentsApps).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentsAppResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentsAppResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> paymentsApps = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "paymentsApps": + paymentsApps = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!paymentsApps.IsSet) + throw new ArgumentException("Property is required for class PaymentsAppResponse.", nameof(paymentsApps)); + + return new PaymentsAppResponse(paymentsApps.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentsAppResponse paymentsAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentsAppResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentsAppResponse paymentsAppResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("paymentsApps"); + JsonSerializer.Serialize(writer, paymentsAppResponse.PaymentsApps, jsonSerializerOptions); + } + } +} diff --git a/Adyen/PaymentsApp/Services/PaymentsAppService.cs b/Adyen/PaymentsApp/Services/PaymentsAppService.cs new file mode 100644 index 000000000..2a6b02413 --- /dev/null +++ b/Adyen/PaymentsApp/Services/PaymentsAppService.cs @@ -0,0 +1,2185 @@ +// +/* + * Payments App API + * + * Board and manage the Adyen Payments App on your Android mobile devices. ## Authentication Each request to the Payments App API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. ## Versioning Payments App API handles versioning as part of the endpoint URL. For example, to send a request to this version of the `/merchants/{merchantId}/generatePaymentsAppBoardingToken` endpoint, use: ```text https://management-test.adyen.com/v1/merchants/{merchantId}/generatePaymentsAppBoardingToken ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. Use this API key to make requests to: ```text https://management-live.adyen.com/v{version} ``` + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.PaymentsApp.Client; +using Adyen.PaymentsApp.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.PaymentsApp.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPaymentsAppService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PaymentsAppServiceEvents Events { get; } + + /// + /// Create a boarding token - merchant level + /// + /// + /// Creates a boarding token used to authenticate the installation of a Payments App instance on an Android device. The boarding token is created for the `boardingRequestToken` of the Payments App for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of . + Task GeneratePaymentsAppBoardingTokenForMerchantAsync(string merchantId, BoardingTokenRequest boardingTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a boarding token - store level + /// + /// + /// Creates a boarding token used to authenticate the installation of a Payments App instance on an Android device. The boarding token is created for the `boardingRequestToken` of the Payments App for the store identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// + /// . + /// . + /// of . + Task GeneratePaymentsAppBoardingTokenForStoreAsync(string merchantId, string storeId, BoardingTokenRequest boardingTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of Payments Apps - merchant level + /// + /// + /// Returns the list of Payments App instances for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** + /// The number of items to return. + /// The number of items to skip. + /// . + /// . + /// of . + Task ListPaymentsAppForMerchantAsync(string merchantId, Option statuses = default, Option limit = default, Option offset = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a list of Payments Apps - store level + /// + /// + /// Returns the list of Payments App instances for the store identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** + /// The number of items to return. + /// The number of items to skip. + /// . + /// . + /// of . + Task ListPaymentsAppForStoreAsync(string merchantId, string storeId, Option statuses = default, Option limit = default, Option offset = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Revoke Payments App instance authentication + /// + /// + /// Revokes the authentication of the Payments App instance for the `installationId` and merchant account identified in the path. This call revokes the authentication of the Payments App instance with the `installationId` identified in the path for both merchant accounts and stores. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the Payments App instance on a device. + /// . + /// . + /// of . + Task RevokePaymentsAppAsync(string merchantId, string installationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGeneratePaymentsAppBoardingTokenForMerchantApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGeneratePaymentsAppBoardingTokenForStoreApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListPaymentsAppForMerchantApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListPaymentsAppForStoreApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRevokePaymentsAppApiResponse : Adyen.Core.Client.IApiResponse, IBadRequest, IUnauthorized, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PaymentsAppServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGeneratePaymentsAppBoardingTokenForMerchant; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGeneratePaymentsAppBoardingTokenForMerchant; + + internal void ExecuteOnGeneratePaymentsAppBoardingTokenForMerchant(PaymentsAppService.GeneratePaymentsAppBoardingTokenForMerchantApiResponse apiResponse) + { + OnGeneratePaymentsAppBoardingTokenForMerchant?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGeneratePaymentsAppBoardingTokenForMerchant(Exception exception) + { + OnErrorGeneratePaymentsAppBoardingTokenForMerchant?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGeneratePaymentsAppBoardingTokenForStore; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGeneratePaymentsAppBoardingTokenForStore; + + internal void ExecuteOnGeneratePaymentsAppBoardingTokenForStore(PaymentsAppService.GeneratePaymentsAppBoardingTokenForStoreApiResponse apiResponse) + { + OnGeneratePaymentsAppBoardingTokenForStore?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGeneratePaymentsAppBoardingTokenForStore(Exception exception) + { + OnErrorGeneratePaymentsAppBoardingTokenForStore?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListPaymentsAppForMerchant; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListPaymentsAppForMerchant; + + internal void ExecuteOnListPaymentsAppForMerchant(PaymentsAppService.ListPaymentsAppForMerchantApiResponse apiResponse) + { + OnListPaymentsAppForMerchant?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListPaymentsAppForMerchant(Exception exception) + { + OnErrorListPaymentsAppForMerchant?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListPaymentsAppForStore; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListPaymentsAppForStore; + + internal void ExecuteOnListPaymentsAppForStore(PaymentsAppService.ListPaymentsAppForStoreApiResponse apiResponse) + { + OnListPaymentsAppForStore?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListPaymentsAppForStore(Exception exception) + { + OnErrorListPaymentsAppForStore?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRevokePaymentsApp; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRevokePaymentsApp; + + internal void ExecuteOnRevokePaymentsApp(PaymentsAppService.RevokePaymentsAppApiResponse apiResponse) + { + OnRevokePaymentsApp?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRevokePaymentsApp(Exception exception) + { + OnErrorRevokePaymentsApp?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PaymentsAppService : IPaymentsAppService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PaymentsAppServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PaymentsAppService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PaymentsAppServiceEvents paymentsAppServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = paymentsAppServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a boarding token - merchant level Creates a boarding token used to authenticate the installation of a Payments App instance on an Android device. The boarding token is created for the `boardingRequestToken` of the Payments App for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GeneratePaymentsAppBoardingTokenForMerchantAsync(string merchantId, BoardingTokenRequest boardingTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/generatePaymentsAppBoardingToken" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/generatePaymentsAppBoardingToken"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (boardingTokenRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(boardingTokenRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GeneratePaymentsAppBoardingTokenForMerchantApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/generatePaymentsAppBoardingToken", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGeneratePaymentsAppBoardingTokenForMerchant(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGeneratePaymentsAppBoardingTokenForMerchant(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GeneratePaymentsAppBoardingTokenForMerchantApiResponse : Adyen.Core.Client.ApiResponse, IGeneratePaymentsAppBoardingTokenForMerchantApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePaymentsAppBoardingTokenForMerchantApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePaymentsAppBoardingTokenForMerchantApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.PaymentsApp.Models.BoardingTokenResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.BoardingTokenResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Create a boarding token - store level Creates a boarding token used to authenticate the installation of a Payments App instance on an Android device. The boarding token is created for the `boardingRequestToken` of the Payments App for the store identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GeneratePaymentsAppBoardingTokenForStoreAsync(string merchantId, string storeId, BoardingTokenRequest boardingTokenRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{storeId}/generatePaymentsAppBoardingToken" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{storeId}/generatePaymentsAppBoardingToken"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (boardingTokenRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(boardingTokenRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GeneratePaymentsAppBoardingTokenForStoreApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{storeId}/generatePaymentsAppBoardingToken", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGeneratePaymentsAppBoardingTokenForStore(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGeneratePaymentsAppBoardingTokenForStore(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GeneratePaymentsAppBoardingTokenForStoreApiResponse : Adyen.Core.Client.ApiResponse, IGeneratePaymentsAppBoardingTokenForStoreApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePaymentsAppBoardingTokenForStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GeneratePaymentsAppBoardingTokenForStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.PaymentsApp.Models.BoardingTokenResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.BoardingTokenResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of Payments Apps - merchant level Returns the list of Payments App instances for the merchant account identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** () + /// The number of items to return. (default to 10) + /// The number of items to skip. (default to 0) + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListPaymentsAppForMerchantAsync(string merchantId, Option statuses = default, Option limit = default, Option offset = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentsApps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentsApps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (statuses.IsSet) + parseQueryString["statuses"] = ClientUtils.ParameterToString(statuses.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListPaymentsAppForMerchantApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentsApps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListPaymentsAppForMerchant(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListPaymentsAppForMerchant(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListPaymentsAppForMerchantApiResponse : Adyen.Core.Client.ApiResponse, IListPaymentsAppForMerchantApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPaymentsAppForMerchantApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPaymentsAppForMerchantApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.PaymentsApp.Models.PaymentsAppResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.PaymentsAppResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a list of Payments Apps - store level Returns the list of Payments App instances for the store identified in the path. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the store. + /// The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** () + /// The number of items to return. (default to 10) + /// The number of items to skip. (default to 0) + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListPaymentsAppForStoreAsync(string merchantId, string storeId, Option statuses = default, Option limit = default, Option offset = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/stores/{storeId}/paymentsApps" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/stores/{storeId}/paymentsApps"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BstoreId%7D", Uri.EscapeDataString(storeId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (statuses.IsSet) + parseQueryString["statuses"] = ClientUtils.ParameterToString(statuses.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (offset.IsSet) + parseQueryString["offset"] = ClientUtils.ParameterToString(offset.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListPaymentsAppForStoreApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/stores/{storeId}/paymentsApps", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListPaymentsAppForStore(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListPaymentsAppForStore(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListPaymentsAppForStoreApiResponse : Adyen.Core.Client.ApiResponse, IListPaymentsAppForStoreApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPaymentsAppForStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListPaymentsAppForStoreApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.PaymentsApp.Models.PaymentsAppResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.PaymentsAppResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Revoke Payments App instance authentication Revokes the authentication of the Payments App instance for the `installationId` and merchant account identified in the path. This call revokes the authentication of the Payments App instance with the `installationId` identified in the path for both merchant accounts and stores. To make this request, your API credential must have the following [role](https://docs.adyen.com/development-resources/api-credentials#api-permissions): * Adyen Payments App role + /// + /// Thrown when fails to make API call. + /// The unique identifier of the merchant account. + /// The unique identifier of the Payments App instance on a device. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RevokePaymentsAppAsync(string merchantId, string installationId, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/merchants/{merchantId}/paymentsApps/{installationId}/revoke" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/merchants/{merchantId}/paymentsApps/{installationId}/revoke"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BmerchantId%7D", Uri.EscapeDataString(merchantId.ToString())); + uriBuilder.Path = uriBuilder.Path.Replace("%7BinstallationId%7D", Uri.EscapeDataString(installationId.ToString())); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RevokePaymentsAppApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/merchants/{merchantId}/paymentsApps/{installationId}/revoke", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRevokePaymentsApp(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRevokePaymentsApp(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RevokePaymentsAppApiResponse : Adyen.Core.Client.ApiResponse, IRevokePaymentsAppApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevokePaymentsAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RevokePaymentsAppApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.PaymentsApp.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Payout/Client/ApiKeyToken.cs b/Adyen/Payout/Client/ApiKeyToken.cs new file mode 100644 index 000000000..e2afc528b --- /dev/null +++ b/Adyen/Payout/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Payout.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Payout/Client/ClientUtils.cs b/Adyen/Payout/Client/ClientUtils.cs new file mode 100644 index 000000000..974724479 --- /dev/null +++ b/Adyen/Payout/Client/ClientUtils.cs @@ -0,0 +1,337 @@ +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Payout.Models; +using Models = Adyen.Payout.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Payout.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.PayoutRequest.ShopperInteractionEnum payoutRequestShopperInteractionEnum) + return Models.PayoutRequest.ShopperInteractionEnum.ToJsonValue(payoutRequestShopperInteractionEnum); + if (obj is Models.PayoutResponse.ResultCodeEnum payoutResponseResultCodeEnum) + return Models.PayoutResponse.ResultCodeEnum.ToJsonValue(payoutResponseResultCodeEnum); + if (obj is Models.Recurring.ContractEnum recurringContractEnum) + return Models.Recurring.ContractEnum.ToJsonValue(recurringContractEnum); + if (obj is Models.Recurring.TokenServiceEnum recurringTokenServiceEnum) + return Models.Recurring.TokenServiceEnum.ToJsonValue(recurringTokenServiceEnum); + if (obj is Models.ResponseAdditionalDataCard.CardProductIdEnum responseAdditionalDataCardCardProductIdEnum) + return Models.ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCardCardProductIdEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudResultTypeEnum responseAdditionalDataCommonFraudResultTypeEnum) + return Models.ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommonFraudResultTypeEnum); + if (obj is Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum responseAdditionalDataCommonFraudRiskLevelEnum) + return Models.ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommonFraudRiskLevelEnum); + if (obj is Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum responseAdditionalDataCommonRecurringProcessingModelEnum) + return Models.ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommonRecurringProcessingModelEnum); + if (obj is Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum responseAdditionalDataCommonTokenizationStoreOperationTypeEnum) + return Models.ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommonTokenizationStoreOperationTypeEnum); + if (obj is Models.StoreDetailAndSubmitRequest.EntityTypeEnum storeDetailAndSubmitRequestEntityTypeEnum) + return Models.StoreDetailAndSubmitRequest.EntityTypeEnum.ToJsonValue(storeDetailAndSubmitRequestEntityTypeEnum); + if (obj is Models.StoreDetailRequest.EntityTypeEnum storeDetailRequestEntityTypeEnum) + return Models.StoreDetailRequest.EntityTypeEnum.ToJsonValue(storeDetailRequestEntityTypeEnum); + if (obj is Models.SubmitRequest.EntityTypeEnum submitRequestEntityTypeEnum) + return Models.SubmitRequest.EntityTypeEnum.ToJsonValue(submitRequestEntityTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Payout/Client/HostConfiguration.cs b/Adyen/Payout/Client/HostConfiguration.cs new file mode 100644 index 000000000..4ffa21c94 --- /dev/null +++ b/Adyen/Payout/Client/HostConfiguration.cs @@ -0,0 +1,163 @@ +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Payout.Services; +using Adyen.Payout.Client; +using Adyen.Payout.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Payout.Client +{ + /// + /// Provides hosting configuration for Payout + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/Payout/v68"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new FraudCheckResultJsonConverter()); + _jsonOptions.Converters.Add(new FraudCheckResultWrapperJsonConverter()); + _jsonOptions.Converters.Add(new FraudResultJsonConverter()); + _jsonOptions.Converters.Add(new FundSourceJsonConverter()); + _jsonOptions.Converters.Add(new ModifyRequestJsonConverter()); + _jsonOptions.Converters.Add(new ModifyResponseJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new PayoutRequestJsonConverter()); + _jsonOptions.Converters.Add(new PayoutResponseJsonConverter()); + _jsonOptions.Converters.Add(new RecurringJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalData3DSecureJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataBillingAddressJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCardJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataCommonJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataDomesticErrorJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataInstallmentsJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataNetworkTokensJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataOpiJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSepaJsonConverter()); + _jsonOptions.Converters.Add(new ResponseAdditionalDataSwishJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new StoreDetailAndSubmitRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoreDetailAndSubmitResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoreDetailRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoreDetailResponseJsonConverter()); + _jsonOptions.Converters.Add(new SubmitRequestJsonConverter()); + _jsonOptions.Converters.Add(new SubmitResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddPayoutHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Payout/Client/JsonSerializerOptionsProvider.cs b/Adyen/Payout/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..767459fc7 --- /dev/null +++ b/Adyen/Payout/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Payout.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Payout/Extensions/HostBuilderExtensions.cs b/Adyen/Payout/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..a46d349ea --- /dev/null +++ b/Adyen/Payout/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Payout; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Payout API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigurePayout(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddPayoutHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Payout/Extensions/ServiceCollectionExtensions.cs b/Adyen/Payout/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..c5200e580 --- /dev/null +++ b/Adyen/Payout/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Payout API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddPayoutServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddPayoutHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Payout/Models/Address.cs b/Adyen/Payout/Models/Address.cs new file mode 100644 index 000000000..1a6b7e27e --- /dev/null +++ b/Adyen/Payout/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/Payout/Models/Amount.cs b/Adyen/Payout/Models/Amount.cs new file mode 100644 index 000000000..87978f788 --- /dev/null +++ b/Adyen/Payout/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Payout/Models/BankAccount.cs b/Adyen/Payout/Models/BankAccount.cs new file mode 100644 index 000000000..4afc3bce1 --- /dev/null +++ b/Adyen/Payout/Models/BankAccount.cs @@ -0,0 +1,377 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// BankAccount. + /// + public partial class BankAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The bank city. + /// The location id of the bank. The field value is `nil` in most cases. + /// The name of the bank. + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// The bank account holder's tax ID. + [JsonConstructor] + public BankAccount(Option bankAccountNumber = default, Option bankCity = default, Option bankLocationId = default, Option bankName = default, Option bic = default, Option countryCode = default, Option iban = default, Option ownerName = default, Option taxId = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankCityOption = bankCity; + _BankLocationIdOption = bankLocationId; + _BankNameOption = bankName; + _BicOption = bic; + _CountryCodeOption = countryCode; + _IbanOption = iban; + _OwnerNameOption = ownerName; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccount() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCityOption { get; private set; } + + /// + /// The bank city. + /// + /// The bank city. + [JsonPropertyName("bankCity")] + public string? BankCity { get { return this._BankCityOption; } set { this._BankCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The location id of the bank. The field value is `nil` in most cases. + /// + /// The location id of the bank. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankNameOption { get; private set; } + + /// + /// The name of the bank. + /// + /// The name of the bank. + [JsonPropertyName("bankName")] + public string? BankName { get { return this._BankNameOption; } set { this._BankNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The bank account holder's tax ID. + /// + /// The bank account holder's tax ID. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccount {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankCity: ").Append(BankCity).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" BankName: ").Append(BankName).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankCity = default; + Option bankLocationId = default; + Option bankName = default; + Option bic = default; + Option countryCode = default; + Option iban = default; + Option ownerName = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCity": + bankCity = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "bankName": + bankName = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BankAccount(bankAccountNumber, bankCity, bankLocationId, bankName, bic, countryCode, iban, ownerName, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccount._BankAccountNumberOption.IsSet) + if (bankAccount.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", bankAccount.BankAccountNumber); + + if (bankAccount._BankCityOption.IsSet) + if (bankAccount.BankCity != null) + writer.WriteString("bankCity", bankAccount.BankCity); + + if (bankAccount._BankLocationIdOption.IsSet) + if (bankAccount.BankLocationId != null) + writer.WriteString("bankLocationId", bankAccount.BankLocationId); + + if (bankAccount._BankNameOption.IsSet) + if (bankAccount.BankName != null) + writer.WriteString("bankName", bankAccount.BankName); + + if (bankAccount._BicOption.IsSet) + if (bankAccount.Bic != null) + writer.WriteString("bic", bankAccount.Bic); + + if (bankAccount._CountryCodeOption.IsSet) + if (bankAccount.CountryCode != null) + writer.WriteString("countryCode", bankAccount.CountryCode); + + if (bankAccount._IbanOption.IsSet) + if (bankAccount.Iban != null) + writer.WriteString("iban", bankAccount.Iban); + + if (bankAccount._OwnerNameOption.IsSet) + if (bankAccount.OwnerName != null) + writer.WriteString("ownerName", bankAccount.OwnerName); + + if (bankAccount._TaxIdOption.IsSet) + if (bankAccount.TaxId != null) + writer.WriteString("taxId", bankAccount.TaxId); + } + } +} diff --git a/Adyen/Payout/Models/Card.cs b/Adyen/Payout/Models/Card.cs new file mode 100644 index 000000000..ed8bab086 --- /dev/null +++ b/Adyen/Payout/Models/Card.cs @@ -0,0 +1,448 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// The card expiry year. Format: 4 digits. For example: 2020 + /// The name of the cardholder, as printed on the card. + /// The issue number of the card (for some UK debit cards only). + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// The month component of the start date (for some UK debit cards only). + /// The year component of the start date (for some UK debit cards only). + [JsonConstructor] + public Card(Option cvc = default, Option expiryMonth = default, Option expiryYear = default, Option holderName = default, Option issueNumber = default, Option number = default, Option startMonth = default, Option startYear = default) + { + _CvcOption = cvc; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _HolderNameOption = holderName; + _IssueNumberOption = issueNumber; + _NumberOption = number; + _StartMonthOption = startMonth; + _StartYearOption = startYear; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the cardholder, as printed on the card. + /// + /// The name of the cardholder, as printed on the card. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueNumberOption { get; private set; } + + /// + /// The issue number of the card (for some UK debit cards only). + /// + /// The issue number of the card (for some UK debit cards only). + [JsonPropertyName("issueNumber")] + public string? IssueNumber { get { return this._IssueNumberOption; } set { this._IssueNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartMonthOption { get; private set; } + + /// + /// The month component of the start date (for some UK debit cards only). + /// + /// The month component of the start date (for some UK debit cards only). + [JsonPropertyName("startMonth")] + public string? StartMonth { get { return this._StartMonthOption; } set { this._StartMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartYearOption { get; private set; } + + /// + /// The year component of the start date (for some UK debit cards only). + /// + /// The year component of the start date (for some UK debit cards only). + [JsonPropertyName("startYear")] + public string? StartYear { get { return this._StartYearOption; } set { this._StartYearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" IssueNumber: ").Append(IssueNumber).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" StartMonth: ").Append(StartMonth).Append("\n"); + sb.Append(" StartYear: ").Append(StartYear).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Cvc (string) maxLength + if (this.Cvc != null && this.Cvc.Length > 20) + { + yield return new ValidationResult("Invalid value for Cvc, length must be less than 20.", new [] { "Cvc" }); + } + + // Cvc (string) minLength + if (this.Cvc != null && this.Cvc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cvc, length must be greater than 1.", new [] { "Cvc" }); + } + + // ExpiryMonth (string) maxLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be less than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryMonth (string) minLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be greater than 1.", new [] { "ExpiryMonth" }); + } + + // ExpiryYear (string) maxLength + if (this.ExpiryYear != null && this.ExpiryYear.Length > 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be less than 4.", new [] { "ExpiryYear" }); + } + + // ExpiryYear (string) minLength + if (this.ExpiryYear != null && this.ExpiryYear.Length < 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be greater than 4.", new [] { "ExpiryYear" }); + } + + // HolderName (string) maxLength + if (this.HolderName != null && this.HolderName.Length > 50) + { + yield return new ValidationResult("Invalid value for HolderName, length must be less than 50.", new [] { "HolderName" }); + } + + // HolderName (string) minLength + if (this.HolderName != null && this.HolderName.Length < 1) + { + yield return new ValidationResult("Invalid value for HolderName, length must be greater than 1.", new [] { "HolderName" }); + } + + // IssueNumber (string) maxLength + if (this.IssueNumber != null && this.IssueNumber.Length > 2) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be less than 2.", new [] { "IssueNumber" }); + } + + // IssueNumber (string) minLength + if (this.IssueNumber != null && this.IssueNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be greater than 1.", new [] { "IssueNumber" }); + } + + // Number (string) maxLength + if (this.Number != null && this.Number.Length > 19) + { + yield return new ValidationResult("Invalid value for Number, length must be less than 19.", new [] { "Number" }); + } + + // Number (string) minLength + if (this.Number != null && this.Number.Length < 4) + { + yield return new ValidationResult("Invalid value for Number, length must be greater than 4.", new [] { "Number" }); + } + + // StartMonth (string) maxLength + if (this.StartMonth != null && this.StartMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be less than 2.", new [] { "StartMonth" }); + } + + // StartMonth (string) minLength + if (this.StartMonth != null && this.StartMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be greater than 1.", new [] { "StartMonth" }); + } + + // StartYear (string) maxLength + if (this.StartYear != null && this.StartYear.Length > 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be less than 4.", new [] { "StartYear" }); + } + + // StartYear (string) minLength + if (this.StartYear != null && this.StartYear.Length < 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be greater than 4.", new [] { "StartYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cvc = default; + Option expiryMonth = default; + Option expiryYear = default; + Option holderName = default; + Option issueNumber = default; + Option number = default; + Option startMonth = default; + Option startYear = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "issueNumber": + issueNumber = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "startMonth": + startMonth = new Option(utf8JsonReader.GetString()!); + break; + case "startYear": + startYear = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Card(cvc, expiryMonth, expiryYear, holderName, issueNumber, number, startMonth, startYear); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + if (card._CvcOption.IsSet) + if (card.Cvc != null) + writer.WriteString("cvc", card.Cvc); + + if (card._ExpiryMonthOption.IsSet) + if (card.ExpiryMonth != null) + writer.WriteString("expiryMonth", card.ExpiryMonth); + + if (card._ExpiryYearOption.IsSet) + if (card.ExpiryYear != null) + writer.WriteString("expiryYear", card.ExpiryYear); + + if (card._HolderNameOption.IsSet) + if (card.HolderName != null) + writer.WriteString("holderName", card.HolderName); + + if (card._IssueNumberOption.IsSet) + if (card.IssueNumber != null) + writer.WriteString("issueNumber", card.IssueNumber); + + if (card._NumberOption.IsSet) + if (card.Number != null) + writer.WriteString("number", card.Number); + + if (card._StartMonthOption.IsSet) + if (card.StartMonth != null) + writer.WriteString("startMonth", card.StartMonth); + + if (card._StartYearOption.IsSet) + if (card.StartYear != null) + writer.WriteString("startYear", card.StartYear); + } + } +} diff --git a/Adyen/Payout/Models/FraudCheckResult.cs b/Adyen/Payout/Models/FraudCheckResult.cs new file mode 100644 index 000000000..abe92f31b --- /dev/null +++ b/Adyen/Payout/Models/FraudCheckResult.cs @@ -0,0 +1,209 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// FraudCheckResult. + /// + public partial class FraudCheckResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The fraud score generated by the risk check. + /// The ID of the risk check. + /// The name of the risk check. + [JsonConstructor] + public FraudCheckResult(int accountScore, int checkId, string name) + { + AccountScore = accountScore; + CheckId = checkId; + Name = name; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudCheckResult() + { + } + + partial void OnCreated(); + + /// + /// The fraud score generated by the risk check. + /// + /// The fraud score generated by the risk check. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// The ID of the risk check. + /// + /// The ID of the risk check. + [JsonPropertyName("checkId")] + public int CheckId { get; set; } + + /// + /// The name of the risk check. + /// + /// The name of the risk check. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudCheckResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" CheckId: ").Append(CheckId).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudCheckResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option checkId = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "checkId": + checkId = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(accountScore)); + + if (!checkId.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(checkId)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class FraudCheckResult.", nameof(name)); + + return new FraudCheckResult(accountScore.Value!.Value!, checkId.Value!.Value!, name.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudCheckResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudCheckResult fraudCheckResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudCheckResult.AccountScore); + + writer.WriteNumber("checkId", fraudCheckResult.CheckId); + + if (fraudCheckResult.Name != null) + writer.WriteString("name", fraudCheckResult.Name); + } + } +} diff --git a/Adyen/Payout/Models/FraudCheckResultWrapper.cs b/Adyen/Payout/Models/FraudCheckResultWrapper.cs new file mode 100644 index 000000000..e17cb1d4f --- /dev/null +++ b/Adyen/Payout/Models/FraudCheckResultWrapper.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// FraudCheckResultWrapper. + /// + public partial class FraudCheckResultWrapper : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// fraudCheckResult + [JsonConstructor] + public FraudCheckResultWrapper(Option fraudCheckResult = default) + { + _FraudCheckResultOption = fraudCheckResult; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudCheckResultWrapper() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudCheckResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("FraudCheckResult")] + public FraudCheckResult? FraudCheckResult { get { return this._FraudCheckResultOption; } set { this._FraudCheckResultOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudCheckResultWrapper {\n"); + sb.Append(" FraudCheckResult: ").Append(FraudCheckResult).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudCheckResultWrapperJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudCheckResultWrapper Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option fraudCheckResult = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "FraudCheckResult": + fraudCheckResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new FraudCheckResultWrapper(fraudCheckResult); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudCheckResultWrapper fraudCheckResultWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudCheckResultWrapper, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudCheckResultWrapper fraudCheckResultWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + if (fraudCheckResultWrapper._FraudCheckResultOption.IsSet) + { + writer.WritePropertyName("FraudCheckResult"); + JsonSerializer.Serialize(writer, fraudCheckResultWrapper.FraudCheckResult, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payout/Models/FraudResult.cs b/Adyen/Payout/Models/FraudResult.cs new file mode 100644 index 000000000..2ef5de422 --- /dev/null +++ b/Adyen/Payout/Models/FraudResult.cs @@ -0,0 +1,197 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// FraudResult. + /// + public partial class FraudResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The total fraud score generated by the risk checks. + /// The result of the individual risk checks. + [JsonConstructor] + public FraudResult(int accountScore, Option?> results = default) + { + AccountScore = accountScore; + _ResultsOption = results; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FraudResult() + { + } + + partial void OnCreated(); + + /// + /// The total fraud score generated by the risk checks. + /// + /// The total fraud score generated by the risk checks. + [JsonPropertyName("accountScore")] + public int AccountScore { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ResultsOption { get; private set; } + + /// + /// The result of the individual risk checks. + /// + /// The result of the individual risk checks. + [JsonPropertyName("results")] + public List? Results { get { return this._ResultsOption; } set { this._ResultsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FraudResult {\n"); + sb.Append(" AccountScore: ").Append(AccountScore).Append("\n"); + sb.Append(" Results: ").Append(Results).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FraudResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FraudResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountScore = default; + Option?> results = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountScore": + accountScore = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "results": + results = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountScore.IsSet) + throw new ArgumentException("Property is required for class FraudResult.", nameof(accountScore)); + + return new FraudResult(accountScore.Value!.Value!, results); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fraudResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FraudResult fraudResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("accountScore", fraudResult.AccountScore); + + if (fraudResult._ResultsOption.IsSet) + { + writer.WritePropertyName("results"); + JsonSerializer.Serialize(writer, fraudResult.Results, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payout/Models/FundSource.cs b/Adyen/Payout/Models/FundSource.cs new file mode 100644 index 000000000..1dc551218 --- /dev/null +++ b/Adyen/Payout/Models/FundSource.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// FundSource. + /// + public partial class FundSource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A map of name-value pairs for passing additional or industry-specific data. + /// billingAddress + /// card + /// Email address of the person. + /// shopperName + /// Phone number of the person + [JsonConstructor] + public FundSource(Option?> additionalData = default, Option billingAddress = default, Option card = default, Option shopperEmail = default, Option shopperName = default, Option telephoneNumber = default) + { + _AdditionalDataOption = additionalData; + _BillingAddressOption = billingAddress; + _CardOption = card; + _ShopperEmailOption = shopperEmail; + _ShopperNameOption = shopperName; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FundSource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// A map of name-value pairs for passing additional or industry-specific data. + /// + /// A map of name-value pairs for passing additional or industry-specific data. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// Email address of the person. + /// + /// Email address of the person. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// Phone number of the person + /// + /// Phone number of the person + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FundSource {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FundSourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FundSource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option billingAddress = default; + Option card = default; + Option shopperEmail = default; + Option shopperName = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new FundSource(additionalData, billingAddress, card, shopperEmail, shopperName, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FundSource fundSource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fundSource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FundSource fundSource, JsonSerializerOptions jsonSerializerOptions) + { + + if (fundSource._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, fundSource.AdditionalData, jsonSerializerOptions); + } + if (fundSource._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, fundSource.BillingAddress, jsonSerializerOptions); + } + if (fundSource._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, fundSource.Card, jsonSerializerOptions); + } + if (fundSource._ShopperEmailOption.IsSet) + if (fundSource.ShopperEmail != null) + writer.WriteString("shopperEmail", fundSource.ShopperEmail); + + if (fundSource._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, fundSource.ShopperName, jsonSerializerOptions); + } + if (fundSource._TelephoneNumberOption.IsSet) + if (fundSource.TelephoneNumber != null) + writer.WriteString("telephoneNumber", fundSource.TelephoneNumber); + } + } +} diff --git a/Adyen/Payout/Models/ModifyRequest.cs b/Adyen/Payout/Models/ModifyRequest.cs new file mode 100644 index 000000000..44a9d7042 --- /dev/null +++ b/Adyen/Payout/Models/ModifyRequest.cs @@ -0,0 +1,218 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ModifyRequest. + /// + public partial class ModifyRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The PSP reference received in the `/submitThirdParty` response. + /// This field contains additional data, which may be required for a particular payout request. + [JsonConstructor] + public ModifyRequest(string merchantAccount, string originalReference, Option?> additionalData = default) + { + MerchantAccount = merchantAccount; + OriginalReference = originalReference; + _AdditionalDataOption = additionalData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ModifyRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The PSP reference received in the `/submitThirdParty` response. + /// + /// The PSP reference received in the `/submitThirdParty` response. + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular payout request. + /// + /// This field contains additional data, which may be required for a particular payout request. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModifyRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModifyRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ModifyRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option originalReference = default; + Option?> additionalData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class ModifyRequest.", nameof(merchantAccount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class ModifyRequest.", nameof(originalReference)); + + return new ModifyRequest(merchantAccount.Value!, originalReference.Value!, additionalData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModifyRequest modifyRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modifyRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ModifyRequest modifyRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (modifyRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", modifyRequest.MerchantAccount); + + if (modifyRequest.OriginalReference != null) + writer.WriteString("originalReference", modifyRequest.OriginalReference); + + if (modifyRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, modifyRequest.AdditionalData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payout/Models/ModifyResponse.cs b/Adyen/Payout/Models/ModifyResponse.cs new file mode 100644 index 000000000..247a1df8b --- /dev/null +++ b/Adyen/Payout/Models/ModifyResponse.cs @@ -0,0 +1,218 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ModifyResponse. + /// + public partial class ModifyResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Adyen's 16-character string reference associated with the transaction. This value is globally unique; quote it when communicating with us about this response. + /// The response: * In case of success, it is either `payout-confirm-received` or `payout-decline-received`. * In case of an error, an informational message is returned. + /// This field contains additional data, which may be returned in a particular response. + [JsonConstructor] + public ModifyResponse(string pspReference, string response, Option?> additionalData = default) + { + PspReference = pspReference; + Response = response; + _AdditionalDataOption = additionalData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ModifyResponse() + { + } + + partial void OnCreated(); + + /// + /// Adyen's 16-character string reference associated with the transaction. This value is globally unique; quote it when communicating with us about this response. + /// + /// Adyen's 16-character string reference associated with the transaction. This value is globally unique; quote it when communicating with us about this response. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The response: * In case of success, it is either `payout-confirm-received` or `payout-decline-received`. * In case of an error, an informational message is returned. + /// + /// The response: * In case of success, it is either `payout-confirm-received` or `payout-decline-received`. * In case of an error, an informational message is returned. + [JsonPropertyName("response")] + public string Response { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular response. + /// + /// This field contains additional data, which may be returned in a particular response. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModifyResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModifyResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ModifyResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option response = default; + Option?> additionalData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "response": + response = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class ModifyResponse.", nameof(pspReference)); + + if (!response.IsSet) + throw new ArgumentException("Property is required for class ModifyResponse.", nameof(response)); + + return new ModifyResponse(pspReference.Value!, response.Value!, additionalData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ModifyResponse modifyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modifyResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ModifyResponse modifyResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (modifyResponse.PspReference != null) + writer.WriteString("pspReference", modifyResponse.PspReference); + + if (modifyResponse.Response != null) + writer.WriteString("response", modifyResponse.Response); + + if (modifyResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, modifyResponse.AdditionalData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payout/Models/Name.cs b/Adyen/Payout/Models/Name.cs new file mode 100644 index 000000000..744eec284 --- /dev/null +++ b/Adyen/Payout/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/Payout/Models/PayoutRequest.cs b/Adyen/Payout/Models/PayoutRequest.cs new file mode 100644 index 000000000..82efbffe3 --- /dev/null +++ b/Adyen/Payout/Models/PayoutRequest.cs @@ -0,0 +1,607 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// PayoutRequest. + /// + public partial class PayoutRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// billingAddress + /// card + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// fundSource + /// recurring + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperName + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonConstructor] + public PayoutRequest(Amount amount, string merchantAccount, string reference, Option billingAddress = default, Option card = default, Option fraudOffset = default, Option fundSource = default, Option recurring = default, Option selectedRecurringDetailReference = default, Option shopperEmail = default, Option shopperInteraction = default, Option shopperName = default, Option shopperReference = default, Option telephoneNumber = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + _BillingAddressOption = billingAddress; + _CardOption = card; + _FraudOffsetOption = fraudOffset; + _FundSourceOption = fundSource; + _RecurringOption = recurring; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _ShopperEmailOption = shopperEmail; + _ShopperInteractionOption = shopperInteraction; + _ShopperNameOption = shopperName; + _ShopperReferenceOption = shopperReference; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayoutRequest() + { + } + + partial void OnCreated(); + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fundSource")] + public FundSource? FundSource { get { return this._FundSourceOption; } set { this._FundSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + /// + /// The `recurringDetailReference` you want to use for this payment. The value `LATEST` can be used to select the most recently stored recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperEmailOption { get; private set; } + + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + /// + /// The shopper's email address. We recommend that you provide this data, as it is used in velocity fraud checks. > Required for Visa and JCB transactions that require 3D Secure 2 authentication if you did not include the `telephoneNumber`. + [JsonPropertyName("shopperEmail")] + public string? ShopperEmail { get { return this._ShopperEmailOption; } set { this._ShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + /// + /// Required for recurring payments. Your reference to uniquely identify this shopper, for example user ID or account ID. The value is case-sensitive and must be at least three characters. > Your reference must not include personally identifiable information (PII) such as name or email address. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + /// + /// The shopper's telephone number. The phone number must include a plus sign (+) and a country code (1-3 digits), followed by the number (4-15 digits). If the value you provide does not follow the guidelines, we do not submit it for authentication. > Required for Visa and JCB transactions that require 3D Secure 2 authentication, if you did not include the `shopperEmail`. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayoutRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" FundSource: ").Append(FundSource).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayoutRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayoutRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option billingAddress = default; + Option card = default; + Option fraudOffset = default; + Option fundSource = default; + Option recurring = default; + Option selectedRecurringDetailReference = default; + Option shopperEmail = default; + Option shopperInteraction = default; + Option shopperName = default; + Option shopperReference = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "fundSource": + fundSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(PayoutRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class PayoutRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class PayoutRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class PayoutRequest.", nameof(reference)); + + return new PayoutRequest(amount.Value!, merchantAccount.Value!, reference.Value!, billingAddress, card, fraudOffset, fundSource, recurring, selectedRecurringDetailReference, shopperEmail, shopperInteraction, shopperName, shopperReference, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayoutRequest payoutRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payoutRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayoutRequest payoutRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, payoutRequest.Amount, jsonSerializerOptions); + if (payoutRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", payoutRequest.MerchantAccount); + + if (payoutRequest.Reference != null) + writer.WriteString("reference", payoutRequest.Reference); + + if (payoutRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, payoutRequest.BillingAddress, jsonSerializerOptions); + } + if (payoutRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, payoutRequest.Card, jsonSerializerOptions); + } + if (payoutRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", payoutRequest._FraudOffsetOption.Value!.Value); + + if (payoutRequest._FundSourceOption.IsSet) + { + writer.WritePropertyName("fundSource"); + JsonSerializer.Serialize(writer, payoutRequest.FundSource, jsonSerializerOptions); + } + if (payoutRequest._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, payoutRequest.Recurring, jsonSerializerOptions); + } + if (payoutRequest._SelectedRecurringDetailReferenceOption.IsSet) + if (payoutRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", payoutRequest.SelectedRecurringDetailReference); + + if (payoutRequest._ShopperEmailOption.IsSet) + if (payoutRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", payoutRequest.ShopperEmail); + + if (payoutRequest._ShopperInteractionOption.IsSet && payoutRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = PayoutRequest.ShopperInteractionEnum.ToJsonValue(payoutRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (payoutRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, payoutRequest.ShopperName, jsonSerializerOptions); + } + if (payoutRequest._ShopperReferenceOption.IsSet) + if (payoutRequest.ShopperReference != null) + writer.WriteString("shopperReference", payoutRequest.ShopperReference); + + if (payoutRequest._TelephoneNumberOption.IsSet) + if (payoutRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", payoutRequest.TelephoneNumber); + } + } +} diff --git a/Adyen/Payout/Models/PayoutResponse.cs b/Adyen/Payout/Models/PayoutResponse.cs new file mode 100644 index 000000000..8c4cac500 --- /dev/null +++ b/Adyen/Payout/Models/PayoutResponse.cs @@ -0,0 +1,648 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// PayoutResponse. + /// + public partial class PayoutResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// dccAmount + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// fraudResult + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + /// The payment session. + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConstructor] + public PayoutResponse(Option?> additionalData = default, Option authCode = default, Option dccAmount = default, Option dccSignature = default, Option fraudResult = default, Option issuerUrl = default, Option md = default, Option paRequest = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default) + { + _AdditionalDataOption = additionalData; + _AuthCodeOption = authCode; + _DccAmountOption = dccAmount; + _DccSignatureOption = dccSignature; + _FraudResultOption = fraudResult; + _IssuerUrlOption = issuerUrl; + _MdOption = md; + _PaRequestOption = paRequest; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PayoutResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.AuthenticationFinished - AuthenticationFinished + /// + public static readonly ResultCodeEnum AuthenticationFinished = new("AuthenticationFinished"); + + /// + /// ResultCodeEnum.AuthenticationNotRequired - AuthenticationNotRequired + /// + public static readonly ResultCodeEnum AuthenticationNotRequired = new("AuthenticationNotRequired"); + + /// + /// ResultCodeEnum.Authorised - Authorised + /// + public static readonly ResultCodeEnum Authorised = new("Authorised"); + + /// + /// ResultCodeEnum.Cancelled - Cancelled + /// + public static readonly ResultCodeEnum Cancelled = new("Cancelled"); + + /// + /// ResultCodeEnum.ChallengeShopper - ChallengeShopper + /// + public static readonly ResultCodeEnum ChallengeShopper = new("ChallengeShopper"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.IdentifyShopper - IdentifyShopper + /// + public static readonly ResultCodeEnum IdentifyShopper = new("IdentifyShopper"); + + /// + /// ResultCodeEnum.PartiallyAuthorised - PartiallyAuthorised + /// + public static readonly ResultCodeEnum PartiallyAuthorised = new("PartiallyAuthorised"); + + /// + /// ResultCodeEnum.Pending - Pending + /// + public static readonly ResultCodeEnum Pending = new("Pending"); + + /// + /// ResultCodeEnum.PresentToShopper - PresentToShopper + /// + public static readonly ResultCodeEnum PresentToShopper = new("PresentToShopper"); + + /// + /// ResultCodeEnum.Received - Received + /// + public static readonly ResultCodeEnum Received = new("Received"); + + /// + /// ResultCodeEnum.RedirectShopper - RedirectShopper + /// + public static readonly ResultCodeEnum RedirectShopper = new("RedirectShopper"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "AuthenticationFinished" => ResultCodeEnum.AuthenticationFinished, + "AuthenticationNotRequired" => ResultCodeEnum.AuthenticationNotRequired, + "Authorised" => ResultCodeEnum.Authorised, + "Cancelled" => ResultCodeEnum.Cancelled, + "ChallengeShopper" => ResultCodeEnum.ChallengeShopper, + "Error" => ResultCodeEnum.Error, + "IdentifyShopper" => ResultCodeEnum.IdentifyShopper, + "PartiallyAuthorised" => ResultCodeEnum.PartiallyAuthorised, + "Pending" => ResultCodeEnum.Pending, + "PresentToShopper" => ResultCodeEnum.PresentToShopper, + "Received" => ResultCodeEnum.Received, + "RedirectShopper" => ResultCodeEnum.RedirectShopper, + "Refused" => ResultCodeEnum.Refused, + "Success" => ResultCodeEnum.Success, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.AuthenticationFinished) + return "AuthenticationFinished"; + + if (value == ResultCodeEnum.AuthenticationNotRequired) + return "AuthenticationNotRequired"; + + if (value == ResultCodeEnum.Authorised) + return "Authorised"; + + if (value == ResultCodeEnum.Cancelled) + return "Cancelled"; + + if (value == ResultCodeEnum.ChallengeShopper) + return "ChallengeShopper"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.IdentifyShopper) + return "IdentifyShopper"; + + if (value == ResultCodeEnum.PartiallyAuthorised) + return "PartiallyAuthorised"; + + if (value == ResultCodeEnum.Pending) + return "Pending"; + + if (value == ResultCodeEnum.PresentToShopper) + return "PresentToShopper"; + + if (value == ResultCodeEnum.Received) + return "Received"; + + if (value == ResultCodeEnum.RedirectShopper) + return "RedirectShopper"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Success) + return "Success"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + /// + /// The result of the payment. For more information, see [Result codes](https://docs.adyen.com/online-payments/payment-result-codes). Possible values: * **AuthenticationFinished** – The payment has been successfully authenticated with 3D Secure 2. Returned for 3D Secure 2 authentication-only transactions. * **AuthenticationNotRequired** – The transaction does not require 3D Secure authentication. Returned for [standalone authentication-only integrations](https://docs.adyen.com/online-payments/3d-secure/other-3ds-flows/authentication-only). * **Authorised** – The payment was successfully authorised. This state serves as an indicator to proceed with the delivery of goods and services. This is a final state. * **Cancelled** – Indicates the payment has been cancelled (either by the shopper or the merchant) before processing was completed. This is a final state. * **ChallengeShopper** – The issuer requires further shopper interaction before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **Error** – There was an error when the payment was being processed. The reason is given in the `refusalReason` field. This is a final state. * **IdentifyShopper** – The issuer requires the shopper's device fingerprint before the payment can be authenticated. Returned for 3D Secure 2 transactions. * **PartiallyAuthorised** – The payment has been authorised for a partial amount. This happens for card payments when the merchant supports Partial Authorisations and the cardholder has insufficient funds. * **Pending** – Indicates that it is not possible to obtain the final status of the payment. This can happen if the systems providing final status information for the payment are unavailable, or if the shopper needs to take further action to complete the payment. * **PresentToShopper** – Indicates that the response contains additional information that you need to present to a shopper, so that they can use it to complete a payment. * **Received** – Indicates the payment has successfully been received by Adyen, and will be processed. This is the initial state for all payments. * **RedirectShopper** – Indicates the shopper should be redirected to an external web page or app to complete the authorisation. * **Refused** – Indicates the payment was refused. The reason is given in the `refusalReason` field. This is a final state. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first: Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("dccAmount")] + public Amount? DccAmount { get { return this._DccAmountOption; } set { this._DccAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DccSignatureOption { get; private set; } + + /// + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + /// + /// Cryptographic signature used to verify `dccQuote`. > This value only applies if you have implemented Dynamic Currency Conversion. For more information, [contact Support](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("dccSignature")] + public string? DccSignature { get { return this._DccSignatureOption; } set { this._DccSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fraudResult")] + public FraudResult? FraudResult { get { return this._FraudResultOption; } set { this._FraudResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerUrlOption { get; private set; } + + /// + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + /// + /// The URL to direct the shopper to. > In case of SecurePlus, do not redirect a shopper to this URL. + [JsonPropertyName("issuerUrl")] + public string? IssuerUrl { get { return this._IssuerUrlOption; } set { this._IssuerUrlOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MdOption { get; private set; } + + /// + /// The payment session. + /// + /// The payment session. + [JsonPropertyName("md")] + public string? Md { get { return this._MdOption; } set { this._MdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaRequestOption { get; private set; } + + /// + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + /// + /// The 3D request data for the issuer. If the value is **CUPSecurePlus-CollectSMSVerificationCode**, collect an SMS code from the shopper and pass it in the `/authorise3D` request. For more information, see [3D Secure](https://docs.adyen.com/classic-integration/3d-secure). + [JsonPropertyName("paRequest")] + public string? PaRequest { get { return this._PaRequestOption; } set { this._PaRequestOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + /// + /// If the payment's authorisation is refused or an error occurs during authorisation, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. For more information, see [Refusal reasons](https://docs.adyen.com/development-resources/refusal-reasons). + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PayoutResponse {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" DccAmount: ").Append(DccAmount).Append("\n"); + sb.Append(" DccSignature: ").Append(DccSignature).Append("\n"); + sb.Append(" FraudResult: ").Append(FraudResult).Append("\n"); + sb.Append(" IssuerUrl: ").Append(IssuerUrl).Append("\n"); + sb.Append(" Md: ").Append(Md).Append("\n"); + sb.Append(" PaRequest: ").Append(PaRequest).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Md (string) maxLength + if (this.Md != null && this.Md.Length > 20000) + { + yield return new ValidationResult("Invalid value for Md, length must be less than 20000.", new [] { "Md" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PayoutResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PayoutResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option authCode = default; + Option dccAmount = default; + Option dccSignature = default; + Option fraudResult = default; + Option issuerUrl = default; + Option md = default; + Option paRequest = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "dccAmount": + dccAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dccSignature": + dccSignature = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResult": + fraudResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "issuerUrl": + issuerUrl = new Option(utf8JsonReader.GetString()!); + break; + case "md": + md = new Option(utf8JsonReader.GetString()!); + break; + case "paRequest": + paRequest = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(PayoutResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + default: + break; + } + } + } + + + return new PayoutResponse(additionalData, authCode, dccAmount, dccSignature, fraudResult, issuerUrl, md, paRequest, pspReference, refusalReason, resultCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PayoutResponse payoutResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, payoutResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PayoutResponse payoutResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (payoutResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, payoutResponse.AdditionalData, jsonSerializerOptions); + } + if (payoutResponse._AuthCodeOption.IsSet) + if (payoutResponse.AuthCode != null) + writer.WriteString("authCode", payoutResponse.AuthCode); + + if (payoutResponse._DccAmountOption.IsSet) + { + writer.WritePropertyName("dccAmount"); + JsonSerializer.Serialize(writer, payoutResponse.DccAmount, jsonSerializerOptions); + } + if (payoutResponse._DccSignatureOption.IsSet) + if (payoutResponse.DccSignature != null) + writer.WriteString("dccSignature", payoutResponse.DccSignature); + + if (payoutResponse._FraudResultOption.IsSet) + { + writer.WritePropertyName("fraudResult"); + JsonSerializer.Serialize(writer, payoutResponse.FraudResult, jsonSerializerOptions); + } + if (payoutResponse._IssuerUrlOption.IsSet) + if (payoutResponse.IssuerUrl != null) + writer.WriteString("issuerUrl", payoutResponse.IssuerUrl); + + if (payoutResponse._MdOption.IsSet) + if (payoutResponse.Md != null) + writer.WriteString("md", payoutResponse.Md); + + if (payoutResponse._PaRequestOption.IsSet) + if (payoutResponse.PaRequest != null) + writer.WriteString("paRequest", payoutResponse.PaRequest); + + if (payoutResponse._PspReferenceOption.IsSet) + if (payoutResponse.PspReference != null) + writer.WriteString("pspReference", payoutResponse.PspReference); + + if (payoutResponse._RefusalReasonOption.IsSet) + if (payoutResponse.RefusalReason != null) + writer.WriteString("refusalReason", payoutResponse.RefusalReason); + + if (payoutResponse._ResultCodeOption.IsSet && payoutResponse.ResultCode != null) + { + string? resultCodeRawValue = PayoutResponse.ResultCodeEnum.ToJsonValue(payoutResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + } + } +} diff --git a/Adyen/Payout/Models/Recurring.cs b/Adyen/Payout/Models/Recurring.cs new file mode 100644 index 000000000..cd7486a69 --- /dev/null +++ b/Adyen/Payout/Models/Recurring.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// Recurring. + /// + public partial class Recurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// A descriptive name for this detail. + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// The name of the token service. + [JsonConstructor] + public Recurring(Option contract = default, Option recurringDetailName = default, Option recurringExpiry = default, Option recurringFrequency = default, Option tokenService = default) + { + _ContractOption = contract; + _RecurringDetailNameOption = recurringDetailName; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _TokenServiceOption = tokenService; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Recurring() + { + } + + partial void OnCreated(); + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonConverter(typeof(ContractEnumJsonConverter))] + public class ContractEnum : IEnum + { + /// + /// Returns the value of the ContractEnum. + /// + public string? Value { get; set; } + + /// + /// ContractEnum.ONECLICK - ONECLICK + /// + public static readonly ContractEnum ONECLICK = new("ONECLICK"); + + /// + /// ContractEnum.ONECLICKRECURRING - ONECLICK,RECURRING + /// + public static readonly ContractEnum ONECLICKRECURRING = new("ONECLICK,RECURRING"); + + /// + /// ContractEnum.RECURRING - RECURRING + /// + public static readonly ContractEnum RECURRING = new("RECURRING"); + + /// + /// ContractEnum.PAYOUT - PAYOUT + /// + public static readonly ContractEnum PAYOUT = new("PAYOUT"); + + /// + /// ContractEnum.EXTERNAL - EXTERNAL + /// + public static readonly ContractEnum EXTERNAL = new("EXTERNAL"); + + private ContractEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractEnum?(string? value) => value == null ? null : new ContractEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractEnum? option) => option?.Value; + + public static bool operator ==(ContractEnum? left, ContractEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractEnum? left, ContractEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractEnum? FromStringOrDefault(string value) + { + return value switch { + "ONECLICK" => ContractEnum.ONECLICK, + "ONECLICK,RECURRING" => ContractEnum.ONECLICKRECURRING, + "RECURRING" => ContractEnum.RECURRING, + "PAYOUT" => ContractEnum.PAYOUT, + "EXTERNAL" => ContractEnum.EXTERNAL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractEnum? value) + { + if (value == null) + return null; + + if (value == ContractEnum.ONECLICK) + return "ONECLICK"; + + if (value == ContractEnum.ONECLICKRECURRING) + return "ONECLICK,RECURRING"; + + if (value == ContractEnum.RECURRING) + return "RECURRING"; + + if (value == ContractEnum.PAYOUT) + return "PAYOUT"; + + if (value == ContractEnum.EXTERNAL) + return "EXTERNAL"; + + return null; + } + + /// + /// JsonConverter for writing ContractEnum. + /// + public class ContractEnumJsonConverter : JsonConverter + { + public override ContractEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractEnum.FromStringOrDefault(value) ?? new ContractEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonPropertyName("contract")] + public ContractEnum? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonConverter(typeof(TokenServiceEnumJsonConverter))] + public class TokenServiceEnum : IEnum + { + /// + /// Returns the value of the TokenServiceEnum. + /// + public string? Value { get; set; } + + /// + /// TokenServiceEnum.VISATOKENSERVICE - VISATOKENSERVICE + /// + public static readonly TokenServiceEnum VISATOKENSERVICE = new("VISATOKENSERVICE"); + + /// + /// TokenServiceEnum.MCTOKENSERVICE - MCTOKENSERVICE + /// + public static readonly TokenServiceEnum MCTOKENSERVICE = new("MCTOKENSERVICE"); + + /// + /// TokenServiceEnum.AMEXTOKENSERVICE - AMEXTOKENSERVICE + /// + public static readonly TokenServiceEnum AMEXTOKENSERVICE = new("AMEXTOKENSERVICE"); + + /// + /// TokenServiceEnum.TOKENSHARING - TOKEN_SHARING + /// + public static readonly TokenServiceEnum TOKENSHARING = new("TOKEN_SHARING"); + + private TokenServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenServiceEnum?(string? value) => value == null ? null : new TokenServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenServiceEnum? option) => option?.Value; + + public static bool operator ==(TokenServiceEnum? left, TokenServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenServiceEnum? left, TokenServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "VISATOKENSERVICE" => TokenServiceEnum.VISATOKENSERVICE, + "MCTOKENSERVICE" => TokenServiceEnum.MCTOKENSERVICE, + "AMEXTOKENSERVICE" => TokenServiceEnum.AMEXTOKENSERVICE, + "TOKEN_SHARING" => TokenServiceEnum.TOKENSHARING, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenServiceEnum? value) + { + if (value == null) + return null; + + if (value == TokenServiceEnum.VISATOKENSERVICE) + return "VISATOKENSERVICE"; + + if (value == TokenServiceEnum.MCTOKENSERVICE) + return "MCTOKENSERVICE"; + + if (value == TokenServiceEnum.AMEXTOKENSERVICE) + return "AMEXTOKENSERVICE"; + + if (value == TokenServiceEnum.TOKENSHARING) + return "TOKEN_SHARING"; + + return null; + } + + /// + /// JsonConverter for writing TokenServiceEnum. + /// + public class TokenServiceEnumJsonConverter : JsonConverter + { + public override TokenServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenServiceEnum.FromStringOrDefault(value) ?? new TokenServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenServiceOption { get; private set; } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonPropertyName("tokenService")] + public TokenServiceEnum? TokenService { get { return this._TokenServiceOption; } set { this._TokenServiceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailNameOption { get; private set; } + + /// + /// A descriptive name for this detail. + /// + /// A descriptive name for this detail. + [JsonPropertyName("recurringDetailName")] + public string? RecurringDetailName { get { return this._RecurringDetailNameOption; } set { this._RecurringDetailNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public DateTimeOffset? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Recurring {\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" TokenService: ").Append(TokenService).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RecurringExpiry. + /// + public static string RecurringExpiryFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Recurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contract = default; + Option recurringDetailName = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option tokenService = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contract": + string? contractRawValue = utf8JsonReader.GetString(); + contract = new Option(Recurring.ContractEnum.FromStringOrDefault(contractRawValue)); + break; + case "recurringDetailName": + recurringDetailName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "tokenService": + string? tokenServiceRawValue = utf8JsonReader.GetString(); + tokenService = new Option(Recurring.TokenServiceEnum.FromStringOrDefault(tokenServiceRawValue)); + break; + default: + break; + } + } + } + + + return new Recurring(contract, recurringDetailName, recurringExpiry, recurringFrequency, tokenService); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurring._ContractOption.IsSet && recurring.Contract != null) + { + string? contractRawValue = Recurring.ContractEnum.ToJsonValue(recurring._ContractOption.Value!.Value); + writer.WriteString("contract", contractRawValue); + } + + if (recurring._RecurringDetailNameOption.IsSet) + if (recurring.RecurringDetailName != null) + writer.WriteString("recurringDetailName", recurring.RecurringDetailName); + + if (recurring._RecurringExpiryOption.IsSet) + writer.WriteString("recurringExpiry", recurring._RecurringExpiryOption.Value!.Value.ToString(RecurringExpiryFormat)); + + if (recurring._RecurringFrequencyOption.IsSet) + if (recurring.RecurringFrequency != null) + writer.WriteString("recurringFrequency", recurring.RecurringFrequency); + + if (recurring._TokenServiceOption.IsSet && recurring.TokenService != null) + { + string? tokenServiceRawValue = Recurring.TokenServiceEnum.ToJsonValue(recurring._TokenServiceOption.Value!.Value); + writer.WriteString("tokenService", tokenServiceRawValue); + } + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalData3DSecure.cs b/Adyen/Payout/Models/ResponseAdditionalData3DSecure.cs new file mode 100644 index 000000000..8003b94a0 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalData3DSecure.cs @@ -0,0 +1,276 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalData3DSecure. + /// + public partial class ResponseAdditionalData3DSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// The CAVV algorithm used. + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonConstructor] + public ResponseAdditionalData3DSecure(Option cardHolderInfo = default, Option cavv = default, Option cavvAlgorithm = default, Option scaExemptionRequested = default, Option threeds2CardEnrolled = default) + { + _CardHolderInfoOption = cardHolderInfo; + _CavvOption = cavv; + _CavvAlgorithmOption = cavvAlgorithm; + _ScaExemptionRequestedOption = scaExemptionRequested; + _Threeds2CardEnrolledOption = threeds2CardEnrolled; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalData3DSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderInfoOption { get; private set; } + + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + /// + /// Information provided by the issuer to the cardholder. If this field is present, you need to display this information to the cardholder. + [JsonPropertyName("cardHolderInfo")] + public string? CardHolderInfo { get { return this._CardHolderInfoOption; } set { this._CardHolderInfoOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvOption { get; private set; } + + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + /// + /// The Cardholder Authentication Verification Value (CAVV) for the 3D Secure authentication session, as a Base64-encoded 20-byte array. + [JsonPropertyName("cavv")] + public string? Cavv { get { return this._CavvOption; } set { this._CavvOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CavvAlgorithmOption { get; private set; } + + /// + /// The CAVV algorithm used. + /// + /// The CAVV algorithm used. + [JsonPropertyName("cavvAlgorithm")] + public string? CavvAlgorithm { get { return this._CavvAlgorithmOption; } set { this._CavvAlgorithmOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaExemptionRequestedOption { get; private set; } + + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + /// + /// Shows the [exemption type](https://docs.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that Adyen requested for the payment. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** + [JsonPropertyName("scaExemptionRequested")] + public string? ScaExemptionRequested { get { return this._ScaExemptionRequestedOption; } set { this._ScaExemptionRequestedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Threeds2CardEnrolledOption { get; private set; } + + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + /// + /// Indicates whether a card is enrolled for 3D Secure 2. + [JsonPropertyName("threeds2.cardEnrolled")] + public bool? Threeds2CardEnrolled { get { return this._Threeds2CardEnrolledOption; } set { this._Threeds2CardEnrolledOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalData3DSecure {\n"); + sb.Append(" CardHolderInfo: ").Append(CardHolderInfo).Append("\n"); + sb.Append(" Cavv: ").Append(Cavv).Append("\n"); + sb.Append(" CavvAlgorithm: ").Append(CavvAlgorithm).Append("\n"); + sb.Append(" ScaExemptionRequested: ").Append(ScaExemptionRequested).Append("\n"); + sb.Append(" Threeds2CardEnrolled: ").Append(Threeds2CardEnrolled).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalData3DSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalData3DSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardHolderInfo = default; + Option cavv = default; + Option cavvAlgorithm = default; + Option scaExemptionRequested = default; + Option threeds2CardEnrolled = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardHolderInfo": + cardHolderInfo = new Option(utf8JsonReader.GetString()!); + break; + case "cavv": + cavv = new Option(utf8JsonReader.GetString()!); + break; + case "cavvAlgorithm": + cavvAlgorithm = new Option(utf8JsonReader.GetString()!); + break; + case "scaExemptionRequested": + scaExemptionRequested = new Option(utf8JsonReader.GetString()!); + break; + case "threeds2.cardEnrolled": + threeds2CardEnrolled = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalData3DSecure(cardHolderInfo, cavv, cavvAlgorithm, scaExemptionRequested, threeds2CardEnrolled); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalData3DSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalData3DSecure responseAdditionalData3DSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalData3DSecure._CardHolderInfoOption.IsSet) + if (responseAdditionalData3DSecure.CardHolderInfo != null) + writer.WriteString("cardHolderInfo", responseAdditionalData3DSecure.CardHolderInfo); + + if (responseAdditionalData3DSecure._CavvOption.IsSet) + if (responseAdditionalData3DSecure.Cavv != null) + writer.WriteString("cavv", responseAdditionalData3DSecure.Cavv); + + if (responseAdditionalData3DSecure._CavvAlgorithmOption.IsSet) + if (responseAdditionalData3DSecure.CavvAlgorithm != null) + writer.WriteString("cavvAlgorithm", responseAdditionalData3DSecure.CavvAlgorithm); + + if (responseAdditionalData3DSecure._ScaExemptionRequestedOption.IsSet) + if (responseAdditionalData3DSecure.ScaExemptionRequested != null) + writer.WriteString("scaExemptionRequested", responseAdditionalData3DSecure.ScaExemptionRequested); + + if (responseAdditionalData3DSecure._Threeds2CardEnrolledOption.IsSet) + writer.WriteBoolean("threeds2.cardEnrolled", responseAdditionalData3DSecure._Threeds2CardEnrolledOption.Value!.Value); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataBillingAddress.cs b/Adyen/Payout/Models/ResponseAdditionalDataBillingAddress.cs new file mode 100644 index 000000000..cc4dc921d --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataBillingAddress.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataBillingAddress. + /// + public partial class ResponseAdditionalDataBillingAddress : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The billing address city passed in the payment request. + /// The billing address country passed in the payment request. Example: NL + /// The billing address house number or name passed in the payment request. + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// The billing address state or province passed in the payment request. Example: NH + /// The billing address street passed in the payment request. + [JsonConstructor] + public ResponseAdditionalDataBillingAddress(Option billingAddressCity = default, Option billingAddressCountry = default, Option billingAddressHouseNumberOrName = default, Option billingAddressPostalCode = default, Option billingAddressStateOrProvince = default, Option billingAddressStreet = default) + { + _BillingAddressCityOption = billingAddressCity; + _BillingAddressCountryOption = billingAddressCountry; + _BillingAddressHouseNumberOrNameOption = billingAddressHouseNumberOrName; + _BillingAddressPostalCodeOption = billingAddressPostalCode; + _BillingAddressStateOrProvinceOption = billingAddressStateOrProvince; + _BillingAddressStreetOption = billingAddressStreet; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataBillingAddress() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCityOption { get; private set; } + + /// + /// The billing address city passed in the payment request. + /// + /// The billing address city passed in the payment request. + [JsonPropertyName("billingAddress.city")] + public string? BillingAddressCity { get { return this._BillingAddressCityOption; } set { this._BillingAddressCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressCountryOption { get; private set; } + + /// + /// The billing address country passed in the payment request. Example: NL + /// + /// The billing address country passed in the payment request. Example: NL + [JsonPropertyName("billingAddress.country")] + public string? BillingAddressCountry { get { return this._BillingAddressCountryOption; } set { this._BillingAddressCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressHouseNumberOrNameOption { get; private set; } + + /// + /// The billing address house number or name passed in the payment request. + /// + /// The billing address house number or name passed in the payment request. + [JsonPropertyName("billingAddress.houseNumberOrName")] + public string? BillingAddressHouseNumberOrName { get { return this._BillingAddressHouseNumberOrNameOption; } set { this._BillingAddressHouseNumberOrNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressPostalCodeOption { get; private set; } + + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + /// + /// The billing address postal code passed in the payment request. Example: 1011 DJ + [JsonPropertyName("billingAddress.postalCode")] + public string? BillingAddressPostalCode { get { return this._BillingAddressPostalCodeOption; } set { this._BillingAddressPostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStateOrProvinceOption { get; private set; } + + /// + /// The billing address state or province passed in the payment request. Example: NH + /// + /// The billing address state or province passed in the payment request. Example: NH + [JsonPropertyName("billingAddress.stateOrProvince")] + public string? BillingAddressStateOrProvince { get { return this._BillingAddressStateOrProvinceOption; } set { this._BillingAddressStateOrProvinceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressStreetOption { get; private set; } + + /// + /// The billing address street passed in the payment request. + /// + /// The billing address street passed in the payment request. + [JsonPropertyName("billingAddress.street")] + public string? BillingAddressStreet { get { return this._BillingAddressStreetOption; } set { this._BillingAddressStreetOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataBillingAddress {\n"); + sb.Append(" BillingAddressCity: ").Append(BillingAddressCity).Append("\n"); + sb.Append(" BillingAddressCountry: ").Append(BillingAddressCountry).Append("\n"); + sb.Append(" BillingAddressHouseNumberOrName: ").Append(BillingAddressHouseNumberOrName).Append("\n"); + sb.Append(" BillingAddressPostalCode: ").Append(BillingAddressPostalCode).Append("\n"); + sb.Append(" BillingAddressStateOrProvince: ").Append(BillingAddressStateOrProvince).Append("\n"); + sb.Append(" BillingAddressStreet: ").Append(BillingAddressStreet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataBillingAddressJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataBillingAddress Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option billingAddressCity = default; + Option billingAddressCountry = default; + Option billingAddressHouseNumberOrName = default; + Option billingAddressPostalCode = default; + Option billingAddressStateOrProvince = default; + Option billingAddressStreet = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "billingAddress.city": + billingAddressCity = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.country": + billingAddressCountry = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.houseNumberOrName": + billingAddressHouseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.postalCode": + billingAddressPostalCode = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.stateOrProvince": + billingAddressStateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + case "billingAddress.street": + billingAddressStreet = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataBillingAddress(billingAddressCity, billingAddressCountry, billingAddressHouseNumberOrName, billingAddressPostalCode, billingAddressStateOrProvince, billingAddressStreet); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataBillingAddress, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataBillingAddress responseAdditionalDataBillingAddress, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataBillingAddress._BillingAddressCityOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCity != null) + writer.WriteString("billingAddress.city", responseAdditionalDataBillingAddress.BillingAddressCity); + + if (responseAdditionalDataBillingAddress._BillingAddressCountryOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressCountry != null) + writer.WriteString("billingAddress.country", responseAdditionalDataBillingAddress.BillingAddressCountry); + + if (responseAdditionalDataBillingAddress._BillingAddressHouseNumberOrNameOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName != null) + writer.WriteString("billingAddress.houseNumberOrName", responseAdditionalDataBillingAddress.BillingAddressHouseNumberOrName); + + if (responseAdditionalDataBillingAddress._BillingAddressPostalCodeOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressPostalCode != null) + writer.WriteString("billingAddress.postalCode", responseAdditionalDataBillingAddress.BillingAddressPostalCode); + + if (responseAdditionalDataBillingAddress._BillingAddressStateOrProvinceOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStateOrProvince != null) + writer.WriteString("billingAddress.stateOrProvince", responseAdditionalDataBillingAddress.BillingAddressStateOrProvince); + + if (responseAdditionalDataBillingAddress._BillingAddressStreetOption.IsSet) + if (responseAdditionalDataBillingAddress.BillingAddressStreet != null) + writer.WriteString("billingAddress.street", responseAdditionalDataBillingAddress.BillingAddressStreet); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataCard.cs b/Adyen/Payout/Models/ResponseAdditionalDataCard.cs new file mode 100644 index 000000000..cdbba6133 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataCard.cs @@ -0,0 +1,564 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataCard. + /// + public partial class ResponseAdditionalDataCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// The cardholder name passed in the payment request. + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// The country where the card was issued. Example: US + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// The card payment method used for the transaction. Example: amex + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// The last four digits of a card number. > Returned only in case of a card payment. + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonConstructor] + public ResponseAdditionalDataCard(Option cardBin = default, Option cardHolderName = default, Option cardIssuingBank = default, Option cardIssuingCountry = default, Option cardIssuingCurrency = default, Option cardPaymentMethod = default, Option cardProductId = default, Option cardSummary = default, Option issuerBin = default) + { + _CardBinOption = cardBin; + _CardHolderNameOption = cardHolderName; + _CardIssuingBankOption = cardIssuingBank; + _CardIssuingCountryOption = cardIssuingCountry; + _CardIssuingCurrencyOption = cardIssuingCurrency; + _CardPaymentMethodOption = cardPaymentMethod; + _CardProductIdOption = cardProductId; + _CardSummaryOption = cardSummary; + _IssuerBinOption = issuerBin; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCard() + { + } + + partial void OnCreated(); + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonConverter(typeof(CardProductIdEnumJsonConverter))] + public class CardProductIdEnum : IEnum + { + /// + /// Returns the value of the CardProductIdEnum. + /// + public string? Value { get; set; } + + /// + /// CardProductIdEnum.A - A + /// + public static readonly CardProductIdEnum A = new("A"); + + /// + /// CardProductIdEnum.B - B + /// + public static readonly CardProductIdEnum B = new("B"); + + /// + /// CardProductIdEnum.C - C + /// + public static readonly CardProductIdEnum C = new("C"); + + /// + /// CardProductIdEnum.D - D + /// + public static readonly CardProductIdEnum D = new("D"); + + /// + /// CardProductIdEnum.F - F + /// + public static readonly CardProductIdEnum F = new("F"); + + /// + /// CardProductIdEnum.MCC - MCC + /// + public static readonly CardProductIdEnum MCC = new("MCC"); + + /// + /// CardProductIdEnum.MCE - MCE + /// + public static readonly CardProductIdEnum MCE = new("MCE"); + + /// + /// CardProductIdEnum.MCF - MCF + /// + public static readonly CardProductIdEnum MCF = new("MCF"); + + /// + /// CardProductIdEnum.MCG - MCG + /// + public static readonly CardProductIdEnum MCG = new("MCG"); + + /// + /// CardProductIdEnum.MCH - MCH + /// + public static readonly CardProductIdEnum MCH = new("MCH"); + + /// + /// CardProductIdEnum.MCI - MCI + /// + public static readonly CardProductIdEnum MCI = new("MCI"); + + private CardProductIdEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CardProductIdEnum?(string? value) => value == null ? null : new CardProductIdEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CardProductIdEnum? option) => option?.Value; + + public static bool operator ==(CardProductIdEnum? left, CardProductIdEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CardProductIdEnum? left, CardProductIdEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CardProductIdEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CardProductIdEnum? FromStringOrDefault(string value) + { + return value switch { + "A" => CardProductIdEnum.A, + "B" => CardProductIdEnum.B, + "C" => CardProductIdEnum.C, + "D" => CardProductIdEnum.D, + "F" => CardProductIdEnum.F, + "MCC" => CardProductIdEnum.MCC, + "MCE" => CardProductIdEnum.MCE, + "MCF" => CardProductIdEnum.MCF, + "MCG" => CardProductIdEnum.MCG, + "MCH" => CardProductIdEnum.MCH, + "MCI" => CardProductIdEnum.MCI, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CardProductIdEnum? value) + { + if (value == null) + return null; + + if (value == CardProductIdEnum.A) + return "A"; + + if (value == CardProductIdEnum.B) + return "B"; + + if (value == CardProductIdEnum.C) + return "C"; + + if (value == CardProductIdEnum.D) + return "D"; + + if (value == CardProductIdEnum.F) + return "F"; + + if (value == CardProductIdEnum.MCC) + return "MCC"; + + if (value == CardProductIdEnum.MCE) + return "MCE"; + + if (value == CardProductIdEnum.MCF) + return "MCF"; + + if (value == CardProductIdEnum.MCG) + return "MCG"; + + if (value == CardProductIdEnum.MCH) + return "MCH"; + + if (value == CardProductIdEnum.MCI) + return "MCI"; + + return null; + } + + /// + /// JsonConverter for writing CardProductIdEnum. + /// + public class CardProductIdEnumJsonConverter : JsonConverter + { + public override CardProductIdEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CardProductIdEnum.FromStringOrDefault(value) ?? new CardProductIdEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CardProductIdEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CardProductIdEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardProductIdOption { get; private set; } + + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + /// + /// The Card Product ID represents the type of card following card scheme product definitions and can be returned for Adyen Acquiring service level payments. Possible values Visa: * **A** - Visa Traditional * **B** - Visa Traditional Rewards * **C** - Visa Signature * **D** - Visa Signature Preferred * **F** - Visa Classic Possible values Mastercard: * **MCC** - Mastercard Card * **MCE** - Mastercard Electronic Card * **MCF** - Mastercard Corporate Fleet Card * **MCG** - Gold Mastercard Card * **MCH** - Mastercard Premium Charge * **MCI** - Mastercard Select Debit + [JsonPropertyName("cardProductId")] + public CardProductIdEnum? CardProductId { get { return this._CardProductIdOption; } set { this._CardProductIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardBinOption { get; private set; } + + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + /// + /// The first six digits of the card number. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with a six-digit BIN. Example: 521234 + [JsonPropertyName("cardBin")] + public string? CardBin { get { return this._CardBinOption; } set { this._CardBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardHolderNameOption { get; private set; } + + /// + /// The cardholder name passed in the payment request. + /// + /// The cardholder name passed in the payment request. + [JsonPropertyName("cardHolderName")] + public string? CardHolderName { get { return this._CardHolderNameOption; } set { this._CardHolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingBankOption { get; private set; } + + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + /// + /// The bank or the financial institution granting lines of credit through card association branded payment cards. This information can be included when available. + [JsonPropertyName("cardIssuingBank")] + public string? CardIssuingBank { get { return this._CardIssuingBankOption; } set { this._CardIssuingBankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCountryOption { get; private set; } + + /// + /// The country where the card was issued. Example: US + /// + /// The country where the card was issued. Example: US + [JsonPropertyName("cardIssuingCountry")] + public string? CardIssuingCountry { get { return this._CardIssuingCountryOption; } set { this._CardIssuingCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardIssuingCurrencyOption { get; private set; } + + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + /// + /// The currency in which the card is issued, if this information is available. Provided as the currency code or currency number from the ISO-4217 standard. Example: USD + [JsonPropertyName("cardIssuingCurrency")] + public string? CardIssuingCurrency { get { return this._CardIssuingCurrencyOption; } set { this._CardIssuingCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardPaymentMethodOption { get; private set; } + + /// + /// The card payment method used for the transaction. Example: amex + /// + /// The card payment method used for the transaction. Example: amex + [JsonPropertyName("cardPaymentMethod")] + public string? CardPaymentMethod { get { return this._CardPaymentMethodOption; } set { this._CardPaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardSummaryOption { get; private set; } + + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + /// + /// The last four digits of a card number. > Returned only in case of a card payment. + [JsonPropertyName("cardSummary")] + public string? CardSummary { get { return this._CardSummaryOption; } set { this._CardSummaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerBinOption { get; private set; } + + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + /// + /// The first eight digits of the card number. Only returned if the card number is 16 digits or more. This is the [Bank Identification Number (BIN)](https://docs.adyen.com/get-started-with-adyen/payment-glossary#bank-identification-number-bin) for card numbers with an eight-digit BIN. Example: 52123423 + [JsonPropertyName("issuerBin")] + public string? IssuerBin { get { return this._IssuerBinOption; } set { this._IssuerBinOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCard {\n"); + sb.Append(" CardBin: ").Append(CardBin).Append("\n"); + sb.Append(" CardHolderName: ").Append(CardHolderName).Append("\n"); + sb.Append(" CardIssuingBank: ").Append(CardIssuingBank).Append("\n"); + sb.Append(" CardIssuingCountry: ").Append(CardIssuingCountry).Append("\n"); + sb.Append(" CardIssuingCurrency: ").Append(CardIssuingCurrency).Append("\n"); + sb.Append(" CardPaymentMethod: ").Append(CardPaymentMethod).Append("\n"); + sb.Append(" CardProductId: ").Append(CardProductId).Append("\n"); + sb.Append(" CardSummary: ").Append(CardSummary).Append("\n"); + sb.Append(" IssuerBin: ").Append(IssuerBin).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardBin = default; + Option cardHolderName = default; + Option cardIssuingBank = default; + Option cardIssuingCountry = default; + Option cardIssuingCurrency = default; + Option cardPaymentMethod = default; + Option cardProductId = default; + Option cardSummary = default; + Option issuerBin = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardBin": + cardBin = new Option(utf8JsonReader.GetString()!); + break; + case "cardHolderName": + cardHolderName = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingBank": + cardIssuingBank = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCountry": + cardIssuingCountry = new Option(utf8JsonReader.GetString()!); + break; + case "cardIssuingCurrency": + cardIssuingCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "cardPaymentMethod": + cardPaymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "cardProductId": + string? cardProductIdRawValue = utf8JsonReader.GetString(); + cardProductId = new Option(ResponseAdditionalDataCard.CardProductIdEnum.FromStringOrDefault(cardProductIdRawValue)); + break; + case "cardSummary": + cardSummary = new Option(utf8JsonReader.GetString()!); + break; + case "issuerBin": + issuerBin = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCard(cardBin, cardHolderName, cardIssuingBank, cardIssuingCountry, cardIssuingCurrency, cardPaymentMethod, cardProductId, cardSummary, issuerBin); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCard responseAdditionalDataCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCard._CardBinOption.IsSet) + if (responseAdditionalDataCard.CardBin != null) + writer.WriteString("cardBin", responseAdditionalDataCard.CardBin); + + if (responseAdditionalDataCard._CardHolderNameOption.IsSet) + if (responseAdditionalDataCard.CardHolderName != null) + writer.WriteString("cardHolderName", responseAdditionalDataCard.CardHolderName); + + if (responseAdditionalDataCard._CardIssuingBankOption.IsSet) + if (responseAdditionalDataCard.CardIssuingBank != null) + writer.WriteString("cardIssuingBank", responseAdditionalDataCard.CardIssuingBank); + + if (responseAdditionalDataCard._CardIssuingCountryOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCountry != null) + writer.WriteString("cardIssuingCountry", responseAdditionalDataCard.CardIssuingCountry); + + if (responseAdditionalDataCard._CardIssuingCurrencyOption.IsSet) + if (responseAdditionalDataCard.CardIssuingCurrency != null) + writer.WriteString("cardIssuingCurrency", responseAdditionalDataCard.CardIssuingCurrency); + + if (responseAdditionalDataCard._CardPaymentMethodOption.IsSet) + if (responseAdditionalDataCard.CardPaymentMethod != null) + writer.WriteString("cardPaymentMethod", responseAdditionalDataCard.CardPaymentMethod); + + if (responseAdditionalDataCard._CardProductIdOption.IsSet && responseAdditionalDataCard.CardProductId != null) + { + string? cardProductIdRawValue = ResponseAdditionalDataCard.CardProductIdEnum.ToJsonValue(responseAdditionalDataCard._CardProductIdOption.Value!.Value); + writer.WriteString("cardProductId", cardProductIdRawValue); + } + + if (responseAdditionalDataCard._CardSummaryOption.IsSet) + if (responseAdditionalDataCard.CardSummary != null) + writer.WriteString("cardSummary", responseAdditionalDataCard.CardSummary); + + if (responseAdditionalDataCard._IssuerBinOption.IsSet) + if (responseAdditionalDataCard.IssuerBin != null) + writer.WriteString("issuerBin", responseAdditionalDataCard.IssuerBin); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataCommon.cs b/Adyen/Payout/Models/ResponseAdditionalDataCommon.cs new file mode 100644 index 000000000..852bd2697 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataCommon.cs @@ -0,0 +1,2200 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataCommon. + /// + public partial class ResponseAdditionalDataCommon : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// The Adyen alias of the card. Example: H167852639363479 + /// The type of the card alias. Example: Default + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// Merchant ID known by the acquirer. + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// Raw AVS result received from the acquirer, where available. Example: D + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// Includes the co-branded card information. + /// The result of CVC verification. + /// The raw result of CVC verification. + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// Indicates if the payment is sent to manual review. + /// The fraud result properties of the payment. + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// Indicates if the card is used for business purposes only. + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// The reference provided for the transaction. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// The payment method used in the transaction. + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// Message to be displayed on the terminal. + /// The recurring contract types applicable to the transaction. + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// The reference that uniquely identifies the recurring transaction. + /// The provided reference of the shopper for a recurring transaction. + /// The processing model used for the recurring transaction. + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// The amount of the payment request. + /// The currency of the payment request. + /// The shopper interaction type of the payment request. Example: Ecommerce + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// The raw 3DS authentication result from the card issuer. Example: N + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// The 3D Secure 2 version. + /// The reference for the shopper that you sent when tokenizing the payment details. + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// The reference that uniquely identifies tokenized payment details. + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonConstructor] + public ResponseAdditionalDataCommon(Option acquirerAccountCode = default, Option acquirerCode = default, Option acquirerReference = default, Option alias = default, Option aliasType = default, Option authCode = default, Option authorisationMid = default, Option authorisedAmountCurrency = default, Option authorisedAmountValue = default, Option avsResult = default, Option avsResultRaw = default, Option bic = default, Option coBrandedWith = default, Option cvcResult = default, Option cvcResultRaw = default, Option dsTransID = default, Option eci = default, Option expiryDate = default, Option extraCostsCurrency = default, Option extraCostsValue = default, Option fraudCheckItemNrFraudCheckname = default, Option fraudManualReview = default, Option fraudResultType = default, Option fraudRiskLevel = default, Option fundingSource = default, Option fundsAvailability = default, Option inferredRefusalReason = default, Option isCardCommercial = default, Option issuerCountry = default, Option liabilityShift = default, Option mcBankNetReferenceNumber = default, Option merchantAdviceCode = default, Option merchantReference = default, Option networkTxReference = default, Option ownerName = default, Option paymentAccountReference = default, Option paymentMethod = default, Option paymentMethodVariant = default, Option payoutEligible = default, Option realtimeAccountUpdaterStatus = default, Option receiptFreeText = default, Option recurringContractTypes = default, Option recurringFirstPspReference = default, Option recurringRecurringDetailReference = default, Option recurringShopperReference = default, Option recurringProcessingModel = default, Option referred = default, Option refusalReasonRaw = default, Option requestAmount = default, Option requestCurrencyCode = default, Option shopperInteraction = default, Option shopperReference = default, Option terminalId = default, Option threeDAuthenticated = default, Option threeDAuthenticatedResponse = default, Option threeDOffered = default, Option threeDOfferedResponse = default, Option threeDSVersion = default, Option tokenizationShopperReference = default, Option tokenizationStoreOperationType = default, Option tokenizationStoredPaymentMethodId = default, Option visaTransactionId = default, Option xid = default) + { + _AcquirerAccountCodeOption = acquirerAccountCode; + _AcquirerCodeOption = acquirerCode; + _AcquirerReferenceOption = acquirerReference; + _AliasOption = alias; + _AliasTypeOption = aliasType; + _AuthCodeOption = authCode; + _AuthorisationMidOption = authorisationMid; + _AuthorisedAmountCurrencyOption = authorisedAmountCurrency; + _AuthorisedAmountValueOption = authorisedAmountValue; + _AvsResultOption = avsResult; + _AvsResultRawOption = avsResultRaw; + _BicOption = bic; + _CoBrandedWithOption = coBrandedWith; + _CvcResultOption = cvcResult; + _CvcResultRawOption = cvcResultRaw; + _DsTransIDOption = dsTransID; + _EciOption = eci; + _ExpiryDateOption = expiryDate; + _ExtraCostsCurrencyOption = extraCostsCurrency; + _ExtraCostsValueOption = extraCostsValue; + _FraudCheckItemNrFraudChecknameOption = fraudCheckItemNrFraudCheckname; + _FraudManualReviewOption = fraudManualReview; + _FraudResultTypeOption = fraudResultType; + _FraudRiskLevelOption = fraudRiskLevel; + _FundingSourceOption = fundingSource; + _FundsAvailabilityOption = fundsAvailability; + _InferredRefusalReasonOption = inferredRefusalReason; + _IsCardCommercialOption = isCardCommercial; + _IssuerCountryOption = issuerCountry; + _LiabilityShiftOption = liabilityShift; + _McBankNetReferenceNumberOption = mcBankNetReferenceNumber; + _MerchantAdviceCodeOption = merchantAdviceCode; + _MerchantReferenceOption = merchantReference; + _NetworkTxReferenceOption = networkTxReference; + _OwnerNameOption = ownerName; + _PaymentAccountReferenceOption = paymentAccountReference; + _PaymentMethodOption = paymentMethod; + _PaymentMethodVariantOption = paymentMethodVariant; + _PayoutEligibleOption = payoutEligible; + _RealtimeAccountUpdaterStatusOption = realtimeAccountUpdaterStatus; + _ReceiptFreeTextOption = receiptFreeText; + _RecurringContractTypesOption = recurringContractTypes; + _RecurringFirstPspReferenceOption = recurringFirstPspReference; + _RecurringRecurringDetailReferenceOption = recurringRecurringDetailReference; + _RecurringShopperReferenceOption = recurringShopperReference; + _RecurringProcessingModelOption = recurringProcessingModel; + _ReferredOption = referred; + _RefusalReasonRawOption = refusalReasonRaw; + _RequestAmountOption = requestAmount; + _RequestCurrencyCodeOption = requestCurrencyCode; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _TerminalIdOption = terminalId; + _ThreeDAuthenticatedOption = threeDAuthenticated; + _ThreeDAuthenticatedResponseOption = threeDAuthenticatedResponse; + _ThreeDOfferedOption = threeDOffered; + _ThreeDOfferedResponseOption = threeDOfferedResponse; + _ThreeDSVersionOption = threeDSVersion; + _TokenizationShopperReferenceOption = tokenizationShopperReference; + _TokenizationStoreOperationTypeOption = tokenizationStoreOperationType; + _TokenizationStoredPaymentMethodIdOption = tokenizationStoredPaymentMethodId; + _VisaTransactionIdOption = visaTransactionId; + _XidOption = xid; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataCommon() + { + } + + partial void OnCreated(); + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonConverter(typeof(FraudResultTypeEnumJsonConverter))] + public class FraudResultTypeEnum : IEnum + { + /// + /// Returns the value of the FraudResultTypeEnum. + /// + public string? Value { get; set; } + + /// + /// FraudResultTypeEnum.GREEN - GREEN + /// + public static readonly FraudResultTypeEnum GREEN = new("GREEN"); + + /// + /// FraudResultTypeEnum.FRAUD - FRAUD + /// + public static readonly FraudResultTypeEnum FRAUD = new("FRAUD"); + + private FraudResultTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudResultTypeEnum?(string? value) => value == null ? null : new FraudResultTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudResultTypeEnum? option) => option?.Value; + + public static bool operator ==(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudResultTypeEnum? left, FraudResultTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudResultTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudResultTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "GREEN" => FraudResultTypeEnum.GREEN, + "FRAUD" => FraudResultTypeEnum.FRAUD, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudResultTypeEnum? value) + { + if (value == null) + return null; + + if (value == FraudResultTypeEnum.GREEN) + return "GREEN"; + + if (value == FraudResultTypeEnum.FRAUD) + return "FRAUD"; + + return null; + } + + /// + /// JsonConverter for writing FraudResultTypeEnum. + /// + public class FraudResultTypeEnumJsonConverter : JsonConverter + { + public override FraudResultTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudResultTypeEnum.FromStringOrDefault(value) ?? new FraudResultTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudResultTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudResultTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudResultTypeOption { get; private set; } + + /// + /// The fraud result properties of the payment. + /// + /// The fraud result properties of the payment. + [JsonPropertyName("fraudResultType")] + public FraudResultTypeEnum? FraudResultType { get { return this._FraudResultTypeOption; } set { this._FraudResultTypeOption = new(value); } } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonConverter(typeof(FraudRiskLevelEnumJsonConverter))] + public class FraudRiskLevelEnum : IEnum + { + /// + /// Returns the value of the FraudRiskLevelEnum. + /// + public string? Value { get; set; } + + /// + /// FraudRiskLevelEnum.VeryLow - veryLow + /// + public static readonly FraudRiskLevelEnum VeryLow = new("veryLow"); + + /// + /// FraudRiskLevelEnum.Low - low + /// + public static readonly FraudRiskLevelEnum Low = new("low"); + + /// + /// FraudRiskLevelEnum.Medium - medium + /// + public static readonly FraudRiskLevelEnum Medium = new("medium"); + + /// + /// FraudRiskLevelEnum.High - high + /// + public static readonly FraudRiskLevelEnum High = new("high"); + + /// + /// FraudRiskLevelEnum.VeryHigh - veryHigh + /// + public static readonly FraudRiskLevelEnum VeryHigh = new("veryHigh"); + + private FraudRiskLevelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator FraudRiskLevelEnum?(string? value) => value == null ? null : new FraudRiskLevelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(FraudRiskLevelEnum? option) => option?.Value; + + public static bool operator ==(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(FraudRiskLevelEnum? left, FraudRiskLevelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is FraudRiskLevelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static FraudRiskLevelEnum? FromStringOrDefault(string value) + { + return value switch { + "veryLow" => FraudRiskLevelEnum.VeryLow, + "low" => FraudRiskLevelEnum.Low, + "medium" => FraudRiskLevelEnum.Medium, + "high" => FraudRiskLevelEnum.High, + "veryHigh" => FraudRiskLevelEnum.VeryHigh, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(FraudRiskLevelEnum? value) + { + if (value == null) + return null; + + if (value == FraudRiskLevelEnum.VeryLow) + return "veryLow"; + + if (value == FraudRiskLevelEnum.Low) + return "low"; + + if (value == FraudRiskLevelEnum.Medium) + return "medium"; + + if (value == FraudRiskLevelEnum.High) + return "high"; + + if (value == FraudRiskLevelEnum.VeryHigh) + return "veryHigh"; + + return null; + } + + /// + /// JsonConverter for writing FraudRiskLevelEnum. + /// + public class FraudRiskLevelEnumJsonConverter : JsonConverter + { + public override FraudRiskLevelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : FraudRiskLevelEnum.FromStringOrDefault(value) ?? new FraudRiskLevelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, FraudRiskLevelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(FraudRiskLevelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudRiskLevelOption { get; private set; } + + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + /// + /// The risk level of the transaction as classified by the [machine learning](https://docs.adyen.com/risk-management/configure-your-risk-profile/machine-learning-rules/) fraud risk rule. The risk level indicates the likelihood that a transaction will result in a fraudulent dispute. The possible return values are: * veryLow * low * medium * high * veryHigh + [JsonPropertyName("fraudRiskLevel")] + public FraudRiskLevelEnum? FraudRiskLevel { get { return this._FraudRiskLevelOption; } set { this._FraudRiskLevelOption = new(value); } } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonConverter(typeof(RecurringProcessingModelEnumJsonConverter))] + public class RecurringProcessingModelEnum : IEnum + { + /// + /// Returns the value of the RecurringProcessingModelEnum. + /// + public string? Value { get; set; } + + /// + /// RecurringProcessingModelEnum.CardOnFile - CardOnFile + /// + public static readonly RecurringProcessingModelEnum CardOnFile = new("CardOnFile"); + + /// + /// RecurringProcessingModelEnum.Subscription - Subscription + /// + public static readonly RecurringProcessingModelEnum Subscription = new("Subscription"); + + /// + /// RecurringProcessingModelEnum.UnscheduledCardOnFile - UnscheduledCardOnFile + /// + public static readonly RecurringProcessingModelEnum UnscheduledCardOnFile = new("UnscheduledCardOnFile"); + + private RecurringProcessingModelEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator RecurringProcessingModelEnum?(string? value) => value == null ? null : new RecurringProcessingModelEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(RecurringProcessingModelEnum? option) => option?.Value; + + public static bool operator ==(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(RecurringProcessingModelEnum? left, RecurringProcessingModelEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is RecurringProcessingModelEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static RecurringProcessingModelEnum? FromStringOrDefault(string value) + { + return value switch { + "CardOnFile" => RecurringProcessingModelEnum.CardOnFile, + "Subscription" => RecurringProcessingModelEnum.Subscription, + "UnscheduledCardOnFile" => RecurringProcessingModelEnum.UnscheduledCardOnFile, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(RecurringProcessingModelEnum? value) + { + if (value == null) + return null; + + if (value == RecurringProcessingModelEnum.CardOnFile) + return "CardOnFile"; + + if (value == RecurringProcessingModelEnum.Subscription) + return "Subscription"; + + if (value == RecurringProcessingModelEnum.UnscheduledCardOnFile) + return "UnscheduledCardOnFile"; + + return null; + } + + /// + /// JsonConverter for writing RecurringProcessingModelEnum. + /// + public class RecurringProcessingModelEnumJsonConverter : JsonConverter + { + public override RecurringProcessingModelEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : RecurringProcessingModelEnum.FromStringOrDefault(value) ?? new RecurringProcessingModelEnum(value); + } + + public override void Write(Utf8JsonWriter writer, RecurringProcessingModelEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(RecurringProcessingModelEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringProcessingModelOption { get; private set; } + + /// + /// The processing model used for the recurring transaction. + /// + /// The processing model used for the recurring transaction. + [JsonPropertyName("recurringProcessingModel")] + public RecurringProcessingModelEnum? RecurringProcessingModel { get { return this._RecurringProcessingModelOption; } set { this._RecurringProcessingModelOption = new(value); } } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonConverter(typeof(TokenizationStoreOperationTypeEnumJsonConverter))] + public class TokenizationStoreOperationTypeEnum : IEnum + { + /// + /// Returns the value of the TokenizationStoreOperationTypeEnum. + /// + public string? Value { get; set; } + + /// + /// TokenizationStoreOperationTypeEnum.Created - created + /// + public static readonly TokenizationStoreOperationTypeEnum Created = new("created"); + + /// + /// TokenizationStoreOperationTypeEnum.Updated - updated + /// + public static readonly TokenizationStoreOperationTypeEnum Updated = new("updated"); + + /// + /// TokenizationStoreOperationTypeEnum.AlreadyExisting - alreadyExisting + /// + public static readonly TokenizationStoreOperationTypeEnum AlreadyExisting = new("alreadyExisting"); + + private TokenizationStoreOperationTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenizationStoreOperationTypeEnum?(string? value) => value == null ? null : new TokenizationStoreOperationTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenizationStoreOperationTypeEnum? option) => option?.Value; + + public static bool operator ==(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenizationStoreOperationTypeEnum? left, TokenizationStoreOperationTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenizationStoreOperationTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenizationStoreOperationTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "created" => TokenizationStoreOperationTypeEnum.Created, + "updated" => TokenizationStoreOperationTypeEnum.Updated, + "alreadyExisting" => TokenizationStoreOperationTypeEnum.AlreadyExisting, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenizationStoreOperationTypeEnum? value) + { + if (value == null) + return null; + + if (value == TokenizationStoreOperationTypeEnum.Created) + return "created"; + + if (value == TokenizationStoreOperationTypeEnum.Updated) + return "updated"; + + if (value == TokenizationStoreOperationTypeEnum.AlreadyExisting) + return "alreadyExisting"; + + return null; + } + + /// + /// JsonConverter for writing TokenizationStoreOperationTypeEnum. + /// + public class TokenizationStoreOperationTypeEnumJsonConverter : JsonConverter + { + public override TokenizationStoreOperationTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenizationStoreOperationTypeEnum.FromStringOrDefault(value) ?? new TokenizationStoreOperationTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenizationStoreOperationTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenizationStoreOperationTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoreOperationTypeOption { get; private set; } + + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + /// + /// The operation performed on the token. Possible values: * **created**: the token has been created. * **updated**: the existing token has been updated. * **alreadyExisting**: the details have already been stored. + [JsonPropertyName("tokenization.store.operationType")] + public TokenizationStoreOperationTypeEnum? TokenizationStoreOperationType { get { return this._TokenizationStoreOperationTypeOption; } set { this._TokenizationStoreOperationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerAccountCodeOption { get; private set; } + + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + /// + /// The name of the Adyen acquirer account. Example: PayPalSandbox_TestAcquirer > Only relevant for PayPal transactions. + [JsonPropertyName("acquirerAccountCode")] + public string? AcquirerAccountCode { get { return this._AcquirerAccountCodeOption; } set { this._AcquirerAccountCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerCodeOption { get; private set; } + + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + /// + /// The name of the acquirer processing the payment request. Example: TestPmmAcquirer + [JsonPropertyName("acquirerCode")] + public string? AcquirerCode { get { return this._AcquirerCodeOption; } set { this._AcquirerCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerReferenceOption { get; private set; } + + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + /// + /// The reference number that can be used for reconciliation in case a non-Adyen acquirer is used for settlement. Example: 7C9N3FNBKT9 + [JsonPropertyName("acquirerReference")] + public string? AcquirerReference { get { return this._AcquirerReferenceOption; } set { this._AcquirerReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasOption { get; private set; } + + /// + /// The Adyen alias of the card. Example: H167852639363479 + /// + /// The Adyen alias of the card. Example: H167852639363479 + [JsonPropertyName("alias")] + public string? Alias { get { return this._AliasOption; } set { this._AliasOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasTypeOption { get; private set; } + + /// + /// The type of the card alias. Example: Default + /// + /// The type of the card alias. Example: Default + [JsonPropertyName("aliasType")] + public string? AliasType { get { return this._AliasTypeOption; } set { this._AliasTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + /// + /// Authorisation code: * When the payment is authorised successfully, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. Example: 58747 + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationMidOption { get; private set; } + + /// + /// Merchant ID known by the acquirer. + /// + /// Merchant ID known by the acquirer. + [JsonPropertyName("authorisationMid")] + public string? AuthorisationMid { get { return this._AuthorisationMidOption; } set { this._AuthorisationMidOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountCurrencyOption { get; private set; } + + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The currency of the authorised amount, as a three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountCurrency")] + public string? AuthorisedAmountCurrency { get { return this._AuthorisedAmountCurrencyOption; } set { this._AuthorisedAmountCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisedAmountValueOption { get; private set; } + + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + /// + /// Value of the amount authorised. This amount is represented in minor units according to the [following table](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("authorisedAmountValue")] + public string? AuthorisedAmountValue { get { return this._AuthorisedAmountValueOption; } set { this._AuthorisedAmountValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultOption { get; private set; } + + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + /// + /// The AVS result code of the payment, which provides information about the outcome of the AVS check. For possible values, see [AVS](https://docs.adyen.com/risk-management/configure-standard-risk-rules/consistency-rules#billing-address-does-not-match-cardholder-address-avs). + [JsonPropertyName("avsResult")] + public string? AvsResult { get { return this._AvsResultOption; } set { this._AvsResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AvsResultRawOption { get; private set; } + + /// + /// Raw AVS result received from the acquirer, where available. Example: D + /// + /// Raw AVS result received from the acquirer, where available. Example: D + [JsonPropertyName("avsResultRaw")] + public string? AvsResultRaw { get { return this._AvsResultRawOption; } set { this._AvsResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + /// + /// BIC of a bank account. Example: TESTNL01 > Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CoBrandedWithOption { get; private set; } + + /// + /// Includes the co-branded card information. + /// + /// Includes the co-branded card information. + [JsonPropertyName("coBrandedWith")] + public string? CoBrandedWith { get { return this._CoBrandedWithOption; } set { this._CoBrandedWithOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultOption { get; private set; } + + /// + /// The result of CVC verification. + /// + /// The result of CVC verification. + /* 1 Matches */ + [JsonPropertyName("cvcResult")] + public string? CvcResult { get { return this._CvcResultOption; } set { this._CvcResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcResultRawOption { get; private set; } + + /// + /// The raw result of CVC verification. + /// + /// The raw result of CVC verification. + /* M */ + [JsonPropertyName("cvcResultRaw")] + public string? CvcResultRaw { get { return this._CvcResultRawOption; } set { this._CvcResultRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DsTransIDOption { get; private set; } + + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + /// + /// Supported for 3D Secure 2. The unique transaction identifier assigned by the DS to identify a single transaction. + [JsonPropertyName("dsTransID")] + public string? DsTransID { get { return this._DsTransIDOption; } set { this._DsTransIDOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EciOption { get; private set; } + + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + /// + /// The Electronic Commerce Indicator returned from the schemes for the 3DS payment session. Example: 02 + [JsonPropertyName("eci")] + public string? Eci { get { return this._EciOption; } set { this._EciOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryDateOption { get; private set; } + + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + /// + /// The expiry date on the card. Example: 6/2016 > Returned only in case of a card payment. + [JsonPropertyName("expiryDate")] + public string? ExpiryDate { get { return this._ExpiryDateOption; } set { this._ExpiryDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsCurrencyOption { get; private set; } + + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + /// + /// The currency of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. Example: EUR + [JsonPropertyName("extraCostsCurrency")] + public string? ExtraCostsCurrency { get { return this._ExtraCostsCurrencyOption; } set { this._ExtraCostsCurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExtraCostsValueOption { get; private set; } + + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + /// + /// The value of the extra amount charged due to additional amounts set in the skin used in the HPP payment request. The amount is in minor units. + [JsonPropertyName("extraCostsValue")] + public string? ExtraCostsValue { get { return this._ExtraCostsValueOption; } set { this._ExtraCostsValueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudCheckItemNrFraudChecknameOption { get; private set; } + + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + /// + /// The fraud score due to a particular fraud check. The fraud check name is found in the key of the key-value pair. + [JsonPropertyName("fraudCheck-[itemNr]-[FraudCheckname]")] + public string? FraudCheckItemNrFraudCheckname { get { return this._FraudCheckItemNrFraudChecknameOption; } set { this._FraudCheckItemNrFraudChecknameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudManualReviewOption { get; private set; } + + /// + /// Indicates if the payment is sent to manual review. + /// + /// Indicates if the payment is sent to manual review. + [JsonPropertyName("fraudManualReview")] + public string? FraudManualReview { get { return this._FraudManualReviewOption; } set { this._FraudManualReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundingSourceOption { get; private set; } + + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + /// + /// Information regarding the funding type of the card. The possible return values are: * CHARGE * CREDIT * DEBIT * PREPAID * PREPAID_RELOADABLE * PREPAID_NONRELOADABLE * DEFFERED_DEBIT > This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. For receiving this field in the notification, enable **Include Funding Source** in **Notifications** > **Additional settings**. + [JsonPropertyName("fundingSource")] + public string? FundingSource { get { return this._FundingSourceOption; } set { this._FundingSourceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FundsAvailabilityOption { get; private set; } + + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + /// + /// Indicates availability of funds. Visa: * \"I\" (fast funds are supported) * \"N\" (otherwise) Mastercard: * \"I\" (product type is Prepaid or Debit, or issuing country is in CEE/HGEM list) * \"N\" (otherwise) > Returned when you verify a card BIN or estimate costs, and only if payoutEligible is \"Y\" or \"D\". + [JsonPropertyName("fundsAvailability")] + public string? FundsAvailability { get { return this._FundsAvailabilityOption; } set { this._FundsAvailabilityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InferredRefusalReasonOption { get; private set; } + + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + /// + /// Provides the more granular indication of why a transaction was refused. When a transaction fails with either \"Refused\", \"Restricted Card\", \"Transaction Not Permitted\", \"Not supported\" or \"DeclinedNon Generic\" refusalReason from the issuer, Adyen cross references its PSP-wide data for extra insight into the refusal reason. If an inferred refusal reason is available, the `inferredRefusalReason`, field is populated and the `refusalReason`, is set to \"Not Supported\". Possible values: * 3D Secure Mandated * Closed Account * ContAuth Not Supported * CVC Mandated * Ecommerce Not Allowed * Crossborder Not Supported * Card Updated * Low Authrate Bin * Non-reloadable prepaid card + [JsonPropertyName("inferredRefusalReason")] + public string? InferredRefusalReason { get { return this._InferredRefusalReasonOption; } set { this._InferredRefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IsCardCommercialOption { get; private set; } + + /// + /// Indicates if the card is used for business purposes only. + /// + /// Indicates if the card is used for business purposes only. + [JsonPropertyName("isCardCommercial")] + public string? IsCardCommercial { get { return this._IsCardCommercialOption; } set { this._IsCardCommercialOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssuerCountryOption { get; private set; } + + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + /// + /// The issuing country of the card based on the BIN list that Adyen maintains. Example: JP + [JsonPropertyName("issuerCountry")] + public string? IssuerCountry { get { return this._IssuerCountryOption; } set { this._IssuerCountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LiabilityShiftOption { get; private set; } + + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + /// + /// A Boolean value indicating whether a liability shift was offered for this payment. + [JsonPropertyName("liabilityShift")] + public string? LiabilityShift { get { return this._LiabilityShiftOption; } set { this._LiabilityShiftOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _McBankNetReferenceNumberOption { get; private set; } + + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + /// + /// The `mcBankNetReferenceNumber`, is a minimum of six characters and a maximum of nine characters long. > Contact Support Team to enable this field. + [JsonPropertyName("mcBankNetReferenceNumber")] + public string? McBankNetReferenceNumber { get { return this._McBankNetReferenceNumberOption; } set { this._McBankNetReferenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAdviceCodeOption { get; private set; } + + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + /// + /// The Merchant Advice Code (MAC) can be returned by Mastercard issuers for refused payments. If present, the MAC contains information about why the payment failed, and whether it can be retried. For more information see [Mastercard Merchant Advice Codes](https://docs.adyen.com/development-resources/raw-acquirer-responses#mastercard-merchant-advice-codes). + [JsonPropertyName("merchantAdviceCode")] + public string? MerchantAdviceCode { get { return this._MerchantAdviceCodeOption; } set { this._MerchantAdviceCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantReferenceOption { get; private set; } + + /// + /// The reference provided for the transaction. + /// + /// The reference provided for the transaction. + [JsonPropertyName("merchantReference")] + public string? MerchantReference { get { return this._MerchantReferenceOption; } set { this._MerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + /// + /// The owner name of a bank account. Only relevant for SEPA Direct Debit transactions. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentAccountReferenceOption { get; private set; } + + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + /// + /// The Payment Account Reference (PAR) value links a network token with the underlying primary account number (PAN). The PAR value consists of 29 uppercase alphanumeric characters. + [JsonPropertyName("paymentAccountReference")] + public string? PaymentAccountReference { get { return this._PaymentAccountReferenceOption; } set { this._PaymentAccountReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodOption { get; private set; } + + /// + /// The payment method used in the transaction. + /// + /// The payment method used in the transaction. + [JsonPropertyName("paymentMethod")] + public string? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodVariantOption { get; private set; } + + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + /// + /// The Adyen sub-variant of the payment method used for the payment request. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). Example: mcpro + [JsonPropertyName("paymentMethodVariant")] + public string? PaymentMethodVariant { get { return this._PaymentMethodVariantOption; } set { this._PaymentMethodVariantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PayoutEligibleOption { get; private set; } + + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + /// + /// Indicates whether a payout is eligible or not for this card. Visa: * \"Y\" * \"N\" Mastercard: * \"Y\" (domestic and cross-border) * \"D\" (only domestic) * \"N\" (no MoneySend) * \"U\" (unknown) + [JsonPropertyName("payoutEligible")] + public string? PayoutEligible { get { return this._PayoutEligibleOption; } set { this._PayoutEligibleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RealtimeAccountUpdaterStatusOption { get; private set; } + + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + /// + /// The response code from the Real Time Account Updater service. Possible return values are: * CardChanged * CardExpiryChanged * CloseAccount * ContactCardAccountHolder + [JsonPropertyName("realtimeAccountUpdaterStatus")] + public string? RealtimeAccountUpdaterStatus { get { return this._RealtimeAccountUpdaterStatusOption; } set { this._RealtimeAccountUpdaterStatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceiptFreeTextOption { get; private set; } + + /// + /// Message to be displayed on the terminal. + /// + /// Message to be displayed on the terminal. + [JsonPropertyName("receiptFreeText")] + public string? ReceiptFreeText { get { return this._ReceiptFreeTextOption; } set { this._ReceiptFreeTextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringContractTypesOption { get; private set; } + + /// + /// The recurring contract types applicable to the transaction. + /// + /// The recurring contract types applicable to the transaction. + [JsonPropertyName("recurring.contractTypes")] + public string? RecurringContractTypes { get { return this._RecurringContractTypesOption; } set { this._RecurringContractTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFirstPspReferenceOption { get; private set; } + + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + /// + /// The `pspReference`, of the first recurring payment that created the recurring detail. This functionality requires additional configuration on Adyen's end. To enable it, contact the Support Team. + [JsonPropertyName("recurring.firstPspReference")] + public string? RecurringFirstPspReference { get { return this._RecurringFirstPspReferenceOption; } set { this._RecurringFirstPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringRecurringDetailReferenceOption { get; private set; } + + /// + /// The reference that uniquely identifies the recurring transaction. + /// + /// The reference that uniquely identifies the recurring transaction. + [JsonPropertyName("recurring.recurringDetailReference")] + [Obsolete("Deprecated since Adyen Payout API v68. Use tokenization.storedPaymentMethodId instead.")] + public string? RecurringRecurringDetailReference { get { return this._RecurringRecurringDetailReferenceOption; } set { this._RecurringRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringShopperReferenceOption { get; private set; } + + /// + /// The provided reference of the shopper for a recurring transaction. + /// + /// The provided reference of the shopper for a recurring transaction. + [JsonPropertyName("recurring.shopperReference")] + [Obsolete("Deprecated since Adyen Payout API v68. Use tokenization.shopperReference instead.")] + public string? RecurringShopperReference { get { return this._RecurringShopperReferenceOption; } set { this._RecurringShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferredOption { get; private set; } + + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + /// + /// If the payment is referred, this field is set to true. This field is unavailable if the payment is referred and is usually not returned with ecommerce transactions. Example: true + [JsonPropertyName("referred")] + public string? Referred { get { return this._ReferredOption; } set { this._ReferredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonRawOption { get; private set; } + + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + /// + /// Raw refusal reason received from the acquirer, where available. Example: AUTHORISED + [JsonPropertyName("refusalReasonRaw")] + public string? RefusalReasonRaw { get { return this._RefusalReasonRawOption; } set { this._RefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestAmountOption { get; private set; } + + /// + /// The amount of the payment request. + /// + /// The amount of the payment request. + [JsonPropertyName("requestAmount")] + public string? RequestAmount { get { return this._RequestAmountOption; } set { this._RequestAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestCurrencyCodeOption { get; private set; } + + /// + /// The currency of the payment request. + /// + /// The currency of the payment request. + [JsonPropertyName("requestCurrencyCode")] + public string? RequestCurrencyCode { get { return this._RequestCurrencyCodeOption; } set { this._RequestCurrencyCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + /// + /// The shopper interaction type of the payment request. Example: Ecommerce + [JsonPropertyName("shopperInteraction")] + public string? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + /// + /// The shopperReference passed in the payment request. Example: AdyenTestShopperXX + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TerminalIdOption { get; private set; } + + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + /// + /// The terminal ID used in a point-of-sale payment. Example: 06022622 + [JsonPropertyName("terminalId")] + public string? TerminalId { get { return this._TerminalIdOption; } set { this._TerminalIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + /// + /// A Boolean value indicating whether 3DS authentication was completed on this payment. Example: true + [JsonPropertyName("threeDAuthenticated")] + public string? ThreeDAuthenticated { get { return this._ThreeDAuthenticatedOption; } set { this._ThreeDAuthenticatedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDAuthenticatedResponseOption { get; private set; } + + /// + /// The raw 3DS authentication result from the card issuer. Example: N + /// + /// The raw 3DS authentication result from the card issuer. Example: N + [JsonPropertyName("threeDAuthenticatedResponse")] + public string? ThreeDAuthenticatedResponse { get { return this._ThreeDAuthenticatedResponseOption; } set { this._ThreeDAuthenticatedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedOption { get; private set; } + + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + /// + /// A Boolean value indicating whether 3DS was offered for this payment. Example: true + [JsonPropertyName("threeDOffered")] + public string? ThreeDOffered { get { return this._ThreeDOfferedOption; } set { this._ThreeDOfferedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDOfferedResponseOption { get; private set; } + + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + /// + /// The raw enrollment result from the 3DS directory services of the card schemes. Example: Y + [JsonPropertyName("threeDOfferedResponse")] + public string? ThreeDOfferedResponse { get { return this._ThreeDOfferedResponseOption; } set { this._ThreeDOfferedResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSVersionOption { get; private set; } + + /// + /// The 3D Secure 2 version. + /// + /// The 3D Secure 2 version. + [JsonPropertyName("threeDSVersion")] + public string? ThreeDSVersion { get { return this._ThreeDSVersionOption; } set { this._ThreeDSVersionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationShopperReferenceOption { get; private set; } + + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + /// + /// The reference for the shopper that you sent when tokenizing the payment details. + [JsonPropertyName("tokenization.shopperReference")] + public string? TokenizationShopperReference { get { return this._TokenizationShopperReferenceOption; } set { this._TokenizationShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenizationStoredPaymentMethodIdOption { get; private set; } + + /// + /// The reference that uniquely identifies tokenized payment details. + /// + /// The reference that uniquely identifies tokenized payment details. + [JsonPropertyName("tokenization.storedPaymentMethodId")] + public string? TokenizationStoredPaymentMethodId { get { return this._TokenizationStoredPaymentMethodIdOption; } set { this._TokenizationStoredPaymentMethodIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VisaTransactionIdOption { get; private set; } + + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + /// + /// The `visaTransactionId`, has a fixed length of 15 numeric characters. > Contact Support Team to enable this field. + [JsonPropertyName("visaTransactionId")] + public string? VisaTransactionId { get { return this._VisaTransactionIdOption; } set { this._VisaTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _XidOption { get; private set; } + + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + /// + /// The 3DS transaction ID of the 3DS session sent in notifications. The value is Base64-encoded and is returned for transactions with directoryResponse 'N' or 'Y'. Example: ODgxNDc2MDg2MDExODk5MAAAAAA= + [JsonPropertyName("xid")] + public string? Xid { get { return this._XidOption; } set { this._XidOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataCommon {\n"); + sb.Append(" AcquirerAccountCode: ").Append(AcquirerAccountCode).Append("\n"); + sb.Append(" AcquirerCode: ").Append(AcquirerCode).Append("\n"); + sb.Append(" AcquirerReference: ").Append(AcquirerReference).Append("\n"); + sb.Append(" Alias: ").Append(Alias).Append("\n"); + sb.Append(" AliasType: ").Append(AliasType).Append("\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" AuthorisationMid: ").Append(AuthorisationMid).Append("\n"); + sb.Append(" AuthorisedAmountCurrency: ").Append(AuthorisedAmountCurrency).Append("\n"); + sb.Append(" AuthorisedAmountValue: ").Append(AuthorisedAmountValue).Append("\n"); + sb.Append(" AvsResult: ").Append(AvsResult).Append("\n"); + sb.Append(" AvsResultRaw: ").Append(AvsResultRaw).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CoBrandedWith: ").Append(CoBrandedWith).Append("\n"); + sb.Append(" CvcResult: ").Append(CvcResult).Append("\n"); + sb.Append(" CvcResultRaw: ").Append(CvcResultRaw).Append("\n"); + sb.Append(" DsTransID: ").Append(DsTransID).Append("\n"); + sb.Append(" Eci: ").Append(Eci).Append("\n"); + sb.Append(" ExpiryDate: ").Append(ExpiryDate).Append("\n"); + sb.Append(" ExtraCostsCurrency: ").Append(ExtraCostsCurrency).Append("\n"); + sb.Append(" ExtraCostsValue: ").Append(ExtraCostsValue).Append("\n"); + sb.Append(" FraudCheckItemNrFraudCheckname: ").Append(FraudCheckItemNrFraudCheckname).Append("\n"); + sb.Append(" FraudManualReview: ").Append(FraudManualReview).Append("\n"); + sb.Append(" FraudResultType: ").Append(FraudResultType).Append("\n"); + sb.Append(" FraudRiskLevel: ").Append(FraudRiskLevel).Append("\n"); + sb.Append(" FundingSource: ").Append(FundingSource).Append("\n"); + sb.Append(" FundsAvailability: ").Append(FundsAvailability).Append("\n"); + sb.Append(" InferredRefusalReason: ").Append(InferredRefusalReason).Append("\n"); + sb.Append(" IsCardCommercial: ").Append(IsCardCommercial).Append("\n"); + sb.Append(" IssuerCountry: ").Append(IssuerCountry).Append("\n"); + sb.Append(" LiabilityShift: ").Append(LiabilityShift).Append("\n"); + sb.Append(" McBankNetReferenceNumber: ").Append(McBankNetReferenceNumber).Append("\n"); + sb.Append(" MerchantAdviceCode: ").Append(MerchantAdviceCode).Append("\n"); + sb.Append(" MerchantReference: ").Append(MerchantReference).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" PaymentAccountReference: ").Append(PaymentAccountReference).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PaymentMethodVariant: ").Append(PaymentMethodVariant).Append("\n"); + sb.Append(" PayoutEligible: ").Append(PayoutEligible).Append("\n"); + sb.Append(" RealtimeAccountUpdaterStatus: ").Append(RealtimeAccountUpdaterStatus).Append("\n"); + sb.Append(" ReceiptFreeText: ").Append(ReceiptFreeText).Append("\n"); + sb.Append(" RecurringContractTypes: ").Append(RecurringContractTypes).Append("\n"); + sb.Append(" RecurringFirstPspReference: ").Append(RecurringFirstPspReference).Append("\n"); + sb.Append(" RecurringRecurringDetailReference: ").Append(RecurringRecurringDetailReference).Append("\n"); + sb.Append(" RecurringShopperReference: ").Append(RecurringShopperReference).Append("\n"); + sb.Append(" RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n"); + sb.Append(" Referred: ").Append(Referred).Append("\n"); + sb.Append(" RefusalReasonRaw: ").Append(RefusalReasonRaw).Append("\n"); + sb.Append(" RequestAmount: ").Append(RequestAmount).Append("\n"); + sb.Append(" RequestCurrencyCode: ").Append(RequestCurrencyCode).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" TerminalId: ").Append(TerminalId).Append("\n"); + sb.Append(" ThreeDAuthenticated: ").Append(ThreeDAuthenticated).Append("\n"); + sb.Append(" ThreeDAuthenticatedResponse: ").Append(ThreeDAuthenticatedResponse).Append("\n"); + sb.Append(" ThreeDOffered: ").Append(ThreeDOffered).Append("\n"); + sb.Append(" ThreeDOfferedResponse: ").Append(ThreeDOfferedResponse).Append("\n"); + sb.Append(" ThreeDSVersion: ").Append(ThreeDSVersion).Append("\n"); + sb.Append(" TokenizationShopperReference: ").Append(TokenizationShopperReference).Append("\n"); + sb.Append(" TokenizationStoreOperationType: ").Append(TokenizationStoreOperationType).Append("\n"); + sb.Append(" TokenizationStoredPaymentMethodId: ").Append(TokenizationStoredPaymentMethodId).Append("\n"); + sb.Append(" VisaTransactionId: ").Append(VisaTransactionId).Append("\n"); + sb.Append(" Xid: ").Append(Xid).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataCommonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataCommon Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerAccountCode = default; + Option acquirerCode = default; + Option acquirerReference = default; + Option alias = default; + Option aliasType = default; + Option authCode = default; + Option authorisationMid = default; + Option authorisedAmountCurrency = default; + Option authorisedAmountValue = default; + Option avsResult = default; + Option avsResultRaw = default; + Option bic = default; + Option coBrandedWith = default; + Option cvcResult = default; + Option cvcResultRaw = default; + Option dsTransID = default; + Option eci = default; + Option expiryDate = default; + Option extraCostsCurrency = default; + Option extraCostsValue = default; + Option fraudCheckItemNrFraudCheckname = default; + Option fraudManualReview = default; + Option fraudResultType = default; + Option fraudRiskLevel = default; + Option fundingSource = default; + Option fundsAvailability = default; + Option inferredRefusalReason = default; + Option isCardCommercial = default; + Option issuerCountry = default; + Option liabilityShift = default; + Option mcBankNetReferenceNumber = default; + Option merchantAdviceCode = default; + Option merchantReference = default; + Option networkTxReference = default; + Option ownerName = default; + Option paymentAccountReference = default; + Option paymentMethod = default; + Option paymentMethodVariant = default; + Option payoutEligible = default; + Option realtimeAccountUpdaterStatus = default; + Option receiptFreeText = default; + Option recurringContractTypes = default; + Option recurringFirstPspReference = default; + Option recurringRecurringDetailReference = default; + Option recurringShopperReference = default; + Option recurringProcessingModel = default; + Option referred = default; + Option refusalReasonRaw = default; + Option requestAmount = default; + Option requestCurrencyCode = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option terminalId = default; + Option threeDAuthenticated = default; + Option threeDAuthenticatedResponse = default; + Option threeDOffered = default; + Option threeDOfferedResponse = default; + Option threeDSVersion = default; + Option tokenizationShopperReference = default; + Option tokenizationStoreOperationType = default; + Option tokenizationStoredPaymentMethodId = default; + Option visaTransactionId = default; + Option xid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerAccountCode": + acquirerAccountCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerCode": + acquirerCode = new Option(utf8JsonReader.GetString()!); + break; + case "acquirerReference": + acquirerReference = new Option(utf8JsonReader.GetString()!); + break; + case "alias": + alias = new Option(utf8JsonReader.GetString()!); + break; + case "aliasType": + aliasType = new Option(utf8JsonReader.GetString()!); + break; + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "authorisationMid": + authorisationMid = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountCurrency": + authorisedAmountCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "authorisedAmountValue": + authorisedAmountValue = new Option(utf8JsonReader.GetString()!); + break; + case "avsResult": + avsResult = new Option(utf8JsonReader.GetString()!); + break; + case "avsResultRaw": + avsResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "coBrandedWith": + coBrandedWith = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResult": + cvcResult = new Option(utf8JsonReader.GetString()!); + break; + case "cvcResultRaw": + cvcResultRaw = new Option(utf8JsonReader.GetString()!); + break; + case "dsTransID": + dsTransID = new Option(utf8JsonReader.GetString()!); + break; + case "eci": + eci = new Option(utf8JsonReader.GetString()!); + break; + case "expiryDate": + expiryDate = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsCurrency": + extraCostsCurrency = new Option(utf8JsonReader.GetString()!); + break; + case "extraCostsValue": + extraCostsValue = new Option(utf8JsonReader.GetString()!); + break; + case "fraudCheck-[itemNr]-[FraudCheckname]": + fraudCheckItemNrFraudCheckname = new Option(utf8JsonReader.GetString()!); + break; + case "fraudManualReview": + fraudManualReview = new Option(utf8JsonReader.GetString()!); + break; + case "fraudResultType": + string? fraudResultTypeRawValue = utf8JsonReader.GetString(); + fraudResultType = new Option(ResponseAdditionalDataCommon.FraudResultTypeEnum.FromStringOrDefault(fraudResultTypeRawValue)); + break; + case "fraudRiskLevel": + string? fraudRiskLevelRawValue = utf8JsonReader.GetString(); + fraudRiskLevel = new Option(ResponseAdditionalDataCommon.FraudRiskLevelEnum.FromStringOrDefault(fraudRiskLevelRawValue)); + break; + case "fundingSource": + fundingSource = new Option(utf8JsonReader.GetString()!); + break; + case "fundsAvailability": + fundsAvailability = new Option(utf8JsonReader.GetString()!); + break; + case "inferredRefusalReason": + inferredRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "isCardCommercial": + isCardCommercial = new Option(utf8JsonReader.GetString()!); + break; + case "issuerCountry": + issuerCountry = new Option(utf8JsonReader.GetString()!); + break; + case "liabilityShift": + liabilityShift = new Option(utf8JsonReader.GetString()!); + break; + case "mcBankNetReferenceNumber": + mcBankNetReferenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAdviceCode": + merchantAdviceCode = new Option(utf8JsonReader.GetString()!); + break; + case "merchantReference": + merchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "paymentAccountReference": + paymentAccountReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodVariant": + paymentMethodVariant = new Option(utf8JsonReader.GetString()!); + break; + case "payoutEligible": + payoutEligible = new Option(utf8JsonReader.GetString()!); + break; + case "realtimeAccountUpdaterStatus": + realtimeAccountUpdaterStatus = new Option(utf8JsonReader.GetString()!); + break; + case "receiptFreeText": + receiptFreeText = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.contractTypes": + recurringContractTypes = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.firstPspReference": + recurringFirstPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.recurringDetailReference": + recurringRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring.shopperReference": + recurringShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringProcessingModel": + string? recurringProcessingModelRawValue = utf8JsonReader.GetString(); + recurringProcessingModel = new Option(ResponseAdditionalDataCommon.RecurringProcessingModelEnum.FromStringOrDefault(recurringProcessingModelRawValue)); + break; + case "referred": + referred = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReasonRaw": + refusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "requestAmount": + requestAmount = new Option(utf8JsonReader.GetString()!); + break; + case "requestCurrencyCode": + requestCurrencyCode = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + shopperInteraction = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "terminalId": + terminalId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticated": + threeDAuthenticated = new Option(utf8JsonReader.GetString()!); + break; + case "threeDAuthenticatedResponse": + threeDAuthenticatedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOffered": + threeDOffered = new Option(utf8JsonReader.GetString()!); + break; + case "threeDOfferedResponse": + threeDOfferedResponse = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSVersion": + threeDSVersion = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.shopperReference": + tokenizationShopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenization.store.operationType": + string? tokenizationStoreOperationTypeRawValue = utf8JsonReader.GetString(); + tokenizationStoreOperationType = new Option(ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.FromStringOrDefault(tokenizationStoreOperationTypeRawValue)); + break; + case "tokenization.storedPaymentMethodId": + tokenizationStoredPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "visaTransactionId": + visaTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "xid": + xid = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataCommon(acquirerAccountCode, acquirerCode, acquirerReference, alias, aliasType, authCode, authorisationMid, authorisedAmountCurrency, authorisedAmountValue, avsResult, avsResultRaw, bic, coBrandedWith, cvcResult, cvcResultRaw, dsTransID, eci, expiryDate, extraCostsCurrency, extraCostsValue, fraudCheckItemNrFraudCheckname, fraudManualReview, fraudResultType, fraudRiskLevel, fundingSource, fundsAvailability, inferredRefusalReason, isCardCommercial, issuerCountry, liabilityShift, mcBankNetReferenceNumber, merchantAdviceCode, merchantReference, networkTxReference, ownerName, paymentAccountReference, paymentMethod, paymentMethodVariant, payoutEligible, realtimeAccountUpdaterStatus, receiptFreeText, recurringContractTypes, recurringFirstPspReference, recurringRecurringDetailReference, recurringShopperReference, recurringProcessingModel, referred, refusalReasonRaw, requestAmount, requestCurrencyCode, shopperInteraction, shopperReference, terminalId, threeDAuthenticated, threeDAuthenticatedResponse, threeDOffered, threeDOfferedResponse, threeDSVersion, tokenizationShopperReference, tokenizationStoreOperationType, tokenizationStoredPaymentMethodId, visaTransactionId, xid); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataCommon, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataCommon responseAdditionalDataCommon, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataCommon._AcquirerAccountCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerAccountCode != null) + writer.WriteString("acquirerAccountCode", responseAdditionalDataCommon.AcquirerAccountCode); + + if (responseAdditionalDataCommon._AcquirerCodeOption.IsSet) + if (responseAdditionalDataCommon.AcquirerCode != null) + writer.WriteString("acquirerCode", responseAdditionalDataCommon.AcquirerCode); + + if (responseAdditionalDataCommon._AcquirerReferenceOption.IsSet) + if (responseAdditionalDataCommon.AcquirerReference != null) + writer.WriteString("acquirerReference", responseAdditionalDataCommon.AcquirerReference); + + if (responseAdditionalDataCommon._AliasOption.IsSet) + if (responseAdditionalDataCommon.Alias != null) + writer.WriteString("alias", responseAdditionalDataCommon.Alias); + + if (responseAdditionalDataCommon._AliasTypeOption.IsSet) + if (responseAdditionalDataCommon.AliasType != null) + writer.WriteString("aliasType", responseAdditionalDataCommon.AliasType); + + if (responseAdditionalDataCommon._AuthCodeOption.IsSet) + if (responseAdditionalDataCommon.AuthCode != null) + writer.WriteString("authCode", responseAdditionalDataCommon.AuthCode); + + if (responseAdditionalDataCommon._AuthorisationMidOption.IsSet) + if (responseAdditionalDataCommon.AuthorisationMid != null) + writer.WriteString("authorisationMid", responseAdditionalDataCommon.AuthorisationMid); + + if (responseAdditionalDataCommon._AuthorisedAmountCurrencyOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountCurrency != null) + writer.WriteString("authorisedAmountCurrency", responseAdditionalDataCommon.AuthorisedAmountCurrency); + + if (responseAdditionalDataCommon._AuthorisedAmountValueOption.IsSet) + if (responseAdditionalDataCommon.AuthorisedAmountValue != null) + writer.WriteString("authorisedAmountValue", responseAdditionalDataCommon.AuthorisedAmountValue); + + if (responseAdditionalDataCommon._AvsResultOption.IsSet) + if (responseAdditionalDataCommon.AvsResult != null) + writer.WriteString("avsResult", responseAdditionalDataCommon.AvsResult); + + if (responseAdditionalDataCommon._AvsResultRawOption.IsSet) + if (responseAdditionalDataCommon.AvsResultRaw != null) + writer.WriteString("avsResultRaw", responseAdditionalDataCommon.AvsResultRaw); + + if (responseAdditionalDataCommon._BicOption.IsSet) + if (responseAdditionalDataCommon.Bic != null) + writer.WriteString("bic", responseAdditionalDataCommon.Bic); + + if (responseAdditionalDataCommon._CoBrandedWithOption.IsSet) + if (responseAdditionalDataCommon.CoBrandedWith != null) + writer.WriteString("coBrandedWith", responseAdditionalDataCommon.CoBrandedWith); + + if (responseAdditionalDataCommon._CvcResultOption.IsSet) + if (responseAdditionalDataCommon.CvcResult != null) + writer.WriteString("cvcResult", responseAdditionalDataCommon.CvcResult); + + if (responseAdditionalDataCommon._CvcResultRawOption.IsSet) + if (responseAdditionalDataCommon.CvcResultRaw != null) + writer.WriteString("cvcResultRaw", responseAdditionalDataCommon.CvcResultRaw); + + if (responseAdditionalDataCommon._DsTransIDOption.IsSet) + if (responseAdditionalDataCommon.DsTransID != null) + writer.WriteString("dsTransID", responseAdditionalDataCommon.DsTransID); + + if (responseAdditionalDataCommon._EciOption.IsSet) + if (responseAdditionalDataCommon.Eci != null) + writer.WriteString("eci", responseAdditionalDataCommon.Eci); + + if (responseAdditionalDataCommon._ExpiryDateOption.IsSet) + if (responseAdditionalDataCommon.ExpiryDate != null) + writer.WriteString("expiryDate", responseAdditionalDataCommon.ExpiryDate); + + if (responseAdditionalDataCommon._ExtraCostsCurrencyOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsCurrency != null) + writer.WriteString("extraCostsCurrency", responseAdditionalDataCommon.ExtraCostsCurrency); + + if (responseAdditionalDataCommon._ExtraCostsValueOption.IsSet) + if (responseAdditionalDataCommon.ExtraCostsValue != null) + writer.WriteString("extraCostsValue", responseAdditionalDataCommon.ExtraCostsValue); + + if (responseAdditionalDataCommon._FraudCheckItemNrFraudChecknameOption.IsSet) + if (responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname != null) + writer.WriteString("fraudCheck-[itemNr]-[FraudCheckname]", responseAdditionalDataCommon.FraudCheckItemNrFraudCheckname); + + if (responseAdditionalDataCommon._FraudManualReviewOption.IsSet) + if (responseAdditionalDataCommon.FraudManualReview != null) + writer.WriteString("fraudManualReview", responseAdditionalDataCommon.FraudManualReview); + + if (responseAdditionalDataCommon._FraudResultTypeOption.IsSet && responseAdditionalDataCommon.FraudResultType != null) + { + string? fraudResultTypeRawValue = ResponseAdditionalDataCommon.FraudResultTypeEnum.ToJsonValue(responseAdditionalDataCommon._FraudResultTypeOption.Value!.Value); + writer.WriteString("fraudResultType", fraudResultTypeRawValue); + } + + if (responseAdditionalDataCommon._FraudRiskLevelOption.IsSet && responseAdditionalDataCommon.FraudRiskLevel != null) + { + string? fraudRiskLevelRawValue = ResponseAdditionalDataCommon.FraudRiskLevelEnum.ToJsonValue(responseAdditionalDataCommon._FraudRiskLevelOption.Value!.Value); + writer.WriteString("fraudRiskLevel", fraudRiskLevelRawValue); + } + + if (responseAdditionalDataCommon._FundingSourceOption.IsSet) + if (responseAdditionalDataCommon.FundingSource != null) + writer.WriteString("fundingSource", responseAdditionalDataCommon.FundingSource); + + if (responseAdditionalDataCommon._FundsAvailabilityOption.IsSet) + if (responseAdditionalDataCommon.FundsAvailability != null) + writer.WriteString("fundsAvailability", responseAdditionalDataCommon.FundsAvailability); + + if (responseAdditionalDataCommon._InferredRefusalReasonOption.IsSet) + if (responseAdditionalDataCommon.InferredRefusalReason != null) + writer.WriteString("inferredRefusalReason", responseAdditionalDataCommon.InferredRefusalReason); + + if (responseAdditionalDataCommon._IsCardCommercialOption.IsSet) + if (responseAdditionalDataCommon.IsCardCommercial != null) + writer.WriteString("isCardCommercial", responseAdditionalDataCommon.IsCardCommercial); + + if (responseAdditionalDataCommon._IssuerCountryOption.IsSet) + if (responseAdditionalDataCommon.IssuerCountry != null) + writer.WriteString("issuerCountry", responseAdditionalDataCommon.IssuerCountry); + + if (responseAdditionalDataCommon._LiabilityShiftOption.IsSet) + if (responseAdditionalDataCommon.LiabilityShift != null) + writer.WriteString("liabilityShift", responseAdditionalDataCommon.LiabilityShift); + + if (responseAdditionalDataCommon._McBankNetReferenceNumberOption.IsSet) + if (responseAdditionalDataCommon.McBankNetReferenceNumber != null) + writer.WriteString("mcBankNetReferenceNumber", responseAdditionalDataCommon.McBankNetReferenceNumber); + + if (responseAdditionalDataCommon._MerchantAdviceCodeOption.IsSet) + if (responseAdditionalDataCommon.MerchantAdviceCode != null) + writer.WriteString("merchantAdviceCode", responseAdditionalDataCommon.MerchantAdviceCode); + + if (responseAdditionalDataCommon._MerchantReferenceOption.IsSet) + if (responseAdditionalDataCommon.MerchantReference != null) + writer.WriteString("merchantReference", responseAdditionalDataCommon.MerchantReference); + + if (responseAdditionalDataCommon._NetworkTxReferenceOption.IsSet) + if (responseAdditionalDataCommon.NetworkTxReference != null) + writer.WriteString("networkTxReference", responseAdditionalDataCommon.NetworkTxReference); + + if (responseAdditionalDataCommon._OwnerNameOption.IsSet) + if (responseAdditionalDataCommon.OwnerName != null) + writer.WriteString("ownerName", responseAdditionalDataCommon.OwnerName); + + if (responseAdditionalDataCommon._PaymentAccountReferenceOption.IsSet) + if (responseAdditionalDataCommon.PaymentAccountReference != null) + writer.WriteString("paymentAccountReference", responseAdditionalDataCommon.PaymentAccountReference); + + if (responseAdditionalDataCommon._PaymentMethodOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethod != null) + writer.WriteString("paymentMethod", responseAdditionalDataCommon.PaymentMethod); + + if (responseAdditionalDataCommon._PaymentMethodVariantOption.IsSet) + if (responseAdditionalDataCommon.PaymentMethodVariant != null) + writer.WriteString("paymentMethodVariant", responseAdditionalDataCommon.PaymentMethodVariant); + + if (responseAdditionalDataCommon._PayoutEligibleOption.IsSet) + if (responseAdditionalDataCommon.PayoutEligible != null) + writer.WriteString("payoutEligible", responseAdditionalDataCommon.PayoutEligible); + + if (responseAdditionalDataCommon._RealtimeAccountUpdaterStatusOption.IsSet) + if (responseAdditionalDataCommon.RealtimeAccountUpdaterStatus != null) + writer.WriteString("realtimeAccountUpdaterStatus", responseAdditionalDataCommon.RealtimeAccountUpdaterStatus); + + if (responseAdditionalDataCommon._ReceiptFreeTextOption.IsSet) + if (responseAdditionalDataCommon.ReceiptFreeText != null) + writer.WriteString("receiptFreeText", responseAdditionalDataCommon.ReceiptFreeText); + + if (responseAdditionalDataCommon._RecurringContractTypesOption.IsSet) + if (responseAdditionalDataCommon.RecurringContractTypes != null) + writer.WriteString("recurring.contractTypes", responseAdditionalDataCommon.RecurringContractTypes); + + if (responseAdditionalDataCommon._RecurringFirstPspReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringFirstPspReference != null) + writer.WriteString("recurring.firstPspReference", responseAdditionalDataCommon.RecurringFirstPspReference); + + if (responseAdditionalDataCommon._RecurringRecurringDetailReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringRecurringDetailReference != null) + writer.WriteString("recurring.recurringDetailReference", responseAdditionalDataCommon.RecurringRecurringDetailReference); + + if (responseAdditionalDataCommon._RecurringShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.RecurringShopperReference != null) + writer.WriteString("recurring.shopperReference", responseAdditionalDataCommon.RecurringShopperReference); + + if (responseAdditionalDataCommon._RecurringProcessingModelOption.IsSet && responseAdditionalDataCommon.RecurringProcessingModel != null) + { + string? recurringProcessingModelRawValue = ResponseAdditionalDataCommon.RecurringProcessingModelEnum.ToJsonValue(responseAdditionalDataCommon._RecurringProcessingModelOption.Value!.Value); + writer.WriteString("recurringProcessingModel", recurringProcessingModelRawValue); + } + + if (responseAdditionalDataCommon._ReferredOption.IsSet) + if (responseAdditionalDataCommon.Referred != null) + writer.WriteString("referred", responseAdditionalDataCommon.Referred); + + if (responseAdditionalDataCommon._RefusalReasonRawOption.IsSet) + if (responseAdditionalDataCommon.RefusalReasonRaw != null) + writer.WriteString("refusalReasonRaw", responseAdditionalDataCommon.RefusalReasonRaw); + + if (responseAdditionalDataCommon._RequestAmountOption.IsSet) + if (responseAdditionalDataCommon.RequestAmount != null) + writer.WriteString("requestAmount", responseAdditionalDataCommon.RequestAmount); + + if (responseAdditionalDataCommon._RequestCurrencyCodeOption.IsSet) + if (responseAdditionalDataCommon.RequestCurrencyCode != null) + writer.WriteString("requestCurrencyCode", responseAdditionalDataCommon.RequestCurrencyCode); + + if (responseAdditionalDataCommon._ShopperInteractionOption.IsSet) + if (responseAdditionalDataCommon.ShopperInteraction != null) + writer.WriteString("shopperInteraction", responseAdditionalDataCommon.ShopperInteraction); + + if (responseAdditionalDataCommon._ShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.ShopperReference != null) + writer.WriteString("shopperReference", responseAdditionalDataCommon.ShopperReference); + + if (responseAdditionalDataCommon._TerminalIdOption.IsSet) + if (responseAdditionalDataCommon.TerminalId != null) + writer.WriteString("terminalId", responseAdditionalDataCommon.TerminalId); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticated != null) + writer.WriteString("threeDAuthenticated", responseAdditionalDataCommon.ThreeDAuthenticated); + + if (responseAdditionalDataCommon._ThreeDAuthenticatedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDAuthenticatedResponse != null) + writer.WriteString("threeDAuthenticatedResponse", responseAdditionalDataCommon.ThreeDAuthenticatedResponse); + + if (responseAdditionalDataCommon._ThreeDOfferedOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOffered != null) + writer.WriteString("threeDOffered", responseAdditionalDataCommon.ThreeDOffered); + + if (responseAdditionalDataCommon._ThreeDOfferedResponseOption.IsSet) + if (responseAdditionalDataCommon.ThreeDOfferedResponse != null) + writer.WriteString("threeDOfferedResponse", responseAdditionalDataCommon.ThreeDOfferedResponse); + + if (responseAdditionalDataCommon._ThreeDSVersionOption.IsSet) + if (responseAdditionalDataCommon.ThreeDSVersion != null) + writer.WriteString("threeDSVersion", responseAdditionalDataCommon.ThreeDSVersion); + + if (responseAdditionalDataCommon._TokenizationShopperReferenceOption.IsSet) + if (responseAdditionalDataCommon.TokenizationShopperReference != null) + writer.WriteString("tokenization.shopperReference", responseAdditionalDataCommon.TokenizationShopperReference); + + if (responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.IsSet && responseAdditionalDataCommon.TokenizationStoreOperationType != null) + { + string? tokenizationStoreOperationTypeRawValue = ResponseAdditionalDataCommon.TokenizationStoreOperationTypeEnum.ToJsonValue(responseAdditionalDataCommon._TokenizationStoreOperationTypeOption.Value!.Value); + writer.WriteString("tokenization.store.operationType", tokenizationStoreOperationTypeRawValue); + } + + if (responseAdditionalDataCommon._TokenizationStoredPaymentMethodIdOption.IsSet) + if (responseAdditionalDataCommon.TokenizationStoredPaymentMethodId != null) + writer.WriteString("tokenization.storedPaymentMethodId", responseAdditionalDataCommon.TokenizationStoredPaymentMethodId); + + if (responseAdditionalDataCommon._VisaTransactionIdOption.IsSet) + if (responseAdditionalDataCommon.VisaTransactionId != null) + writer.WriteString("visaTransactionId", responseAdditionalDataCommon.VisaTransactionId); + + if (responseAdditionalDataCommon._XidOption.IsSet) + if (responseAdditionalDataCommon.Xid != null) + writer.WriteString("xid", responseAdditionalDataCommon.Xid); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataDomesticError.cs b/Adyen/Payout/Models/ResponseAdditionalDataDomesticError.cs new file mode 100644 index 000000000..045607d2c --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataDomesticError.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataDomesticError. + /// + public partial class ResponseAdditionalDataDomesticError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonConstructor] + public ResponseAdditionalDataDomesticError(Option domesticRefusalReasonRaw = default, Option domesticShopperAdvice = default) + { + _DomesticRefusalReasonRawOption = domesticRefusalReasonRaw; + _DomesticShopperAdviceOption = domesticShopperAdvice; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataDomesticError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticRefusalReasonRawOption { get; private set; } + + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + /// + /// The reason the transaction was declined, given by the local issuer. Currently available for merchants in Japan. + [JsonPropertyName("domesticRefusalReasonRaw")] + public string? DomesticRefusalReasonRaw { get { return this._DomesticRefusalReasonRawOption; } set { this._DomesticRefusalReasonRawOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DomesticShopperAdviceOption { get; private set; } + + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + /// + /// The action the shopper should take, in a local language. Currently available in Japanese, for merchants in Japan. + [JsonPropertyName("domesticShopperAdvice")] + public string? DomesticShopperAdvice { get { return this._DomesticShopperAdviceOption; } set { this._DomesticShopperAdviceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataDomesticError {\n"); + sb.Append(" DomesticRefusalReasonRaw: ").Append(DomesticRefusalReasonRaw).Append("\n"); + sb.Append(" DomesticShopperAdvice: ").Append(DomesticShopperAdvice).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataDomesticErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataDomesticError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option domesticRefusalReasonRaw = default; + Option domesticShopperAdvice = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "domesticRefusalReasonRaw": + domesticRefusalReasonRaw = new Option(utf8JsonReader.GetString()!); + break; + case "domesticShopperAdvice": + domesticShopperAdvice = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataDomesticError(domesticRefusalReasonRaw, domesticShopperAdvice); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataDomesticError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataDomesticError responseAdditionalDataDomesticError, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataDomesticError._DomesticRefusalReasonRawOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticRefusalReasonRaw != null) + writer.WriteString("domesticRefusalReasonRaw", responseAdditionalDataDomesticError.DomesticRefusalReasonRaw); + + if (responseAdditionalDataDomesticError._DomesticShopperAdviceOption.IsSet) + if (responseAdditionalDataDomesticError.DomesticShopperAdvice != null) + writer.WriteString("domesticShopperAdvice", responseAdditionalDataDomesticError.DomesticShopperAdvice); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataInstallments.cs b/Adyen/Payout/Models/ResponseAdditionalDataInstallments.cs new file mode 100644 index 000000000..281978d79 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataInstallments.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataInstallments. + /// + public partial class ResponseAdditionalDataInstallments : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// Annual interest rate. + /// First Installment Amount in minor units. + /// Installment fee amount in minor units. + /// Interest rate for the installment period. + /// Maximum number of installments possible for this payment. + /// Minimum number of installments possible for this payment. + /// Total number of installments possible for this payment. + /// Subsequent Installment Amount in minor units. + /// Total amount in minor units. + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonConstructor] + public ResponseAdditionalDataInstallments(Option installmentPaymentDataInstallmentType = default, Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default, Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default, Option installmentPaymentDataOptionItemNrInstallmentFee = default, Option installmentPaymentDataOptionItemNrInterestRate = default, Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrNumberOfInstallments = default, Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default, Option installmentPaymentDataOptionItemNrTotalAmountDue = default, Option installmentPaymentDataPaymentOptions = default, Option installmentsValue = default) + { + _InstallmentPaymentDataInstallmentTypeOption = installmentPaymentDataInstallmentType; + _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = installmentPaymentDataOptionItemNrAnnualPercentageRate; + _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = installmentPaymentDataOptionItemNrFirstInstallmentAmount; + _InstallmentPaymentDataOptionItemNrInstallmentFeeOption = installmentPaymentDataOptionItemNrInstallmentFee; + _InstallmentPaymentDataOptionItemNrInterestRateOption = installmentPaymentDataOptionItemNrInterestRate; + _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMaximumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrMinimumNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = installmentPaymentDataOptionItemNrNumberOfInstallments; + _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = installmentPaymentDataOptionItemNrSubsequentInstallmentAmount; + _InstallmentPaymentDataOptionItemNrTotalAmountDueOption = installmentPaymentDataOptionItemNrTotalAmountDue; + _InstallmentPaymentDataPaymentOptionsOption = installmentPaymentDataPaymentOptions; + _InstallmentsValueOption = installmentsValue; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataInstallments() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataInstallmentTypeOption { get; private set; } + + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + /// + /// Type of installment. The value of `installmentType` should be **IssuerFinanced**. + [JsonPropertyName("installmentPaymentData.installmentType")] + public string? InstallmentPaymentDataInstallmentType { get { return this._InstallmentPaymentDataInstallmentTypeOption; } set { this._InstallmentPaymentDataInstallmentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption { get; private set; } + + /// + /// Annual interest rate. + /// + /// Annual interest rate. + [JsonPropertyName("installmentPaymentData.option[itemNr].annualPercentageRate")] + public string? InstallmentPaymentDataOptionItemNrAnnualPercentageRate { get { return this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption; } set { this._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption { get; private set; } + + /// + /// First Installment Amount in minor units. + /// + /// First Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].firstInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrFirstInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInstallmentFeeOption { get; private set; } + + /// + /// Installment fee amount in minor units. + /// + /// Installment fee amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].installmentFee")] + public string? InstallmentPaymentDataOptionItemNrInstallmentFee { get { return this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption; } set { this._InstallmentPaymentDataOptionItemNrInstallmentFeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrInterestRateOption { get; private set; } + + /// + /// Interest rate for the installment period. + /// + /// Interest rate for the installment period. + [JsonPropertyName("installmentPaymentData.option[itemNr].interestRate")] + public string? InstallmentPaymentDataOptionItemNrInterestRate { get { return this._InstallmentPaymentDataOptionItemNrInterestRateOption; } set { this._InstallmentPaymentDataOptionItemNrInterestRateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption { get; private set; } + + /// + /// Maximum number of installments possible for this payment. + /// + /// Maximum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].maximumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption { get; private set; } + + /// + /// Minimum number of installments possible for this payment. + /// + /// Minimum number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].minimumNumberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption { get; private set; } + + /// + /// Total number of installments possible for this payment. + /// + /// Total number of installments possible for this payment. + [JsonPropertyName("installmentPaymentData.option[itemNr].numberOfInstallments")] + public string? InstallmentPaymentDataOptionItemNrNumberOfInstallments { get { return this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption; } set { this._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption { get; private set; } + + /// + /// Subsequent Installment Amount in minor units. + /// + /// Subsequent Installment Amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].subsequentInstallmentAmount")] + public string? InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount { get { return this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption; } set { this._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataOptionItemNrTotalAmountDueOption { get; private set; } + + /// + /// Total amount in minor units. + /// + /// Total amount in minor units. + [JsonPropertyName("installmentPaymentData.option[itemNr].totalAmountDue")] + public string? InstallmentPaymentDataOptionItemNrTotalAmountDue { get { return this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption; } set { this._InstallmentPaymentDataOptionItemNrTotalAmountDueOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentPaymentDataPaymentOptionsOption { get; private set; } + + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + /// + /// Possible values: * PayInInstallmentsOnly * PayInFullOnly * PayInFullOrInstallments + [JsonPropertyName("installmentPaymentData.paymentOptions")] + public string? InstallmentPaymentDataPaymentOptions { get { return this._InstallmentPaymentDataPaymentOptionsOption; } set { this._InstallmentPaymentDataPaymentOptionsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallmentsValueOption { get; private set; } + + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + /// + /// The number of installments that the payment amount should be charged with. Example: 5 > Only relevant for card payments in countries that support installments. + [JsonPropertyName("installments.value")] + public string? InstallmentsValue { get { return this._InstallmentsValueOption; } set { this._InstallmentsValueOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataInstallments {\n"); + sb.Append(" InstallmentPaymentDataInstallmentType: ").Append(InstallmentPaymentDataInstallmentType).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrAnnualPercentageRate: ").Append(InstallmentPaymentDataOptionItemNrAnnualPercentageRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrFirstInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrFirstInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInstallmentFee: ").Append(InstallmentPaymentDataOptionItemNrInstallmentFee).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrInterestRate: ").Append(InstallmentPaymentDataOptionItemNrInterestRate).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrNumberOfInstallments: ").Append(InstallmentPaymentDataOptionItemNrNumberOfInstallments).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount: ").Append(InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount).Append("\n"); + sb.Append(" InstallmentPaymentDataOptionItemNrTotalAmountDue: ").Append(InstallmentPaymentDataOptionItemNrTotalAmountDue).Append("\n"); + sb.Append(" InstallmentPaymentDataPaymentOptions: ").Append(InstallmentPaymentDataPaymentOptions).Append("\n"); + sb.Append(" InstallmentsValue: ").Append(InstallmentsValue).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataInstallmentsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataInstallments Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option installmentPaymentDataInstallmentType = default; + Option installmentPaymentDataOptionItemNrAnnualPercentageRate = default; + Option installmentPaymentDataOptionItemNrFirstInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrInstallmentFee = default; + Option installmentPaymentDataOptionItemNrInterestRate = default; + Option installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrNumberOfInstallments = default; + Option installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = default; + Option installmentPaymentDataOptionItemNrTotalAmountDue = default; + Option installmentPaymentDataPaymentOptions = default; + Option installmentsValue = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "installmentPaymentData.installmentType": + installmentPaymentDataInstallmentType = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].annualPercentageRate": + installmentPaymentDataOptionItemNrAnnualPercentageRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].firstInstallmentAmount": + installmentPaymentDataOptionItemNrFirstInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].installmentFee": + installmentPaymentDataOptionItemNrInstallmentFee = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].interestRate": + installmentPaymentDataOptionItemNrInterestRate = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].maximumNumberOfInstallments": + installmentPaymentDataOptionItemNrMaximumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].minimumNumberOfInstallments": + installmentPaymentDataOptionItemNrMinimumNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].numberOfInstallments": + installmentPaymentDataOptionItemNrNumberOfInstallments = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].subsequentInstallmentAmount": + installmentPaymentDataOptionItemNrSubsequentInstallmentAmount = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.option[itemNr].totalAmountDue": + installmentPaymentDataOptionItemNrTotalAmountDue = new Option(utf8JsonReader.GetString()!); + break; + case "installmentPaymentData.paymentOptions": + installmentPaymentDataPaymentOptions = new Option(utf8JsonReader.GetString()!); + break; + case "installments.value": + installmentsValue = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataInstallments(installmentPaymentDataInstallmentType, installmentPaymentDataOptionItemNrAnnualPercentageRate, installmentPaymentDataOptionItemNrFirstInstallmentAmount, installmentPaymentDataOptionItemNrInstallmentFee, installmentPaymentDataOptionItemNrInterestRate, installmentPaymentDataOptionItemNrMaximumNumberOfInstallments, installmentPaymentDataOptionItemNrMinimumNumberOfInstallments, installmentPaymentDataOptionItemNrNumberOfInstallments, installmentPaymentDataOptionItemNrSubsequentInstallmentAmount, installmentPaymentDataOptionItemNrTotalAmountDue, installmentPaymentDataPaymentOptions, installmentsValue); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataInstallments, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataInstallments responseAdditionalDataInstallments, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataInstallments._InstallmentPaymentDataInstallmentTypeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType != null) + writer.WriteString("installmentPaymentData.installmentType", responseAdditionalDataInstallments.InstallmentPaymentDataInstallmentType); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrAnnualPercentageRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].annualPercentageRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrAnnualPercentageRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrFirstInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].firstInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrFirstInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInstallmentFeeOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee != null) + writer.WriteString("installmentPaymentData.option[itemNr].installmentFee", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInstallmentFee); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrInterestRateOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate != null) + writer.WriteString("installmentPaymentData.option[itemNr].interestRate", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrInterestRate); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].maximumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMaximumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].minimumNumberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrMinimumNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrNumberOfInstallmentsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments != null) + writer.WriteString("installmentPaymentData.option[itemNr].numberOfInstallments", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrNumberOfInstallments); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmountOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount != null) + writer.WriteString("installmentPaymentData.option[itemNr].subsequentInstallmentAmount", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrSubsequentInstallmentAmount); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataOptionItemNrTotalAmountDueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue != null) + writer.WriteString("installmentPaymentData.option[itemNr].totalAmountDue", responseAdditionalDataInstallments.InstallmentPaymentDataOptionItemNrTotalAmountDue); + + if (responseAdditionalDataInstallments._InstallmentPaymentDataPaymentOptionsOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions != null) + writer.WriteString("installmentPaymentData.paymentOptions", responseAdditionalDataInstallments.InstallmentPaymentDataPaymentOptions); + + if (responseAdditionalDataInstallments._InstallmentsValueOption.IsSet) + if (responseAdditionalDataInstallments.InstallmentsValue != null) + writer.WriteString("installments.value", responseAdditionalDataInstallments.InstallmentsValue); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataNetworkTokens.cs b/Adyen/Payout/Models/ResponseAdditionalDataNetworkTokens.cs new file mode 100644 index 000000000..a6ccb102a --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataNetworkTokens.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataNetworkTokens. + /// + public partial class ResponseAdditionalDataNetworkTokens : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether a network token is available for the specified card. + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// The last four digits of a network token. + [JsonConstructor] + public ResponseAdditionalDataNetworkTokens(Option networkTokenAvailable = default, Option networkTokenBin = default, Option networkTokenTokenSummary = default) + { + _NetworkTokenAvailableOption = networkTokenAvailable; + _NetworkTokenBinOption = networkTokenBin; + _NetworkTokenTokenSummaryOption = networkTokenTokenSummary; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataNetworkTokens() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenAvailableOption { get; private set; } + + /// + /// Indicates whether a network token is available for the specified card. + /// + /// Indicates whether a network token is available for the specified card. + [JsonPropertyName("networkToken.available")] + public string? NetworkTokenAvailable { get { return this._NetworkTokenAvailableOption; } set { this._NetworkTokenAvailableOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenBinOption { get; private set; } + + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + /// + /// The Bank Identification Number of a tokenized card, which is the first six digits of a card number. + [JsonPropertyName("networkToken.bin")] + public string? NetworkTokenBin { get { return this._NetworkTokenBinOption; } set { this._NetworkTokenBinOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTokenTokenSummaryOption { get; private set; } + + /// + /// The last four digits of a network token. + /// + /// The last four digits of a network token. + [JsonPropertyName("networkToken.tokenSummary")] + public string? NetworkTokenTokenSummary { get { return this._NetworkTokenTokenSummaryOption; } set { this._NetworkTokenTokenSummaryOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataNetworkTokens {\n"); + sb.Append(" NetworkTokenAvailable: ").Append(NetworkTokenAvailable).Append("\n"); + sb.Append(" NetworkTokenBin: ").Append(NetworkTokenBin).Append("\n"); + sb.Append(" NetworkTokenTokenSummary: ").Append(NetworkTokenTokenSummary).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataNetworkTokensJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataNetworkTokens Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option networkTokenAvailable = default; + Option networkTokenBin = default; + Option networkTokenTokenSummary = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "networkToken.available": + networkTokenAvailable = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.bin": + networkTokenBin = new Option(utf8JsonReader.GetString()!); + break; + case "networkToken.tokenSummary": + networkTokenTokenSummary = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataNetworkTokens(networkTokenAvailable, networkTokenBin, networkTokenTokenSummary); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataNetworkTokens, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataNetworkTokens responseAdditionalDataNetworkTokens, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataNetworkTokens._NetworkTokenAvailableOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenAvailable != null) + writer.WriteString("networkToken.available", responseAdditionalDataNetworkTokens.NetworkTokenAvailable); + + if (responseAdditionalDataNetworkTokens._NetworkTokenBinOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenBin != null) + writer.WriteString("networkToken.bin", responseAdditionalDataNetworkTokens.NetworkTokenBin); + + if (responseAdditionalDataNetworkTokens._NetworkTokenTokenSummaryOption.IsSet) + if (responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary != null) + writer.WriteString("networkToken.tokenSummary", responseAdditionalDataNetworkTokens.NetworkTokenTokenSummary); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataOpi.cs b/Adyen/Payout/Models/ResponseAdditionalDataOpi.cs new file mode 100644 index 000000000..08c35484c --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataOpi.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataOpi. + /// + public partial class ResponseAdditionalDataOpi : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonConstructor] + public ResponseAdditionalDataOpi(Option opiTransToken = default) + { + _OpiTransTokenOption = opiTransToken; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataOpi() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OpiTransTokenOption { get; private set; } + + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + /// + /// Returned in the response if you included `opi.includeTransToken: true` in an ecommerce payment request. This contains an Oracle Payment Interface token that you can store in your Oracle Opera database to identify tokenized ecommerce transactions. For more information and required settings, see [Oracle Opera](https://docs.adyen.com/plugins/oracle-opera#opi-token-ecommerce). + [JsonPropertyName("opi.transToken")] + public string? OpiTransToken { get { return this._OpiTransTokenOption; } set { this._OpiTransTokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataOpi {\n"); + sb.Append(" OpiTransToken: ").Append(OpiTransToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataOpiJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataOpi Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option opiTransToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "opi.transToken": + opiTransToken = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataOpi(opiTransToken); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataOpi, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataOpi responseAdditionalDataOpi, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataOpi._OpiTransTokenOption.IsSet) + if (responseAdditionalDataOpi.OpiTransToken != null) + writer.WriteString("opi.transToken", responseAdditionalDataOpi.OpiTransToken); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataSepa.cs b/Adyen/Payout/Models/ResponseAdditionalDataSepa.cs new file mode 100644 index 000000000..1cf05ef25 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataSepa.cs @@ -0,0 +1,227 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataSepa. + /// + public partial class ResponseAdditionalDataSepa : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// Its value corresponds to the pspReference value of the transaction. + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonConstructor] + public ResponseAdditionalDataSepa(Option sepadirectdebitDateOfSignature = default, Option sepadirectdebitMandateId = default, Option sepadirectdebitSequenceType = default) + { + _SepadirectdebitDateOfSignatureOption = sepadirectdebitDateOfSignature; + _SepadirectdebitMandateIdOption = sepadirectdebitMandateId; + _SepadirectdebitSequenceTypeOption = sepadirectdebitSequenceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSepa() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitDateOfSignatureOption { get; private set; } + + /// + /// The transaction signature date. Format: yyyy-MM-dd + /// + /// The transaction signature date. Format: yyyy-MM-dd + [JsonPropertyName("sepadirectdebit.dateOfSignature")] + public string? SepadirectdebitDateOfSignature { get { return this._SepadirectdebitDateOfSignatureOption; } set { this._SepadirectdebitDateOfSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitMandateIdOption { get; private set; } + + /// + /// Its value corresponds to the pspReference value of the transaction. + /// + /// Its value corresponds to the pspReference value of the transaction. + [JsonPropertyName("sepadirectdebit.mandateId")] + public string? SepadirectdebitMandateId { get { return this._SepadirectdebitMandateIdOption; } set { this._SepadirectdebitMandateIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SepadirectdebitSequenceTypeOption { get; private set; } + + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + /// + /// This field can take one of the following values: * OneOff: (OOFF) Direct debit instruction to initiate exactly one direct debit transaction. * First: (FRST) Initial/first collection in a series of direct debit instructions. * Recurring: (RCUR) Direct debit instruction to carry out regular direct debit transactions initiated by the creditor. * Final: (FNAL) Last/final collection in a series of direct debit instructions. Example: OOFF + [JsonPropertyName("sepadirectdebit.sequenceType")] + public string? SepadirectdebitSequenceType { get { return this._SepadirectdebitSequenceTypeOption; } set { this._SepadirectdebitSequenceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSepa {\n"); + sb.Append(" SepadirectdebitDateOfSignature: ").Append(SepadirectdebitDateOfSignature).Append("\n"); + sb.Append(" SepadirectdebitMandateId: ").Append(SepadirectdebitMandateId).Append("\n"); + sb.Append(" SepadirectdebitSequenceType: ").Append(SepadirectdebitSequenceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSepaJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSepa Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option sepadirectdebitDateOfSignature = default; + Option sepadirectdebitMandateId = default; + Option sepadirectdebitSequenceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "sepadirectdebit.dateOfSignature": + sepadirectdebitDateOfSignature = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.mandateId": + sepadirectdebitMandateId = new Option(utf8JsonReader.GetString()!); + break; + case "sepadirectdebit.sequenceType": + sepadirectdebitSequenceType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSepa(sepadirectdebitDateOfSignature, sepadirectdebitMandateId, sepadirectdebitSequenceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSepa, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSepa responseAdditionalDataSepa, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSepa._SepadirectdebitDateOfSignatureOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitDateOfSignature != null) + writer.WriteString("sepadirectdebit.dateOfSignature", responseAdditionalDataSepa.SepadirectdebitDateOfSignature); + + if (responseAdditionalDataSepa._SepadirectdebitMandateIdOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitMandateId != null) + writer.WriteString("sepadirectdebit.mandateId", responseAdditionalDataSepa.SepadirectdebitMandateId); + + if (responseAdditionalDataSepa._SepadirectdebitSequenceTypeOption.IsSet) + if (responseAdditionalDataSepa.SepadirectdebitSequenceType != null) + writer.WriteString("sepadirectdebit.sequenceType", responseAdditionalDataSepa.SepadirectdebitSequenceType); + } + } +} diff --git a/Adyen/Payout/Models/ResponseAdditionalDataSwish.cs b/Adyen/Payout/Models/ResponseAdditionalDataSwish.cs new file mode 100644 index 000000000..e58263314 --- /dev/null +++ b/Adyen/Payout/Models/ResponseAdditionalDataSwish.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ResponseAdditionalDataSwish. + /// + public partial class ResponseAdditionalDataSwish : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A Swish shopper's telephone number. + [JsonConstructor] + public ResponseAdditionalDataSwish(Option swishPayerAlias = default) + { + _SwishPayerAliasOption = swishPayerAlias; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResponseAdditionalDataSwish() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SwishPayerAliasOption { get; private set; } + + /// + /// A Swish shopper's telephone number. + /// + /// A Swish shopper's telephone number. + [JsonPropertyName("swish.payerAlias")] + public string? SwishPayerAlias { get { return this._SwishPayerAliasOption; } set { this._SwishPayerAliasOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResponseAdditionalDataSwish {\n"); + sb.Append(" SwishPayerAlias: ").Append(SwishPayerAlias).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResponseAdditionalDataSwishJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResponseAdditionalDataSwish Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option swishPayerAlias = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "swish.payerAlias": + swishPayerAlias = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResponseAdditionalDataSwish(swishPayerAlias); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, responseAdditionalDataSwish, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResponseAdditionalDataSwish responseAdditionalDataSwish, JsonSerializerOptions jsonSerializerOptions) + { + + if (responseAdditionalDataSwish._SwishPayerAliasOption.IsSet) + if (responseAdditionalDataSwish.SwishPayerAlias != null) + writer.WriteString("swish.payerAlias", responseAdditionalDataSwish.SwishPayerAlias); + } + } +} diff --git a/Adyen/Payout/Models/ServiceError.cs b/Adyen/Payout/Models/ServiceError.cs new file mode 100644 index 000000000..b91960726 --- /dev/null +++ b/Adyen/Payout/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Payout/Models/StoreDetailAndSubmitRequest.cs b/Adyen/Payout/Models/StoreDetailAndSubmitRequest.cs new file mode 100644 index 000000000..354b3494b --- /dev/null +++ b/Adyen/Payout/Models/StoreDetailAndSubmitRequest.cs @@ -0,0 +1,694 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// StoreDetailAndSubmitRequest. + /// + public partial class StoreDetailAndSubmitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + /// The type of the entity the payout is processed for. + /// The merchant account identifier, with which you want to process the transaction. + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + /// recurring + /// The merchant reference for this payment. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + /// The shopper's email address. + /// The shopper's reference for the payment transaction. + /// This field contains additional data, which may be required for a particular request. + /// bank + /// billingAddress + /// card + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + /// shopperName + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + /// The shopper's social security number. + /// The shopper's phone number. + [JsonConstructor] + public StoreDetailAndSubmitRequest(Amount amount, DateOnly dateOfBirth, EntityTypeEnum entityType, string merchantAccount, string nationality, Recurring recurring, string reference, string shopperEmail, string shopperReference, Option?> additionalData = default, Option bank = default, Option billingAddress = default, Option card = default, Option fraudOffset = default, Option selectedBrand = default, Option shopperName = default, Option shopperStatement = default, Option socialSecurityNumber = default, Option telephoneNumber = default) + { + Amount = amount; + DateOfBirth = dateOfBirth; + EntityType = entityType; + MerchantAccount = merchantAccount; + Nationality = nationality; + Recurring = recurring; + Reference = reference; + ShopperEmail = shopperEmail; + ShopperReference = shopperReference; + _AdditionalDataOption = additionalData; + _BankOption = bank; + _BillingAddressOption = billingAddress; + _CardOption = card; + _FraudOffsetOption = fraudOffset; + _SelectedBrandOption = selectedBrand; + _ShopperNameOption = shopperName; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreDetailAndSubmitRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of the entity the payout is processed for. + /// + /// The type of the entity the payout is processed for. + [JsonConverter(typeof(EntityTypeEnumJsonConverter))] + public class EntityTypeEnum : IEnum + { + /// + /// Returns the value of the EntityTypeEnum. + /// + public string? Value { get; set; } + + /// + /// EntityTypeEnum.NaturalPerson - NaturalPerson + /// + public static readonly EntityTypeEnum NaturalPerson = new("NaturalPerson"); + + /// + /// EntityTypeEnum.Company - Company + /// + public static readonly EntityTypeEnum Company = new("Company"); + + private EntityTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EntityTypeEnum?(string? value) => value == null ? null : new EntityTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EntityTypeEnum? option) => option?.Value; + + public static bool operator ==(EntityTypeEnum? left, EntityTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EntityTypeEnum? left, EntityTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EntityTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EntityTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "NaturalPerson" => EntityTypeEnum.NaturalPerson, + "Company" => EntityTypeEnum.Company, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EntityTypeEnum? value) + { + if (value == null) + return null; + + if (value == EntityTypeEnum.NaturalPerson) + return "NaturalPerson"; + + if (value == EntityTypeEnum.Company) + return "Company"; + + return null; + } + + /// + /// JsonConverter for writing EntityTypeEnum. + /// + public class EntityTypeEnumJsonConverter : JsonConverter + { + public override EntityTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EntityTypeEnum.FromStringOrDefault(value) ?? new EntityTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EntityTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EntityTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the entity the payout is processed for. + /// + /// The type of the entity the payout is processed for. + [JsonPropertyName("entityType")] + public EntityTypeEnum EntityType { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + /// + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + [JsonPropertyName("dateOfBirth")] + public DateOnly DateOfBirth { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + [JsonPropertyName("nationality")] + public string Nationality { get; set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring Recurring { get; set; } + + /// + /// The merchant reference for this payment. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + /// + /// The merchant reference for this payment. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// The shopper's reference for the payment transaction. + /// + /// The shopper's reference for the payment transaction. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular request. + /// + /// This field contains additional data, which may be required for a particular request. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bank")] + public BankAccount? Bank { get { return this._BankOption; } set { this._BankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + /// + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + /// + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's phone number. + /// + /// The shopper's phone number. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreDetailAndSubmitRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Nationality: ").Append(Nationality).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Bank: ").Append(Bank).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Nationality (string) maxLength + if (this.Nationality != null && this.Nationality.Length > 2) + { + yield return new ValidationResult("Invalid value for Nationality, length must be less than 2.", new [] { "Nationality" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreDetailAndSubmitRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreDetailAndSubmitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option dateOfBirth = default; + Option entityType = default; + Option merchantAccount = default; + Option nationality = default; + Option recurring = default; + Option reference = default; + Option shopperEmail = default; + Option shopperReference = default; + Option?> additionalData = default; + Option bank = default; + Option billingAddress = default; + Option card = default; + Option fraudOffset = default; + Option selectedBrand = default; + Option shopperName = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + entityType = new Option(StoreDetailAndSubmitRequest.EntityTypeEnum.FromStringOrDefault(entityTypeRawValue)); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "nationality": + nationality = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bank": + bank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(amount)); + + if (!dateOfBirth.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(dateOfBirth)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(entityType)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(merchantAccount)); + + if (!nationality.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(nationality)); + + if (!recurring.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(recurring)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(reference)); + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(shopperEmail)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitRequest.", nameof(shopperReference)); + + return new StoreDetailAndSubmitRequest(amount.Value!, dateOfBirth.Value!.Value!, entityType.Value!.Value!, merchantAccount.Value!, nationality.Value!, recurring.Value!, reference.Value!, shopperEmail.Value!, shopperReference.Value!, additionalData, bank, billingAddress, card, fraudOffset, selectedBrand, shopperName, shopperStatement, socialSecurityNumber, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreDetailAndSubmitRequest storeDetailAndSubmitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeDetailAndSubmitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreDetailAndSubmitRequest storeDetailAndSubmitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.Amount, jsonSerializerOptions); + writer.WriteString("dateOfBirth", storeDetailAndSubmitRequest.DateOfBirth.ToString(DateOfBirthFormat)); + + if (storeDetailAndSubmitRequest.EntityType != null) + { + string? entityTypeRawValue = StoreDetailAndSubmitRequest.EntityTypeEnum.ToJsonValue(storeDetailAndSubmitRequest.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + } + + if (storeDetailAndSubmitRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storeDetailAndSubmitRequest.MerchantAccount); + + if (storeDetailAndSubmitRequest.Nationality != null) + writer.WriteString("nationality", storeDetailAndSubmitRequest.Nationality); + + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.Recurring, jsonSerializerOptions); + if (storeDetailAndSubmitRequest.Reference != null) + writer.WriteString("reference", storeDetailAndSubmitRequest.Reference); + + if (storeDetailAndSubmitRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", storeDetailAndSubmitRequest.ShopperEmail); + + if (storeDetailAndSubmitRequest.ShopperReference != null) + writer.WriteString("shopperReference", storeDetailAndSubmitRequest.ShopperReference); + + if (storeDetailAndSubmitRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.AdditionalData, jsonSerializerOptions); + } + if (storeDetailAndSubmitRequest._BankOption.IsSet) + { + writer.WritePropertyName("bank"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.Bank, jsonSerializerOptions); + } + if (storeDetailAndSubmitRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.BillingAddress, jsonSerializerOptions); + } + if (storeDetailAndSubmitRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.Card, jsonSerializerOptions); + } + if (storeDetailAndSubmitRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", storeDetailAndSubmitRequest._FraudOffsetOption.Value!.Value); + + if (storeDetailAndSubmitRequest._SelectedBrandOption.IsSet) + if (storeDetailAndSubmitRequest.SelectedBrand != null) + writer.WriteString("selectedBrand", storeDetailAndSubmitRequest.SelectedBrand); + + if (storeDetailAndSubmitRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitRequest.ShopperName, jsonSerializerOptions); + } + if (storeDetailAndSubmitRequest._ShopperStatementOption.IsSet) + if (storeDetailAndSubmitRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", storeDetailAndSubmitRequest.ShopperStatement); + + if (storeDetailAndSubmitRequest._SocialSecurityNumberOption.IsSet) + if (storeDetailAndSubmitRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", storeDetailAndSubmitRequest.SocialSecurityNumber); + + if (storeDetailAndSubmitRequest._TelephoneNumberOption.IsSet) + if (storeDetailAndSubmitRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", storeDetailAndSubmitRequest.TelephoneNumber); + } + } +} diff --git a/Adyen/Payout/Models/StoreDetailAndSubmitResponse.cs b/Adyen/Payout/Models/StoreDetailAndSubmitResponse.cs new file mode 100644 index 000000000..c13d35d8e --- /dev/null +++ b/Adyen/Payout/Models/StoreDetailAndSubmitResponse.cs @@ -0,0 +1,242 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// StoreDetailAndSubmitResponse. + /// + public partial class StoreDetailAndSubmitResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A new reference to uniquely identify this request. + /// The response: * In case of success is payout-submit-received. * In case of an error, an informational message is returned. + /// This field contains additional data, which may be returned in a particular response. + /// In case of refusal, an informational message for the reason. + [JsonConstructor] + public StoreDetailAndSubmitResponse(string pspReference, string resultCode, Option?> additionalData = default, Option refusalReason = default) + { + PspReference = pspReference; + ResultCode = resultCode; + _AdditionalDataOption = additionalData; + _RefusalReasonOption = refusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreDetailAndSubmitResponse() + { + } + + partial void OnCreated(); + + /// + /// A new reference to uniquely identify this request. + /// + /// A new reference to uniquely identify this request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The response: * In case of success is payout-submit-received. * In case of an error, an informational message is returned. + /// + /// The response: * In case of success is payout-submit-received. * In case of an error, an informational message is returned. + [JsonPropertyName("resultCode")] + public string ResultCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular response. + /// + /// This field contains additional data, which may be returned in a particular response. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// In case of refusal, an informational message for the reason. + /// + /// In case of refusal, an informational message for the reason. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreDetailAndSubmitResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreDetailAndSubmitResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreDetailAndSubmitResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option resultCode = default; + Option?> additionalData = default; + Option refusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitResponse.", nameof(pspReference)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class StoreDetailAndSubmitResponse.", nameof(resultCode)); + + return new StoreDetailAndSubmitResponse(pspReference.Value!, resultCode.Value!, additionalData, refusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreDetailAndSubmitResponse storeDetailAndSubmitResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeDetailAndSubmitResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreDetailAndSubmitResponse storeDetailAndSubmitResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storeDetailAndSubmitResponse.PspReference != null) + writer.WriteString("pspReference", storeDetailAndSubmitResponse.PspReference); + + if (storeDetailAndSubmitResponse.ResultCode != null) + writer.WriteString("resultCode", storeDetailAndSubmitResponse.ResultCode); + + if (storeDetailAndSubmitResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, storeDetailAndSubmitResponse.AdditionalData, jsonSerializerOptions); + } + if (storeDetailAndSubmitResponse._RefusalReasonOption.IsSet) + if (storeDetailAndSubmitResponse.RefusalReason != null) + writer.WriteString("refusalReason", storeDetailAndSubmitResponse.RefusalReason); + } + } +} diff --git a/Adyen/Payout/Models/StoreDetailRequest.cs b/Adyen/Payout/Models/StoreDetailRequest.cs new file mode 100644 index 000000000..17fe92e51 --- /dev/null +++ b/Adyen/Payout/Models/StoreDetailRequest.cs @@ -0,0 +1,631 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// StoreDetailRequest. + /// + public partial class StoreDetailRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + /// The type of the entity the payout is processed for. + /// The merchant account identifier, with which you want to process the transaction. + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + /// recurring + /// The shopper's email address. + /// The shopper's reference for the payment transaction. + /// This field contains additional data, which may be required for a particular request. + /// bank + /// billingAddress + /// card + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + /// shopperName + /// The shopper's social security number. + /// The shopper's phone number. + [JsonConstructor] + public StoreDetailRequest(DateOnly dateOfBirth, EntityTypeEnum entityType, string merchantAccount, string nationality, Recurring recurring, string shopperEmail, string shopperReference, Option?> additionalData = default, Option bank = default, Option billingAddress = default, Option card = default, Option fraudOffset = default, Option selectedBrand = default, Option shopperName = default, Option socialSecurityNumber = default, Option telephoneNumber = default) + { + DateOfBirth = dateOfBirth; + EntityType = entityType; + MerchantAccount = merchantAccount; + Nationality = nationality; + Recurring = recurring; + ShopperEmail = shopperEmail; + ShopperReference = shopperReference; + _AdditionalDataOption = additionalData; + _BankOption = bank; + _BillingAddressOption = billingAddress; + _CardOption = card; + _FraudOffsetOption = fraudOffset; + _SelectedBrandOption = selectedBrand; + _ShopperNameOption = shopperName; + _SocialSecurityNumberOption = socialSecurityNumber; + _TelephoneNumberOption = telephoneNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreDetailRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of the entity the payout is processed for. + /// + /// The type of the entity the payout is processed for. + [JsonConverter(typeof(EntityTypeEnumJsonConverter))] + public class EntityTypeEnum : IEnum + { + /// + /// Returns the value of the EntityTypeEnum. + /// + public string? Value { get; set; } + + /// + /// EntityTypeEnum.NaturalPerson - NaturalPerson + /// + public static readonly EntityTypeEnum NaturalPerson = new("NaturalPerson"); + + /// + /// EntityTypeEnum.Company - Company + /// + public static readonly EntityTypeEnum Company = new("Company"); + + private EntityTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EntityTypeEnum?(string? value) => value == null ? null : new EntityTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EntityTypeEnum? option) => option?.Value; + + public static bool operator ==(EntityTypeEnum? left, EntityTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EntityTypeEnum? left, EntityTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EntityTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EntityTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "NaturalPerson" => EntityTypeEnum.NaturalPerson, + "Company" => EntityTypeEnum.Company, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EntityTypeEnum? value) + { + if (value == null) + return null; + + if (value == EntityTypeEnum.NaturalPerson) + return "NaturalPerson"; + + if (value == EntityTypeEnum.Company) + return "Company"; + + return null; + } + + /// + /// JsonConverter for writing EntityTypeEnum. + /// + public class EntityTypeEnumJsonConverter : JsonConverter + { + public override EntityTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EntityTypeEnum.FromStringOrDefault(value) ?? new EntityTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EntityTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EntityTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the entity the payout is processed for. + /// + /// The type of the entity the payout is processed for. + [JsonPropertyName("entityType")] + public EntityTypeEnum EntityType { get; set; } + + /// + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + /// + /// The date of birth. Format: [ISO-8601](https://www.w3.org/TR/NOTE-datetime); example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. + [JsonPropertyName("dateOfBirth")] + public DateOnly DateOfBirth { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). + [JsonPropertyName("nationality")] + public string Nationality { get; set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring Recurring { get; set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// The shopper's reference for the payment transaction. + /// + /// The shopper's reference for the payment transaction. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular request. + /// + /// This field contains additional data, which may be required for a particular request. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bank")] + public BankAccount? Bank { get { return this._BankOption; } set { this._BankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedBrandOption { get; private set; } + + /// + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + /// + /// The name of the brand to make a payout to. For Paysafecard it must be set to `paysafecard`. + [JsonPropertyName("selectedBrand")] + public string? SelectedBrand { get { return this._SelectedBrandOption; } set { this._SelectedBrandOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TelephoneNumberOption { get; private set; } + + /// + /// The shopper's phone number. + /// + /// The shopper's phone number. + [JsonPropertyName("telephoneNumber")] + public string? TelephoneNumber { get { return this._TelephoneNumberOption; } set { this._TelephoneNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreDetailRequest {\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Nationality: ").Append(Nationality).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Bank: ").Append(Bank).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" SelectedBrand: ").Append(SelectedBrand).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" TelephoneNumber: ").Append(TelephoneNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Nationality (string) maxLength + if (this.Nationality != null && this.Nationality.Length > 2) + { + yield return new ValidationResult("Invalid value for Nationality, length must be less than 2.", new [] { "Nationality" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreDetailRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreDetailRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dateOfBirth = default; + Option entityType = default; + Option merchantAccount = default; + Option nationality = default; + Option recurring = default; + Option shopperEmail = default; + Option shopperReference = default; + Option?> additionalData = default; + Option bank = default; + Option billingAddress = default; + Option card = default; + Option fraudOffset = default; + Option selectedBrand = default; + Option shopperName = default; + Option socialSecurityNumber = default; + Option telephoneNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + entityType = new Option(StoreDetailRequest.EntityTypeEnum.FromStringOrDefault(entityTypeRawValue)); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "nationality": + nationality = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "bank": + bank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "selectedBrand": + selectedBrand = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "telephoneNumber": + telephoneNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!dateOfBirth.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(dateOfBirth)); + + if (!entityType.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(entityType)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(merchantAccount)); + + if (!nationality.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(nationality)); + + if (!recurring.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(recurring)); + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(shopperEmail)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailRequest.", nameof(shopperReference)); + + return new StoreDetailRequest(dateOfBirth.Value!.Value!, entityType.Value!.Value!, merchantAccount.Value!, nationality.Value!, recurring.Value!, shopperEmail.Value!, shopperReference.Value!, additionalData, bank, billingAddress, card, fraudOffset, selectedBrand, shopperName, socialSecurityNumber, telephoneNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreDetailRequest storeDetailRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeDetailRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreDetailRequest storeDetailRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("dateOfBirth", storeDetailRequest.DateOfBirth.ToString(DateOfBirthFormat)); + + if (storeDetailRequest.EntityType != null) + { + string? entityTypeRawValue = StoreDetailRequest.EntityTypeEnum.ToJsonValue(storeDetailRequest.EntityType); + writer.WriteString("entityType", entityTypeRawValue); + } + + if (storeDetailRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storeDetailRequest.MerchantAccount); + + if (storeDetailRequest.Nationality != null) + writer.WriteString("nationality", storeDetailRequest.Nationality); + + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, storeDetailRequest.Recurring, jsonSerializerOptions); + if (storeDetailRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", storeDetailRequest.ShopperEmail); + + if (storeDetailRequest.ShopperReference != null) + writer.WriteString("shopperReference", storeDetailRequest.ShopperReference); + + if (storeDetailRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, storeDetailRequest.AdditionalData, jsonSerializerOptions); + } + if (storeDetailRequest._BankOption.IsSet) + { + writer.WritePropertyName("bank"); + JsonSerializer.Serialize(writer, storeDetailRequest.Bank, jsonSerializerOptions); + } + if (storeDetailRequest._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, storeDetailRequest.BillingAddress, jsonSerializerOptions); + } + if (storeDetailRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, storeDetailRequest.Card, jsonSerializerOptions); + } + if (storeDetailRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", storeDetailRequest._FraudOffsetOption.Value!.Value); + + if (storeDetailRequest._SelectedBrandOption.IsSet) + if (storeDetailRequest.SelectedBrand != null) + writer.WriteString("selectedBrand", storeDetailRequest.SelectedBrand); + + if (storeDetailRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, storeDetailRequest.ShopperName, jsonSerializerOptions); + } + if (storeDetailRequest._SocialSecurityNumberOption.IsSet) + if (storeDetailRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", storeDetailRequest.SocialSecurityNumber); + + if (storeDetailRequest._TelephoneNumberOption.IsSet) + if (storeDetailRequest.TelephoneNumber != null) + writer.WriteString("telephoneNumber", storeDetailRequest.TelephoneNumber); + } + } +} diff --git a/Adyen/Payout/Models/StoreDetailResponse.cs b/Adyen/Payout/Models/StoreDetailResponse.cs new file mode 100644 index 000000000..844af69a6 --- /dev/null +++ b/Adyen/Payout/Models/StoreDetailResponse.cs @@ -0,0 +1,238 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// StoreDetailResponse. + /// + public partial class StoreDetailResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A new reference to uniquely identify this request. + /// The token which you can use later on for submitting the payout. + /// The result code of the transaction. `Success` indicates that the details were stored successfully. + /// This field contains additional data, which may be returned in a particular response. + [JsonConstructor] + public StoreDetailResponse(string pspReference, string recurringDetailReference, string resultCode, Option?> additionalData = default) + { + PspReference = pspReference; + RecurringDetailReference = recurringDetailReference; + ResultCode = resultCode; + _AdditionalDataOption = additionalData; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoreDetailResponse() + { + } + + partial void OnCreated(); + + /// + /// A new reference to uniquely identify this request. + /// + /// A new reference to uniquely identify this request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The token which you can use later on for submitting the payout. + /// + /// The token which you can use later on for submitting the payout. + [JsonPropertyName("recurringDetailReference")] + public string RecurringDetailReference { get; set; } + + /// + /// The result code of the transaction. `Success` indicates that the details were stored successfully. + /// + /// The result code of the transaction. `Success` indicates that the details were stored successfully. + [JsonPropertyName("resultCode")] + public string ResultCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular response. + /// + /// This field contains additional data, which may be returned in a particular response. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoreDetailResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoreDetailResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoreDetailResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option recurringDetailReference = default; + Option resultCode = default; + Option?> additionalData = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailResponse.", nameof(pspReference)); + + if (!recurringDetailReference.IsSet) + throw new ArgumentException("Property is required for class StoreDetailResponse.", nameof(recurringDetailReference)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class StoreDetailResponse.", nameof(resultCode)); + + return new StoreDetailResponse(pspReference.Value!, recurringDetailReference.Value!, resultCode.Value!, additionalData); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoreDetailResponse storeDetailResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storeDetailResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoreDetailResponse storeDetailResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storeDetailResponse.PspReference != null) + writer.WriteString("pspReference", storeDetailResponse.PspReference); + + if (storeDetailResponse.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storeDetailResponse.RecurringDetailReference); + + if (storeDetailResponse.ResultCode != null) + writer.WriteString("resultCode", storeDetailResponse.ResultCode); + + if (storeDetailResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, storeDetailResponse.AdditionalData, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Payout/Models/SubmitRequest.cs b/Adyen/Payout/Models/SubmitRequest.cs new file mode 100644 index 000000000..e0a89fd86 --- /dev/null +++ b/Adyen/Payout/Models/SubmitRequest.cs @@ -0,0 +1,597 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// SubmitRequest. + /// + public partial class SubmitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier you want to process the transaction request with. + /// recurring + /// The merchant reference for this payout. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + /// This is the `recurringDetailReference` you want to use for this payout. You can use the value LATEST to select the most recently used recurring detail. + /// The shopper's email address. + /// The shopper's reference for the payout transaction. + /// This field contains additional data, which may be required for a particular request. + /// The date of birth. Format: ISO-8601; example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. > This field is required to update the existing `dateOfBirth` that is associated with this recurring contract. + /// The type of the entity the payout is processed for. Allowed values: * NaturalPerson * Company > This field is required to update the existing `entityType` that is associated with this recurring contract. + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). > This field is required to update the existing nationality that is associated with this recurring contract. + /// shopperName + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + /// The shopper's social security number. + [JsonConstructor] + public SubmitRequest(Amount amount, string merchantAccount, Recurring recurring, string reference, string selectedRecurringDetailReference, string shopperEmail, string shopperReference, Option?> additionalData = default, Option dateOfBirth = default, Option entityType = default, Option fraudOffset = default, Option nationality = default, Option shopperName = default, Option shopperStatement = default, Option socialSecurityNumber = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Recurring = recurring; + Reference = reference; + SelectedRecurringDetailReference = selectedRecurringDetailReference; + ShopperEmail = shopperEmail; + ShopperReference = shopperReference; + _AdditionalDataOption = additionalData; + _DateOfBirthOption = dateOfBirth; + _EntityTypeOption = entityType; + _FraudOffsetOption = fraudOffset; + _NationalityOption = nationality; + _ShopperNameOption = shopperName; + _ShopperStatementOption = shopperStatement; + _SocialSecurityNumberOption = socialSecurityNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubmitRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of the entity the payout is processed for. Allowed values: * NaturalPerson * Company > This field is required to update the existing `entityType` that is associated with this recurring contract. + /// + /// The type of the entity the payout is processed for. Allowed values: * NaturalPerson * Company > This field is required to update the existing `entityType` that is associated with this recurring contract. + [JsonConverter(typeof(EntityTypeEnumJsonConverter))] + public class EntityTypeEnum : IEnum + { + /// + /// Returns the value of the EntityTypeEnum. + /// + public string? Value { get; set; } + + /// + /// EntityTypeEnum.NaturalPerson - NaturalPerson + /// + public static readonly EntityTypeEnum NaturalPerson = new("NaturalPerson"); + + /// + /// EntityTypeEnum.Company - Company + /// + public static readonly EntityTypeEnum Company = new("Company"); + + private EntityTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EntityTypeEnum?(string? value) => value == null ? null : new EntityTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EntityTypeEnum? option) => option?.Value; + + public static bool operator ==(EntityTypeEnum? left, EntityTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EntityTypeEnum? left, EntityTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EntityTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EntityTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "NaturalPerson" => EntityTypeEnum.NaturalPerson, + "Company" => EntityTypeEnum.Company, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EntityTypeEnum? value) + { + if (value == null) + return null; + + if (value == EntityTypeEnum.NaturalPerson) + return "NaturalPerson"; + + if (value == EntityTypeEnum.Company) + return "Company"; + + return null; + } + + /// + /// JsonConverter for writing EntityTypeEnum. + /// + public class EntityTypeEnumJsonConverter : JsonConverter + { + public override EntityTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EntityTypeEnum.FromStringOrDefault(value) ?? new EntityTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EntityTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EntityTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EntityTypeOption { get; private set; } + + /// + /// The type of the entity the payout is processed for. Allowed values: * NaturalPerson * Company > This field is required to update the existing `entityType` that is associated with this recurring contract. + /// + /// The type of the entity the payout is processed for. Allowed values: * NaturalPerson * Company > This field is required to update the existing `entityType` that is associated with this recurring contract. + [JsonPropertyName("entityType")] + public EntityTypeEnum? EntityType { get { return this._EntityTypeOption; } set { this._EntityTypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier you want to process the transaction request with. + /// + /// The merchant account identifier you want to process the transaction request with. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring Recurring { get; set; } + + /// + /// The merchant reference for this payout. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + /// + /// The merchant reference for this payout. This reference will be used in all communication to the merchant about the status of the payout. Although it is a good idea to make sure it is unique, this is not a requirement. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is the `recurringDetailReference` you want to use for this payout. You can use the value LATEST to select the most recently used recurring detail. + /// + /// This is the `recurringDetailReference` you want to use for this payout. You can use the value LATEST to select the most recently used recurring detail. + [JsonPropertyName("selectedRecurringDetailReference")] + public string SelectedRecurringDetailReference { get; set; } + + /// + /// The shopper's email address. + /// + /// The shopper's email address. + [JsonPropertyName("shopperEmail")] + public string ShopperEmail { get; set; } + + /// + /// The shopper's reference for the payout transaction. + /// + /// The shopper's reference for the payout transaction. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular request. + /// + /// This field contains additional data, which may be required for a particular request. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The date of birth. Format: ISO-8601; example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. > This field is required to update the existing `dateOfBirth` that is associated with this recurring contract. + /// + /// The date of birth. Format: ISO-8601; example: YYYY-MM-DD For Paysafecard it must be the same as used when registering the Paysafecard account. > This field is mandatory for natural persons. > This field is required to update the existing `dateOfBirth` that is associated with this recurring contract. + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FraudOffsetOption { get; private set; } + + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + /// + /// An integer value that is added to the normal fraud score. The value can be either positive or negative. + [JsonPropertyName("fraudOffset")] + public int? FraudOffset { get { return this._FraudOffsetOption; } set { this._FraudOffsetOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NationalityOption { get; private set; } + + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). > This field is required to update the existing nationality that is associated with this recurring contract. + /// + /// The shopper's nationality. A valid value is an ISO 2-character country code (e.g. 'NL'). > This field is required to update the existing nationality that is associated with this recurring contract. + [JsonPropertyName("nationality")] + public string? Nationality { get { return this._NationalityOption; } set { this._NationalityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperStatementOption { get; private set; } + + /// + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + /// + /// The description of this payout. This description is shown on the bank statement of the shopper (if this is supported by the chosen payment method). + [JsonPropertyName("shopperStatement")] + public string? ShopperStatement { get { return this._ShopperStatementOption; } set { this._ShopperStatementOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// The shopper's social security number. + /// + /// The shopper's social security number. + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubmitRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" ShopperEmail: ").Append(ShopperEmail).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" EntityType: ").Append(EntityType).Append("\n"); + sb.Append(" FraudOffset: ").Append(FraudOffset).Append("\n"); + sb.Append(" Nationality: ").Append(Nationality).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" ShopperStatement: ").Append(ShopperStatement).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubmitRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubmitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option recurring = default; + Option reference = default; + Option selectedRecurringDetailReference = default; + Option shopperEmail = default; + Option shopperReference = default; + Option?> additionalData = default; + Option dateOfBirth = default; + Option entityType = default; + Option fraudOffset = default; + Option nationality = default; + Option shopperName = default; + Option shopperStatement = default; + Option socialSecurityNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperEmail": + shopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "entityType": + string? entityTypeRawValue = utf8JsonReader.GetString(); + entityType = new Option(SubmitRequest.EntityTypeEnum.FromStringOrDefault(entityTypeRawValue)); + break; + case "fraudOffset": + fraudOffset = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "nationality": + nationality = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "shopperStatement": + shopperStatement = new Option(utf8JsonReader.GetString()!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(merchantAccount)); + + if (!recurring.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(recurring)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(reference)); + + if (!selectedRecurringDetailReference.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(selectedRecurringDetailReference)); + + if (!shopperEmail.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(shopperEmail)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class SubmitRequest.", nameof(shopperReference)); + + return new SubmitRequest(amount.Value!, merchantAccount.Value!, recurring.Value!, reference.Value!, selectedRecurringDetailReference.Value!, shopperEmail.Value!, shopperReference.Value!, additionalData, dateOfBirth, entityType, fraudOffset, nationality, shopperName, shopperStatement, socialSecurityNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubmitRequest submitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, submitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubmitRequest submitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, submitRequest.Amount, jsonSerializerOptions); + if (submitRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", submitRequest.MerchantAccount); + + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, submitRequest.Recurring, jsonSerializerOptions); + if (submitRequest.Reference != null) + writer.WriteString("reference", submitRequest.Reference); + + if (submitRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", submitRequest.SelectedRecurringDetailReference); + + if (submitRequest.ShopperEmail != null) + writer.WriteString("shopperEmail", submitRequest.ShopperEmail); + + if (submitRequest.ShopperReference != null) + writer.WriteString("shopperReference", submitRequest.ShopperReference); + + if (submitRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, submitRequest.AdditionalData, jsonSerializerOptions); + } + if (submitRequest._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", submitRequest._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (submitRequest._EntityTypeOption.IsSet && submitRequest.EntityType != null) + { + string? entityTypeRawValue = SubmitRequest.EntityTypeEnum.ToJsonValue(submitRequest._EntityTypeOption.Value!.Value); + writer.WriteString("entityType", entityTypeRawValue); + } + + if (submitRequest._FraudOffsetOption.IsSet) + writer.WriteNumber("fraudOffset", submitRequest._FraudOffsetOption.Value!.Value); + + if (submitRequest._NationalityOption.IsSet) + if (submitRequest.Nationality != null) + writer.WriteString("nationality", submitRequest.Nationality); + + if (submitRequest._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, submitRequest.ShopperName, jsonSerializerOptions); + } + if (submitRequest._ShopperStatementOption.IsSet) + if (submitRequest.ShopperStatement != null) + writer.WriteString("shopperStatement", submitRequest.ShopperStatement); + + if (submitRequest._SocialSecurityNumberOption.IsSet) + if (submitRequest.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", submitRequest.SocialSecurityNumber); + } + } +} diff --git a/Adyen/Payout/Models/SubmitResponse.cs b/Adyen/Payout/Models/SubmitResponse.cs new file mode 100644 index 000000000..79ef744b4 --- /dev/null +++ b/Adyen/Payout/Models/SubmitResponse.cs @@ -0,0 +1,242 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Payout.Client; + +namespace Adyen.Payout.Models +{ + /// + /// SubmitResponse. + /// + public partial class SubmitResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A new reference to uniquely identify this request. + /// The response: * In case of success, it is `payout-submit-received`. * In case of an error, an informational message is returned. + /// This field contains additional data, which may be returned in a particular response. + /// In case of refusal, an informational message for the reason. + [JsonConstructor] + public SubmitResponse(string pspReference, string resultCode, Option?> additionalData = default, Option refusalReason = default) + { + PspReference = pspReference; + ResultCode = resultCode; + _AdditionalDataOption = additionalData; + _RefusalReasonOption = refusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SubmitResponse() + { + } + + partial void OnCreated(); + + /// + /// A new reference to uniquely identify this request. + /// + /// A new reference to uniquely identify this request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The response: * In case of success, it is `payout-submit-received`. * In case of an error, an informational message is returned. + /// + /// The response: * In case of success, it is `payout-submit-received`. * In case of an error, an informational message is returned. + [JsonPropertyName("resultCode")] + public string ResultCode { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular response. + /// + /// This field contains additional data, which may be returned in a particular response. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// In case of refusal, an informational message for the reason. + /// + /// In case of refusal, an informational message for the reason. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SubmitResponse {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SubmitResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SubmitResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option resultCode = default; + Option?> additionalData = default; + Option refusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class SubmitResponse.", nameof(pspReference)); + + if (!resultCode.IsSet) + throw new ArgumentException("Property is required for class SubmitResponse.", nameof(resultCode)); + + return new SubmitResponse(pspReference.Value!, resultCode.Value!, additionalData, refusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SubmitResponse submitResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, submitResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SubmitResponse submitResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (submitResponse.PspReference != null) + writer.WriteString("pspReference", submitResponse.PspReference); + + if (submitResponse.ResultCode != null) + writer.WriteString("resultCode", submitResponse.ResultCode); + + if (submitResponse._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, submitResponse.AdditionalData, jsonSerializerOptions); + } + if (submitResponse._RefusalReasonOption.IsSet) + if (submitResponse.RefusalReason != null) + writer.WriteString("refusalReason", submitResponse.RefusalReason); + } + } +} diff --git a/Adyen/Payout/Services/InitializationService.cs b/Adyen/Payout/Services/InitializationService.cs new file mode 100644 index 000000000..ce0c6ec8b --- /dev/null +++ b/Adyen/Payout/Services/InitializationService.cs @@ -0,0 +1,1429 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Payout.Client; +using Adyen.Payout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Payout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IInitializationService : IAdyenApiService + { + /// + /// The class containing the events. + /// + InitializationServiceEvents Events { get; } + + /// + /// Store payout details + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Stores payment details under the `PAYOUT` recurring contract. These payment details can be used later to submit a payout via the `/submitThirdParty` call. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task StoreDetailAsync(StoreDetailRequest storeDetailRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Store details and submit a payout + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Submits a payout and stores its details for subsequent payouts. The submitted payout must be confirmed or declined either by a reviewer or via `/confirmThirdParty` or `/declineThirdParty` calls. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task StoreDetailAndSubmitThirdPartyAsync(StoreDetailAndSubmitRequest storeDetailAndSubmitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Submit a payout + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Submits a payout using the previously stored payment details. To store payment details, use the `/storeDetail` API call. The submitted payout must be confirmed or declined either by a reviewer or via `/confirmThirdParty` or `/declineThirdParty` calls. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task SubmitThirdPartyAsync(SubmitRequest submitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IStoreDetailApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IStoreDetailAndSubmitThirdPartyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ISubmitThirdPartyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class InitializationServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnStoreDetail; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorStoreDetail; + + internal void ExecuteOnStoreDetail(InitializationService.StoreDetailApiResponse apiResponse) + { + OnStoreDetail?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorStoreDetail(Exception exception) + { + OnErrorStoreDetail?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnStoreDetailAndSubmitThirdParty; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorStoreDetailAndSubmitThirdParty; + + internal void ExecuteOnStoreDetailAndSubmitThirdParty(InitializationService.StoreDetailAndSubmitThirdPartyApiResponse apiResponse) + { + OnStoreDetailAndSubmitThirdParty?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorStoreDetailAndSubmitThirdParty(Exception exception) + { + OnErrorStoreDetailAndSubmitThirdParty?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnSubmitThirdParty; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorSubmitThirdParty; + + internal void ExecuteOnSubmitThirdParty(InitializationService.SubmitThirdPartyApiResponse apiResponse) + { + OnSubmitThirdParty?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorSubmitThirdParty(Exception exception) + { + OnErrorSubmitThirdParty?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class InitializationService : IInitializationService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public InitializationServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public InitializationService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, InitializationServiceEvents initializationServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = initializationServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Store payout details > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Stores payment details under the `PAYOUT` recurring contract. These payment details can be used later to submit a payout via the `/submitThirdParty` call. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task StoreDetailAsync(StoreDetailRequest storeDetailRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/storeDetail" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/storeDetail"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storeDetailRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storeDetailRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + StoreDetailApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/storeDetail", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnStoreDetail(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorStoreDetail(exception); + throw; + } + } + + /// + /// The . + /// + public partial class StoreDetailApiResponse : Adyen.Core.Client.ApiResponse, IStoreDetailApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoreDetailApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoreDetailApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.StoreDetailResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.StoreDetailResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Store details and submit a payout > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Submits a payout and stores its details for subsequent payouts. The submitted payout must be confirmed or declined either by a reviewer or via `/confirmThirdParty` or `/declineThirdParty` calls. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task StoreDetailAndSubmitThirdPartyAsync(StoreDetailAndSubmitRequest storeDetailAndSubmitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/storeDetailAndSubmitThirdParty" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/storeDetailAndSubmitThirdParty"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storeDetailAndSubmitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storeDetailAndSubmitRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + StoreDetailAndSubmitThirdPartyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/storeDetailAndSubmitThirdParty", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnStoreDetailAndSubmitThirdParty(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorStoreDetailAndSubmitThirdParty(exception); + throw; + } + } + + /// + /// The . + /// + public partial class StoreDetailAndSubmitThirdPartyApiResponse : Adyen.Core.Client.ApiResponse, IStoreDetailAndSubmitThirdPartyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoreDetailAndSubmitThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public StoreDetailAndSubmitThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.StoreDetailAndSubmitResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.StoreDetailAndSubmitResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Submit a payout > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Submits a payout using the previously stored payment details. To store payment details, use the `/storeDetail` API call. The submitted payout must be confirmed or declined either by a reviewer or via `/confirmThirdParty` or `/declineThirdParty` calls. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task SubmitThirdPartyAsync(SubmitRequest submitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/submitThirdParty" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/submitThirdParty"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (submitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(submitRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + SubmitThirdPartyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/submitThirdParty", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnSubmitThirdParty(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorSubmitThirdParty(exception); + throw; + } + } + + /// + /// The . + /// + public partial class SubmitThirdPartyApiResponse : Adyen.Core.Client.ApiResponse, ISubmitThirdPartyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SubmitThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public SubmitThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.SubmitResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.SubmitResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Payout/Services/InstantPayoutsService.cs b/Adyen/Payout/Services/InstantPayoutsService.cs new file mode 100644 index 000000000..81f4d69b5 --- /dev/null +++ b/Adyen/Payout/Services/InstantPayoutsService.cs @@ -0,0 +1,541 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Payout.Client; +using Adyen.Payout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Payout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IInstantPayoutsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + InstantPayoutsServiceEvents Events { get; } + + /// + /// Make an instant card payout + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. With this call, you can pay out to your customers, and funds will be made available within 30 minutes on the cardholder's bank account (this is dependent on whether the issuer supports this functionality). Instant card payouts are only supported for Visa and Mastercard cards. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task PayoutAsync(PayoutRequest payoutRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IPayoutApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class InstantPayoutsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnPayout; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorPayout; + + internal void ExecuteOnPayout(InstantPayoutsService.PayoutApiResponse apiResponse) + { + OnPayout?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorPayout(Exception exception) + { + OnErrorPayout?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class InstantPayoutsService : IInstantPayoutsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public InstantPayoutsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public InstantPayoutsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, InstantPayoutsServiceEvents instantPayoutsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = instantPayoutsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Make an instant card payout > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) endpoint instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. With this call, you can pay out to your customers, and funds will be made available within 30 minutes on the cardholder's bank account (this is dependent on whether the issuer supports this functionality). Instant card payouts are only supported for Visa and Mastercard cards. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task PayoutAsync(PayoutRequest payoutRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/payout" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/payout"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (payoutRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(payoutRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + PayoutApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/payout", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnPayout(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorPayout(exception); + throw; + } + } + + /// + /// The . + /// + public partial class PayoutApiResponse : Adyen.Core.Client.ApiResponse, IPayoutApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PayoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public PayoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.PayoutResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.PayoutResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Payout/Services/ReviewingService.cs b/Adyen/Payout/Services/ReviewingService.cs new file mode 100644 index 000000000..c3dd8f68a --- /dev/null +++ b/Adyen/Payout/Services/ReviewingService.cs @@ -0,0 +1,985 @@ +// +/* + * Adyen Payout API + * + * > The **Payout API is deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. A set of API endpoints that allow you to store payout details, confirm, or decline a payout. For more information, refer to [Online payouts](https://docs.adyen.com/online-payments/online-payouts). ## Authentication To use the Payout API, you need to have [two API credentials](https://docs.adyen.com/online-payments/online-payouts#payouts-to-bank-accounts-and-wallets): one for storing payout details and submitting payouts, and another one for confirming or declining payouts. If you don't have the required API credentials, contact our [Support Team](https://www.adyen.help/hc/en-us/requests/new). If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using [basic authentication](https://docs.adyen.com/development-resources/api-credentials#basic-authentication). The following example shows how to authenticate your request with basic authentication when submitting a payout: ``` curl -U \"storePayout@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payout/v68/payout ``` ## Going live To authenticate to the live endpoints, you need [API credentials](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payout/v68/payout ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Payout.Client; +using Adyen.Payout.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Payout.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IReviewingService : IAdyenApiService + { + /// + /// The class containing the events. + /// + ReviewingServiceEvents Events { get; } + + /// + /// Confirm a payout + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Confirms a previously submitted payout. To cancel a payout, use the `/declineThirdParty` endpoint. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ConfirmThirdPartyAsync(ModifyRequest modifyRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel a payout + /// + /// + /// > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Cancels a previously submitted payout. To confirm and send a payout, use the `/confirmThirdParty` endpoint. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task DeclineThirdPartyAsync(ModifyRequest modifyRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IConfirmThirdPartyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDeclineThirdPartyApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class ReviewingServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnConfirmThirdParty; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorConfirmThirdParty; + + internal void ExecuteOnConfirmThirdParty(ReviewingService.ConfirmThirdPartyApiResponse apiResponse) + { + OnConfirmThirdParty?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorConfirmThirdParty(Exception exception) + { + OnErrorConfirmThirdParty?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDeclineThirdParty; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDeclineThirdParty; + + internal void ExecuteOnDeclineThirdParty(ReviewingService.DeclineThirdPartyApiResponse apiResponse) + { + OnDeclineThirdParty?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeclineThirdParty(Exception exception) + { + OnErrorDeclineThirdParty?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class ReviewingService : IReviewingService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public ReviewingServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public ReviewingService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ReviewingServiceEvents reviewingServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = reviewingServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Confirm a payout > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Confirms a previously submitted payout. To cancel a payout, use the `/declineThirdParty` endpoint. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ConfirmThirdPartyAsync(ModifyRequest modifyRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/confirmThirdParty" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/confirmThirdParty"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (modifyRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(modifyRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ConfirmThirdPartyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/confirmThirdParty", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnConfirmThirdParty(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorConfirmThirdParty(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ConfirmThirdPartyApiResponse : Adyen.Core.Client.ApiResponse, IConfirmThirdPartyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ConfirmThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ConfirmThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.ModifyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.ModifyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel a payout > This endpoint is **deprecated** and no longer supports new integrations. Do one of the following: >- If you are building a new integration, use the [Transfers API](https://docs.adyen.com/api-explorer/transfers/latest/overview) instead. > - If you are already using the Payout API, reach out to your Adyen contact to learn how to migrate to the Transfers API. > > With the Transfers API, you can: > - Handle multiple payout use cases with a single API. > - Use new payout functionalities, such as instant payouts to bank accounts. > - Receive webhooks with more details and defined transfer states. > > For more information about the payout features of the Transfers API, see our [Payouts](https://docs.adyen.com/payouts/payout-service) documentation. Cancels a previously submitted payout. To confirm and send a payout, use the `/confirmThirdParty` endpoint. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DeclineThirdPartyAsync(ModifyRequest modifyRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/declineThirdParty" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/declineThirdParty"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (modifyRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(modifyRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DeclineThirdPartyApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/declineThirdParty", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDeclineThirdParty(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDeclineThirdParty(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DeclineThirdPartyApiResponse : Adyen.Core.Client.ApiResponse, IDeclineThirdPartyApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeclineThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DeclineThirdPartyApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Payout.Models.ModifyResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Payout.Models.ModifyResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Payout.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Payout.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Payout.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Payout.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Payout.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Payout.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/PosMobile/Client/ApiKeyToken.cs b/Adyen/PosMobile/Client/ApiKeyToken.cs new file mode 100644 index 000000000..4f18670dd --- /dev/null +++ b/Adyen/PosMobile/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.PosMobile.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/PosMobile/Client/ClientUtils.cs b/Adyen/PosMobile/Client/ClientUtils.cs new file mode 100644 index 000000000..3d8cf020a --- /dev/null +++ b/Adyen/PosMobile/Client/ClientUtils.cs @@ -0,0 +1,313 @@ +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.PosMobile.Models; +using Models = Adyen.PosMobile.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.PosMobile.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/PosMobile/Client/HostConfiguration.cs b/Adyen/PosMobile/Client/HostConfiguration.cs new file mode 100644 index 000000000..16b935af6 --- /dev/null +++ b/Adyen/PosMobile/Client/HostConfiguration.cs @@ -0,0 +1,130 @@ +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.PosMobile.Services; +using Adyen.PosMobile.Client; +using Adyen.PosMobile.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.PosMobile.Client +{ + /// + /// Provides hosting configuration for PosMobile + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://checkout-test.adyen.com/checkout/possdk/v68"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new CreateSessionRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreateSessionResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddPosMobileHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/PosMobile/Client/JsonSerializerOptionsProvider.cs b/Adyen/PosMobile/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..15be59cb1 --- /dev/null +++ b/Adyen/PosMobile/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.PosMobile.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/PosMobile/Extensions/HostBuilderExtensions.cs b/Adyen/PosMobile/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..0dd12b21a --- /dev/null +++ b/Adyen/PosMobile/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.PosMobile; +using Adyen.PosMobile.Client; + +namespace Adyen.PosMobile.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the PosMobile API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigurePosMobile(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddPosMobileHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/PosMobile/Extensions/ServiceCollectionExtensions.cs b/Adyen/PosMobile/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..e0c06ecf8 --- /dev/null +++ b/Adyen/PosMobile/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.PosMobile.Client; + +namespace Adyen.PosMobile.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen PosMobile API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddPosMobileServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddPosMobileHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/PosMobile/Models/CreateSessionRequest.cs b/Adyen/PosMobile/Models/CreateSessionRequest.cs new file mode 100644 index 000000000..e8398c64c --- /dev/null +++ b/Adyen/PosMobile/Models/CreateSessionRequest.cs @@ -0,0 +1,222 @@ +// +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PosMobile.Client; + +namespace Adyen.PosMobile.Models +{ + /// + /// CreateSessionRequest. + /// + public partial class CreateSessionRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of your merchant account. + /// The setup token provided by the POS Mobile SDK. - When using the Android POS Mobile SDK, obtain the token through the `AuthenticationService.authenticate(setupToken)` callback of `AuthenticationService`. - When using the iOS POS Mobile SDK, obtain the token through the `PaymentServiceDelegate.register(with:)` callback of `PaymentServiceDelegate`. + /// The unique identifier of the store that you want to process transactions for. + [JsonConstructor] + public CreateSessionRequest(string merchantAccount, string setupToken, Option store = default) + { + MerchantAccount = merchantAccount; + SetupToken = setupToken; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateSessionRequest() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of your merchant account. + /// + /// The unique identifier of your merchant account. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The setup token provided by the POS Mobile SDK. - When using the Android POS Mobile SDK, obtain the token through the `AuthenticationService.authenticate(setupToken)` callback of `AuthenticationService`. - When using the iOS POS Mobile SDK, obtain the token through the `PaymentServiceDelegate.register(with:)` callback of `PaymentServiceDelegate`. + /// + /// The setup token provided by the POS Mobile SDK. - When using the Android POS Mobile SDK, obtain the token through the `AuthenticationService.authenticate(setupToken)` callback of `AuthenticationService`. - When using the iOS POS Mobile SDK, obtain the token through the `PaymentServiceDelegate.register(with:)` callback of `PaymentServiceDelegate`. + [JsonPropertyName("setupToken")] + public string SetupToken { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The unique identifier of the store that you want to process transactions for. + /// + /// The unique identifier of the store that you want to process transactions for. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateSessionRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" SetupToken: ").Append(SetupToken).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // SetupToken (string) maxLength + if (this.SetupToken != null && this.SetupToken.Length > 50000) + { + yield return new ValidationResult("Invalid value for SetupToken, length must be less than 50000.", new [] { "SetupToken" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateSessionRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateSessionRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option setupToken = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "setupToken": + setupToken = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CreateSessionRequest.", nameof(merchantAccount)); + + if (!setupToken.IsSet) + throw new ArgumentException("Property is required for class CreateSessionRequest.", nameof(setupToken)); + + return new CreateSessionRequest(merchantAccount.Value!, setupToken.Value!, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateSessionRequest createSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createSessionRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateSessionRequest createSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createSessionRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", createSessionRequest.MerchantAccount); + + if (createSessionRequest.SetupToken != null) + writer.WriteString("setupToken", createSessionRequest.SetupToken); + + if (createSessionRequest._StoreOption.IsSet) + if (createSessionRequest.Store != null) + writer.WriteString("store", createSessionRequest.Store); + } + } +} diff --git a/Adyen/PosMobile/Models/CreateSessionResponse.cs b/Adyen/PosMobile/Models/CreateSessionResponse.cs new file mode 100644 index 000000000..9e89547e4 --- /dev/null +++ b/Adyen/PosMobile/Models/CreateSessionResponse.cs @@ -0,0 +1,277 @@ +// +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.PosMobile.Client; + +namespace Adyen.PosMobile.Models +{ + /// + /// CreateSessionResponse. + /// + public partial class CreateSessionResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the session. + /// The unique identifier of the SDK installation. If you create the [Terminal API](https://docs.adyen.com/point-of-sale/design-your-integration/terminal-api/) transaction request on your backend, use this as the `POIID` in the `MessageHeader` of the request. + /// The unique identifier of your merchant account. + /// The data that the SDK uses to authenticate responses from the Adyen payments platform. Pass this value to your POS app. + /// The unique identifier of the store that you want to process transactions for. + [JsonConstructor] + public CreateSessionResponse(Option id = default, Option installationId = default, Option merchantAccount = default, Option sdkData = default, Option store = default) + { + _IdOption = id; + _InstallationIdOption = installationId; + _MerchantAccountOption = merchantAccount; + _SdkDataOption = sdkData; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreateSessionResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the session. + /// + /// The unique identifier of the session. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstallationIdOption { get; private set; } + + /// + /// The unique identifier of the SDK installation. If you create the [Terminal API](https://docs.adyen.com/point-of-sale/design-your-integration/terminal-api/) transaction request on your backend, use this as the `POIID` in the `MessageHeader` of the request. + /// + /// The unique identifier of the SDK installation. If you create the [Terminal API](https://docs.adyen.com/point-of-sale/design-your-integration/terminal-api/) transaction request on your backend, use this as the `POIID` in the `MessageHeader` of the request. + [JsonPropertyName("installationId")] + public string? InstallationId { get { return this._InstallationIdOption; } set { this._InstallationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountOption { get; private set; } + + /// + /// The unique identifier of your merchant account. + /// + /// The unique identifier of your merchant account. + [JsonPropertyName("merchantAccount")] + public string? MerchantAccount { get { return this._MerchantAccountOption; } set { this._MerchantAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SdkDataOption { get; private set; } + + /// + /// The data that the SDK uses to authenticate responses from the Adyen payments platform. Pass this value to your POS app. + /// + /// The data that the SDK uses to authenticate responses from the Adyen payments platform. Pass this value to your POS app. + [JsonPropertyName("sdkData")] + public string? SdkData { get { return this._SdkDataOption; } set { this._SdkDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The unique identifier of the store that you want to process transactions for. + /// + /// The unique identifier of the store that you want to process transactions for. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreateSessionResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" InstallationId: ").Append(InstallationId).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" SdkData: ").Append(SdkData).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreateSessionResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreateSessionResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option installationId = default; + Option merchantAccount = default; + Option sdkData = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "installationId": + installationId = new Option(utf8JsonReader.GetString()!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "sdkData": + sdkData = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CreateSessionResponse(id, installationId, merchantAccount, sdkData, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreateSessionResponse createSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createSessionResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreateSessionResponse createSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (createSessionResponse._IdOption.IsSet) + if (createSessionResponse.Id != null) + writer.WriteString("id", createSessionResponse.Id); + + if (createSessionResponse._InstallationIdOption.IsSet) + if (createSessionResponse.InstallationId != null) + writer.WriteString("installationId", createSessionResponse.InstallationId); + + if (createSessionResponse._MerchantAccountOption.IsSet) + if (createSessionResponse.MerchantAccount != null) + writer.WriteString("merchantAccount", createSessionResponse.MerchantAccount); + + if (createSessionResponse._SdkDataOption.IsSet) + if (createSessionResponse.SdkData != null) + writer.WriteString("sdkData", createSessionResponse.SdkData); + + if (createSessionResponse._StoreOption.IsSet) + if (createSessionResponse.Store != null) + writer.WriteString("store", createSessionResponse.Store); + } + } +} diff --git a/Adyen/PosMobile/Services/PosMobileService.cs b/Adyen/PosMobile/Services/PosMobileService.cs new file mode 100644 index 000000000..a385c6021 --- /dev/null +++ b/Adyen/PosMobile/Services/PosMobileService.cs @@ -0,0 +1,321 @@ +// +/* + * POS Mobile API + * + * The POS Mobile API is used in the mutual authentication flow between an Adyen Android or iOS [POS Mobile SDK](https://docs.adyen.com/point-of-sale/ipp-mobile/) and the Adyen payments platform. The POS Mobile SDK for Android or iOS devices enables businesses to accept in-person payments using a commercial off-the-shelf (COTS) device like a phone. For example, Tap to Pay transactions, or transactions on a mobile device in combination with a card reader. ## Authentication Each request to the POS Mobile API must be signed with an API key. [Generate your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) in the Customer Area and then set this key to the `X-API-Key` header value. You also need to have a [client key](https://docs.adyen.com/development-resources/client-side-authentication/). The client key is part of the setup but you won't need to use it in your integration later. Therefore, you don't need to specify allowed origins, and you don't need to store the key in your system. To access the live endpoints, you need to generate a new API key and client key in your live Customer Area. ## Versioning The POS Mobile API handles versioning as part of the endpoint URL. For example: ``` https://checkout-test.adyen.com/checkout/possdk/v68/sessions ``` ## Going live To access the live endpoints, you need an API key and client key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/possdk/v68/sessions ``` + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.PosMobile.Client; +using Adyen.PosMobile.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.PosMobile.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IPosMobileService : IAdyenApiService + { + /// + /// The class containing the events. + /// + PosMobileServiceEvents Events { get; } + + /// + /// Create a communication session + /// + /// + /// Establishes a secure communications session between the POS Mobile SDK and the Adyen payments platform, through mutual authentication. The request sends a setup token that identifies the SDK and the device. The response returns a session token that the SDK can use to authenticate responses received from the Adyen payments platform. >This request applies to **mobile in-person** transactions. You cannot use this request to create online payments sessions. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateCommunicationSessionAsync(CreateSessionRequest createSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateCommunicationSessionApiResponse : Adyen.Core.Client.IApiResponse, ICreated + { + /// + /// Returns true if the response is 201 Created. + /// + /// + bool IsCreated { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class PosMobileServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateCommunicationSession; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateCommunicationSession; + + internal void ExecuteOnCreateCommunicationSession(PosMobileService.CreateCommunicationSessionApiResponse apiResponse) + { + OnCreateCommunicationSession?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateCommunicationSession(Exception exception) + { + OnErrorCreateCommunicationSession?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class PosMobileService : IPosMobileService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public PosMobileServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public PosMobileService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, PosMobileServiceEvents posMobileServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = posMobileServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a communication session Establishes a secure communications session between the POS Mobile SDK and the Adyen payments platform, through mutual authentication. The request sends a setup token that identifies the SDK and the device. The response returns a session token that the SDK can use to authenticate responses received from the Adyen payments platform. >This request applies to **mobile in-person** transactions. You cannot use this request to create online payments sessions. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateCommunicationSessionAsync(CreateSessionRequest createSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/sessions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/sessions"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createSessionRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createSessionRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateCommunicationSessionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/sessions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateCommunicationSession(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateCommunicationSession(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateCommunicationSessionApiResponse : Adyen.Core.Client.ApiResponse, ICreateCommunicationSessionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateCommunicationSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateCommunicationSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created. + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created. + /// + /// + public Adyen.PosMobile.Models.CreateSessionResponse? Created() + { + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeCreatedResponse([NotNullWhen(true)]out Adyen.PosMobile.Models.CreateSessionResponse? result) + { + result = null; + + try + { + result = Created(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)201); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Recurring/Client/ApiKeyToken.cs b/Adyen/Recurring/Client/ApiKeyToken.cs new file mode 100644 index 000000000..3e1a71079 --- /dev/null +++ b/Adyen/Recurring/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Recurring.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Recurring/Client/ClientUtils.cs b/Adyen/Recurring/Client/ClientUtils.cs new file mode 100644 index 000000000..fc6a0f73e --- /dev/null +++ b/Adyen/Recurring/Client/ClientUtils.cs @@ -0,0 +1,317 @@ +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Recurring.Models; +using Models = Adyen.Recurring.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Recurring.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.Recurring.ContractEnum recurringContractEnum) + return Models.Recurring.ContractEnum.ToJsonValue(recurringContractEnum); + if (obj is Models.Recurring.TokenServiceEnum recurringTokenServiceEnum) + return Models.Recurring.TokenServiceEnum.ToJsonValue(recurringTokenServiceEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Recurring/Client/HostConfiguration.cs b/Adyen/Recurring/Client/HostConfiguration.cs new file mode 100644 index 000000000..6644487f8 --- /dev/null +++ b/Adyen/Recurring/Client/HostConfiguration.cs @@ -0,0 +1,153 @@ +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Recurring.Services; +using Adyen.Recurring.Client; +using Adyen.Recurring.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Recurring.Client +{ + /// + /// Provides hosting configuration for Recurring + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/Recurring/v68"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CreatePermitRequestJsonConverter()); + _jsonOptions.Converters.Add(new CreatePermitResultJsonConverter()); + _jsonOptions.Converters.Add(new DisablePermitRequestJsonConverter()); + _jsonOptions.Converters.Add(new DisablePermitResultJsonConverter()); + _jsonOptions.Converters.Add(new DisableRequestJsonConverter()); + _jsonOptions.Converters.Add(new DisableResultJsonConverter()); + _jsonOptions.Converters.Add(new NameJsonConverter()); + _jsonOptions.Converters.Add(new NotifyShopperRequestJsonConverter()); + _jsonOptions.Converters.Add(new NotifyShopperResultJsonConverter()); + _jsonOptions.Converters.Add(new PermitJsonConverter()); + _jsonOptions.Converters.Add(new PermitRestrictionJsonConverter()); + _jsonOptions.Converters.Add(new PermitResultJsonConverter()); + _jsonOptions.Converters.Add(new RecurringJsonConverter()); + _jsonOptions.Converters.Add(new RecurringDetailJsonConverter()); + _jsonOptions.Converters.Add(new RecurringDetailWrapperJsonConverter()); + _jsonOptions.Converters.Add(new RecurringDetailsRequestJsonConverter()); + _jsonOptions.Converters.Add(new RecurringDetailsResultJsonConverter()); + _jsonOptions.Converters.Add(new ScheduleAccountUpdaterRequestJsonConverter()); + _jsonOptions.Converters.Add(new ScheduleAccountUpdaterResultJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new TokenDetailsJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddRecurringHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Recurring/Client/JsonSerializerOptionsProvider.cs b/Adyen/Recurring/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..1cdd13803 --- /dev/null +++ b/Adyen/Recurring/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Recurring.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Recurring/Extensions/HostBuilderExtensions.cs b/Adyen/Recurring/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..663a017a8 --- /dev/null +++ b/Adyen/Recurring/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Recurring; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Recurring API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureRecurring(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddRecurringHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Recurring/Extensions/ServiceCollectionExtensions.cs b/Adyen/Recurring/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..40a798350 --- /dev/null +++ b/Adyen/Recurring/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Recurring API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddRecurringServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddRecurringHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Recurring/Models/Address.cs b/Adyen/Recurring/Models/Address.cs new file mode 100644 index 000000000..a0d13176c --- /dev/null +++ b/Adyen/Recurring/Models/Address.cs @@ -0,0 +1,294 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the city. Maximum length: 3000 characters. + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// The number or name of the house. Maximum length: 3000 characters. + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string city, string country, string houseNumberOrName, string postalCode, string street, Option stateOrProvince = default) + { + City = city; + Country = country; + HouseNumberOrName = houseNumberOrName; + PostalCode = postalCode; + Street = street; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The name of the city. Maximum length: 3000 characters. + /// + /// The name of the city. Maximum length: 3000 characters. + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + /// + /// The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don't know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// The number or name of the house. Maximum length: 3000 characters. + /// + /// The number or name of the house. Maximum length: 3000 characters. + [JsonPropertyName("houseNumberOrName")] + public string HouseNumberOrName { get; set; } + + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + /// + /// A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. + [JsonPropertyName("postalCode")] + public string PostalCode { get; set; } + + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + /// + /// The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) maxLength + if (this.City != null && this.City.Length > 3000) + { + yield return new ValidationResult("Invalid value for City, length must be less than 3000.", new [] { "City" }); + } + + // HouseNumberOrName (string) maxLength + if (this.HouseNumberOrName != null && this.HouseNumberOrName.Length > 3000) + { + yield return new ValidationResult("Invalid value for HouseNumberOrName, length must be less than 3000.", new [] { "HouseNumberOrName" }); + } + + // Street (string) maxLength + if (this.Street != null && this.Street.Length > 3000) + { + yield return new ValidationResult("Invalid value for Street, length must be less than 3000.", new [] { "Street" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option houseNumberOrName = default; + Option postalCode = default; + Option street = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "houseNumberOrName": + houseNumberOrName = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!city.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(city)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + if (!houseNumberOrName.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(houseNumberOrName)); + + if (!postalCode.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(postalCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(street)); + + return new Address(city.Value!, country.Value!, houseNumberOrName.Value!, postalCode.Value!, street.Value!, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.City != null) + writer.WriteString("city", address.City); + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address.HouseNumberOrName != null) + writer.WriteString("houseNumberOrName", address.HouseNumberOrName); + + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address.Street != null) + writer.WriteString("street", address.Street); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/Recurring/Models/Amount.cs b/Adyen/Recurring/Models/Amount.cs new file mode 100644 index 000000000..bf2fc7a0b --- /dev/null +++ b/Adyen/Recurring/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Recurring/Models/BankAccount.cs b/Adyen/Recurring/Models/BankAccount.cs new file mode 100644 index 000000000..3d88e6174 --- /dev/null +++ b/Adyen/Recurring/Models/BankAccount.cs @@ -0,0 +1,377 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// BankAccount. + /// + public partial class BankAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number (without separators). + /// The bank city. + /// The location id of the bank. The field value is `nil` in most cases. + /// The name of the bank. + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// The bank account holder's tax ID. + [JsonConstructor] + public BankAccount(Option bankAccountNumber = default, Option bankCity = default, Option bankLocationId = default, Option bankName = default, Option bic = default, Option countryCode = default, Option iban = default, Option ownerName = default, Option taxId = default) + { + _BankAccountNumberOption = bankAccountNumber; + _BankCityOption = bankCity; + _BankLocationIdOption = bankLocationId; + _BankNameOption = bankName; + _BicOption = bic; + _CountryCodeOption = countryCode; + _IbanOption = iban; + _OwnerNameOption = ownerName; + _TaxIdOption = taxId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccount() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountNumberOption { get; private set; } + + /// + /// The bank account number (without separators). + /// + /// The bank account number (without separators). + [JsonPropertyName("bankAccountNumber")] + public string? BankAccountNumber { get { return this._BankAccountNumberOption; } set { this._BankAccountNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankCityOption { get; private set; } + + /// + /// The bank city. + /// + /// The bank city. + [JsonPropertyName("bankCity")] + public string? BankCity { get { return this._BankCityOption; } set { this._BankCityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankLocationIdOption { get; private set; } + + /// + /// The location id of the bank. The field value is `nil` in most cases. + /// + /// The location id of the bank. The field value is `nil` in most cases. + [JsonPropertyName("bankLocationId")] + public string? BankLocationId { get { return this._BankLocationIdOption; } set { this._BankLocationIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankNameOption { get; private set; } + + /// + /// The name of the bank. + /// + /// The name of the bank. + [JsonPropertyName("bankName")] + public string? BankName { get { return this._BankNameOption; } set { this._BankNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BicOption { get; private set; } + + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + /// + /// The [Business Identifier Code](https://en.wikipedia.org/wiki/ISO_9362) (BIC) is the SWIFT address assigned to a bank. The field value is `nil` in most cases. + [JsonPropertyName("bic")] + public string? Bic { get { return this._BicOption; } set { this._BicOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryCodeOption { get; private set; } + + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + /// + /// Country code where the bank is located. A valid value is an ISO two-character country code (e.g. 'NL'). + [JsonPropertyName("countryCode")] + public string? CountryCode { get { return this._CountryCodeOption; } set { this._CountryCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IbanOption { get; private set; } + + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + /// + /// The [International Bank Account Number](https://en.wikipedia.org/wiki/International_Bank_Account_Number) (IBAN). + [JsonPropertyName("iban")] + public string? Iban { get { return this._IbanOption; } set { this._IbanOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OwnerNameOption { get; private set; } + + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + /// + /// The name of the bank account holder. If you submit a name with non-Latin characters, we automatically replace some of them with corresponding Latin characters to meet the FATF recommendations. For example: * χ12 is converted to ch12. * üA is converted to euA. * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'. After replacement, the ownerName must have at least three alphanumeric characters (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character (A-Z, a-z). For example: * John17 - allowed. * J17 - allowed. * 171 - not allowed. * John-7 - allowed. > If provided details don't match the required format, the response returns the error message: 203 'Invalid bank account holder name'. + [JsonPropertyName("ownerName")] + public string? OwnerName { get { return this._OwnerNameOption; } set { this._OwnerNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TaxIdOption { get; private set; } + + /// + /// The bank account holder's tax ID. + /// + /// The bank account holder's tax ID. + [JsonPropertyName("taxId")] + public string? TaxId { get { return this._TaxIdOption; } set { this._TaxIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccount {\n"); + sb.Append(" BankAccountNumber: ").Append(BankAccountNumber).Append("\n"); + sb.Append(" BankCity: ").Append(BankCity).Append("\n"); + sb.Append(" BankLocationId: ").Append(BankLocationId).Append("\n"); + sb.Append(" BankName: ").Append(BankName).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); + sb.Append(" TaxId: ").Append(TaxId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option bankAccountNumber = default; + Option bankCity = default; + Option bankLocationId = default; + Option bankName = default; + Option bic = default; + Option countryCode = default; + Option iban = default; + Option ownerName = default; + Option taxId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "bankAccountNumber": + bankAccountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCity": + bankCity = new Option(utf8JsonReader.GetString()!); + break; + case "bankLocationId": + bankLocationId = new Option(utf8JsonReader.GetString()!); + break; + case "bankName": + bankName = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "countryCode": + countryCode = new Option(utf8JsonReader.GetString()!); + break; + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "ownerName": + ownerName = new Option(utf8JsonReader.GetString()!); + break; + case "taxId": + taxId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BankAccount(bankAccountNumber, bankCity, bankLocationId, bankName, bic, countryCode, iban, ownerName, taxId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccount bankAccount, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankAccount._BankAccountNumberOption.IsSet) + if (bankAccount.BankAccountNumber != null) + writer.WriteString("bankAccountNumber", bankAccount.BankAccountNumber); + + if (bankAccount._BankCityOption.IsSet) + if (bankAccount.BankCity != null) + writer.WriteString("bankCity", bankAccount.BankCity); + + if (bankAccount._BankLocationIdOption.IsSet) + if (bankAccount.BankLocationId != null) + writer.WriteString("bankLocationId", bankAccount.BankLocationId); + + if (bankAccount._BankNameOption.IsSet) + if (bankAccount.BankName != null) + writer.WriteString("bankName", bankAccount.BankName); + + if (bankAccount._BicOption.IsSet) + if (bankAccount.Bic != null) + writer.WriteString("bic", bankAccount.Bic); + + if (bankAccount._CountryCodeOption.IsSet) + if (bankAccount.CountryCode != null) + writer.WriteString("countryCode", bankAccount.CountryCode); + + if (bankAccount._IbanOption.IsSet) + if (bankAccount.Iban != null) + writer.WriteString("iban", bankAccount.Iban); + + if (bankAccount._OwnerNameOption.IsSet) + if (bankAccount.OwnerName != null) + writer.WriteString("ownerName", bankAccount.OwnerName); + + if (bankAccount._TaxIdOption.IsSet) + if (bankAccount.TaxId != null) + writer.WriteString("taxId", bankAccount.TaxId); + } + } +} diff --git a/Adyen/Recurring/Models/Card.cs b/Adyen/Recurring/Models/Card.cs new file mode 100644 index 000000000..ca0eb0c24 --- /dev/null +++ b/Adyen/Recurring/Models/Card.cs @@ -0,0 +1,448 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// The card expiry year. Format: 4 digits. For example: 2020 + /// The name of the cardholder, as printed on the card. + /// The issue number of the card (for some UK debit cards only). + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// The month component of the start date (for some UK debit cards only). + /// The year component of the start date (for some UK debit cards only). + [JsonConstructor] + public Card(Option cvc = default, Option expiryMonth = default, Option expiryYear = default, Option holderName = default, Option issueNumber = default, Option number = default, Option startMonth = default, Option startYear = default) + { + _CvcOption = cvc; + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _HolderNameOption = holderName; + _IssueNumberOption = issueNumber; + _NumberOption = number; + _StartMonthOption = startMonth; + _StartYearOption = startYear; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CvcOption { get; private set; } + + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + /// + /// The [card verification code](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid) (1-20 characters). Depending on the card brand, it is known also as: * CVV2/CVC2 – length: 3 digits * CID – length: 4 digits > If you are using [Client-Side Encryption](https://docs.adyen.com/classic-integration/cse-integration-ecommerce), the CVC code is present in the encrypted data. You must never post the card details to the server. > This field must be always present in a [one-click payment request](https://docs.adyen.com/classic-integration/recurring-payments). > When this value is returned in a response, it is always empty because it is not stored. + [JsonPropertyName("cvc")] + public string? Cvc { get { return this._CvcOption; } set { this._CvcOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + /// + /// The card expiry month. Format: 2 digits, zero-padded for single digits. For example: * 03 = March * 11 = November + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + /// + /// The card expiry year. Format: 4 digits. For example: 2020 + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HolderNameOption { get; private set; } + + /// + /// The name of the cardholder, as printed on the card. + /// + /// The name of the cardholder, as printed on the card. + [JsonPropertyName("holderName")] + public string? HolderName { get { return this._HolderNameOption; } set { this._HolderNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueNumberOption { get; private set; } + + /// + /// The issue number of the card (for some UK debit cards only). + /// + /// The issue number of the card (for some UK debit cards only). + [JsonPropertyName("issueNumber")] + public string? IssueNumber { get { return this._IssueNumberOption; } set { this._IssueNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + /// + /// The card number (4-19 characters). Do not use any separators. When this value is returned in a response, only the last 4 digits of the card number are returned. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartMonthOption { get; private set; } + + /// + /// The month component of the start date (for some UK debit cards only). + /// + /// The month component of the start date (for some UK debit cards only). + [JsonPropertyName("startMonth")] + public string? StartMonth { get { return this._StartMonthOption; } set { this._StartMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartYearOption { get; private set; } + + /// + /// The year component of the start date (for some UK debit cards only). + /// + /// The year component of the start date (for some UK debit cards only). + [JsonPropertyName("startYear")] + public string? StartYear { get { return this._StartYearOption; } set { this._StartYearOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" Cvc: ").Append(Cvc).Append("\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" HolderName: ").Append(HolderName).Append("\n"); + sb.Append(" IssueNumber: ").Append(IssueNumber).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" StartMonth: ").Append(StartMonth).Append("\n"); + sb.Append(" StartYear: ").Append(StartYear).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Cvc (string) maxLength + if (this.Cvc != null && this.Cvc.Length > 20) + { + yield return new ValidationResult("Invalid value for Cvc, length must be less than 20.", new [] { "Cvc" }); + } + + // Cvc (string) minLength + if (this.Cvc != null && this.Cvc.Length < 1) + { + yield return new ValidationResult("Invalid value for Cvc, length must be greater than 1.", new [] { "Cvc" }); + } + + // ExpiryMonth (string) maxLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be less than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryMonth (string) minLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be greater than 1.", new [] { "ExpiryMonth" }); + } + + // ExpiryYear (string) maxLength + if (this.ExpiryYear != null && this.ExpiryYear.Length > 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be less than 4.", new [] { "ExpiryYear" }); + } + + // ExpiryYear (string) minLength + if (this.ExpiryYear != null && this.ExpiryYear.Length < 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be greater than 4.", new [] { "ExpiryYear" }); + } + + // HolderName (string) maxLength + if (this.HolderName != null && this.HolderName.Length > 50) + { + yield return new ValidationResult("Invalid value for HolderName, length must be less than 50.", new [] { "HolderName" }); + } + + // HolderName (string) minLength + if (this.HolderName != null && this.HolderName.Length < 1) + { + yield return new ValidationResult("Invalid value for HolderName, length must be greater than 1.", new [] { "HolderName" }); + } + + // IssueNumber (string) maxLength + if (this.IssueNumber != null && this.IssueNumber.Length > 2) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be less than 2.", new [] { "IssueNumber" }); + } + + // IssueNumber (string) minLength + if (this.IssueNumber != null && this.IssueNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be greater than 1.", new [] { "IssueNumber" }); + } + + // Number (string) maxLength + if (this.Number != null && this.Number.Length > 19) + { + yield return new ValidationResult("Invalid value for Number, length must be less than 19.", new [] { "Number" }); + } + + // Number (string) minLength + if (this.Number != null && this.Number.Length < 4) + { + yield return new ValidationResult("Invalid value for Number, length must be greater than 4.", new [] { "Number" }); + } + + // StartMonth (string) maxLength + if (this.StartMonth != null && this.StartMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be less than 2.", new [] { "StartMonth" }); + } + + // StartMonth (string) minLength + if (this.StartMonth != null && this.StartMonth.Length < 1) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be greater than 1.", new [] { "StartMonth" }); + } + + // StartYear (string) maxLength + if (this.StartYear != null && this.StartYear.Length > 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be less than 4.", new [] { "StartYear" }); + } + + // StartYear (string) minLength + if (this.StartYear != null && this.StartYear.Length < 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be greater than 4.", new [] { "StartYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cvc = default; + Option expiryMonth = default; + Option expiryYear = default; + Option holderName = default; + Option issueNumber = default; + Option number = default; + Option startMonth = default; + Option startYear = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cvc": + cvc = new Option(utf8JsonReader.GetString()!); + break; + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "holderName": + holderName = new Option(utf8JsonReader.GetString()!); + break; + case "issueNumber": + issueNumber = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "startMonth": + startMonth = new Option(utf8JsonReader.GetString()!); + break; + case "startYear": + startYear = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Card(cvc, expiryMonth, expiryYear, holderName, issueNumber, number, startMonth, startYear); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + if (card._CvcOption.IsSet) + if (card.Cvc != null) + writer.WriteString("cvc", card.Cvc); + + if (card._ExpiryMonthOption.IsSet) + if (card.ExpiryMonth != null) + writer.WriteString("expiryMonth", card.ExpiryMonth); + + if (card._ExpiryYearOption.IsSet) + if (card.ExpiryYear != null) + writer.WriteString("expiryYear", card.ExpiryYear); + + if (card._HolderNameOption.IsSet) + if (card.HolderName != null) + writer.WriteString("holderName", card.HolderName); + + if (card._IssueNumberOption.IsSet) + if (card.IssueNumber != null) + writer.WriteString("issueNumber", card.IssueNumber); + + if (card._NumberOption.IsSet) + if (card.Number != null) + writer.WriteString("number", card.Number); + + if (card._StartMonthOption.IsSet) + if (card.StartMonth != null) + writer.WriteString("startMonth", card.StartMonth); + + if (card._StartYearOption.IsSet) + if (card.StartYear != null) + writer.WriteString("startYear", card.StartYear); + } + } +} diff --git a/Adyen/Recurring/Models/CreatePermitRequest.cs b/Adyen/Recurring/Models/CreatePermitRequest.cs new file mode 100644 index 000000000..a3f26d11e --- /dev/null +++ b/Adyen/Recurring/Models/CreatePermitRequest.cs @@ -0,0 +1,230 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// CreatePermitRequest. + /// + public partial class CreatePermitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The permits to create for this recurring contract. + /// The recurring contract the new permits will use. + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + [JsonConstructor] + public CreatePermitRequest(string merchantAccount, List permits, string recurringDetailReference, string shopperReference) + { + MerchantAccount = merchantAccount; + Permits = permits; + RecurringDetailReference = recurringDetailReference; + ShopperReference = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreatePermitRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The permits to create for this recurring contract. + /// + /// The permits to create for this recurring contract. + [JsonPropertyName("permits")] + public List Permits { get; set; } + + /// + /// The recurring contract the new permits will use. + /// + /// The recurring contract the new permits will use. + [JsonPropertyName("recurringDetailReference")] + public string RecurringDetailReference { get; set; } + + /// + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + /// + /// The shopper's reference to uniquely identify this shopper (e.g. user ID or account ID). + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreatePermitRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Permits: ").Append(Permits).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreatePermitRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreatePermitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> permits = default; + Option recurringDetailReference = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "permits": + permits = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class CreatePermitRequest.", nameof(merchantAccount)); + + if (!permits.IsSet) + throw new ArgumentException("Property is required for class CreatePermitRequest.", nameof(permits)); + + if (!recurringDetailReference.IsSet) + throw new ArgumentException("Property is required for class CreatePermitRequest.", nameof(recurringDetailReference)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class CreatePermitRequest.", nameof(shopperReference)); + + return new CreatePermitRequest(merchantAccount.Value!, permits.Value!, recurringDetailReference.Value!, shopperReference.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreatePermitRequest createPermitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createPermitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreatePermitRequest createPermitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (createPermitRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", createPermitRequest.MerchantAccount); + + writer.WritePropertyName("permits"); + JsonSerializer.Serialize(writer, createPermitRequest.Permits, jsonSerializerOptions); + if (createPermitRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", createPermitRequest.RecurringDetailReference); + + if (createPermitRequest.ShopperReference != null) + writer.WriteString("shopperReference", createPermitRequest.ShopperReference); + } + } +} diff --git a/Adyen/Recurring/Models/CreatePermitResult.cs b/Adyen/Recurring/Models/CreatePermitResult.cs new file mode 100644 index 000000000..68d9d61e3 --- /dev/null +++ b/Adyen/Recurring/Models/CreatePermitResult.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// CreatePermitResult. + /// + public partial class CreatePermitResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// List of new permits. + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + [JsonConstructor] + public CreatePermitResult(Option?> permitResultList = default, Option pspReference = default) + { + _PermitResultListOption = permitResultList; + _PspReferenceOption = pspReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CreatePermitResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PermitResultListOption { get; private set; } + + /// + /// List of new permits. + /// + /// List of new permits. + [JsonPropertyName("permitResultList")] + public List? PermitResultList { get { return this._PermitResultListOption; } set { this._PermitResultListOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + /// + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CreatePermitResult {\n"); + sb.Append(" PermitResultList: ").Append(PermitResultList).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CreatePermitResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CreatePermitResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> permitResultList = default; + Option pspReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "permitResultList": + permitResultList = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CreatePermitResult(permitResultList, pspReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CreatePermitResult createPermitResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, createPermitResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CreatePermitResult createPermitResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (createPermitResult._PermitResultListOption.IsSet) + { + writer.WritePropertyName("permitResultList"); + JsonSerializer.Serialize(writer, createPermitResult.PermitResultList, jsonSerializerOptions); + } + if (createPermitResult._PspReferenceOption.IsSet) + if (createPermitResult.PspReference != null) + writer.WriteString("pspReference", createPermitResult.PspReference); + } + } +} diff --git a/Adyen/Recurring/Models/DisablePermitRequest.cs b/Adyen/Recurring/Models/DisablePermitRequest.cs new file mode 100644 index 000000000..d8b9974a9 --- /dev/null +++ b/Adyen/Recurring/Models/DisablePermitRequest.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// DisablePermitRequest. + /// + public partial class DisablePermitRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The permit token to disable. + [JsonConstructor] + public DisablePermitRequest(string merchantAccount, string token) + { + MerchantAccount = merchantAccount; + Token = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisablePermitRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The permit token to disable. + /// + /// The permit token to disable. + [JsonPropertyName("token")] + public string Token { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisablePermitRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisablePermitRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisablePermitRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class DisablePermitRequest.", nameof(merchantAccount)); + + if (!token.IsSet) + throw new ArgumentException("Property is required for class DisablePermitRequest.", nameof(token)); + + return new DisablePermitRequest(merchantAccount.Value!, token.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisablePermitRequest disablePermitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disablePermitRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisablePermitRequest disablePermitRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (disablePermitRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", disablePermitRequest.MerchantAccount); + + if (disablePermitRequest.Token != null) + writer.WriteString("token", disablePermitRequest.Token); + } + } +} diff --git a/Adyen/Recurring/Models/DisablePermitResult.cs b/Adyen/Recurring/Models/DisablePermitResult.cs new file mode 100644 index 000000000..1b23d5fb1 --- /dev/null +++ b/Adyen/Recurring/Models/DisablePermitResult.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// DisablePermitResult. + /// + public partial class DisablePermitResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + /// Status of the disable request. + [JsonConstructor] + public DisablePermitResult(Option pspReference = default, Option status = default) + { + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisablePermitResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + /// + /// A unique reference associated with the request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// Status of the disable request. + /// + /// Status of the disable request. + [JsonPropertyName("status")] + public string? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisablePermitResult {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisablePermitResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisablePermitResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DisablePermitResult(pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisablePermitResult disablePermitResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disablePermitResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisablePermitResult disablePermitResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (disablePermitResult._PspReferenceOption.IsSet) + if (disablePermitResult.PspReference != null) + writer.WriteString("pspReference", disablePermitResult.PspReference); + + if (disablePermitResult._StatusOption.IsSet) + if (disablePermitResult.Status != null) + writer.WriteString("status", disablePermitResult.Status); + } + } +} diff --git a/Adyen/Recurring/Models/DisableRequest.cs b/Adyen/Recurring/Models/DisableRequest.cs new file mode 100644 index 000000000..6d3d91563 --- /dev/null +++ b/Adyen/Recurring/Models/DisableRequest.cs @@ -0,0 +1,241 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// DisableRequest. + /// + public partial class DisableRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier with which you want to process the transaction. + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + /// Specify the contract if you only want to disable a specific use. This field can be set to one of the following values, or to their combination (comma-separated): * ONECLICK * RECURRING * PAYOUT + /// The ID that uniquely identifies the recurring detail reference. If it is not provided, the whole recurring contract of the `shopperReference` will be disabled, which includes all recurring details. + [JsonConstructor] + public DisableRequest(string merchantAccount, string shopperReference, Option contract = default, Option recurringDetailReference = default) + { + MerchantAccount = merchantAccount; + ShopperReference = shopperReference; + _ContractOption = contract; + _RecurringDetailReferenceOption = recurringDetailReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisableRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier with which you want to process the transaction. + /// + /// The merchant account identifier with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + /// + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// Specify the contract if you only want to disable a specific use. This field can be set to one of the following values, or to their combination (comma-separated): * ONECLICK * RECURRING * PAYOUT + /// + /// Specify the contract if you only want to disable a specific use. This field can be set to one of the following values, or to their combination (comma-separated): * ONECLICK * RECURRING * PAYOUT + [JsonPropertyName("contract")] + public string? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// The ID that uniquely identifies the recurring detail reference. If it is not provided, the whole recurring contract of the `shopperReference` will be disabled, which includes all recurring details. + /// + /// The ID that uniquely identifies the recurring detail reference. If it is not provided, the whole recurring contract of the `shopperReference` will be disabled, which includes all recurring details. + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisableRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisableRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisableRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option shopperReference = default; + Option contract = default; + Option recurringDetailReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "contract": + contract = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class DisableRequest.", nameof(merchantAccount)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class DisableRequest.", nameof(shopperReference)); + + return new DisableRequest(merchantAccount.Value!, shopperReference.Value!, contract, recurringDetailReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisableRequest disableRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disableRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisableRequest disableRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (disableRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", disableRequest.MerchantAccount); + + if (disableRequest.ShopperReference != null) + writer.WriteString("shopperReference", disableRequest.ShopperReference); + + if (disableRequest._ContractOption.IsSet) + if (disableRequest.Contract != null) + writer.WriteString("contract", disableRequest.Contract); + + if (disableRequest._RecurringDetailReferenceOption.IsSet) + if (disableRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", disableRequest.RecurringDetailReference); + } + } +} diff --git a/Adyen/Recurring/Models/DisableResult.cs b/Adyen/Recurring/Models/DisableResult.cs new file mode 100644 index 000000000..fb8af5dcd --- /dev/null +++ b/Adyen/Recurring/Models/DisableResult.cs @@ -0,0 +1,177 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// DisableResult. + /// + public partial class DisableResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Depending on whether a specific recurring detail was in the request, result is either [detail-successfully-disabled] or [all-details-successfully-disabled]. + [JsonConstructor] + public DisableResult(Option response = default) + { + _ResponseOption = response; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DisableResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseOption { get; private set; } + + /// + /// Depending on whether a specific recurring detail was in the request, result is either [detail-successfully-disabled] or [all-details-successfully-disabled]. + /// + /// Depending on whether a specific recurring detail was in the request, result is either [detail-successfully-disabled] or [all-details-successfully-disabled]. + [JsonPropertyName("response")] + public string? Response { get { return this._ResponseOption; } set { this._ResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DisableResult {\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DisableResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DisableResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option response = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "response": + response = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DisableResult(response); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DisableResult disableResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, disableResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DisableResult disableResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (disableResult._ResponseOption.IsSet) + if (disableResult.Response != null) + writer.WriteString("response", disableResult.Response); + } + } +} diff --git a/Adyen/Recurring/Models/Name.cs b/Adyen/Recurring/Models/Name.cs new file mode 100644 index 000000000..1c999b4a3 --- /dev/null +++ b/Adyen/Recurring/Models/Name.cs @@ -0,0 +1,203 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Name. + /// + public partial class Name : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The first name. + /// The last name. + [JsonConstructor] + public Name(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Name() + { + } + + partial void OnCreated(); + + /// + /// The first name. + /// + /// The first name. + [JsonPropertyName("firstName")] + public string FirstName { get; set; } + + /// + /// The last name. + /// + /// The last name. + [JsonPropertyName("lastName")] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // FirstName (string) maxLength + if (this.FirstName != null && this.FirstName.Length > 80) + { + yield return new ValidationResult("Invalid value for FirstName, length must be less than 80.", new [] { "FirstName" }); + } + + // LastName (string) maxLength + if (this.LastName != null && this.LastName.Length > 80) + { + yield return new ValidationResult("Invalid value for LastName, length must be less than 80.", new [] { "LastName" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option firstName = default; + Option lastName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!firstName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(firstName)); + + if (!lastName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(lastName)); + + return new Name(firstName.Value!, lastName.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, name, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) + { + + if (name.FirstName != null) + writer.WriteString("firstName", name.FirstName); + + if (name.LastName != null) + writer.WriteString("lastName", name.LastName); + } + } +} diff --git a/Adyen/Recurring/Models/NotifyShopperRequest.cs b/Adyen/Recurring/Models/NotifyShopperRequest.cs new file mode 100644 index 000000000..c5ff6eabe --- /dev/null +++ b/Adyen/Recurring/Models/NotifyShopperRequest.cs @@ -0,0 +1,354 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// NotifyShopperRequest. + /// + public partial class NotifyShopperRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier with which you want to process the transaction. + /// Pre-debit notification reference sent by the merchant. This is a mandatory field + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + /// Date on which the subscription amount will be debited from the shopper. In YYYY-MM-DD format + /// Sequence of the debit. Depends on Frequency and Billing Attempts Rule. + /// Reference of Pre-debit notification that is displayed to the shopper. Optional field. Maps to reference if missing + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonConstructor] + public NotifyShopperRequest(Amount amount, string merchantAccount, string reference, string shopperReference, Option billingDate = default, Option billingSequenceNumber = default, Option displayedReference = default, Option recurringDetailReference = default, Option storedPaymentMethodId = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + Reference = reference; + ShopperReference = shopperReference; + _BillingDateOption = billingDate; + _BillingSequenceNumberOption = billingSequenceNumber; + _DisplayedReferenceOption = displayedReference; + _RecurringDetailReferenceOption = recurringDetailReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NotifyShopperRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier with which you want to process the transaction. + /// + /// The merchant account identifier with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// Pre-debit notification reference sent by the merchant. This is a mandatory field + /// + /// Pre-debit notification reference sent by the merchant. This is a mandatory field + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + /// + /// The ID that uniquely identifies the shopper. This `shopperReference` must be the same as the `shopperReference` used in the initial payment. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingDateOption { get; private set; } + + /// + /// Date on which the subscription amount will be debited from the shopper. In YYYY-MM-DD format + /// + /// Date on which the subscription amount will be debited from the shopper. In YYYY-MM-DD format + [JsonPropertyName("billingDate")] + public string? BillingDate { get { return this._BillingDateOption; } set { this._BillingDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingSequenceNumberOption { get; private set; } + + /// + /// Sequence of the debit. Depends on Frequency and Billing Attempts Rule. + /// + /// Sequence of the debit. Depends on Frequency and Billing Attempts Rule. + [JsonPropertyName("billingSequenceNumber")] + public string? BillingSequenceNumber { get { return this._BillingSequenceNumberOption; } set { this._BillingSequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisplayedReferenceOption { get; private set; } + + /// + /// Reference of Pre-debit notification that is displayed to the shopper. Optional field. Maps to reference if missing + /// + /// Reference of Pre-debit notification that is displayed to the shopper. Optional field. Maps to reference if missing + [JsonPropertyName("displayedReference")] + public string? DisplayedReference { get { return this._DisplayedReferenceOption; } set { this._DisplayedReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + /// + /// This is the `recurringDetailReference` returned in the response when you created the token. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NotifyShopperRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" BillingDate: ").Append(BillingDate).Append("\n"); + sb.Append(" BillingSequenceNumber: ").Append(BillingSequenceNumber).Append("\n"); + sb.Append(" DisplayedReference: ").Append(DisplayedReference).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NotifyShopperRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NotifyShopperRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option reference = default; + Option shopperReference = default; + Option billingDate = default; + Option billingSequenceNumber = default; + Option displayedReference = default; + Option recurringDetailReference = default; + Option storedPaymentMethodId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "billingDate": + billingDate = new Option(utf8JsonReader.GetString()!); + break; + case "billingSequenceNumber": + billingSequenceNumber = new Option(utf8JsonReader.GetString()!); + break; + case "displayedReference": + displayedReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class NotifyShopperRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class NotifyShopperRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class NotifyShopperRequest.", nameof(reference)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class NotifyShopperRequest.", nameof(shopperReference)); + + return new NotifyShopperRequest(amount.Value!, merchantAccount.Value!, reference.Value!, shopperReference.Value!, billingDate, billingSequenceNumber, displayedReference, recurringDetailReference, storedPaymentMethodId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NotifyShopperRequest notifyShopperRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, notifyShopperRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NotifyShopperRequest notifyShopperRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, notifyShopperRequest.Amount, jsonSerializerOptions); + if (notifyShopperRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", notifyShopperRequest.MerchantAccount); + + if (notifyShopperRequest.Reference != null) + writer.WriteString("reference", notifyShopperRequest.Reference); + + if (notifyShopperRequest.ShopperReference != null) + writer.WriteString("shopperReference", notifyShopperRequest.ShopperReference); + + if (notifyShopperRequest._BillingDateOption.IsSet) + if (notifyShopperRequest.BillingDate != null) + writer.WriteString("billingDate", notifyShopperRequest.BillingDate); + + if (notifyShopperRequest._BillingSequenceNumberOption.IsSet) + if (notifyShopperRequest.BillingSequenceNumber != null) + writer.WriteString("billingSequenceNumber", notifyShopperRequest.BillingSequenceNumber); + + if (notifyShopperRequest._DisplayedReferenceOption.IsSet) + if (notifyShopperRequest.DisplayedReference != null) + writer.WriteString("displayedReference", notifyShopperRequest.DisplayedReference); + + if (notifyShopperRequest._RecurringDetailReferenceOption.IsSet) + if (notifyShopperRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", notifyShopperRequest.RecurringDetailReference); + + if (notifyShopperRequest._StoredPaymentMethodIdOption.IsSet) + if (notifyShopperRequest.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", notifyShopperRequest.StoredPaymentMethodId); + } + } +} diff --git a/Adyen/Recurring/Models/NotifyShopperResult.cs b/Adyen/Recurring/Models/NotifyShopperResult.cs new file mode 100644 index 000000000..075ab8f88 --- /dev/null +++ b/Adyen/Recurring/Models/NotifyShopperResult.cs @@ -0,0 +1,327 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// NotifyShopperResult. + /// + public partial class NotifyShopperResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Reference of Pre-debit notification that is displayed to the shopper + /// A simple description of the `resultCode`. + /// The unique reference that is associated with the request. + /// Reference of Pre-debit notification sent in my the merchant + /// The code indicating the status of notification. + /// The unique reference for the request sent downstream. + /// This is the recurringDetailReference returned in the response when token was created + [JsonConstructor] + public NotifyShopperResult(Option displayedReference = default, Option message = default, Option pspReference = default, Option reference = default, Option resultCode = default, Option shopperNotificationReference = default, Option storedPaymentMethodId = default) + { + _DisplayedReferenceOption = displayedReference; + _MessageOption = message; + _PspReferenceOption = pspReference; + _ReferenceOption = reference; + _ResultCodeOption = resultCode; + _ShopperNotificationReferenceOption = shopperNotificationReference; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NotifyShopperResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DisplayedReferenceOption { get; private set; } + + /// + /// Reference of Pre-debit notification that is displayed to the shopper + /// + /// Reference of Pre-debit notification that is displayed to the shopper + [JsonPropertyName("displayedReference")] + public string? DisplayedReference { get { return this._DisplayedReferenceOption; } set { this._DisplayedReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A simple description of the `resultCode`. + /// + /// A simple description of the `resultCode`. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The unique reference that is associated with the request. + /// + /// The unique reference that is associated with the request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Reference of Pre-debit notification sent in my the merchant + /// + /// Reference of Pre-debit notification sent in my the merchant + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The code indicating the status of notification. + /// + /// The code indicating the status of notification. + [JsonPropertyName("resultCode")] + public string? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNotificationReferenceOption { get; private set; } + + /// + /// The unique reference for the request sent downstream. + /// + /// The unique reference for the request sent downstream. + [JsonPropertyName("shopperNotificationReference")] + public string? ShopperNotificationReference { get { return this._ShopperNotificationReferenceOption; } set { this._ShopperNotificationReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// This is the recurringDetailReference returned in the response when token was created + /// + /// This is the recurringDetailReference returned in the response when token was created + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NotifyShopperResult {\n"); + sb.Append(" DisplayedReference: ").Append(DisplayedReference).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ShopperNotificationReference: ").Append(ShopperNotificationReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NotifyShopperResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NotifyShopperResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option displayedReference = default; + Option message = default; + Option pspReference = default; + Option reference = default; + Option resultCode = default; + Option shopperNotificationReference = default; + Option storedPaymentMethodId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "displayedReference": + displayedReference = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + resultCode = new Option(utf8JsonReader.GetString()!); + break; + case "shopperNotificationReference": + shopperNotificationReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NotifyShopperResult(displayedReference, message, pspReference, reference, resultCode, shopperNotificationReference, storedPaymentMethodId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NotifyShopperResult notifyShopperResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, notifyShopperResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NotifyShopperResult notifyShopperResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (notifyShopperResult._DisplayedReferenceOption.IsSet) + if (notifyShopperResult.DisplayedReference != null) + writer.WriteString("displayedReference", notifyShopperResult.DisplayedReference); + + if (notifyShopperResult._MessageOption.IsSet) + if (notifyShopperResult.Message != null) + writer.WriteString("message", notifyShopperResult.Message); + + if (notifyShopperResult._PspReferenceOption.IsSet) + if (notifyShopperResult.PspReference != null) + writer.WriteString("pspReference", notifyShopperResult.PspReference); + + if (notifyShopperResult._ReferenceOption.IsSet) + if (notifyShopperResult.Reference != null) + writer.WriteString("reference", notifyShopperResult.Reference); + + if (notifyShopperResult._ResultCodeOption.IsSet) + if (notifyShopperResult.ResultCode != null) + writer.WriteString("resultCode", notifyShopperResult.ResultCode); + + if (notifyShopperResult._ShopperNotificationReferenceOption.IsSet) + if (notifyShopperResult.ShopperNotificationReference != null) + writer.WriteString("shopperNotificationReference", notifyShopperResult.ShopperNotificationReference); + + if (notifyShopperResult._StoredPaymentMethodIdOption.IsSet) + if (notifyShopperResult.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", notifyShopperResult.StoredPaymentMethodId); + } + } +} diff --git a/Adyen/Recurring/Models/Permit.cs b/Adyen/Recurring/Models/Permit.cs new file mode 100644 index 000000000..45b48d0d7 --- /dev/null +++ b/Adyen/Recurring/Models/Permit.cs @@ -0,0 +1,281 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Permit. + /// + public partial class Permit : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Partner ID (when using the permit-per-partner token sharing model). + /// The profile to apply to this permit (when using the shared permits model). + /// restriction + /// The key to link permit requests to permit results. + /// The expiry date for this permit. + [JsonConstructor] + public Permit(Option partnerId = default, Option profileReference = default, Option restriction = default, Option resultKey = default, Option validTillDate = default) + { + _PartnerIdOption = partnerId; + _ProfileReferenceOption = profileReference; + _RestrictionOption = restriction; + _ResultKeyOption = resultKey; + _ValidTillDateOption = validTillDate; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Permit() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PartnerIdOption { get; private set; } + + /// + /// Partner ID (when using the permit-per-partner token sharing model). + /// + /// Partner ID (when using the permit-per-partner token sharing model). + [JsonPropertyName("partnerId")] + public string? PartnerId { get { return this._PartnerIdOption; } set { this._PartnerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProfileReferenceOption { get; private set; } + + /// + /// The profile to apply to this permit (when using the shared permits model). + /// + /// The profile to apply to this permit (when using the shared permits model). + [JsonPropertyName("profileReference")] + public string? ProfileReference { get { return this._ProfileReferenceOption; } set { this._ProfileReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RestrictionOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("restriction")] + public PermitRestriction? Restriction { get { return this._RestrictionOption; } set { this._RestrictionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultKeyOption { get; private set; } + + /// + /// The key to link permit requests to permit results. + /// + /// The key to link permit requests to permit results. + [JsonPropertyName("resultKey")] + public string? ResultKey { get { return this._ResultKeyOption; } set { this._ResultKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValidTillDateOption { get; private set; } + + /// + /// The expiry date for this permit. + /// + /// The expiry date for this permit. + [JsonPropertyName("validTillDate")] + public DateTimeOffset? ValidTillDate { get { return this._ValidTillDateOption; } set { this._ValidTillDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Permit {\n"); + sb.Append(" PartnerId: ").Append(PartnerId).Append("\n"); + sb.Append(" ProfileReference: ").Append(ProfileReference).Append("\n"); + sb.Append(" Restriction: ").Append(Restriction).Append("\n"); + sb.Append(" ResultKey: ").Append(ResultKey).Append("\n"); + sb.Append(" ValidTillDate: ").Append(ValidTillDate).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PermitJsonConverter : JsonConverter + { + /// + /// The format to use to serialize ValidTillDate. + /// + public static string ValidTillDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Permit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option partnerId = default; + Option profileReference = default; + Option restriction = default; + Option resultKey = default; + Option validTillDate = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "partnerId": + partnerId = new Option(utf8JsonReader.GetString()!); + break; + case "profileReference": + profileReference = new Option(utf8JsonReader.GetString()!); + break; + case "restriction": + restriction = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "resultKey": + resultKey = new Option(utf8JsonReader.GetString()!); + break; + case "validTillDate": + validTillDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new Permit(partnerId, profileReference, restriction, resultKey, validTillDate); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Permit permit, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, permit, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Permit permit, JsonSerializerOptions jsonSerializerOptions) + { + + if (permit._PartnerIdOption.IsSet) + if (permit.PartnerId != null) + writer.WriteString("partnerId", permit.PartnerId); + + if (permit._ProfileReferenceOption.IsSet) + if (permit.ProfileReference != null) + writer.WriteString("profileReference", permit.ProfileReference); + + if (permit._RestrictionOption.IsSet) + { + writer.WritePropertyName("restriction"); + JsonSerializer.Serialize(writer, permit.Restriction, jsonSerializerOptions); + } + if (permit._ResultKeyOption.IsSet) + if (permit.ResultKey != null) + writer.WriteString("resultKey", permit.ResultKey); + + if (permit._ValidTillDateOption.IsSet) + writer.WriteString("validTillDate", permit._ValidTillDateOption.Value!.Value.ToString(ValidTillDateFormat)); + } + } +} diff --git a/Adyen/Recurring/Models/PermitRestriction.cs b/Adyen/Recurring/Models/PermitRestriction.cs new file mode 100644 index 000000000..31e5ee80f --- /dev/null +++ b/Adyen/Recurring/Models/PermitRestriction.cs @@ -0,0 +1,226 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// PermitRestriction. + /// + public partial class PermitRestriction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// maxAmount + /// singleTransactionLimit + /// Only a single payment can be made using this permit if set to true, otherwise multiple payments are allowed. + [JsonConstructor] + public PermitRestriction(Option maxAmount = default, Option singleTransactionLimit = default, Option singleUse = default) + { + _MaxAmountOption = maxAmount; + _SingleTransactionLimitOption = singleTransactionLimit; + _SingleUseOption = singleUse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PermitRestriction() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaxAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("maxAmount")] + public Amount? MaxAmount { get { return this._MaxAmountOption; } set { this._MaxAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SingleTransactionLimitOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("singleTransactionLimit")] + public Amount? SingleTransactionLimit { get { return this._SingleTransactionLimitOption; } set { this._SingleTransactionLimitOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SingleUseOption { get; private set; } + + /// + /// Only a single payment can be made using this permit if set to true, otherwise multiple payments are allowed. + /// + /// Only a single payment can be made using this permit if set to true, otherwise multiple payments are allowed. + [JsonPropertyName("singleUse")] + public bool? SingleUse { get { return this._SingleUseOption; } set { this._SingleUseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PermitRestriction {\n"); + sb.Append(" MaxAmount: ").Append(MaxAmount).Append("\n"); + sb.Append(" SingleTransactionLimit: ").Append(SingleTransactionLimit).Append("\n"); + sb.Append(" SingleUse: ").Append(SingleUse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PermitRestrictionJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PermitRestriction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option maxAmount = default; + Option singleTransactionLimit = default; + Option singleUse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "maxAmount": + maxAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "singleTransactionLimit": + singleTransactionLimit = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "singleUse": + singleUse = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new PermitRestriction(maxAmount, singleTransactionLimit, singleUse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PermitRestriction permitRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, permitRestriction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PermitRestriction permitRestriction, JsonSerializerOptions jsonSerializerOptions) + { + + if (permitRestriction._MaxAmountOption.IsSet) + { + writer.WritePropertyName("maxAmount"); + JsonSerializer.Serialize(writer, permitRestriction.MaxAmount, jsonSerializerOptions); + } + if (permitRestriction._SingleTransactionLimitOption.IsSet) + { + writer.WritePropertyName("singleTransactionLimit"); + JsonSerializer.Serialize(writer, permitRestriction.SingleTransactionLimit, jsonSerializerOptions); + } + if (permitRestriction._SingleUseOption.IsSet) + writer.WriteBoolean("singleUse", permitRestriction._SingleUseOption.Value!.Value); + } + } +} diff --git a/Adyen/Recurring/Models/PermitResult.cs b/Adyen/Recurring/Models/PermitResult.cs new file mode 100644 index 000000000..3d1e7bee1 --- /dev/null +++ b/Adyen/Recurring/Models/PermitResult.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// PermitResult. + /// + public partial class PermitResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The key to link permit requests to permit results. + /// The permit token which is used to make payments by the partner company. + [JsonConstructor] + public PermitResult(Option resultKey = default, Option token = default) + { + _ResultKeyOption = resultKey; + _TokenOption = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PermitResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultKeyOption { get; private set; } + + /// + /// The key to link permit requests to permit results. + /// + /// The key to link permit requests to permit results. + [JsonPropertyName("resultKey")] + public string? ResultKey { get { return this._ResultKeyOption; } set { this._ResultKeyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenOption { get; private set; } + + /// + /// The permit token which is used to make payments by the partner company. + /// + /// The permit token which is used to make payments by the partner company. + [JsonPropertyName("token")] + public string? Token { get { return this._TokenOption; } set { this._TokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PermitResult {\n"); + sb.Append(" ResultKey: ").Append(ResultKey).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PermitResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PermitResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option resultKey = default; + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "resultKey": + resultKey = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PermitResult(resultKey, token); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PermitResult permitResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, permitResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PermitResult permitResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (permitResult._ResultKeyOption.IsSet) + if (permitResult.ResultKey != null) + writer.WriteString("resultKey", permitResult.ResultKey); + + if (permitResult._TokenOption.IsSet) + if (permitResult.Token != null) + writer.WriteString("token", permitResult.Token); + } + } +} diff --git a/Adyen/Recurring/Models/Recurring.cs b/Adyen/Recurring/Models/Recurring.cs new file mode 100644 index 000000000..42977f334 --- /dev/null +++ b/Adyen/Recurring/Models/Recurring.cs @@ -0,0 +1,538 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// Recurring. + /// + public partial class Recurring : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// A descriptive name for this detail. + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// The name of the token service. + [JsonConstructor] + public Recurring(Option contract = default, Option recurringDetailName = default, Option recurringExpiry = default, Option recurringFrequency = default, Option tokenService = default) + { + _ContractOption = contract; + _RecurringDetailNameOption = recurringDetailName; + _RecurringExpiryOption = recurringExpiry; + _RecurringFrequencyOption = recurringFrequency; + _TokenServiceOption = tokenService; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Recurring() + { + } + + partial void OnCreated(); + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonConverter(typeof(ContractEnumJsonConverter))] + public class ContractEnum : IEnum + { + /// + /// Returns the value of the ContractEnum. + /// + public string? Value { get; set; } + + /// + /// ContractEnum.ONECLICK - ONECLICK + /// + public static readonly ContractEnum ONECLICK = new("ONECLICK"); + + /// + /// ContractEnum.ONECLICKRECURRING - ONECLICK,RECURRING + /// + public static readonly ContractEnum ONECLICKRECURRING = new("ONECLICK,RECURRING"); + + /// + /// ContractEnum.RECURRING - RECURRING + /// + public static readonly ContractEnum RECURRING = new("RECURRING"); + + /// + /// ContractEnum.PAYOUT - PAYOUT + /// + public static readonly ContractEnum PAYOUT = new("PAYOUT"); + + /// + /// ContractEnum.EXTERNAL - EXTERNAL + /// + public static readonly ContractEnum EXTERNAL = new("EXTERNAL"); + + private ContractEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ContractEnum?(string? value) => value == null ? null : new ContractEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ContractEnum? option) => option?.Value; + + public static bool operator ==(ContractEnum? left, ContractEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ContractEnum? left, ContractEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ContractEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ContractEnum? FromStringOrDefault(string value) + { + return value switch { + "ONECLICK" => ContractEnum.ONECLICK, + "ONECLICK,RECURRING" => ContractEnum.ONECLICKRECURRING, + "RECURRING" => ContractEnum.RECURRING, + "PAYOUT" => ContractEnum.PAYOUT, + "EXTERNAL" => ContractEnum.EXTERNAL, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ContractEnum? value) + { + if (value == null) + return null; + + if (value == ContractEnum.ONECLICK) + return "ONECLICK"; + + if (value == ContractEnum.ONECLICKRECURRING) + return "ONECLICK,RECURRING"; + + if (value == ContractEnum.RECURRING) + return "RECURRING"; + + if (value == ContractEnum.PAYOUT) + return "PAYOUT"; + + if (value == ContractEnum.EXTERNAL) + return "EXTERNAL"; + + return null; + } + + /// + /// JsonConverter for writing ContractEnum. + /// + public class ContractEnumJsonConverter : JsonConverter + { + public override ContractEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ContractEnum.FromStringOrDefault(value) ?? new ContractEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ContractEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ContractEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ContractOption { get; private set; } + + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + /// + /// The type of recurring contract to be used. Possible values: * `ONECLICK` – Payment details can be used to initiate a one-click payment, where the shopper enters the [card security code (CVC/CVV)](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-security-code-cvc-cvv-cid). * `RECURRING` – Payment details can be used without the card security code to initiate [card-not-present transactions](https://docs.adyen.com/payments-fundamentals/payment-glossary#card-not-present-cnp). * `ONECLICK,RECURRING` – Payment details can be used regardless of whether the shopper is on your site or not. * `PAYOUT` – Payment details can be used to [make a payout](https://docs.adyen.com/online-payments/online-payouts). * `EXTERNAL` - Use this when you store payment details and send the raw card number or network token directly in your API request. + [JsonPropertyName("contract")] + public ContractEnum? Contract { get { return this._ContractOption; } set { this._ContractOption = new(value); } } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonConverter(typeof(TokenServiceEnumJsonConverter))] + public class TokenServiceEnum : IEnum + { + /// + /// Returns the value of the TokenServiceEnum. + /// + public string? Value { get; set; } + + /// + /// TokenServiceEnum.VISATOKENSERVICE - VISATOKENSERVICE + /// + public static readonly TokenServiceEnum VISATOKENSERVICE = new("VISATOKENSERVICE"); + + /// + /// TokenServiceEnum.MCTOKENSERVICE - MCTOKENSERVICE + /// + public static readonly TokenServiceEnum MCTOKENSERVICE = new("MCTOKENSERVICE"); + + /// + /// TokenServiceEnum.AMEXTOKENSERVICE - AMEXTOKENSERVICE + /// + public static readonly TokenServiceEnum AMEXTOKENSERVICE = new("AMEXTOKENSERVICE"); + + /// + /// TokenServiceEnum.TOKENSHARING - TOKEN_SHARING + /// + public static readonly TokenServiceEnum TOKENSHARING = new("TOKEN_SHARING"); + + private TokenServiceEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TokenServiceEnum?(string? value) => value == null ? null : new TokenServiceEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TokenServiceEnum? option) => option?.Value; + + public static bool operator ==(TokenServiceEnum? left, TokenServiceEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TokenServiceEnum? left, TokenServiceEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TokenServiceEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TokenServiceEnum? FromStringOrDefault(string value) + { + return value switch { + "VISATOKENSERVICE" => TokenServiceEnum.VISATOKENSERVICE, + "MCTOKENSERVICE" => TokenServiceEnum.MCTOKENSERVICE, + "AMEXTOKENSERVICE" => TokenServiceEnum.AMEXTOKENSERVICE, + "TOKEN_SHARING" => TokenServiceEnum.TOKENSHARING, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TokenServiceEnum? value) + { + if (value == null) + return null; + + if (value == TokenServiceEnum.VISATOKENSERVICE) + return "VISATOKENSERVICE"; + + if (value == TokenServiceEnum.MCTOKENSERVICE) + return "MCTOKENSERVICE"; + + if (value == TokenServiceEnum.AMEXTOKENSERVICE) + return "AMEXTOKENSERVICE"; + + if (value == TokenServiceEnum.TOKENSHARING) + return "TOKEN_SHARING"; + + return null; + } + + /// + /// JsonConverter for writing TokenServiceEnum. + /// + public class TokenServiceEnumJsonConverter : JsonConverter + { + public override TokenServiceEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TokenServiceEnum.FromStringOrDefault(value) ?? new TokenServiceEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TokenServiceEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TokenServiceEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenServiceOption { get; private set; } + + /// + /// The name of the token service. + /// + /// The name of the token service. + [JsonPropertyName("tokenService")] + public TokenServiceEnum? TokenService { get { return this._TokenServiceOption; } set { this._TokenServiceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailNameOption { get; private set; } + + /// + /// A descriptive name for this detail. + /// + /// A descriptive name for this detail. + [JsonPropertyName("recurringDetailName")] + public string? RecurringDetailName { get { return this._RecurringDetailNameOption; } set { this._RecurringDetailNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringExpiryOption { get; private set; } + + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + /// + /// Date after which no further authorisations shall be performed. Only for 3D Secure 2. + [JsonPropertyName("recurringExpiry")] + public DateTimeOffset? RecurringExpiry { get { return this._RecurringExpiryOption; } set { this._RecurringExpiryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringFrequencyOption { get; private set; } + + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + /// + /// Minimum number of days between authorisations. Only for 3D Secure 2. + [JsonPropertyName("recurringFrequency")] + public string? RecurringFrequency { get { return this._RecurringFrequencyOption; } set { this._RecurringFrequencyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Recurring {\n"); + sb.Append(" Contract: ").Append(Contract).Append("\n"); + sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); + sb.Append(" RecurringExpiry: ").Append(RecurringExpiry).Append("\n"); + sb.Append(" RecurringFrequency: ").Append(RecurringFrequency).Append("\n"); + sb.Append(" TokenService: ").Append(TokenService).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RecurringExpiry. + /// + public static string RecurringExpiryFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Recurring Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option contract = default; + Option recurringDetailName = default; + Option recurringExpiry = default; + Option recurringFrequency = default; + Option tokenService = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "contract": + string? contractRawValue = utf8JsonReader.GetString(); + contract = new Option(Recurring.ContractEnum.FromStringOrDefault(contractRawValue)); + break; + case "recurringDetailName": + recurringDetailName = new Option(utf8JsonReader.GetString()!); + break; + case "recurringExpiry": + recurringExpiry = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "recurringFrequency": + recurringFrequency = new Option(utf8JsonReader.GetString()!); + break; + case "tokenService": + string? tokenServiceRawValue = utf8JsonReader.GetString(); + tokenService = new Option(Recurring.TokenServiceEnum.FromStringOrDefault(tokenServiceRawValue)); + break; + default: + break; + } + } + } + + + return new Recurring(contract, recurringDetailName, recurringExpiry, recurringFrequency, tokenService); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurring, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Recurring recurring, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurring._ContractOption.IsSet && recurring.Contract != null) + { + string? contractRawValue = Recurring.ContractEnum.ToJsonValue(recurring._ContractOption.Value!.Value); + writer.WriteString("contract", contractRawValue); + } + + if (recurring._RecurringDetailNameOption.IsSet) + if (recurring.RecurringDetailName != null) + writer.WriteString("recurringDetailName", recurring.RecurringDetailName); + + if (recurring._RecurringExpiryOption.IsSet) + writer.WriteString("recurringExpiry", recurring._RecurringExpiryOption.Value!.Value.ToString(RecurringExpiryFormat)); + + if (recurring._RecurringFrequencyOption.IsSet) + if (recurring.RecurringFrequency != null) + writer.WriteString("recurringFrequency", recurring.RecurringFrequency); + + if (recurring._TokenServiceOption.IsSet && recurring.TokenService != null) + { + string? tokenServiceRawValue = Recurring.TokenServiceEnum.ToJsonValue(recurring._TokenServiceOption.Value!.Value); + writer.WriteString("tokenService", tokenServiceRawValue); + } + } + } +} diff --git a/Adyen/Recurring/Models/RecurringDetail.cs b/Adyen/Recurring/Models/RecurringDetail.cs new file mode 100644 index 000000000..85883a049 --- /dev/null +++ b/Adyen/Recurring/Models/RecurringDetail.cs @@ -0,0 +1,573 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// RecurringDetail. + /// + public partial class RecurringDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reference that uniquely identifies the recurring detail. + /// The payment method, such as “mc\", \"visa\", \"ideal\", \"paypal\". + /// This field contains additional data, which may be returned in a particular response. The additionalData object consists of entries, each of which includes the key and value. + /// The alias of the credit card number. Applies only to recurring contracts storing credit card details + /// The alias type of the credit card number. Applies only to recurring contracts storing credit card details. + /// bank + /// billingAddress + /// card + /// Types of recurring contracts. + /// The date when the recurring details were created. + /// The `pspReference` of the first recurring payment that created the recurring detail. + /// An optional descriptive name for this recurring detail. + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// The type or sub-brand of a payment method used, e.g. Visa Debit, Visa Corporate, etc. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). + /// shopperName + /// A shopper's social security number (only in countries where it is legal to collect). + /// tokenDetails + [JsonConstructor] + public RecurringDetail(string recurringDetailReference, string variant, Option?> additionalData = default, Option alias = default, Option aliasType = default, Option bank = default, Option billingAddress = default, Option card = default, Option?> contractTypes = default, Option creationDate = default, Option firstPspReference = default, Option name = default, Option networkTxReference = default, Option paymentMethodVariant = default, Option shopperName = default, Option socialSecurityNumber = default, Option tokenDetails = default) + { + RecurringDetailReference = recurringDetailReference; + Variant = variant; + _AdditionalDataOption = additionalData; + _AliasOption = alias; + _AliasTypeOption = aliasType; + _BankOption = bank; + _BillingAddressOption = billingAddress; + _CardOption = card; + _ContractTypesOption = contractTypes; + _CreationDateOption = creationDate; + _FirstPspReferenceOption = firstPspReference; + _NameOption = name; + _NetworkTxReferenceOption = networkTxReference; + _PaymentMethodVariantOption = paymentMethodVariant; + _ShopperNameOption = shopperName; + _SocialSecurityNumberOption = socialSecurityNumber; + _TokenDetailsOption = tokenDetails; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringDetail() + { + } + + partial void OnCreated(); + + /// + /// The reference that uniquely identifies the recurring detail. + /// + /// The reference that uniquely identifies the recurring detail. + [JsonPropertyName("recurringDetailReference")] + public string RecurringDetailReference { get; set; } + + /// + /// The payment method, such as “mc\", \"visa\", \"ideal\", \"paypal\". + /// + /// The payment method, such as “mc\", \"visa\", \"ideal\", \"paypal\". + [JsonPropertyName("variant")] + public string Variant { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be returned in a particular response. The additionalData object consists of entries, each of which includes the key and value. + /// + /// This field contains additional data, which may be returned in a particular response. The additionalData object consists of entries, each of which includes the key and value. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasOption { get; private set; } + + /// + /// The alias of the credit card number. Applies only to recurring contracts storing credit card details + /// + /// The alias of the credit card number. Applies only to recurring contracts storing credit card details + [JsonPropertyName("alias")] + public string? Alias { get { return this._AliasOption; } set { this._AliasOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AliasTypeOption { get; private set; } + + /// + /// The alias type of the credit card number. Applies only to recurring contracts storing credit card details. + /// + /// The alias type of the credit card number. Applies only to recurring contracts storing credit card details. + [JsonPropertyName("aliasType")] + public string? AliasType { get { return this._AliasTypeOption; } set { this._AliasTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bank")] + public BankAccount? Bank { get { return this._BankOption; } set { this._BankOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BillingAddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("billingAddress")] + public Address? BillingAddress { get { return this._BillingAddressOption; } set { this._BillingAddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ContractTypesOption { get; private set; } + + /// + /// Types of recurring contracts. + /// + /// Types of recurring contracts. + [JsonPropertyName("contractTypes")] + public List? ContractTypes { get { return this._ContractTypesOption; } set { this._ContractTypesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date when the recurring details were created. + /// + /// The date when the recurring details were created. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstPspReferenceOption { get; private set; } + + /// + /// The `pspReference` of the first recurring payment that created the recurring detail. + /// + /// The `pspReference` of the first recurring payment that created the recurring detail. + [JsonPropertyName("firstPspReference")] + public string? FirstPspReference { get { return this._FirstPspReferenceOption; } set { this._FirstPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// An optional descriptive name for this recurring detail. + /// + /// An optional descriptive name for this recurring detail. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NetworkTxReferenceOption { get; private set; } + + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + /// + /// Returned in the response if you are not tokenizing with Adyen and are using the Merchant-initiated transactions (MIT) framework from Mastercard or Visa. This contains either the Mastercard Trace ID or the Visa Transaction ID. + [JsonPropertyName("networkTxReference")] + public string? NetworkTxReference { get { return this._NetworkTxReferenceOption; } set { this._NetworkTxReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMethodVariantOption { get; private set; } + + /// + /// The type or sub-brand of a payment method used, e.g. Visa Debit, Visa Corporate, etc. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). + /// + /// The type or sub-brand of a payment method used, e.g. Visa Debit, Visa Corporate, etc. For more information, refer to [PaymentMethodVariant](https://docs.adyen.com/development-resources/paymentmethodvariant). + [JsonPropertyName("paymentMethodVariant")] + public string? PaymentMethodVariant { get { return this._PaymentMethodVariantOption; } set { this._PaymentMethodVariantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperNameOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperName")] + public Name? ShopperName { get { return this._ShopperNameOption; } set { this._ShopperNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SocialSecurityNumberOption { get; private set; } + + /// + /// A shopper's social security number (only in countries where it is legal to collect). + /// + /// A shopper's social security number (only in countries where it is legal to collect). + [JsonPropertyName("socialSecurityNumber")] + public string? SocialSecurityNumber { get { return this._SocialSecurityNumberOption; } set { this._SocialSecurityNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenDetailsOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenDetails")] + public TokenDetails? TokenDetails { get { return this._TokenDetailsOption; } set { this._TokenDetailsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringDetail {\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" Variant: ").Append(Variant).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Alias: ").Append(Alias).Append("\n"); + sb.Append(" AliasType: ").Append(AliasType).Append("\n"); + sb.Append(" Bank: ").Append(Bank).Append("\n"); + sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" ContractTypes: ").Append(ContractTypes).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" FirstPspReference: ").Append(FirstPspReference).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" NetworkTxReference: ").Append(NetworkTxReference).Append("\n"); + sb.Append(" PaymentMethodVariant: ").Append(PaymentMethodVariant).Append("\n"); + sb.Append(" ShopperName: ").Append(ShopperName).Append("\n"); + sb.Append(" SocialSecurityNumber: ").Append(SocialSecurityNumber).Append("\n"); + sb.Append(" TokenDetails: ").Append(TokenDetails).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringDetailJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option recurringDetailReference = default; + Option variant = default; + Option?> additionalData = default; + Option alias = default; + Option aliasType = default; + Option bank = default; + Option billingAddress = default; + Option card = default; + Option?> contractTypes = default; + Option creationDate = default; + Option firstPspReference = default; + Option name = default; + Option networkTxReference = default; + Option paymentMethodVariant = default; + Option shopperName = default; + Option socialSecurityNumber = default; + Option tokenDetails = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "variant": + variant = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "alias": + alias = new Option(utf8JsonReader.GetString()!); + break; + case "aliasType": + aliasType = new Option(utf8JsonReader.GetString()!); + break; + case "bank": + bank = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billingAddress": + billingAddress = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "contractTypes": + contractTypes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "firstPspReference": + firstPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "networkTxReference": + networkTxReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethodVariant": + paymentMethodVariant = new Option(utf8JsonReader.GetString()!); + break; + case "shopperName": + shopperName = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "socialSecurityNumber": + socialSecurityNumber = new Option(utf8JsonReader.GetString()!); + break; + case "tokenDetails": + tokenDetails = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!recurringDetailReference.IsSet) + throw new ArgumentException("Property is required for class RecurringDetail.", nameof(recurringDetailReference)); + + if (!variant.IsSet) + throw new ArgumentException("Property is required for class RecurringDetail.", nameof(variant)); + + return new RecurringDetail(recurringDetailReference.Value!, variant.Value!, additionalData, alias, aliasType, bank, billingAddress, card, contractTypes, creationDate, firstPspReference, name, networkTxReference, paymentMethodVariant, shopperName, socialSecurityNumber, tokenDetails); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringDetail recurringDetail, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringDetail, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringDetail recurringDetail, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringDetail.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", recurringDetail.RecurringDetailReference); + + if (recurringDetail.Variant != null) + writer.WriteString("variant", recurringDetail.Variant); + + if (recurringDetail._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, recurringDetail.AdditionalData, jsonSerializerOptions); + } + if (recurringDetail._AliasOption.IsSet) + if (recurringDetail.Alias != null) + writer.WriteString("alias", recurringDetail.Alias); + + if (recurringDetail._AliasTypeOption.IsSet) + if (recurringDetail.AliasType != null) + writer.WriteString("aliasType", recurringDetail.AliasType); + + if (recurringDetail._BankOption.IsSet) + { + writer.WritePropertyName("bank"); + JsonSerializer.Serialize(writer, recurringDetail.Bank, jsonSerializerOptions); + } + if (recurringDetail._BillingAddressOption.IsSet) + { + writer.WritePropertyName("billingAddress"); + JsonSerializer.Serialize(writer, recurringDetail.BillingAddress, jsonSerializerOptions); + } + if (recurringDetail._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, recurringDetail.Card, jsonSerializerOptions); + } + if (recurringDetail._ContractTypesOption.IsSet) + { + writer.WritePropertyName("contractTypes"); + JsonSerializer.Serialize(writer, recurringDetail.ContractTypes, jsonSerializerOptions); + } + if (recurringDetail._CreationDateOption.IsSet) + writer.WriteString("creationDate", recurringDetail._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (recurringDetail._FirstPspReferenceOption.IsSet) + if (recurringDetail.FirstPspReference != null) + writer.WriteString("firstPspReference", recurringDetail.FirstPspReference); + + if (recurringDetail._NameOption.IsSet) + if (recurringDetail.Name != null) + writer.WriteString("name", recurringDetail.Name); + + if (recurringDetail._NetworkTxReferenceOption.IsSet) + if (recurringDetail.NetworkTxReference != null) + writer.WriteString("networkTxReference", recurringDetail.NetworkTxReference); + + if (recurringDetail._PaymentMethodVariantOption.IsSet) + if (recurringDetail.PaymentMethodVariant != null) + writer.WriteString("paymentMethodVariant", recurringDetail.PaymentMethodVariant); + + if (recurringDetail._ShopperNameOption.IsSet) + { + writer.WritePropertyName("shopperName"); + JsonSerializer.Serialize(writer, recurringDetail.ShopperName, jsonSerializerOptions); + } + if (recurringDetail._SocialSecurityNumberOption.IsSet) + if (recurringDetail.SocialSecurityNumber != null) + writer.WriteString("socialSecurityNumber", recurringDetail.SocialSecurityNumber); + + if (recurringDetail._TokenDetailsOption.IsSet) + { + writer.WritePropertyName("tokenDetails"); + JsonSerializer.Serialize(writer, recurringDetail.TokenDetails, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Recurring/Models/RecurringDetailWrapper.cs b/Adyen/Recurring/Models/RecurringDetailWrapper.cs new file mode 100644 index 000000000..647de2faf --- /dev/null +++ b/Adyen/Recurring/Models/RecurringDetailWrapper.cs @@ -0,0 +1,178 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// RecurringDetailWrapper. + /// + public partial class RecurringDetailWrapper : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// recurringDetail + [JsonConstructor] + public RecurringDetailWrapper(Option recurringDetail = default) + { + _RecurringDetailOption = recurringDetail; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringDetailWrapper() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("RecurringDetail")] + public RecurringDetail? RecurringDetail { get { return this._RecurringDetailOption; } set { this._RecurringDetailOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringDetailWrapper {\n"); + sb.Append(" RecurringDetail: ").Append(RecurringDetail).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringDetailWrapperJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringDetailWrapper Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option recurringDetail = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "RecurringDetail": + recurringDetail = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new RecurringDetailWrapper(recurringDetail); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringDetailWrapper recurringDetailWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringDetailWrapper, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringDetailWrapper recurringDetailWrapper, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringDetailWrapper._RecurringDetailOption.IsSet) + { + writer.WritePropertyName("RecurringDetail"); + JsonSerializer.Serialize(writer, recurringDetailWrapper.RecurringDetail, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Recurring/Models/RecurringDetailsRequest.cs b/Adyen/Recurring/Models/RecurringDetailsRequest.cs new file mode 100644 index 000000000..f52daa0be --- /dev/null +++ b/Adyen/Recurring/Models/RecurringDetailsRequest.cs @@ -0,0 +1,217 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// RecurringDetailsRequest. + /// + public partial class RecurringDetailsRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier you want to process the (transaction) request with. + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + /// recurring + [JsonConstructor] + public RecurringDetailsRequest(string merchantAccount, string shopperReference, Option recurring = default) + { + MerchantAccount = merchantAccount; + ShopperReference = shopperReference; + _RecurringOption = recurring; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringDetailsRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier you want to process the (transaction) request with. + /// + /// The merchant account identifier you want to process the (transaction) request with. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + /// + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurring")] + public Recurring? Recurring { get { return this._RecurringOption; } set { this._RecurringOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringDetailsRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Recurring: ").Append(Recurring).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringDetailsRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringDetailsRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option shopperReference = default; + Option recurring = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "recurring": + recurring = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class RecurringDetailsRequest.", nameof(merchantAccount)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class RecurringDetailsRequest.", nameof(shopperReference)); + + return new RecurringDetailsRequest(merchantAccount.Value!, shopperReference.Value!, recurring); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringDetailsRequest recurringDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringDetailsRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringDetailsRequest recurringDetailsRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringDetailsRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", recurringDetailsRequest.MerchantAccount); + + if (recurringDetailsRequest.ShopperReference != null) + writer.WriteString("shopperReference", recurringDetailsRequest.ShopperReference); + + if (recurringDetailsRequest._RecurringOption.IsSet) + { + writer.WritePropertyName("recurring"); + JsonSerializer.Serialize(writer, recurringDetailsRequest.Recurring, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Recurring/Models/RecurringDetailsResult.cs b/Adyen/Recurring/Models/RecurringDetailsResult.cs new file mode 100644 index 000000000..046a0d2ae --- /dev/null +++ b/Adyen/Recurring/Models/RecurringDetailsResult.cs @@ -0,0 +1,257 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// RecurringDetailsResult. + /// + public partial class RecurringDetailsResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the recurring details were created. + /// Payment details stored for recurring payments. + /// The most recent email for this shopper (if available). + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + [JsonConstructor] + public RecurringDetailsResult(Option creationDate = default, Option?> details = default, Option lastKnownShopperEmail = default, Option shopperReference = default) + { + _CreationDateOption = creationDate; + _DetailsOption = details; + _LastKnownShopperEmailOption = lastKnownShopperEmail; + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringDetailsResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date when the recurring details were created. + /// + /// The date when the recurring details were created. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DetailsOption { get; private set; } + + /// + /// Payment details stored for recurring payments. + /// + /// Payment details stored for recurring payments. + [JsonPropertyName("details")] + public List? Details { get { return this._DetailsOption; } set { this._DetailsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastKnownShopperEmailOption { get; private set; } + + /// + /// The most recent email for this shopper (if available). + /// + /// The most recent email for this shopper (if available). + [JsonPropertyName("lastKnownShopperEmail")] + public string? LastKnownShopperEmail { get { return this._LastKnownShopperEmailOption; } set { this._LastKnownShopperEmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + /// + /// The reference you use to uniquely identify the shopper (e.g. user ID or account ID). + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringDetailsResult {\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Details: ").Append(Details).Append("\n"); + sb.Append(" LastKnownShopperEmail: ").Append(LastKnownShopperEmail).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringDetailsResultJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringDetailsResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option creationDate = default; + Option?> details = default; + Option lastKnownShopperEmail = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "details": + details = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lastKnownShopperEmail": + lastKnownShopperEmail = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RecurringDetailsResult(creationDate, details, lastKnownShopperEmail, shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringDetailsResult recurringDetailsResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringDetailsResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringDetailsResult recurringDetailsResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringDetailsResult._CreationDateOption.IsSet) + writer.WriteString("creationDate", recurringDetailsResult._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (recurringDetailsResult._DetailsOption.IsSet) + { + writer.WritePropertyName("details"); + JsonSerializer.Serialize(writer, recurringDetailsResult.Details, jsonSerializerOptions); + } + if (recurringDetailsResult._LastKnownShopperEmailOption.IsSet) + if (recurringDetailsResult.LastKnownShopperEmail != null) + writer.WriteString("lastKnownShopperEmail", recurringDetailsResult.LastKnownShopperEmail); + + if (recurringDetailsResult._ShopperReferenceOption.IsSet) + if (recurringDetailsResult.ShopperReference != null) + writer.WriteString("shopperReference", recurringDetailsResult.ShopperReference); + } + } +} diff --git a/Adyen/Recurring/Models/ScheduleAccountUpdaterRequest.cs b/Adyen/Recurring/Models/ScheduleAccountUpdaterRequest.cs new file mode 100644 index 000000000..a87792b32 --- /dev/null +++ b/Adyen/Recurring/Models/ScheduleAccountUpdaterRequest.cs @@ -0,0 +1,292 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// ScheduleAccountUpdaterRequest. + /// + public partial class ScheduleAccountUpdaterRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Account of the merchant. + /// A reference that merchants can apply for the call. + /// This field contains additional data, which may be required for a particular request. + /// card + /// The selected detail recurring reference. Optional if `card` is provided. + /// The reference of the shopper that owns the recurring contract. Optional if `card` is provided. + [JsonConstructor] + public ScheduleAccountUpdaterRequest(string merchantAccount, string reference, Option?> additionalData = default, Option card = default, Option selectedRecurringDetailReference = default, Option shopperReference = default) + { + MerchantAccount = merchantAccount; + Reference = reference; + _AdditionalDataOption = additionalData; + _CardOption = card; + _SelectedRecurringDetailReferenceOption = selectedRecurringDetailReference; + _ShopperReferenceOption = shopperReference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScheduleAccountUpdaterRequest() + { + } + + partial void OnCreated(); + + /// + /// Account of the merchant. + /// + /// Account of the merchant. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// A reference that merchants can apply for the call. + /// + /// A reference that merchants can apply for the call. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// This field contains additional data, which may be required for a particular request. + /// + /// This field contains additional data, which may be required for a particular request. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SelectedRecurringDetailReferenceOption { get; private set; } + + /// + /// The selected detail recurring reference. Optional if `card` is provided. + /// + /// The selected detail recurring reference. Optional if `card` is provided. + [JsonPropertyName("selectedRecurringDetailReference")] + public string? SelectedRecurringDetailReference { get { return this._SelectedRecurringDetailReferenceOption; } set { this._SelectedRecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// The reference of the shopper that owns the recurring contract. Optional if `card` is provided. + /// + /// The reference of the shopper that owns the recurring contract. Optional if `card` is provided. + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScheduleAccountUpdaterRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" SelectedRecurringDetailReference: ").Append(SelectedRecurringDetailReference).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScheduleAccountUpdaterRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScheduleAccountUpdaterRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option reference = default; + Option?> additionalData = default; + Option card = default; + Option selectedRecurringDetailReference = default; + Option shopperReference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "selectedRecurringDetailReference": + selectedRecurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class ScheduleAccountUpdaterRequest.", nameof(merchantAccount)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class ScheduleAccountUpdaterRequest.", nameof(reference)); + + return new ScheduleAccountUpdaterRequest(merchantAccount.Value!, reference.Value!, additionalData, card, selectedRecurringDetailReference, shopperReference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScheduleAccountUpdaterRequest scheduleAccountUpdaterRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scheduleAccountUpdaterRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScheduleAccountUpdaterRequest scheduleAccountUpdaterRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (scheduleAccountUpdaterRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", scheduleAccountUpdaterRequest.MerchantAccount); + + if (scheduleAccountUpdaterRequest.Reference != null) + writer.WriteString("reference", scheduleAccountUpdaterRequest.Reference); + + if (scheduleAccountUpdaterRequest._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, scheduleAccountUpdaterRequest.AdditionalData, jsonSerializerOptions); + } + if (scheduleAccountUpdaterRequest._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, scheduleAccountUpdaterRequest.Card, jsonSerializerOptions); + } + if (scheduleAccountUpdaterRequest._SelectedRecurringDetailReferenceOption.IsSet) + if (scheduleAccountUpdaterRequest.SelectedRecurringDetailReference != null) + writer.WriteString("selectedRecurringDetailReference", scheduleAccountUpdaterRequest.SelectedRecurringDetailReference); + + if (scheduleAccountUpdaterRequest._ShopperReferenceOption.IsSet) + if (scheduleAccountUpdaterRequest.ShopperReference != null) + writer.WriteString("shopperReference", scheduleAccountUpdaterRequest.ShopperReference); + } + } +} diff --git a/Adyen/Recurring/Models/ScheduleAccountUpdaterResult.cs b/Adyen/Recurring/Models/ScheduleAccountUpdaterResult.cs new file mode 100644 index 000000000..5cc6bf387 --- /dev/null +++ b/Adyen/Recurring/Models/ScheduleAccountUpdaterResult.cs @@ -0,0 +1,191 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// ScheduleAccountUpdaterResult. + /// + public partial class ScheduleAccountUpdaterResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Adyen's 16-character unique reference associated with the transaction. This value is globally unique; quote it when communicating with us about this request. + /// The result of scheduling an Account Updater. If scheduling was successful, this field returns **Success**; otherwise it contains the error message. + [JsonConstructor] + public ScheduleAccountUpdaterResult(string pspReference, string result) + { + PspReference = pspReference; + Result = result; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ScheduleAccountUpdaterResult() + { + } + + partial void OnCreated(); + + /// + /// Adyen's 16-character unique reference associated with the transaction. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character unique reference associated with the transaction. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string PspReference { get; set; } + + /// + /// The result of scheduling an Account Updater. If scheduling was successful, this field returns **Success**; otherwise it contains the error message. + /// + /// The result of scheduling an Account Updater. If scheduling was successful, this field returns **Success**; otherwise it contains the error message. + [JsonPropertyName("result")] + public string Result { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScheduleAccountUpdaterResult {\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ScheduleAccountUpdaterResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ScheduleAccountUpdaterResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option pspReference = default; + Option result = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!pspReference.IsSet) + throw new ArgumentException("Property is required for class ScheduleAccountUpdaterResult.", nameof(pspReference)); + + if (!result.IsSet) + throw new ArgumentException("Property is required for class ScheduleAccountUpdaterResult.", nameof(result)); + + return new ScheduleAccountUpdaterResult(pspReference.Value!, result.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ScheduleAccountUpdaterResult scheduleAccountUpdaterResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, scheduleAccountUpdaterResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ScheduleAccountUpdaterResult scheduleAccountUpdaterResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (scheduleAccountUpdaterResult.PspReference != null) + writer.WriteString("pspReference", scheduleAccountUpdaterResult.PspReference); + + if (scheduleAccountUpdaterResult.Result != null) + writer.WriteString("result", scheduleAccountUpdaterResult.Result); + } + } +} diff --git a/Adyen/Recurring/Models/ServiceError.cs b/Adyen/Recurring/Models/ServiceError.cs new file mode 100644 index 000000000..27c5c4699 --- /dev/null +++ b/Adyen/Recurring/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Recurring/Models/TokenDetails.cs b/Adyen/Recurring/Models/TokenDetails.cs new file mode 100644 index 000000000..c377e0b49 --- /dev/null +++ b/Adyen/Recurring/Models/TokenDetails.cs @@ -0,0 +1,201 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Recurring.Client; + +namespace Adyen.Recurring.Models +{ + /// + /// TokenDetails. + /// + public partial class TokenDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// tokenData + /// tokenDataType + [JsonConstructor] + public TokenDetails(Option?> tokenData = default, Option tokenDataType = default) + { + _TokenDataOption = tokenData; + _TokenDataTypeOption = tokenDataType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenDetails() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TokenDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenData")] + public Dictionary? TokenData { get { return this._TokenDataOption; } set { this._TokenDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenDataTypeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tokenDataType")] + public string? TokenDataType { get { return this._TokenDataTypeOption; } set { this._TokenDataTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenDetails {\n"); + sb.Append(" TokenData: ").Append(TokenData).Append("\n"); + sb.Append(" TokenDataType: ").Append(TokenDataType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> tokenData = default; + Option tokenDataType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "tokenData": + tokenData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tokenDataType": + tokenDataType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TokenDetails(tokenData, tokenDataType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenDetails tokenDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenDetails tokenDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (tokenDetails._TokenDataOption.IsSet) + { + writer.WritePropertyName("tokenData"); + JsonSerializer.Serialize(writer, tokenDetails.TokenData, jsonSerializerOptions); + } + if (tokenDetails._TokenDataTypeOption.IsSet) + if (tokenDetails.TokenDataType != null) + writer.WriteString("tokenDataType", tokenDetails.TokenDataType); + } + } +} diff --git a/Adyen/Recurring/Services/RecurringService.cs b/Adyen/Recurring/Services/RecurringService.cs new file mode 100644 index 000000000..52a6913ec --- /dev/null +++ b/Adyen/Recurring/Services/RecurringService.cs @@ -0,0 +1,2763 @@ +// +/* + * Adyen Recurring API + * + * > The Recurring API is a legacy API for managing tokens. We strongly recommend to use [Checkout API recurring endpoints](https://docs.adyen.com/api-explorer/Checkout/71/post/storedPaymentMethods) instead when possible. The Recurring API allows you to manage and remove your tokens or stored payment details. Tokens should be created with validation during a payment request. For more information, refer to our [Tokenization documentation](https://docs.adyen.com/online-payments/tokenization). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"ws@Company.YOUR_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Recurring API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Recurring/v68/disable ``` ## Server-side API libraries We provide open-source [server-side API libraries](https://docs.adyen.com/development-resources/libraries/) in several languages: - PHP - Java - Node.js - .NET - Go - Python - Ruby - Apex (beta) See our [integration examples](https://github.com/adyen-examples#%EF%B8%8F-official-integration-examples) for example uses of the libraries. ## Developer resources Recurring API is available through a Postman collection. Click the button below to create a fork, then set the environment variables at **Environments** > **Adyen APIs**. [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D25716737-0d1ef0da-f5a1-4004-b24a-c5152c51dc7b%26entityType%3Dcollection%26workspaceId%3Da8d63f9f-cfc7-4810-90c5-9e0c60030d3e#?env%5BAdyen%20APIs%5D=W3sia2V5IjoiWC1BUEktS2V5IiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoic2VjcmV0In0seyJrZXkiOiJZT1VSX01FUkNIQU5UX0FDQ09VTlQiLCJ2YWx1ZSI6IiIsImVuYWJsZWQiOnRydWUsInR5cGUiOiJkZWZhdWx0In0seyJrZXkiOiJZT1VSX0NPTVBBTllfQUNDT1VOVCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifSx7ImtleSI6IllPVVJfQkFMQU5DRV9QTEFURk9STSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQifV0=) ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Recurring/v68/disable ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. + * + * The version of the OpenAPI document: 68 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Recurring.Client; +using Adyen.Recurring.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Recurring.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IRecurringService : IAdyenApiService + { + /// + /// The class containing the events. + /// + RecurringServiceEvents Events { get; } + + /// + /// Create new permits linked to a recurring contract. + /// + /// + /// Create permits for a recurring contract, including support for defining restrictions. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + [Obsolete("Deprecated since Adyen Recurring API v68.")] + Task CreatePermitAsync(CreatePermitRequest createPermitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Disable stored payment details + /// + /// + /// Disables stored payment details to stop charging a shopper with this particular recurring detail ID. For more information, refer to [Disable stored details](https://docs.adyen.com/classic-integration/recurring-payments/disable-stored-details/). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task DisableAsync(DisableRequest disableRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Disable an existing permit. + /// + /// + /// Disable a permit that was previously linked to a recurringDetailReference. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + [Obsolete("Deprecated since Adyen Recurring API v68.")] + Task DisablePermitAsync(DisablePermitRequest disablePermitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get stored payment details + /// + /// + /// Lists the stored payment details for a shopper, if there are any available. The recurring detail ID can be used with a regular authorisation request to charge the shopper. A summary of the payment detail is returned for presentation to the shopper. For more information, refer to [Retrieve stored details](https://docs.adyen.com/classic-integration/recurring-payments/retrieve-stored-details/). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ListRecurringDetailsAsync(RecurringDetailsRequest recurringDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Ask issuer to notify the shopper + /// + /// + /// Sends a request to the issuer so they can inform the shopper about the upcoming recurring payment. This endpoint is used only for local acquiring in India. For more information, refer to [Recurring card payments in India](https://docs.adyen.com/payment-methods/cards/cards-recurring-india). + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task NotifyShopperAsync(NotifyShopperRequest notifyShopperRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Schedule running the Account Updater + /// + /// + /// When making the API call, you can submit either the credit card information, or the recurring detail reference and the shopper reference: * If the card information is provided, all the sub-fields for `card` are mandatory. * If the recurring detail reference is provided, the fields for `shopperReference` and `selectedRecurringDetailReference` are mandatory. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ScheduleAccountUpdaterAsync(ScheduleAccountUpdaterRequest scheduleAccountUpdaterRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreatePermitApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDisableApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IDisablePermitApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IListRecurringDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface INotifyShopperApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IScheduleAccountUpdaterApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class RecurringServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreatePermit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreatePermit; + + internal void ExecuteOnCreatePermit(RecurringService.CreatePermitApiResponse apiResponse) + { + OnCreatePermit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreatePermit(Exception exception) + { + OnErrorCreatePermit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDisable; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDisable; + + internal void ExecuteOnDisable(RecurringService.DisableApiResponse apiResponse) + { + OnDisable?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDisable(Exception exception) + { + OnErrorDisable?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnDisablePermit; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorDisablePermit; + + internal void ExecuteOnDisablePermit(RecurringService.DisablePermitApiResponse apiResponse) + { + OnDisablePermit?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDisablePermit(Exception exception) + { + OnErrorDisablePermit?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnListRecurringDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorListRecurringDetails; + + internal void ExecuteOnListRecurringDetails(RecurringService.ListRecurringDetailsApiResponse apiResponse) + { + OnListRecurringDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorListRecurringDetails(Exception exception) + { + OnErrorListRecurringDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnNotifyShopper; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorNotifyShopper; + + internal void ExecuteOnNotifyShopper(RecurringService.NotifyShopperApiResponse apiResponse) + { + OnNotifyShopper?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorNotifyShopper(Exception exception) + { + OnErrorNotifyShopper?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnScheduleAccountUpdater; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorScheduleAccountUpdater; + + internal void ExecuteOnScheduleAccountUpdater(RecurringService.ScheduleAccountUpdaterApiResponse apiResponse) + { + OnScheduleAccountUpdater?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorScheduleAccountUpdater(Exception exception) + { + OnErrorScheduleAccountUpdater?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class RecurringService : IRecurringService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public RecurringServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public RecurringService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, RecurringServiceEvents recurringServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = recurringServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create new permits linked to a recurring contract. Create permits for a recurring contract, including support for defining restrictions. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreatePermitAsync(CreatePermitRequest createPermitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/createPermit" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/createPermit"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (createPermitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(createPermitRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreatePermitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/createPermit", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreatePermit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreatePermit(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreatePermitApiResponse : Adyen.Core.Client.ApiResponse, ICreatePermitApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePermitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreatePermitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.CreatePermitResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.CreatePermitResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Disable stored payment details Disables stored payment details to stop charging a shopper with this particular recurring detail ID. For more information, refer to [Disable stored details](https://docs.adyen.com/classic-integration/recurring-payments/disable-stored-details/). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DisableAsync(DisableRequest disableRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/disable" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/disable"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (disableRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(disableRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DisableApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/disable", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDisable(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDisable(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DisableApiResponse : Adyen.Core.Client.ApiResponse, IDisableApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DisableApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DisableApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.DisableResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.DisableResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Disable an existing permit. Disable a permit that was previously linked to a recurringDetailReference. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task DisablePermitAsync(DisablePermitRequest disablePermitRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/disablePermit" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/disablePermit"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (disablePermitRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(disablePermitRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + DisablePermitApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/disablePermit", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnDisablePermit(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorDisablePermit(exception); + throw; + } + } + + /// + /// The . + /// + public partial class DisablePermitApiResponse : Adyen.Core.Client.ApiResponse, IDisablePermitApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DisablePermitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public DisablePermitApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.DisablePermitResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.DisablePermitResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get stored payment details Lists the stored payment details for a shopper, if there are any available. The recurring detail ID can be used with a regular authorisation request to charge the shopper. A summary of the payment detail is returned for presentation to the shopper. For more information, refer to [Retrieve stored details](https://docs.adyen.com/classic-integration/recurring-payments/retrieve-stored-details/). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ListRecurringDetailsAsync(RecurringDetailsRequest recurringDetailsRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/listRecurringDetails" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/listRecurringDetails"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (recurringDetailsRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(recurringDetailsRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ListRecurringDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/listRecurringDetails", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnListRecurringDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorListRecurringDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ListRecurringDetailsApiResponse : Adyen.Core.Client.ApiResponse, IListRecurringDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListRecurringDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ListRecurringDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.RecurringDetailsResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.RecurringDetailsResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Ask issuer to notify the shopper Sends a request to the issuer so they can inform the shopper about the upcoming recurring payment. This endpoint is used only for local acquiring in India. For more information, refer to [Recurring card payments in India](https://docs.adyen.com/payment-methods/cards/cards-recurring-india). + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task NotifyShopperAsync(NotifyShopperRequest notifyShopperRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/notifyShopper" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/notifyShopper"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (notifyShopperRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(notifyShopperRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + NotifyShopperApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/notifyShopper", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnNotifyShopper(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorNotifyShopper(exception); + throw; + } + } + + /// + /// The . + /// + public partial class NotifyShopperApiResponse : Adyen.Core.Client.ApiResponse, INotifyShopperApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public NotifyShopperApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public NotifyShopperApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.NotifyShopperResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.NotifyShopperResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Schedule running the Account Updater When making the API call, you can submit either the credit card information, or the recurring detail reference and the shopper reference: * If the card information is provided, all the sub-fields for `card` are mandatory. * If the recurring detail reference is provided, the fields for `shopperReference` and `selectedRecurringDetailReference` are mandatory. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ScheduleAccountUpdaterAsync(ScheduleAccountUpdaterRequest scheduleAccountUpdaterRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/scheduleAccountUpdater" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/scheduleAccountUpdater"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (scheduleAccountUpdaterRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(scheduleAccountUpdaterRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ScheduleAccountUpdaterApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/scheduleAccountUpdater", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnScheduleAccountUpdater(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorScheduleAccountUpdater(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ScheduleAccountUpdaterApiResponse : Adyen.Core.Client.ApiResponse, IScheduleAccountUpdaterApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ScheduleAccountUpdaterApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ScheduleAccountUpdaterApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Recurring.Models.ScheduleAccountUpdaterResult? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ScheduleAccountUpdaterResult? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Recurring.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Recurring.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Recurring.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Recurring.Models.ServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Recurring.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Recurring.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/ReportWebhooks/Client/ClientUtils.cs b/Adyen/ReportWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..2134576c8 --- /dev/null +++ b/Adyen/ReportWebhooks/Client/ClientUtils.cs @@ -0,0 +1,289 @@ +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.ReportWebhooks.Models; +using Models = Adyen.ReportWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.ReportWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.ReportNotificationRequest.TypeEnum reportNotificationRequestTypeEnum) + return Models.ReportNotificationRequest.TypeEnum.ToJsonValue(reportNotificationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/ReportWebhooks/Client/HmacKeyToken.cs b/Adyen/ReportWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..48a658d17 --- /dev/null +++ b/Adyen/ReportWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.ReportWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/ReportWebhooks/Client/HostConfiguration.cs b/Adyen/ReportWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..53ce46a39 --- /dev/null +++ b/Adyen/ReportWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,132 @@ +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.ReportWebhooks.Client; +using Adyen.ReportWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.ReportWebhooks.Client +{ + /// + /// Provides hosting configuration for ReportWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new ReportNotificationDataJsonConverter()); + _jsonOptions.Converters.Add(new ReportNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddReportWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/ReportWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/ReportWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..9326497fe --- /dev/null +++ b/Adyen/ReportWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.ReportWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/ReportWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/ReportWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..58bb3212e --- /dev/null +++ b/Adyen/ReportWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.ReportWebhooks; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the ReportWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureReportWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddReportWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/ReportWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/ReportWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..9387a08c1 --- /dev/null +++ b/Adyen/ReportWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen ReportWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddReportWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddReportWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/ReportWebhooks/Handlers/ReportWebhooksHandler.cs b/Adyen/ReportWebhooks/Handlers/ReportWebhooksHandler.cs new file mode 100644 index 000000000..de13bddae --- /dev/null +++ b/Adyen/ReportWebhooks/Handlers/ReportWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.ReportWebhooks.Client; +using Adyen.ReportWebhooks.Models; + +namespace Adyen.ReportWebhooks.Handlers +{ + /// + /// Interface for deserializing ReportWebhooks webhooks or verify its HMAC signature. + /// + public interface IReportWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.ReportWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + ReportNotificationRequest? DeserializeReportNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize ReportWebhooks or verify the HMAC signature of the webhook. + /// + public partial class ReportWebhooksHandler : IReportWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.ReportWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing ReportWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public ReportWebhooksHandler(Adyen.ReportWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public ReportNotificationRequest? DeserializeReportNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/ReportWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/ReportWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..dcb6e3aad --- /dev/null +++ b/Adyen/ReportWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/ReportWebhooks/Models/ReportNotificationData.cs b/Adyen/ReportWebhooks/Models/ReportNotificationData.cs new file mode 100644 index 000000000..ca2da2aa5 --- /dev/null +++ b/Adyen/ReportWebhooks/Models/ReportNotificationData.cs @@ -0,0 +1,340 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Models +{ + /// + /// ReportNotificationData. + /// + public partial class ReportNotificationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The URL at which you can download the report. To download, you must authenticate your GET request with your [API credentials](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/overview). + /// The filename of the report. + /// The type of report. Possible values: - `balanceplatform_accounting_interactive_report` - `balanceplatform_accounting_report` - `balanceplatform_balance_report` - `balanceplatform_fee_report` - `balanceplatform_payment_instrument_report` - `balanceplatform_payout_report` - `balanceplatform_statement_report` + /// accountHolder + /// balanceAccount + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public ReportNotificationData(string downloadUrl, string fileName, string reportType, Option accountHolder = default, Option balanceAccount = default, Option balancePlatform = default, Option creationDate = default, Option id = default) + { + DownloadUrl = downloadUrl; + FileName = fileName; + ReportType = reportType; + _AccountHolderOption = accountHolder; + _BalanceAccountOption = balanceAccount; + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReportNotificationData() + { + } + + partial void OnCreated(); + + /// + /// The URL at which you can download the report. To download, you must authenticate your GET request with your [API credentials](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/overview). + /// + /// The URL at which you can download the report. To download, you must authenticate your GET request with your [API credentials](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/overview). + [JsonPropertyName("downloadUrl")] + public string DownloadUrl { get; set; } + + /// + /// The filename of the report. + /// + /// The filename of the report. + [JsonPropertyName("fileName")] + public string FileName { get; set; } + + /// + /// The type of report. Possible values: - `balanceplatform_accounting_interactive_report` - `balanceplatform_accounting_report` - `balanceplatform_balance_report` - `balanceplatform_fee_report` - `balanceplatform_payment_instrument_report` - `balanceplatform_payout_report` - `balanceplatform_statement_report` + /// + /// The type of report. Possible values: - `balanceplatform_accounting_interactive_report` - `balanceplatform_accounting_report` - `balanceplatform_balance_report` - `balanceplatform_fee_report` - `balanceplatform_payment_instrument_report` - `balanceplatform_payout_report` - `balanceplatform_statement_report` + [JsonPropertyName("reportType")] + public string ReportType { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference? BalanceAccount { get { return this._BalanceAccountOption; } set { this._BalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReportNotificationData {\n"); + sb.Append(" DownloadUrl: ").Append(DownloadUrl).Append("\n"); + sb.Append(" FileName: ").Append(FileName).Append("\n"); + sb.Append(" ReportType: ").Append(ReportType).Append("\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReportNotificationDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReportNotificationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option downloadUrl = default; + Option fileName = default; + Option reportType = default; + Option accountHolder = default; + Option balanceAccount = default; + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "downloadUrl": + downloadUrl = new Option(utf8JsonReader.GetString()!); + break; + case "fileName": + fileName = new Option(utf8JsonReader.GetString()!); + break; + case "reportType": + reportType = new Option(utf8JsonReader.GetString()!); + break; + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!downloadUrl.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationData.", nameof(downloadUrl)); + + if (!fileName.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationData.", nameof(fileName)); + + if (!reportType.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationData.", nameof(reportType)); + + return new ReportNotificationData(downloadUrl.Value!, fileName.Value!, reportType.Value!, accountHolder, balanceAccount, balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReportNotificationData reportNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, reportNotificationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReportNotificationData reportNotificationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (reportNotificationData.DownloadUrl != null) + writer.WriteString("downloadUrl", reportNotificationData.DownloadUrl); + + if (reportNotificationData.FileName != null) + writer.WriteString("fileName", reportNotificationData.FileName); + + if (reportNotificationData.ReportType != null) + writer.WriteString("reportType", reportNotificationData.ReportType); + + if (reportNotificationData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, reportNotificationData.AccountHolder, jsonSerializerOptions); + } + if (reportNotificationData._BalanceAccountOption.IsSet) + { + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, reportNotificationData.BalanceAccount, jsonSerializerOptions); + } + if (reportNotificationData._BalancePlatformOption.IsSet) + if (reportNotificationData.BalancePlatform != null) + writer.WriteString("balancePlatform", reportNotificationData.BalancePlatform); + + if (reportNotificationData._CreationDateOption.IsSet) + writer.WriteString("creationDate", reportNotificationData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (reportNotificationData._IdOption.IsSet) + if (reportNotificationData.Id != null) + writer.WriteString("id", reportNotificationData.Id); + } + } +} diff --git a/Adyen/ReportWebhooks/Models/ReportNotificationRequest.cs b/Adyen/ReportWebhooks/Models/ReportNotificationRequest.cs new file mode 100644 index 000000000..1525c3de2 --- /dev/null +++ b/Adyen/ReportWebhooks/Models/ReportNotificationRequest.cs @@ -0,0 +1,336 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Models +{ + /// + /// ReportNotificationRequest. + /// + public partial class ReportNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// Type of webhook. + /// When the event was queued. + [JsonConstructor] + public ReportNotificationRequest(ReportNotificationData data, string environment, TypeEnum type, Option timestamp = default) + { + Data = data; + Environment = environment; + Type = type; + _TimestampOption = timestamp; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReportNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformReportCreated - balancePlatform.report.created + /// + public static readonly TypeEnum BalancePlatformReportCreated = new("balancePlatform.report.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.report.created" => TypeEnum.BalancePlatformReportCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformReportCreated) + return "balancePlatform.report.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// Type of webhook. + /// + /// Type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public ReportNotificationData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReportNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReportNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReportNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option type = default; + Option timestamp = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ReportNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationRequest.", nameof(environment)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ReportNotificationRequest.", nameof(type)); + + return new ReportNotificationRequest(data.Value!, environment.Value!, type.Value!.Value!, timestamp); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReportNotificationRequest reportNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, reportNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReportNotificationRequest reportNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, reportNotificationRequest.Data, jsonSerializerOptions); + if (reportNotificationRequest.Environment != null) + writer.WriteString("environment", reportNotificationRequest.Environment); + + if (reportNotificationRequest.Type != null) + { + string? typeRawValue = ReportNotificationRequest.TypeEnum.ToJsonValue(reportNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (reportNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", reportNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + } + } +} diff --git a/Adyen/ReportWebhooks/Models/Resource.cs b/Adyen/ReportWebhooks/Models/Resource.cs new file mode 100644 index 000000000..fd6162449 --- /dev/null +++ b/Adyen/ReportWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/ReportWebhooks/Models/ResourceReference.cs b/Adyen/ReportWebhooks/Models/ResourceReference.cs new file mode 100644 index 000000000..a2af7966c --- /dev/null +++ b/Adyen/ReportWebhooks/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Report webhooks + * + * Adyen sends webhooks to inform your system that reports were generated and are ready to be downloaded. You can download reports programmatically by making an HTTP GET request, or manually from your [Balance Platform Customer Area](https://balanceplatform-test.adyen.com/balanceplatform). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.ReportWebhooks.Client; + +namespace Adyen.ReportWebhooks.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/Service/ApiException.cs b/Adyen/Service/ApiException.cs deleted file mode 100644 index 5c687f468..000000000 --- a/Adyen/Service/ApiException.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using Adyen.Model; - -namespace Adyen.Service -{ - public class ApiException:Exception - { - public int StatusCode { get; set; } - - public ApiError ApiError{ get; set; } - - public ApiException(int statusCode,string message) - :base(message) - { - StatusCode = statusCode; - } - } -} diff --git a/Adyen/SessionAuthentication/Client/ApiKeyToken.cs b/Adyen/SessionAuthentication/Client/ApiKeyToken.cs new file mode 100644 index 000000000..c28b89897 --- /dev/null +++ b/Adyen/SessionAuthentication/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.SessionAuthentication.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/SessionAuthentication/Client/ClientUtils.cs b/Adyen/SessionAuthentication/Client/ClientUtils.cs new file mode 100644 index 000000000..ca8d4216d --- /dev/null +++ b/Adyen/SessionAuthentication/Client/ClientUtils.cs @@ -0,0 +1,317 @@ +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.SessionAuthentication.Models; +using Models = Adyen.SessionAuthentication.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.SessionAuthentication.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.ProductType productType) + return ProductTypeValueConverter.ToJsonValue(productType); + if (obj is Models.ResourceType resourceType) + return ResourceTypeValueConverter.ToJsonValue(resourceType); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/SessionAuthentication/Client/HostConfiguration.cs b/Adyen/SessionAuthentication/Client/HostConfiguration.cs new file mode 100644 index 000000000..d0fb6703f --- /dev/null +++ b/Adyen/SessionAuthentication/Client/HostConfiguration.cs @@ -0,0 +1,143 @@ +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.SessionAuthentication.Services; +using Adyen.SessionAuthentication.Client; +using Adyen.SessionAuthentication.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.SessionAuthentication.Client +{ + /// + /// Provides hosting configuration for SessionAuthentication + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://test.adyen.com/authe/api/v1"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountHolderResourceJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationSessionRequestJsonConverter()); + _jsonOptions.Converters.Add(new AuthenticationSessionResponseJsonConverter()); + _jsonOptions.Converters.Add(new BalanceAccountResourceJsonConverter()); + _jsonOptions.Converters.Add(new DefaultErrorResponseEntityJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new LegalEntityResourceJsonConverter()); + _jsonOptions.Converters.Add(new MerchantAccountResourceJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentResourceJsonConverter()); + _jsonOptions.Converters.Add(new PolicyJsonConverter()); + _jsonOptions.Converters.Add(new ProductTypeJsonConverter()); + _jsonOptions.Converters.Add(new ProductTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceTypeJsonConverter()); + _jsonOptions.Converters.Add(new ResourceTypeNullableJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddSessionAuthenticationHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/SessionAuthentication/Client/JsonSerializerOptionsProvider.cs b/Adyen/SessionAuthentication/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..8c43626f4 --- /dev/null +++ b/Adyen/SessionAuthentication/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.SessionAuthentication.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/SessionAuthentication/Extensions/HostBuilderExtensions.cs b/Adyen/SessionAuthentication/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..463b9cd0c --- /dev/null +++ b/Adyen/SessionAuthentication/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.SessionAuthentication; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the SessionAuthentication API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureSessionAuthentication(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddSessionAuthenticationHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/SessionAuthentication/Extensions/ServiceCollectionExtensions.cs b/Adyen/SessionAuthentication/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..87756897d --- /dev/null +++ b/Adyen/SessionAuthentication/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen SessionAuthentication API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddSessionAuthenticationServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddSessionAuthenticationHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/AccountHolderResource.cs b/Adyen/SessionAuthentication/Models/AccountHolderResource.cs new file mode 100644 index 000000000..9628c2bdb --- /dev/null +++ b/Adyen/SessionAuthentication/Models/AccountHolderResource.cs @@ -0,0 +1,171 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// AccountHolderResource. + /// + public partial class AccountHolderResource : Resource, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource connected to the component. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the account holder linked to the balance account shown in the component. + [JsonConstructor] + public AccountHolderResource(string accountHolderId) : base() + { + AccountHolderId = accountHolderId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AccountHolderResource() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the resource connected to the component. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the account holder linked to the balance account shown in the component. + /// + /// The unique identifier of the resource connected to the component. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the account holder linked to the balance account shown in the component. + [JsonPropertyName("accountHolderId")] + public string AccountHolderId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AccountHolderResource {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class AccountHolderResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AccountHolderResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountHolderId.IsSet) + throw new ArgumentException("Property is required for class AccountHolderResource.", nameof(accountHolderId)); + + return new AccountHolderResource(accountHolderId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AccountHolderResource accountHolderResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, accountHolderResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AccountHolderResource accountHolderResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (accountHolderResource.AccountHolderId != null) + writer.WriteString("accountHolderId", accountHolderResource.AccountHolderId); + + if (accountHolderResource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(accountHolderResource.Type)); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/AuthenticationSessionRequest.cs b/Adyen/SessionAuthentication/Models/AuthenticationSessionRequest.cs new file mode 100644 index 000000000..21cab2927 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/AuthenticationSessionRequest.cs @@ -0,0 +1,210 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// AuthenticationSessionRequest. + /// + public partial class AuthenticationSessionRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The URL where the component will appear. In your live environment, you must protect the URL with an SSL certificate and ensure that it starts with `https://`. + /// policy + /// product + [JsonConstructor] + public AuthenticationSessionRequest(string allowOrigin, Policy policy, ProductType product) + { + AllowOrigin = allowOrigin; + Policy = policy; + Product = product; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationSessionRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("product")] + public ProductType Product { get; set; } + + /// + /// The URL where the component will appear. In your live environment, you must protect the URL with an SSL certificate and ensure that it starts with `https://`. + /// + /// The URL where the component will appear. In your live environment, you must protect the URL with an SSL certificate and ensure that it starts with `https://`. + [JsonPropertyName("allowOrigin")] + public string AllowOrigin { get; set; } + + /// + /// . + /// + [JsonPropertyName("policy")] + public Policy Policy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationSessionRequest {\n"); + sb.Append(" AllowOrigin: ").Append(AllowOrigin).Append("\n"); + sb.Append(" Policy: ").Append(Policy).Append("\n"); + sb.Append(" Product: ").Append(Product).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationSessionRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationSessionRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option allowOrigin = default; + Option policy = default; + Option product = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "allowOrigin": + allowOrigin = new Option(utf8JsonReader.GetString()!); + break; + case "policy": + policy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "product": + string? productRawValue = utf8JsonReader.GetString(); + if (productRawValue != null) + product = new Option(ProductTypeValueConverter.FromStringOrDefault(productRawValue)); + break; + default: + break; + } + } + } + + if (!allowOrigin.IsSet) + throw new ArgumentException("Property is required for class AuthenticationSessionRequest.", nameof(allowOrigin)); + + if (!policy.IsSet) + throw new ArgumentException("Property is required for class AuthenticationSessionRequest.", nameof(policy)); + + if (!product.IsSet) + throw new ArgumentException("Property is required for class AuthenticationSessionRequest.", nameof(product)); + + return new AuthenticationSessionRequest(allowOrigin.Value!, policy.Value!, product.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationSessionRequest authenticationSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationSessionRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationSessionRequest authenticationSessionRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationSessionRequest.AllowOrigin != null) + writer.WriteString("allowOrigin", authenticationSessionRequest.AllowOrigin); + + writer.WritePropertyName("policy"); + JsonSerializer.Serialize(writer, authenticationSessionRequest.Policy, jsonSerializerOptions); + var productRawValue = ProductTypeValueConverter.ToJsonValue(authenticationSessionRequest.Product); + writer.WriteString("product", productRawValue); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/AuthenticationSessionResponse.cs b/Adyen/SessionAuthentication/Models/AuthenticationSessionResponse.cs new file mode 100644 index 000000000..d983c72fb --- /dev/null +++ b/Adyen/SessionAuthentication/Models/AuthenticationSessionResponse.cs @@ -0,0 +1,202 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// AuthenticationSessionResponse. + /// + public partial class AuthenticationSessionResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the session. + /// The session token created. + [JsonConstructor] + public AuthenticationSessionResponse(Option id = default, Option token = default) + { + _IdOption = id; + _TokenOption = token; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AuthenticationSessionResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the session. + /// + /// The unique identifier of the session. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenOption { get; private set; } + + /// + /// The session token created. + /// + /// The session token created. + [JsonPropertyName("token")] + public string? Token { get { return this._TokenOption; } set { this._TokenOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AuthenticationSessionResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Token: ").Append(Token).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AuthenticationSessionResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AuthenticationSessionResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option token = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "token": + token = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new AuthenticationSessionResponse(id, token); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AuthenticationSessionResponse authenticationSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, authenticationSessionResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AuthenticationSessionResponse authenticationSessionResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (authenticationSessionResponse._IdOption.IsSet) + if (authenticationSessionResponse.Id != null) + writer.WriteString("id", authenticationSessionResponse.Id); + + if (authenticationSessionResponse._TokenOption.IsSet) + if (authenticationSessionResponse.Token != null) + writer.WriteString("token", authenticationSessionResponse.Token); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/BalanceAccountResource.cs b/Adyen/SessionAuthentication/Models/BalanceAccountResource.cs new file mode 100644 index 000000000..df84dc83b --- /dev/null +++ b/Adyen/SessionAuthentication/Models/BalanceAccountResource.cs @@ -0,0 +1,170 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// BalanceAccountResource. + /// + public partial class BalanceAccountResource : Resource, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balanceAccountId + [JsonConstructor] + public BalanceAccountResource(string balanceAccountId) : base() + { + BalanceAccountId = balanceAccountId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceAccountResource() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("balanceAccountId")] + public string BalanceAccountId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceAccountResource {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class BalanceAccountResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceAccountResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!balanceAccountId.IsSet) + throw new ArgumentException("Property is required for class BalanceAccountResource.", nameof(balanceAccountId)); + + return new BalanceAccountResource(balanceAccountId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceAccountResource balanceAccountResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceAccountResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceAccountResource balanceAccountResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceAccountResource.BalanceAccountId != null) + writer.WriteString("balanceAccountId", balanceAccountResource.BalanceAccountId); + + if (balanceAccountResource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(balanceAccountResource.Type)); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/DefaultErrorResponseEntity.cs b/Adyen/SessionAuthentication/Models/DefaultErrorResponseEntity.cs new file mode 100644 index 000000000..e6919b710 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/DefaultErrorResponseEntity.cs @@ -0,0 +1,352 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// Standardized error response following RFC-7807 format. + /// + public partial class DefaultErrorResponseEntity : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// Unique business error code. + /// A URI that identifies the specific occurrence of the problem if applicable. + /// Array of fields with validation errors when applicable. + /// The unique reference for the request. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonConstructor] + public DefaultErrorResponseEntity(Option detail = default, Option errorCode = default, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option status = default, Option title = default, Option type = default) + { + _DetailOption = detail; + _ErrorCodeOption = errorCode; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _StatusOption = status; + _TitleOption = title; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DefaultErrorResponseEntity() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailOption { get; private set; } + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string? Detail { get { return this._DetailOption; } set { this._DetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// Unique business error code. + /// + /// Unique business error code. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + /// + /// A URI that identifies the specific occurrence of the problem if applicable. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Array of fields with validation errors when applicable. + /// + /// Array of fields with validation errors when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// The unique reference for the request. + /// + /// The unique reference for the request. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + /// + /// A URI that identifies the validation error type. It points to human-readable documentation for the problem type. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DefaultErrorResponseEntity {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DefaultErrorResponseEntityJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DefaultErrorResponseEntity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option status = default; + Option title = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DefaultErrorResponseEntity(detail, errorCode, instance, invalidFields, requestId, status, title, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, defaultErrorResponseEntity, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DefaultErrorResponseEntity defaultErrorResponseEntity, JsonSerializerOptions jsonSerializerOptions) + { + + if (defaultErrorResponseEntity._DetailOption.IsSet) + if (defaultErrorResponseEntity.Detail != null) + writer.WriteString("detail", defaultErrorResponseEntity.Detail); + + if (defaultErrorResponseEntity._ErrorCodeOption.IsSet) + if (defaultErrorResponseEntity.ErrorCode != null) + writer.WriteString("errorCode", defaultErrorResponseEntity.ErrorCode); + + if (defaultErrorResponseEntity._InstanceOption.IsSet) + if (defaultErrorResponseEntity.Instance != null) + writer.WriteString("instance", defaultErrorResponseEntity.Instance); + + if (defaultErrorResponseEntity._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, defaultErrorResponseEntity.InvalidFields, jsonSerializerOptions); + } + if (defaultErrorResponseEntity._RequestIdOption.IsSet) + if (defaultErrorResponseEntity.RequestId != null) + writer.WriteString("requestId", defaultErrorResponseEntity.RequestId); + + if (defaultErrorResponseEntity._StatusOption.IsSet) + writer.WriteNumber("status", defaultErrorResponseEntity._StatusOption.Value!.Value); + + if (defaultErrorResponseEntity._TitleOption.IsSet) + if (defaultErrorResponseEntity.Title != null) + writer.WriteString("title", defaultErrorResponseEntity.Title); + + if (defaultErrorResponseEntity._TypeOption.IsSet) + if (defaultErrorResponseEntity.Type != null) + writer.WriteString("type", defaultErrorResponseEntity.Type); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/InvalidField.cs b/Adyen/SessionAuthentication/Models/InvalidField.cs new file mode 100644 index 000000000..838b4f9f7 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The field that has an invalid value. + /// The invalid value. + /// Description of the validation error. + [JsonConstructor] + public InvalidField(string name, string value, string message) + { + Name = name; + Value = value; + Message = message; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option value = default; + Option message = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + return new InvalidField(name.Value!, value.Value!, message.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/LegalEntityResource.cs b/Adyen/SessionAuthentication/Models/LegalEntityResource.cs new file mode 100644 index 000000000..4a292202e --- /dev/null +++ b/Adyen/SessionAuthentication/Models/LegalEntityResource.cs @@ -0,0 +1,171 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// LegalEntityResource. + /// + public partial class LegalEntityResource : Resource, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the resource connected to the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the legal entity that has a contractual relationship with your platform and owns the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). For sole proprietorships, this is the legal entity of the individual owner. + [JsonConstructor] + public LegalEntityResource(string legalEntityId) : base() + { + LegalEntityId = legalEntityId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public LegalEntityResource() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the resource connected to the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the legal entity that has a contractual relationship with your platform and owns the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). For sole proprietorships, this is the legal entity of the individual owner. + /// + /// The unique identifier of the resource connected to the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the legal entity that has a contractual relationship with your platform and owns the [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments). For sole proprietorships, this is the legal entity of the individual owner. + [JsonPropertyName("legalEntityId")] + public string LegalEntityId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LegalEntityResource {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" LegalEntityId: ").Append(LegalEntityId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class LegalEntityResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override LegalEntityResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option legalEntityId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legalEntityId": + legalEntityId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!legalEntityId.IsSet) + throw new ArgumentException("Property is required for class LegalEntityResource.", nameof(legalEntityId)); + + return new LegalEntityResource(legalEntityId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LegalEntityResource legalEntityResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, legalEntityResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LegalEntityResource legalEntityResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (legalEntityResource.LegalEntityId != null) + writer.WriteString("legalEntityId", legalEntityResource.LegalEntityId); + + if (legalEntityResource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(legalEntityResource.Type)); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/MerchantAccountResource.cs b/Adyen/SessionAuthentication/Models/MerchantAccountResource.cs new file mode 100644 index 000000000..05edc7bb7 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/MerchantAccountResource.cs @@ -0,0 +1,170 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// MerchantAccountResource. + /// + public partial class MerchantAccountResource : Resource, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// merchantAccountCode + [JsonConstructor] + public MerchantAccountResource(Option merchantAccountCode = default) : base() + { + _MerchantAccountCodeOption = merchantAccountCode; + OnCreated(); + } + + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantAccountCodeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchantAccountCode")] + public string? MerchantAccountCode { get { return this._MerchantAccountCodeOption; } set { this._MerchantAccountCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantAccountResource {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" MerchantAccountCode: ").Append(MerchantAccountCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class MerchantAccountResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantAccountResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option merchantAccountCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "merchantAccountCode": + merchantAccountCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantAccountResource(merchantAccountCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantAccountResource merchantAccountResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantAccountResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantAccountResource merchantAccountResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantAccountResource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(merchantAccountResource.Type)); + + if (merchantAccountResource._MerchantAccountCodeOption.IsSet) + if (merchantAccountResource.MerchantAccountCode != null) + writer.WriteString("merchantAccountCode", merchantAccountResource.MerchantAccountCode); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/PaymentInstrumentResource.cs b/Adyen/SessionAuthentication/Models/PaymentInstrumentResource.cs new file mode 100644 index 000000000..a3f4ef2a4 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/PaymentInstrumentResource.cs @@ -0,0 +1,170 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// PaymentInstrumentResource. + /// + public partial class PaymentInstrumentResource : Resource, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// paymentInstrumentId + [JsonConstructor] + public PaymentInstrumentResource(string paymentInstrumentId) : base() + { + PaymentInstrumentId = paymentInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrumentResource() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("paymentInstrumentId")] + public string PaymentInstrumentId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrumentResource {\n"); + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrumentResource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option paymentInstrumentId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!paymentInstrumentId.IsSet) + throw new ArgumentException("Property is required for class PaymentInstrumentResource.", nameof(paymentInstrumentId)); + + return new PaymentInstrumentResource(paymentInstrumentId.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrumentResource paymentInstrumentResource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrumentResource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrumentResource paymentInstrumentResource, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrumentResource.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", paymentInstrumentResource.PaymentInstrumentId); + + if (paymentInstrumentResource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(paymentInstrumentResource.Type)); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/Policy.cs b/Adyen/SessionAuthentication/Models/Policy.cs new file mode 100644 index 000000000..e7a9e69ce --- /dev/null +++ b/Adyen/SessionAuthentication/Models/Policy.cs @@ -0,0 +1,205 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// Policy. + /// + public partial class Policy : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An object containing the type and the unique identifier of the user of the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the ID of the legal entity that has a contractual relationship with your platform. For sole proprietorships, use the ID of the legal entity of the individual owner. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the ID of the account holder that is associated with the balance account shown in the component. + /// The name of the role required to use the component. + [JsonConstructor] + public Policy(Option?> resources = default, Option?> roles = default) + { + _ResourcesOption = resources; + _RolesOption = roles; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Policy() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ResourcesOption { get; private set; } + + /// + /// An object containing the type and the unique identifier of the user of the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the ID of the legal entity that has a contractual relationship with your platform. For sole proprietorships, use the ID of the legal entity of the individual owner. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the ID of the account holder that is associated with the balance account shown in the component. + /// + /// An object containing the type and the unique identifier of the user of the component. For [Onboarding components](https://docs.adyen.com/platforms/onboard-users/components), this is the ID of the legal entity that has a contractual relationship with your platform. For sole proprietorships, use the ID of the legal entity of the individual owner. For [Platform Experience components](https://docs.adyen.com/platforms/build-user-dashboards), this is the ID of the account holder that is associated with the balance account shown in the component. + [JsonPropertyName("resources")] + public HashSet? Resources { get { return this._ResourcesOption; } set { this._ResourcesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RolesOption { get; private set; } + + /// + /// The name of the role required to use the component. + /// + /// The name of the role required to use the component. + [JsonPropertyName("roles")] + public HashSet? Roles { get { return this._RolesOption; } set { this._RolesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Policy {\n"); + sb.Append(" Resources: ").Append(Resources).Append("\n"); + sb.Append(" Roles: ").Append(Roles).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PolicyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Policy Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> resources = default; + Option?> roles = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "resources": + resources = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "roles": + roles = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Policy(resources, roles); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Policy policy, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, policy, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Policy policy, JsonSerializerOptions jsonSerializerOptions) + { + + if (policy._ResourcesOption.IsSet) + { + writer.WritePropertyName("resources"); + JsonSerializer.Serialize(writer, policy.Resources, jsonSerializerOptions); + } + if (policy._RolesOption.IsSet) + { + writer.WritePropertyName("roles"); + JsonSerializer.Serialize(writer, policy.Roles, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/SessionAuthentication/Models/ProductType.cs b/Adyen/SessionAuthentication/Models/ProductType.cs new file mode 100644 index 000000000..7e755c0c9 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/ProductType.cs @@ -0,0 +1,190 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// Defines ProductType + /// + public enum ProductType + { + /// + /// Enum Onboarding for value: onboarding + /// + Onboarding = 1, + + /// + /// Enum Platform for value: platform + /// + Platform = 2, + + /// + /// Enum Bank for value: bank + /// + Bank = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class ProductTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ProductType FromString(string value) + { + if (value.Equals("onboarding")) + return ProductType.Onboarding; + + if (value.Equals("platform")) + return ProductType.Platform; + + if (value.Equals("bank")) + return ProductType.Bank; + + throw new NotImplementedException($"Could not convert value to type ProductType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ProductType? FromStringOrDefault(string value) + { + if (value.Equals("onboarding")) + return ProductType.Onboarding; + + if (value.Equals("platform")) + return ProductType.Platform; + + if (value.Equals("bank")) + return ProductType.Bank; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ProductType value) + { + if (value == ProductType.Onboarding) + return "onboarding"; + + if (value == ProductType.Platform) + return "platform"; + + if (value == ProductType.Bank) + return "bank"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ProductTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ProductType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProductType? result = rawValue == null + ? null + : ProductTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProductType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProductType productType, JsonSerializerOptions options) + { + writer.WriteStringValue(ProductTypeValueConverter.ToJsonValue(productType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ProductTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a ProductType from the Json object + /// + /// + /// + /// + /// + public override ProductType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProductType? result = rawValue == null + ? null + : ProductTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProductType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProductType? productType, JsonSerializerOptions options) + { + writer.WriteStringValue(productType.HasValue ? ProductTypeValueConverter.ToJsonValue(productType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/Resource.cs b/Adyen/SessionAuthentication/Models/Resource.cs new file mode 100644 index 000000000..f949945da --- /dev/null +++ b/Adyen/SessionAuthentication/Models/Resource.cs @@ -0,0 +1,215 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructor] + public Resource() + { + Type = (ResourceType)Enum.Parse(typeof(ResourceType), this.GetType().Name); + OnCreated(); + } + + + partial void OnCreated(); + + /// + /// The discriminator. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public ResourceType Type { get; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + + string? discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "type"); + + if (discriminator != null && discriminator.Equals("AccountHolderResource")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + if (discriminator != null && discriminator.Equals("BalanceAccountResource")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + if (discriminator != null && discriminator.Equals("LegalEntityResource")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + if (discriminator != null && discriminator.Equals("MerchantAccountResource")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + if (discriminator != null && discriminator.Equals("PaymentInstrumentResource")) + return JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(ResourceTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new Resource(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + if (resource is AccountHolderResource accountHolderResource){ + JsonSerializer.Serialize(writer, accountHolderResource, jsonSerializerOptions); + return; + } + + if (resource is BalanceAccountResource balanceAccountResource){ + JsonSerializer.Serialize(writer, balanceAccountResource, jsonSerializerOptions); + return; + } + + if (resource is LegalEntityResource legalEntityResource){ + JsonSerializer.Serialize(writer, legalEntityResource, jsonSerializerOptions); + return; + } + + if (resource is MerchantAccountResource merchantAccountResource){ + JsonSerializer.Serialize(writer, merchantAccountResource, jsonSerializerOptions); + return; + } + + if (resource is PaymentInstrumentResource paymentInstrumentResource){ + JsonSerializer.Serialize(writer, paymentInstrumentResource, jsonSerializerOptions); + return; + } + + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource.Type != null) + writer.WriteString("type", ResourceTypeValueConverter.ToJsonValue(resource.Type)); + } + } +} diff --git a/Adyen/SessionAuthentication/Models/ResourceType.cs b/Adyen/SessionAuthentication/Models/ResourceType.cs new file mode 100644 index 000000000..71f9d9819 --- /dev/null +++ b/Adyen/SessionAuthentication/Models/ResourceType.cs @@ -0,0 +1,218 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.SessionAuthentication.Client; + +namespace Adyen.SessionAuthentication.Models +{ + /// + /// Defines ResourceType + /// + public enum ResourceType + { + /// + /// Enum LegalEntity for value: legalEntity + /// + LegalEntity = 1, + + /// + /// Enum BalanceAccount for value: balanceAccount + /// + BalanceAccount = 2, + + /// + /// Enum AccountHolder for value: accountHolder + /// + AccountHolder = 3, + + /// + /// Enum MerchantAccount for value: merchantAccount + /// + MerchantAccount = 4, + + /// + /// Enum PaymentInstrument for value: paymentInstrument + /// + PaymentInstrument = 5 + } + + /// + /// Converts to and from the JSON value + /// + public static class ResourceTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ResourceType FromString(string value) + { + if (value.Equals("legalEntity")) + return ResourceType.LegalEntity; + + if (value.Equals("balanceAccount")) + return ResourceType.BalanceAccount; + + if (value.Equals("accountHolder")) + return ResourceType.AccountHolder; + + if (value.Equals("merchantAccount")) + return ResourceType.MerchantAccount; + + if (value.Equals("paymentInstrument")) + return ResourceType.PaymentInstrument; + + throw new NotImplementedException($"Could not convert value to type ResourceType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ResourceType? FromStringOrDefault(string value) + { + if (value.Equals("legalEntity")) + return ResourceType.LegalEntity; + + if (value.Equals("balanceAccount")) + return ResourceType.BalanceAccount; + + if (value.Equals("accountHolder")) + return ResourceType.AccountHolder; + + if (value.Equals("merchantAccount")) + return ResourceType.MerchantAccount; + + if (value.Equals("paymentInstrument")) + return ResourceType.PaymentInstrument; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ResourceType value) + { + if (value == ResourceType.LegalEntity) + return "legalEntity"; + + if (value == ResourceType.BalanceAccount) + return "balanceAccount"; + + if (value == ResourceType.AccountHolder) + return "accountHolder"; + + if (value == ResourceType.MerchantAccount) + return "merchantAccount"; + + if (value == ResourceType.PaymentInstrument) + return "paymentInstrument"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ResourceTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ResourceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ResourceType? result = rawValue == null + ? null + : ResourceTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ResourceType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceType resourceType, JsonSerializerOptions options) + { + writer.WriteStringValue(ResourceTypeValueConverter.ToJsonValue(resourceType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ResourceTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a ResourceType from the Json object + /// + /// + /// + /// + /// + public override ResourceType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ResourceType? result = rawValue == null + ? null + : ResourceTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ResourceType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceType? resourceType, JsonSerializerOptions options) + { + writer.WriteStringValue(resourceType.HasValue ? ResourceTypeValueConverter.ToJsonValue(resourceType.Value).ToString() : "null"); + } + } +} diff --git a/Adyen/SessionAuthentication/Services/SessionAuthenticationService.cs b/Adyen/SessionAuthentication/Services/SessionAuthenticationService.cs new file mode 100644 index 000000000..5f66788c4 --- /dev/null +++ b/Adyen/SessionAuthentication/Services/SessionAuthenticationService.cs @@ -0,0 +1,449 @@ +// +/* + * Session authentication API + * + * The Session authentication API enables you to create and manage the JSON Web Tokens (JWT) required for integrating [components](https://docs.adyen.com/platforms/components-overview). ## Authentication We recommend that you use an API key to connect to the Session authentication API. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the Session authentication API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H 'Content-Type: application/json' \\ -H 'X-API-Key: YOUR_API_KEY' \\ ... ``` ## Roles and permissions To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. ## Going live To access the live endpoint, generate an API key in your live Customer Area if you have a [platform](https://docs.adyen.com/platforms/) or [marketplace setup](https://docs.adyen.com/marketplaces/). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. You can then use the API key to send requests to `https://authe-live.adyen.com/authe/api/v1`. + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.SessionAuthentication.Client; +using Adyen.SessionAuthentication.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.SessionAuthentication.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ISessionAuthenticationService : IAdyenApiService + { + /// + /// The class containing the events. + /// + SessionAuthenticationServiceEvents Events { get; } + + /// + /// Create a session token + /// + /// + /// Creates a session token that is required to integrate [components](https://docs.adyen.com/platforms/components-overview). The response contains encrypted session data. The front end then uses the session data to make the required server-side calls for the component. To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CreateAuthenticationSessionAsync(AuthenticationSessionRequest authenticationSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface ICreateAuthenticationSessionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class SessionAuthenticationServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCreateAuthenticationSession; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCreateAuthenticationSession; + + internal void ExecuteOnCreateAuthenticationSession(SessionAuthenticationService.CreateAuthenticationSessionApiResponse apiResponse) + { + OnCreateAuthenticationSession?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateAuthenticationSession(Exception exception) + { + OnErrorCreateAuthenticationSession?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class SessionAuthenticationService : ISessionAuthenticationService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public SessionAuthenticationServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public SessionAuthenticationService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, SessionAuthenticationServiceEvents sessionAuthenticationServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = sessionAuthenticationServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Create a session token Creates a session token that is required to integrate [components](https://docs.adyen.com/platforms/components-overview). The response contains encrypted session data. The front end then uses the session data to make the required server-side calls for the component. To create a token, you must meet specific requirements. These requirements vary depending on the type of component. For more information, see the documentation for [Onboarding](https://docs.adyen.com/platforms/onboard-users/components) and [Platform Experience](https://docs.adyen.com/platforms/build-user-dashboards) components. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CreateAuthenticationSessionAsync(AuthenticationSessionRequest authenticationSessionRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/sessions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/sessions"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (authenticationSessionRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(authenticationSessionRequest, _jsonSerializerOptions)); + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CreateAuthenticationSessionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/sessions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCreateAuthenticationSession(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCreateAuthenticationSession(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CreateAuthenticationSessionApiResponse : Adyen.Core.Client.ApiResponse, ICreateAuthenticationSessionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAuthenticationSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CreateAuthenticationSessionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.SessionAuthentication.Models.AuthenticationSessionResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.SessionAuthentication.Models.AuthenticationSessionResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.SessionAuthentication.Models.DefaultErrorResponseEntity? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/StoredValue/Client/ApiKeyToken.cs b/Adyen/StoredValue/Client/ApiKeyToken.cs new file mode 100644 index 000000000..e0ce4ffee --- /dev/null +++ b/Adyen/StoredValue/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.StoredValue.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/StoredValue/Client/ClientUtils.cs b/Adyen/StoredValue/Client/ClientUtils.cs new file mode 100644 index 000000000..5f58305cb --- /dev/null +++ b/Adyen/StoredValue/Client/ClientUtils.cs @@ -0,0 +1,339 @@ +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.StoredValue.Models; +using Models = Adyen.StoredValue.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.StoredValue.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.StoredValueBalanceCheckRequest.ShopperInteractionEnum storedValueBalanceCheckRequestShopperInteractionEnum) + return Models.StoredValueBalanceCheckRequest.ShopperInteractionEnum.ToJsonValue(storedValueBalanceCheckRequestShopperInteractionEnum); + if (obj is Models.StoredValueBalanceCheckResponse.ResultCodeEnum storedValueBalanceCheckResponseResultCodeEnum) + return Models.StoredValueBalanceCheckResponse.ResultCodeEnum.ToJsonValue(storedValueBalanceCheckResponseResultCodeEnum); + if (obj is Models.StoredValueBalanceMergeRequest.ShopperInteractionEnum storedValueBalanceMergeRequestShopperInteractionEnum) + return Models.StoredValueBalanceMergeRequest.ShopperInteractionEnum.ToJsonValue(storedValueBalanceMergeRequestShopperInteractionEnum); + if (obj is Models.StoredValueBalanceMergeResponse.ResultCodeEnum storedValueBalanceMergeResponseResultCodeEnum) + return Models.StoredValueBalanceMergeResponse.ResultCodeEnum.ToJsonValue(storedValueBalanceMergeResponseResultCodeEnum); + if (obj is Models.StoredValueIssueRequest.ShopperInteractionEnum storedValueIssueRequestShopperInteractionEnum) + return Models.StoredValueIssueRequest.ShopperInteractionEnum.ToJsonValue(storedValueIssueRequestShopperInteractionEnum); + if (obj is Models.StoredValueIssueResponse.ResultCodeEnum storedValueIssueResponseResultCodeEnum) + return Models.StoredValueIssueResponse.ResultCodeEnum.ToJsonValue(storedValueIssueResponseResultCodeEnum); + if (obj is Models.StoredValueLoadRequest.LoadTypeEnum storedValueLoadRequestLoadTypeEnum) + return Models.StoredValueLoadRequest.LoadTypeEnum.ToJsonValue(storedValueLoadRequestLoadTypeEnum); + if (obj is Models.StoredValueLoadRequest.ShopperInteractionEnum storedValueLoadRequestShopperInteractionEnum) + return Models.StoredValueLoadRequest.ShopperInteractionEnum.ToJsonValue(storedValueLoadRequestShopperInteractionEnum); + if (obj is Models.StoredValueLoadResponse.ResultCodeEnum storedValueLoadResponseResultCodeEnum) + return Models.StoredValueLoadResponse.ResultCodeEnum.ToJsonValue(storedValueLoadResponseResultCodeEnum); + if (obj is Models.StoredValueStatusChangeRequest.StatusEnum storedValueStatusChangeRequestStatusEnum) + return Models.StoredValueStatusChangeRequest.StatusEnum.ToJsonValue(storedValueStatusChangeRequestStatusEnum); + if (obj is Models.StoredValueStatusChangeRequest.ShopperInteractionEnum storedValueStatusChangeRequestShopperInteractionEnum) + return Models.StoredValueStatusChangeRequest.ShopperInteractionEnum.ToJsonValue(storedValueStatusChangeRequestShopperInteractionEnum); + if (obj is Models.StoredValueStatusChangeResponse.ResultCodeEnum storedValueStatusChangeResponseResultCodeEnum) + return Models.StoredValueStatusChangeResponse.ResultCodeEnum.ToJsonValue(storedValueStatusChangeResponseResultCodeEnum); + if (obj is Models.StoredValueVoidResponse.ResultCodeEnum storedValueVoidResponseResultCodeEnum) + return Models.StoredValueVoidResponse.ResultCodeEnum.ToJsonValue(storedValueVoidResponseResultCodeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/StoredValue/Client/HostConfiguration.cs b/Adyen/StoredValue/Client/HostConfiguration.cs new file mode 100644 index 000000000..71f58cd1e --- /dev/null +++ b/Adyen/StoredValue/Client/HostConfiguration.cs @@ -0,0 +1,142 @@ +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.StoredValue.Services; +using Adyen.StoredValue.Client; +using Adyen.StoredValue.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.StoredValue.Client +{ + /// + /// Provides hosting configuration for StoredValue + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://pal-test.adyen.com/pal/servlet/StoredValue/v46"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueBalanceCheckRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueBalanceCheckResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueBalanceMergeRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueBalanceMergeResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueIssueRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueIssueResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueLoadRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueLoadResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueStatusChangeRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueStatusChangeResponseJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueVoidRequestJsonConverter()); + _jsonOptions.Converters.Add(new StoredValueVoidResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddStoredValueHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/StoredValue/Client/JsonSerializerOptionsProvider.cs b/Adyen/StoredValue/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..c655dd73f --- /dev/null +++ b/Adyen/StoredValue/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.StoredValue.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/StoredValue/Extensions/HostBuilderExtensions.cs b/Adyen/StoredValue/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..f2a2399ad --- /dev/null +++ b/Adyen/StoredValue/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.StoredValue; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the StoredValue API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureStoredValue(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddStoredValueHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/StoredValue/Extensions/ServiceCollectionExtensions.cs b/Adyen/StoredValue/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..edcbebc42 --- /dev/null +++ b/Adyen/StoredValue/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen StoredValue API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddStoredValueServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddStoredValueHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/StoredValue/Models/Amount.cs b/Adyen/StoredValue/Models/Amount.cs new file mode 100644 index 000000000..33e0660b4 --- /dev/null +++ b/Adyen/StoredValue/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/StoredValue/Models/ServiceError.cs b/Adyen/StoredValue/Models/ServiceError.cs new file mode 100644 index 000000000..479ede3cb --- /dev/null +++ b/Adyen/StoredValue/Models/ServiceError.cs @@ -0,0 +1,302 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option?> additionalData = default, Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _AdditionalDataOption = additionalData; + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AdditionalDataOption { get; private set; } + + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + /// + /// Contains additional information about the payment. Some data fields are included only if you select them first. Go to **Customer Area** > **Developers** > **Additional data**. + [JsonPropertyName("additionalData")] + public Dictionary? AdditionalData { get { return this._AdditionalDataOption; } set { this._AdditionalDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" AdditionalData: ").Append(AdditionalData).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> additionalData = default; + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "additionalData": + additionalData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(additionalData, errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._AdditionalDataOption.IsSet) + { + writer.WritePropertyName("additionalData"); + JsonSerializer.Serialize(writer, serviceError.AdditionalData, jsonSerializerOptions); + } + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueBalanceCheckRequest.cs b/Adyen/StoredValue/Models/StoredValueBalanceCheckRequest.cs new file mode 100644 index 000000000..ad26289ab --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueBalanceCheckRequest.cs @@ -0,0 +1,469 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueBalanceCheckRequest. + /// + public partial class StoredValueBalanceCheckRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information if available + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// amount + /// recurringDetailReference + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperReference + /// The physical store, for which this payment is processed. + [JsonConstructor] + public StoredValueBalanceCheckRequest(string merchantAccount, Dictionary paymentMethod, string reference, Option amount = default, Option recurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default, Option store = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + _AmountOption = amount; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueBalanceCheckRequest() + { + } + + partial void OnCreated(); + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueBalanceCheckRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueBalanceCheckRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueBalanceCheckRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> paymentMethod = default; + Option reference = default; + Option amount = default; + Option recurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(StoredValueBalanceCheckRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceCheckRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceCheckRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceCheckRequest.", nameof(reference)); + + return new StoredValueBalanceCheckRequest(merchantAccount.Value!, paymentMethod.Value!, reference.Value!, amount, recurringDetailReference, shopperInteraction, shopperReference, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueBalanceCheckRequest storedValueBalanceCheckRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueBalanceCheckRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueBalanceCheckRequest storedValueBalanceCheckRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueBalanceCheckRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueBalanceCheckRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueBalanceCheckRequest.PaymentMethod, jsonSerializerOptions); + if (storedValueBalanceCheckRequest.Reference != null) + writer.WriteString("reference", storedValueBalanceCheckRequest.Reference); + + if (storedValueBalanceCheckRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storedValueBalanceCheckRequest.Amount, jsonSerializerOptions); + } + if (storedValueBalanceCheckRequest._RecurringDetailReferenceOption.IsSet) + if (storedValueBalanceCheckRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedValueBalanceCheckRequest.RecurringDetailReference); + + if (storedValueBalanceCheckRequest._ShopperInteractionOption.IsSet && storedValueBalanceCheckRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = StoredValueBalanceCheckRequest.ShopperInteractionEnum.ToJsonValue(storedValueBalanceCheckRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (storedValueBalanceCheckRequest._ShopperReferenceOption.IsSet) + if (storedValueBalanceCheckRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedValueBalanceCheckRequest.ShopperReference); + + if (storedValueBalanceCheckRequest._StoreOption.IsSet) + if (storedValueBalanceCheckRequest.Store != null) + writer.WriteString("store", storedValueBalanceCheckRequest.Store); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueBalanceCheckResponse.cs b/Adyen/StoredValue/Models/StoredValueBalanceCheckResponse.cs new file mode 100644 index 000000000..12e27975d --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueBalanceCheckResponse.cs @@ -0,0 +1,401 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueBalanceCheckResponse. + /// + public partial class StoredValueBalanceCheckResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// currentBalance + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueBalanceCheckResponse(Option currentBalance = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _CurrentBalanceOption = currentBalance; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueBalanceCheckResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueBalanceCheckResponse {\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueBalanceCheckResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueBalanceCheckResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currentBalance = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueBalanceCheckResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueBalanceCheckResponse(currentBalance, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueBalanceCheckResponse storedValueBalanceCheckResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueBalanceCheckResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueBalanceCheckResponse storedValueBalanceCheckResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueBalanceCheckResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueBalanceCheckResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueBalanceCheckResponse._PspReferenceOption.IsSet) + if (storedValueBalanceCheckResponse.PspReference != null) + writer.WriteString("pspReference", storedValueBalanceCheckResponse.PspReference); + + if (storedValueBalanceCheckResponse._RefusalReasonOption.IsSet) + if (storedValueBalanceCheckResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueBalanceCheckResponse.RefusalReason); + + if (storedValueBalanceCheckResponse._ResultCodeOption.IsSet && storedValueBalanceCheckResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueBalanceCheckResponse.ResultCodeEnum.ToJsonValue(storedValueBalanceCheckResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueBalanceCheckResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueBalanceCheckResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueBalanceCheckResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueBalanceMergeRequest.cs b/Adyen/StoredValue/Models/StoredValueBalanceMergeRequest.cs new file mode 100644 index 000000000..c4418484a --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueBalanceMergeRequest.cs @@ -0,0 +1,488 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueBalanceMergeRequest. + /// + public partial class StoredValueBalanceMergeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information if available + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The collection that contains the source payment method and its specific information if available. Note that type should not be included since it is inferred from the (target) payment method + /// amount + /// recurringDetailReference + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperReference + /// The physical store, for which this payment is processed. + [JsonConstructor] + public StoredValueBalanceMergeRequest(string merchantAccount, Dictionary paymentMethod, string reference, Dictionary sourcePaymentMethod, Option amount = default, Option recurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default, Option store = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + SourcePaymentMethod = sourcePaymentMethod; + _AmountOption = amount; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueBalanceMergeRequest() + { + } + + partial void OnCreated(); + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// The collection that contains the source payment method and its specific information if available. Note that type should not be included since it is inferred from the (target) payment method + /// + /// The collection that contains the source payment method and its specific information if available. Note that type should not be included since it is inferred from the (target) payment method + [JsonPropertyName("sourcePaymentMethod")] + public Dictionary SourcePaymentMethod { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueBalanceMergeRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" SourcePaymentMethod: ").Append(SourcePaymentMethod).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueBalanceMergeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueBalanceMergeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> paymentMethod = default; + Option reference = default; + Option?> sourcePaymentMethod = default; + Option amount = default; + Option recurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "sourcePaymentMethod": + sourcePaymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(StoredValueBalanceMergeRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceMergeRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceMergeRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceMergeRequest.", nameof(reference)); + + if (!sourcePaymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueBalanceMergeRequest.", nameof(sourcePaymentMethod)); + + return new StoredValueBalanceMergeRequest(merchantAccount.Value!, paymentMethod.Value!, reference.Value!, sourcePaymentMethod.Value!, amount, recurringDetailReference, shopperInteraction, shopperReference, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueBalanceMergeRequest storedValueBalanceMergeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueBalanceMergeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueBalanceMergeRequest storedValueBalanceMergeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueBalanceMergeRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueBalanceMergeRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueBalanceMergeRequest.PaymentMethod, jsonSerializerOptions); + if (storedValueBalanceMergeRequest.Reference != null) + writer.WriteString("reference", storedValueBalanceMergeRequest.Reference); + + writer.WritePropertyName("sourcePaymentMethod"); + JsonSerializer.Serialize(writer, storedValueBalanceMergeRequest.SourcePaymentMethod, jsonSerializerOptions); + if (storedValueBalanceMergeRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storedValueBalanceMergeRequest.Amount, jsonSerializerOptions); + } + if (storedValueBalanceMergeRequest._RecurringDetailReferenceOption.IsSet) + if (storedValueBalanceMergeRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedValueBalanceMergeRequest.RecurringDetailReference); + + if (storedValueBalanceMergeRequest._ShopperInteractionOption.IsSet && storedValueBalanceMergeRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = StoredValueBalanceMergeRequest.ShopperInteractionEnum.ToJsonValue(storedValueBalanceMergeRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (storedValueBalanceMergeRequest._ShopperReferenceOption.IsSet) + if (storedValueBalanceMergeRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedValueBalanceMergeRequest.ShopperReference); + + if (storedValueBalanceMergeRequest._StoreOption.IsSet) + if (storedValueBalanceMergeRequest.Store != null) + writer.WriteString("store", storedValueBalanceMergeRequest.Store); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueBalanceMergeResponse.cs b/Adyen/StoredValue/Models/StoredValueBalanceMergeResponse.cs new file mode 100644 index 000000000..0b82d1111 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueBalanceMergeResponse.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueBalanceMergeResponse. + /// + public partial class StoredValueBalanceMergeResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// currentBalance + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueBalanceMergeResponse(Option authCode = default, Option currentBalance = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _AuthCodeOption = authCode; + _CurrentBalanceOption = currentBalance; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueBalanceMergeResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueBalanceMergeResponse {\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueBalanceMergeResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueBalanceMergeResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authCode = default; + Option currentBalance = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueBalanceMergeResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueBalanceMergeResponse(authCode, currentBalance, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueBalanceMergeResponse storedValueBalanceMergeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueBalanceMergeResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueBalanceMergeResponse storedValueBalanceMergeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueBalanceMergeResponse._AuthCodeOption.IsSet) + if (storedValueBalanceMergeResponse.AuthCode != null) + writer.WriteString("authCode", storedValueBalanceMergeResponse.AuthCode); + + if (storedValueBalanceMergeResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueBalanceMergeResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueBalanceMergeResponse._PspReferenceOption.IsSet) + if (storedValueBalanceMergeResponse.PspReference != null) + writer.WriteString("pspReference", storedValueBalanceMergeResponse.PspReference); + + if (storedValueBalanceMergeResponse._RefusalReasonOption.IsSet) + if (storedValueBalanceMergeResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueBalanceMergeResponse.RefusalReason); + + if (storedValueBalanceMergeResponse._ResultCodeOption.IsSet && storedValueBalanceMergeResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueBalanceMergeResponse.ResultCodeEnum.ToJsonValue(storedValueBalanceMergeResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueBalanceMergeResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueBalanceMergeResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueBalanceMergeResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueIssueRequest.cs b/Adyen/StoredValue/Models/StoredValueIssueRequest.cs new file mode 100644 index 000000000..f068ad080 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueIssueRequest.cs @@ -0,0 +1,469 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueIssueRequest. + /// + public partial class StoredValueIssueRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information if available + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// amount + /// recurringDetailReference + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperReference + /// The physical store, for which this payment is processed. + [JsonConstructor] + public StoredValueIssueRequest(string merchantAccount, Dictionary paymentMethod, string reference, Option amount = default, Option recurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default, Option store = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + _AmountOption = amount; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueIssueRequest() + { + } + + partial void OnCreated(); + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueIssueRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueIssueRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueIssueRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> paymentMethod = default; + Option reference = default; + Option amount = default; + Option recurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(StoredValueIssueRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueIssueRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueIssueRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoredValueIssueRequest.", nameof(reference)); + + return new StoredValueIssueRequest(merchantAccount.Value!, paymentMethod.Value!, reference.Value!, amount, recurringDetailReference, shopperInteraction, shopperReference, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueIssueRequest storedValueIssueRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueIssueRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueIssueRequest storedValueIssueRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueIssueRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueIssueRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueIssueRequest.PaymentMethod, jsonSerializerOptions); + if (storedValueIssueRequest.Reference != null) + writer.WriteString("reference", storedValueIssueRequest.Reference); + + if (storedValueIssueRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storedValueIssueRequest.Amount, jsonSerializerOptions); + } + if (storedValueIssueRequest._RecurringDetailReferenceOption.IsSet) + if (storedValueIssueRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedValueIssueRequest.RecurringDetailReference); + + if (storedValueIssueRequest._ShopperInteractionOption.IsSet && storedValueIssueRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = StoredValueIssueRequest.ShopperInteractionEnum.ToJsonValue(storedValueIssueRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (storedValueIssueRequest._ShopperReferenceOption.IsSet) + if (storedValueIssueRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedValueIssueRequest.ShopperReference); + + if (storedValueIssueRequest._StoreOption.IsSet) + if (storedValueIssueRequest.Store != null) + writer.WriteString("store", storedValueIssueRequest.Store); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueIssueResponse.cs b/Adyen/StoredValue/Models/StoredValueIssueResponse.cs new file mode 100644 index 000000000..cddd12689 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueIssueResponse.cs @@ -0,0 +1,452 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueIssueResponse. + /// + public partial class StoredValueIssueResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// currentBalance + /// The collection that contains the type of the payment method and its specific information if available + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueIssueResponse(Option authCode = default, Option currentBalance = default, Option?> paymentMethod = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _AuthCodeOption = authCode; + _CurrentBalanceOption = currentBalance; + _PaymentMethodOption = paymentMethod; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueIssueResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PaymentMethodOption { get; private set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary? PaymentMethod { get { return this._PaymentMethodOption; } set { this._PaymentMethodOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueIssueResponse {\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueIssueResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueIssueResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authCode = default; + Option currentBalance = default; + Option?> paymentMethod = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueIssueResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueIssueResponse(authCode, currentBalance, paymentMethod, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueIssueResponse storedValueIssueResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueIssueResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueIssueResponse storedValueIssueResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueIssueResponse._AuthCodeOption.IsSet) + if (storedValueIssueResponse.AuthCode != null) + writer.WriteString("authCode", storedValueIssueResponse.AuthCode); + + if (storedValueIssueResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueIssueResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueIssueResponse._PaymentMethodOption.IsSet) + { + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueIssueResponse.PaymentMethod, jsonSerializerOptions); + } + if (storedValueIssueResponse._PspReferenceOption.IsSet) + if (storedValueIssueResponse.PspReference != null) + writer.WriteString("pspReference", storedValueIssueResponse.PspReference); + + if (storedValueIssueResponse._RefusalReasonOption.IsSet) + if (storedValueIssueResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueIssueResponse.RefusalReason); + + if (storedValueIssueResponse._ResultCodeOption.IsSet && storedValueIssueResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueIssueResponse.ResultCodeEnum.ToJsonValue(storedValueIssueResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueIssueResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueIssueResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueIssueResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueLoadRequest.cs b/Adyen/StoredValue/Models/StoredValueLoadRequest.cs new file mode 100644 index 000000000..5b0f7ba12 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueLoadRequest.cs @@ -0,0 +1,593 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueLoadRequest. + /// + public partial class StoredValueLoadRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information if available + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The type of load you are trying to do, when absent we default to 'Load' + /// recurringDetailReference + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperReference + /// The physical store, for which this payment is processed. + [JsonConstructor] + public StoredValueLoadRequest(Amount amount, string merchantAccount, Dictionary paymentMethod, string reference, Option loadType = default, Option recurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default, Option store = default) + { + Amount = amount; + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + _LoadTypeOption = loadType; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueLoadRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of load you are trying to do, when absent we default to 'Load' + /// + /// The type of load you are trying to do, when absent we default to 'Load' + [JsonConverter(typeof(LoadTypeEnumJsonConverter))] + public class LoadTypeEnum : IEnum + { + /// + /// Returns the value of the LoadTypeEnum. + /// + public string? Value { get; set; } + + /// + /// LoadTypeEnum.MerchandiseReturn - merchandiseReturn + /// + public static readonly LoadTypeEnum MerchandiseReturn = new("merchandiseReturn"); + + /// + /// LoadTypeEnum.Load - load + /// + public static readonly LoadTypeEnum Load = new("load"); + + private LoadTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator LoadTypeEnum?(string? value) => value == null ? null : new LoadTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(LoadTypeEnum? option) => option?.Value; + + public static bool operator ==(LoadTypeEnum? left, LoadTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(LoadTypeEnum? left, LoadTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is LoadTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static LoadTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "merchandiseReturn" => LoadTypeEnum.MerchandiseReturn, + "load" => LoadTypeEnum.Load, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(LoadTypeEnum? value) + { + if (value == null) + return null; + + if (value == LoadTypeEnum.MerchandiseReturn) + return "merchandiseReturn"; + + if (value == LoadTypeEnum.Load) + return "load"; + + return null; + } + + /// + /// JsonConverter for writing LoadTypeEnum. + /// + public class LoadTypeEnumJsonConverter : JsonConverter + { + public override LoadTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : LoadTypeEnum.FromStringOrDefault(value) ?? new LoadTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, LoadTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(LoadTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LoadTypeOption { get; private set; } + + /// + /// The type of load you are trying to do, when absent we default to 'Load' + /// + /// The type of load you are trying to do, when absent we default to 'Load' + [JsonPropertyName("loadType")] + public LoadTypeEnum? LoadType { get { return this._LoadTypeOption; } set { this._LoadTypeOption = new(value); } } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueLoadRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" LoadType: ").Append(LoadType).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueLoadRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueLoadRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option merchantAccount = default; + Option?> paymentMethod = default; + Option reference = default; + Option loadType = default; + Option recurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "loadType": + string? loadTypeRawValue = utf8JsonReader.GetString(); + loadType = new Option(StoredValueLoadRequest.LoadTypeEnum.FromStringOrDefault(loadTypeRawValue)); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(StoredValueLoadRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class StoredValueLoadRequest.", nameof(amount)); + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueLoadRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueLoadRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoredValueLoadRequest.", nameof(reference)); + + return new StoredValueLoadRequest(amount.Value!, merchantAccount.Value!, paymentMethod.Value!, reference.Value!, loadType, recurringDetailReference, shopperInteraction, shopperReference, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueLoadRequest storedValueLoadRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueLoadRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueLoadRequest storedValueLoadRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storedValueLoadRequest.Amount, jsonSerializerOptions); + if (storedValueLoadRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueLoadRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueLoadRequest.PaymentMethod, jsonSerializerOptions); + if (storedValueLoadRequest.Reference != null) + writer.WriteString("reference", storedValueLoadRequest.Reference); + + if (storedValueLoadRequest._LoadTypeOption.IsSet && storedValueLoadRequest.LoadType != null) + { + string? loadTypeRawValue = StoredValueLoadRequest.LoadTypeEnum.ToJsonValue(storedValueLoadRequest._LoadTypeOption.Value!.Value); + writer.WriteString("loadType", loadTypeRawValue); + } + + if (storedValueLoadRequest._RecurringDetailReferenceOption.IsSet) + if (storedValueLoadRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedValueLoadRequest.RecurringDetailReference); + + if (storedValueLoadRequest._ShopperInteractionOption.IsSet && storedValueLoadRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = StoredValueLoadRequest.ShopperInteractionEnum.ToJsonValue(storedValueLoadRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (storedValueLoadRequest._ShopperReferenceOption.IsSet) + if (storedValueLoadRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedValueLoadRequest.ShopperReference); + + if (storedValueLoadRequest._StoreOption.IsSet) + if (storedValueLoadRequest.Store != null) + writer.WriteString("store", storedValueLoadRequest.Store); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueLoadResponse.cs b/Adyen/StoredValue/Models/StoredValueLoadResponse.cs new file mode 100644 index 000000000..9ddfd2fde --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueLoadResponse.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueLoadResponse. + /// + public partial class StoredValueLoadResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// currentBalance + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueLoadResponse(Option authCode = default, Option currentBalance = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _AuthCodeOption = authCode; + _CurrentBalanceOption = currentBalance; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueLoadResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueLoadResponse {\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueLoadResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueLoadResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authCode = default; + Option currentBalance = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueLoadResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueLoadResponse(authCode, currentBalance, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueLoadResponse storedValueLoadResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueLoadResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueLoadResponse storedValueLoadResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueLoadResponse._AuthCodeOption.IsSet) + if (storedValueLoadResponse.AuthCode != null) + writer.WriteString("authCode", storedValueLoadResponse.AuthCode); + + if (storedValueLoadResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueLoadResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueLoadResponse._PspReferenceOption.IsSet) + if (storedValueLoadResponse.PspReference != null) + writer.WriteString("pspReference", storedValueLoadResponse.PspReference); + + if (storedValueLoadResponse._RefusalReasonOption.IsSet) + if (storedValueLoadResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueLoadResponse.RefusalReason); + + if (storedValueLoadResponse._ResultCodeOption.IsSet && storedValueLoadResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueLoadResponse.ResultCodeEnum.ToJsonValue(storedValueLoadResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueLoadResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueLoadResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueLoadResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueStatusChangeRequest.cs b/Adyen/StoredValue/Models/StoredValueStatusChangeRequest.cs new file mode 100644 index 000000000..6f72ce8e9 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueStatusChangeRequest.cs @@ -0,0 +1,596 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueStatusChangeRequest. + /// + public partial class StoredValueStatusChangeRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The collection that contains the type of the payment method and its specific information if available + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// The status you want to change to + /// amount + /// recurringDetailReference + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// shopperReference + /// The physical store, for which this payment is processed. + [JsonConstructor] + public StoredValueStatusChangeRequest(string merchantAccount, Dictionary paymentMethod, string reference, StatusEnum status, Option amount = default, Option recurringDetailReference = default, Option shopperInteraction = default, Option shopperReference = default, Option store = default) + { + MerchantAccount = merchantAccount; + PaymentMethod = paymentMethod; + Reference = reference; + Status = status; + _AmountOption = amount; + _RecurringDetailReferenceOption = recurringDetailReference; + _ShopperInteractionOption = shopperInteraction; + _ShopperReferenceOption = shopperReference; + _StoreOption = store; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueStatusChangeRequest() + { + } + + partial void OnCreated(); + + /// + /// The status you want to change to + /// + /// The status you want to change to + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Active - active + /// + public static readonly StatusEnum Active = new("active"); + + /// + /// StatusEnum.Inactive - inactive + /// + public static readonly StatusEnum Inactive = new("inactive"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "active" => StatusEnum.Active, + "inactive" => StatusEnum.Inactive, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Active) + return "active"; + + if (value == StatusEnum.Inactive) + return "inactive"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status you want to change to + /// + /// The status you want to change to + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonConverter(typeof(ShopperInteractionEnumJsonConverter))] + public class ShopperInteractionEnum : IEnum + { + /// + /// Returns the value of the ShopperInteractionEnum. + /// + public string? Value { get; set; } + + /// + /// ShopperInteractionEnum.Ecommerce - Ecommerce + /// + public static readonly ShopperInteractionEnum Ecommerce = new("Ecommerce"); + + /// + /// ShopperInteractionEnum.ContAuth - ContAuth + /// + public static readonly ShopperInteractionEnum ContAuth = new("ContAuth"); + + /// + /// ShopperInteractionEnum.Moto - Moto + /// + public static readonly ShopperInteractionEnum Moto = new("Moto"); + + /// + /// ShopperInteractionEnum.POS - POS + /// + public static readonly ShopperInteractionEnum POS = new("POS"); + + private ShopperInteractionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ShopperInteractionEnum?(string? value) => value == null ? null : new ShopperInteractionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ShopperInteractionEnum? option) => option?.Value; + + public static bool operator ==(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ShopperInteractionEnum? left, ShopperInteractionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ShopperInteractionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ShopperInteractionEnum? FromStringOrDefault(string value) + { + return value switch { + "Ecommerce" => ShopperInteractionEnum.Ecommerce, + "ContAuth" => ShopperInteractionEnum.ContAuth, + "Moto" => ShopperInteractionEnum.Moto, + "POS" => ShopperInteractionEnum.POS, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ShopperInteractionEnum? value) + { + if (value == null) + return null; + + if (value == ShopperInteractionEnum.Ecommerce) + return "Ecommerce"; + + if (value == ShopperInteractionEnum.ContAuth) + return "ContAuth"; + + if (value == ShopperInteractionEnum.Moto) + return "Moto"; + + if (value == ShopperInteractionEnum.POS) + return "POS"; + + return null; + } + + /// + /// JsonConverter for writing ShopperInteractionEnum. + /// + public class ShopperInteractionEnumJsonConverter : JsonConverter + { + public override ShopperInteractionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ShopperInteractionEnum.FromStringOrDefault(value) ?? new ShopperInteractionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ShopperInteractionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ShopperInteractionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperInteractionOption { get; private set; } + + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + /// + /// Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper interaction by default. This field has the following possible values: * `Ecommerce` - Online transactions where the cardholder is present (online). For better authorisation rates, we recommend sending the card security code (CSC) along with the request. * `ContAuth` - Card on file and/or subscription transactions, where the cardholder is known to the merchant (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * `Moto` - Mail-order and telephone-order transactions where the shopper is in contact with the merchant via email or telephone. * `POS` - Point-of-sale transactions where the shopper is physically present to make a payment using a secure payment terminal. + [JsonPropertyName("shopperInteraction")] + public ShopperInteractionEnum? ShopperInteraction { get { return this._ShopperInteractionOption; } set { this._ShopperInteractionOption = new(value); } } + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The collection that contains the type of the payment method and its specific information if available + /// + /// The collection that contains the type of the payment method and its specific information if available + [JsonPropertyName("paymentMethod")] + public Dictionary PaymentMethod { get; set; } + + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + /// + /// The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RecurringDetailReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("recurringDetailReference")] + public string? RecurringDetailReference { get { return this._RecurringDetailReferenceOption; } set { this._RecurringDetailReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ShopperReferenceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("shopperReference")] + public string? ShopperReference { get { return this._ShopperReferenceOption; } set { this._ShopperReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueStatusChangeRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" RecurringDetailReference: ").Append(RecurringDetailReference).Append("\n"); + sb.Append(" ShopperInteraction: ").Append(ShopperInteraction).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueStatusChangeRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueStatusChangeRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option?> paymentMethod = default; + Option reference = default; + Option status = default; + Option amount = default; + Option recurringDetailReference = default; + Option shopperInteraction = default; + Option shopperReference = default; + Option store = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMethod": + paymentMethod = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(StoredValueStatusChangeRequest.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recurringDetailReference": + recurringDetailReference = new Option(utf8JsonReader.GetString()!); + break; + case "shopperInteraction": + string? shopperInteractionRawValue = utf8JsonReader.GetString(); + shopperInteraction = new Option(StoredValueStatusChangeRequest.ShopperInteractionEnum.FromStringOrDefault(shopperInteractionRawValue)); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueStatusChangeRequest.", nameof(merchantAccount)); + + if (!paymentMethod.IsSet) + throw new ArgumentException("Property is required for class StoredValueStatusChangeRequest.", nameof(paymentMethod)); + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class StoredValueStatusChangeRequest.", nameof(reference)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class StoredValueStatusChangeRequest.", nameof(status)); + + return new StoredValueStatusChangeRequest(merchantAccount.Value!, paymentMethod.Value!, reference.Value!, status.Value!.Value!, amount, recurringDetailReference, shopperInteraction, shopperReference, store); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueStatusChangeRequest storedValueStatusChangeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueStatusChangeRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueStatusChangeRequest storedValueStatusChangeRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueStatusChangeRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueStatusChangeRequest.MerchantAccount); + + writer.WritePropertyName("paymentMethod"); + JsonSerializer.Serialize(writer, storedValueStatusChangeRequest.PaymentMethod, jsonSerializerOptions); + if (storedValueStatusChangeRequest.Reference != null) + writer.WriteString("reference", storedValueStatusChangeRequest.Reference); + + if (storedValueStatusChangeRequest.Status != null) + { + string? statusRawValue = StoredValueStatusChangeRequest.StatusEnum.ToJsonValue(storedValueStatusChangeRequest.Status); + writer.WriteString("status", statusRawValue); + } + + if (storedValueStatusChangeRequest._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, storedValueStatusChangeRequest.Amount, jsonSerializerOptions); + } + if (storedValueStatusChangeRequest._RecurringDetailReferenceOption.IsSet) + if (storedValueStatusChangeRequest.RecurringDetailReference != null) + writer.WriteString("recurringDetailReference", storedValueStatusChangeRequest.RecurringDetailReference); + + if (storedValueStatusChangeRequest._ShopperInteractionOption.IsSet && storedValueStatusChangeRequest.ShopperInteraction != null) + { + string? shopperInteractionRawValue = StoredValueStatusChangeRequest.ShopperInteractionEnum.ToJsonValue(storedValueStatusChangeRequest._ShopperInteractionOption.Value!.Value); + writer.WriteString("shopperInteraction", shopperInteractionRawValue); + } + + if (storedValueStatusChangeRequest._ShopperReferenceOption.IsSet) + if (storedValueStatusChangeRequest.ShopperReference != null) + writer.WriteString("shopperReference", storedValueStatusChangeRequest.ShopperReference); + + if (storedValueStatusChangeRequest._StoreOption.IsSet) + if (storedValueStatusChangeRequest.Store != null) + writer.WriteString("store", storedValueStatusChangeRequest.Store); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueStatusChangeResponse.cs b/Adyen/StoredValue/Models/StoredValueStatusChangeResponse.cs new file mode 100644 index 000000000..e8a60e26a --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueStatusChangeResponse.cs @@ -0,0 +1,426 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueStatusChangeResponse. + /// + public partial class StoredValueStatusChangeResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// currentBalance + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueStatusChangeResponse(Option authCode = default, Option currentBalance = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _AuthCodeOption = authCode; + _CurrentBalanceOption = currentBalance; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueStatusChangeResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthCodeOption { get; private set; } + + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + /// + /// Authorisation code: * When the payment is authorised, this field holds the authorisation code for the payment. * When the payment is not authorised, this field is empty. + [JsonPropertyName("authCode")] + public string? AuthCode { get { return this._AuthCodeOption; } set { this._AuthCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueStatusChangeResponse {\n"); + sb.Append(" AuthCode: ").Append(AuthCode).Append("\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueStatusChangeResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueStatusChangeResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authCode = default; + Option currentBalance = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authCode": + authCode = new Option(utf8JsonReader.GetString()!); + break; + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueStatusChangeResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueStatusChangeResponse(authCode, currentBalance, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueStatusChangeResponse storedValueStatusChangeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueStatusChangeResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueStatusChangeResponse storedValueStatusChangeResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueStatusChangeResponse._AuthCodeOption.IsSet) + if (storedValueStatusChangeResponse.AuthCode != null) + writer.WriteString("authCode", storedValueStatusChangeResponse.AuthCode); + + if (storedValueStatusChangeResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueStatusChangeResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueStatusChangeResponse._PspReferenceOption.IsSet) + if (storedValueStatusChangeResponse.PspReference != null) + writer.WriteString("pspReference", storedValueStatusChangeResponse.PspReference); + + if (storedValueStatusChangeResponse._RefusalReasonOption.IsSet) + if (storedValueStatusChangeResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueStatusChangeResponse.RefusalReason); + + if (storedValueStatusChangeResponse._ResultCodeOption.IsSet && storedValueStatusChangeResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueStatusChangeResponse.ResultCodeEnum.ToJsonValue(storedValueStatusChangeResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueStatusChangeResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueStatusChangeResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueStatusChangeResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueVoidRequest.cs b/Adyen/StoredValue/Models/StoredValueVoidRequest.cs new file mode 100644 index 000000000..c87246ec1 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueVoidRequest.cs @@ -0,0 +1,303 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueVoidRequest. + /// + public partial class StoredValueVoidRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The merchant account identifier, with which you want to process the transaction. + /// The original pspReference of the payment to modify. + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// The physical store, for which this payment is processed. + /// The reference of the tender. + /// The unique ID of a POS terminal. + [JsonConstructor] + public StoredValueVoidRequest(string merchantAccount, string originalReference, Option reference = default, Option store = default, Option tenderReference = default, Option uniqueTerminalId = default) + { + MerchantAccount = merchantAccount; + OriginalReference = originalReference; + _ReferenceOption = reference; + _StoreOption = store; + _TenderReferenceOption = tenderReference; + _UniqueTerminalIdOption = uniqueTerminalId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueVoidRequest() + { + } + + partial void OnCreated(); + + /// + /// The merchant account identifier, with which you want to process the transaction. + /// + /// The merchant account identifier, with which you want to process the transaction. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// The original pspReference of the payment to modify. + /// + /// The original pspReference of the payment to modify. + [JsonPropertyName("originalReference")] + public string OriginalReference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + /// + /// Your reference for the payment modification. This reference is visible in Customer Area and in reports. Maximum length: 80 characters. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoreOption { get; private set; } + + /// + /// The physical store, for which this payment is processed. + /// + /// The physical store, for which this payment is processed. + [JsonPropertyName("store")] + public string? Store { get { return this._StoreOption; } set { this._StoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TenderReferenceOption { get; private set; } + + /// + /// The reference of the tender. + /// + /// The reference of the tender. + [JsonPropertyName("tenderReference")] + public string? TenderReference { get { return this._TenderReferenceOption; } set { this._TenderReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UniqueTerminalIdOption { get; private set; } + + /// + /// The unique ID of a POS terminal. + /// + /// The unique ID of a POS terminal. + [JsonPropertyName("uniqueTerminalId")] + public string? UniqueTerminalId { get { return this._UniqueTerminalIdOption; } set { this._UniqueTerminalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueVoidRequest {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" OriginalReference: ").Append(OriginalReference).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" TenderReference: ").Append(TenderReference).Append("\n"); + sb.Append(" UniqueTerminalId: ").Append(UniqueTerminalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Store (string) maxLength + if (this.Store != null && this.Store.Length > 16) + { + yield return new ValidationResult("Invalid value for Store, length must be less than 16.", new [] { "Store" }); + } + + // Store (string) minLength + if (this.Store != null && this.Store.Length < 1) + { + yield return new ValidationResult("Invalid value for Store, length must be greater than 1.", new [] { "Store" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueVoidRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueVoidRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option originalReference = default; + Option reference = default; + Option store = default; + Option tenderReference = default; + Option uniqueTerminalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "originalReference": + originalReference = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "store": + store = new Option(utf8JsonReader.GetString()!); + break; + case "tenderReference": + tenderReference = new Option(utf8JsonReader.GetString()!); + break; + case "uniqueTerminalId": + uniqueTerminalId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class StoredValueVoidRequest.", nameof(merchantAccount)); + + if (!originalReference.IsSet) + throw new ArgumentException("Property is required for class StoredValueVoidRequest.", nameof(originalReference)); + + return new StoredValueVoidRequest(merchantAccount.Value!, originalReference.Value!, reference, store, tenderReference, uniqueTerminalId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueVoidRequest storedValueVoidRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueVoidRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueVoidRequest storedValueVoidRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueVoidRequest.MerchantAccount != null) + writer.WriteString("merchantAccount", storedValueVoidRequest.MerchantAccount); + + if (storedValueVoidRequest.OriginalReference != null) + writer.WriteString("originalReference", storedValueVoidRequest.OriginalReference); + + if (storedValueVoidRequest._ReferenceOption.IsSet) + if (storedValueVoidRequest.Reference != null) + writer.WriteString("reference", storedValueVoidRequest.Reference); + + if (storedValueVoidRequest._StoreOption.IsSet) + if (storedValueVoidRequest.Store != null) + writer.WriteString("store", storedValueVoidRequest.Store); + + if (storedValueVoidRequest._TenderReferenceOption.IsSet) + if (storedValueVoidRequest.TenderReference != null) + writer.WriteString("tenderReference", storedValueVoidRequest.TenderReference); + + if (storedValueVoidRequest._UniqueTerminalIdOption.IsSet) + if (storedValueVoidRequest.UniqueTerminalId != null) + writer.WriteString("uniqueTerminalId", storedValueVoidRequest.UniqueTerminalId); + } + } +} diff --git a/Adyen/StoredValue/Models/StoredValueVoidResponse.cs b/Adyen/StoredValue/Models/StoredValueVoidResponse.cs new file mode 100644 index 000000000..0f60505d2 --- /dev/null +++ b/Adyen/StoredValue/Models/StoredValueVoidResponse.cs @@ -0,0 +1,401 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.StoredValue.Client; + +namespace Adyen.StoredValue.Models +{ + /// + /// StoredValueVoidResponse. + /// + public partial class StoredValueVoidResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// currentBalance + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// Raw refusal reason received from the third party, where available + [JsonConstructor] + public StoredValueVoidResponse(Option currentBalance = default, Option pspReference = default, Option refusalReason = default, Option resultCode = default, Option thirdPartyRefusalReason = default) + { + _CurrentBalanceOption = currentBalance; + _PspReferenceOption = pspReference; + _RefusalReasonOption = refusalReason; + _ResultCodeOption = resultCode; + _ThirdPartyRefusalReasonOption = thirdPartyRefusalReason; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public StoredValueVoidResponse() + { + } + + partial void OnCreated(); + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonConverter(typeof(ResultCodeEnumJsonConverter))] + public class ResultCodeEnum : IEnum + { + /// + /// Returns the value of the ResultCodeEnum. + /// + public string? Value { get; set; } + + /// + /// ResultCodeEnum.Success - Success + /// + public static readonly ResultCodeEnum Success = new("Success"); + + /// + /// ResultCodeEnum.Refused - Refused + /// + public static readonly ResultCodeEnum Refused = new("Refused"); + + /// + /// ResultCodeEnum.Error - Error + /// + public static readonly ResultCodeEnum Error = new("Error"); + + /// + /// ResultCodeEnum.NotEnoughBalance - NotEnoughBalance + /// + public static readonly ResultCodeEnum NotEnoughBalance = new("NotEnoughBalance"); + + private ResultCodeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ResultCodeEnum?(string? value) => value == null ? null : new ResultCodeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ResultCodeEnum? option) => option?.Value; + + public static bool operator ==(ResultCodeEnum? left, ResultCodeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ResultCodeEnum? left, ResultCodeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ResultCodeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ResultCodeEnum? FromStringOrDefault(string value) + { + return value switch { + "Success" => ResultCodeEnum.Success, + "Refused" => ResultCodeEnum.Refused, + "Error" => ResultCodeEnum.Error, + "NotEnoughBalance" => ResultCodeEnum.NotEnoughBalance, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ResultCodeEnum? value) + { + if (value == null) + return null; + + if (value == ResultCodeEnum.Success) + return "Success"; + + if (value == ResultCodeEnum.Refused) + return "Refused"; + + if (value == ResultCodeEnum.Error) + return "Error"; + + if (value == ResultCodeEnum.NotEnoughBalance) + return "NotEnoughBalance"; + + return null; + } + + /// + /// JsonConverter for writing ResultCodeEnum. + /// + public class ResultCodeEnumJsonConverter : JsonConverter + { + public override ResultCodeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ResultCodeEnum.FromStringOrDefault(value) ?? new ResultCodeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ResultCodeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ResultCodeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultCodeOption { get; private set; } + + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + /// + /// The result of the payment. Possible values: * **Success** – The operation has been completed successfully. * **Refused** – The operation was refused. The reason is given in the `refusalReason` field. * **Error** – There was an error when the operation was processed. The reason is given in the `refusalReason` field. * **NotEnoughBalance** – The amount on the payment method is lower than the amount given in the request. Only applicable to balance checks. + [JsonPropertyName("resultCode")] + public ResultCodeEnum? ResultCode { get { return this._ResultCodeOption; } set { this._ResultCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrentBalanceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("currentBalance")] + public Amount? CurrentBalance { get { return this._CurrentBalanceOption; } set { this._CurrentBalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + /// + /// Adyen's 16-character string reference associated with the transaction/request. This value is globally unique; quote it when communicating with us about this request. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RefusalReasonOption { get; private set; } + + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + /// + /// If the transaction is refused or an error occurs, this field holds Adyen's mapped reason for the refusal or a description of the error. When a transaction fails, the authorisation response includes `resultCode` and `refusalReason` values. + [JsonPropertyName("refusalReason")] + public string? RefusalReason { get { return this._RefusalReasonOption; } set { this._RefusalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThirdPartyRefusalReasonOption { get; private set; } + + /// + /// Raw refusal reason received from the third party, where available + /// + /// Raw refusal reason received from the third party, where available + [JsonPropertyName("thirdPartyRefusalReason")] + public string? ThirdPartyRefusalReason { get { return this._ThirdPartyRefusalReasonOption; } set { this._ThirdPartyRefusalReasonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class StoredValueVoidResponse {\n"); + sb.Append(" CurrentBalance: ").Append(CurrentBalance).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" RefusalReason: ").Append(RefusalReason).Append("\n"); + sb.Append(" ResultCode: ").Append(ResultCode).Append("\n"); + sb.Append(" ThirdPartyRefusalReason: ").Append(ThirdPartyRefusalReason).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class StoredValueVoidResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override StoredValueVoidResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currentBalance = default; + Option pspReference = default; + Option refusalReason = default; + Option resultCode = default; + Option thirdPartyRefusalReason = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currentBalance": + currentBalance = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "refusalReason": + refusalReason = new Option(utf8JsonReader.GetString()!); + break; + case "resultCode": + string? resultCodeRawValue = utf8JsonReader.GetString(); + resultCode = new Option(StoredValueVoidResponse.ResultCodeEnum.FromStringOrDefault(resultCodeRawValue)); + break; + case "thirdPartyRefusalReason": + thirdPartyRefusalReason = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new StoredValueVoidResponse(currentBalance, pspReference, refusalReason, resultCode, thirdPartyRefusalReason); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, StoredValueVoidResponse storedValueVoidResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, storedValueVoidResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, StoredValueVoidResponse storedValueVoidResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (storedValueVoidResponse._CurrentBalanceOption.IsSet) + { + writer.WritePropertyName("currentBalance"); + JsonSerializer.Serialize(writer, storedValueVoidResponse.CurrentBalance, jsonSerializerOptions); + } + if (storedValueVoidResponse._PspReferenceOption.IsSet) + if (storedValueVoidResponse.PspReference != null) + writer.WriteString("pspReference", storedValueVoidResponse.PspReference); + + if (storedValueVoidResponse._RefusalReasonOption.IsSet) + if (storedValueVoidResponse.RefusalReason != null) + writer.WriteString("refusalReason", storedValueVoidResponse.RefusalReason); + + if (storedValueVoidResponse._ResultCodeOption.IsSet && storedValueVoidResponse.ResultCode != null) + { + string? resultCodeRawValue = StoredValueVoidResponse.ResultCodeEnum.ToJsonValue(storedValueVoidResponse._ResultCodeOption.Value!.Value); + writer.WriteString("resultCode", resultCodeRawValue); + } + + if (storedValueVoidResponse._ThirdPartyRefusalReasonOption.IsSet) + if (storedValueVoidResponse.ThirdPartyRefusalReason != null) + writer.WriteString("thirdPartyRefusalReason", storedValueVoidResponse.ThirdPartyRefusalReason); + } + } +} diff --git a/Adyen/StoredValue/Services/StoredValueService.cs b/Adyen/StoredValue/Services/StoredValueService.cs new file mode 100644 index 000000000..63b83fbde --- /dev/null +++ b/Adyen/StoredValue/Services/StoredValueService.cs @@ -0,0 +1,2497 @@ +// +/* + * Adyen Stored Value API + * + * A set of API endpoints to manage stored value products. + * + * The version of the OpenAPI document: 46 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.StoredValue.Client; +using Adyen.StoredValue.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.StoredValue.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface IStoredValueService : IAdyenApiService + { + /// + /// The class containing the events. + /// + StoredValueServiceEvents Events { get; } + + /// + /// Changes the status of the payment method. + /// + /// + /// Changes the status of the provided payment method to the specified status. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task ChangeStatusAsync(StoredValueStatusChangeRequest storedValueStatusChangeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Checks the balance. + /// + /// + /// Checks the balance of the provided payment method. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task CheckBalanceAsync(StoredValueBalanceCheckRequest storedValueBalanceCheckRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Issues a new card. + /// + /// + /// Issues a new card of the given payment method. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task IssueAsync(StoredValueIssueRequest storedValueIssueRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Loads the payment method. + /// + /// + /// Loads the payment method with the specified funds. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task LoadAsync(StoredValueLoadRequest storedValueLoadRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Merge the balance of two cards. + /// + /// + /// Increases the balance of the paymentmethod by the full amount left on the source paymentmethod + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task MergeBalanceAsync(StoredValueBalanceMergeRequest storedValueBalanceMergeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Voids a transaction. + /// + /// + /// Voids the referenced stored value transaction. + /// + /// Thrown when fails to make API call. + /// + /// . + /// . + /// of . + Task VoidTransactionAsync(StoredValueVoidRequest storedValueVoidRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IChangeStatusApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICheckBalanceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IIssueApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ILoadApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IMergeBalanceApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IVoidTransactionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class StoredValueServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnChangeStatus; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorChangeStatus; + + internal void ExecuteOnChangeStatus(StoredValueService.ChangeStatusApiResponse apiResponse) + { + OnChangeStatus?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorChangeStatus(Exception exception) + { + OnErrorChangeStatus?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCheckBalance; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCheckBalance; + + internal void ExecuteOnCheckBalance(StoredValueService.CheckBalanceApiResponse apiResponse) + { + OnCheckBalance?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCheckBalance(Exception exception) + { + OnErrorCheckBalance?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnIssue; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorIssue; + + internal void ExecuteOnIssue(StoredValueService.IssueApiResponse apiResponse) + { + OnIssue?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorIssue(Exception exception) + { + OnErrorIssue?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnLoad; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorLoad; + + internal void ExecuteOnLoad(StoredValueService.LoadApiResponse apiResponse) + { + OnLoad?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorLoad(Exception exception) + { + OnErrorLoad?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnMergeBalance; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorMergeBalance; + + internal void ExecuteOnMergeBalance(StoredValueService.MergeBalanceApiResponse apiResponse) + { + OnMergeBalance?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorMergeBalance(Exception exception) + { + OnErrorMergeBalance?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnVoidTransaction; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorVoidTransaction; + + internal void ExecuteOnVoidTransaction(StoredValueService.VoidTransactionApiResponse apiResponse) + { + OnVoidTransaction?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorVoidTransaction(Exception exception) + { + OnErrorVoidTransaction?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class StoredValueService : IStoredValueService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public StoredValueServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public StoredValueService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, StoredValueServiceEvents storedValueServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = storedValueServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Changes the status of the payment method. Changes the status of the provided payment method to the specified status. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ChangeStatusAsync(StoredValueStatusChangeRequest storedValueStatusChangeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/changeStatus" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/changeStatus"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueStatusChangeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueStatusChangeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ChangeStatusApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/changeStatus", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnChangeStatus(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorChangeStatus(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ChangeStatusApiResponse : Adyen.Core.Client.ApiResponse, IChangeStatusApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ChangeStatusApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ChangeStatusApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueStatusChangeResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueStatusChangeResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Checks the balance. Checks the balance of the provided payment method. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CheckBalanceAsync(StoredValueBalanceCheckRequest storedValueBalanceCheckRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/checkBalance" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/checkBalance"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueBalanceCheckRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueBalanceCheckRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CheckBalanceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/checkBalance", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCheckBalance(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCheckBalance(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CheckBalanceApiResponse : Adyen.Core.Client.ApiResponse, ICheckBalanceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckBalanceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CheckBalanceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueBalanceCheckResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueBalanceCheckResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Issues a new card. Issues a new card of the given payment method. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task IssueAsync(StoredValueIssueRequest storedValueIssueRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/issue" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/issue"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueIssueRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueIssueRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + IssueApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/issue", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnIssue(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorIssue(exception); + throw; + } + } + + /// + /// The . + /// + public partial class IssueApiResponse : Adyen.Core.Client.ApiResponse, IIssueApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public IssueApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public IssueApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueIssueResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueIssueResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Loads the payment method. Loads the payment method with the specified funds. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task LoadAsync(StoredValueLoadRequest storedValueLoadRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/load" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/load"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueLoadRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueLoadRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + LoadApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/load", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnLoad(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorLoad(exception); + throw; + } + } + + /// + /// The . + /// + public partial class LoadApiResponse : Adyen.Core.Client.ApiResponse, ILoadApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public LoadApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public LoadApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueLoadResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueLoadResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Merge the balance of two cards. Increases the balance of the paymentmethod by the full amount left on the source paymentmethod + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task MergeBalanceAsync(StoredValueBalanceMergeRequest storedValueBalanceMergeRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/mergeBalance" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/mergeBalance"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueBalanceMergeRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueBalanceMergeRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + MergeBalanceApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/mergeBalance", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnMergeBalance(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorMergeBalance(exception); + throw; + } + } + + /// + /// The . + /// + public partial class MergeBalanceApiResponse : Adyen.Core.Client.ApiResponse, IMergeBalanceApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public MergeBalanceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public MergeBalanceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueBalanceMergeResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueBalanceMergeResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Voids a transaction. Voids the referenced stored value transaction. + /// + /// Thrown when fails to make API call. + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task VoidTransactionAsync(StoredValueVoidRequest storedValueVoidRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/voidTransaction" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/voidTransaction"); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (storedValueVoidRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(storedValueVoidRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + VoidTransactionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/voidTransaction", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnVoidTransaction(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorVoidTransaction(exception); + throw; + } + } + + /// + /// The . + /// + public partial class VoidTransactionApiResponse : Adyen.Core.Client.ApiResponse, IVoidTransactionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public VoidTransactionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public VoidTransactionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.StoredValue.Models.StoredValueVoidResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.StoredValueVoidResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.StoredValue.Models.ServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.StoredValue.Models.ServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.StoredValue.Models.ServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.StoredValue.Models.ServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/ApiSerialization/Converter/JsonBase64Converter.cs b/Adyen/TerminalApi/ApiSerialization/Converter/JsonBase64Converter.cs similarity index 100% rename from Adyen/ApiSerialization/Converter/JsonBase64Converter.cs rename to Adyen/TerminalApi/ApiSerialization/Converter/JsonBase64Converter.cs diff --git a/Adyen/ApiSerialization/Converter/JsonConvertDeserializerWrapper.cs b/Adyen/TerminalApi/ApiSerialization/Converter/JsonConvertDeserializerWrapper.cs similarity index 100% rename from Adyen/ApiSerialization/Converter/JsonConvertDeserializerWrapper.cs rename to Adyen/TerminalApi/ApiSerialization/Converter/JsonConvertDeserializerWrapper.cs diff --git a/Adyen/ApiSerialization/Converter/JsonConvertSerializerWrapper.cs b/Adyen/TerminalApi/ApiSerialization/Converter/JsonConvertSerializerWrapper.cs similarity index 100% rename from Adyen/ApiSerialization/Converter/JsonConvertSerializerWrapper.cs rename to Adyen/TerminalApi/ApiSerialization/Converter/JsonConvertSerializerWrapper.cs diff --git a/Adyen/ApiSerialization/Converter/SaleToPoiMessageConverter.cs b/Adyen/TerminalApi/ApiSerialization/Converter/SaleToPoiMessageConverter.cs similarity index 100% rename from Adyen/ApiSerialization/Converter/SaleToPoiMessageConverter.cs rename to Adyen/TerminalApi/ApiSerialization/Converter/SaleToPoiMessageConverter.cs diff --git a/Adyen/ApiSerialization/Converter/SaleToPoiMessageSecuredConverter.cs b/Adyen/TerminalApi/ApiSerialization/Converter/SaleToPoiMessageSecuredConverter.cs similarity index 100% rename from Adyen/ApiSerialization/Converter/SaleToPoiMessageSecuredConverter.cs rename to Adyen/TerminalApi/ApiSerialization/Converter/SaleToPoiMessageSecuredConverter.cs diff --git a/Adyen/ApiSerialization/IMessagePayload.cs b/Adyen/TerminalApi/ApiSerialization/IMessagePayload.cs similarity index 100% rename from Adyen/ApiSerialization/IMessagePayload.cs rename to Adyen/TerminalApi/ApiSerialization/IMessagePayload.cs diff --git a/Adyen/ApiSerialization/IMessagePayloadSerializer.cs b/Adyen/TerminalApi/ApiSerialization/IMessagePayloadSerializer.cs similarity index 100% rename from Adyen/ApiSerialization/IMessagePayloadSerializer.cs rename to Adyen/TerminalApi/ApiSerialization/IMessagePayloadSerializer.cs diff --git a/Adyen/ApiSerialization/MessageHeaderSerializer.cs b/Adyen/TerminalApi/ApiSerialization/MessageHeaderSerializer.cs similarity index 100% rename from Adyen/ApiSerialization/MessageHeaderSerializer.cs rename to Adyen/TerminalApi/ApiSerialization/MessageHeaderSerializer.cs diff --git a/Adyen/ApiSerialization/MessagePayloadSerializer.cs b/Adyen/TerminalApi/ApiSerialization/MessagePayloadSerializer.cs similarity index 100% rename from Adyen/ApiSerialization/MessagePayloadSerializer.cs rename to Adyen/TerminalApi/ApiSerialization/MessagePayloadSerializer.cs diff --git a/Adyen/ApiSerialization/MessagePayloadSerializerFactory.cs b/Adyen/TerminalApi/ApiSerialization/MessagePayloadSerializerFactory.cs similarity index 100% rename from Adyen/ApiSerialization/MessagePayloadSerializerFactory.cs rename to Adyen/TerminalApi/ApiSerialization/MessagePayloadSerializerFactory.cs diff --git a/Adyen/ApiSerialization/OpenAPIDateConverter.cs b/Adyen/TerminalApi/ApiSerialization/OpenAPIDateConverter.cs similarity index 100% rename from Adyen/ApiSerialization/OpenAPIDateConverter.cs rename to Adyen/TerminalApi/ApiSerialization/OpenAPIDateConverter.cs diff --git a/Adyen/ApiSerialization/SaleToPoiMessageSecuredSerializer.cs b/Adyen/TerminalApi/ApiSerialization/SaleToPoiMessageSecuredSerializer.cs similarity index 100% rename from Adyen/ApiSerialization/SaleToPoiMessageSecuredSerializer.cs rename to Adyen/TerminalApi/ApiSerialization/SaleToPoiMessageSecuredSerializer.cs diff --git a/Adyen/ApiSerialization/SaleToPoiMessageSerializer.cs b/Adyen/TerminalApi/ApiSerialization/SaleToPoiMessageSerializer.cs similarity index 100% rename from Adyen/ApiSerialization/SaleToPoiMessageSerializer.cs rename to Adyen/TerminalApi/ApiSerialization/SaleToPoiMessageSerializer.cs diff --git a/Adyen/ApiSerialization/TypeHelper.cs b/Adyen/TerminalApi/ApiSerialization/TypeHelper.cs similarity index 100% rename from Adyen/ApiSerialization/TypeHelper.cs rename to Adyen/TerminalApi/ApiSerialization/TypeHelper.cs diff --git a/Adyen/BaseUrlConfig.cs b/Adyen/TerminalApi/BaseUrlConfig.cs similarity index 100% rename from Adyen/BaseUrlConfig.cs rename to Adyen/TerminalApi/BaseUrlConfig.cs diff --git a/Adyen/Client.cs b/Adyen/TerminalApi/Client.cs similarity index 97% rename from Adyen/Client.cs rename to Adyen/TerminalApi/Client.cs index 60a202ad9..4cc9717f1 100644 --- a/Adyen/Client.cs +++ b/Adyen/TerminalApi/Client.cs @@ -1,137 +1,137 @@ -using System; -using System.Net.Http; -using Adyen.Constants; -using Adyen.HttpClient; -using Adyen.HttpClient.Interfaces; -using Environment = Adyen.Model.Environment; - -namespace Adyen -{ - public class Client - { - public Config Config { get; set; } - - public string ApplicationName { get; set; } - - public delegate void CallbackLogHandler(string message); - - public event CallbackLogHandler LogCallback; - private static System.Net.Http.HttpClient _httpClient; - - [Obsolete("Providing username and password are obsolete, please use Config instead.")] - public Client(string username, string password, Environment environment, string liveEndpointUrlPrefix = null) - { - Config = new Config - { - Username = username, - Password = password, - Environment = environment - }; - SetEnvironment(environment, liveEndpointUrlPrefix, Config.TerminalApiRegion, Config.CloudApiEndPoint); - - HttpClient = new HttpClientWrapper(Config, GetHttpClient()); - } - - [Obsolete("Providing x-api-key is obsolete, please use Config instead.")] - public Client(string xapikey, Environment environment, string liveEndpointUrlPrefix = null) - { - Config = new Config - { - XApiKey = xapikey, - Environment = environment, - LiveEndpointUrlPrefix = liveEndpointUrlPrefix - }; - SetEnvironment(environment, Config.LiveEndpointUrlPrefix, Config.TerminalApiRegion, Config.CloudApiEndPoint); - HttpClient = new HttpClientWrapper(Config, GetHttpClient()); - } - - public Client(Config config) - { - Config = config; - SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); - HttpClient = new HttpClientWrapper(config, GetHttpClient()); - } - - public Client(Config config, System.Net.Http.HttpClient httpClient) - { - Config = config; - SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); - HttpClient = new HttpClientWrapper(config, httpClient); - } - - public Client(Config config, IHttpClientFactory factory, string clientName = null) - { - Config = config; - SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); - HttpClient = clientName != null ? new HttpClientWrapper(config, factory.CreateClient(clientName)) : new HttpClientWrapper(Config, factory.CreateClient()); - } - - /// - /// Configures the environment. - /// - /// Specifies whether the is Test or Live. - /// The prefix for live endpoint URLs. Required for live configurations, see: https://docs.adyen.com/development-resources/live-endpoints". - /// Specifies the geographical region for the Terminal API integration, the passed is used to automatically determine this endpoint URL, see: https://docs.adyen.com/point-of-sale/design-your-integration/terminal-api/#live-endpoints. - /// Specifies the cloud endpoint for the Terminal API integration. This URL is where your SaleToPOIMessage(s) are sent. You can override this value for (mock) testing purposes. - public void SetEnvironment(Environment environment, string liveEndpointUrlPrefix = "", Region region = Region.EU, string cloudApiEndpoint = null) - { - Config.Environment = environment; - Config.LiveEndpointUrlPrefix = liveEndpointUrlPrefix; - Config.TerminalApiRegion = region; - Config.CloudApiEndPoint = cloudApiEndpoint; - Config.CloudApiEndPoint = GetCloudApiEndpoint(); - } - - /// - /// Retrieves the current terminal-api endpoint URL for sending the SaleToPoiMessage(s). - /// - /// The full terminal-api endpoint URL for the Cloud Terminal API integration. - /// Thrown if the specified is not part of . - public string GetCloudApiEndpoint() - { - // Check if the cloud API endpoint has already been set - if (Config.CloudApiEndPoint != null) - { - return Config.CloudApiEndPoint; - } - - // For LIVE environment, handle region mapping - if (Config.Environment == Environment.Live) - { - if (!RegionMapping.TERMINAL_API_ENDPOINTS_MAPPING.TryGetValue(Config.TerminalApiRegion, out string endpointUrl)) - { - throw new ArgumentOutOfRangeException($"Currently not supported: {Config.TerminalApiRegion}"); - } - return endpointUrl; - } - - // Default to test endpoint if the environment is TEST (default). - return ClientConfig.CloudApiEndPointTest; - } - - // Get a new HttpClient and set a timeout - private System.Net.Http.HttpClient GetHttpClient() - { - if (_httpClient == null) - { - _httpClient = new System.Net.Http.HttpClient(HttpClientExtensions.ConfigureHttpMessageHandler(Config)) - { - Timeout = TimeSpan.FromMilliseconds(Config.Timeout) - }; - } - return _httpClient; - } - - public IClient HttpClient { get; set; } - - public string LibraryVersion => ClientConfig.LibVersion; - - public void LogLine(string message) - { - if (LogCallback != null) - { - LogCallback(message); - } - } - } -} +using System; +using System.Net.Http; +using Adyen.Constants; +using Adyen.HttpClient; +using Adyen.HttpClient.Interfaces; +using Environment = Adyen.Model.Environment; + +namespace Adyen +{ + public class Client + { + public Config Config { get; set; } + + public string ApplicationName { get; set; } + + public delegate void CallbackLogHandler(string message); + + public event CallbackLogHandler LogCallback; + private static System.Net.Http.HttpClient _httpClient; + + [Obsolete("Providing username and password are obsolete, please use Config instead.")] + public Client(string username, string password, Environment environment, string liveEndpointUrlPrefix = null) + { + Config = new Config + { + Username = username, + Password = password, + Environment = environment + }; + SetEnvironment(environment, liveEndpointUrlPrefix, Config.TerminalApiRegion, Config.CloudApiEndPoint); + + HttpClient = new HttpClientWrapper(Config, GetHttpClient()); + } + + [Obsolete("Providing x-api-key is obsolete, please use Config instead.")] + public Client(string xapikey, Environment environment, string liveEndpointUrlPrefix = null) + { + Config = new Config + { + XApiKey = xapikey, + Environment = environment, + LiveEndpointUrlPrefix = liveEndpointUrlPrefix + }; + SetEnvironment(environment, Config.LiveEndpointUrlPrefix, Config.TerminalApiRegion, Config.CloudApiEndPoint); + HttpClient = new HttpClientWrapper(Config, GetHttpClient()); + } + + public Client(Config config) + { + Config = config; + SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); + HttpClient = new HttpClientWrapper(config, GetHttpClient()); + } + + public Client(Config config, System.Net.Http.HttpClient httpClient) + { + Config = config; + SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); + HttpClient = new HttpClientWrapper(config, httpClient); + } + + public Client(Config config, IHttpClientFactory factory, string clientName = null) + { + Config = config; + SetEnvironment(config.Environment, config.LiveEndpointUrlPrefix, config.TerminalApiRegion, config.CloudApiEndPoint); + HttpClient = clientName != null ? new HttpClientWrapper(config, factory.CreateClient(clientName)) : new HttpClientWrapper(Config, factory.CreateClient()); + } + + /// + /// Configures the environment. + /// + /// Specifies whether the is Test or Live. + /// The prefix for live endpoint URLs. Required for live configurations, see: https://docs.adyen.com/development-resources/live-endpoints". + /// Specifies the geographical region for the Terminal API integration, the passed is used to automatically determine this endpoint URL, see: https://docs.adyen.com/point-of-sale/design-your-integration/terminal-api/#live-endpoints. + /// Specifies the cloud endpoint for the Terminal API integration. This URL is where your SaleToPOIMessage(s) are sent. You can override this value for (mock) testing purposes. + public void SetEnvironment(Environment environment, string liveEndpointUrlPrefix = "", Region region = Region.EU, string cloudApiEndpoint = null) + { + Config.Environment = environment; + Config.LiveEndpointUrlPrefix = liveEndpointUrlPrefix; + Config.TerminalApiRegion = region; + Config.CloudApiEndPoint = cloudApiEndpoint; + Config.CloudApiEndPoint = GetCloudApiEndpoint(); + } + + /// + /// Retrieves the current terminal-api endpoint URL for sending the SaleToPoiMessage(s). + /// + /// The full terminal-api endpoint URL for the Cloud Terminal API integration. + /// Thrown if the specified is not part of . + public string GetCloudApiEndpoint() + { + // Check if the cloud API endpoint has already been set + if (Config.CloudApiEndPoint != null) + { + return Config.CloudApiEndPoint; + } + + // For LIVE environment, handle region mapping + if (Config.Environment == Environment.Live) + { + if (!RegionMapping.TERMINAL_API_ENDPOINTS_MAPPING.TryGetValue(Config.TerminalApiRegion, out string endpointUrl)) + { + throw new ArgumentOutOfRangeException($"Currently not supported: {Config.TerminalApiRegion}"); + } + return endpointUrl; + } + + // Default to test endpoint if the environment is TEST (default). + return ClientConfig.CloudApiEndPointTest; + } + + // Get a new HttpClient and set a timeout + private System.Net.Http.HttpClient GetHttpClient() + { + if (_httpClient == null) + { + _httpClient = new System.Net.Http.HttpClient(HttpClientExtensions.ConfigureHttpMessageHandler(Config)) + { + Timeout = TimeSpan.FromMilliseconds(Config.Timeout) + }; + } + return _httpClient; + } + + public IClient HttpClient { get; set; } + + public string LibraryVersion => ClientConfig.LibVersion; + + public void LogLine(string message) + { + if (LogCallback != null) + { + LogCallback(message); + } + } + } +} diff --git a/Adyen/Service/Resource/Terminal/TerminalApi.cs b/Adyen/TerminalApi/Clients/TerminalApi.cs similarity index 100% rename from Adyen/Service/Resource/Terminal/TerminalApi.cs rename to Adyen/TerminalApi/Clients/TerminalApi.cs diff --git a/Adyen/Service/Resource/Terminal/TerminalApiAsyncClient.cs b/Adyen/TerminalApi/Clients/TerminalApiAsyncClient.cs similarity index 100% rename from Adyen/Service/Resource/Terminal/TerminalApiAsyncClient.cs rename to Adyen/TerminalApi/Clients/TerminalApiAsyncClient.cs diff --git a/Adyen/Service/Resource/Terminal/TerminalApiLocal.cs b/Adyen/TerminalApi/Clients/TerminalApiLocal.cs similarity index 100% rename from Adyen/Service/Resource/Terminal/TerminalApiLocal.cs rename to Adyen/TerminalApi/Clients/TerminalApiLocal.cs diff --git a/Adyen/Service/Resource/Terminal/TerminalApiLocalClient.cs b/Adyen/TerminalApi/Clients/TerminalApiLocalClient.cs similarity index 100% rename from Adyen/Service/Resource/Terminal/TerminalApiLocalClient.cs rename to Adyen/TerminalApi/Clients/TerminalApiLocalClient.cs diff --git a/Adyen/Service/Resource/Terminal/TerminalApiSyncClient.cs b/Adyen/TerminalApi/Clients/TerminalApiSyncClient.cs similarity index 100% rename from Adyen/Service/Resource/Terminal/TerminalApiSyncClient.cs rename to Adyen/TerminalApi/Clients/TerminalApiSyncClient.cs diff --git a/Adyen/Config.cs b/Adyen/TerminalApi/Config.cs similarity index 94% rename from Adyen/Config.cs rename to Adyen/TerminalApi/Config.cs index 0f6ce4cf1..7daae70d9 100644 --- a/Adyen/Config.cs +++ b/Adyen/TerminalApi/Config.cs @@ -1,80 +1,81 @@ -using System; -using System.Net; -using Adyen.Constants; -using Environment = Adyen.Model.Environment; - -namespace Adyen -{ - public class Config - { - public string Username { get; set; } - public string Password { get; set; } - public bool HasPassword => !string.IsNullOrEmpty(Password); - - public Environment Environment { get; set; } - public string LiveEndpointUrlPrefix { get; set; } - public string ApplicationName { get; set; } - public IWebProxy Proxy { get; set; } - - /// - /// Your Adyen API key. - /// - public string XApiKey { get; set; } - public bool HasApiKey => !string.IsNullOrEmpty(XApiKey); - - /// - /// HttpConnection Timeout in milliseconds (e.g. the time required to send the request and receive the response). - /// In > NET6.0, we recommend configuring your own and pass it in the constructor. - /// The values shown here are defaults, if no is provided. - /// - public int Timeout { get; set; } = 60000; - - /// - /// Only The amount of time it should take to establish the TCP Connection. - /// This value is only used in when no default was passed in the constructor. - /// In > NET6.0, we recommend configuring your own and pass it in the constructor. - /// The values shown here are defaults, if no is provided. - /// - public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(15); - - /// - /// Force reconnection to refresh DNS and avoid stale connections. - /// Once a connection exceeds the specified lifetime, it is no longer considered reusable and it is closed and removed from the pool. - /// This value is only used in when no default was passed in the constructor. - /// In > NET6.0, we recommend configuring your own and pass it in the constructor. - /// The values shown here are defaults, if no is provided. - /// - public TimeSpan PooledConnectionLifetime { get; set; } = TimeSpan.FromMinutes(5); - - /// - /// Close idle connections after the specified time. - /// This value is only used in when no default was passed in the constructor. - /// In > NET6.0, we recommend configuring your own and pass it in the constructor. - /// The values shown here are defaults, if no is provided. - /// - public TimeSpan PooledConnectionIdleTimeout { get; set; }= TimeSpan.FromMinutes(2); - - /// - /// Maximum number of concurrent TCP connections per server. - /// This value is only used in when no default was passed in the constructor. - /// In > NET6.0, we recommend configuring your own and pass it in the constructor. - /// The values shown here are defaults, if no is provided. - /// - public int MaxConnectionsPerServer { get; set; } = 2; - - /// - /// The url of the Cloud Terminal Api endpoint. - /// This value is populated when specifying the in . - /// - public string CloudApiEndPoint { get; set; } - - /// - /// The url of the Terminal Api endpoint, can be overriden if you want to send local terminal-api requests. - /// - public string LocalTerminalApiEndpoint { get; set; } - - public BaseUrlConfig BaseUrlConfig { get; set; } - - public Region TerminalApiRegion { get; set; } - } +using System; +using System.Net; +using Adyen.Constants; +using Environment = Adyen.Model.Environment; + +namespace Adyen +{ + public class Config + { + public string Username { get; set; } + public string Password { get; set; } + public bool HasPassword => !string.IsNullOrEmpty(Password); + + public Environment Environment { get; set; } + public string LiveEndpointUrlPrefix { get; set; } + public string ApplicationName { get; set; } + public IWebProxy Proxy { get; set; } + + /// + /// Your Adyen API key. + /// + public string XApiKey { get; set; } + + public bool HasApiKey => !string.IsNullOrEmpty(XApiKey); + + /// + /// HttpConnection Timeout in milliseconds (e.g. the time required to send the request and receive the response). + /// In > NET6.0, we recommend configuring your own and pass it in the constructor. + /// The values shown here are defaults, if no is provided. + /// + public int Timeout { get; set; } = 60000; + + /// + /// Only The amount of time it should take to establish the TCP Connection. + /// This value is only used in when no default was passed in the constructor. + /// In > NET6.0, we recommend configuring your own and pass it in the constructor. + /// The values shown here are defaults, if no is provided. + /// + public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(15); + + /// + /// Force reconnection to refresh DNS and avoid stale connections. + /// Once a connection exceeds the specified lifetime, it is no longer considered reusable and it is closed and removed from the pool. + /// This value is only used in when no default was passed in the constructor. + /// In > NET6.0, we recommend configuring your own and pass it in the constructor. + /// The values shown here are defaults, if no is provided. + /// + public TimeSpan PooledConnectionLifetime { get; set; } = TimeSpan.FromMinutes(5); + + /// + /// Close idle connections after the specified time. + /// This value is only used in when no default was passed in the constructor. + /// In > NET6.0, we recommend configuring your own and pass it in the constructor. + /// The values shown here are defaults, if no is provided. + /// + public TimeSpan PooledConnectionIdleTimeout { get; set; } = TimeSpan.FromMinutes(2); + + /// + /// Maximum number of concurrent TCP connections per server. + /// This value is only used in when no default was passed in the constructor. + /// In > NET6.0, we recommend configuring your own and pass it in the constructor. + /// The values shown here are defaults, if no is provided. + /// + public int MaxConnectionsPerServer { get; set; } = 2; + + /// + /// The url of the Cloud Terminal Api endpoint. + /// This value is populated when specifying the in . + /// + public string CloudApiEndPoint { get; set; } + + /// + /// The url of the Terminal Api endpoint, can be overriden if you want to send local terminal-api requests. + /// + public string LocalTerminalApiEndpoint { get; set; } + + public BaseUrlConfig BaseUrlConfig { get; set; } + + public Region TerminalApiRegion { get; set; } + } } \ No newline at end of file diff --git a/Adyen/TerminalApi/Constants/ClientConfig.cs b/Adyen/TerminalApi/Constants/ClientConfig.cs new file mode 100644 index 000000000..1f5781057 --- /dev/null +++ b/Adyen/TerminalApi/Constants/ClientConfig.cs @@ -0,0 +1,34 @@ +namespace Adyen.Constants +{ + public class ClientConfig + { + //Test cloud api endpoints + public const string CloudApiEndPointTest = "https://terminal-api-test.adyen.com"; + + //Live cloud api endpoints + public const string CloudApiEndPointEULive = "https://terminal-api-live.adyen.com"; + public const string CloudApiEndPointAULive = "https://terminal-api-live-au.adyen.com"; + public const string CloudApiEndPointUSLive = "https://terminal-api-live-us.adyen.com"; + public const string CloudApiEndPointAPSELive = "https://terminal-api-live-apse.adyen.com"; + + public const string NexoProtocolVersion = "3.0"; + + /// + /// Moved to . + /// + [Obsolete("Use Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName instead.")] + public const string UserAgentSuffix = Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName + "/"; + + /// + /// Moved to . + /// + [Obsolete("Use Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName instead.")] + public const string LibName = Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName; + + /// + /// Moved to . + /// + [Obsolete("Use Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion instead.")] + public const string LibVersion = Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion; + } +} diff --git a/Adyen/Constants/Region.cs b/Adyen/TerminalApi/Constants/Region.cs similarity index 100% rename from Adyen/Constants/Region.cs rename to Adyen/TerminalApi/Constants/Region.cs diff --git a/Adyen/Model/Environment.cs b/Adyen/TerminalApi/Environment.cs similarity index 100% rename from Adyen/Model/Environment.cs rename to Adyen/TerminalApi/Environment.cs diff --git a/Adyen/Exceptions/DeserializationException.cs b/Adyen/TerminalApi/Exceptions/DeserializationException.cs similarity index 100% rename from Adyen/Exceptions/DeserializationException.cs rename to Adyen/TerminalApi/Exceptions/DeserializationException.cs diff --git a/Adyen/Exceptions/ExceptionMessages.cs b/Adyen/TerminalApi/Exceptions/ExceptionMessages.cs similarity index 100% rename from Adyen/Exceptions/ExceptionMessages.cs rename to Adyen/TerminalApi/Exceptions/ExceptionMessages.cs diff --git a/Adyen/HttpClient/HttpClientException.cs b/Adyen/TerminalApi/HttpClient/HttpClientException.cs similarity index 100% rename from Adyen/HttpClient/HttpClientException.cs rename to Adyen/TerminalApi/HttpClient/HttpClientException.cs diff --git a/Adyen/HttpClient/HttpClientExtension.cs b/Adyen/TerminalApi/HttpClient/HttpClientExtension.cs similarity index 100% rename from Adyen/HttpClient/HttpClientExtension.cs rename to Adyen/TerminalApi/HttpClient/HttpClientExtension.cs diff --git a/Adyen/HttpClient/HttpClientWrapper.cs b/Adyen/TerminalApi/HttpClient/HttpClientWrapper.cs similarity index 89% rename from Adyen/HttpClient/HttpClientWrapper.cs rename to Adyen/TerminalApi/HttpClient/HttpClientWrapper.cs index c393a1169..c7b16621e 100644 --- a/Adyen/HttpClient/HttpClientWrapper.cs +++ b/Adyen/TerminalApi/HttpClient/HttpClientWrapper.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using System.Web; using Adyen.Constants; +using Adyen.Core.Client.Extensions; using Adyen.HttpClient.Interfaces; using Adyen.Model; @@ -68,11 +69,11 @@ public HttpRequestMessage GetHttpRequestMessage(string endpoint, string requestB if (!string.IsNullOrWhiteSpace(_config.ApplicationName)) { - httpRequestMessage.Headers.Add("UserAgent", $"{_config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}"); + httpRequestMessage.Headers.Add("UserAgent", $"{_config.ApplicationName} {HttpRequestMessageExtensions.AdyenLibraryName}/{HttpRequestMessageExtensions.AdyenLibraryVersion}"); } else { - httpRequestMessage.Headers.Add("UserAgent", $"{ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}"); + httpRequestMessage.Headers.Add("UserAgent", $"{HttpRequestMessageExtensions.AdyenLibraryName}/{HttpRequestMessageExtensions.AdyenLibraryVersion}"); } if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey)) @@ -94,8 +95,8 @@ public HttpRequestMessage GetHttpRequestMessage(string endpoint, string requestB } // Add library name and version to request for analysis - httpRequestMessage.Headers.Add(ApiConstants.AdyenLibraryName, ClientConfig.LibName); - httpRequestMessage.Headers.Add(ApiConstants.AdyenLibraryVersion, ClientConfig.LibVersion); + httpRequestMessage.Headers.Add("adyen-library-name", HttpRequestMessageExtensions.AdyenLibraryName); + httpRequestMessage.Headers.Add("adyen-library-version", HttpRequestMessageExtensions.AdyenLibraryVersion); return httpRequestMessage; } diff --git a/Adyen/HttpClient/Interfaces/IClient.cs b/Adyen/TerminalApi/HttpClient/Interfaces/IClient.cs similarity index 100% rename from Adyen/HttpClient/Interfaces/IClient.cs rename to Adyen/TerminalApi/HttpClient/Interfaces/IClient.cs diff --git a/Adyen/Model/TerminalApi/AbortRequest.cs b/Adyen/TerminalApi/Models/AbortRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/AbortRequest.cs rename to Adyen/TerminalApi/Models/AbortRequest.cs diff --git a/Adyen/Service/AbstractService.cs b/Adyen/TerminalApi/Models/AbstractService.cs similarity index 97% rename from Adyen/Service/AbstractService.cs rename to Adyen/TerminalApi/Models/AbstractService.cs index 517317c16..b749dd706 100644 --- a/Adyen/Service/AbstractService.cs +++ b/Adyen/TerminalApi/Models/AbstractService.cs @@ -1,132 +1,132 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Adyen.Exceptions; -using Environment = Adyen.Model.Environment; - -namespace Adyen.Service -{ - public class AbstractService - { - public Client Client { get; set; } - - private const string PaymentPrefix = "pal-"; - private const string CheckoutPrefix = "checkout-"; - - protected AbstractService(Client client) - { - Client = client; - } - - /// - /// Build the query string - /// - /// Key, value pairs - /// URL encoded query string - private protected static string ToQueryString(IDictionary queryParams) - { - if (queryParams == null || queryParams.Count == 0) - { - return string.Empty; - } - - var queryString = string.Join("&", - queryParams.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value)}")); - - if (!string.IsNullOrEmpty(queryString)) - { - return "?" + queryString; - } - - return string.Empty; - } - - /// - /// The base URL creation for the environment - /// - /// String - /// baseURL - private protected string CreateBaseUrl(string url) - { - var config = Client.Config; - return config.Environment == Environment.Live - ? ConstructLiveUrl(config, - url) - : ConstructTestUrl(config, - url); - } - - /// - /// Allow users to override the baseUrl in a test environment - /// - /// Config - /// String - /// baseUrl - private static string ConstructTestUrl(Config config, string url) - { - if (config.BaseUrlConfig == null) return url.Replace("-live", "-test"); - - var baseUrl = config.BaseUrlConfig.BaseUrl; - if (url.Contains(PaymentPrefix) - && !string.IsNullOrEmpty(config.BaseUrlConfig.PaymentUrl)) - { - baseUrl = config.BaseUrlConfig.PaymentUrl; - } else if (url.Contains(CheckoutPrefix) - && !string.IsNullOrEmpty(config.BaseUrlConfig.CheckoutUrl)) - { - baseUrl = config.BaseUrlConfig.CheckoutUrl; - } - - var urlPath = new Uri(url).AbsolutePath; - var returnUrl = new Uri(baseUrl + urlPath).ToString(); - - return returnUrl; - } - - /// - /// Construct live baseUrl - /// - /// Config - /// String - /// baseUrl - /// - private static string ConstructLiveUrl(Config config, string url) - { - // Change base url for Live environment - if (url.Contains(PaymentPrefix)) - { - if (config.LiveEndpointUrlPrefix == default) - { - throw new InvalidOperationException(ExceptionMessages.MissingLiveEndpointUrlPrefix); - } - - url = url.Replace("https://pal-test.adyen.com/pal/servlet/", - "https://" + config.LiveEndpointUrlPrefix + "-pal-live.adyenpayments.com/pal/servlet/"); - } - else if (url.Contains(CheckoutPrefix)) - { - if (config.LiveEndpointUrlPrefix == default) - { - throw new InvalidOperationException(ExceptionMessages.MissingLiveEndpointUrlPrefix); - } - - if (url.Contains("possdk")) - { - url = url.Replace("https://checkout-test.adyen.com/", - "https://" + config.LiveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/"); - } - else - { - url = url.Replace("https://checkout-test.adyen.com/", - "https://" + config.LiveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/checkout/"); - } - } - - - // If no prefix is required just replace "test" -> "live" - url = url.Replace("-test", "-live"); - return url; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using Adyen.Exceptions; +using Environment = Adyen.Model.Environment; + +namespace Adyen.Service +{ + public class AbstractService + { + public Client Client { get; set; } + + private const string PaymentPrefix = "pal-"; + private const string CheckoutPrefix = "checkout-"; + + protected AbstractService(Client client) + { + Client = client; + } + + /// + /// Build the query string + /// + /// Key, value pairs + /// URL encoded query string + private protected static string ToQueryString(IDictionary queryParams) + { + if (queryParams == null || queryParams.Count == 0) + { + return string.Empty; + } + + var queryString = string.Join("&", + queryParams.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value)}")); + + if (!string.IsNullOrEmpty(queryString)) + { + return "?" + queryString; + } + + return string.Empty; + } + + /// + /// The base URL creation for the environment + /// + /// String + /// baseURL + private protected string CreateBaseUrl(string url) + { + var config = Client.Config; + return config.Environment == Environment.Live + ? ConstructLiveUrl(config, + url) + : ConstructTestUrl(config, + url); + } + + /// + /// Allow users to override the baseUrl in a test environment + /// + /// Config + /// String + /// baseUrl + private static string ConstructTestUrl(Config config, string url) + { + if (config.BaseUrlConfig == null) return url.Replace("-live", "-test"); + + var baseUrl = config.BaseUrlConfig.BaseUrl; + if (url.Contains(PaymentPrefix) + && !string.IsNullOrEmpty(config.BaseUrlConfig.PaymentUrl)) + { + baseUrl = config.BaseUrlConfig.PaymentUrl; + } else if (url.Contains(CheckoutPrefix) + && !string.IsNullOrEmpty(config.BaseUrlConfig.CheckoutUrl)) + { + baseUrl = config.BaseUrlConfig.CheckoutUrl; + } + + var urlPath = new Uri(url).AbsolutePath; + var returnUrl = new Uri(baseUrl + urlPath).ToString(); + + return returnUrl; + } + + /// + /// Construct live baseUrl + /// + /// Config + /// String + /// baseUrl + /// + private static string ConstructLiveUrl(Config config, string url) + { + // Change base url for Live environment + if (url.Contains(PaymentPrefix)) + { + if (config.LiveEndpointUrlPrefix == default) + { + throw new InvalidOperationException(ExceptionMessages.MissingLiveEndpointUrlPrefix); + } + + url = url.Replace("https://pal-test.adyen.com/pal/servlet/", + "https://" + config.LiveEndpointUrlPrefix + "-pal-live.adyenpayments.com/pal/servlet/"); + } + else if (url.Contains(CheckoutPrefix)) + { + if (config.LiveEndpointUrlPrefix == default) + { + throw new InvalidOperationException(ExceptionMessages.MissingLiveEndpointUrlPrefix); + } + + if (url.Contains("possdk")) + { + url = url.Replace("https://checkout-test.adyen.com/", + "https://" + config.LiveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/"); + } + else + { + url = url.Replace("https://checkout-test.adyen.com/", + "https://" + config.LiveEndpointUrlPrefix + "-checkout-live.adyenpayments.com/checkout/"); + } + } + + + // If no prefix is required just replace "test" -> "live" + url = url.Replace("-test", "-live"); + return url; + } + } } \ No newline at end of file diff --git a/Adyen/Model/TerminalApi/AccountType.cs b/Adyen/TerminalApi/Models/AccountType.cs similarity index 100% rename from Adyen/Model/TerminalApi/AccountType.cs rename to Adyen/TerminalApi/Models/AccountType.cs diff --git a/Adyen/Model/TerminalApi/AdminRequest.cs b/Adyen/TerminalApi/Models/AdminRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/AdminRequest.cs rename to Adyen/TerminalApi/Models/AdminRequest.cs diff --git a/Adyen/Model/TerminalApi/AdminResponse.cs b/Adyen/TerminalApi/Models/AdminResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/AdminResponse.cs rename to Adyen/TerminalApi/Models/AdminResponse.cs diff --git a/Adyen/Model/TerminalApi/AlgorithmIdentifier.cs b/Adyen/TerminalApi/Models/AlgorithmIdentifier.cs similarity index 100% rename from Adyen/Model/TerminalApi/AlgorithmIdentifier.cs rename to Adyen/TerminalApi/Models/AlgorithmIdentifier.cs diff --git a/Adyen/Model/TerminalApi/AlgorithmType.cs b/Adyen/TerminalApi/Models/AlgorithmType.cs similarity index 100% rename from Adyen/Model/TerminalApi/AlgorithmType.cs rename to Adyen/TerminalApi/Models/AlgorithmType.cs diff --git a/Adyen/Model/TerminalApi/AlignmentType.cs b/Adyen/TerminalApi/Models/AlignmentType.cs similarity index 100% rename from Adyen/Model/TerminalApi/AlignmentType.cs rename to Adyen/TerminalApi/Models/AlignmentType.cs diff --git a/Adyen/Model/TerminalApi/AllowedProduct.cs b/Adyen/TerminalApi/Models/AllowedProduct.cs similarity index 100% rename from Adyen/Model/TerminalApi/AllowedProduct.cs rename to Adyen/TerminalApi/Models/AllowedProduct.cs diff --git a/Adyen/Model/TerminalApi/Amount.cs b/Adyen/TerminalApi/Models/Amount.cs similarity index 100% rename from Adyen/Model/TerminalApi/Amount.cs rename to Adyen/TerminalApi/Models/Amount.cs diff --git a/Adyen/Model/TerminalApi/AmountsReq.cs b/Adyen/TerminalApi/Models/AmountsReq.cs similarity index 100% rename from Adyen/Model/TerminalApi/AmountsReq.cs rename to Adyen/TerminalApi/Models/AmountsReq.cs diff --git a/Adyen/Model/TerminalApi/AmountsResp.cs b/Adyen/TerminalApi/Models/AmountsResp.cs similarity index 100% rename from Adyen/Model/TerminalApi/AmountsResp.cs rename to Adyen/TerminalApi/Models/AmountsResp.cs diff --git a/Adyen/Model/ApplicationInformation/ApplicationInfo.cs b/Adyen/TerminalApi/Models/ApplicationInformation/ApplicationInfo.cs similarity index 96% rename from Adyen/Model/ApplicationInformation/ApplicationInfo.cs rename to Adyen/TerminalApi/Models/ApplicationInformation/ApplicationInfo.cs index 0427270a9..3408fe322 100644 --- a/Adyen/Model/ApplicationInformation/ApplicationInfo.cs +++ b/Adyen/TerminalApi/Models/ApplicationInformation/ApplicationInfo.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; @@ -21,8 +21,8 @@ public ApplicationInfo() { AdyenLibrary = new CommonField { - Name = ClientConfig.LibName, - Version = ClientConfig.LibVersion + Name = Adyen.Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryName, + Version = Core.Client.Extensions.HttpRequestMessageExtensions.AdyenLibraryVersion }; } @@ -178,4 +178,4 @@ IEnumerable IValidatableObject.Validate(ValidationContext vali } } -} +} \ No newline at end of file diff --git a/Adyen/Model/ApplicationInformation/CommonField.cs b/Adyen/TerminalApi/Models/ApplicationInformation/CommonField.cs similarity index 99% rename from Adyen/Model/ApplicationInformation/CommonField.cs rename to Adyen/TerminalApi/Models/ApplicationInformation/CommonField.cs index e1884260c..1ff4bc3f1 100644 --- a/Adyen/Model/ApplicationInformation/CommonField.cs +++ b/Adyen/TerminalApi/Models/ApplicationInformation/CommonField.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; @@ -121,4 +121,4 @@ IEnumerable IValidatableObject.Validate(ValidationContext vali yield break; } } -} +} \ No newline at end of file diff --git a/Adyen/Model/ApplicationInformation/ExternalPlatform.cs b/Adyen/TerminalApi/Models/ApplicationInformation/ExternalPlatform.cs similarity index 99% rename from Adyen/Model/ApplicationInformation/ExternalPlatform.cs rename to Adyen/TerminalApi/Models/ApplicationInformation/ExternalPlatform.cs index dfd53c0fd..b97ac85ab 100644 --- a/Adyen/Model/ApplicationInformation/ExternalPlatform.cs +++ b/Adyen/TerminalApi/Models/ApplicationInformation/ExternalPlatform.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; @@ -139,4 +139,4 @@ IEnumerable IValidatableObject.Validate(ValidationContext vali } } -} +} \ No newline at end of file diff --git a/Adyen/Model/ApplicationInformation/MerchantDevice.cs b/Adyen/TerminalApi/Models/ApplicationInformation/MerchantDevice.cs similarity index 99% rename from Adyen/Model/ApplicationInformation/MerchantDevice.cs rename to Adyen/TerminalApi/Models/ApplicationInformation/MerchantDevice.cs index 799a29e69..bbcd6ebd7 100644 --- a/Adyen/Model/ApplicationInformation/MerchantDevice.cs +++ b/Adyen/TerminalApi/Models/ApplicationInformation/MerchantDevice.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; @@ -139,4 +139,4 @@ IEnumerable IValidatableObject.Validate(ValidationContext vali } } -} +} \ No newline at end of file diff --git a/Adyen/Model/ApplicationInformation/ShopperInteractionDevice.cs b/Adyen/TerminalApi/Models/ApplicationInformation/ShopperInteractionDevice.cs similarity index 97% rename from Adyen/Model/ApplicationInformation/ShopperInteractionDevice.cs rename to Adyen/TerminalApi/Models/ApplicationInformation/ShopperInteractionDevice.cs index 57b152246..f301f54f0 100644 --- a/Adyen/Model/ApplicationInformation/ShopperInteractionDevice.cs +++ b/Adyen/TerminalApi/Models/ApplicationInformation/ShopperInteractionDevice.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; @@ -54,7 +54,7 @@ public class ShopperInteractionDevice : IEquatable, I public override string ToString() { var sb = new StringBuilder(); - sb.Append("class PaymentMethodsApplicationInfoShopperInteractionDevice {\n"); + sb.Append("class ShopperInteractionDevice {\n"); sb.Append(" Locale: ").Append(Locale).Append("\n"); sb.Append(" Os: ").Append(Os).Append("\n"); sb.Append(" OsVersion: ").Append(OsVersion).Append("\n"); @@ -138,4 +138,4 @@ IEnumerable IValidatableObject.Validate(ValidationContext vali yield break; } } -} +} \ No newline at end of file diff --git a/Adyen/Model/TerminalApi/AreaSize.cs b/Adyen/TerminalApi/Models/AreaSize.cs similarity index 100% rename from Adyen/Model/TerminalApi/AreaSize.cs rename to Adyen/TerminalApi/Models/AreaSize.cs diff --git a/Adyen/Model/TerminalApi/AuthenticatedData.cs b/Adyen/TerminalApi/Models/AuthenticatedData.cs similarity index 100% rename from Adyen/Model/TerminalApi/AuthenticatedData.cs rename to Adyen/TerminalApi/Models/AuthenticatedData.cs diff --git a/Adyen/Model/TerminalApi/AuthenticationMethodType.cs b/Adyen/TerminalApi/Models/AuthenticationMethodType.cs similarity index 100% rename from Adyen/Model/TerminalApi/AuthenticationMethodType.cs rename to Adyen/TerminalApi/Models/AuthenticationMethodType.cs diff --git a/Adyen/Model/TerminalApi/BalanceInquiryRequest.cs b/Adyen/TerminalApi/Models/BalanceInquiryRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/BalanceInquiryRequest.cs rename to Adyen/TerminalApi/Models/BalanceInquiryRequest.cs diff --git a/Adyen/Model/TerminalApi/BalanceInquiryResponse.cs b/Adyen/TerminalApi/Models/BalanceInquiryResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/BalanceInquiryResponse.cs rename to Adyen/TerminalApi/Models/BalanceInquiryResponse.cs diff --git a/Adyen/Model/TerminalApi/BarcodeType.cs b/Adyen/TerminalApi/Models/BarcodeType.cs similarity index 100% rename from Adyen/Model/TerminalApi/BarcodeType.cs rename to Adyen/TerminalApi/Models/BarcodeType.cs diff --git a/Adyen/Model/TerminalApi/BatchRequest.cs b/Adyen/TerminalApi/Models/BatchRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/BatchRequest.cs rename to Adyen/TerminalApi/Models/BatchRequest.cs diff --git a/Adyen/Model/TerminalApi/BatchResponse.cs b/Adyen/TerminalApi/Models/BatchResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/BatchResponse.cs rename to Adyen/TerminalApi/Models/BatchResponse.cs diff --git a/Adyen/Model/TerminalApi/CapturedSignature.cs b/Adyen/TerminalApi/Models/CapturedSignature.cs similarity index 100% rename from Adyen/Model/TerminalApi/CapturedSignature.cs rename to Adyen/TerminalApi/Models/CapturedSignature.cs diff --git a/Adyen/Model/TerminalApi/CardAcquisitionRequest.cs b/Adyen/TerminalApi/Models/CardAcquisitionRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardAcquisitionRequest.cs rename to Adyen/TerminalApi/Models/CardAcquisitionRequest.cs diff --git a/Adyen/Model/TerminalApi/CardAcquisitionResponse.cs b/Adyen/TerminalApi/Models/CardAcquisitionResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardAcquisitionResponse.cs rename to Adyen/TerminalApi/Models/CardAcquisitionResponse.cs diff --git a/Adyen/Model/TerminalApi/CardAcquisitionTransaction.cs b/Adyen/TerminalApi/Models/CardAcquisitionTransaction.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardAcquisitionTransaction.cs rename to Adyen/TerminalApi/Models/CardAcquisitionTransaction.cs diff --git a/Adyen/Model/TerminalApi/CardData.cs b/Adyen/TerminalApi/Models/CardData.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardData.cs rename to Adyen/TerminalApi/Models/CardData.cs diff --git a/Adyen/Model/TerminalApi/CardReaderAPDURequest.cs b/Adyen/TerminalApi/Models/CardReaderAPDURequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderAPDURequest.cs rename to Adyen/TerminalApi/Models/CardReaderAPDURequest.cs diff --git a/Adyen/Model/TerminalApi/CardReaderAPDUResponse.cs b/Adyen/TerminalApi/Models/CardReaderAPDUResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderAPDUResponse.cs rename to Adyen/TerminalApi/Models/CardReaderAPDUResponse.cs diff --git a/Adyen/Model/TerminalApi/CardReaderInitRequest.cs b/Adyen/TerminalApi/Models/CardReaderInitRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderInitRequest.cs rename to Adyen/TerminalApi/Models/CardReaderInitRequest.cs diff --git a/Adyen/Model/TerminalApi/CardReaderInitResponse.cs b/Adyen/TerminalApi/Models/CardReaderInitResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderInitResponse.cs rename to Adyen/TerminalApi/Models/CardReaderInitResponse.cs diff --git a/Adyen/Model/TerminalApi/CardReaderPowerOffRequest.cs b/Adyen/TerminalApi/Models/CardReaderPowerOffRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderPowerOffRequest.cs rename to Adyen/TerminalApi/Models/CardReaderPowerOffRequest.cs diff --git a/Adyen/Model/TerminalApi/CardReaderPowerOffResponse.cs b/Adyen/TerminalApi/Models/CardReaderPowerOffResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardReaderPowerOffResponse.cs rename to Adyen/TerminalApi/Models/CardReaderPowerOffResponse.cs diff --git a/Adyen/Model/TerminalApi/CardholderPIN.cs b/Adyen/TerminalApi/Models/CardholderPIN.cs similarity index 100% rename from Adyen/Model/TerminalApi/CardholderPIN.cs rename to Adyen/TerminalApi/Models/CardholderPIN.cs diff --git a/Adyen/Model/TerminalApi/CashHandlingDevice.cs b/Adyen/TerminalApi/Models/CashHandlingDevice.cs similarity index 100% rename from Adyen/Model/TerminalApi/CashHandlingDevice.cs rename to Adyen/TerminalApi/Models/CashHandlingDevice.cs diff --git a/Adyen/Model/TerminalApi/CharacterHeightType.cs b/Adyen/TerminalApi/Models/CharacterHeightType.cs similarity index 100% rename from Adyen/Model/TerminalApi/CharacterHeightType.cs rename to Adyen/TerminalApi/Models/CharacterHeightType.cs diff --git a/Adyen/Model/TerminalApi/CharacterStyleType.cs b/Adyen/TerminalApi/Models/CharacterStyleType.cs similarity index 100% rename from Adyen/Model/TerminalApi/CharacterStyleType.cs rename to Adyen/TerminalApi/Models/CharacterStyleType.cs diff --git a/Adyen/Model/TerminalApi/CharacterWidthType.cs b/Adyen/TerminalApi/Models/CharacterWidthType.cs similarity index 100% rename from Adyen/Model/TerminalApi/CharacterWidthType.cs rename to Adyen/TerminalApi/Models/CharacterWidthType.cs diff --git a/Adyen/Model/TerminalApi/CheckData.cs b/Adyen/TerminalApi/Models/CheckData.cs similarity index 100% rename from Adyen/Model/TerminalApi/CheckData.cs rename to Adyen/TerminalApi/Models/CheckData.cs diff --git a/Adyen/Model/TerminalApi/CheckTypeCodeType.cs b/Adyen/TerminalApi/Models/CheckTypeCodeType.cs similarity index 100% rename from Adyen/Model/TerminalApi/CheckTypeCodeType.cs rename to Adyen/TerminalApi/Models/CheckTypeCodeType.cs diff --git a/Adyen/Model/TerminalApi/CoinsOrBills.cs b/Adyen/TerminalApi/Models/CoinsOrBills.cs similarity index 100% rename from Adyen/Model/TerminalApi/CoinsOrBills.cs rename to Adyen/TerminalApi/Models/CoinsOrBills.cs diff --git a/Adyen/Model/TerminalApi/ColorType.cs b/Adyen/TerminalApi/Models/ColorType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ColorType.cs rename to Adyen/TerminalApi/Models/ColorType.cs diff --git a/Adyen/Model/TerminalApi/ContentInformation.cs b/Adyen/TerminalApi/Models/ContentInformation.cs similarity index 100% rename from Adyen/Model/TerminalApi/ContentInformation.cs rename to Adyen/TerminalApi/Models/ContentInformation.cs diff --git a/Adyen/Model/TerminalApi/ContentType.cs b/Adyen/TerminalApi/Models/ContentType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ContentType.cs rename to Adyen/TerminalApi/Models/ContentType.cs diff --git a/Adyen/Model/TerminalApi/CurrencyConversion.cs b/Adyen/TerminalApi/Models/CurrencyConversion.cs similarity index 100% rename from Adyen/Model/TerminalApi/CurrencyConversion.cs rename to Adyen/TerminalApi/Models/CurrencyConversion.cs diff --git a/Adyen/Model/TerminalApi/CustomerOrder.cs b/Adyen/TerminalApi/Models/CustomerOrder.cs similarity index 100% rename from Adyen/Model/TerminalApi/CustomerOrder.cs rename to Adyen/TerminalApi/Models/CustomerOrder.cs diff --git a/Adyen/Model/TerminalApi/CustomerOrderReqType.cs b/Adyen/TerminalApi/Models/CustomerOrderReqType.cs similarity index 100% rename from Adyen/Model/TerminalApi/CustomerOrderReqType.cs rename to Adyen/TerminalApi/Models/CustomerOrderReqType.cs diff --git a/Adyen/Model/TerminalApi/DeviceType.cs b/Adyen/TerminalApi/Models/DeviceType.cs similarity index 100% rename from Adyen/Model/TerminalApi/DeviceType.cs rename to Adyen/TerminalApi/Models/DeviceType.cs diff --git a/Adyen/Model/TerminalApi/DiagnosisRequest.cs b/Adyen/TerminalApi/Models/DiagnosisRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/DiagnosisRequest.cs rename to Adyen/TerminalApi/Models/DiagnosisRequest.cs diff --git a/Adyen/Model/TerminalApi/DiagnosisResponse.cs b/Adyen/TerminalApi/Models/DiagnosisResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/DiagnosisResponse.cs rename to Adyen/TerminalApi/Models/DiagnosisResponse.cs diff --git a/Adyen/Model/TerminalApi/DigestedData.cs b/Adyen/TerminalApi/Models/DigestedData.cs similarity index 100% rename from Adyen/Model/TerminalApi/DigestedData.cs rename to Adyen/TerminalApi/Models/DigestedData.cs diff --git a/Adyen/Model/TerminalApi/DisplayOutput.cs b/Adyen/TerminalApi/Models/DisplayOutput.cs similarity index 100% rename from Adyen/Model/TerminalApi/DisplayOutput.cs rename to Adyen/TerminalApi/Models/DisplayOutput.cs diff --git a/Adyen/Model/TerminalApi/DisplayRequest.cs b/Adyen/TerminalApi/Models/DisplayRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/DisplayRequest.cs rename to Adyen/TerminalApi/Models/DisplayRequest.cs diff --git a/Adyen/Model/TerminalApi/DisplayResponse.cs b/Adyen/TerminalApi/Models/DisplayResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/DisplayResponse.cs rename to Adyen/TerminalApi/Models/DisplayResponse.cs diff --git a/Adyen/Model/TerminalApi/DocumentQualifierType.cs b/Adyen/TerminalApi/Models/DocumentQualifierType.cs similarity index 100% rename from Adyen/Model/TerminalApi/DocumentQualifierType.cs rename to Adyen/TerminalApi/Models/DocumentQualifierType.cs diff --git a/Adyen/Model/TerminalApi/EnableServiceRequest.cs b/Adyen/TerminalApi/Models/EnableServiceRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/EnableServiceRequest.cs rename to Adyen/TerminalApi/Models/EnableServiceRequest.cs diff --git a/Adyen/Model/TerminalApi/EnableServiceResponse.cs b/Adyen/TerminalApi/Models/EnableServiceResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/EnableServiceResponse.cs rename to Adyen/TerminalApi/Models/EnableServiceResponse.cs diff --git a/Adyen/Model/TerminalApi/EncapsulatedContent.cs b/Adyen/TerminalApi/Models/EncapsulatedContent.cs similarity index 100% rename from Adyen/Model/TerminalApi/EncapsulatedContent.cs rename to Adyen/TerminalApi/Models/EncapsulatedContent.cs diff --git a/Adyen/Model/TerminalApi/EncryptedContent.cs b/Adyen/TerminalApi/Models/EncryptedContent.cs similarity index 100% rename from Adyen/Model/TerminalApi/EncryptedContent.cs rename to Adyen/TerminalApi/Models/EncryptedContent.cs diff --git a/Adyen/Model/TerminalApi/EntryModeType.cs b/Adyen/TerminalApi/Models/EntryModeType.cs similarity index 100% rename from Adyen/Model/TerminalApi/EntryModeType.cs rename to Adyen/TerminalApi/Models/EntryModeType.cs diff --git a/Adyen/Model/TerminalApi/EnvelopedData.cs b/Adyen/TerminalApi/Models/EnvelopedData.cs similarity index 100% rename from Adyen/Model/TerminalApi/EnvelopedData.cs rename to Adyen/TerminalApi/Models/EnvelopedData.cs diff --git a/Adyen/Model/TerminalApi/ErrorConditionType.cs b/Adyen/TerminalApi/Models/ErrorConditionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ErrorConditionType.cs rename to Adyen/TerminalApi/Models/ErrorConditionType.cs diff --git a/Adyen/Model/TerminalApi/EventNotification.cs b/Adyen/TerminalApi/Models/EventNotification.cs similarity index 100% rename from Adyen/Model/TerminalApi/EventNotification.cs rename to Adyen/TerminalApi/Models/EventNotification.cs diff --git a/Adyen/Model/TerminalApi/EventToNotifyType.cs b/Adyen/TerminalApi/Models/EventToNotifyType.cs similarity index 69% rename from Adyen/Model/TerminalApi/EventToNotifyType.cs rename to Adyen/TerminalApi/Models/EventToNotifyType.cs index 612cdca7b..6350f2988 100644 --- a/Adyen/Model/TerminalApi/EventToNotifyType.cs +++ b/Adyen/TerminalApi/Models/EventToNotifyType.cs @@ -1,7 +1,6 @@ namespace Adyen.Model.TerminalApi { /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute] public enum EventToNotifyType { @@ -53,5 +52,14 @@ public enum EventToNotifyType /// Reject, + + /// Indicates that the terminal has established a network connection. + NetworkConnected, + + /// Indicates that the terminal has no longer a network connection. + NetworkDisconnected, + + /// Delivers the result (or timeout failure) of the Barcode scan. + ScanBarcodeResult, } -} \ No newline at end of file +} diff --git a/Adyen/Model/TerminalApi/ForceTypeModeType.cs b/Adyen/TerminalApi/Models/ForceTypeModeType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ForceTypeModeType.cs rename to Adyen/TerminalApi/Models/ForceTypeModeType.cs diff --git a/Adyen/Model/TerminalApi/GenericProfileType.cs b/Adyen/TerminalApi/Models/GenericProfileType.cs similarity index 100% rename from Adyen/Model/TerminalApi/GenericProfileType.cs rename to Adyen/TerminalApi/Models/GenericProfileType.cs diff --git a/Adyen/Model/TerminalApi/GeographicCoordinates.cs b/Adyen/TerminalApi/Models/GeographicCoordinates.cs similarity index 100% rename from Adyen/Model/TerminalApi/GeographicCoordinates.cs rename to Adyen/TerminalApi/Models/GeographicCoordinates.cs diff --git a/Adyen/Model/TerminalApi/Geolocation.cs b/Adyen/TerminalApi/Models/Geolocation.cs similarity index 100% rename from Adyen/Model/TerminalApi/Geolocation.cs rename to Adyen/TerminalApi/Models/Geolocation.cs diff --git a/Adyen/Model/TerminalApi/GetTotalsRequest.cs b/Adyen/TerminalApi/Models/GetTotalsRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/GetTotalsRequest.cs rename to Adyen/TerminalApi/Models/GetTotalsRequest.cs diff --git a/Adyen/Model/TerminalApi/GetTotalsResponse.cs b/Adyen/TerminalApi/Models/GetTotalsResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/GetTotalsResponse.cs rename to Adyen/TerminalApi/Models/GetTotalsResponse.cs diff --git a/Adyen/Model/TerminalApi/GlobalStatusType.cs b/Adyen/TerminalApi/Models/GlobalStatusType.cs similarity index 100% rename from Adyen/Model/TerminalApi/GlobalStatusType.cs rename to Adyen/TerminalApi/Models/GlobalStatusType.cs diff --git a/Adyen/Model/TerminalApi/HostStatus.cs b/Adyen/TerminalApi/Models/HostStatus.cs similarity index 100% rename from Adyen/Model/TerminalApi/HostStatus.cs rename to Adyen/TerminalApi/Models/HostStatus.cs diff --git a/Adyen/Model/TerminalApi/ICCResetData.cs b/Adyen/TerminalApi/Models/ICCResetData.cs similarity index 100% rename from Adyen/Model/TerminalApi/ICCResetData.cs rename to Adyen/TerminalApi/Models/ICCResetData.cs diff --git a/Adyen/Model/TerminalApi/IdentificationSupportType.cs b/Adyen/TerminalApi/Models/IdentificationSupportType.cs similarity index 100% rename from Adyen/Model/TerminalApi/IdentificationSupportType.cs rename to Adyen/TerminalApi/Models/IdentificationSupportType.cs diff --git a/Adyen/Model/TerminalApi/IdentificationType.cs b/Adyen/TerminalApi/Models/IdentificationType.cs similarity index 100% rename from Adyen/Model/TerminalApi/IdentificationType.cs rename to Adyen/TerminalApi/Models/IdentificationType.cs diff --git a/Adyen/Model/TerminalApi/InfoQualifyType.cs b/Adyen/TerminalApi/Models/InfoQualifyType.cs similarity index 100% rename from Adyen/Model/TerminalApi/InfoQualifyType.cs rename to Adyen/TerminalApi/Models/InfoQualifyType.cs diff --git a/Adyen/Model/TerminalApi/Input.cs b/Adyen/TerminalApi/Models/Input.cs similarity index 100% rename from Adyen/Model/TerminalApi/Input.cs rename to Adyen/TerminalApi/Models/Input.cs diff --git a/Adyen/Model/TerminalApi/InputCommandType.cs b/Adyen/TerminalApi/Models/InputCommandType.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputCommandType.cs rename to Adyen/TerminalApi/Models/InputCommandType.cs diff --git a/Adyen/Model/TerminalApi/InputData.cs b/Adyen/TerminalApi/Models/InputData.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputData.cs rename to Adyen/TerminalApi/Models/InputData.cs diff --git a/Adyen/Model/TerminalApi/InputRequest.cs b/Adyen/TerminalApi/Models/InputRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputRequest.cs rename to Adyen/TerminalApi/Models/InputRequest.cs diff --git a/Adyen/Model/TerminalApi/InputResponse.cs b/Adyen/TerminalApi/Models/InputResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputResponse.cs rename to Adyen/TerminalApi/Models/InputResponse.cs diff --git a/Adyen/Model/TerminalApi/InputResult.cs b/Adyen/TerminalApi/Models/InputResult.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputResult.cs rename to Adyen/TerminalApi/Models/InputResult.cs diff --git a/Adyen/Model/TerminalApi/InputUpdate.cs b/Adyen/TerminalApi/Models/InputUpdate.cs similarity index 100% rename from Adyen/Model/TerminalApi/InputUpdate.cs rename to Adyen/TerminalApi/Models/InputUpdate.cs diff --git a/Adyen/Model/TerminalApi/Instalment.cs b/Adyen/TerminalApi/Models/Instalment.cs similarity index 100% rename from Adyen/Model/TerminalApi/Instalment.cs rename to Adyen/TerminalApi/Models/Instalment.cs diff --git a/Adyen/Model/TerminalApi/IssuerAndSerialNumber.cs b/Adyen/TerminalApi/Models/IssuerAndSerialNumber.cs similarity index 100% rename from Adyen/Model/TerminalApi/IssuerAndSerialNumber.cs rename to Adyen/TerminalApi/Models/IssuerAndSerialNumber.cs diff --git a/Adyen/Model/TerminalApi/KEK.cs b/Adyen/TerminalApi/Models/KEK.cs similarity index 100% rename from Adyen/Model/TerminalApi/KEK.cs rename to Adyen/TerminalApi/Models/KEK.cs diff --git a/Adyen/Model/TerminalApi/KEKIdentifier.cs b/Adyen/TerminalApi/Models/KEKIdentifier.cs similarity index 100% rename from Adyen/Model/TerminalApi/KEKIdentifier.cs rename to Adyen/TerminalApi/Models/KEKIdentifier.cs diff --git a/Adyen/Model/TerminalApi/KeyTransport.cs b/Adyen/TerminalApi/Models/KeyTransport.cs similarity index 100% rename from Adyen/Model/TerminalApi/KeyTransport.cs rename to Adyen/TerminalApi/Models/KeyTransport.cs diff --git a/Adyen/Model/TerminalApi/LoginRequest.cs b/Adyen/TerminalApi/Models/LoginRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoginRequest.cs rename to Adyen/TerminalApi/Models/LoginRequest.cs diff --git a/Adyen/Model/TerminalApi/LoginResponse.cs b/Adyen/TerminalApi/Models/LoginResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoginResponse.cs rename to Adyen/TerminalApi/Models/LoginResponse.cs diff --git a/Adyen/Model/TerminalApi/LogoutRequest.cs b/Adyen/TerminalApi/Models/LogoutRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/LogoutRequest.cs rename to Adyen/TerminalApi/Models/LogoutRequest.cs diff --git a/Adyen/Model/TerminalApi/LogoutResponse.cs b/Adyen/TerminalApi/Models/LogoutResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/LogoutResponse.cs rename to Adyen/TerminalApi/Models/LogoutResponse.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAccount.cs b/Adyen/TerminalApi/Models/LoyaltyAccount.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAccount.cs rename to Adyen/TerminalApi/Models/LoyaltyAccount.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAccountID.cs b/Adyen/TerminalApi/Models/LoyaltyAccountID.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAccountID.cs rename to Adyen/TerminalApi/Models/LoyaltyAccountID.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAccountReq.cs b/Adyen/TerminalApi/Models/LoyaltyAccountReq.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAccountReq.cs rename to Adyen/TerminalApi/Models/LoyaltyAccountReq.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAccountStatus.cs b/Adyen/TerminalApi/Models/LoyaltyAccountStatus.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAccountStatus.cs rename to Adyen/TerminalApi/Models/LoyaltyAccountStatus.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAcquirerData.cs b/Adyen/TerminalApi/Models/LoyaltyAcquirerData.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAcquirerData.cs rename to Adyen/TerminalApi/Models/LoyaltyAcquirerData.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyAmount.cs b/Adyen/TerminalApi/Models/LoyaltyAmount.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyAmount.cs rename to Adyen/TerminalApi/Models/LoyaltyAmount.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyData.cs b/Adyen/TerminalApi/Models/LoyaltyData.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyData.cs rename to Adyen/TerminalApi/Models/LoyaltyData.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyHandlingType.cs b/Adyen/TerminalApi/Models/LoyaltyHandlingType.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyHandlingType.cs rename to Adyen/TerminalApi/Models/LoyaltyHandlingType.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyRequest.cs b/Adyen/TerminalApi/Models/LoyaltyRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyRequest.cs rename to Adyen/TerminalApi/Models/LoyaltyRequest.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyResponse.cs b/Adyen/TerminalApi/Models/LoyaltyResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyResponse.cs rename to Adyen/TerminalApi/Models/LoyaltyResponse.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyResult.cs b/Adyen/TerminalApi/Models/LoyaltyResult.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyResult.cs rename to Adyen/TerminalApi/Models/LoyaltyResult.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyTotals.cs b/Adyen/TerminalApi/Models/LoyaltyTotals.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyTotals.cs rename to Adyen/TerminalApi/Models/LoyaltyTotals.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyTransaction.cs b/Adyen/TerminalApi/Models/LoyaltyTransaction.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyTransaction.cs rename to Adyen/TerminalApi/Models/LoyaltyTransaction.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyTransactionType.cs b/Adyen/TerminalApi/Models/LoyaltyTransactionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyTransactionType.cs rename to Adyen/TerminalApi/Models/LoyaltyTransactionType.cs diff --git a/Adyen/Model/TerminalApi/LoyaltyUnitType.cs b/Adyen/TerminalApi/Models/LoyaltyUnitType.cs similarity index 100% rename from Adyen/Model/TerminalApi/LoyaltyUnitType.cs rename to Adyen/TerminalApi/Models/LoyaltyUnitType.cs diff --git a/Adyen/Model/TerminalApi/MenuEntry.cs b/Adyen/TerminalApi/Models/MenuEntry.cs similarity index 100% rename from Adyen/Model/TerminalApi/MenuEntry.cs rename to Adyen/TerminalApi/Models/MenuEntry.cs diff --git a/Adyen/Model/TerminalApi/MenuEntryTagType.cs b/Adyen/TerminalApi/Models/MenuEntryTagType.cs similarity index 100% rename from Adyen/Model/TerminalApi/MenuEntryTagType.cs rename to Adyen/TerminalApi/Models/MenuEntryTagType.cs diff --git a/Adyen/Model/TerminalApi/MessageCategoryType.cs b/Adyen/TerminalApi/Models/MessageCategoryType.cs similarity index 100% rename from Adyen/Model/TerminalApi/MessageCategoryType.cs rename to Adyen/TerminalApi/Models/MessageCategoryType.cs diff --git a/Adyen/Model/TerminalApi/MessageClassType.cs b/Adyen/TerminalApi/Models/MessageClassType.cs similarity index 100% rename from Adyen/Model/TerminalApi/MessageClassType.cs rename to Adyen/TerminalApi/Models/MessageClassType.cs diff --git a/Adyen/Model/TerminalApi/MessageHeader.cs b/Adyen/TerminalApi/Models/MessageHeader.cs similarity index 100% rename from Adyen/Model/TerminalApi/MessageHeader.cs rename to Adyen/TerminalApi/Models/MessageHeader.cs diff --git a/Adyen/Model/TerminalApi/MessageReference.cs b/Adyen/TerminalApi/Models/MessageReference.cs similarity index 100% rename from Adyen/Model/TerminalApi/MessageReference.cs rename to Adyen/TerminalApi/Models/MessageReference.cs diff --git a/Adyen/Model/TerminalApi/MessageType.cs b/Adyen/TerminalApi/Models/MessageType.cs similarity index 100% rename from Adyen/Model/TerminalApi/MessageType.cs rename to Adyen/TerminalApi/Models/MessageType.cs diff --git a/Adyen/Model/TerminalApi/MobileData.cs b/Adyen/TerminalApi/Models/MobileData.cs similarity index 100% rename from Adyen/Model/TerminalApi/MobileData.cs rename to Adyen/TerminalApi/Models/MobileData.cs diff --git a/Adyen/Model/TerminalApi/NamedKeyEncryptedData.cs b/Adyen/TerminalApi/Models/NamedKeyEncryptedData.cs similarity index 100% rename from Adyen/Model/TerminalApi/NamedKeyEncryptedData.cs rename to Adyen/TerminalApi/Models/NamedKeyEncryptedData.cs diff --git a/Adyen/Model/TerminalApi/OriginalPOITransaction.cs b/Adyen/TerminalApi/Models/OriginalPOITransaction.cs similarity index 100% rename from Adyen/Model/TerminalApi/OriginalPOITransaction.cs rename to Adyen/TerminalApi/Models/OriginalPOITransaction.cs diff --git a/Adyen/Model/TerminalApi/OutputBarcode.cs b/Adyen/TerminalApi/Models/OutputBarcode.cs similarity index 100% rename from Adyen/Model/TerminalApi/OutputBarcode.cs rename to Adyen/TerminalApi/Models/OutputBarcode.cs diff --git a/Adyen/Model/TerminalApi/OutputContent.cs b/Adyen/TerminalApi/Models/OutputContent.cs similarity index 100% rename from Adyen/Model/TerminalApi/OutputContent.cs rename to Adyen/TerminalApi/Models/OutputContent.cs diff --git a/Adyen/Model/TerminalApi/OutputFormatType.cs b/Adyen/TerminalApi/Models/OutputFormatType.cs similarity index 100% rename from Adyen/Model/TerminalApi/OutputFormatType.cs rename to Adyen/TerminalApi/Models/OutputFormatType.cs diff --git a/Adyen/Model/TerminalApi/OutputResult.cs b/Adyen/TerminalApi/Models/OutputResult.cs similarity index 100% rename from Adyen/Model/TerminalApi/OutputResult.cs rename to Adyen/TerminalApi/Models/OutputResult.cs diff --git a/Adyen/Model/TerminalApi/OutputText.cs b/Adyen/TerminalApi/Models/OutputText.cs similarity index 100% rename from Adyen/Model/TerminalApi/OutputText.cs rename to Adyen/TerminalApi/Models/OutputText.cs diff --git a/Adyen/Model/TerminalApi/PINFormatType.cs b/Adyen/TerminalApi/Models/PINFormatType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PINFormatType.cs rename to Adyen/TerminalApi/Models/PINFormatType.cs diff --git a/Adyen/Model/TerminalApi/PINRequest.cs b/Adyen/TerminalApi/Models/PINRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/PINRequest.cs rename to Adyen/TerminalApi/Models/PINRequest.cs diff --git a/Adyen/Model/TerminalApi/PINRequestType.cs b/Adyen/TerminalApi/Models/PINRequestType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PINRequestType.cs rename to Adyen/TerminalApi/Models/PINRequestType.cs diff --git a/Adyen/Model/TerminalApi/PINResponse.cs b/Adyen/TerminalApi/Models/PINResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/PINResponse.cs rename to Adyen/TerminalApi/Models/PINResponse.cs diff --git a/Adyen/Model/TerminalApi/POIData.cs b/Adyen/TerminalApi/Models/POIData.cs similarity index 100% rename from Adyen/Model/TerminalApi/POIData.cs rename to Adyen/TerminalApi/Models/POIData.cs diff --git a/Adyen/Model/TerminalApi/POIProfile.cs b/Adyen/TerminalApi/Models/POIProfile.cs similarity index 100% rename from Adyen/Model/TerminalApi/POIProfile.cs rename to Adyen/TerminalApi/Models/POIProfile.cs diff --git a/Adyen/Model/TerminalApi/POISoftware.cs b/Adyen/TerminalApi/Models/POISoftware.cs similarity index 100% rename from Adyen/Model/TerminalApi/POISoftware.cs rename to Adyen/TerminalApi/Models/POISoftware.cs diff --git a/Adyen/Model/TerminalApi/POIStatus.cs b/Adyen/TerminalApi/Models/POIStatus.cs similarity index 100% rename from Adyen/Model/TerminalApi/POIStatus.cs rename to Adyen/TerminalApi/Models/POIStatus.cs diff --git a/Adyen/Model/TerminalApi/POISystemData.cs b/Adyen/TerminalApi/Models/POISystemData.cs similarity index 100% rename from Adyen/Model/TerminalApi/POISystemData.cs rename to Adyen/TerminalApi/Models/POISystemData.cs diff --git a/Adyen/Model/TerminalApi/POITerminalData.cs b/Adyen/TerminalApi/Models/POITerminalData.cs similarity index 100% rename from Adyen/Model/TerminalApi/POITerminalData.cs rename to Adyen/TerminalApi/Models/POITerminalData.cs diff --git a/Adyen/Model/TerminalApi/Parameter.cs b/Adyen/TerminalApi/Models/Parameter.cs similarity index 100% rename from Adyen/Model/TerminalApi/Parameter.cs rename to Adyen/TerminalApi/Models/Parameter.cs diff --git a/Adyen/Model/TerminalApi/PaymentAccountReq.cs b/Adyen/TerminalApi/Models/PaymentAccountReq.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentAccountReq.cs rename to Adyen/TerminalApi/Models/PaymentAccountReq.cs diff --git a/Adyen/Model/TerminalApi/PaymentAccountStatus.cs b/Adyen/TerminalApi/Models/PaymentAccountStatus.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentAccountStatus.cs rename to Adyen/TerminalApi/Models/PaymentAccountStatus.cs diff --git a/Adyen/Model/TerminalApi/PaymentAcquirerData.cs b/Adyen/TerminalApi/Models/PaymentAcquirerData.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentAcquirerData.cs rename to Adyen/TerminalApi/Models/PaymentAcquirerData.cs diff --git a/Adyen/Model/TerminalApi/PaymentData.cs b/Adyen/TerminalApi/Models/PaymentData.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentData.cs rename to Adyen/TerminalApi/Models/PaymentData.cs diff --git a/Adyen/Model/TerminalApi/PaymentInstrumentData.cs b/Adyen/TerminalApi/Models/PaymentInstrumentData.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentInstrumentData.cs rename to Adyen/TerminalApi/Models/PaymentInstrumentData.cs diff --git a/Adyen/Model/TerminalApi/PaymentInstrumentType.cs b/Adyen/TerminalApi/Models/PaymentInstrumentType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentInstrumentType.cs rename to Adyen/TerminalApi/Models/PaymentInstrumentType.cs diff --git a/Adyen/Model/TerminalApi/PaymentReceipt.cs b/Adyen/TerminalApi/Models/PaymentReceipt.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentReceipt.cs rename to Adyen/TerminalApi/Models/PaymentReceipt.cs diff --git a/Adyen/Model/TerminalApi/PaymentRequest.cs b/Adyen/TerminalApi/Models/PaymentRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentRequest.cs rename to Adyen/TerminalApi/Models/PaymentRequest.cs diff --git a/Adyen/Model/TerminalApi/PaymentResponse.cs b/Adyen/TerminalApi/Models/PaymentResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentResponse.cs rename to Adyen/TerminalApi/Models/PaymentResponse.cs diff --git a/Adyen/Model/TerminalApi/PaymentResult.cs b/Adyen/TerminalApi/Models/PaymentResult.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentResult.cs rename to Adyen/TerminalApi/Models/PaymentResult.cs diff --git a/Adyen/Model/TerminalApi/PaymentToken.cs b/Adyen/TerminalApi/Models/PaymentToken.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentToken.cs rename to Adyen/TerminalApi/Models/PaymentToken.cs diff --git a/Adyen/Model/TerminalApi/PaymentTotals.cs b/Adyen/TerminalApi/Models/PaymentTotals.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentTotals.cs rename to Adyen/TerminalApi/Models/PaymentTotals.cs diff --git a/Adyen/Model/TerminalApi/PaymentTransaction.cs b/Adyen/TerminalApi/Models/PaymentTransaction.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentTransaction.cs rename to Adyen/TerminalApi/Models/PaymentTransaction.cs diff --git a/Adyen/Model/TerminalApi/PaymentType.cs b/Adyen/TerminalApi/Models/PaymentType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PaymentType.cs rename to Adyen/TerminalApi/Models/PaymentType.cs diff --git a/Adyen/Model/TerminalApi/PerformedTransaction.cs b/Adyen/TerminalApi/Models/PerformedTransaction.cs similarity index 100% rename from Adyen/Model/TerminalApi/PerformedTransaction.cs rename to Adyen/TerminalApi/Models/PerformedTransaction.cs diff --git a/Adyen/Model/TerminalApi/PeriodUnitType.cs b/Adyen/TerminalApi/Models/PeriodUnitType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PeriodUnitType.cs rename to Adyen/TerminalApi/Models/PeriodUnitType.cs diff --git a/Adyen/Model/TerminalApi/PredefinedContent.cs b/Adyen/TerminalApi/Models/PredefinedContent.cs similarity index 100% rename from Adyen/Model/TerminalApi/PredefinedContent.cs rename to Adyen/TerminalApi/Models/PredefinedContent.cs diff --git a/Adyen/Model/TerminalApi/PrintOutput.cs b/Adyen/TerminalApi/Models/PrintOutput.cs similarity index 100% rename from Adyen/Model/TerminalApi/PrintOutput.cs rename to Adyen/TerminalApi/Models/PrintOutput.cs diff --git a/Adyen/Model/TerminalApi/PrintRequest.cs b/Adyen/TerminalApi/Models/PrintRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/PrintRequest.cs rename to Adyen/TerminalApi/Models/PrintRequest.cs diff --git a/Adyen/Model/TerminalApi/PrintResponse.cs b/Adyen/TerminalApi/Models/PrintResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/PrintResponse.cs rename to Adyen/TerminalApi/Models/PrintResponse.cs diff --git a/Adyen/Model/TerminalApi/PrinterStatusType.cs b/Adyen/TerminalApi/Models/PrinterStatusType.cs similarity index 100% rename from Adyen/Model/TerminalApi/PrinterStatusType.cs rename to Adyen/TerminalApi/Models/PrinterStatusType.cs diff --git a/Adyen/Model/TerminalApi/Rebates.cs b/Adyen/TerminalApi/Models/Rebates.cs similarity index 100% rename from Adyen/Model/TerminalApi/Rebates.cs rename to Adyen/TerminalApi/Models/Rebates.cs diff --git a/Adyen/Model/TerminalApi/RecipientIdentifier.cs b/Adyen/TerminalApi/Models/RecipientIdentifier.cs similarity index 100% rename from Adyen/Model/TerminalApi/RecipientIdentifier.cs rename to Adyen/TerminalApi/Models/RecipientIdentifier.cs diff --git a/Adyen/Model/TerminalApi/ReconciliationRequest.cs b/Adyen/TerminalApi/Models/ReconciliationRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReconciliationRequest.cs rename to Adyen/TerminalApi/Models/ReconciliationRequest.cs diff --git a/Adyen/Model/TerminalApi/ReconciliationResponse.cs b/Adyen/TerminalApi/Models/ReconciliationResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReconciliationResponse.cs rename to Adyen/TerminalApi/Models/ReconciliationResponse.cs diff --git a/Adyen/Model/TerminalApi/ReconciliationType.cs b/Adyen/TerminalApi/Models/ReconciliationType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReconciliationType.cs rename to Adyen/TerminalApi/Models/ReconciliationType.cs diff --git a/Adyen/Model/TerminalApi/RelativeDistinguishedName.cs b/Adyen/TerminalApi/Models/RelativeDistinguishedName.cs similarity index 100% rename from Adyen/Model/TerminalApi/RelativeDistinguishedName.cs rename to Adyen/TerminalApi/Models/RelativeDistinguishedName.cs diff --git a/Adyen/Model/TerminalApi/RepeatedMessageResponse.cs b/Adyen/TerminalApi/Models/RepeatedMessageResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/RepeatedMessageResponse.cs rename to Adyen/TerminalApi/Models/RepeatedMessageResponse.cs diff --git a/Adyen/Model/TerminalApi/RepeatedResponseMessageBody.cs b/Adyen/TerminalApi/Models/RepeatedResponseMessageBody.cs similarity index 100% rename from Adyen/Model/TerminalApi/RepeatedResponseMessageBody.cs rename to Adyen/TerminalApi/Models/RepeatedResponseMessageBody.cs diff --git a/Adyen/Model/TerminalApi/Message/SaleToPOIRequest.cs b/Adyen/TerminalApi/Models/Requests/SaleToPOIRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/Message/SaleToPOIRequest.cs rename to Adyen/TerminalApi/Models/Requests/SaleToPOIRequest.cs diff --git a/Adyen/Model/TerminalApi/Message/SaleToPoiRequestSecured.cs b/Adyen/TerminalApi/Models/Requests/SaleToPoiRequestSecured.cs similarity index 100% rename from Adyen/Model/TerminalApi/Message/SaleToPoiRequestSecured.cs rename to Adyen/TerminalApi/Models/Requests/SaleToPoiRequestSecured.cs diff --git a/Adyen/Model/TerminalApi/Message/SaleToPoiResponseSecured.cs b/Adyen/TerminalApi/Models/Requests/SaleToPoiResponseSecured.cs similarity index 100% rename from Adyen/Model/TerminalApi/Message/SaleToPoiResponseSecured.cs rename to Adyen/TerminalApi/Models/Requests/SaleToPoiResponseSecured.cs diff --git a/Adyen/Model/TerminalApi/Response.cs b/Adyen/TerminalApi/Models/Response.cs similarity index 100% rename from Adyen/Model/TerminalApi/Response.cs rename to Adyen/TerminalApi/Models/Response.cs diff --git a/Adyen/Model/TerminalApi/ResponseModeType.cs b/Adyen/TerminalApi/Models/ResponseModeType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ResponseModeType.cs rename to Adyen/TerminalApi/Models/ResponseModeType.cs diff --git a/Adyen/Model/TerminalApi/ResultType.cs b/Adyen/TerminalApi/Models/ResultType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ResultType.cs rename to Adyen/TerminalApi/Models/ResultType.cs diff --git a/Adyen/Model/TerminalApi/ReversalReasonType.cs b/Adyen/TerminalApi/Models/ReversalReasonType.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReversalReasonType.cs rename to Adyen/TerminalApi/Models/ReversalReasonType.cs diff --git a/Adyen/Model/TerminalApi/ReversalRequest.cs b/Adyen/TerminalApi/Models/ReversalRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReversalRequest.cs rename to Adyen/TerminalApi/Models/ReversalRequest.cs diff --git a/Adyen/Model/TerminalApi/ReversalResponse.cs b/Adyen/TerminalApi/Models/ReversalResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/ReversalResponse.cs rename to Adyen/TerminalApi/Models/ReversalResponse.cs diff --git a/Adyen/Model/TerminalApi/SaleData.cs b/Adyen/TerminalApi/Models/SaleData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleData.cs rename to Adyen/TerminalApi/Models/SaleData.cs diff --git a/Adyen/Model/TerminalApi/SaleItem.cs b/Adyen/TerminalApi/Models/SaleItem.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleItem.cs rename to Adyen/TerminalApi/Models/SaleItem.cs diff --git a/Adyen/Model/TerminalApi/SaleItemRebate.cs b/Adyen/TerminalApi/Models/SaleItemRebate.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleItemRebate.cs rename to Adyen/TerminalApi/Models/SaleItemRebate.cs diff --git a/Adyen/Model/TerminalApi/SaleProfile.cs b/Adyen/TerminalApi/Models/SaleProfile.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleProfile.cs rename to Adyen/TerminalApi/Models/SaleProfile.cs diff --git a/Adyen/Model/TerminalApi/SaleSoftware.cs b/Adyen/TerminalApi/Models/SaleSoftware.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleSoftware.cs rename to Adyen/TerminalApi/Models/SaleSoftware.cs diff --git a/Adyen/Model/TerminalApi/SaleTerminalData.cs b/Adyen/TerminalApi/Models/SaleTerminalData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleTerminalData.cs rename to Adyen/TerminalApi/Models/SaleTerminalData.cs diff --git a/Adyen/Model/Terminal/SaleToAcquirerData.cs b/Adyen/TerminalApi/Models/SaleToAcquirerData.cs similarity index 99% rename from Adyen/Model/Terminal/SaleToAcquirerData.cs rename to Adyen/TerminalApi/Models/SaleToAcquirerData.cs index 160feed02..246b09233 100644 --- a/Adyen/Model/Terminal/SaleToAcquirerData.cs +++ b/Adyen/TerminalApi/Models/SaleToAcquirerData.cs @@ -137,6 +137,7 @@ public override string ToString() sb.Append(" RecurringDetailName: ").Append(RecurringDetailName).Append("\n"); sb.Append(" RecurringTokenService: ").Append(RecurringTokenService).Append("\n"); sb.Append(" Store: ").Append(Store).Append("\n"); + sb.Append(" Ssc: ").Append(Ssc).Append("\n"); sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); sb.Append(" Currency: ").Append(Currency).Append("\n"); sb.Append(" ApplicationInfo: ").Append(ApplicationInfo).Append("\n"); diff --git a/Adyen/Model/TerminalApi/SaleToIssuerData.cs b/Adyen/TerminalApi/Models/SaleToIssuerData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleToIssuerData.cs rename to Adyen/TerminalApi/Models/SaleToIssuerData.cs diff --git a/Adyen/Model/TerminalApi/SaleToPOIMessage.cs b/Adyen/TerminalApi/Models/SaleToPOIMessage.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleToPOIMessage.cs rename to Adyen/TerminalApi/Models/SaleToPOIMessage.cs diff --git a/Adyen/Model/TerminalApi/SaleToPOIResponse.cs b/Adyen/TerminalApi/Models/SaleToPOIResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/SaleToPOIResponse.cs rename to Adyen/TerminalApi/Models/SaleToPOIResponse.cs diff --git a/Adyen/Model/TerminalApi/SensitiveCardData.cs b/Adyen/TerminalApi/Models/SensitiveCardData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SensitiveCardData.cs rename to Adyen/TerminalApi/Models/SensitiveCardData.cs diff --git a/Adyen/Model/TerminalApi/SensitiveMobileData.cs b/Adyen/TerminalApi/Models/SensitiveMobileData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SensitiveMobileData.cs rename to Adyen/TerminalApi/Models/SensitiveMobileData.cs diff --git a/Adyen/Model/TerminalApi/SignaturePoint.cs b/Adyen/TerminalApi/Models/SignaturePoint.cs similarity index 100% rename from Adyen/Model/TerminalApi/SignaturePoint.cs rename to Adyen/TerminalApi/Models/SignaturePoint.cs diff --git a/Adyen/Model/TerminalApi/SignedData.cs b/Adyen/TerminalApi/Models/SignedData.cs similarity index 100% rename from Adyen/Model/TerminalApi/SignedData.cs rename to Adyen/TerminalApi/Models/SignedData.cs diff --git a/Adyen/Model/TerminalApi/Signer.cs b/Adyen/TerminalApi/Models/Signer.cs similarity index 100% rename from Adyen/Model/TerminalApi/Signer.cs rename to Adyen/TerminalApi/Models/Signer.cs diff --git a/Adyen/Model/TerminalApi/SignerIdentifier.cs b/Adyen/TerminalApi/Models/SignerIdentifier.cs similarity index 100% rename from Adyen/Model/TerminalApi/SignerIdentifier.cs rename to Adyen/TerminalApi/Models/SignerIdentifier.cs diff --git a/Adyen/Model/TerminalApi/SoundActionType.cs b/Adyen/TerminalApi/Models/SoundActionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/SoundActionType.cs rename to Adyen/TerminalApi/Models/SoundActionType.cs diff --git a/Adyen/Model/TerminalApi/SoundContent.cs b/Adyen/TerminalApi/Models/SoundContent.cs similarity index 100% rename from Adyen/Model/TerminalApi/SoundContent.cs rename to Adyen/TerminalApi/Models/SoundContent.cs diff --git a/Adyen/Model/TerminalApi/SoundFormatType.cs b/Adyen/TerminalApi/Models/SoundFormatType.cs similarity index 100% rename from Adyen/Model/TerminalApi/SoundFormatType.cs rename to Adyen/TerminalApi/Models/SoundFormatType.cs diff --git a/Adyen/Model/TerminalApi/SoundRequest.cs b/Adyen/TerminalApi/Models/SoundRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/SoundRequest.cs rename to Adyen/TerminalApi/Models/SoundRequest.cs diff --git a/Adyen/Model/TerminalApi/SoundResponse.cs b/Adyen/TerminalApi/Models/SoundResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/SoundResponse.cs rename to Adyen/TerminalApi/Models/SoundResponse.cs diff --git a/Adyen/Model/Terminal/Split.cs b/Adyen/TerminalApi/Models/Split.cs similarity index 100% rename from Adyen/Model/Terminal/Split.cs rename to Adyen/TerminalApi/Models/Split.cs diff --git a/Adyen/Model/Terminal/SplitItem.cs b/Adyen/TerminalApi/Models/SplitItem.cs similarity index 100% rename from Adyen/Model/Terminal/SplitItem.cs rename to Adyen/TerminalApi/Models/SplitItem.cs diff --git a/Adyen/Model/Terminal/SplitItemType.cs b/Adyen/TerminalApi/Models/SplitItemType.cs similarity index 100% rename from Adyen/Model/Terminal/SplitItemType.cs rename to Adyen/TerminalApi/Models/SplitItemType.cs diff --git a/Adyen/Model/TerminalApi/SponsoredMerchant.cs b/Adyen/TerminalApi/Models/SponsoredMerchant.cs similarity index 100% rename from Adyen/Model/TerminalApi/SponsoredMerchant.cs rename to Adyen/TerminalApi/Models/SponsoredMerchant.cs diff --git a/Adyen/Model/TerminalApi/StoredValueAccountID.cs b/Adyen/TerminalApi/Models/StoredValueAccountID.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueAccountID.cs rename to Adyen/TerminalApi/Models/StoredValueAccountID.cs diff --git a/Adyen/Model/TerminalApi/StoredValueAccountStatus.cs b/Adyen/TerminalApi/Models/StoredValueAccountStatus.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueAccountStatus.cs rename to Adyen/TerminalApi/Models/StoredValueAccountStatus.cs diff --git a/Adyen/Model/TerminalApi/StoredValueAccountType.cs b/Adyen/TerminalApi/Models/StoredValueAccountType.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueAccountType.cs rename to Adyen/TerminalApi/Models/StoredValueAccountType.cs diff --git a/Adyen/Model/TerminalApi/StoredValueData.cs b/Adyen/TerminalApi/Models/StoredValueData.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueData.cs rename to Adyen/TerminalApi/Models/StoredValueData.cs diff --git a/Adyen/Model/TerminalApi/StoredValueRequest.cs b/Adyen/TerminalApi/Models/StoredValueRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueRequest.cs rename to Adyen/TerminalApi/Models/StoredValueRequest.cs diff --git a/Adyen/Model/TerminalApi/StoredValueResponse.cs b/Adyen/TerminalApi/Models/StoredValueResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueResponse.cs rename to Adyen/TerminalApi/Models/StoredValueResponse.cs diff --git a/Adyen/Model/TerminalApi/StoredValueResult.cs b/Adyen/TerminalApi/Models/StoredValueResult.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueResult.cs rename to Adyen/TerminalApi/Models/StoredValueResult.cs diff --git a/Adyen/Model/TerminalApi/StoredValueTransactionType.cs b/Adyen/TerminalApi/Models/StoredValueTransactionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/StoredValueTransactionType.cs rename to Adyen/TerminalApi/Models/StoredValueTransactionType.cs diff --git a/Adyen/Model/TerminalApi/TerminalEnvironmentType.cs b/Adyen/TerminalApi/Models/TerminalEnvironmentType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TerminalEnvironmentType.cs rename to Adyen/TerminalApi/Models/TerminalEnvironmentType.cs diff --git a/Adyen/Model/TerminalApi/TokenRequestedType.cs b/Adyen/TerminalApi/Models/TokenRequestedType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TokenRequestedType.cs rename to Adyen/TerminalApi/Models/TokenRequestedType.cs diff --git a/Adyen/Model/TerminalApi/TotalDetailsType.cs b/Adyen/TerminalApi/Models/TotalDetailsType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TotalDetailsType.cs rename to Adyen/TerminalApi/Models/TotalDetailsType.cs diff --git a/Adyen/Model/TerminalApi/TotalFilter.cs b/Adyen/TerminalApi/Models/TotalFilter.cs similarity index 100% rename from Adyen/Model/TerminalApi/TotalFilter.cs rename to Adyen/TerminalApi/Models/TotalFilter.cs diff --git a/Adyen/Model/TerminalApi/TrackData.cs b/Adyen/TerminalApi/Models/TrackData.cs similarity index 100% rename from Adyen/Model/TerminalApi/TrackData.cs rename to Adyen/TerminalApi/Models/TrackData.cs diff --git a/Adyen/Model/TerminalApi/TrackFormatType.cs b/Adyen/TerminalApi/Models/TrackFormatType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TrackFormatType.cs rename to Adyen/TerminalApi/Models/TrackFormatType.cs diff --git a/Adyen/Model/TerminalApi/TransactionActionType.cs b/Adyen/TerminalApi/Models/TransactionActionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionActionType.cs rename to Adyen/TerminalApi/Models/TransactionActionType.cs diff --git a/Adyen/Model/TerminalApi/TransactionConditions.cs b/Adyen/TerminalApi/Models/TransactionConditions.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionConditions.cs rename to Adyen/TerminalApi/Models/TransactionConditions.cs diff --git a/Adyen/Model/TerminalApi/TransactionIdentification.cs b/Adyen/TerminalApi/Models/TransactionIdentification.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionIdentification.cs rename to Adyen/TerminalApi/Models/TransactionIdentification.cs diff --git a/Adyen/Model/TerminalApi/TransactionStatusRequest.cs b/Adyen/TerminalApi/Models/TransactionStatusRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionStatusRequest.cs rename to Adyen/TerminalApi/Models/TransactionStatusRequest.cs diff --git a/Adyen/Model/TerminalApi/TransactionStatusResponse.cs b/Adyen/TerminalApi/Models/TransactionStatusResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionStatusResponse.cs rename to Adyen/TerminalApi/Models/TransactionStatusResponse.cs diff --git a/Adyen/Model/TerminalApi/TransactionToPerform.cs b/Adyen/TerminalApi/Models/TransactionToPerform.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionToPerform.cs rename to Adyen/TerminalApi/Models/TransactionToPerform.cs diff --git a/Adyen/Model/TerminalApi/TransactionTotals.cs b/Adyen/TerminalApi/Models/TransactionTotals.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionTotals.cs rename to Adyen/TerminalApi/Models/TransactionTotals.cs diff --git a/Adyen/Model/TerminalApi/TransactionType.cs b/Adyen/TerminalApi/Models/TransactionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransactionType.cs rename to Adyen/TerminalApi/Models/TransactionType.cs diff --git a/Adyen/Model/TerminalApi/TransmitRequest.cs b/Adyen/TerminalApi/Models/TransmitRequest.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransmitRequest.cs rename to Adyen/TerminalApi/Models/TransmitRequest.cs diff --git a/Adyen/Model/TerminalApi/TransmitResponse.cs b/Adyen/TerminalApi/Models/TransmitResponse.cs similarity index 100% rename from Adyen/Model/TerminalApi/TransmitResponse.cs rename to Adyen/TerminalApi/Models/TransmitResponse.cs diff --git a/Adyen/Model/TerminalApi/UTMCoordinates.cs b/Adyen/TerminalApi/Models/UTMCoordinates.cs similarity index 100% rename from Adyen/Model/TerminalApi/UTMCoordinates.cs rename to Adyen/TerminalApi/Models/UTMCoordinates.cs diff --git a/Adyen/Model/TerminalApi/UnitOfMeasureType.cs b/Adyen/TerminalApi/Models/UnitOfMeasureType.cs similarity index 100% rename from Adyen/Model/TerminalApi/UnitOfMeasureType.cs rename to Adyen/TerminalApi/Models/UnitOfMeasureType.cs diff --git a/Adyen/Model/TerminalApi/VersionType.cs b/Adyen/TerminalApi/Models/VersionType.cs similarity index 100% rename from Adyen/Model/TerminalApi/VersionType.cs rename to Adyen/TerminalApi/Models/VersionType.cs diff --git a/Adyen/Model/RequestOptions.cs b/Adyen/TerminalApi/RequestOptions.cs similarity index 100% rename from Adyen/Model/RequestOptions.cs rename to Adyen/TerminalApi/RequestOptions.cs diff --git a/Adyen/Security/AesEncryptor.cs b/Adyen/TerminalApi/Security/AesEncryptor.cs similarity index 100% rename from Adyen/Security/AesEncryptor.cs rename to Adyen/TerminalApi/Security/AesEncryptor.cs diff --git a/Adyen/Security/EncryptionCredentialDetails.cs b/Adyen/TerminalApi/Security/EncryptionCredentialDetails.cs similarity index 100% rename from Adyen/Security/EncryptionCredentialDetails.cs rename to Adyen/TerminalApi/Security/EncryptionCredentialDetails.cs diff --git a/Adyen/Security/EncryptionDerivedKey.cs b/Adyen/TerminalApi/Security/EncryptionDerivedKey.cs similarity index 100% rename from Adyen/Security/EncryptionDerivedKey.cs rename to Adyen/TerminalApi/Security/EncryptionDerivedKey.cs diff --git a/Adyen/Security/EncryptionDerivedKeyGenerator.cs b/Adyen/TerminalApi/Security/EncryptionDerivedKeyGenerator.cs similarity index 100% rename from Adyen/Security/EncryptionDerivedKeyGenerator.cs rename to Adyen/TerminalApi/Security/EncryptionDerivedKeyGenerator.cs diff --git a/Adyen/Security/Exceptions/NexoCryptoException.cs b/Adyen/TerminalApi/Security/Exceptions/NexoCryptoException.cs similarity index 100% rename from Adyen/Security/Exceptions/NexoCryptoException.cs rename to Adyen/TerminalApi/Security/Exceptions/NexoCryptoException.cs diff --git a/Adyen/Security/Extension/ArrayExtension.cs b/Adyen/TerminalApi/Security/Extension/ArrayExtension.cs similarity index 100% rename from Adyen/Security/Extension/ArrayExtension.cs rename to Adyen/TerminalApi/Security/Extension/ArrayExtension.cs diff --git a/Adyen/Security/HmacSha256Wrapper.cs b/Adyen/TerminalApi/Security/HmacSha256Wrapper.cs similarity index 100% rename from Adyen/Security/HmacSha256Wrapper.cs rename to Adyen/TerminalApi/Security/HmacSha256Wrapper.cs diff --git a/Adyen/Security/IvModGenerator.cs b/Adyen/TerminalApi/Security/IvModGenerator.cs similarity index 100% rename from Adyen/Security/IvModGenerator.cs rename to Adyen/TerminalApi/Security/IvModGenerator.cs diff --git a/Adyen/Security/SaleToPoiMessageSecured.cs b/Adyen/TerminalApi/Security/SaleToPoiMessageSecured.cs similarity index 100% rename from Adyen/Security/SaleToPoiMessageSecured.cs rename to Adyen/TerminalApi/Security/SaleToPoiMessageSecured.cs diff --git a/Adyen/Security/SaleToPoiMessageSecuredEncryptor.cs b/Adyen/TerminalApi/Security/SaleToPoiMessageSecuredEncryptor.cs similarity index 100% rename from Adyen/Security/SaleToPoiMessageSecuredEncryptor.cs rename to Adyen/TerminalApi/Security/SaleToPoiMessageSecuredEncryptor.cs diff --git a/Adyen/Security/SecurityTrailer.cs b/Adyen/TerminalApi/Security/SecurityTrailer.cs similarity index 100% rename from Adyen/Security/SecurityTrailer.cs rename to Adyen/TerminalApi/Security/SecurityTrailer.cs diff --git a/Adyen/Security/TerminalCommonNameValidator.cs b/Adyen/TerminalApi/Security/TerminalCommonNameValidator.cs similarity index 100% rename from Adyen/Security/TerminalCommonNameValidator.cs rename to Adyen/TerminalApi/Security/TerminalCommonNameValidator.cs diff --git a/Adyen/Service/ServiceResource.cs b/Adyen/TerminalApi/Services/ServiceResource.cs similarity index 97% rename from Adyen/Service/ServiceResource.cs rename to Adyen/TerminalApi/Services/ServiceResource.cs index d5ffc3384..fce890f9a 100644 --- a/Adyen/Service/ServiceResource.cs +++ b/Adyen/TerminalApi/Services/ServiceResource.cs @@ -1,46 +1,46 @@ -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Adyen.Model; -using Newtonsoft.Json; - -namespace Adyen.Service -{ - public class ServiceResource - { - private readonly AbstractService _abstractService; - protected string Endpoint; - - public ServiceResource(AbstractService abstractService, string endpoint) - { - _abstractService = abstractService; - Endpoint = endpoint; - } - - public string Request(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null) - { - var clientInterface = _abstractService.Client.HttpClient; - return clientInterface.Request(Endpoint, json, requestOptions, httpMethod); - } - - public T Request(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null) - { - var clientInterface = _abstractService.Client.HttpClient; - var jsonResponse = clientInterface.Request(Endpoint, json, requestOptions, httpMethod); - return JsonConvert.DeserializeObject(jsonResponse); - } - - public async Task RequestAsync(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null, CancellationToken cancellationToken = default) - { - var clientInterface = _abstractService.Client.HttpClient; - return await clientInterface.RequestAsync(Endpoint, json, requestOptions, httpMethod, cancellationToken).ConfigureAwait(false); - } - - public async Task RequestAsync(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null, CancellationToken cancellationToken = default) - { - var clientInterface = _abstractService.Client.HttpClient; - var jsonResponse = await clientInterface.RequestAsync(Endpoint, json, requestOptions, httpMethod, cancellationToken).ConfigureAwait(false); - return JsonConvert.DeserializeObject(jsonResponse); - } - } +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Adyen.Model; +using Newtonsoft.Json; + +namespace Adyen.Service +{ + public class ServiceResource + { + private readonly AbstractService _abstractService; + protected string Endpoint; + + public ServiceResource(AbstractService abstractService, string endpoint) + { + _abstractService = abstractService; + Endpoint = endpoint; + } + + public string Request(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null) + { + var clientInterface = _abstractService.Client.HttpClient; + return clientInterface.Request(Endpoint, json, requestOptions, httpMethod); + } + + public T Request(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null) + { + var clientInterface = _abstractService.Client.HttpClient; + var jsonResponse = clientInterface.Request(Endpoint, json, requestOptions, httpMethod); + return JsonConvert.DeserializeObject(jsonResponse); + } + + public async Task RequestAsync(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null, CancellationToken cancellationToken = default) + { + var clientInterface = _abstractService.Client.HttpClient; + return await clientInterface.RequestAsync(Endpoint, json, requestOptions, httpMethod, cancellationToken).ConfigureAwait(false); + } + + public async Task RequestAsync(string json, RequestOptions requestOptions = null, HttpMethod httpMethod = null, CancellationToken cancellationToken = default) + { + var clientInterface = _abstractService.Client.HttpClient; + var jsonResponse = await clientInterface.RequestAsync(Endpoint, json, requestOptions, httpMethod, cancellationToken).ConfigureAwait(false); + return JsonConvert.DeserializeObject(jsonResponse); + } + } } \ No newline at end of file diff --git a/Adyen/Service/TerminalApiAsyncService.cs b/Adyen/TerminalApi/Services/TerminalApiAsyncService.cs similarity index 100% rename from Adyen/Service/TerminalApiAsyncService.cs rename to Adyen/TerminalApi/Services/TerminalApiAsyncService.cs diff --git a/Adyen/Service/TerminalApiLocalService.cs b/Adyen/TerminalApi/Services/TerminalApiLocalService.cs similarity index 97% rename from Adyen/Service/TerminalApiLocalService.cs rename to Adyen/TerminalApi/Services/TerminalApiLocalService.cs index b21b955a4..b1ce906db 100644 --- a/Adyen/Service/TerminalApiLocalService.cs +++ b/Adyen/TerminalApi/Services/TerminalApiLocalService.cs @@ -38,7 +38,7 @@ public interface ITerminalApiLocalService /// /// Example: /// handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true }; - /// var httpClient = new (, new (handler)); + /// var httpClient = new (, new (handler)); /// var terminalApiLocalService = new (httpClient, , , ); /// /// . @@ -52,7 +52,7 @@ public interface ITerminalApiLocalService /// /// Example: /// handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true }; - /// var httpClient = new (, new (handler)); + /// var httpClient = new (, new (handler)); /// var terminalApiLocalService = new (httpClient, , , ); /// /// . diff --git a/Adyen/Service/TerminalApiSyncService.cs b/Adyen/TerminalApi/Services/TerminalApiSyncService.cs similarity index 100% rename from Adyen/Service/TerminalApiSyncService.cs rename to Adyen/TerminalApi/Services/TerminalApiSyncService.cs diff --git a/Adyen/Service/TerminalCloudApi.cs b/Adyen/TerminalApi/Services/TerminalCloudApi.cs similarity index 100% rename from Adyen/Service/TerminalCloudApi.cs rename to Adyen/TerminalApi/Services/TerminalCloudApi.cs diff --git a/Adyen/Service/TerminalLocalApi.cs b/Adyen/TerminalApi/Services/TerminalLocalApi.cs similarity index 100% rename from Adyen/Service/TerminalLocalApi.cs rename to Adyen/TerminalApi/Services/TerminalLocalApi.cs diff --git a/Adyen/Service/TerminalLocalApiUnencrypted.cs b/Adyen/TerminalApi/Services/TerminalLocalApiUnencrypted.cs similarity index 100% rename from Adyen/Service/TerminalLocalApiUnencrypted.cs rename to Adyen/TerminalApi/Services/TerminalLocalApiUnencrypted.cs diff --git a/Adyen/Util/TerminalApi/AdditionalResponse.cs b/Adyen/TerminalApi/Utilities/AdditionalResponse.cs similarity index 100% rename from Adyen/Util/TerminalApi/AdditionalResponse.cs rename to Adyen/TerminalApi/Utilities/AdditionalResponse.cs diff --git a/Adyen/Util/TerminalApi/CardAcquisitionUtil.cs b/Adyen/TerminalApi/Utilities/CardAcquisitionUtil.cs similarity index 100% rename from Adyen/Util/TerminalApi/CardAcquisitionUtil.cs rename to Adyen/TerminalApi/Utilities/CardAcquisitionUtil.cs diff --git a/Adyen/TokenizationWebhooks/Client/ClientUtils.cs b/Adyen/TokenizationWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..14abe74ba --- /dev/null +++ b/Adyen/TokenizationWebhooks/Client/ClientUtils.cs @@ -0,0 +1,303 @@ +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.TokenizationWebhooks.Models; +using Models = Adyen.TokenizationWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.TokenizationWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.TokenizationAlreadyExistingDetailsNotificationRequest.EnvironmentEnum tokenizationAlreadyExistingDetailsNotificationRequestEnvironmentEnum) + return Models.TokenizationAlreadyExistingDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationAlreadyExistingDetailsNotificationRequestEnvironmentEnum); + if (obj is Models.TokenizationAlreadyExistingDetailsNotificationRequest.TypeEnum tokenizationAlreadyExistingDetailsNotificationRequestTypeEnum) + return Models.TokenizationAlreadyExistingDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationAlreadyExistingDetailsNotificationRequestTypeEnum); + if (obj is Models.TokenizationCreatedDetailsNotificationRequest.EnvironmentEnum tokenizationCreatedDetailsNotificationRequestEnvironmentEnum) + return Models.TokenizationCreatedDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationCreatedDetailsNotificationRequestEnvironmentEnum); + if (obj is Models.TokenizationCreatedDetailsNotificationRequest.TypeEnum tokenizationCreatedDetailsNotificationRequestTypeEnum) + return Models.TokenizationCreatedDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationCreatedDetailsNotificationRequestTypeEnum); + if (obj is Models.TokenizationDisabledDetailsNotificationRequest.EnvironmentEnum tokenizationDisabledDetailsNotificationRequestEnvironmentEnum) + return Models.TokenizationDisabledDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationDisabledDetailsNotificationRequestEnvironmentEnum); + if (obj is Models.TokenizationDisabledDetailsNotificationRequest.TypeEnum tokenizationDisabledDetailsNotificationRequestTypeEnum) + return Models.TokenizationDisabledDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationDisabledDetailsNotificationRequestTypeEnum); + if (obj is Models.TokenizationUpdatedDetailsNotificationRequest.EnvironmentEnum tokenizationUpdatedDetailsNotificationRequestEnvironmentEnum) + return Models.TokenizationUpdatedDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationUpdatedDetailsNotificationRequestEnvironmentEnum); + if (obj is Models.TokenizationUpdatedDetailsNotificationRequest.TypeEnum tokenizationUpdatedDetailsNotificationRequestTypeEnum) + return Models.TokenizationUpdatedDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationUpdatedDetailsNotificationRequestTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/TokenizationWebhooks/Client/HmacKeyToken.cs b/Adyen/TokenizationWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..59649bf88 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.TokenizationWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/TokenizationWebhooks/Client/HostConfiguration.cs b/Adyen/TokenizationWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..4a6d763f0 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,134 @@ +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.TokenizationWebhooks.Client; +using Adyen.TokenizationWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.TokenizationWebhooks.Client +{ + /// + /// Provides hosting configuration for TokenizationWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new RecurringTokenJsonConverter()); + _jsonOptions.Converters.Add(new RecurringTokenStoreOperationJsonConverter()); + _jsonOptions.Converters.Add(new TokenizationAlreadyExistingDetailsNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TokenizationCreatedDetailsNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TokenizationDisabledDetailsNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TokenizationNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new TokenizationUpdatedDetailsNotificationRequestJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddTokenizationWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/TokenizationWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/TokenizationWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..57633ba38 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.TokenizationWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/TokenizationWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/TokenizationWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..5ca3b1144 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.TokenizationWebhooks; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the TokenizationWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureTokenizationWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddTokenizationWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/TokenizationWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/TokenizationWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..a3f156cb7 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen TokenizationWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddTokenizationWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddTokenizationWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Handlers/TokenizationWebhooksHandler.cs b/Adyen/TokenizationWebhooks/Handlers/TokenizationWebhooksHandler.cs new file mode 100644 index 000000000..f66878553 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Handlers/TokenizationWebhooksHandler.cs @@ -0,0 +1,121 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.TokenizationWebhooks.Client; +using Adyen.TokenizationWebhooks.Models; + +namespace Adyen.TokenizationWebhooks.Handlers +{ + /// + /// Interface for deserializing TokenizationWebhooks webhooks or verify its HMAC signature. + /// + public interface ITokenizationWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.TokenizationWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TokenizationAlreadyExistingDetailsNotificationRequest? DeserializeTokenizationAlreadyExistingDetailsNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TokenizationCreatedDetailsNotificationRequest? DeserializeTokenizationCreatedDetailsNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TokenizationDisabledDetailsNotificationRequest? DeserializeTokenizationDisabledDetailsNotificationRequest(string json); + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TokenizationUpdatedDetailsNotificationRequest? DeserializeTokenizationUpdatedDetailsNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize TokenizationWebhooks or verify the HMAC signature of the webhook. + /// + public partial class TokenizationWebhooksHandler : ITokenizationWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.TokenizationWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing TokenizationWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public TokenizationWebhooksHandler(Adyen.TokenizationWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public TokenizationAlreadyExistingDetailsNotificationRequest? DeserializeTokenizationAlreadyExistingDetailsNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public TokenizationCreatedDetailsNotificationRequest? DeserializeTokenizationCreatedDetailsNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public TokenizationDisabledDetailsNotificationRequest? DeserializeTokenizationDisabledDetailsNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public TokenizationUpdatedDetailsNotificationRequest? DeserializeTokenizationUpdatedDetailsNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/RecurringToken.cs b/Adyen/TokenizationWebhooks/Models/RecurringToken.cs new file mode 100644 index 000000000..6fece2b88 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/RecurringToken.cs @@ -0,0 +1,231 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// RecurringToken. + /// + public partial class RecurringToken : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + /// The ID of the token. + /// The type of the payment method. + [JsonConstructor] + public RecurringToken(string merchantAccount, string shopperReference, string storedPaymentMethodId, string type) + { + MerchantAccount = merchantAccount; + ShopperReference = shopperReference; + StoredPaymentMethodId = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringToken() + { + } + + partial void OnCreated(); + + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + /// + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// The ID of the token. + /// + /// The ID of the token. + [JsonPropertyName("storedPaymentMethodId")] + public string StoredPaymentMethodId { get; set; } + + /// + /// The type of the payment method. + /// + /// The type of the payment method. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringToken {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringTokenJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringToken Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option shopperReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class RecurringToken.", nameof(merchantAccount)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class RecurringToken.", nameof(shopperReference)); + + if (!storedPaymentMethodId.IsSet) + throw new ArgumentException("Property is required for class RecurringToken.", nameof(storedPaymentMethodId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RecurringToken.", nameof(type)); + + return new RecurringToken(merchantAccount.Value!, shopperReference.Value!, storedPaymentMethodId.Value!, type.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringToken recurringToken, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringToken, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringToken recurringToken, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringToken.MerchantAccount != null) + writer.WriteString("merchantAccount", recurringToken.MerchantAccount); + + if (recurringToken.ShopperReference != null) + writer.WriteString("shopperReference", recurringToken.ShopperReference); + + if (recurringToken.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", recurringToken.StoredPaymentMethodId); + + if (recurringToken.Type != null) + writer.WriteString("type", recurringToken.Type); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/RecurringTokenStoreOperation.cs b/Adyen/TokenizationWebhooks/Models/RecurringTokenStoreOperation.cs new file mode 100644 index 000000000..525fcecc9 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/RecurringTokenStoreOperation.cs @@ -0,0 +1,251 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// RecurringTokenStoreOperation. + /// + public partial class RecurringTokenStoreOperation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + /// A text description that provides details about the operation, intended for audit purposes. + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + /// The ID of the token. + /// The type of the payment method. + [JsonConstructor] + public RecurringTokenStoreOperation(string merchantAccount, string operation, string shopperReference, string storedPaymentMethodId, string type) + { + MerchantAccount = merchantAccount; + Operation = operation; + ShopperReference = shopperReference; + StoredPaymentMethodId = storedPaymentMethodId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RecurringTokenStoreOperation() + { + } + + partial void OnCreated(); + + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + /// + /// The identifier of the merchant account related to the event that triggered the webhook. + [JsonPropertyName("merchantAccount")] + public string MerchantAccount { get; set; } + + /// + /// A text description that provides details about the operation, intended for audit purposes. + /// + /// A text description that provides details about the operation, intended for audit purposes. + [JsonPropertyName("operation")] + public string Operation { get; set; } + + /// + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + /// + /// Your unique shopper reference that is associated with the `storedPaymentMethodId`. + [JsonPropertyName("shopperReference")] + public string ShopperReference { get; set; } + + /// + /// The ID of the token. + /// + /// The ID of the token. + [JsonPropertyName("storedPaymentMethodId")] + public string StoredPaymentMethodId { get; set; } + + /// + /// The type of the payment method. + /// + /// The type of the payment method. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RecurringTokenStoreOperation {\n"); + sb.Append(" MerchantAccount: ").Append(MerchantAccount).Append("\n"); + sb.Append(" Operation: ").Append(Operation).Append("\n"); + sb.Append(" ShopperReference: ").Append(ShopperReference).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RecurringTokenStoreOperationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RecurringTokenStoreOperation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option merchantAccount = default; + Option operation = default; + Option shopperReference = default; + Option storedPaymentMethodId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "merchantAccount": + merchantAccount = new Option(utf8JsonReader.GetString()!); + break; + case "operation": + operation = new Option(utf8JsonReader.GetString()!); + break; + case "shopperReference": + shopperReference = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!merchantAccount.IsSet) + throw new ArgumentException("Property is required for class RecurringTokenStoreOperation.", nameof(merchantAccount)); + + if (!operation.IsSet) + throw new ArgumentException("Property is required for class RecurringTokenStoreOperation.", nameof(operation)); + + if (!shopperReference.IsSet) + throw new ArgumentException("Property is required for class RecurringTokenStoreOperation.", nameof(shopperReference)); + + if (!storedPaymentMethodId.IsSet) + throw new ArgumentException("Property is required for class RecurringTokenStoreOperation.", nameof(storedPaymentMethodId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RecurringTokenStoreOperation.", nameof(type)); + + return new RecurringTokenStoreOperation(merchantAccount.Value!, operation.Value!, shopperReference.Value!, storedPaymentMethodId.Value!, type.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecurringTokenStoreOperation recurringTokenStoreOperation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, recurringTokenStoreOperation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RecurringTokenStoreOperation recurringTokenStoreOperation, JsonSerializerOptions jsonSerializerOptions) + { + + if (recurringTokenStoreOperation.MerchantAccount != null) + writer.WriteString("merchantAccount", recurringTokenStoreOperation.MerchantAccount); + + if (recurringTokenStoreOperation.Operation != null) + writer.WriteString("operation", recurringTokenStoreOperation.Operation); + + if (recurringTokenStoreOperation.ShopperReference != null) + writer.WriteString("shopperReference", recurringTokenStoreOperation.ShopperReference); + + if (recurringTokenStoreOperation.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", recurringTokenStoreOperation.StoredPaymentMethodId); + + if (recurringTokenStoreOperation.Type != null) + writer.WriteString("type", recurringTokenStoreOperation.Type); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/TokenizationAlreadyExistingDetailsNotificationRequest.cs b/Adyen/TokenizationWebhooks/Models/TokenizationAlreadyExistingDetailsNotificationRequest.cs new file mode 100644 index 000000000..574e03ca4 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/TokenizationAlreadyExistingDetailsNotificationRequest.cs @@ -0,0 +1,486 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// TokenizationAlreadyExistingDetailsNotificationRequest. + /// + public partial class TokenizationAlreadyExistingDetailsNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The PSP reference of the event that triggered the webhook. + /// The type of webhook. + /// The version of this entity. + [JsonConstructor] + public TokenizationAlreadyExistingDetailsNotificationRequest(DateTimeOffset createdAt, RecurringTokenStoreOperation data, EnvironmentEnum environment, string eventId, TypeEnum type, Option version = default) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + EventId = eventId; + Type = type; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenizationAlreadyExistingDetailsNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonConverter(typeof(EnvironmentEnumJsonConverter))] + public class EnvironmentEnum : IEnum + { + /// + /// Returns the value of the EnvironmentEnum. + /// + public string? Value { get; set; } + + /// + /// EnvironmentEnum.Test - test + /// + public static readonly EnvironmentEnum Test = new("test"); + + /// + /// EnvironmentEnum.Live - live + /// + public static readonly EnvironmentEnum Live = new("live"); + + private EnvironmentEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EnvironmentEnum?(string? value) => value == null ? null : new EnvironmentEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EnvironmentEnum? option) => option?.Value; + + public static bool operator ==(EnvironmentEnum? left, EnvironmentEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EnvironmentEnum? left, EnvironmentEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EnvironmentEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EnvironmentEnum? FromStringOrDefault(string value) + { + return value switch { + "test" => EnvironmentEnum.Test, + "live" => EnvironmentEnum.Live, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EnvironmentEnum? value) + { + if (value == null) + return null; + + if (value == EnvironmentEnum.Test) + return "test"; + + if (value == EnvironmentEnum.Live) + return "live"; + + return null; + } + + /// + /// JsonConverter for writing EnvironmentEnum. + /// + public class EnvironmentEnumJsonConverter : JsonConverter + { + public override EnvironmentEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EnvironmentEnum.FromStringOrDefault(value) ?? new EnvironmentEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EnvironmentEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EnvironmentEnum.ToJsonValue(value)); + } + } + } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /* live */ + [JsonPropertyName("environment")] + public EnvironmentEnum Environment { get; set; } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.RecurringTokenAlreadyExisting - recurring.token.alreadyExisting + /// + public static readonly TypeEnum RecurringTokenAlreadyExisting = new("recurring.token.alreadyExisting"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "recurring.token.alreadyExisting" => TypeEnum.RecurringTokenAlreadyExisting, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.RecurringTokenAlreadyExisting) + return "recurring.token.alreadyExisting"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /* 2024-10-29T16:15:29+01:00 */ + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public RecurringTokenStoreOperation Data { get; set; } + + /// + /// The PSP reference of the event that triggered the webhook. + /// + /// The PSP reference of the event that triggered the webhook. + [JsonPropertyName("eventId")] + public string EventId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// The version of this entity. + /// + /// The version of this entity. + /* 1 */ + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenizationAlreadyExistingDetailsNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenizationAlreadyExistingDetailsNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenizationAlreadyExistingDetailsNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option eventId = default; + Option type = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + string? environmentRawValue = utf8JsonReader.GetString(); + environment = new Option(TokenizationAlreadyExistingDetailsNotificationRequest.EnvironmentEnum.FromStringOrDefault(environmentRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TokenizationAlreadyExistingDetailsNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TokenizationAlreadyExistingDetailsNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TokenizationAlreadyExistingDetailsNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TokenizationAlreadyExistingDetailsNotificationRequest.", nameof(environment)); + + if (!eventId.IsSet) + throw new ArgumentException("Property is required for class TokenizationAlreadyExistingDetailsNotificationRequest.", nameof(eventId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TokenizationAlreadyExistingDetailsNotificationRequest.", nameof(type)); + + return new TokenizationAlreadyExistingDetailsNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!.Value!, eventId.Value!, type.Value!.Value!, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenizationAlreadyExistingDetailsNotificationRequest tokenizationAlreadyExistingDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenizationAlreadyExistingDetailsNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenizationAlreadyExistingDetailsNotificationRequest tokenizationAlreadyExistingDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", tokenizationAlreadyExistingDetailsNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tokenizationAlreadyExistingDetailsNotificationRequest.Data, jsonSerializerOptions); + if (tokenizationAlreadyExistingDetailsNotificationRequest.Environment != null) + { + string? environmentRawValue = TokenizationAlreadyExistingDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationAlreadyExistingDetailsNotificationRequest.Environment); + writer.WriteString("environment", environmentRawValue); + } + + if (tokenizationAlreadyExistingDetailsNotificationRequest.EventId != null) + writer.WriteString("eventId", tokenizationAlreadyExistingDetailsNotificationRequest.EventId); + + if (tokenizationAlreadyExistingDetailsNotificationRequest.Type != null) + { + string? typeRawValue = TokenizationAlreadyExistingDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationAlreadyExistingDetailsNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (tokenizationAlreadyExistingDetailsNotificationRequest._VersionOption.IsSet) + if (tokenizationAlreadyExistingDetailsNotificationRequest.Version != null) + writer.WriteString("version", tokenizationAlreadyExistingDetailsNotificationRequest.Version); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/TokenizationCreatedDetailsNotificationRequest.cs b/Adyen/TokenizationWebhooks/Models/TokenizationCreatedDetailsNotificationRequest.cs new file mode 100644 index 000000000..b57a6f72c --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/TokenizationCreatedDetailsNotificationRequest.cs @@ -0,0 +1,486 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// TokenizationCreatedDetailsNotificationRequest. + /// + public partial class TokenizationCreatedDetailsNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The PSP reference of the event that triggered the webhook. + /// The type of webhook. + /// The version of this entity. + [JsonConstructor] + public TokenizationCreatedDetailsNotificationRequest(DateTimeOffset createdAt, RecurringTokenStoreOperation data, EnvironmentEnum environment, string eventId, TypeEnum type, Option version = default) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + EventId = eventId; + Type = type; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenizationCreatedDetailsNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonConverter(typeof(EnvironmentEnumJsonConverter))] + public class EnvironmentEnum : IEnum + { + /// + /// Returns the value of the EnvironmentEnum. + /// + public string? Value { get; set; } + + /// + /// EnvironmentEnum.Test - test + /// + public static readonly EnvironmentEnum Test = new("test"); + + /// + /// EnvironmentEnum.Live - live + /// + public static readonly EnvironmentEnum Live = new("live"); + + private EnvironmentEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EnvironmentEnum?(string? value) => value == null ? null : new EnvironmentEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EnvironmentEnum? option) => option?.Value; + + public static bool operator ==(EnvironmentEnum? left, EnvironmentEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EnvironmentEnum? left, EnvironmentEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EnvironmentEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EnvironmentEnum? FromStringOrDefault(string value) + { + return value switch { + "test" => EnvironmentEnum.Test, + "live" => EnvironmentEnum.Live, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EnvironmentEnum? value) + { + if (value == null) + return null; + + if (value == EnvironmentEnum.Test) + return "test"; + + if (value == EnvironmentEnum.Live) + return "live"; + + return null; + } + + /// + /// JsonConverter for writing EnvironmentEnum. + /// + public class EnvironmentEnumJsonConverter : JsonConverter + { + public override EnvironmentEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EnvironmentEnum.FromStringOrDefault(value) ?? new EnvironmentEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EnvironmentEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EnvironmentEnum.ToJsonValue(value)); + } + } + } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /* live */ + [JsonPropertyName("environment")] + public EnvironmentEnum Environment { get; set; } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.RecurringTokenCreated - recurring.token.created + /// + public static readonly TypeEnum RecurringTokenCreated = new("recurring.token.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "recurring.token.created" => TypeEnum.RecurringTokenCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.RecurringTokenCreated) + return "recurring.token.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /* 2024-10-29T16:15:29+01:00 */ + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public RecurringTokenStoreOperation Data { get; set; } + + /// + /// The PSP reference of the event that triggered the webhook. + /// + /// The PSP reference of the event that triggered the webhook. + [JsonPropertyName("eventId")] + public string EventId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// The version of this entity. + /// + /// The version of this entity. + /* 1 */ + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenizationCreatedDetailsNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenizationCreatedDetailsNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenizationCreatedDetailsNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option eventId = default; + Option type = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + string? environmentRawValue = utf8JsonReader.GetString(); + environment = new Option(TokenizationCreatedDetailsNotificationRequest.EnvironmentEnum.FromStringOrDefault(environmentRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TokenizationCreatedDetailsNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TokenizationCreatedDetailsNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TokenizationCreatedDetailsNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TokenizationCreatedDetailsNotificationRequest.", nameof(environment)); + + if (!eventId.IsSet) + throw new ArgumentException("Property is required for class TokenizationCreatedDetailsNotificationRequest.", nameof(eventId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TokenizationCreatedDetailsNotificationRequest.", nameof(type)); + + return new TokenizationCreatedDetailsNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!.Value!, eventId.Value!, type.Value!.Value!, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenizationCreatedDetailsNotificationRequest tokenizationCreatedDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenizationCreatedDetailsNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenizationCreatedDetailsNotificationRequest tokenizationCreatedDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", tokenizationCreatedDetailsNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tokenizationCreatedDetailsNotificationRequest.Data, jsonSerializerOptions); + if (tokenizationCreatedDetailsNotificationRequest.Environment != null) + { + string? environmentRawValue = TokenizationCreatedDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationCreatedDetailsNotificationRequest.Environment); + writer.WriteString("environment", environmentRawValue); + } + + if (tokenizationCreatedDetailsNotificationRequest.EventId != null) + writer.WriteString("eventId", tokenizationCreatedDetailsNotificationRequest.EventId); + + if (tokenizationCreatedDetailsNotificationRequest.Type != null) + { + string? typeRawValue = TokenizationCreatedDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationCreatedDetailsNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (tokenizationCreatedDetailsNotificationRequest._VersionOption.IsSet) + if (tokenizationCreatedDetailsNotificationRequest.Version != null) + writer.WriteString("version", tokenizationCreatedDetailsNotificationRequest.Version); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/TokenizationDisabledDetailsNotificationRequest.cs b/Adyen/TokenizationWebhooks/Models/TokenizationDisabledDetailsNotificationRequest.cs new file mode 100644 index 000000000..847d33515 --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/TokenizationDisabledDetailsNotificationRequest.cs @@ -0,0 +1,486 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// TokenizationDisabledDetailsNotificationRequest. + /// + public partial class TokenizationDisabledDetailsNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The PSP reference of the event that triggered the webhook. + /// The type of webhook. + /// The version of this entity. + [JsonConstructor] + public TokenizationDisabledDetailsNotificationRequest(DateTimeOffset createdAt, RecurringToken data, EnvironmentEnum environment, string eventId, TypeEnum type, Option version = default) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + EventId = eventId; + Type = type; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenizationDisabledDetailsNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonConverter(typeof(EnvironmentEnumJsonConverter))] + public class EnvironmentEnum : IEnum + { + /// + /// Returns the value of the EnvironmentEnum. + /// + public string? Value { get; set; } + + /// + /// EnvironmentEnum.Test - test + /// + public static readonly EnvironmentEnum Test = new("test"); + + /// + /// EnvironmentEnum.Live - live + /// + public static readonly EnvironmentEnum Live = new("live"); + + private EnvironmentEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EnvironmentEnum?(string? value) => value == null ? null : new EnvironmentEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EnvironmentEnum? option) => option?.Value; + + public static bool operator ==(EnvironmentEnum? left, EnvironmentEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EnvironmentEnum? left, EnvironmentEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EnvironmentEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EnvironmentEnum? FromStringOrDefault(string value) + { + return value switch { + "test" => EnvironmentEnum.Test, + "live" => EnvironmentEnum.Live, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EnvironmentEnum? value) + { + if (value == null) + return null; + + if (value == EnvironmentEnum.Test) + return "test"; + + if (value == EnvironmentEnum.Live) + return "live"; + + return null; + } + + /// + /// JsonConverter for writing EnvironmentEnum. + /// + public class EnvironmentEnumJsonConverter : JsonConverter + { + public override EnvironmentEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EnvironmentEnum.FromStringOrDefault(value) ?? new EnvironmentEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EnvironmentEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EnvironmentEnum.ToJsonValue(value)); + } + } + } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /* live */ + [JsonPropertyName("environment")] + public EnvironmentEnum Environment { get; set; } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.RecurringTokenDisabled - recurring.token.disabled + /// + public static readonly TypeEnum RecurringTokenDisabled = new("recurring.token.disabled"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "recurring.token.disabled" => TypeEnum.RecurringTokenDisabled, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.RecurringTokenDisabled) + return "recurring.token.disabled"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /* 2024-10-29T16:15:29+01:00 */ + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public RecurringToken Data { get; set; } + + /// + /// The PSP reference of the event that triggered the webhook. + /// + /// The PSP reference of the event that triggered the webhook. + [JsonPropertyName("eventId")] + public string EventId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// The version of this entity. + /// + /// The version of this entity. + /* 1 */ + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenizationDisabledDetailsNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenizationDisabledDetailsNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenizationDisabledDetailsNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option eventId = default; + Option type = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + string? environmentRawValue = utf8JsonReader.GetString(); + environment = new Option(TokenizationDisabledDetailsNotificationRequest.EnvironmentEnum.FromStringOrDefault(environmentRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TokenizationDisabledDetailsNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TokenizationDisabledDetailsNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TokenizationDisabledDetailsNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TokenizationDisabledDetailsNotificationRequest.", nameof(environment)); + + if (!eventId.IsSet) + throw new ArgumentException("Property is required for class TokenizationDisabledDetailsNotificationRequest.", nameof(eventId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TokenizationDisabledDetailsNotificationRequest.", nameof(type)); + + return new TokenizationDisabledDetailsNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!.Value!, eventId.Value!, type.Value!.Value!, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenizationDisabledDetailsNotificationRequest tokenizationDisabledDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenizationDisabledDetailsNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenizationDisabledDetailsNotificationRequest tokenizationDisabledDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", tokenizationDisabledDetailsNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tokenizationDisabledDetailsNotificationRequest.Data, jsonSerializerOptions); + if (tokenizationDisabledDetailsNotificationRequest.Environment != null) + { + string? environmentRawValue = TokenizationDisabledDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationDisabledDetailsNotificationRequest.Environment); + writer.WriteString("environment", environmentRawValue); + } + + if (tokenizationDisabledDetailsNotificationRequest.EventId != null) + writer.WriteString("eventId", tokenizationDisabledDetailsNotificationRequest.EventId); + + if (tokenizationDisabledDetailsNotificationRequest.Type != null) + { + string? typeRawValue = TokenizationDisabledDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationDisabledDetailsNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (tokenizationDisabledDetailsNotificationRequest._VersionOption.IsSet) + if (tokenizationDisabledDetailsNotificationRequest.Version != null) + writer.WriteString("version", tokenizationDisabledDetailsNotificationRequest.Version); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/TokenizationNotificationResponse.cs b/Adyen/TokenizationWebhooks/Models/TokenizationNotificationResponse.cs new file mode 100644 index 000000000..779328f4a --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/TokenizationNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// TokenizationNotificationResponse. + /// + public partial class TokenizationNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public TokenizationNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenizationNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenizationNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenizationNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenizationNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TokenizationNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenizationNotificationResponse tokenizationNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenizationNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenizationNotificationResponse tokenizationNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (tokenizationNotificationResponse._NotificationResponseOption.IsSet) + if (tokenizationNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", tokenizationNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/TokenizationWebhooks/Models/TokenizationUpdatedDetailsNotificationRequest.cs b/Adyen/TokenizationWebhooks/Models/TokenizationUpdatedDetailsNotificationRequest.cs new file mode 100644 index 000000000..f336fc52b --- /dev/null +++ b/Adyen/TokenizationWebhooks/Models/TokenizationUpdatedDetailsNotificationRequest.cs @@ -0,0 +1,486 @@ +// +/* + * Tokenization webhooks + * + * With Adyen, you can securely store payment details of your shoppers with their consent. We refer to these saved payment details as tokens. We use webhooks to inform you about token lifecycle events. For more information, refer to our [documentation](https://docs.adyen.com/online-payments/tokenization/). + * + * The version of the OpenAPI document: 1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TokenizationWebhooks.Client; + +namespace Adyen.TokenizationWebhooks.Models +{ + /// + /// TokenizationUpdatedDetailsNotificationRequest. + /// + public partial class TokenizationUpdatedDetailsNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// The PSP reference of the event that triggered the webhook. + /// The type of webhook. + /// The version of this entity. + [JsonConstructor] + public TokenizationUpdatedDetailsNotificationRequest(DateTimeOffset createdAt, RecurringTokenStoreOperation data, EnvironmentEnum environment, string eventId, TypeEnum type, Option version = default) + { + CreatedAt = createdAt; + Data = data; + Environment = environment; + EventId = eventId; + Type = type; + _VersionOption = version; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TokenizationUpdatedDetailsNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonConverter(typeof(EnvironmentEnumJsonConverter))] + public class EnvironmentEnum : IEnum + { + /// + /// Returns the value of the EnvironmentEnum. + /// + public string? Value { get; set; } + + /// + /// EnvironmentEnum.Test - test + /// + public static readonly EnvironmentEnum Test = new("test"); + + /// + /// EnvironmentEnum.Live - live + /// + public static readonly EnvironmentEnum Live = new("live"); + + private EnvironmentEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator EnvironmentEnum?(string? value) => value == null ? null : new EnvironmentEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(EnvironmentEnum? option) => option?.Value; + + public static bool operator ==(EnvironmentEnum? left, EnvironmentEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(EnvironmentEnum? left, EnvironmentEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is EnvironmentEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static EnvironmentEnum? FromStringOrDefault(string value) + { + return value switch { + "test" => EnvironmentEnum.Test, + "live" => EnvironmentEnum.Live, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(EnvironmentEnum? value) + { + if (value == null) + return null; + + if (value == EnvironmentEnum.Test) + return "test"; + + if (value == EnvironmentEnum.Live) + return "live"; + + return null; + } + + /// + /// JsonConverter for writing EnvironmentEnum. + /// + public class EnvironmentEnumJsonConverter : JsonConverter + { + public override EnvironmentEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : EnvironmentEnum.FromStringOrDefault(value) ?? new EnvironmentEnum(value); + } + + public override void Write(Utf8JsonWriter writer, EnvironmentEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(EnvironmentEnum.ToJsonValue(value)); + } + } + } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /* live */ + [JsonPropertyName("environment")] + public EnvironmentEnum Environment { get; set; } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.RecurringTokenUpdated - recurring.token.updated + /// + public static readonly TypeEnum RecurringTokenUpdated = new("recurring.token.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "recurring.token.updated" => TypeEnum.RecurringTokenUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.RecurringTokenUpdated) + return "recurring.token.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /// + /// The date and time when the event happened, in ISO 8601 extended format. + /* 2024-10-29T16:15:29+01:00 */ + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + /// + /// . + /// + [JsonPropertyName("data")] + public RecurringTokenStoreOperation Data { get; set; } + + /// + /// The PSP reference of the event that triggered the webhook. + /// + /// The PSP reference of the event that triggered the webhook. + [JsonPropertyName("eventId")] + public string EventId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _VersionOption { get; private set; } + + /// + /// The version of this entity. + /// + /// The version of this entity. + /* 1 */ + [JsonPropertyName("version")] + public string? Version { get { return this._VersionOption; } set { this._VersionOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TokenizationUpdatedDetailsNotificationRequest {\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Version: ").Append(Version).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TokenizationUpdatedDetailsNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TokenizationUpdatedDetailsNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option createdAt = default; + Option data = default; + Option environment = default; + Option eventId = default; + Option type = default; + Option version = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + string? environmentRawValue = utf8JsonReader.GetString(); + environment = new Option(TokenizationUpdatedDetailsNotificationRequest.EnvironmentEnum.FromStringOrDefault(environmentRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TokenizationUpdatedDetailsNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "version": + version = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!createdAt.IsSet) + throw new ArgumentException("Property is required for class TokenizationUpdatedDetailsNotificationRequest.", nameof(createdAt)); + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TokenizationUpdatedDetailsNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TokenizationUpdatedDetailsNotificationRequest.", nameof(environment)); + + if (!eventId.IsSet) + throw new ArgumentException("Property is required for class TokenizationUpdatedDetailsNotificationRequest.", nameof(eventId)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TokenizationUpdatedDetailsNotificationRequest.", nameof(type)); + + return new TokenizationUpdatedDetailsNotificationRequest(createdAt.Value!.Value!, data.Value!, environment.Value!.Value!, eventId.Value!, type.Value!.Value!, version); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TokenizationUpdatedDetailsNotificationRequest tokenizationUpdatedDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, tokenizationUpdatedDetailsNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TokenizationUpdatedDetailsNotificationRequest tokenizationUpdatedDetailsNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("createdAt", tokenizationUpdatedDetailsNotificationRequest.CreatedAt.ToString(CreatedAtFormat)); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tokenizationUpdatedDetailsNotificationRequest.Data, jsonSerializerOptions); + if (tokenizationUpdatedDetailsNotificationRequest.Environment != null) + { + string? environmentRawValue = TokenizationUpdatedDetailsNotificationRequest.EnvironmentEnum.ToJsonValue(tokenizationUpdatedDetailsNotificationRequest.Environment); + writer.WriteString("environment", environmentRawValue); + } + + if (tokenizationUpdatedDetailsNotificationRequest.EventId != null) + writer.WriteString("eventId", tokenizationUpdatedDetailsNotificationRequest.EventId); + + if (tokenizationUpdatedDetailsNotificationRequest.Type != null) + { + string? typeRawValue = TokenizationUpdatedDetailsNotificationRequest.TypeEnum.ToJsonValue(tokenizationUpdatedDetailsNotificationRequest.Type); + writer.WriteString("type", typeRawValue); + } + + if (tokenizationUpdatedDetailsNotificationRequest._VersionOption.IsSet) + if (tokenizationUpdatedDetailsNotificationRequest.Version != null) + writer.WriteString("version", tokenizationUpdatedDetailsNotificationRequest.Version); + } + } +} diff --git a/Adyen/TransactionWebhooks/Client/ClientUtils.cs b/Adyen/TransactionWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..a45fa4f8a --- /dev/null +++ b/Adyen/TransactionWebhooks/Client/ClientUtils.cs @@ -0,0 +1,307 @@ +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.TransactionWebhooks.Models; +using Models = Adyen.TransactionWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.TransactionWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.BankCategoryData.PriorityEnum bankCategoryDataPriorityEnum) + return Models.BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryDataPriorityEnum); + if (obj is Models.BankCategoryData.TypeEnum bankCategoryDataTypeEnum) + return Models.BankCategoryData.TypeEnum.ToJsonValue(bankCategoryDataTypeEnum); + if (obj is Models.InternalCategoryData.TypeEnum internalCategoryDataTypeEnum) + return Models.InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryDataTypeEnum); + if (obj is Models.IssuedCard.PanEntryModeEnum issuedCardPanEntryModeEnum) + return Models.IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCardPanEntryModeEnum); + if (obj is Models.IssuedCard.ProcessingTypeEnum issuedCardProcessingTypeEnum) + return Models.IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCardProcessingTypeEnum); + if (obj is Models.IssuedCard.TypeEnum issuedCardTypeEnum) + return Models.IssuedCard.TypeEnum.ToJsonValue(issuedCardTypeEnum); + if (obj is Models.PlatformPayment.PlatformPaymentTypeEnum platformPaymentPlatformPaymentTypeEnum) + return Models.PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPaymentPlatformPaymentTypeEnum); + if (obj is Models.PlatformPayment.TypeEnum platformPaymentTypeEnum) + return Models.PlatformPayment.TypeEnum.ToJsonValue(platformPaymentTypeEnum); + if (obj is Models.Transaction.StatusEnum transactionStatusEnum) + return Models.Transaction.StatusEnum.ToJsonValue(transactionStatusEnum); + if (obj is Models.TransactionNotificationRequestV4.TypeEnum transactionNotificationRequestV4TypeEnum) + return Models.TransactionNotificationRequestV4.TypeEnum.ToJsonValue(transactionNotificationRequestV4TypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/TransactionWebhooks/Client/HmacKeyToken.cs b/Adyen/TransactionWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..1e25c3bc8 --- /dev/null +++ b/Adyen/TransactionWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.TransactionWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/TransactionWebhooks/Client/HostConfiguration.cs b/Adyen/TransactionWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..71f142952 --- /dev/null +++ b/Adyen/TransactionWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,143 @@ +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.TransactionWebhooks.Client; +using Adyen.TransactionWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.TransactionWebhooks.Client +{ + /// + /// Provides hosting configuration for TransactionWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new BankCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new InternalCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new IssuedCardJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new PlatformPaymentJsonConverter()); + _jsonOptions.Converters.Add(new RelayedAuthorisationDataJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSecureJsonConverter()); + _jsonOptions.Converters.Add(new TransactionJsonConverter()); + _jsonOptions.Converters.Add(new TransactionNotificationRequestV4JsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationValidationFactJsonConverter()); + _jsonOptions.Converters.Add(new TransferViewJsonConverter()); + _jsonOptions.Converters.Add(new TransferViewCategoryDataJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddTransactionWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/TransactionWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/TransactionWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..2ac825084 --- /dev/null +++ b/Adyen/TransactionWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.TransactionWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/TransactionWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/TransactionWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..e24cc4361 --- /dev/null +++ b/Adyen/TransactionWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.TransactionWebhooks; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the TransactionWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureTransactionWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddTransactionWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/TransactionWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/TransactionWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..9de93e6cc --- /dev/null +++ b/Adyen/TransactionWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen TransactionWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddTransactionWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddTransactionWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/TransactionWebhooks/Handlers/TransactionWebhooksHandler.cs b/Adyen/TransactionWebhooks/Handlers/TransactionWebhooksHandler.cs new file mode 100644 index 000000000..89834475b --- /dev/null +++ b/Adyen/TransactionWebhooks/Handlers/TransactionWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.TransactionWebhooks.Client; +using Adyen.TransactionWebhooks.Models; + +namespace Adyen.TransactionWebhooks.Handlers +{ + /// + /// Interface for deserializing TransactionWebhooks webhooks or verify its HMAC signature. + /// + public interface ITransactionWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.TransactionWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TransactionNotificationRequestV4? DeserializeTransactionNotificationRequestV4(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize TransactionWebhooks or verify the HMAC signature of the webhook. + /// + public partial class TransactionWebhooksHandler : ITransactionWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.TransactionWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing TransactionWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public TransactionWebhooksHandler(Adyen.TransactionWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public TransactionNotificationRequestV4? DeserializeTransactionNotificationRequestV4(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/Amount.cs b/Adyen/TransactionWebhooks/Models/Amount.cs new file mode 100644 index 000000000..c87cc3caf --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/TransactionWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..4c2ac3011 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/BankCategoryData.cs b/Adyen/TransactionWebhooks/Models/BankCategoryData.cs new file mode 100644 index 000000000..bf107b7d3 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/BankCategoryData.cs @@ -0,0 +1,441 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// BankCategoryData. + /// + public partial class BankCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// **bank** (default to TypeEnum.Bank) + [JsonConstructor] + public BankCategoryData(Option priority = default, Option type = default) + { + _PriorityOption = priority; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankCategoryData() + { + } + + partial void OnCreated(); + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// **bank** + /// + /// **bank** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Bank - bank + /// + public static readonly TypeEnum Bank = new("bank"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => TypeEnum.Bank, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Bank) + return "bank"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **bank** + /// + /// **bank** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankCategoryData {\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option priority = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(BankCategoryData.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BankCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BankCategoryData(priority, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankCategoryData._PriorityOption.IsSet && bankCategoryData.Priority != null) + { + string? priorityRawValue = BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryData._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (bankCategoryData._TypeOption.IsSet && bankCategoryData.Type != null) + { + string? typeRawValue = BankCategoryData.TypeEnum.ToJsonValue(bankCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/InternalCategoryData.cs b/Adyen/TransactionWebhooks/Models/InternalCategoryData.cs new file mode 100644 index 000000000..5e5a83222 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/InternalCategoryData.cs @@ -0,0 +1,324 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// InternalCategoryData. + /// + public partial class InternalCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// **internal** (default to TypeEnum.Internal) + [JsonConstructor] + public InternalCategoryData(Option modificationMerchantReference = default, Option modificationPspReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternalCategoryData() + { + } + + partial void OnCreated(); + + /// + /// **internal** + /// + /// **internal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Internal - internal + /// + public static readonly TypeEnum Internal = new("internal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "internal" => TypeEnum.Internal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Internal) + return "internal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **internal** + /// + /// **internal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternalCategoryData {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternalCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternalCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InternalCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new InternalCategoryData(modificationMerchantReference, modificationPspReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internalCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (internalCategoryData._ModificationMerchantReferenceOption.IsSet) + if (internalCategoryData.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", internalCategoryData.ModificationMerchantReference); + + if (internalCategoryData._ModificationPspReferenceOption.IsSet) + if (internalCategoryData.ModificationPspReference != null) + writer.WriteString("modificationPspReference", internalCategoryData.ModificationPspReference); + + if (internalCategoryData._TypeOption.IsSet && internalCategoryData.Type != null) + { + string? typeRawValue = InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/IssuedCard.cs b/Adyen/TransactionWebhooks/Models/IssuedCard.cs new file mode 100644 index 000000000..803b510cd --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/IssuedCard.cs @@ -0,0 +1,787 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// IssuedCard. + /// + public partial class IssuedCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// relayedAuthorisationData + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// threeDSecure + /// **issuedCard** (default to TypeEnum.IssuedCard) + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonConstructor] + public IssuedCard(Option authorisationType = default, Option panEntryMode = default, Option processingType = default, Option relayedAuthorisationData = default, Option schemeTraceId = default, Option schemeUniqueTransactionId = default, Option threeDSecure = default, Option type = default, Option?> validationFacts = default) + { + _AuthorisationTypeOption = authorisationType; + _PanEntryModeOption = panEntryMode; + _ProcessingTypeOption = processingType; + _RelayedAuthorisationDataOption = relayedAuthorisationData; + _SchemeTraceIdOption = schemeTraceId; + _SchemeUniqueTransactionIdOption = schemeUniqueTransactionId; + _ThreeDSecureOption = threeDSecure; + _TypeOption = type; + _ValidationFactsOption = validationFacts; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IssuedCard() + { + } + + partial void OnCreated(); + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonConverter(typeof(PanEntryModeEnumJsonConverter))] + public class PanEntryModeEnum : IEnum + { + /// + /// Returns the value of the PanEntryModeEnum. + /// + public string? Value { get; set; } + + /// + /// PanEntryModeEnum.Chip - chip + /// + public static readonly PanEntryModeEnum Chip = new("chip"); + + /// + /// PanEntryModeEnum.Cof - cof + /// + public static readonly PanEntryModeEnum Cof = new("cof"); + + /// + /// PanEntryModeEnum.Contactless - contactless + /// + public static readonly PanEntryModeEnum Contactless = new("contactless"); + + /// + /// PanEntryModeEnum.Ecommerce - ecommerce + /// + public static readonly PanEntryModeEnum Ecommerce = new("ecommerce"); + + /// + /// PanEntryModeEnum.Magstripe - magstripe + /// + public static readonly PanEntryModeEnum Magstripe = new("magstripe"); + + /// + /// PanEntryModeEnum.Manual - manual + /// + public static readonly PanEntryModeEnum Manual = new("manual"); + + /// + /// PanEntryModeEnum.Token - token + /// + public static readonly PanEntryModeEnum Token = new("token"); + + private PanEntryModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PanEntryModeEnum?(string? value) => value == null ? null : new PanEntryModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PanEntryModeEnum? option) => option?.Value; + + public static bool operator ==(PanEntryModeEnum? left, PanEntryModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PanEntryModeEnum? left, PanEntryModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PanEntryModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PanEntryModeEnum? FromStringOrDefault(string value) + { + return value switch { + "chip" => PanEntryModeEnum.Chip, + "cof" => PanEntryModeEnum.Cof, + "contactless" => PanEntryModeEnum.Contactless, + "ecommerce" => PanEntryModeEnum.Ecommerce, + "magstripe" => PanEntryModeEnum.Magstripe, + "manual" => PanEntryModeEnum.Manual, + "token" => PanEntryModeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PanEntryModeEnum? value) + { + if (value == null) + return null; + + if (value == PanEntryModeEnum.Chip) + return "chip"; + + if (value == PanEntryModeEnum.Cof) + return "cof"; + + if (value == PanEntryModeEnum.Contactless) + return "contactless"; + + if (value == PanEntryModeEnum.Ecommerce) + return "ecommerce"; + + if (value == PanEntryModeEnum.Magstripe) + return "magstripe"; + + if (value == PanEntryModeEnum.Manual) + return "manual"; + + if (value == PanEntryModeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing PanEntryModeEnum. + /// + public class PanEntryModeEnumJsonConverter : JsonConverter + { + public override PanEntryModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PanEntryModeEnum.FromStringOrDefault(value) ?? new PanEntryModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PanEntryModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PanEntryModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PanEntryModeOption { get; private set; } + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonPropertyName("panEntryMode")] + public PanEntryModeEnum? PanEntryMode { get { return this._PanEntryModeOption; } set { this._PanEntryModeOption = new(value); } } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.AtmWithdraw - atmWithdraw + /// + public static readonly ProcessingTypeEnum AtmWithdraw = new("atmWithdraw"); + + /// + /// ProcessingTypeEnum.BalanceInquiry - balanceInquiry + /// + public static readonly ProcessingTypeEnum BalanceInquiry = new("balanceInquiry"); + + /// + /// ProcessingTypeEnum.Ecommerce - ecommerce + /// + public static readonly ProcessingTypeEnum Ecommerce = new("ecommerce"); + + /// + /// ProcessingTypeEnum.Moto - moto + /// + public static readonly ProcessingTypeEnum Moto = new("moto"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + /// + /// ProcessingTypeEnum.PurchaseWithCashback - purchaseWithCashback + /// + public static readonly ProcessingTypeEnum PurchaseWithCashback = new("purchaseWithCashback"); + + /// + /// ProcessingTypeEnum.Recurring - recurring + /// + public static readonly ProcessingTypeEnum Recurring = new("recurring"); + + /// + /// ProcessingTypeEnum.Token - token + /// + public static readonly ProcessingTypeEnum Token = new("token"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "atmWithdraw" => ProcessingTypeEnum.AtmWithdraw, + "balanceInquiry" => ProcessingTypeEnum.BalanceInquiry, + "ecommerce" => ProcessingTypeEnum.Ecommerce, + "moto" => ProcessingTypeEnum.Moto, + "pos" => ProcessingTypeEnum.Pos, + "purchaseWithCashback" => ProcessingTypeEnum.PurchaseWithCashback, + "recurring" => ProcessingTypeEnum.Recurring, + "token" => ProcessingTypeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.AtmWithdraw) + return "atmWithdraw"; + + if (value == ProcessingTypeEnum.BalanceInquiry) + return "balanceInquiry"; + + if (value == ProcessingTypeEnum.Ecommerce) + return "ecommerce"; + + if (value == ProcessingTypeEnum.Moto) + return "moto"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + if (value == ProcessingTypeEnum.PurchaseWithCashback) + return "purchaseWithCashback"; + + if (value == ProcessingTypeEnum.Recurring) + return "recurring"; + + if (value == ProcessingTypeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProcessingTypeOption { get; private set; } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum? ProcessingType { get { return this._ProcessingTypeOption; } set { this._ProcessingTypeOption = new(value); } } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IssuedCard - issuedCard + /// + public static readonly TypeEnum IssuedCard = new("issuedCard"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "issuedCard" => TypeEnum.IssuedCard, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IssuedCard) + return "issuedCard"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTypeOption { get; private set; } + + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + [JsonPropertyName("authorisationType")] + public string? AuthorisationType { get { return this._AuthorisationTypeOption; } set { this._AuthorisationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RelayedAuthorisationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("relayedAuthorisationData")] + public RelayedAuthorisationData? RelayedAuthorisationData { get { return this._RelayedAuthorisationDataOption; } set { this._RelayedAuthorisationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeTraceIdOption { get; private set; } + + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + [JsonPropertyName("schemeTraceId")] + public string? SchemeTraceId { get { return this._SchemeTraceIdOption; } set { this._SchemeTraceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeUniqueTransactionIdOption { get; private set; } + + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + [JsonPropertyName("schemeUniqueTransactionId")] + public string? SchemeUniqueTransactionId { get { return this._SchemeUniqueTransactionIdOption; } set { this._SchemeUniqueTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSecure")] + public ThreeDSecure? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValidationFactsOption { get; private set; } + + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonPropertyName("validationFacts")] + public List? ValidationFacts { get { return this._ValidationFactsOption; } set { this._ValidationFactsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IssuedCard {\n"); + sb.Append(" AuthorisationType: ").Append(AuthorisationType).Append("\n"); + sb.Append(" PanEntryMode: ").Append(PanEntryMode).Append("\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" RelayedAuthorisationData: ").Append(RelayedAuthorisationData).Append("\n"); + sb.Append(" SchemeTraceId: ").Append(SchemeTraceId).Append("\n"); + sb.Append(" SchemeUniqueTransactionId: ").Append(SchemeUniqueTransactionId).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IssuedCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IssuedCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authorisationType = default; + Option panEntryMode = default; + Option processingType = default; + Option relayedAuthorisationData = default; + Option schemeTraceId = default; + Option schemeUniqueTransactionId = default; + Option threeDSecure = default; + Option type = default; + Option?> validationFacts = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authorisationType": + authorisationType = new Option(utf8JsonReader.GetString()!); + break; + case "panEntryMode": + string? panEntryModeRawValue = utf8JsonReader.GetString(); + panEntryMode = new Option(IssuedCard.PanEntryModeEnum.FromStringOrDefault(panEntryModeRawValue)); + break; + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(IssuedCard.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "relayedAuthorisationData": + relayedAuthorisationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "schemeTraceId": + schemeTraceId = new Option(utf8JsonReader.GetString()!); + break; + case "schemeUniqueTransactionId": + schemeUniqueTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSecure": + threeDSecure = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IssuedCard.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "validationFacts": + validationFacts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new IssuedCard(authorisationType, panEntryMode, processingType, relayedAuthorisationData, schemeTraceId, schemeUniqueTransactionId, threeDSecure, type, validationFacts); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, issuedCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (issuedCard._AuthorisationTypeOption.IsSet) + if (issuedCard.AuthorisationType != null) + writer.WriteString("authorisationType", issuedCard.AuthorisationType); + + if (issuedCard._PanEntryModeOption.IsSet && issuedCard.PanEntryMode != null) + { + string? panEntryModeRawValue = IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCard._PanEntryModeOption.Value!.Value); + writer.WriteString("panEntryMode", panEntryModeRawValue); + } + + if (issuedCard._ProcessingTypeOption.IsSet && issuedCard.ProcessingType != null) + { + string? processingTypeRawValue = IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCard._ProcessingTypeOption.Value!.Value); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (issuedCard._RelayedAuthorisationDataOption.IsSet) + { + writer.WritePropertyName("relayedAuthorisationData"); + JsonSerializer.Serialize(writer, issuedCard.RelayedAuthorisationData, jsonSerializerOptions); + } + if (issuedCard._SchemeTraceIdOption.IsSet) + if (issuedCard.SchemeTraceId != null) + writer.WriteString("schemeTraceId", issuedCard.SchemeTraceId); + + if (issuedCard._SchemeUniqueTransactionIdOption.IsSet) + if (issuedCard.SchemeUniqueTransactionId != null) + writer.WriteString("schemeUniqueTransactionId", issuedCard.SchemeUniqueTransactionId); + + if (issuedCard._ThreeDSecureOption.IsSet) + { + writer.WritePropertyName("threeDSecure"); + JsonSerializer.Serialize(writer, issuedCard.ThreeDSecure, jsonSerializerOptions); + } + if (issuedCard._TypeOption.IsSet && issuedCard.Type != null) + { + string? typeRawValue = IssuedCard.TypeEnum.ToJsonValue(issuedCard._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (issuedCard._ValidationFactsOption.IsSet) + { + writer.WritePropertyName("validationFacts"); + JsonSerializer.Serialize(writer, issuedCard.ValidationFacts, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/PaymentInstrument.cs b/Adyen/TransactionWebhooks/Models/PaymentInstrument.cs new file mode 100644 index 000000000..0b5d82687 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/PaymentInstrument.cs @@ -0,0 +1,252 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// PaymentInstrument. + /// + public partial class PaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + /// The type of wallet that the network token is associated with. + [JsonConstructor] + public PaymentInstrument(Option description = default, Option id = default, Option reference = default, Option tokenType = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + _TokenTypeOption = tokenType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenTypeOption { get; private set; } + + /// + /// The type of wallet that the network token is associated with. + /// + /// The type of wallet that the network token is associated with. + [JsonPropertyName("tokenType")] + public string? TokenType { get { return this._TokenTypeOption; } set { this._TokenTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrument {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TokenType: ").Append(TokenType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + Option tokenType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenType": + tokenType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentInstrument(description, id, reference, tokenType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrument._DescriptionOption.IsSet) + if (paymentInstrument.Description != null) + writer.WriteString("description", paymentInstrument.Description); + + if (paymentInstrument._IdOption.IsSet) + if (paymentInstrument.Id != null) + writer.WriteString("id", paymentInstrument.Id); + + if (paymentInstrument._ReferenceOption.IsSet) + if (paymentInstrument.Reference != null) + writer.WriteString("reference", paymentInstrument.Reference); + + if (paymentInstrument._TokenTypeOption.IsSet) + if (paymentInstrument.TokenType != null) + writer.WriteString("tokenType", paymentInstrument.TokenType); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/PlatformPayment.cs b/Adyen/TransactionWebhooks/Models/PlatformPayment.cs new file mode 100644 index 000000000..6007d1e25 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/PlatformPayment.cs @@ -0,0 +1,640 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// PlatformPayment. + /// + public partial class PlatformPayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// The payment's merchant reference included in the transfer. + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// The payment reference included in the transfer. + /// **platformPayment** (default to TypeEnum.PlatformPayment) + [JsonConstructor] + public PlatformPayment(Option modificationMerchantReference = default, Option modificationPspReference = default, Option paymentMerchantReference = default, Option platformPaymentType = default, Option pspPaymentReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _PaymentMerchantReferenceOption = paymentMerchantReference; + _PlatformPaymentTypeOption = platformPaymentType; + _PspPaymentReferenceOption = pspPaymentReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformPayment() + { + } + + partial void OnCreated(); + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonConverter(typeof(PlatformPaymentTypeEnumJsonConverter))] + public class PlatformPaymentTypeEnum : IEnum + { + /// + /// Returns the value of the PlatformPaymentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PlatformPaymentTypeEnum.AcquiringFees - AcquiringFees + /// + public static readonly PlatformPaymentTypeEnum AcquiringFees = new("AcquiringFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenCommission - AdyenCommission + /// + public static readonly PlatformPaymentTypeEnum AdyenCommission = new("AdyenCommission"); + + /// + /// PlatformPaymentTypeEnum.AdyenFees - AdyenFees + /// + public static readonly PlatformPaymentTypeEnum AdyenFees = new("AdyenFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenMarkup - AdyenMarkup + /// + public static readonly PlatformPaymentTypeEnum AdyenMarkup = new("AdyenMarkup"); + + /// + /// PlatformPaymentTypeEnum.BalanceAccount - BalanceAccount + /// + public static readonly PlatformPaymentTypeEnum BalanceAccount = new("BalanceAccount"); + + /// + /// PlatformPaymentTypeEnum.ChargebackRemainder - ChargebackRemainder + /// + public static readonly PlatformPaymentTypeEnum ChargebackRemainder = new("ChargebackRemainder"); + + /// + /// PlatformPaymentTypeEnum.Commission - Commission + /// + public static readonly PlatformPaymentTypeEnum Commission = new("Commission"); + + /// + /// PlatformPaymentTypeEnum.DCCPlatformCommission - DCCPlatformCommission + /// + public static readonly PlatformPaymentTypeEnum DCCPlatformCommission = new("DCCPlatformCommission"); + + /// + /// PlatformPaymentTypeEnum.Default - Default + /// + public static readonly PlatformPaymentTypeEnum Default = new("Default"); + + /// + /// PlatformPaymentTypeEnum.Interchange - Interchange + /// + public static readonly PlatformPaymentTypeEnum Interchange = new("Interchange"); + + /// + /// PlatformPaymentTypeEnum.PaymentFee - PaymentFee + /// + public static readonly PlatformPaymentTypeEnum PaymentFee = new("PaymentFee"); + + /// + /// PlatformPaymentTypeEnum.Remainder - Remainder + /// + public static readonly PlatformPaymentTypeEnum Remainder = new("Remainder"); + + /// + /// PlatformPaymentTypeEnum.SchemeFee - SchemeFee + /// + public static readonly PlatformPaymentTypeEnum SchemeFee = new("SchemeFee"); + + /// + /// PlatformPaymentTypeEnum.Surcharge - Surcharge + /// + public static readonly PlatformPaymentTypeEnum Surcharge = new("Surcharge"); + + /// + /// PlatformPaymentTypeEnum.Tip - Tip + /// + public static readonly PlatformPaymentTypeEnum Tip = new("Tip"); + + /// + /// PlatformPaymentTypeEnum.TopUp - TopUp + /// + public static readonly PlatformPaymentTypeEnum TopUp = new("TopUp"); + + /// + /// PlatformPaymentTypeEnum.VAT - VAT + /// + public static readonly PlatformPaymentTypeEnum VAT = new("VAT"); + + private PlatformPaymentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlatformPaymentTypeEnum?(string? value) => value == null ? null : new PlatformPaymentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlatformPaymentTypeEnum? option) => option?.Value; + + public static bool operator ==(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlatformPaymentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlatformPaymentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "AcquiringFees" => PlatformPaymentTypeEnum.AcquiringFees, + "AdyenCommission" => PlatformPaymentTypeEnum.AdyenCommission, + "AdyenFees" => PlatformPaymentTypeEnum.AdyenFees, + "AdyenMarkup" => PlatformPaymentTypeEnum.AdyenMarkup, + "BalanceAccount" => PlatformPaymentTypeEnum.BalanceAccount, + "ChargebackRemainder" => PlatformPaymentTypeEnum.ChargebackRemainder, + "Commission" => PlatformPaymentTypeEnum.Commission, + "DCCPlatformCommission" => PlatformPaymentTypeEnum.DCCPlatformCommission, + "Default" => PlatformPaymentTypeEnum.Default, + "Interchange" => PlatformPaymentTypeEnum.Interchange, + "PaymentFee" => PlatformPaymentTypeEnum.PaymentFee, + "Remainder" => PlatformPaymentTypeEnum.Remainder, + "SchemeFee" => PlatformPaymentTypeEnum.SchemeFee, + "Surcharge" => PlatformPaymentTypeEnum.Surcharge, + "Tip" => PlatformPaymentTypeEnum.Tip, + "TopUp" => PlatformPaymentTypeEnum.TopUp, + "VAT" => PlatformPaymentTypeEnum.VAT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlatformPaymentTypeEnum? value) + { + if (value == null) + return null; + + if (value == PlatformPaymentTypeEnum.AcquiringFees) + return "AcquiringFees"; + + if (value == PlatformPaymentTypeEnum.AdyenCommission) + return "AdyenCommission"; + + if (value == PlatformPaymentTypeEnum.AdyenFees) + return "AdyenFees"; + + if (value == PlatformPaymentTypeEnum.AdyenMarkup) + return "AdyenMarkup"; + + if (value == PlatformPaymentTypeEnum.BalanceAccount) + return "BalanceAccount"; + + if (value == PlatformPaymentTypeEnum.ChargebackRemainder) + return "ChargebackRemainder"; + + if (value == PlatformPaymentTypeEnum.Commission) + return "Commission"; + + if (value == PlatformPaymentTypeEnum.DCCPlatformCommission) + return "DCCPlatformCommission"; + + if (value == PlatformPaymentTypeEnum.Default) + return "Default"; + + if (value == PlatformPaymentTypeEnum.Interchange) + return "Interchange"; + + if (value == PlatformPaymentTypeEnum.PaymentFee) + return "PaymentFee"; + + if (value == PlatformPaymentTypeEnum.Remainder) + return "Remainder"; + + if (value == PlatformPaymentTypeEnum.SchemeFee) + return "SchemeFee"; + + if (value == PlatformPaymentTypeEnum.Surcharge) + return "Surcharge"; + + if (value == PlatformPaymentTypeEnum.Tip) + return "Tip"; + + if (value == PlatformPaymentTypeEnum.TopUp) + return "TopUp"; + + if (value == PlatformPaymentTypeEnum.VAT) + return "VAT"; + + return null; + } + + /// + /// JsonConverter for writing PlatformPaymentTypeEnum. + /// + public class PlatformPaymentTypeEnumJsonConverter : JsonConverter + { + public override PlatformPaymentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlatformPaymentTypeEnum.FromStringOrDefault(value) ?? new PlatformPaymentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlatformPaymentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlatformPaymentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentTypeOption { get; private set; } + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonPropertyName("platformPaymentType")] + public PlatformPaymentTypeEnum? PlatformPaymentType { get { return this._PlatformPaymentTypeOption; } set { this._PlatformPaymentTypeOption = new(value); } } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlatformPayment - platformPayment + /// + public static readonly TypeEnum PlatformPayment = new("platformPayment"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "platformPayment" => TypeEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMerchantReferenceOption { get; private set; } + + /// + /// The payment's merchant reference included in the transfer. + /// + /// The payment's merchant reference included in the transfer. + [JsonPropertyName("paymentMerchantReference")] + public string? PaymentMerchantReference { get { return this._PaymentMerchantReferenceOption; } set { this._PaymentMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspPaymentReferenceOption { get; private set; } + + /// + /// The payment reference included in the transfer. + /// + /// The payment reference included in the transfer. + [JsonPropertyName("pspPaymentReference")] + public string? PspPaymentReference { get { return this._PspPaymentReferenceOption; } set { this._PspPaymentReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformPayment {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" PaymentMerchantReference: ").Append(PaymentMerchantReference).Append("\n"); + sb.Append(" PlatformPaymentType: ").Append(PlatformPaymentType).Append("\n"); + sb.Append(" PspPaymentReference: ").Append(PspPaymentReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformPaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformPayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option paymentMerchantReference = default; + Option platformPaymentType = default; + Option pspPaymentReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMerchantReference": + paymentMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentType": + string? platformPaymentTypeRawValue = utf8JsonReader.GetString(); + platformPaymentType = new Option(PlatformPayment.PlatformPaymentTypeEnum.FromStringOrDefault(platformPaymentTypeRawValue)); + break; + case "pspPaymentReference": + pspPaymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PlatformPayment.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PlatformPayment(modificationMerchantReference, modificationPspReference, paymentMerchantReference, platformPaymentType, pspPaymentReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformPayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformPayment._ModificationMerchantReferenceOption.IsSet) + if (platformPayment.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", platformPayment.ModificationMerchantReference); + + if (platformPayment._ModificationPspReferenceOption.IsSet) + if (platformPayment.ModificationPspReference != null) + writer.WriteString("modificationPspReference", platformPayment.ModificationPspReference); + + if (platformPayment._PaymentMerchantReferenceOption.IsSet) + if (platformPayment.PaymentMerchantReference != null) + writer.WriteString("paymentMerchantReference", platformPayment.PaymentMerchantReference); + + if (platformPayment._PlatformPaymentTypeOption.IsSet && platformPayment.PlatformPaymentType != null) + { + string? platformPaymentTypeRawValue = PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPayment._PlatformPaymentTypeOption.Value!.Value); + writer.WriteString("platformPaymentType", platformPaymentTypeRawValue); + } + + if (platformPayment._PspPaymentReferenceOption.IsSet) + if (platformPayment.PspPaymentReference != null) + writer.WriteString("pspPaymentReference", platformPayment.PspPaymentReference); + + if (platformPayment._TypeOption.IsSet && platformPayment.Type != null) + { + string? typeRawValue = PlatformPayment.TypeEnum.ToJsonValue(platformPayment._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/RelayedAuthorisationData.cs b/Adyen/TransactionWebhooks/Models/RelayedAuthorisationData.cs new file mode 100644 index 000000000..6e6ec653e --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/RelayedAuthorisationData.cs @@ -0,0 +1,203 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// RelayedAuthorisationData. + /// + public partial class RelayedAuthorisationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// Your reference for the relayed authorisation data. + [JsonConstructor] + public RelayedAuthorisationData(Option?> metadata = default, Option reference = default) + { + _MetadataOption = metadata; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RelayedAuthorisationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the relayed authorisation data. + /// + /// Your reference for the relayed authorisation data. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RelayedAuthorisationData {\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RelayedAuthorisationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RelayedAuthorisationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> metadata = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RelayedAuthorisationData(metadata, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, relayedAuthorisationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (relayedAuthorisationData._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, relayedAuthorisationData.Metadata, jsonSerializerOptions); + } + if (relayedAuthorisationData._ReferenceOption.IsSet) + if (relayedAuthorisationData.Reference != null) + writer.WriteString("reference", relayedAuthorisationData.Reference); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/Resource.cs b/Adyen/TransactionWebhooks/Models/Resource.cs new file mode 100644 index 000000000..e0a0af6e9 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/ResourceReference.cs b/Adyen/TransactionWebhooks/Models/ResourceReference.cs new file mode 100644 index 000000000..461d27dc4 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/ThreeDSecure.cs b/Adyen/TransactionWebhooks/Models/ThreeDSecure.cs new file mode 100644 index 000000000..4d9089820 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/ThreeDSecure.cs @@ -0,0 +1,177 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// ThreeDSecure. + /// + public partial class ThreeDSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction identifier for the Access Control Server + [JsonConstructor] + public ThreeDSecure(Option acsTransactionId = default) + { + _AcsTransactionIdOption = acsTransactionId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsTransactionIdOption { get; private set; } + + /// + /// The transaction identifier for the Access Control Server + /// + /// The transaction identifier for the Access Control Server + [JsonPropertyName("acsTransactionId")] + public string? AcsTransactionId { get { return this._AcsTransactionIdOption; } set { this._AcsTransactionIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecure {\n"); + sb.Append(" AcsTransactionId: ").Append(AcsTransactionId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acsTransactionId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsTransactionId": + acsTransactionId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSecure(acsTransactionId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSecure._AcsTransactionIdOption.IsSet) + if (threeDSecure.AcsTransactionId != null) + writer.WriteString("acsTransactionId", threeDSecure.AcsTransactionId); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/Transaction.cs b/Adyen/TransactionWebhooks/Models/Transaction.cs new file mode 100644 index 000000000..11e010451 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/Transaction.cs @@ -0,0 +1,550 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// Transaction. + /// + public partial class Transaction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// amount + /// balanceAccount + /// The unique identifier of the balance platform. + /// The date the transaction was booked into the balance account. + /// The unique identifier of the transaction. + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// The date the transfer amount becomes available in the balance account. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The `description` from the `/transfers` request. + /// paymentInstrument + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + /// transfer + [JsonConstructor] + public Transaction(ResourceReference accountHolder, Amount amount, ResourceReference balanceAccount, string balancePlatform, DateTimeOffset bookingDate, string id, StatusEnum status, DateTimeOffset valueDate, Option creationDate = default, Option description = default, Option paymentInstrument = default, Option referenceForBeneficiary = default, Option transfer = default) + { + AccountHolder = accountHolder; + Amount = amount; + BalanceAccount = balanceAccount; + BalancePlatform = balancePlatform; + BookingDate = bookingDate; + Id = id; + Status = status; + ValueDate = valueDate; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _PaymentInstrumentOption = paymentInstrument; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _TransferOption = transfer; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Transaction() + { + } + + partial void OnCreated(); + + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "booked" => StatusEnum.Booked, + "pending" => StatusEnum.Pending, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.Pending) + return "pending"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference AccountHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference BalanceAccount { get; set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string BalancePlatform { get; set; } + + /// + /// The date the transaction was booked into the balance account. + /// + /// The date the transaction was booked into the balance account. + [JsonPropertyName("bookingDate")] + public DateTimeOffset BookingDate { get; set; } + + /// + /// The unique identifier of the transaction. + /// + /// The unique identifier of the transaction. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The date the transfer amount becomes available in the balance account. + /// + /// The date the transfer amount becomes available in the balance account. + [JsonPropertyName("valueDate")] + public DateTimeOffset ValueDate { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The `description` from the `/transfers` request. + /// + /// The `description` from the `/transfers` request. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + /// + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transfer")] + public TransferView? Transfer { get { return this._TransferOption; } set { this._TransferOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Transaction {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" BookingDate: ").Append(BookingDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" ValueDate: ").Append(ValueDate).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Transfer: ").Append(Transfer).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionJsonConverter : JsonConverter + { + /// + /// The format to use to serialize BookingDate. + /// + public static string BookingDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValueDate. + /// + public static string ValueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Transaction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option amount = default; + Option balanceAccount = default; + Option balancePlatform = default; + Option bookingDate = default; + Option id = default; + Option status = default; + Option valueDate = default; + Option creationDate = default; + Option description = default; + Option paymentInstrument = default; + Option referenceForBeneficiary = default; + Option transfer = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "bookingDate": + bookingDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Transaction.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "valueDate": + valueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "transfer": + transfer = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountHolder.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(accountHolder)); + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(amount)); + + if (!balanceAccount.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(balanceAccount)); + + if (!balancePlatform.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(balancePlatform)); + + if (!bookingDate.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(bookingDate)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(status)); + + if (!valueDate.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(valueDate)); + + return new Transaction(accountHolder.Value!, amount.Value!, balanceAccount.Value!, balancePlatform.Value!, bookingDate.Value!.Value!, id.Value!, status.Value!.Value!, valueDate.Value!.Value!, creationDate, description, paymentInstrument, referenceForBeneficiary, transfer); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Transaction transaction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transaction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Transaction transaction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, transaction.AccountHolder, jsonSerializerOptions); + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transaction.Amount, jsonSerializerOptions); + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, transaction.BalanceAccount, jsonSerializerOptions); + if (transaction.BalancePlatform != null) + writer.WriteString("balancePlatform", transaction.BalancePlatform); + + writer.WriteString("bookingDate", transaction.BookingDate.ToString(BookingDateFormat)); + + if (transaction.Id != null) + writer.WriteString("id", transaction.Id); + + if (transaction.Status != null) + { + string? statusRawValue = Transaction.StatusEnum.ToJsonValue(transaction.Status); + writer.WriteString("status", statusRawValue); + } + + writer.WriteString("valueDate", transaction.ValueDate.ToString(ValueDateFormat)); + + if (transaction._CreationDateOption.IsSet) + writer.WriteString("creationDate", transaction._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (transaction._DescriptionOption.IsSet) + if (transaction.Description != null) + writer.WriteString("description", transaction.Description); + + if (transaction._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, transaction.PaymentInstrument, jsonSerializerOptions); + } + if (transaction._ReferenceForBeneficiaryOption.IsSet) + if (transaction.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transaction.ReferenceForBeneficiary); + + if (transaction._TransferOption.IsSet) + { + writer.WritePropertyName("transfer"); + JsonSerializer.Serialize(writer, transaction.Transfer, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/TransactionNotificationRequestV4.cs b/Adyen/TransactionWebhooks/Models/TransactionNotificationRequestV4.cs new file mode 100644 index 000000000..94508b7ae --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/TransactionNotificationRequestV4.cs @@ -0,0 +1,340 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// TransactionNotificationRequestV4. + /// + public partial class TransactionNotificationRequestV4 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// When the event was queued. + /// Type of the webhook. + [JsonConstructor] + public TransactionNotificationRequestV4(Transaction data, string environment, Option timestamp = default, Option type = default) + { + Data = data; + Environment = environment; + _TimestampOption = timestamp; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionNotificationRequestV4() + { + } + + partial void OnCreated(); + + /// + /// Type of the webhook. + /// + /// Type of the webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformTransactionCreated - balancePlatform.transaction.created + /// + public static readonly TypeEnum BalancePlatformTransactionCreated = new("balancePlatform.transaction.created"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.transaction.created" => TypeEnum.BalancePlatformTransactionCreated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformTransactionCreated) + return "balancePlatform.transaction.created"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Type of the webhook. + /// + /// Type of the webhook. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("data")] + public Transaction Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionNotificationRequestV4 {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionNotificationRequestV4JsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionNotificationRequestV4 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option timestamp = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransactionNotificationRequestV4.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TransactionNotificationRequestV4.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TransactionNotificationRequestV4.", nameof(environment)); + + return new TransactionNotificationRequestV4(data.Value!, environment.Value!, timestamp, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionNotificationRequestV4 transactionNotificationRequestV4, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionNotificationRequestV4, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionNotificationRequestV4 transactionNotificationRequestV4, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, transactionNotificationRequestV4.Data, jsonSerializerOptions); + if (transactionNotificationRequestV4.Environment != null) + writer.WriteString("environment", transactionNotificationRequestV4.Environment); + + if (transactionNotificationRequestV4._TimestampOption.IsSet) + writer.WriteString("timestamp", transactionNotificationRequestV4._TimestampOption.Value!.Value.ToString(TimestampFormat)); + + if (transactionNotificationRequestV4._TypeOption.IsSet && transactionNotificationRequestV4.Type != null) + { + string? typeRawValue = TransactionNotificationRequestV4.TypeEnum.ToJsonValue(transactionNotificationRequestV4._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/TransferNotificationValidationFact.cs b/Adyen/TransactionWebhooks/Models/TransferNotificationValidationFact.cs new file mode 100644 index 000000000..f552e271d --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/TransferNotificationValidationFact.cs @@ -0,0 +1,202 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// TransferNotificationValidationFact. + /// + public partial class TransferNotificationValidationFact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The evaluation result of the validation fact. + /// The type of the validation fact. + [JsonConstructor] + public TransferNotificationValidationFact(Option result = default, Option type = default) + { + _ResultOption = result; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationValidationFact() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The evaluation result of the validation fact. + /// + /// The evaluation result of the validation fact. + [JsonPropertyName("result")] + public string? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the validation fact. + /// + /// The type of the validation fact. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationValidationFact {\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationValidationFactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationValidationFact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option result = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationValidationFact(result, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationValidationFact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationValidationFact._ResultOption.IsSet) + if (transferNotificationValidationFact.Result != null) + writer.WriteString("result", transferNotificationValidationFact.Result); + + if (transferNotificationValidationFact._TypeOption.IsSet) + if (transferNotificationValidationFact.Type != null) + writer.WriteString("type", transferNotificationValidationFact.Type); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/TransferView.cs b/Adyen/TransactionWebhooks/Models/TransferView.cs new file mode 100644 index 000000000..6da1be417 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/TransferView.cs @@ -0,0 +1,221 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// TransferView. + /// + public partial class TransferView : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + /// categoryData + /// The ID of the resource. + [JsonConstructor] + public TransferView(string reference, Option categoryData = default, Option id = default) + { + Reference = reference; + _CategoryDataOption = categoryData; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferView() + { + } + + partial void OnCreated(); + + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("categoryData")] + public TransferViewCategoryData? CategoryData { get { return this._CategoryDataOption; } set { this._CategoryDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferView {\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" CategoryData: ").Append(CategoryData).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferViewJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferView Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reference = default; + Option categoryData = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "categoryData": + categoryData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class TransferView.", nameof(reference)); + + return new TransferView(reference.Value!, categoryData, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferView transferView, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferView, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferView transferView, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferView.Reference != null) + writer.WriteString("reference", transferView.Reference); + + if (transferView._CategoryDataOption.IsSet) + { + writer.WritePropertyName("categoryData"); + JsonSerializer.Serialize(writer, transferView.CategoryData, jsonSerializerOptions); + } + if (transferView._IdOption.IsSet) + if (transferView.Id != null) + writer.WriteString("id", transferView.Id); + } + } +} diff --git a/Adyen/TransactionWebhooks/Models/TransferViewCategoryData.cs b/Adyen/TransactionWebhooks/Models/TransferViewCategoryData.cs new file mode 100644 index 000000000..68c50cb33 --- /dev/null +++ b/Adyen/TransactionWebhooks/Models/TransferViewCategoryData.cs @@ -0,0 +1,253 @@ +// +/* + * Transaction webhooks + * + * After a transfer is booked in a balance account, Adyen sends webhooks with information about the transaction. You can use the data from these webhooks to, for example: - Update balances in your dashboards. - Keep track of incoming and outgoing funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransactionWebhooks.Client; + +namespace Adyen.TransactionWebhooks.Models +{ + /// + /// The relevant data according to the transfer category.. + /// + public partial class TransferViewCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferViewCategoryData(BankCategoryData bankCategoryData) + { + BankCategoryData = bankCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferViewCategoryData(InternalCategoryData internalCategoryData) + { + InternalCategoryData = internalCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferViewCategoryData(IssuedCard issuedCard) + { + IssuedCard = issuedCard; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferViewCategoryData(PlatformPayment platformPayment) + { + PlatformPayment = platformPayment; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public BankCategoryData? BankCategoryData { get; set; } + + /// + /// .. + /// + public InternalCategoryData? InternalCategoryData { get; set; } + + /// + /// .. + /// + public IssuedCard? IssuedCard { get; set; } + + /// + /// .. + /// + public PlatformPayment? PlatformPayment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferViewCategoryData {\n"); + if (this.BankCategoryData != null) + sb.Append(BankCategoryData.ToString().Replace("\n", "\n ")); + if (this.InternalCategoryData != null) + sb.Append(InternalCategoryData.ToString().Replace("\n", "\n ")); + if (this.IssuedCard != null) + sb.Append(IssuedCard.ToString().Replace("\n", "\n ")); + if (this.PlatformPayment != null) + sb.Append(PlatformPayment.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferViewCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferViewCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + BankCategoryData? bankCategoryData = default; + InternalCategoryData? internalCategoryData = default; + IssuedCard? issuedCard = default; + PlatformPayment? platformPayment = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderBankCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBankCategoryData, jsonSerializerOptions, out bankCategoryData); + + Utf8JsonReader utf8JsonReaderInternalCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalCategoryData, jsonSerializerOptions, out internalCategoryData); + + Utf8JsonReader utf8JsonReaderIssuedCard = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIssuedCard, jsonSerializerOptions, out issuedCard); + + Utf8JsonReader utf8JsonReaderPlatformPayment = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPlatformPayment, jsonSerializerOptions, out platformPayment); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (bankCategoryData?.Type != null) + return new TransferViewCategoryData(bankCategoryData); + + if (internalCategoryData?.Type != null) + return new TransferViewCategoryData(internalCategoryData); + + if (issuedCard?.Type != null) + return new TransferViewCategoryData(issuedCard); + + if (platformPayment?.Type != null) + return new TransferViewCategoryData(platformPayment); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferViewCategoryData transferViewCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + if (transferViewCategoryData.BankCategoryData != null) + JsonSerializer.Serialize(writer, transferViewCategoryData.BankCategoryData, jsonSerializerOptions); + if (transferViewCategoryData.InternalCategoryData != null) + JsonSerializer.Serialize(writer, transferViewCategoryData.InternalCategoryData, jsonSerializerOptions); + if (transferViewCategoryData.IssuedCard != null) + JsonSerializer.Serialize(writer, transferViewCategoryData.IssuedCard, jsonSerializerOptions); + if (transferViewCategoryData.PlatformPayment != null) + JsonSerializer.Serialize(writer, transferViewCategoryData.PlatformPayment, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferViewCategoryData, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferViewCategoryData transferViewCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Client/ClientUtils.cs b/Adyen/TransferWebhooks/Client/ClientUtils.cs new file mode 100644 index 000000000..89d052e82 --- /dev/null +++ b/Adyen/TransferWebhooks/Client/ClientUtils.cs @@ -0,0 +1,383 @@ +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.TransferWebhooks.Models; +using Models = Adyen.TransferWebhooks.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.TransferWebhooks.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AULocalAccountIdentification.TypeEnum aULocalAccountIdentificationTypeEnum) + return Models.AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentificationTypeEnum); + if (obj is Models.AdditionalBankIdentification.TypeEnum additionalBankIdentificationTypeEnum) + return Models.AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentificationTypeEnum); + if (obj is Models.AmountAdjustment.AmountAdjustmentTypeEnum amountAdjustmentAmountAdjustmentTypeEnum) + return Models.AmountAdjustment.AmountAdjustmentTypeEnum.ToJsonValue(amountAdjustmentAmountAdjustmentTypeEnum); + if (obj is Models.BRLocalAccountIdentification.TypeEnum bRLocalAccountIdentificationTypeEnum) + return Models.BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentificationTypeEnum); + if (obj is Models.BankCategoryData.PriorityEnum bankCategoryDataPriorityEnum) + return Models.BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryDataPriorityEnum); + if (obj is Models.BankCategoryData.TypeEnum bankCategoryDataTypeEnum) + return Models.BankCategoryData.TypeEnum.ToJsonValue(bankCategoryDataTypeEnum); + if (obj is Models.CALocalAccountIdentification.AccountTypeEnum cALocalAccountIdentificationAccountTypeEnum) + return Models.CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentificationAccountTypeEnum); + if (obj is Models.CALocalAccountIdentification.TypeEnum cALocalAccountIdentificationTypeEnum) + return Models.CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentificationTypeEnum); + if (obj is Models.CZLocalAccountIdentification.TypeEnum cZLocalAccountIdentificationTypeEnum) + return Models.CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentificationTypeEnum); + if (obj is Models.ConfirmationTrackingData.StatusEnum confirmationTrackingDataStatusEnum) + return Models.ConfirmationTrackingData.StatusEnum.ToJsonValue(confirmationTrackingDataStatusEnum); + if (obj is Models.ConfirmationTrackingData.TypeEnum confirmationTrackingDataTypeEnum) + return Models.ConfirmationTrackingData.TypeEnum.ToJsonValue(confirmationTrackingDataTypeEnum); + if (obj is Models.DKLocalAccountIdentification.TypeEnum dKLocalAccountIdentificationTypeEnum) + return Models.DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentificationTypeEnum); + if (obj is Models.EstimationTrackingData.TypeEnum estimationTrackingDataTypeEnum) + return Models.EstimationTrackingData.TypeEnum.ToJsonValue(estimationTrackingDataTypeEnum); + if (obj is Models.HKLocalAccountIdentification.TypeEnum hKLocalAccountIdentificationTypeEnum) + return Models.HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentificationTypeEnum); + if (obj is Models.HULocalAccountIdentification.TypeEnum hULocalAccountIdentificationTypeEnum) + return Models.HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentificationTypeEnum); + if (obj is Models.IbanAccountIdentification.TypeEnum ibanAccountIdentificationTypeEnum) + return Models.IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentificationTypeEnum); + if (obj is Models.InternalCategoryData.TypeEnum internalCategoryDataTypeEnum) + return Models.InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryDataTypeEnum); + if (obj is Models.InternalReviewTrackingData.StatusEnum internalReviewTrackingDataStatusEnum) + return Models.InternalReviewTrackingData.StatusEnum.ToJsonValue(internalReviewTrackingDataStatusEnum); + if (obj is Models.InternalReviewTrackingData.ReasonEnum internalReviewTrackingDataReasonEnum) + return Models.InternalReviewTrackingData.ReasonEnum.ToJsonValue(internalReviewTrackingDataReasonEnum); + if (obj is Models.InternalReviewTrackingData.TypeEnum internalReviewTrackingDataTypeEnum) + return Models.InternalReviewTrackingData.TypeEnum.ToJsonValue(internalReviewTrackingDataTypeEnum); + if (obj is Models.IssuedCard.PanEntryModeEnum issuedCardPanEntryModeEnum) + return Models.IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCardPanEntryModeEnum); + if (obj is Models.IssuedCard.ProcessingTypeEnum issuedCardProcessingTypeEnum) + return Models.IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCardProcessingTypeEnum); + if (obj is Models.IssuedCard.TypeEnum issuedCardTypeEnum) + return Models.IssuedCard.TypeEnum.ToJsonValue(issuedCardTypeEnum); + if (obj is Models.IssuingTransactionData.TypeEnum issuingTransactionDataTypeEnum) + return Models.IssuingTransactionData.TypeEnum.ToJsonValue(issuingTransactionDataTypeEnum); + if (obj is Models.MerchantPurchaseData.TypeEnum merchantPurchaseDataTypeEnum) + return Models.MerchantPurchaseData.TypeEnum.ToJsonValue(merchantPurchaseDataTypeEnum); + if (obj is Models.Modification.StatusEnum modificationStatusEnum) + return Models.Modification.StatusEnum.ToJsonValue(modificationStatusEnum); + if (obj is Models.NOLocalAccountIdentification.TypeEnum nOLocalAccountIdentificationTypeEnum) + return Models.NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentificationTypeEnum); + if (obj is Models.NZLocalAccountIdentification.TypeEnum nZLocalAccountIdentificationTypeEnum) + return Models.NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentificationTypeEnum); + if (obj is Models.NumberAndBicAccountIdentification.TypeEnum numberAndBicAccountIdentificationTypeEnum) + return Models.NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentificationTypeEnum); + if (obj is Models.PLLocalAccountIdentification.TypeEnum pLLocalAccountIdentificationTypeEnum) + return Models.PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentificationTypeEnum); + if (obj is Models.PartyIdentification.TypeEnum partyIdentificationTypeEnum) + return Models.PartyIdentification.TypeEnum.ToJsonValue(partyIdentificationTypeEnum); + if (obj is Models.PlatformPayment.PlatformPaymentTypeEnum platformPaymentPlatformPaymentTypeEnum) + return Models.PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPaymentPlatformPaymentTypeEnum); + if (obj is Models.PlatformPayment.TypeEnum platformPaymentTypeEnum) + return Models.PlatformPayment.TypeEnum.ToJsonValue(platformPaymentTypeEnum); + if (obj is Models.SELocalAccountIdentification.TypeEnum sELocalAccountIdentificationTypeEnum) + return Models.SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentificationTypeEnum); + if (obj is Models.SGLocalAccountIdentification.TypeEnum sGLocalAccountIdentificationTypeEnum) + return Models.SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentificationTypeEnum); + if (obj is Models.TransferData.CategoryEnum transferDataCategoryEnum) + return Models.TransferData.CategoryEnum.ToJsonValue(transferDataCategoryEnum); + if (obj is Models.TransferData.StatusEnum transferDataStatusEnum) + return Models.TransferData.StatusEnum.ToJsonValue(transferDataStatusEnum); + if (obj is Models.TransferData.DirectionEnum transferDataDirectionEnum) + return Models.TransferData.DirectionEnum.ToJsonValue(transferDataDirectionEnum); + if (obj is Models.TransferData.ReasonEnum transferDataReasonEnum) + return Models.TransferData.ReasonEnum.ToJsonValue(transferDataReasonEnum); + if (obj is Models.TransferData.TypeEnum transferDataTypeEnum) + return Models.TransferData.TypeEnum.ToJsonValue(transferDataTypeEnum); + if (obj is Models.TransferEvent.ReasonEnum transferEventReasonEnum) + return Models.TransferEvent.ReasonEnum.ToJsonValue(transferEventReasonEnum); + if (obj is Models.TransferEvent.StatusEnum transferEventStatusEnum) + return Models.TransferEvent.StatusEnum.ToJsonValue(transferEventStatusEnum); + if (obj is Models.TransferEvent.TypeEnum transferEventTypeEnum) + return Models.TransferEvent.TypeEnum.ToJsonValue(transferEventTypeEnum); + if (obj is Models.TransferNotificationRequest.TypeEnum transferNotificationRequestTypeEnum) + return Models.TransferNotificationRequest.TypeEnum.ToJsonValue(transferNotificationRequestTypeEnum); + if (obj is Models.TransferReview.ScaOnApprovalEnum transferReviewScaOnApprovalEnum) + return Models.TransferReview.ScaOnApprovalEnum.ToJsonValue(transferReviewScaOnApprovalEnum); + if (obj is Models.UKLocalAccountIdentification.TypeEnum uKLocalAccountIdentificationTypeEnum) + return Models.UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentificationTypeEnum); + if (obj is Models.USLocalAccountIdentification.AccountTypeEnum uSLocalAccountIdentificationAccountTypeEnum) + return Models.USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentificationAccountTypeEnum); + if (obj is Models.USLocalAccountIdentification.TypeEnum uSLocalAccountIdentificationTypeEnum) + return Models.USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentificationTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + } +} diff --git a/Adyen/TransferWebhooks/Client/HmacKeyToken.cs b/Adyen/TransferWebhooks/Client/HmacKeyToken.cs new file mode 100644 index 000000000..e6a2d26e2 --- /dev/null +++ b/Adyen/TransferWebhooks/Client/HmacKeyToken.cs @@ -0,0 +1,34 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.TransferWebhooks.Client +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + public class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/Adyen/TransferWebhooks/Client/HostConfiguration.cs b/Adyen/TransferWebhooks/Client/HostConfiguration.cs new file mode 100644 index 000000000..e05703466 --- /dev/null +++ b/Adyen/TransferWebhooks/Client/HostConfiguration.cs @@ -0,0 +1,193 @@ +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +using Adyen.TransferWebhooks.Client; +using Adyen.TransferWebhooks.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.TransferWebhooks.Client +{ + /// + /// Provides hosting configuration for TransferWebhooks + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "http://localhost"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalBankIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AirlineJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AmountAdjustmentJsonConverter()); + _jsonOptions.Converters.Add(new BRLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BalanceMutationJsonConverter()); + _jsonOptions.Converters.Add(new BalancePlatformNotificationResponseJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountV3JsonConverter()); + _jsonOptions.Converters.Add(new BankAccountV3AccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BankCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new CALocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CardIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new ConfirmationTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyV3JsonConverter()); + _jsonOptions.Converters.Add(new DKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new DirectDebitInformationJsonConverter()); + _jsonOptions.Converters.Add(new EstimationTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new ExecutionDateJsonConverter()); + _jsonOptions.Converters.Add(new ExternalReasonJsonConverter()); + _jsonOptions.Converters.Add(new HKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new HULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new InternalCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new InternalReviewTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new IssuedCardJsonConverter()); + _jsonOptions.Converters.Add(new IssuingTransactionDataJsonConverter()); + _jsonOptions.Converters.Add(new LegJsonConverter()); + _jsonOptions.Converters.Add(new LodgingJsonConverter()); + _jsonOptions.Converters.Add(new MerchantDataJsonConverter()); + _jsonOptions.Converters.Add(new MerchantPurchaseDataJsonConverter()); + _jsonOptions.Converters.Add(new ModificationJsonConverter()); + _jsonOptions.Converters.Add(new NOLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NameLocationJsonConverter()); + _jsonOptions.Converters.Add(new NumberAndBicAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PLLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PartyIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new PlatformPaymentJsonConverter()); + _jsonOptions.Converters.Add(new RelayedAuthorisationDataJsonConverter()); + _jsonOptions.Converters.Add(new ResourceJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + _jsonOptions.Converters.Add(new SELocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new SGLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSecureJsonConverter()); + _jsonOptions.Converters.Add(new TransactionEventViolationJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleReferenceJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleSourceJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRulesResultJsonConverter()); + _jsonOptions.Converters.Add(new TransferDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferDataCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferDataTrackingJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventEventsDataInnerJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationCounterPartyJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationMerchantDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationRequestJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationValidationFactJsonConverter()); + _jsonOptions.Converters.Add(new TransferReviewJsonConverter()); + _jsonOptions.Converters.Add(new UKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new USLocalAccountIdentificationJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddTransferWebhooksHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + _services.AddSingleton(); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + return this; + } + } +} diff --git a/Adyen/TransferWebhooks/Client/JsonSerializerOptionsProvider.cs b/Adyen/TransferWebhooks/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..a096c3fc0 --- /dev/null +++ b/Adyen/TransferWebhooks/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.TransferWebhooks.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/TransferWebhooks/Extensions/HostBuilderExtensions.cs b/Adyen/TransferWebhooks/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..2fd28d2b8 --- /dev/null +++ b/Adyen/TransferWebhooks/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.TransferWebhooks; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the TransferWebhooks API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureTransferWebhooks(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddTransferWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/TransferWebhooks/Extensions/ServiceCollectionExtensions.cs b/Adyen/TransferWebhooks/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..4a14f3475 --- /dev/null +++ b/Adyen/TransferWebhooks/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen TransferWebhooks API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddTransferWebhooksServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddTransferWebhooksHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/TransferWebhooks/Handlers/TransferWebhooksHandler.cs b/Adyen/TransferWebhooks/Handlers/TransferWebhooksHandler.cs new file mode 100644 index 000000000..9817d2f19 --- /dev/null +++ b/Adyen/TransferWebhooks/Handlers/TransferWebhooksHandler.cs @@ -0,0 +1,82 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Adyen.Core.Auth; +using Adyen.TransferWebhooks.Client; +using Adyen.TransferWebhooks.Models; + +namespace Adyen.TransferWebhooks.Handlers +{ + /// + /// Interface for deserializing TransferWebhooks webhooks or verify its HMAC signature. + /// + public interface ITransferWebhooksHandler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + Adyen.TransferWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + TransferNotificationRequest? DeserializeTransferNotificationRequest(string json); + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize TransferWebhooks or verify the HMAC signature of the webhook. + /// + public partial class TransferWebhooksHandler : ITransferWebhooksHandler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public Adyen.TransferWebhooks.Client.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing TransferWebhooks or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public TransferWebhooksHandler(Adyen.TransferWebhooks.Client.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + /// + public TransferNotificationRequest? DeserializeTransferNotificationRequest(string json) + { + return JsonSerializer.Deserialize(json, JsonSerializerOptionsProvider.Options); + } + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return Adyen.Core.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/AULocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/AULocalAccountIdentification.cs new file mode 100644 index 000000000..def6a5c77 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/AULocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// AULocalAccountIdentification. + /// + public partial class AULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// **auLocal** (default to TypeEnum.AuLocal) + [JsonConstructor] + public AULocalAccountIdentification(string accountNumber, string bsbCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BsbCode = bsbCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuLocal - auLocal + /// + public static readonly TypeEnum AuLocal = new("auLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auLocal" => TypeEnum.AuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuLocal) + return "auLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + [JsonPropertyName("bsbCode")] + public string BsbCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BsbCode: ").Append(BsbCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 9.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // BsbCode (string) maxLength + if (this.BsbCode != null && this.BsbCode.Length > 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be less than 6.", new [] { "BsbCode" }); + } + + // BsbCode (string) minLength + if (this.BsbCode != null && this.BsbCode.Length < 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be greater than 6.", new [] { "BsbCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bsbCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bsbCode": + bsbCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(accountNumber)); + + if (!bsbCode.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(bsbCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(type)); + + return new AULocalAccountIdentification(accountNumber.Value!, bsbCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, aULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (aULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", aULocalAccountIdentification.AccountNumber); + + if (aULocalAccountIdentification.BsbCode != null) + writer.WriteString("bsbCode", aULocalAccountIdentification.BsbCode); + + if (aULocalAccountIdentification.Type != null) + { + string? typeRawValue = AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/AdditionalBankIdentification.cs b/Adyen/TransferWebhooks/Models/AdditionalBankIdentification.cs new file mode 100644 index 000000000..c60dfecbf --- /dev/null +++ b/Adyen/TransferWebhooks/Models/AdditionalBankIdentification.cs @@ -0,0 +1,326 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// AdditionalBankIdentification. + /// + public partial class AdditionalBankIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the additional bank identification. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConstructor] + public AdditionalBankIdentification(Option code = default, Option type = default) + { + _CodeOption = code; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalBankIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuBsbCode - auBsbCode + /// + public static readonly TypeEnum AuBsbCode = new("auBsbCode"); + + /// + /// TypeEnum.CaRoutingNumber - caRoutingNumber + /// + public static readonly TypeEnum CaRoutingNumber = new("caRoutingNumber"); + + /// + /// TypeEnum.GbSortCode - gbSortCode + /// + public static readonly TypeEnum GbSortCode = new("gbSortCode"); + + /// + /// TypeEnum.UsRoutingNumber - usRoutingNumber + /// + public static readonly TypeEnum UsRoutingNumber = new("usRoutingNumber"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auBsbCode" => TypeEnum.AuBsbCode, + "caRoutingNumber" => TypeEnum.CaRoutingNumber, + "gbSortCode" => TypeEnum.GbSortCode, + "usRoutingNumber" => TypeEnum.UsRoutingNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuBsbCode) + return "auBsbCode"; + + if (value == TypeEnum.CaRoutingNumber) + return "caRoutingNumber"; + + if (value == TypeEnum.GbSortCode) + return "gbSortCode"; + + if (value == TypeEnum.UsRoutingNumber) + return "usRoutingNumber"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The value of the additional bank identification. + /// + /// The value of the additional bank identification. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalBankIdentification {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalBankIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalBankIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AdditionalBankIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AdditionalBankIdentification(code, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalBankIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalBankIdentification._CodeOption.IsSet) + if (additionalBankIdentification.Code != null) + writer.WriteString("code", additionalBankIdentification.Code); + + if (additionalBankIdentification._TypeOption.IsSet && additionalBankIdentification.Type != null) + { + string? typeRawValue = AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Address.cs b/Adyen/TransferWebhooks/Models/Address.cs new file mode 100644 index 000000000..2f730ea9d --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Address.cs @@ -0,0 +1,308 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string country, Option city = default, Option line1 = default, Option line2 = default, Option postalCode = default, Option stateOrProvince = default) + { + Country = country; + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) minLength + if (this.City != null && this.City.Length < 3) + { + yield return new ValidationResult("Invalid value for City, length must be greater than 3.", new [] { "City" }); + } + + // PostalCode (string) minLength + if (this.PostalCode != null && this.PostalCode.Length < 3) + { + yield return new ValidationResult("Invalid value for PostalCode, length must be greater than 3.", new [] { "PostalCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option line1 = default; + Option line2 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + return new Address(country.Value!, city, line1, line2, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address._CityOption.IsSet) + if (address.City != null) + writer.WriteString("city", address.City); + + if (address._Line1Option.IsSet) + if (address.Line1 != null) + writer.WriteString("line1", address.Line1); + + if (address._Line2Option.IsSet) + if (address.Line2 != null) + writer.WriteString("line2", address.Line2); + + if (address._PostalCodeOption.IsSet) + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Airline.cs b/Adyen/TransferWebhooks/Models/Airline.cs new file mode 100644 index 000000000..4d09b8f0b --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Airline.cs @@ -0,0 +1,203 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Airline. + /// + public partial class Airline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Details about the flight legs for this ticket. + /// The ticket's unique identifier + [JsonConstructor] + public Airline(Option?> legs = default, Option ticketNumber = default) + { + _LegsOption = legs; + _TicketNumberOption = ticketNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Airline() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LegsOption { get; private set; } + + /// + /// Details about the flight legs for this ticket. + /// + /// Details about the flight legs for this ticket. + [JsonPropertyName("legs")] + public List? Legs { get { return this._LegsOption; } set { this._LegsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TicketNumberOption { get; private set; } + + /// + /// The ticket's unique identifier + /// + /// The ticket's unique identifier + [JsonPropertyName("ticketNumber")] + public string? TicketNumber { get { return this._TicketNumberOption; } set { this._TicketNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Airline {\n"); + sb.Append(" Legs: ").Append(Legs).Append("\n"); + sb.Append(" TicketNumber: ").Append(TicketNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AirlineJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Airline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> legs = default; + Option ticketNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legs": + legs = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ticketNumber": + ticketNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Airline(legs, ticketNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, airline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + if (airline._LegsOption.IsSet) + { + writer.WritePropertyName("legs"); + JsonSerializer.Serialize(writer, airline.Legs, jsonSerializerOptions); + } + if (airline._TicketNumberOption.IsSet) + if (airline.TicketNumber != null) + writer.WriteString("ticketNumber", airline.TicketNumber); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Amount.cs b/Adyen/TransferWebhooks/Models/Amount.cs new file mode 100644 index 000000000..084c6c51a --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/AmountAdjustment.cs b/Adyen/TransferWebhooks/Models/AmountAdjustment.cs new file mode 100644 index 000000000..192770fd2 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/AmountAdjustment.cs @@ -0,0 +1,350 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// AmountAdjustment. + /// + public partial class AmountAdjustment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// The basepoints associated with the applied markup. + [JsonConstructor] + public AmountAdjustment(Option amount = default, Option amountAdjustmentType = default, Option basepoints = default) + { + _AmountOption = amount; + _AmountAdjustmentTypeOption = amountAdjustmentType; + _BasepointsOption = basepoints; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmountAdjustment() + { + } + + partial void OnCreated(); + + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + [JsonConverter(typeof(AmountAdjustmentTypeEnumJsonConverter))] + public class AmountAdjustmentTypeEnum : IEnum + { + /// + /// Returns the value of the AmountAdjustmentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AmountAdjustmentTypeEnum.AtmMarkup - atmMarkup + /// + public static readonly AmountAdjustmentTypeEnum AtmMarkup = new("atmMarkup"); + + /// + /// AmountAdjustmentTypeEnum.AuthHoldReserve - authHoldReserve + /// + public static readonly AmountAdjustmentTypeEnum AuthHoldReserve = new("authHoldReserve"); + + /// + /// AmountAdjustmentTypeEnum.Exchange - exchange + /// + public static readonly AmountAdjustmentTypeEnum Exchange = new("exchange"); + + /// + /// AmountAdjustmentTypeEnum.ForexMarkup - forexMarkup + /// + public static readonly AmountAdjustmentTypeEnum ForexMarkup = new("forexMarkup"); + + private AmountAdjustmentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AmountAdjustmentTypeEnum?(string? value) => value == null ? null : new AmountAdjustmentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AmountAdjustmentTypeEnum? option) => option?.Value; + + public static bool operator ==(AmountAdjustmentTypeEnum? left, AmountAdjustmentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AmountAdjustmentTypeEnum? left, AmountAdjustmentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AmountAdjustmentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AmountAdjustmentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "atmMarkup" => AmountAdjustmentTypeEnum.AtmMarkup, + "authHoldReserve" => AmountAdjustmentTypeEnum.AuthHoldReserve, + "exchange" => AmountAdjustmentTypeEnum.Exchange, + "forexMarkup" => AmountAdjustmentTypeEnum.ForexMarkup, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AmountAdjustmentTypeEnum? value) + { + if (value == null) + return null; + + if (value == AmountAdjustmentTypeEnum.AtmMarkup) + return "atmMarkup"; + + if (value == AmountAdjustmentTypeEnum.AuthHoldReserve) + return "authHoldReserve"; + + if (value == AmountAdjustmentTypeEnum.Exchange) + return "exchange"; + + if (value == AmountAdjustmentTypeEnum.ForexMarkup) + return "forexMarkup"; + + return null; + } + + /// + /// JsonConverter for writing AmountAdjustmentTypeEnum. + /// + public class AmountAdjustmentTypeEnumJsonConverter : JsonConverter + { + public override AmountAdjustmentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AmountAdjustmentTypeEnum.FromStringOrDefault(value) ?? new AmountAdjustmentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AmountAdjustmentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AmountAdjustmentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountAdjustmentTypeOption { get; private set; } + + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + [JsonPropertyName("amountAdjustmentType")] + public AmountAdjustmentTypeEnum? AmountAdjustmentType { get { return this._AmountAdjustmentTypeOption; } set { this._AmountAdjustmentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BasepointsOption { get; private set; } + + /// + /// The basepoints associated with the applied markup. + /// + /// The basepoints associated with the applied markup. + [JsonPropertyName("basepoints")] + public int? Basepoints { get { return this._BasepointsOption; } set { this._BasepointsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmountAdjustment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" AmountAdjustmentType: ").Append(AmountAdjustmentType).Append("\n"); + sb.Append(" Basepoints: ").Append(Basepoints).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountAdjustmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmountAdjustment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option amountAdjustmentType = default; + Option basepoints = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amountAdjustmentType": + string? amountAdjustmentTypeRawValue = utf8JsonReader.GetString(); + amountAdjustmentType = new Option(AmountAdjustment.AmountAdjustmentTypeEnum.FromStringOrDefault(amountAdjustmentTypeRawValue)); + break; + case "basepoints": + basepoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new AmountAdjustment(amount, amountAdjustmentType, basepoints); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmountAdjustment amountAdjustment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amountAdjustment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmountAdjustment amountAdjustment, JsonSerializerOptions jsonSerializerOptions) + { + + if (amountAdjustment._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, amountAdjustment.Amount, jsonSerializerOptions); + } + if (amountAdjustment._AmountAdjustmentTypeOption.IsSet && amountAdjustment.AmountAdjustmentType != null) + { + string? amountAdjustmentTypeRawValue = AmountAdjustment.AmountAdjustmentTypeEnum.ToJsonValue(amountAdjustment._AmountAdjustmentTypeOption.Value!.Value); + writer.WriteString("amountAdjustmentType", amountAdjustmentTypeRawValue); + } + + if (amountAdjustment._BasepointsOption.IsSet) + writer.WriteNumber("basepoints", amountAdjustment._BasepointsOption.Value!.Value); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BRLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/BRLocalAccountIdentification.cs new file mode 100644 index 000000000..a9ebddc4c --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BRLocalAccountIdentification.cs @@ -0,0 +1,402 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// BRLocalAccountIdentification. + /// + public partial class BRLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 3-digit bank code, with leading zeros. + /// The bank account branch number, without separators or whitespace. + /// The 8-digit ISPB, with leading zeros. + /// **brLocal** (default to TypeEnum.BrLocal) + [JsonConstructor] + public BRLocalAccountIdentification(string accountNumber, string bankCode, string branchNumber, Option ispb = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + BranchNumber = branchNumber; + _IspbOption = ispb; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BRLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BrLocal - brLocal + /// + public static readonly TypeEnum BrLocal = new("brLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "brLocal" => TypeEnum.BrLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BrLocal) + return "brLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit bank code, with leading zeros. + /// + /// The 3-digit bank code, with leading zeros. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// The bank account branch number, without separators or whitespace. + /// + /// The bank account branch number, without separators or whitespace. + [JsonPropertyName("branchNumber")] + public string BranchNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IspbOption { get; private set; } + + /// + /// The 8-digit ISPB, with leading zeros. + /// + /// The 8-digit ISPB, with leading zeros. + [JsonPropertyName("ispb")] + public string? Ispb { get { return this._IspbOption; } set { this._IspbOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BRLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" BranchNumber: ").Append(BranchNumber).Append("\n"); + sb.Append(" Ispb: ").Append(Ispb).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 1.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 3.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 3.", new [] { "BankCode" }); + } + + // BranchNumber (string) maxLength + if (this.BranchNumber != null && this.BranchNumber.Length > 4) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be less than 4.", new [] { "BranchNumber" }); + } + + // BranchNumber (string) minLength + if (this.BranchNumber != null && this.BranchNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be greater than 1.", new [] { "BranchNumber" }); + } + + // Ispb (string) maxLength + if (this.Ispb != null && this.Ispb.Length > 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be less than 8.", new [] { "Ispb" }); + } + + // Ispb (string) minLength + if (this.Ispb != null && this.Ispb.Length < 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be greater than 8.", new [] { "Ispb" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BRLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BRLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option branchNumber = default; + Option ispb = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "branchNumber": + branchNumber = new Option(utf8JsonReader.GetString()!); + break; + case "ispb": + ispb = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BRLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(bankCode)); + + if (!branchNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(branchNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(type)); + + return new BRLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, branchNumber.Value!, ispb, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bRLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (bRLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", bRLocalAccountIdentification.AccountNumber); + + if (bRLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", bRLocalAccountIdentification.BankCode); + + if (bRLocalAccountIdentification.BranchNumber != null) + writer.WriteString("branchNumber", bRLocalAccountIdentification.BranchNumber); + + if (bRLocalAccountIdentification._IspbOption.IsSet) + if (bRLocalAccountIdentification.Ispb != null) + writer.WriteString("ispb", bRLocalAccountIdentification.Ispb); + + if (bRLocalAccountIdentification.Type != null) + { + string? typeRawValue = BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BalanceMutation.cs b/Adyen/TransferWebhooks/Models/BalanceMutation.cs new file mode 100644 index 000000000..3f27bb1b3 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BalanceMutation.cs @@ -0,0 +1,249 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// BalanceMutation. + /// + public partial class BalanceMutation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// The amount in the payment's currency that is debited or credited on the received accounting register. + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + [JsonConstructor] + public BalanceMutation(Option balance = default, Option currency = default, Option received = default, Option reserved = default) + { + _BalanceOption = balance; + _CurrencyOption = currency; + _ReceivedOption = received; + _ReservedOption = reserved; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceMutation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + [JsonPropertyName("balance")] + public long? Balance { get { return this._BalanceOption; } set { this._BalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceivedOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the received accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the received accounting register. + [JsonPropertyName("received")] + public long? Received { get { return this._ReceivedOption; } set { this._ReceivedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReservedOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + [JsonPropertyName("reserved")] + public long? Reserved { get { return this._ReservedOption; } set { this._ReservedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceMutation {\n"); + sb.Append(" Balance: ").Append(Balance).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Received: ").Append(Received).Append("\n"); + sb.Append(" Reserved: ").Append(Reserved).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceMutationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceMutation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balance = default; + Option currency = default; + Option received = default; + Option reserved = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balance": + balance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "received": + received = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "reserved": + reserved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new BalanceMutation(balance, currency, received, reserved); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceMutation balanceMutation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceMutation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceMutation balanceMutation, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceMutation._BalanceOption.IsSet) + writer.WriteNumber("balance", balanceMutation._BalanceOption.Value!.Value); + + if (balanceMutation._CurrencyOption.IsSet) + if (balanceMutation.Currency != null) + writer.WriteString("currency", balanceMutation.Currency); + + if (balanceMutation._ReceivedOption.IsSet) + writer.WriteNumber("received", balanceMutation._ReceivedOption.Value!.Value); + + if (balanceMutation._ReservedOption.IsSet) + writer.WriteNumber("reserved", balanceMutation._ReservedOption.Value!.Value); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BalancePlatformNotificationResponse.cs b/Adyen/TransferWebhooks/Models/BalancePlatformNotificationResponse.cs new file mode 100644 index 000000000..89d268849 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BalancePlatformNotificationResponse.cs @@ -0,0 +1,177 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// BalancePlatformNotificationResponse. + /// + public partial class BalancePlatformNotificationResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonConstructor] + public BalancePlatformNotificationResponse(Option notificationResponse = default) + { + _NotificationResponseOption = notificationResponse; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalancePlatformNotificationResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NotificationResponseOption { get; private set; } + + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + /// + /// Respond with any **2xx** HTTP status code to [accept the webhook](https://docs.adyen.com/development-resources/webhooks/#accept-webhooks). + [JsonPropertyName("notificationResponse")] + public string? NotificationResponse { get { return this._NotificationResponseOption; } set { this._NotificationResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalancePlatformNotificationResponse {\n"); + sb.Append(" NotificationResponse: ").Append(NotificationResponse).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalancePlatformNotificationResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalancePlatformNotificationResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option notificationResponse = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "notificationResponse": + notificationResponse = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new BalancePlatformNotificationResponse(notificationResponse); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balancePlatformNotificationResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalancePlatformNotificationResponse balancePlatformNotificationResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (balancePlatformNotificationResponse._NotificationResponseOption.IsSet) + if (balancePlatformNotificationResponse.NotificationResponse != null) + writer.WriteString("notificationResponse", balancePlatformNotificationResponse.NotificationResponse); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BankAccountV3.cs b/Adyen/TransferWebhooks/Models/BankAccountV3.cs new file mode 100644 index 000000000..0fc037633 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BankAccountV3.cs @@ -0,0 +1,188 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// BankAccountV3. + /// + public partial class BankAccountV3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// accountIdentification + [JsonConstructor] + public BankAccountV3(PartyIdentification accountHolder, BankAccountV3AccountIdentification accountIdentification) + { + AccountHolder = accountHolder; + AccountIdentification = accountIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountV3() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public PartyIdentification AccountHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("accountIdentification")] + public BankAccountV3AccountIdentification AccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountV3 {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" AccountIdentification: ").Append(AccountIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountV3JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountV3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option accountIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountIdentification": + accountIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountHolder.IsSet) + throw new ArgumentException("Property is required for class BankAccountV3.", nameof(accountHolder)); + + if (!accountIdentification.IsSet) + throw new ArgumentException("Property is required for class BankAccountV3.", nameof(accountIdentification)); + + return new BankAccountV3(accountHolder.Value!, accountIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountV3 bankAccountV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountV3, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountV3 bankAccountV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, bankAccountV3.AccountHolder, jsonSerializerOptions); + writer.WritePropertyName("accountIdentification"); + JsonSerializer.Serialize(writer, bankAccountV3.AccountIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BankAccountV3AccountIdentification.cs b/Adyen/TransferWebhooks/Models/BankAccountV3AccountIdentification.cs new file mode 100644 index 000000000..79f737e0f --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BankAccountV3AccountIdentification.cs @@ -0,0 +1,565 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Contains the bank account details. The fields required in this object depend on the country of the bank account and the currency of the transfer.. + /// + public partial class BankAccountV3AccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(AULocalAccountIdentification aULocalAccountIdentification) + { + AULocalAccountIdentification = aULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(BRLocalAccountIdentification bRLocalAccountIdentification) + { + BRLocalAccountIdentification = bRLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(CALocalAccountIdentification cALocalAccountIdentification) + { + CALocalAccountIdentification = cALocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(CZLocalAccountIdentification cZLocalAccountIdentification) + { + CZLocalAccountIdentification = cZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(DKLocalAccountIdentification dKLocalAccountIdentification) + { + DKLocalAccountIdentification = dKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(HKLocalAccountIdentification hKLocalAccountIdentification) + { + HKLocalAccountIdentification = hKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(HULocalAccountIdentification hULocalAccountIdentification) + { + HULocalAccountIdentification = hULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NOLocalAccountIdentification nOLocalAccountIdentification) + { + NOLocalAccountIdentification = nOLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NZLocalAccountIdentification nZLocalAccountIdentification) + { + NZLocalAccountIdentification = nZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NumberAndBicAccountIdentification numberAndBicAccountIdentification) + { + NumberAndBicAccountIdentification = numberAndBicAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(PLLocalAccountIdentification pLLocalAccountIdentification) + { + PLLocalAccountIdentification = pLLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(SELocalAccountIdentification sELocalAccountIdentification) + { + SELocalAccountIdentification = sELocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(SGLocalAccountIdentification sGLocalAccountIdentification) + { + SGLocalAccountIdentification = sGLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(UKLocalAccountIdentification uKLocalAccountIdentification) + { + UKLocalAccountIdentification = uKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(USLocalAccountIdentification uSLocalAccountIdentification) + { + USLocalAccountIdentification = uSLocalAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AULocalAccountIdentification? AULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public BRLocalAccountIdentification? BRLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CALocalAccountIdentification? CALocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CZLocalAccountIdentification? CZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public DKLocalAccountIdentification? DKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HKLocalAccountIdentification? HKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HULocalAccountIdentification? HULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// .. + /// + public NOLocalAccountIdentification? NOLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NZLocalAccountIdentification? NZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NumberAndBicAccountIdentification? NumberAndBicAccountIdentification { get; set; } + + /// + /// .. + /// + public PLLocalAccountIdentification? PLLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SELocalAccountIdentification? SELocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SGLocalAccountIdentification? SGLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public UKLocalAccountIdentification? UKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public USLocalAccountIdentification? USLocalAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountV3AccountIdentification {\n"); + if (this.AULocalAccountIdentification != null) + sb.Append(AULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.BRLocalAccountIdentification != null) + sb.Append(BRLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CALocalAccountIdentification != null) + sb.Append(CALocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CZLocalAccountIdentification != null) + sb.Append(CZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.DKLocalAccountIdentification != null) + sb.Append(DKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HKLocalAccountIdentification != null) + sb.Append(HKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HULocalAccountIdentification != null) + sb.Append(HULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NOLocalAccountIdentification != null) + sb.Append(NOLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NZLocalAccountIdentification != null) + sb.Append(NZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NumberAndBicAccountIdentification != null) + sb.Append(NumberAndBicAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.PLLocalAccountIdentification != null) + sb.Append(PLLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SELocalAccountIdentification != null) + sb.Append(SELocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SGLocalAccountIdentification != null) + sb.Append(SGLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.UKLocalAccountIdentification != null) + sb.Append(UKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.USLocalAccountIdentification != null) + sb.Append(USLocalAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountV3AccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountV3AccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AULocalAccountIdentification? aULocalAccountIdentification = default; + BRLocalAccountIdentification? bRLocalAccountIdentification = default; + CALocalAccountIdentification? cALocalAccountIdentification = default; + CZLocalAccountIdentification? cZLocalAccountIdentification = default; + DKLocalAccountIdentification? dKLocalAccountIdentification = default; + HKLocalAccountIdentification? hKLocalAccountIdentification = default; + HULocalAccountIdentification? hULocalAccountIdentification = default; + IbanAccountIdentification? ibanAccountIdentification = default; + NOLocalAccountIdentification? nOLocalAccountIdentification = default; + NZLocalAccountIdentification? nZLocalAccountIdentification = default; + NumberAndBicAccountIdentification? numberAndBicAccountIdentification = default; + PLLocalAccountIdentification? pLLocalAccountIdentification = default; + SELocalAccountIdentification? sELocalAccountIdentification = default; + SGLocalAccountIdentification? sGLocalAccountIdentification = default; + UKLocalAccountIdentification? uKLocalAccountIdentification = default; + USLocalAccountIdentification? uSLocalAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAULocalAccountIdentification, jsonSerializerOptions, out aULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderBRLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBRLocalAccountIdentification, jsonSerializerOptions, out bRLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCALocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCALocalAccountIdentification, jsonSerializerOptions, out cALocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCZLocalAccountIdentification, jsonSerializerOptions, out cZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderDKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDKLocalAccountIdentification, jsonSerializerOptions, out dKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHKLocalAccountIdentification, jsonSerializerOptions, out hKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHULocalAccountIdentification, jsonSerializerOptions, out hULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + + Utf8JsonReader utf8JsonReaderNOLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNOLocalAccountIdentification, jsonSerializerOptions, out nOLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNZLocalAccountIdentification, jsonSerializerOptions, out nZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNumberAndBicAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumberAndBicAccountIdentification, jsonSerializerOptions, out numberAndBicAccountIdentification); + + Utf8JsonReader utf8JsonReaderPLLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPLLocalAccountIdentification, jsonSerializerOptions, out pLLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSELocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSELocalAccountIdentification, jsonSerializerOptions, out sELocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSGLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSGLocalAccountIdentification, jsonSerializerOptions, out sGLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUKLocalAccountIdentification, jsonSerializerOptions, out uKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUSLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSLocalAccountIdentification, jsonSerializerOptions, out uSLocalAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (aULocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(aULocalAccountIdentification); + + if (bRLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(bRLocalAccountIdentification); + + if (cALocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(cALocalAccountIdentification); + + if (cZLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(cZLocalAccountIdentification); + + if (dKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(dKLocalAccountIdentification); + + if (hKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(hKLocalAccountIdentification); + + if (hULocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(hULocalAccountIdentification); + + if (ibanAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(ibanAccountIdentification); + + if (nOLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(nOLocalAccountIdentification); + + if (nZLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(nZLocalAccountIdentification); + + if (numberAndBicAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(numberAndBicAccountIdentification); + + if (pLLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(pLLocalAccountIdentification); + + if (sELocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(sELocalAccountIdentification); + + if (sGLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(sGLocalAccountIdentification); + + if (uKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(uKLocalAccountIdentification); + + if (uSLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(uSLocalAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountV3AccountIdentification bankAccountV3AccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + if (bankAccountV3AccountIdentification.AULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.AULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.BRLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.BRLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.CALocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.CALocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.CZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.CZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.DKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.DKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.HKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.HKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.HULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.HULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.IbanAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NOLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NOLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NumberAndBicAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NumberAndBicAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.PLLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.PLLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.SELocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.SELocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.SGLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.SGLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.UKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.UKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.USLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.USLocalAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, bankAccountV3AccountIdentification, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountV3AccountIdentification bankAccountV3AccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Models/BankCategoryData.cs b/Adyen/TransferWebhooks/Models/BankCategoryData.cs new file mode 100644 index 000000000..462bf885f --- /dev/null +++ b/Adyen/TransferWebhooks/Models/BankCategoryData.cs @@ -0,0 +1,441 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// BankCategoryData. + /// + public partial class BankCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// **bank** (default to TypeEnum.Bank) + [JsonConstructor] + public BankCategoryData(Option priority = default, Option type = default) + { + _PriorityOption = priority; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankCategoryData() + { + } + + partial void OnCreated(); + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// **bank** + /// + /// **bank** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Bank - bank + /// + public static readonly TypeEnum Bank = new("bank"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => TypeEnum.Bank, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Bank) + return "bank"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **bank** + /// + /// **bank** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankCategoryData {\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option priority = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(BankCategoryData.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BankCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BankCategoryData(priority, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankCategoryData._PriorityOption.IsSet && bankCategoryData.Priority != null) + { + string? priorityRawValue = BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryData._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (bankCategoryData._TypeOption.IsSet && bankCategoryData.Type != null) + { + string? typeRawValue = BankCategoryData.TypeEnum.ToJsonValue(bankCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/CALocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/CALocalAccountIdentification.cs new file mode 100644 index 000000000..bce1c50ac --- /dev/null +++ b/Adyen/TransferWebhooks/Models/CALocalAccountIdentification.cs @@ -0,0 +1,496 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// CALocalAccountIdentification. + /// + public partial class CALocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// The 3-digit institution number, without separators or whitespace. + /// The 5-digit transit number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **caLocal** (default to TypeEnum.CaLocal) + [JsonConstructor] + public CALocalAccountIdentification(string accountNumber, string institutionNumber, string transitNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + InstitutionNumber = institutionNumber; + TransitNumber = transitNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CALocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CaLocal - caLocal + /// + public static readonly TypeEnum CaLocal = new("caLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "caLocal" => TypeEnum.CaLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CaLocal) + return "caLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit institution number, without separators or whitespace. + /// + /// The 3-digit institution number, without separators or whitespace. + [JsonPropertyName("institutionNumber")] + public string InstitutionNumber { get; set; } + + /// + /// The 5-digit transit number, without separators or whitespace. + /// + /// The 5-digit transit number, without separators or whitespace. + [JsonPropertyName("transitNumber")] + public string TransitNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CALocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" InstitutionNumber: ").Append(InstitutionNumber).Append("\n"); + sb.Append(" TransitNumber: ").Append(TransitNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 12) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 12.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // InstitutionNumber (string) maxLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length > 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be less than 3.", new [] { "InstitutionNumber" }); + } + + // InstitutionNumber (string) minLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length < 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be greater than 3.", new [] { "InstitutionNumber" }); + } + + // TransitNumber (string) maxLength + if (this.TransitNumber != null && this.TransitNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be less than 5.", new [] { "TransitNumber" }); + } + + // TransitNumber (string) minLength + if (this.TransitNumber != null && this.TransitNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be greater than 5.", new [] { "TransitNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CALocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CALocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option institutionNumber = default; + Option transitNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "institutionNumber": + institutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "transitNumber": + transitNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(CALocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CALocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(accountNumber)); + + if (!institutionNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(institutionNumber)); + + if (!transitNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(transitNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(type)); + + return new CALocalAccountIdentification(accountNumber.Value!, institutionNumber.Value!, transitNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cALocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cALocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cALocalAccountIdentification.AccountNumber); + + if (cALocalAccountIdentification.InstitutionNumber != null) + writer.WriteString("institutionNumber", cALocalAccountIdentification.InstitutionNumber); + + if (cALocalAccountIdentification.TransitNumber != null) + writer.WriteString("transitNumber", cALocalAccountIdentification.TransitNumber); + + if (cALocalAccountIdentification._AccountTypeOption.IsSet && cALocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (cALocalAccountIdentification.Type != null) + { + string? typeRawValue = CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/CZLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/CZLocalAccountIdentification.cs new file mode 100644 index 000000000..bb9a821f6 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/CZLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// CZLocalAccountIdentification. + /// + public partial class CZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// **czLocal** (default to TypeEnum.CzLocal) + [JsonConstructor] + public CZLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CzLocal - czLocal + /// + public static readonly TypeEnum CzLocal = new("czLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "czLocal" => TypeEnum.CzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CzLocal) + return "czLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(type)); + + return new CZLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cZLocalAccountIdentification.AccountNumber); + + if (cZLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", cZLocalAccountIdentification.BankCode); + + if (cZLocalAccountIdentification.Type != null) + { + string? typeRawValue = CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Card.cs b/Adyen/TransferWebhooks/Models/Card.cs new file mode 100644 index 000000000..626c2abe1 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Card.cs @@ -0,0 +1,188 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cardHolder + /// cardIdentification + [JsonConstructor] + public Card(PartyIdentification cardHolder, CardIdentification cardIdentification) + { + CardHolder = cardHolder; + CardIdentification = cardIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("cardHolder")] + public PartyIdentification CardHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("cardIdentification")] + public CardIdentification CardIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" CardHolder: ").Append(CardHolder).Append("\n"); + sb.Append(" CardIdentification: ").Append(CardIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardHolder = default; + Option cardIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardHolder": + cardHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardIdentification": + cardIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!cardHolder.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardHolder)); + + if (!cardIdentification.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardIdentification)); + + return new Card(cardHolder.Value!, cardIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("cardHolder"); + JsonSerializer.Serialize(writer, card.CardHolder, jsonSerializerOptions); + writer.WritePropertyName("cardIdentification"); + JsonSerializer.Serialize(writer, card.CardIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/CardIdentification.cs b/Adyen/TransferWebhooks/Models/CardIdentification.cs new file mode 100644 index 000000000..dbb567401 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/CardIdentification.cs @@ -0,0 +1,399 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// CardIdentification. + /// + public partial class CardIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// The expiry year of the card. Format: four digits. For example: 2020 + /// The issue number of the card. Applies only to some UK debit cards. + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + [JsonConstructor] + public CardIdentification(Option expiryMonth = default, Option expiryYear = default, Option issueNumber = default, Option number = default, Option startMonth = default, Option startYear = default, Option storedPaymentMethodId = default) + { + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _IssueNumberOption = issueNumber; + _NumberOption = number; + _StartMonthOption = startMonth; + _StartYearOption = startYear; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardIdentification() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The expiry year of the card. Format: four digits. For example: 2020 + /// + /// The expiry year of the card. Format: four digits. For example: 2020 + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueNumberOption { get; private set; } + + /// + /// The issue number of the card. Applies only to some UK debit cards. + /// + /// The issue number of the card. Applies only to some UK debit cards. + [JsonPropertyName("issueNumber")] + public string? IssueNumber { get { return this._IssueNumberOption; } set { this._IssueNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + /// + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartMonthOption { get; private set; } + + /// + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + [JsonPropertyName("startMonth")] + public string? StartMonth { get { return this._StartMonthOption; } set { this._StartMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartYearOption { get; private set; } + + /// + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + /// + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + [JsonPropertyName("startYear")] + public string? StartYear { get { return this._StartYearOption; } set { this._StartYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + /// + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardIdentification {\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" IssueNumber: ").Append(IssueNumber).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" StartMonth: ").Append(StartMonth).Append("\n"); + sb.Append(" StartYear: ").Append(StartYear).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ExpiryMonth (string) maxLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be less than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryMonth (string) minLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length < 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be greater than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryYear (string) maxLength + if (this.ExpiryYear != null && this.ExpiryYear.Length > 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be less than 4.", new [] { "ExpiryYear" }); + } + + // ExpiryYear (string) minLength + if (this.ExpiryYear != null && this.ExpiryYear.Length < 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be greater than 4.", new [] { "ExpiryYear" }); + } + + // IssueNumber (string) maxLength + if (this.IssueNumber != null && this.IssueNumber.Length > 2) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be less than 2.", new [] { "IssueNumber" }); + } + + // IssueNumber (string) minLength + if (this.IssueNumber != null && this.IssueNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be greater than 1.", new [] { "IssueNumber" }); + } + + // Number (string) maxLength + if (this.Number != null && this.Number.Length > 19) + { + yield return new ValidationResult("Invalid value for Number, length must be less than 19.", new [] { "Number" }); + } + + // Number (string) minLength + if (this.Number != null && this.Number.Length < 4) + { + yield return new ValidationResult("Invalid value for Number, length must be greater than 4.", new [] { "Number" }); + } + + // StartMonth (string) maxLength + if (this.StartMonth != null && this.StartMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be less than 2.", new [] { "StartMonth" }); + } + + // StartMonth (string) minLength + if (this.StartMonth != null && this.StartMonth.Length < 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be greater than 2.", new [] { "StartMonth" }); + } + + // StartYear (string) maxLength + if (this.StartYear != null && this.StartYear.Length > 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be less than 4.", new [] { "StartYear" }); + } + + // StartYear (string) minLength + if (this.StartYear != null && this.StartYear.Length < 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be greater than 4.", new [] { "StartYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option expiryMonth = default; + Option expiryYear = default; + Option issueNumber = default; + Option number = default; + Option startMonth = default; + Option startYear = default; + Option storedPaymentMethodId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "issueNumber": + issueNumber = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "startMonth": + startMonth = new Option(utf8JsonReader.GetString()!); + break; + case "startYear": + startYear = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardIdentification(expiryMonth, expiryYear, issueNumber, number, startMonth, startYear, storedPaymentMethodId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardIdentification cardIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardIdentification cardIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardIdentification._ExpiryMonthOption.IsSet) + if (cardIdentification.ExpiryMonth != null) + writer.WriteString("expiryMonth", cardIdentification.ExpiryMonth); + + if (cardIdentification._ExpiryYearOption.IsSet) + if (cardIdentification.ExpiryYear != null) + writer.WriteString("expiryYear", cardIdentification.ExpiryYear); + + if (cardIdentification._IssueNumberOption.IsSet) + if (cardIdentification.IssueNumber != null) + writer.WriteString("issueNumber", cardIdentification.IssueNumber); + + if (cardIdentification._NumberOption.IsSet) + if (cardIdentification.Number != null) + writer.WriteString("number", cardIdentification.Number); + + if (cardIdentification._StartMonthOption.IsSet) + if (cardIdentification.StartMonth != null) + writer.WriteString("startMonth", cardIdentification.StartMonth); + + if (cardIdentification._StartYearOption.IsSet) + if (cardIdentification.StartYear != null) + writer.WriteString("startYear", cardIdentification.StartYear); + + if (cardIdentification._StoredPaymentMethodIdOption.IsSet) + if (cardIdentification.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", cardIdentification.StoredPaymentMethodId); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/ConfirmationTrackingData.cs b/Adyen/TransferWebhooks/Models/ConfirmationTrackingData.cs new file mode 100644 index 000000000..e8374c9b3 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/ConfirmationTrackingData.cs @@ -0,0 +1,396 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// ConfirmationTrackingData. + /// + public partial class ConfirmationTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. (default to TypeEnum.Confirmation) + [JsonConstructor] + public ConfirmationTrackingData(StatusEnum status, TypeEnum type = default) + { + Status = status; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ConfirmationTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.Accepted - accepted + /// + public static readonly StatusEnum Accepted = new("accepted"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "credited" => StatusEnum.Credited, + "accepted" => StatusEnum.Accepted, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.Accepted) + return "accepted"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Confirmation - confirmation + /// + public static readonly TypeEnum Confirmation = new("confirmation"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "confirmation" => TypeEnum.Confirmation, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Confirmation) + return "confirmation"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ConfirmationTrackingData {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ConfirmationTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ConfirmationTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(ConfirmationTrackingData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ConfirmationTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ConfirmationTrackingData.", nameof(status)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ConfirmationTrackingData.", nameof(type)); + + return new ConfirmationTrackingData(status.Value!.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ConfirmationTrackingData confirmationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, confirmationTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ConfirmationTrackingData confirmationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + if (confirmationTrackingData.Status != null) + { + string? statusRawValue = ConfirmationTrackingData.StatusEnum.ToJsonValue(confirmationTrackingData.Status); + writer.WriteString("status", statusRawValue); + } + + if (confirmationTrackingData.Type != null) + { + string? typeRawValue = ConfirmationTrackingData.TypeEnum.ToJsonValue(confirmationTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/CounterpartyV3.cs b/Adyen/TransferWebhooks/Models/CounterpartyV3.cs new file mode 100644 index 000000000..2dea46eb1 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/CounterpartyV3.cs @@ -0,0 +1,277 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// CounterpartyV3. + /// + public partial class CounterpartyV3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// bankAccount + /// card + /// merchant + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonConstructor] + public CounterpartyV3(Option balanceAccountId = default, Option bankAccount = default, Option card = default, Option merchant = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _BankAccountOption = bankAccount; + _CardOption = card; + _MerchantOption = merchant; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CounterpartyV3() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountV3? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public MerchantData? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CounterpartyV3 {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyV3JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CounterpartyV3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option bankAccount = default; + Option card = default; + Option merchant = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CounterpartyV3(balanceAccountId, bankAccount, card, merchant, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CounterpartyV3 counterpartyV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterpartyV3, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CounterpartyV3 counterpartyV3, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterpartyV3._BalanceAccountIdOption.IsSet) + if (counterpartyV3.BalanceAccountId != null) + writer.WriteString("balanceAccountId", counterpartyV3.BalanceAccountId); + + if (counterpartyV3._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, counterpartyV3.BankAccount, jsonSerializerOptions); + } + if (counterpartyV3._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, counterpartyV3.Card, jsonSerializerOptions); + } + if (counterpartyV3._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, counterpartyV3.Merchant, jsonSerializerOptions); + } + if (counterpartyV3._TransferInstrumentIdOption.IsSet) + if (counterpartyV3.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", counterpartyV3.TransferInstrumentId); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/DKLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/DKLocalAccountIdentification.cs new file mode 100644 index 000000000..2e420d48c --- /dev/null +++ b/Adyen/TransferWebhooks/Models/DKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// DKLocalAccountIdentification. + /// + public partial class DKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// **dkLocal** (default to TypeEnum.DkLocal) + [JsonConstructor] + public DKLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DkLocal - dkLocal + /// + public static readonly TypeEnum DkLocal = new("dkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dkLocal" => TypeEnum.DkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DkLocal) + return "dkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(type)); + + return new DKLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (dKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", dKLocalAccountIdentification.AccountNumber); + + if (dKLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", dKLocalAccountIdentification.BankCode); + + if (dKLocalAccountIdentification.Type != null) + { + string? typeRawValue = DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/DirectDebitInformation.cs b/Adyen/TransferWebhooks/Models/DirectDebitInformation.cs new file mode 100644 index 000000000..9bc7ba58c --- /dev/null +++ b/Adyen/TransferWebhooks/Models/DirectDebitInformation.cs @@ -0,0 +1,260 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// DirectDebitInformation. + /// + public partial class DirectDebitInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + /// The date when the funds are deducted from your user's balance account. + /// Your unique identifier for the direct debit mandate. + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + [JsonConstructor] + public DirectDebitInformation(Option dateOfSignature = default, Option dueDate = default, Option mandateId = default, Option sequenceType = default) + { + _DateOfSignatureOption = dateOfSignature; + _DueDateOption = dueDate; + _MandateIdOption = mandateId; + _SequenceTypeOption = sequenceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DirectDebitInformation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfSignatureOption { get; private set; } + + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + [JsonPropertyName("dateOfSignature")] + public DateTimeOffset? DateOfSignature { get { return this._DateOfSignatureOption; } set { this._DateOfSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DueDateOption { get; private set; } + + /// + /// The date when the funds are deducted from your user's balance account. + /// + /// The date when the funds are deducted from your user's balance account. + [JsonPropertyName("dueDate")] + public DateTimeOffset? DueDate { get { return this._DueDateOption; } set { this._DueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateIdOption { get; private set; } + + /// + /// Your unique identifier for the direct debit mandate. + /// + /// Your unique identifier for the direct debit mandate. + [JsonPropertyName("mandateId")] + public string? MandateId { get { return this._MandateIdOption; } set { this._MandateIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SequenceTypeOption { get; private set; } + + /// + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + /// + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + [JsonPropertyName("sequenceType")] + public string? SequenceType { get { return this._SequenceTypeOption; } set { this._SequenceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DirectDebitInformation {\n"); + sb.Append(" DateOfSignature: ").Append(DateOfSignature).Append("\n"); + sb.Append(" DueDate: ").Append(DueDate).Append("\n"); + sb.Append(" MandateId: ").Append(MandateId).Append("\n"); + sb.Append(" SequenceType: ").Append(SequenceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DirectDebitInformationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfSignature. + /// + public static string DateOfSignatureFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DueDate. + /// + public static string DueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DirectDebitInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dateOfSignature = default; + Option dueDate = default; + Option mandateId = default; + Option sequenceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dateOfSignature": + dateOfSignature = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dueDate": + dueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "mandateId": + mandateId = new Option(utf8JsonReader.GetString()!); + break; + case "sequenceType": + sequenceType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DirectDebitInformation(dateOfSignature, dueDate, mandateId, sequenceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DirectDebitInformation directDebitInformation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, directDebitInformation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DirectDebitInformation directDebitInformation, JsonSerializerOptions jsonSerializerOptions) + { + + if (directDebitInformation._DateOfSignatureOption.IsSet) + writer.WriteString("dateOfSignature", directDebitInformation._DateOfSignatureOption.Value!.Value.ToString(DateOfSignatureFormat)); + + if (directDebitInformation._DueDateOption.IsSet) + writer.WriteString("dueDate", directDebitInformation._DueDateOption.Value!.Value.ToString(DueDateFormat)); + + if (directDebitInformation._MandateIdOption.IsSet) + if (directDebitInformation.MandateId != null) + writer.WriteString("mandateId", directDebitInformation.MandateId); + + if (directDebitInformation._SequenceTypeOption.IsSet) + if (directDebitInformation.SequenceType != null) + writer.WriteString("sequenceType", directDebitInformation.SequenceType); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/EstimationTrackingData.cs b/Adyen/TransferWebhooks/Models/EstimationTrackingData.cs new file mode 100644 index 000000000..f9808fef0 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/EstimationTrackingData.cs @@ -0,0 +1,293 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// EstimationTrackingData. + /// + public partial class EstimationTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The estimated time the beneficiary should have access to the funds. + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. (default to TypeEnum.Estimation) + [JsonConstructor] + public EstimationTrackingData(DateTimeOffset estimatedArrivalTime, TypeEnum type = default) + { + EstimatedArrivalTime = estimatedArrivalTime; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EstimationTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Estimation - estimation + /// + public static readonly TypeEnum Estimation = new("estimation"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "estimation" => TypeEnum.Estimation, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Estimation) + return "estimation"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The estimated time the beneficiary should have access to the funds. + /// + /// The estimated time the beneficiary should have access to the funds. + [JsonPropertyName("estimatedArrivalTime")] + public DateTimeOffset EstimatedArrivalTime { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EstimationTrackingData {\n"); + sb.Append(" EstimatedArrivalTime: ").Append(EstimatedArrivalTime).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EstimationTrackingDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EstimatedArrivalTime. + /// + public static string EstimatedArrivalTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EstimationTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option estimatedArrivalTime = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "estimatedArrivalTime": + estimatedArrivalTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(EstimationTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!estimatedArrivalTime.IsSet) + throw new ArgumentException("Property is required for class EstimationTrackingData.", nameof(estimatedArrivalTime)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class EstimationTrackingData.", nameof(type)); + + return new EstimationTrackingData(estimatedArrivalTime.Value!.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EstimationTrackingData estimationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, estimationTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EstimationTrackingData estimationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("estimatedArrivalTime", estimationTrackingData.EstimatedArrivalTime.ToString(EstimatedArrivalTimeFormat)); + + if (estimationTrackingData.Type != null) + { + string? typeRawValue = EstimationTrackingData.TypeEnum.ToJsonValue(estimationTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/ExecutionDate.cs b/Adyen/TransferWebhooks/Models/ExecutionDate.cs new file mode 100644 index 000000000..9d62313b5 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/ExecutionDate.cs @@ -0,0 +1,206 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// ExecutionDate. + /// + public partial class ExecutionDate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + [JsonConstructor] + public ExecutionDate(Option date = default, Option timezone = default) + { + _DateOption = date; + _TimezoneOption = timezone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExecutionDate() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOption { get; private set; } + + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + [JsonPropertyName("date")] + public DateOnly? Date { get { return this._DateOption; } set { this._DateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimezoneOption { get; private set; } + + /// + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + /// + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + [JsonPropertyName("timezone")] + public string? Timezone { get { return this._TimezoneOption; } set { this._TimezoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExecutionDate {\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Timezone: ").Append(Timezone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExecutionDateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Date. + /// + public static string DateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExecutionDate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option date = default; + Option timezone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "date": + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "timezone": + timezone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExecutionDate(date, timezone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExecutionDate executionDate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, executionDate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExecutionDate executionDate, JsonSerializerOptions jsonSerializerOptions) + { + + if (executionDate._DateOption.IsSet) + writer.WriteString("date", executionDate._DateOption.Value!.Value.ToString(DateFormat)); + + if (executionDate._TimezoneOption.IsSet) + if (executionDate.Timezone != null) + writer.WriteString("timezone", executionDate.Timezone); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/ExternalReason.cs b/Adyen/TransferWebhooks/Models/ExternalReason.cs new file mode 100644 index 000000000..f1f85c97a --- /dev/null +++ b/Adyen/TransferWebhooks/Models/ExternalReason.cs @@ -0,0 +1,227 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// ExternalReason. + /// + public partial class ExternalReason : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason code. + /// The description of the reason code. + /// The namespace for the reason code. + [JsonConstructor] + public ExternalReason(Option code = default, Option description = default, Option @namespace = default) + { + _CodeOption = code; + _DescriptionOption = description; + _NamespaceOption = @namespace; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExternalReason() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The reason code. + /// + /// The reason code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the reason code. + /// + /// The description of the reason code. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NamespaceOption { get; private set; } + + /// + /// The namespace for the reason code. + /// + /// The namespace for the reason code. + [JsonPropertyName("namespace")] + public string? Namespace { get { return this._NamespaceOption; } set { this._NamespaceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExternalReason {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Namespace: ").Append(Namespace).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExternalReasonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExternalReason Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option description = default; + Option varNamespace = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "namespace": + varNamespace = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExternalReason(code, description, varNamespace); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExternalReason externalReason, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, externalReason, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExternalReason externalReason, JsonSerializerOptions jsonSerializerOptions) + { + + if (externalReason._CodeOption.IsSet) + if (externalReason.Code != null) + writer.WriteString("code", externalReason.Code); + + if (externalReason._DescriptionOption.IsSet) + if (externalReason.Description != null) + writer.WriteString("description", externalReason.Description); + + if (externalReason._NamespaceOption.IsSet) + if (externalReason.Namespace != null) + writer.WriteString("namespace", externalReason.Namespace); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/HKLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/HKLocalAccountIdentification.cs new file mode 100644 index 000000000..aa0d7ca81 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/HKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// HKLocalAccountIdentification. + /// + public partial class HKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// The 3-digit clearing code, without separators or whitespace. + /// **hkLocal** (default to TypeEnum.HkLocal) + [JsonConstructor] + public HKLocalAccountIdentification(string accountNumber, string clearingCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingCode = clearingCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HkLocal - hkLocal + /// + public static readonly TypeEnum HkLocal = new("hkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "hkLocal" => TypeEnum.HkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HkLocal) + return "hkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit clearing code, without separators or whitespace. + /// + /// The 3-digit clearing code, without separators or whitespace. + [JsonPropertyName("clearingCode")] + public string ClearingCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingCode: ").Append(ClearingCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 9.", new [] { "AccountNumber" }); + } + + // ClearingCode (string) maxLength + if (this.ClearingCode != null && this.ClearingCode.Length > 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be less than 3.", new [] { "ClearingCode" }); + } + + // ClearingCode (string) minLength + if (this.ClearingCode != null && this.ClearingCode.Length < 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be greater than 3.", new [] { "ClearingCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingCode": + clearingCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingCode.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(clearingCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(type)); + + return new HKLocalAccountIdentification(accountNumber.Value!, clearingCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hKLocalAccountIdentification.AccountNumber); + + if (hKLocalAccountIdentification.ClearingCode != null) + writer.WriteString("clearingCode", hKLocalAccountIdentification.ClearingCode); + + if (hKLocalAccountIdentification.Type != null) + { + string? typeRawValue = HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/HULocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/HULocalAccountIdentification.cs new file mode 100644 index 000000000..bcee51ada --- /dev/null +++ b/Adyen/TransferWebhooks/Models/HULocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// HULocalAccountIdentification. + /// + public partial class HULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 24-digit bank account number, without separators or whitespace. + /// **huLocal** (default to TypeEnum.HuLocal) + [JsonConstructor] + public HULocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HuLocal - huLocal + /// + public static readonly TypeEnum HuLocal = new("huLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "huLocal" => TypeEnum.HuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HuLocal) + return "huLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 24-digit bank account number, without separators or whitespace. + /// + /// The 24-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 24.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 24.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(type)); + + return new HULocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hULocalAccountIdentification.AccountNumber); + + if (hULocalAccountIdentification.Type != null) + { + string? typeRawValue = HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/IbanAccountIdentification.cs b/Adyen/TransferWebhooks/Models/IbanAccountIdentification.cs new file mode 100644 index 000000000..2fb9819de --- /dev/null +++ b/Adyen/TransferWebhooks/Models/IbanAccountIdentification.cs @@ -0,0 +1,289 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// IbanAccountIdentification. + /// + public partial class IbanAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// **iban** (default to TypeEnum.Iban) + [JsonConstructor] + public IbanAccountIdentification(string iban, TypeEnum type = default) + { + Iban = iban; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **iban** + /// + /// **iban** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Iban - iban + /// + public static readonly TypeEnum Iban = new("iban"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "iban" => TypeEnum.Iban, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Iban) + return "iban"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **iban** + /// + /// **iban** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentification {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(iban)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(type)); + + return new IbanAccountIdentification(iban.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentification.Iban != null) + writer.WriteString("iban", ibanAccountIdentification.Iban); + + if (ibanAccountIdentification.Type != null) + { + string? typeRawValue = IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/InternalCategoryData.cs b/Adyen/TransferWebhooks/Models/InternalCategoryData.cs new file mode 100644 index 000000000..6a9f7ffa7 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/InternalCategoryData.cs @@ -0,0 +1,324 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// InternalCategoryData. + /// + public partial class InternalCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// **internal** (default to TypeEnum.Internal) + [JsonConstructor] + public InternalCategoryData(Option modificationMerchantReference = default, Option modificationPspReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternalCategoryData() + { + } + + partial void OnCreated(); + + /// + /// **internal** + /// + /// **internal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Internal - internal + /// + public static readonly TypeEnum Internal = new("internal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "internal" => TypeEnum.Internal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Internal) + return "internal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **internal** + /// + /// **internal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternalCategoryData {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternalCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternalCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InternalCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new InternalCategoryData(modificationMerchantReference, modificationPspReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internalCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (internalCategoryData._ModificationMerchantReferenceOption.IsSet) + if (internalCategoryData.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", internalCategoryData.ModificationMerchantReference); + + if (internalCategoryData._ModificationPspReferenceOption.IsSet) + if (internalCategoryData.ModificationPspReference != null) + writer.WriteString("modificationPspReference", internalCategoryData.ModificationPspReference); + + if (internalCategoryData._TypeOption.IsSet && internalCategoryData.Type != null) + { + string? typeRawValue = InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/InternalReviewTrackingData.cs b/Adyen/TransferWebhooks/Models/InternalReviewTrackingData.cs new file mode 100644 index 000000000..0cc2bbd95 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/InternalReviewTrackingData.cs @@ -0,0 +1,518 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// InternalReviewTrackingData. + /// + public partial class InternalReviewTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. (default to TypeEnum.InternalReview) + [JsonConstructor] + public InternalReviewTrackingData(StatusEnum status, Option reason = default, TypeEnum type = default) + { + Status = status; + _ReasonOption = reason; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternalReviewTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "pending" => StatusEnum.Pending, + "failed" => StatusEnum.Failed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Pending) + return "pending"; + + if (value == StatusEnum.Failed) + return "failed"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.RefusedForRegulatoryReasons - refusedForRegulatoryReasons + /// + public static readonly ReasonEnum RefusedForRegulatoryReasons = new("refusedForRegulatoryReasons"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "refusedForRegulatoryReasons" => ReasonEnum.RefusedForRegulatoryReasons, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.RefusedForRegulatoryReasons) + return "refusedForRegulatoryReasons"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.InternalReview - internalReview + /// + public static readonly TypeEnum InternalReview = new("internalReview"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "internalReview" => TypeEnum.InternalReview, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.InternalReview) + return "internalReview"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternalReviewTrackingData {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternalReviewTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternalReviewTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option reason = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(InternalReviewTrackingData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(InternalReviewTrackingData.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InternalReviewTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class InternalReviewTrackingData.", nameof(status)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class InternalReviewTrackingData.", nameof(type)); + + return new InternalReviewTrackingData(status.Value!.Value!, reason, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternalReviewTrackingData internalReviewTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internalReviewTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternalReviewTrackingData internalReviewTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + if (internalReviewTrackingData.Status != null) + { + string? statusRawValue = InternalReviewTrackingData.StatusEnum.ToJsonValue(internalReviewTrackingData.Status); + writer.WriteString("status", statusRawValue); + } + + if (internalReviewTrackingData._ReasonOption.IsSet && internalReviewTrackingData.Reason != null) + { + string? reasonRawValue = InternalReviewTrackingData.ReasonEnum.ToJsonValue(internalReviewTrackingData._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (internalReviewTrackingData.Type != null) + { + string? typeRawValue = InternalReviewTrackingData.TypeEnum.ToJsonValue(internalReviewTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/IssuedCard.cs b/Adyen/TransferWebhooks/Models/IssuedCard.cs new file mode 100644 index 000000000..98f54917e --- /dev/null +++ b/Adyen/TransferWebhooks/Models/IssuedCard.cs @@ -0,0 +1,787 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// IssuedCard. + /// + public partial class IssuedCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// relayedAuthorisationData + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// threeDSecure + /// **issuedCard** (default to TypeEnum.IssuedCard) + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonConstructor] + public IssuedCard(Option authorisationType = default, Option panEntryMode = default, Option processingType = default, Option relayedAuthorisationData = default, Option schemeTraceId = default, Option schemeUniqueTransactionId = default, Option threeDSecure = default, Option type = default, Option?> validationFacts = default) + { + _AuthorisationTypeOption = authorisationType; + _PanEntryModeOption = panEntryMode; + _ProcessingTypeOption = processingType; + _RelayedAuthorisationDataOption = relayedAuthorisationData; + _SchemeTraceIdOption = schemeTraceId; + _SchemeUniqueTransactionIdOption = schemeUniqueTransactionId; + _ThreeDSecureOption = threeDSecure; + _TypeOption = type; + _ValidationFactsOption = validationFacts; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IssuedCard() + { + } + + partial void OnCreated(); + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonConverter(typeof(PanEntryModeEnumJsonConverter))] + public class PanEntryModeEnum : IEnum + { + /// + /// Returns the value of the PanEntryModeEnum. + /// + public string? Value { get; set; } + + /// + /// PanEntryModeEnum.Chip - chip + /// + public static readonly PanEntryModeEnum Chip = new("chip"); + + /// + /// PanEntryModeEnum.Cof - cof + /// + public static readonly PanEntryModeEnum Cof = new("cof"); + + /// + /// PanEntryModeEnum.Contactless - contactless + /// + public static readonly PanEntryModeEnum Contactless = new("contactless"); + + /// + /// PanEntryModeEnum.Ecommerce - ecommerce + /// + public static readonly PanEntryModeEnum Ecommerce = new("ecommerce"); + + /// + /// PanEntryModeEnum.Magstripe - magstripe + /// + public static readonly PanEntryModeEnum Magstripe = new("magstripe"); + + /// + /// PanEntryModeEnum.Manual - manual + /// + public static readonly PanEntryModeEnum Manual = new("manual"); + + /// + /// PanEntryModeEnum.Token - token + /// + public static readonly PanEntryModeEnum Token = new("token"); + + private PanEntryModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PanEntryModeEnum?(string? value) => value == null ? null : new PanEntryModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PanEntryModeEnum? option) => option?.Value; + + public static bool operator ==(PanEntryModeEnum? left, PanEntryModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PanEntryModeEnum? left, PanEntryModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PanEntryModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PanEntryModeEnum? FromStringOrDefault(string value) + { + return value switch { + "chip" => PanEntryModeEnum.Chip, + "cof" => PanEntryModeEnum.Cof, + "contactless" => PanEntryModeEnum.Contactless, + "ecommerce" => PanEntryModeEnum.Ecommerce, + "magstripe" => PanEntryModeEnum.Magstripe, + "manual" => PanEntryModeEnum.Manual, + "token" => PanEntryModeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PanEntryModeEnum? value) + { + if (value == null) + return null; + + if (value == PanEntryModeEnum.Chip) + return "chip"; + + if (value == PanEntryModeEnum.Cof) + return "cof"; + + if (value == PanEntryModeEnum.Contactless) + return "contactless"; + + if (value == PanEntryModeEnum.Ecommerce) + return "ecommerce"; + + if (value == PanEntryModeEnum.Magstripe) + return "magstripe"; + + if (value == PanEntryModeEnum.Manual) + return "manual"; + + if (value == PanEntryModeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing PanEntryModeEnum. + /// + public class PanEntryModeEnumJsonConverter : JsonConverter + { + public override PanEntryModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PanEntryModeEnum.FromStringOrDefault(value) ?? new PanEntryModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PanEntryModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PanEntryModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PanEntryModeOption { get; private set; } + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonPropertyName("panEntryMode")] + public PanEntryModeEnum? PanEntryMode { get { return this._PanEntryModeOption; } set { this._PanEntryModeOption = new(value); } } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.AtmWithdraw - atmWithdraw + /// + public static readonly ProcessingTypeEnum AtmWithdraw = new("atmWithdraw"); + + /// + /// ProcessingTypeEnum.BalanceInquiry - balanceInquiry + /// + public static readonly ProcessingTypeEnum BalanceInquiry = new("balanceInquiry"); + + /// + /// ProcessingTypeEnum.Ecommerce - ecommerce + /// + public static readonly ProcessingTypeEnum Ecommerce = new("ecommerce"); + + /// + /// ProcessingTypeEnum.Moto - moto + /// + public static readonly ProcessingTypeEnum Moto = new("moto"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + /// + /// ProcessingTypeEnum.PurchaseWithCashback - purchaseWithCashback + /// + public static readonly ProcessingTypeEnum PurchaseWithCashback = new("purchaseWithCashback"); + + /// + /// ProcessingTypeEnum.Recurring - recurring + /// + public static readonly ProcessingTypeEnum Recurring = new("recurring"); + + /// + /// ProcessingTypeEnum.Token - token + /// + public static readonly ProcessingTypeEnum Token = new("token"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "atmWithdraw" => ProcessingTypeEnum.AtmWithdraw, + "balanceInquiry" => ProcessingTypeEnum.BalanceInquiry, + "ecommerce" => ProcessingTypeEnum.Ecommerce, + "moto" => ProcessingTypeEnum.Moto, + "pos" => ProcessingTypeEnum.Pos, + "purchaseWithCashback" => ProcessingTypeEnum.PurchaseWithCashback, + "recurring" => ProcessingTypeEnum.Recurring, + "token" => ProcessingTypeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.AtmWithdraw) + return "atmWithdraw"; + + if (value == ProcessingTypeEnum.BalanceInquiry) + return "balanceInquiry"; + + if (value == ProcessingTypeEnum.Ecommerce) + return "ecommerce"; + + if (value == ProcessingTypeEnum.Moto) + return "moto"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + if (value == ProcessingTypeEnum.PurchaseWithCashback) + return "purchaseWithCashback"; + + if (value == ProcessingTypeEnum.Recurring) + return "recurring"; + + if (value == ProcessingTypeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProcessingTypeOption { get; private set; } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum? ProcessingType { get { return this._ProcessingTypeOption; } set { this._ProcessingTypeOption = new(value); } } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IssuedCard - issuedCard + /// + public static readonly TypeEnum IssuedCard = new("issuedCard"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "issuedCard" => TypeEnum.IssuedCard, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IssuedCard) + return "issuedCard"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTypeOption { get; private set; } + + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + [JsonPropertyName("authorisationType")] + public string? AuthorisationType { get { return this._AuthorisationTypeOption; } set { this._AuthorisationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RelayedAuthorisationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("relayedAuthorisationData")] + public RelayedAuthorisationData? RelayedAuthorisationData { get { return this._RelayedAuthorisationDataOption; } set { this._RelayedAuthorisationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeTraceIdOption { get; private set; } + + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + [JsonPropertyName("schemeTraceId")] + public string? SchemeTraceId { get { return this._SchemeTraceIdOption; } set { this._SchemeTraceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeUniqueTransactionIdOption { get; private set; } + + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + [JsonPropertyName("schemeUniqueTransactionId")] + public string? SchemeUniqueTransactionId { get { return this._SchemeUniqueTransactionIdOption; } set { this._SchemeUniqueTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSecure")] + public ThreeDSecure? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValidationFactsOption { get; private set; } + + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonPropertyName("validationFacts")] + public List? ValidationFacts { get { return this._ValidationFactsOption; } set { this._ValidationFactsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IssuedCard {\n"); + sb.Append(" AuthorisationType: ").Append(AuthorisationType).Append("\n"); + sb.Append(" PanEntryMode: ").Append(PanEntryMode).Append("\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" RelayedAuthorisationData: ").Append(RelayedAuthorisationData).Append("\n"); + sb.Append(" SchemeTraceId: ").Append(SchemeTraceId).Append("\n"); + sb.Append(" SchemeUniqueTransactionId: ").Append(SchemeUniqueTransactionId).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IssuedCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IssuedCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authorisationType = default; + Option panEntryMode = default; + Option processingType = default; + Option relayedAuthorisationData = default; + Option schemeTraceId = default; + Option schemeUniqueTransactionId = default; + Option threeDSecure = default; + Option type = default; + Option?> validationFacts = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authorisationType": + authorisationType = new Option(utf8JsonReader.GetString()!); + break; + case "panEntryMode": + string? panEntryModeRawValue = utf8JsonReader.GetString(); + panEntryMode = new Option(IssuedCard.PanEntryModeEnum.FromStringOrDefault(panEntryModeRawValue)); + break; + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(IssuedCard.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "relayedAuthorisationData": + relayedAuthorisationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "schemeTraceId": + schemeTraceId = new Option(utf8JsonReader.GetString()!); + break; + case "schemeUniqueTransactionId": + schemeUniqueTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSecure": + threeDSecure = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IssuedCard.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "validationFacts": + validationFacts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new IssuedCard(authorisationType, panEntryMode, processingType, relayedAuthorisationData, schemeTraceId, schemeUniqueTransactionId, threeDSecure, type, validationFacts); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, issuedCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (issuedCard._AuthorisationTypeOption.IsSet) + if (issuedCard.AuthorisationType != null) + writer.WriteString("authorisationType", issuedCard.AuthorisationType); + + if (issuedCard._PanEntryModeOption.IsSet && issuedCard.PanEntryMode != null) + { + string? panEntryModeRawValue = IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCard._PanEntryModeOption.Value!.Value); + writer.WriteString("panEntryMode", panEntryModeRawValue); + } + + if (issuedCard._ProcessingTypeOption.IsSet && issuedCard.ProcessingType != null) + { + string? processingTypeRawValue = IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCard._ProcessingTypeOption.Value!.Value); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (issuedCard._RelayedAuthorisationDataOption.IsSet) + { + writer.WritePropertyName("relayedAuthorisationData"); + JsonSerializer.Serialize(writer, issuedCard.RelayedAuthorisationData, jsonSerializerOptions); + } + if (issuedCard._SchemeTraceIdOption.IsSet) + if (issuedCard.SchemeTraceId != null) + writer.WriteString("schemeTraceId", issuedCard.SchemeTraceId); + + if (issuedCard._SchemeUniqueTransactionIdOption.IsSet) + if (issuedCard.SchemeUniqueTransactionId != null) + writer.WriteString("schemeUniqueTransactionId", issuedCard.SchemeUniqueTransactionId); + + if (issuedCard._ThreeDSecureOption.IsSet) + { + writer.WritePropertyName("threeDSecure"); + JsonSerializer.Serialize(writer, issuedCard.ThreeDSecure, jsonSerializerOptions); + } + if (issuedCard._TypeOption.IsSet && issuedCard.Type != null) + { + string? typeRawValue = IssuedCard.TypeEnum.ToJsonValue(issuedCard._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (issuedCard._ValidationFactsOption.IsSet) + { + writer.WritePropertyName("validationFacts"); + JsonSerializer.Serialize(writer, issuedCard.ValidationFacts, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/IssuingTransactionData.cs b/Adyen/TransferWebhooks/Models/IssuingTransactionData.cs new file mode 100644 index 000000000..d531b7923 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/IssuingTransactionData.cs @@ -0,0 +1,294 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// IssuingTransactionData. + /// + public partial class IssuingTransactionData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// captureCycleId associated with transfer event. + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data (default to TypeEnum.IssuingTransactionData) + [JsonConstructor] + public IssuingTransactionData(Option captureCycleId = default, TypeEnum type = default) + { + _CaptureCycleIdOption = captureCycleId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IssuingTransactionData() + { + } + + partial void OnCreated(); + + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IssuingTransactionData - issuingTransactionData + /// + public static readonly TypeEnum IssuingTransactionData = new("issuingTransactionData"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "issuingTransactionData" => TypeEnum.IssuingTransactionData, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IssuingTransactionData) + return "issuingTransactionData"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureCycleIdOption { get; private set; } + + /// + /// captureCycleId associated with transfer event. + /// + /// captureCycleId associated with transfer event. + [JsonPropertyName("captureCycleId")] + public string? CaptureCycleId { get { return this._CaptureCycleIdOption; } set { this._CaptureCycleIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IssuingTransactionData {\n"); + sb.Append(" CaptureCycleId: ").Append(CaptureCycleId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IssuingTransactionDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IssuingTransactionData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option captureCycleId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "captureCycleId": + captureCycleId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IssuingTransactionData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IssuingTransactionData.", nameof(type)); + + return new IssuingTransactionData(captureCycleId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IssuingTransactionData issuingTransactionData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, issuingTransactionData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IssuingTransactionData issuingTransactionData, JsonSerializerOptions jsonSerializerOptions) + { + + if (issuingTransactionData._CaptureCycleIdOption.IsSet) + if (issuingTransactionData.CaptureCycleId != null) + writer.WriteString("captureCycleId", issuingTransactionData.CaptureCycleId); + + if (issuingTransactionData.Type != null) + { + string? typeRawValue = IssuingTransactionData.TypeEnum.ToJsonValue(issuingTransactionData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Leg.cs b/Adyen/TransferWebhooks/Models/Leg.cs new file mode 100644 index 000000000..c76a63791 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Leg.cs @@ -0,0 +1,302 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Leg. + /// + public partial class Leg : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + /// The basic fare code for this leg. + /// IATA code of the carrier operating the flight. + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + /// The flight departure date. + /// The flight identifier. + [JsonConstructor] + public Leg(Option arrivalAirportCode = default, Option basicFareCode = default, Option carrierCode = default, Option departureAirportCode = default, Option departureDate = default, Option flightNumber = default) + { + _ArrivalAirportCodeOption = arrivalAirportCode; + _BasicFareCodeOption = basicFareCode; + _CarrierCodeOption = carrierCode; + _DepartureAirportCodeOption = departureAirportCode; + _DepartureDateOption = departureDate; + _FlightNumberOption = flightNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Leg() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ArrivalAirportCodeOption { get; private set; } + + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + [JsonPropertyName("arrivalAirportCode")] + public string? ArrivalAirportCode { get { return this._ArrivalAirportCodeOption; } set { this._ArrivalAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BasicFareCodeOption { get; private set; } + + /// + /// The basic fare code for this leg. + /// + /// The basic fare code for this leg. + [JsonPropertyName("basicFareCode")] + public string? BasicFareCode { get { return this._BasicFareCodeOption; } set { this._BasicFareCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierCodeOption { get; private set; } + + /// + /// IATA code of the carrier operating the flight. + /// + /// IATA code of the carrier operating the flight. + [JsonPropertyName("carrierCode")] + public string? CarrierCode { get { return this._CarrierCodeOption; } set { this._CarrierCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureAirportCodeOption { get; private set; } + + /// + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + /// + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + [JsonPropertyName("departureAirportCode")] + public string? DepartureAirportCode { get { return this._DepartureAirportCodeOption; } set { this._DepartureAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureDateOption { get; private set; } + + /// + /// The flight departure date. + /// + /// The flight departure date. + [JsonPropertyName("departureDate")] + public string? DepartureDate { get { return this._DepartureDateOption; } set { this._DepartureDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FlightNumberOption { get; private set; } + + /// + /// The flight identifier. + /// + /// The flight identifier. + [JsonPropertyName("flightNumber")] + public string? FlightNumber { get { return this._FlightNumberOption; } set { this._FlightNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Leg {\n"); + sb.Append(" ArrivalAirportCode: ").Append(ArrivalAirportCode).Append("\n"); + sb.Append(" BasicFareCode: ").Append(BasicFareCode).Append("\n"); + sb.Append(" CarrierCode: ").Append(CarrierCode).Append("\n"); + sb.Append(" DepartureAirportCode: ").Append(DepartureAirportCode).Append("\n"); + sb.Append(" DepartureDate: ").Append(DepartureDate).Append("\n"); + sb.Append(" FlightNumber: ").Append(FlightNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Leg Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option arrivalAirportCode = default; + Option basicFareCode = default; + Option carrierCode = default; + Option departureAirportCode = default; + Option departureDate = default; + Option flightNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "arrivalAirportCode": + arrivalAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "basicFareCode": + basicFareCode = new Option(utf8JsonReader.GetString()!); + break; + case "carrierCode": + carrierCode = new Option(utf8JsonReader.GetString()!); + break; + case "departureAirportCode": + departureAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "departureDate": + departureDate = new Option(utf8JsonReader.GetString()!); + break; + case "flightNumber": + flightNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Leg(arrivalAirportCode, basicFareCode, carrierCode, departureAirportCode, departureDate, flightNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, leg, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + if (leg._ArrivalAirportCodeOption.IsSet) + if (leg.ArrivalAirportCode != null) + writer.WriteString("arrivalAirportCode", leg.ArrivalAirportCode); + + if (leg._BasicFareCodeOption.IsSet) + if (leg.BasicFareCode != null) + writer.WriteString("basicFareCode", leg.BasicFareCode); + + if (leg._CarrierCodeOption.IsSet) + if (leg.CarrierCode != null) + writer.WriteString("carrierCode", leg.CarrierCode); + + if (leg._DepartureAirportCodeOption.IsSet) + if (leg.DepartureAirportCode != null) + writer.WriteString("departureAirportCode", leg.DepartureAirportCode); + + if (leg._DepartureDateOption.IsSet) + if (leg.DepartureDate != null) + writer.WriteString("departureDate", leg.DepartureDate); + + if (leg._FlightNumberOption.IsSet) + if (leg.FlightNumber != null) + writer.WriteString("flightNumber", leg.FlightNumber); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Lodging.cs b/Adyen/TransferWebhooks/Models/Lodging.cs new file mode 100644 index 000000000..0303df508 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Lodging.cs @@ -0,0 +1,201 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Lodging. + /// + public partial class Lodging : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The check-in date. + /// The total number of nights the room is booked for. + [JsonConstructor] + public Lodging(Option checkInDate = default, Option numberOfNights = default) + { + _CheckInDateOption = checkInDate; + _NumberOfNightsOption = numberOfNights; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Lodging() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckInDateOption { get; private set; } + + /// + /// The check-in date. + /// + /// The check-in date. + [JsonPropertyName("checkInDate")] + public string? CheckInDate { get { return this._CheckInDateOption; } set { this._CheckInDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOfNightsOption { get; private set; } + + /// + /// The total number of nights the room is booked for. + /// + /// The total number of nights the room is booked for. + [JsonPropertyName("numberOfNights")] + public int? NumberOfNights { get { return this._NumberOfNightsOption; } set { this._NumberOfNightsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Lodging {\n"); + sb.Append(" CheckInDate: ").Append(CheckInDate).Append("\n"); + sb.Append(" NumberOfNights: ").Append(NumberOfNights).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LodgingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Lodging Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkInDate = default; + Option numberOfNights = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkInDate": + checkInDate = new Option(utf8JsonReader.GetString()!); + break; + case "numberOfNights": + numberOfNights = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Lodging(checkInDate, numberOfNights); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Lodging lodging, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, lodging, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Lodging lodging, JsonSerializerOptions jsonSerializerOptions) + { + + if (lodging._CheckInDateOption.IsSet) + if (lodging.CheckInDate != null) + writer.WriteString("checkInDate", lodging.CheckInDate); + + if (lodging._NumberOfNightsOption.IsSet) + writer.WriteNumber("numberOfNights", lodging._NumberOfNightsOption.Value!.Value); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/MerchantData.cs b/Adyen/TransferWebhooks/Models/MerchantData.cs new file mode 100644 index 000000000..9b2f88e58 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/MerchantData.cs @@ -0,0 +1,277 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// MerchantData. + /// + public partial class MerchantData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the merchant's acquirer. + /// The merchant category code. + /// The unique identifier of the merchant. + /// nameLocation + /// The postal code of the merchant. + [JsonConstructor] + public MerchantData(Option acquirerId = default, Option mcc = default, Option merchantId = default, Option nameLocation = default, Option postalCode = default) + { + _AcquirerIdOption = acquirerId; + _MccOption = mcc; + _MerchantIdOption = merchantId; + _NameLocationOption = nameLocation; + _PostalCodeOption = postalCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerIdOption { get; private set; } + + /// + /// The unique identifier of the merchant's acquirer. + /// + /// The unique identifier of the merchant's acquirer. + [JsonPropertyName("acquirerId")] + public string? AcquirerId { get { return this._AcquirerIdOption; } set { this._AcquirerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The merchant category code. + /// + /// The merchant category code. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant. + /// + /// The unique identifier of the merchant. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameLocationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nameLocation")] + public NameLocation? NameLocation { get { return this._NameLocationOption; } set { this._NameLocationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code of the merchant. + /// + /// The postal code of the merchant. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantData {\n"); + sb.Append(" AcquirerId: ").Append(AcquirerId).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" NameLocation: ").Append(NameLocation).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerId = default; + Option mcc = default; + Option merchantId = default; + Option nameLocation = default; + Option postalCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerId": + acquirerId = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "nameLocation": + nameLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantData(acquirerId, mcc, merchantId, nameLocation, postalCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantData merchantData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantData merchantData, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantData._AcquirerIdOption.IsSet) + if (merchantData.AcquirerId != null) + writer.WriteString("acquirerId", merchantData.AcquirerId); + + if (merchantData._MccOption.IsSet) + if (merchantData.Mcc != null) + writer.WriteString("mcc", merchantData.Mcc); + + if (merchantData._MerchantIdOption.IsSet) + if (merchantData.MerchantId != null) + writer.WriteString("merchantId", merchantData.MerchantId); + + if (merchantData._NameLocationOption.IsSet) + { + writer.WritePropertyName("nameLocation"); + JsonSerializer.Serialize(writer, merchantData.NameLocation, jsonSerializerOptions); + } + if (merchantData._PostalCodeOption.IsSet) + if (merchantData.PostalCode != null) + writer.WriteString("postalCode", merchantData.PostalCode); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/MerchantPurchaseData.cs b/Adyen/TransferWebhooks/Models/MerchantPurchaseData.cs new file mode 100644 index 000000000..d84753831 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/MerchantPurchaseData.cs @@ -0,0 +1,320 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// MerchantPurchaseData. + /// + public partial class MerchantPurchaseData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// airline + /// Lodging information. + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data (default to TypeEnum.MerchantPurchaseData) + [JsonConstructor] + public MerchantPurchaseData(Option airline = default, Option?> lodging = default, TypeEnum type = default) + { + _AirlineOption = airline; + _LodgingOption = lodging; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantPurchaseData() + { + } + + partial void OnCreated(); + + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.MerchantPurchaseData - merchantPurchaseData + /// + public static readonly TypeEnum MerchantPurchaseData = new("merchantPurchaseData"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "merchantPurchaseData" => TypeEnum.MerchantPurchaseData, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.MerchantPurchaseData) + return "merchantPurchaseData"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("airline")] + public Airline? Airline { get { return this._AirlineOption; } set { this._AirlineOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LodgingOption { get; private set; } + + /// + /// Lodging information. + /// + /// Lodging information. + [JsonPropertyName("lodging")] + public List? Lodging { get { return this._LodgingOption; } set { this._LodgingOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantPurchaseData {\n"); + sb.Append(" Airline: ").Append(Airline).Append("\n"); + sb.Append(" Lodging: ").Append(Lodging).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantPurchaseDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantPurchaseData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option airline = default; + Option?> lodging = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "airline": + airline = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lodging": + lodging = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MerchantPurchaseData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MerchantPurchaseData.", nameof(type)); + + return new MerchantPurchaseData(airline, lodging, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantPurchaseData merchantPurchaseData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantPurchaseData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantPurchaseData merchantPurchaseData, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantPurchaseData._AirlineOption.IsSet) + { + writer.WritePropertyName("airline"); + JsonSerializer.Serialize(writer, merchantPurchaseData.Airline, jsonSerializerOptions); + } + if (merchantPurchaseData._LodgingOption.IsSet) + { + writer.WritePropertyName("lodging"); + JsonSerializer.Serialize(writer, merchantPurchaseData.Lodging, jsonSerializerOptions); + } + if (merchantPurchaseData.Type != null) + { + string? typeRawValue = MerchantPurchaseData.TypeEnum.ToJsonValue(merchantPurchaseData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Modification.cs b/Adyen/TransferWebhooks/Models/Modification.cs new file mode 100644 index 000000000..40c12d0a8 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Modification.cs @@ -0,0 +1,968 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Modification. + /// + public partial class Modification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The direction of the money movement. + /// Our reference for the modification. + /// Your reference for the modification, used internally within your platform. + /// The status of the transfer event. + /// The type of transfer modification. + [JsonConstructor] + public Modification(Option direction = default, Option id = default, Option reference = default, Option status = default, Option type = default) + { + _DirectionOption = direction; + _IdOption = id; + _ReferenceOption = reference; + _StatusOption = status; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Modification() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectionOption { get; private set; } + + /// + /// The direction of the money movement. + /// + /// The direction of the money movement. + [JsonPropertyName("direction")] + public string? Direction { get { return this._DirectionOption; } set { this._DirectionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Our reference for the modification. + /// + /// Our reference for the modification. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the modification, used internally within your platform. + /// + /// Your reference for the modification, used internally within your platform. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer modification. + /// + /// The type of transfer modification. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Modification {\n"); + sb.Append(" Direction: ").Append(Direction).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Modification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option direction = default; + Option id = default; + Option reference = default; + Option status = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "direction": + direction = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Modification.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Modification(direction, id, reference, status, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Modification modification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Modification modification, JsonSerializerOptions jsonSerializerOptions) + { + + if (modification._DirectionOption.IsSet) + if (modification.Direction != null) + writer.WriteString("direction", modification.Direction); + + if (modification._IdOption.IsSet) + if (modification.Id != null) + writer.WriteString("id", modification.Id); + + if (modification._ReferenceOption.IsSet) + if (modification.Reference != null) + writer.WriteString("reference", modification.Reference); + + if (modification._StatusOption.IsSet && modification.Status != null) + { + string? statusRawValue = Modification.StatusEnum.ToJsonValue(modification._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (modification._TypeOption.IsSet) + if (modification.Type != null) + writer.WriteString("type", modification.Type); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/NOLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/NOLocalAccountIdentification.cs new file mode 100644 index 000000000..b313f04c8 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/NOLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// NOLocalAccountIdentification. + /// + public partial class NOLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 11-digit bank account number, without separators or whitespace. + /// **noLocal** (default to TypeEnum.NoLocal) + [JsonConstructor] + public NOLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NOLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NoLocal - noLocal + /// + public static readonly TypeEnum NoLocal = new("noLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "noLocal" => TypeEnum.NoLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NoLocal) + return "noLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 11-digit bank account number, without separators or whitespace. + /// + /// The 11-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NOLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 11.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 11.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NOLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NOLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NOLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(type)); + + return new NOLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nOLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nOLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nOLocalAccountIdentification.AccountNumber); + + if (nOLocalAccountIdentification.Type != null) + { + string? typeRawValue = NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/NZLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/NZLocalAccountIdentification.cs new file mode 100644 index 000000000..46785038d --- /dev/null +++ b/Adyen/TransferWebhooks/Models/NZLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// NZLocalAccountIdentification. + /// + public partial class NZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// **nzLocal** (default to TypeEnum.NzLocal) + [JsonConstructor] + public NZLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NzLocal - nzLocal + /// + public static readonly TypeEnum NzLocal = new("nzLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nzLocal" => TypeEnum.NzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NzLocal) + return "nzLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 16) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 16.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 15) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 15.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(type)); + + return new NZLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nZLocalAccountIdentification.AccountNumber); + + if (nZLocalAccountIdentification.Type != null) + { + string? typeRawValue = NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/NameLocation.cs b/Adyen/TransferWebhooks/Models/NameLocation.cs new file mode 100644 index 000000000..019fcee5e --- /dev/null +++ b/Adyen/TransferWebhooks/Models/NameLocation.cs @@ -0,0 +1,302 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// NameLocation. + /// + public partial class NameLocation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The city where the merchant is located. + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + /// The name of the merchant's shop or service. + /// The raw data. + /// The state where the merchant is located. + [JsonConstructor] + public NameLocation(Option city = default, Option country = default, Option countryOfOrigin = default, Option name = default, Option rawData = default, Option state = default) + { + _CityOption = city; + _CountryOption = country; + _CountryOfOriginOption = countryOfOrigin; + _NameOption = name; + _RawDataOption = rawData; + _StateOption = state; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NameLocation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city where the merchant is located. + /// + /// The city where the merchant is located. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + /// + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOfOriginOption { get; private set; } + + /// + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + /// + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + [JsonPropertyName("countryOfOrigin")] + public string? CountryOfOrigin { get { return this._CountryOfOriginOption; } set { this._CountryOfOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the merchant's shop or service. + /// + /// The name of the merchant's shop or service. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RawDataOption { get; private set; } + + /// + /// The raw data. + /// + /// The raw data. + [JsonPropertyName("rawData")] + public string? RawData { get { return this._RawDataOption; } set { this._RawDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOption { get; private set; } + + /// + /// The state where the merchant is located. + /// + /// The state where the merchant is located. + [JsonPropertyName("state")] + public string? State { get { return this._StateOption; } set { this._StateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NameLocation {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" CountryOfOrigin: ").Append(CountryOfOrigin).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RawData: ").Append(RawData).Append("\n"); + sb.Append(" State: ").Append(State).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameLocationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NameLocation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option countryOfOrigin = default; + Option name = default; + Option rawData = default; + Option state = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "countryOfOrigin": + countryOfOrigin = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "rawData": + rawData = new Option(utf8JsonReader.GetString()!); + break; + case "state": + state = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NameLocation(city, country, countryOfOrigin, name, rawData, state); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NameLocation nameLocation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nameLocation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NameLocation nameLocation, JsonSerializerOptions jsonSerializerOptions) + { + + if (nameLocation._CityOption.IsSet) + if (nameLocation.City != null) + writer.WriteString("city", nameLocation.City); + + if (nameLocation._CountryOption.IsSet) + if (nameLocation.Country != null) + writer.WriteString("country", nameLocation.Country); + + if (nameLocation._CountryOfOriginOption.IsSet) + if (nameLocation.CountryOfOrigin != null) + writer.WriteString("countryOfOrigin", nameLocation.CountryOfOrigin); + + if (nameLocation._NameOption.IsSet) + if (nameLocation.Name != null) + writer.WriteString("name", nameLocation.Name); + + if (nameLocation._RawDataOption.IsSet) + if (nameLocation.RawData != null) + writer.WriteString("rawData", nameLocation.RawData); + + if (nameLocation._StateOption.IsSet) + if (nameLocation.State != null) + writer.WriteString("state", nameLocation.State); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/NumberAndBicAccountIdentification.cs b/Adyen/TransferWebhooks/Models/NumberAndBicAccountIdentification.cs new file mode 100644 index 000000000..351bc96ba --- /dev/null +++ b/Adyen/TransferWebhooks/Models/NumberAndBicAccountIdentification.cs @@ -0,0 +1,352 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// NumberAndBicAccountIdentification. + /// + public partial class NumberAndBicAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// additionalBankIdentification + /// **numberAndBic** (default to TypeEnum.NumberAndBic) + [JsonConstructor] + public NumberAndBicAccountIdentification(string accountNumber, string bic, Option additionalBankIdentification = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _AdditionalBankIdentificationOption = additionalBankIdentification; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NumberAndBicAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NumberAndBic - numberAndBic + /// + public static readonly TypeEnum NumberAndBic = new("numberAndBic"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "numberAndBic" => TypeEnum.NumberAndBic, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NumberAndBic) + return "numberAndBic"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalBankIdentificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalBankIdentification")] + public AdditionalBankIdentification? AdditionalBankIdentification { get { return this._AdditionalBankIdentificationOption; } set { this._AdditionalBankIdentificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberAndBicAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" AdditionalBankIdentification: ").Append(AdditionalBankIdentification).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 34) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 34.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NumberAndBicAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NumberAndBicAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option additionalBankIdentification = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "additionalBankIdentification": + additionalBankIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NumberAndBicAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(bic)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(type)); + + return new NumberAndBicAccountIdentification(accountNumber.Value!, bic.Value!, additionalBankIdentification, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, numberAndBicAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (numberAndBicAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", numberAndBicAccountIdentification.AccountNumber); + + if (numberAndBicAccountIdentification.Bic != null) + writer.WriteString("bic", numberAndBicAccountIdentification.Bic); + + if (numberAndBicAccountIdentification._AdditionalBankIdentificationOption.IsSet) + { + writer.WritePropertyName("additionalBankIdentification"); + JsonSerializer.Serialize(writer, numberAndBicAccountIdentification.AdditionalBankIdentification, jsonSerializerOptions); + } + if (numberAndBicAccountIdentification.Type != null) + { + string? typeRawValue = NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/PLLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/PLLocalAccountIdentification.cs new file mode 100644 index 000000000..4d1373841 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/PLLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// PLLocalAccountIdentification. + /// + public partial class PLLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// **plLocal** (default to TypeEnum.PlLocal) + [JsonConstructor] + public PLLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PLLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlLocal - plLocal + /// + public static readonly TypeEnum PlLocal = new("plLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "plLocal" => TypeEnum.PlLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlLocal) + return "plLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PLLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 26.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 26.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PLLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PLLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PLLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(type)); + + return new PLLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pLLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (pLLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", pLLocalAccountIdentification.AccountNumber); + + if (pLLocalAccountIdentification.Type != null) + { + string? typeRawValue = PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/PartyIdentification.cs b/Adyen/TransferWebhooks/Models/PartyIdentification.cs new file mode 100644 index 000000000..13b1c8c13 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/PartyIdentification.cs @@ -0,0 +1,514 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// PartyIdentification. + /// + public partial class PartyIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// The email address of the organization or individual. Maximum length: 254 characters. + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. (default to TypeEnum.Unknown) + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonConstructor] + public PartyIdentification(Option address = default, Option dateOfBirth = default, Option email = default, Option firstName = default, Option fullName = default, Option lastName = default, Option reference = default, Option type = default, Option url = default) + { + _AddressOption = address; + _DateOfBirthOption = dateOfBirth; + _EmailOption = email; + _FirstNameOption = firstName; + _FullNameOption = fullName; + _LastNameOption = lastName; + _ReferenceOption = reference; + _TypeOption = type; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PartyIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.Unknown - unknown + /// + public static readonly TypeEnum Unknown = new("unknown"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "unknown" => TypeEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public Address? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullNameOption { get; private set; } + + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + [JsonPropertyName("fullName")] + public string? FullName { get { return this._FullNameOption; } set { this._FullNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PartyIdentification {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" FullName: ").Append(FullName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) maxLength + if (this.Email != null && this.Email.Length > 254) + { + yield return new ValidationResult("Invalid value for Email, length must be less than 254.", new [] { "Email" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + // Url (string) maxLength + if (this.Url != null && this.Url.Length > 255) + { + yield return new ValidationResult("Invalid value for Url, length must be less than 255.", new [] { "Url" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PartyIdentificationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PartyIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option dateOfBirth = default; + Option email = default; + Option firstName = default; + Option fullName = default; + Option lastName = default; + Option reference = default; + Option type = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "fullName": + fullName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PartyIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PartyIdentification(address, dateOfBirth, email, firstName, fullName, lastName, reference, type, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PartyIdentification partyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, partyIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PartyIdentification partyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (partyIdentification._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, partyIdentification.Address, jsonSerializerOptions); + } + if (partyIdentification._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", partyIdentification._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (partyIdentification._EmailOption.IsSet) + if (partyIdentification.Email != null) + writer.WriteString("email", partyIdentification.Email); + + if (partyIdentification._FirstNameOption.IsSet) + if (partyIdentification.FirstName != null) + writer.WriteString("firstName", partyIdentification.FirstName); + + if (partyIdentification._FullNameOption.IsSet) + if (partyIdentification.FullName != null) + writer.WriteString("fullName", partyIdentification.FullName); + + if (partyIdentification._LastNameOption.IsSet) + if (partyIdentification.LastName != null) + writer.WriteString("lastName", partyIdentification.LastName); + + if (partyIdentification._ReferenceOption.IsSet) + if (partyIdentification.Reference != null) + writer.WriteString("reference", partyIdentification.Reference); + + if (partyIdentification._TypeOption.IsSet && partyIdentification.Type != null) + { + string? typeRawValue = PartyIdentification.TypeEnum.ToJsonValue(partyIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (partyIdentification._UrlOption.IsSet) + if (partyIdentification.Url != null) + writer.WriteString("url", partyIdentification.Url); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/PaymentInstrument.cs b/Adyen/TransferWebhooks/Models/PaymentInstrument.cs new file mode 100644 index 000000000..8db69f358 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/PaymentInstrument.cs @@ -0,0 +1,252 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// PaymentInstrument. + /// + public partial class PaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + /// The type of wallet that the network token is associated with. + [JsonConstructor] + public PaymentInstrument(Option description = default, Option id = default, Option reference = default, Option tokenType = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + _TokenTypeOption = tokenType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenTypeOption { get; private set; } + + /// + /// The type of wallet that the network token is associated with. + /// + /// The type of wallet that the network token is associated with. + [JsonPropertyName("tokenType")] + public string? TokenType { get { return this._TokenTypeOption; } set { this._TokenTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrument {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TokenType: ").Append(TokenType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + Option tokenType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenType": + tokenType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentInstrument(description, id, reference, tokenType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrument._DescriptionOption.IsSet) + if (paymentInstrument.Description != null) + writer.WriteString("description", paymentInstrument.Description); + + if (paymentInstrument._IdOption.IsSet) + if (paymentInstrument.Id != null) + writer.WriteString("id", paymentInstrument.Id); + + if (paymentInstrument._ReferenceOption.IsSet) + if (paymentInstrument.Reference != null) + writer.WriteString("reference", paymentInstrument.Reference); + + if (paymentInstrument._TokenTypeOption.IsSet) + if (paymentInstrument.TokenType != null) + writer.WriteString("tokenType", paymentInstrument.TokenType); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/PlatformPayment.cs b/Adyen/TransferWebhooks/Models/PlatformPayment.cs new file mode 100644 index 000000000..8315786b6 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/PlatformPayment.cs @@ -0,0 +1,640 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// PlatformPayment. + /// + public partial class PlatformPayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// The payment's merchant reference included in the transfer. + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// The payment reference included in the transfer. + /// **platformPayment** (default to TypeEnum.PlatformPayment) + [JsonConstructor] + public PlatformPayment(Option modificationMerchantReference = default, Option modificationPspReference = default, Option paymentMerchantReference = default, Option platformPaymentType = default, Option pspPaymentReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _PaymentMerchantReferenceOption = paymentMerchantReference; + _PlatformPaymentTypeOption = platformPaymentType; + _PspPaymentReferenceOption = pspPaymentReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformPayment() + { + } + + partial void OnCreated(); + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonConverter(typeof(PlatformPaymentTypeEnumJsonConverter))] + public class PlatformPaymentTypeEnum : IEnum + { + /// + /// Returns the value of the PlatformPaymentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PlatformPaymentTypeEnum.AcquiringFees - AcquiringFees + /// + public static readonly PlatformPaymentTypeEnum AcquiringFees = new("AcquiringFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenCommission - AdyenCommission + /// + public static readonly PlatformPaymentTypeEnum AdyenCommission = new("AdyenCommission"); + + /// + /// PlatformPaymentTypeEnum.AdyenFees - AdyenFees + /// + public static readonly PlatformPaymentTypeEnum AdyenFees = new("AdyenFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenMarkup - AdyenMarkup + /// + public static readonly PlatformPaymentTypeEnum AdyenMarkup = new("AdyenMarkup"); + + /// + /// PlatformPaymentTypeEnum.BalanceAccount - BalanceAccount + /// + public static readonly PlatformPaymentTypeEnum BalanceAccount = new("BalanceAccount"); + + /// + /// PlatformPaymentTypeEnum.ChargebackRemainder - ChargebackRemainder + /// + public static readonly PlatformPaymentTypeEnum ChargebackRemainder = new("ChargebackRemainder"); + + /// + /// PlatformPaymentTypeEnum.Commission - Commission + /// + public static readonly PlatformPaymentTypeEnum Commission = new("Commission"); + + /// + /// PlatformPaymentTypeEnum.DCCPlatformCommission - DCCPlatformCommission + /// + public static readonly PlatformPaymentTypeEnum DCCPlatformCommission = new("DCCPlatformCommission"); + + /// + /// PlatformPaymentTypeEnum.Default - Default + /// + public static readonly PlatformPaymentTypeEnum Default = new("Default"); + + /// + /// PlatformPaymentTypeEnum.Interchange - Interchange + /// + public static readonly PlatformPaymentTypeEnum Interchange = new("Interchange"); + + /// + /// PlatformPaymentTypeEnum.PaymentFee - PaymentFee + /// + public static readonly PlatformPaymentTypeEnum PaymentFee = new("PaymentFee"); + + /// + /// PlatformPaymentTypeEnum.Remainder - Remainder + /// + public static readonly PlatformPaymentTypeEnum Remainder = new("Remainder"); + + /// + /// PlatformPaymentTypeEnum.SchemeFee - SchemeFee + /// + public static readonly PlatformPaymentTypeEnum SchemeFee = new("SchemeFee"); + + /// + /// PlatformPaymentTypeEnum.Surcharge - Surcharge + /// + public static readonly PlatformPaymentTypeEnum Surcharge = new("Surcharge"); + + /// + /// PlatformPaymentTypeEnum.Tip - Tip + /// + public static readonly PlatformPaymentTypeEnum Tip = new("Tip"); + + /// + /// PlatformPaymentTypeEnum.TopUp - TopUp + /// + public static readonly PlatformPaymentTypeEnum TopUp = new("TopUp"); + + /// + /// PlatformPaymentTypeEnum.VAT - VAT + /// + public static readonly PlatformPaymentTypeEnum VAT = new("VAT"); + + private PlatformPaymentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlatformPaymentTypeEnum?(string? value) => value == null ? null : new PlatformPaymentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlatformPaymentTypeEnum? option) => option?.Value; + + public static bool operator ==(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlatformPaymentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlatformPaymentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "AcquiringFees" => PlatformPaymentTypeEnum.AcquiringFees, + "AdyenCommission" => PlatformPaymentTypeEnum.AdyenCommission, + "AdyenFees" => PlatformPaymentTypeEnum.AdyenFees, + "AdyenMarkup" => PlatformPaymentTypeEnum.AdyenMarkup, + "BalanceAccount" => PlatformPaymentTypeEnum.BalanceAccount, + "ChargebackRemainder" => PlatformPaymentTypeEnum.ChargebackRemainder, + "Commission" => PlatformPaymentTypeEnum.Commission, + "DCCPlatformCommission" => PlatformPaymentTypeEnum.DCCPlatformCommission, + "Default" => PlatformPaymentTypeEnum.Default, + "Interchange" => PlatformPaymentTypeEnum.Interchange, + "PaymentFee" => PlatformPaymentTypeEnum.PaymentFee, + "Remainder" => PlatformPaymentTypeEnum.Remainder, + "SchemeFee" => PlatformPaymentTypeEnum.SchemeFee, + "Surcharge" => PlatformPaymentTypeEnum.Surcharge, + "Tip" => PlatformPaymentTypeEnum.Tip, + "TopUp" => PlatformPaymentTypeEnum.TopUp, + "VAT" => PlatformPaymentTypeEnum.VAT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlatformPaymentTypeEnum? value) + { + if (value == null) + return null; + + if (value == PlatformPaymentTypeEnum.AcquiringFees) + return "AcquiringFees"; + + if (value == PlatformPaymentTypeEnum.AdyenCommission) + return "AdyenCommission"; + + if (value == PlatformPaymentTypeEnum.AdyenFees) + return "AdyenFees"; + + if (value == PlatformPaymentTypeEnum.AdyenMarkup) + return "AdyenMarkup"; + + if (value == PlatformPaymentTypeEnum.BalanceAccount) + return "BalanceAccount"; + + if (value == PlatformPaymentTypeEnum.ChargebackRemainder) + return "ChargebackRemainder"; + + if (value == PlatformPaymentTypeEnum.Commission) + return "Commission"; + + if (value == PlatformPaymentTypeEnum.DCCPlatformCommission) + return "DCCPlatformCommission"; + + if (value == PlatformPaymentTypeEnum.Default) + return "Default"; + + if (value == PlatformPaymentTypeEnum.Interchange) + return "Interchange"; + + if (value == PlatformPaymentTypeEnum.PaymentFee) + return "PaymentFee"; + + if (value == PlatformPaymentTypeEnum.Remainder) + return "Remainder"; + + if (value == PlatformPaymentTypeEnum.SchemeFee) + return "SchemeFee"; + + if (value == PlatformPaymentTypeEnum.Surcharge) + return "Surcharge"; + + if (value == PlatformPaymentTypeEnum.Tip) + return "Tip"; + + if (value == PlatformPaymentTypeEnum.TopUp) + return "TopUp"; + + if (value == PlatformPaymentTypeEnum.VAT) + return "VAT"; + + return null; + } + + /// + /// JsonConverter for writing PlatformPaymentTypeEnum. + /// + public class PlatformPaymentTypeEnumJsonConverter : JsonConverter + { + public override PlatformPaymentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlatformPaymentTypeEnum.FromStringOrDefault(value) ?? new PlatformPaymentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlatformPaymentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlatformPaymentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentTypeOption { get; private set; } + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonPropertyName("platformPaymentType")] + public PlatformPaymentTypeEnum? PlatformPaymentType { get { return this._PlatformPaymentTypeOption; } set { this._PlatformPaymentTypeOption = new(value); } } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlatformPayment - platformPayment + /// + public static readonly TypeEnum PlatformPayment = new("platformPayment"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "platformPayment" => TypeEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMerchantReferenceOption { get; private set; } + + /// + /// The payment's merchant reference included in the transfer. + /// + /// The payment's merchant reference included in the transfer. + [JsonPropertyName("paymentMerchantReference")] + public string? PaymentMerchantReference { get { return this._PaymentMerchantReferenceOption; } set { this._PaymentMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspPaymentReferenceOption { get; private set; } + + /// + /// The payment reference included in the transfer. + /// + /// The payment reference included in the transfer. + [JsonPropertyName("pspPaymentReference")] + public string? PspPaymentReference { get { return this._PspPaymentReferenceOption; } set { this._PspPaymentReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformPayment {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" PaymentMerchantReference: ").Append(PaymentMerchantReference).Append("\n"); + sb.Append(" PlatformPaymentType: ").Append(PlatformPaymentType).Append("\n"); + sb.Append(" PspPaymentReference: ").Append(PspPaymentReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformPaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformPayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option paymentMerchantReference = default; + Option platformPaymentType = default; + Option pspPaymentReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMerchantReference": + paymentMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentType": + string? platformPaymentTypeRawValue = utf8JsonReader.GetString(); + platformPaymentType = new Option(PlatformPayment.PlatformPaymentTypeEnum.FromStringOrDefault(platformPaymentTypeRawValue)); + break; + case "pspPaymentReference": + pspPaymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PlatformPayment.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PlatformPayment(modificationMerchantReference, modificationPspReference, paymentMerchantReference, platformPaymentType, pspPaymentReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformPayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformPayment._ModificationMerchantReferenceOption.IsSet) + if (platformPayment.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", platformPayment.ModificationMerchantReference); + + if (platformPayment._ModificationPspReferenceOption.IsSet) + if (platformPayment.ModificationPspReference != null) + writer.WriteString("modificationPspReference", platformPayment.ModificationPspReference); + + if (platformPayment._PaymentMerchantReferenceOption.IsSet) + if (platformPayment.PaymentMerchantReference != null) + writer.WriteString("paymentMerchantReference", platformPayment.PaymentMerchantReference); + + if (platformPayment._PlatformPaymentTypeOption.IsSet && platformPayment.PlatformPaymentType != null) + { + string? platformPaymentTypeRawValue = PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPayment._PlatformPaymentTypeOption.Value!.Value); + writer.WriteString("platformPaymentType", platformPaymentTypeRawValue); + } + + if (platformPayment._PspPaymentReferenceOption.IsSet) + if (platformPayment.PspPaymentReference != null) + writer.WriteString("pspPaymentReference", platformPayment.PspPaymentReference); + + if (platformPayment._TypeOption.IsSet && platformPayment.Type != null) + { + string? typeRawValue = PlatformPayment.TypeEnum.ToJsonValue(platformPayment._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/RelayedAuthorisationData.cs b/Adyen/TransferWebhooks/Models/RelayedAuthorisationData.cs new file mode 100644 index 000000000..0777c4b16 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/RelayedAuthorisationData.cs @@ -0,0 +1,203 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// RelayedAuthorisationData. + /// + public partial class RelayedAuthorisationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// Your reference for the relayed authorisation data. + [JsonConstructor] + public RelayedAuthorisationData(Option?> metadata = default, Option reference = default) + { + _MetadataOption = metadata; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RelayedAuthorisationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the relayed authorisation data. + /// + /// Your reference for the relayed authorisation data. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RelayedAuthorisationData {\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RelayedAuthorisationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RelayedAuthorisationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> metadata = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RelayedAuthorisationData(metadata, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, relayedAuthorisationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (relayedAuthorisationData._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, relayedAuthorisationData.Metadata, jsonSerializerOptions); + } + if (relayedAuthorisationData._ReferenceOption.IsSet) + if (relayedAuthorisationData.Reference != null) + writer.WriteString("reference", relayedAuthorisationData.Reference); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/Resource.cs b/Adyen/TransferWebhooks/Models/Resource.cs new file mode 100644 index 000000000..839858e82 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/Resource.cs @@ -0,0 +1,231 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Resource. + /// + public partial class Resource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the balance platform. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The ID of the resource. + [JsonConstructor] + public Resource(Option balancePlatform = default, Option creationDate = default, Option id = default) + { + _BalancePlatformOption = balancePlatform; + _CreationDateOption = creationDate; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Resource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Resource {\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Resource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balancePlatform = default; + Option creationDate = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Resource(balancePlatform, creationDate, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Resource resource, JsonSerializerOptions jsonSerializerOptions) + { + + if (resource._BalancePlatformOption.IsSet) + if (resource.BalancePlatform != null) + writer.WriteString("balancePlatform", resource.BalancePlatform); + + if (resource._CreationDateOption.IsSet) + writer.WriteString("creationDate", resource._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (resource._IdOption.IsSet) + if (resource.Id != null) + writer.WriteString("id", resource.Id); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/ResourceReference.cs b/Adyen/TransferWebhooks/Models/ResourceReference.cs new file mode 100644 index 000000000..293eb8d22 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/SELocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/SELocalAccountIdentification.cs new file mode 100644 index 000000000..d3a0befe3 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/SELocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// SELocalAccountIdentification. + /// + public partial class SELocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// **seLocal** (default to TypeEnum.SeLocal) + [JsonConstructor] + public SELocalAccountIdentification(string accountNumber, string clearingNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingNumber = clearingNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SELocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SeLocal - seLocal + /// + public static readonly TypeEnum SeLocal = new("seLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "seLocal" => TypeEnum.SeLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SeLocal) + return "seLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + [JsonPropertyName("clearingNumber")] + public string ClearingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SELocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingNumber: ").Append(ClearingNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 7) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 7.", new [] { "AccountNumber" }); + } + + // ClearingNumber (string) maxLength + if (this.ClearingNumber != null && this.ClearingNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be less than 5.", new [] { "ClearingNumber" }); + } + + // ClearingNumber (string) minLength + if (this.ClearingNumber != null && this.ClearingNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be greater than 4.", new [] { "ClearingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SELocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SELocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingNumber": + clearingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SELocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(clearingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(type)); + + return new SELocalAccountIdentification(accountNumber.Value!, clearingNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sELocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sELocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sELocalAccountIdentification.AccountNumber); + + if (sELocalAccountIdentification.ClearingNumber != null) + writer.WriteString("clearingNumber", sELocalAccountIdentification.ClearingNumber); + + if (sELocalAccountIdentification.Type != null) + { + string? typeRawValue = SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/SGLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/SGLocalAccountIdentification.cs new file mode 100644 index 000000000..816e857bc --- /dev/null +++ b/Adyen/TransferWebhooks/Models/SGLocalAccountIdentification.cs @@ -0,0 +1,337 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// SGLocalAccountIdentification. + /// + public partial class SGLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// **sgLocal** (default to TypeEnum.SgLocal) + [JsonConstructor] + public SGLocalAccountIdentification(string accountNumber, string bic, Option type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SGLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SgLocal - sgLocal + /// + public static readonly TypeEnum SgLocal = new("sgLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sgLocal" => TypeEnum.SgLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SgLocal) + return "sgLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SGLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 19) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 19.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SGLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SGLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SGLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(bic)); + + return new SGLocalAccountIdentification(accountNumber.Value!, bic.Value!, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sGLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sGLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sGLocalAccountIdentification.AccountNumber); + + if (sGLocalAccountIdentification.Bic != null) + writer.WriteString("bic", sGLocalAccountIdentification.Bic); + + if (sGLocalAccountIdentification._TypeOption.IsSet && sGLocalAccountIdentification.Type != null) + { + string? typeRawValue = SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/ThreeDSecure.cs b/Adyen/TransferWebhooks/Models/ThreeDSecure.cs new file mode 100644 index 000000000..e2e670765 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/ThreeDSecure.cs @@ -0,0 +1,177 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// ThreeDSecure. + /// + public partial class ThreeDSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction identifier for the Access Control Server + [JsonConstructor] + public ThreeDSecure(Option acsTransactionId = default) + { + _AcsTransactionIdOption = acsTransactionId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsTransactionIdOption { get; private set; } + + /// + /// The transaction identifier for the Access Control Server + /// + /// The transaction identifier for the Access Control Server + [JsonPropertyName("acsTransactionId")] + public string? AcsTransactionId { get { return this._AcsTransactionIdOption; } set { this._AcsTransactionIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecure {\n"); + sb.Append(" AcsTransactionId: ").Append(AcsTransactionId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acsTransactionId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsTransactionId": + acsTransactionId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSecure(acsTransactionId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSecure._AcsTransactionIdOption.IsSet) + if (threeDSecure.AcsTransactionId != null) + writer.WriteString("acsTransactionId", threeDSecure.AcsTransactionId); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransactionEventViolation.cs b/Adyen/TransferWebhooks/Models/TransactionEventViolation.cs new file mode 100644 index 000000000..e63c71647 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransactionEventViolation.cs @@ -0,0 +1,228 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransactionEventViolation. + /// + public partial class TransactionEventViolation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An explanation about why the transaction rule failed. + /// transactionRule + /// transactionRuleSource + [JsonConstructor] + public TransactionEventViolation(Option reason = default, Option transactionRule = default, Option transactionRuleSource = default) + { + _ReasonOption = reason; + _TransactionRuleOption = transactionRule; + _TransactionRuleSourceOption = transactionRuleSource; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionEventViolation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// An explanation about why the transaction rule failed. + /// + /// An explanation about why the transaction rule failed. + [JsonPropertyName("reason")] + public string? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRule")] + public TransactionRuleReference? TransactionRule { get { return this._TransactionRuleOption; } set { this._TransactionRuleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRuleSource")] + public TransactionRuleSource? TransactionRuleSource { get { return this._TransactionRuleSourceOption; } set { this._TransactionRuleSourceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionEventViolation {\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" TransactionRule: ").Append(TransactionRule).Append("\n"); + sb.Append(" TransactionRuleSource: ").Append(TransactionRuleSource).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionEventViolationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionEventViolation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reason = default; + Option transactionRule = default; + Option transactionRuleSource = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reason": + reason = new Option(utf8JsonReader.GetString()!); + break; + case "transactionRule": + transactionRule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRuleSource": + transactionRuleSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionEventViolation(reason, transactionRule, transactionRuleSource); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionEventViolation transactionEventViolation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionEventViolation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionEventViolation transactionEventViolation, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionEventViolation._ReasonOption.IsSet) + if (transactionEventViolation.Reason != null) + writer.WriteString("reason", transactionEventViolation.Reason); + + if (transactionEventViolation._TransactionRuleOption.IsSet) + { + writer.WritePropertyName("transactionRule"); + JsonSerializer.Serialize(writer, transactionEventViolation.TransactionRule, jsonSerializerOptions); + } + if (transactionEventViolation._TransactionRuleSourceOption.IsSet) + { + writer.WritePropertyName("transactionRuleSource"); + JsonSerializer.Serialize(writer, transactionEventViolation.TransactionRuleSource, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransactionRuleReference.cs b/Adyen/TransferWebhooks/Models/TransactionRuleReference.cs new file mode 100644 index 000000000..419c763f1 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransactionRuleReference.cs @@ -0,0 +1,276 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransactionRuleReference. + /// + public partial class TransactionRuleReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The outcome type of the rule. + /// The reference for the resource. + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + [JsonConstructor] + public TransactionRuleReference(Option description = default, Option id = default, Option outcomeType = default, Option reference = default, Option score = default) + { + _DescriptionOption = description; + _IdOption = id; + _OutcomeTypeOption = outcomeType; + _ReferenceOption = reference; + _ScoreOption = score; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutcomeTypeOption { get; private set; } + + /// + /// The outcome type of the rule. + /// + /// The outcome type of the rule. + [JsonPropertyName("outcomeType")] + public string? OutcomeType { get { return this._OutcomeTypeOption; } set { this._OutcomeTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + /// + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" OutcomeType: ").Append(OutcomeType).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option outcomeType = default; + Option reference = default; + Option score = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "outcomeType": + outcomeType = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new TransactionRuleReference(description, id, outcomeType, reference, score); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleReference transactionRuleReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleReference transactionRuleReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleReference._DescriptionOption.IsSet) + if (transactionRuleReference.Description != null) + writer.WriteString("description", transactionRuleReference.Description); + + if (transactionRuleReference._IdOption.IsSet) + if (transactionRuleReference.Id != null) + writer.WriteString("id", transactionRuleReference.Id); + + if (transactionRuleReference._OutcomeTypeOption.IsSet) + if (transactionRuleReference.OutcomeType != null) + writer.WriteString("outcomeType", transactionRuleReference.OutcomeType); + + if (transactionRuleReference._ReferenceOption.IsSet) + if (transactionRuleReference.Reference != null) + writer.WriteString("reference", transactionRuleReference.Reference); + + if (transactionRuleReference._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRuleReference._ScoreOption.Value!.Value); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransactionRuleSource.cs b/Adyen/TransferWebhooks/Models/TransactionRuleSource.cs new file mode 100644 index 000000000..8c7372a02 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransactionRuleSource.cs @@ -0,0 +1,202 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransactionRuleSource. + /// + public partial class TransactionRuleSource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ID of the resource, when applicable. + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonConstructor] + public TransactionRuleSource(Option id = default, Option type = default) + { + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleSource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// ID of the resource, when applicable. + /// + /// ID of the resource, when applicable. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleSource {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleSourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleSource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransactionRuleSource(id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleSource transactionRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleSource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleSource transactionRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleSource._IdOption.IsSet) + if (transactionRuleSource.Id != null) + writer.WriteString("id", transactionRuleSource.Id); + + if (transactionRuleSource._TypeOption.IsSet) + if (transactionRuleSource.Type != null) + writer.WriteString("type", transactionRuleSource.Type); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransactionRulesResult.cs b/Adyen/TransferWebhooks/Models/TransactionRulesResult.cs new file mode 100644 index 000000000..c0c5f0b89 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransactionRulesResult.cs @@ -0,0 +1,252 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransactionRulesResult. + /// + public partial class TransactionRulesResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The advice given by the Risk analysis. + /// Indicates whether the transaction passed the evaluation for all hardblock rules + /// The score of the Risk analysis. + /// Array containing all the transaction rules that the transaction triggered. + [JsonConstructor] + public TransactionRulesResult(Option advice = default, Option allHardBlockRulesPassed = default, Option score = default, Option?> triggeredTransactionRules = default) + { + _AdviceOption = advice; + _AllHardBlockRulesPassedOption = allHardBlockRulesPassed; + _ScoreOption = score; + _TriggeredTransactionRulesOption = triggeredTransactionRules; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRulesResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdviceOption { get; private set; } + + /// + /// The advice given by the Risk analysis. + /// + /// The advice given by the Risk analysis. + [JsonPropertyName("advice")] + public string? Advice { get { return this._AdviceOption; } set { this._AdviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllHardBlockRulesPassedOption { get; private set; } + + /// + /// Indicates whether the transaction passed the evaluation for all hardblock rules + /// + /// Indicates whether the transaction passed the evaluation for all hardblock rules + [JsonPropertyName("allHardBlockRulesPassed")] + public bool? AllHardBlockRulesPassed { get { return this._AllHardBlockRulesPassedOption; } set { this._AllHardBlockRulesPassedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The score of the Risk analysis. + /// + /// The score of the Risk analysis. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TriggeredTransactionRulesOption { get; private set; } + + /// + /// Array containing all the transaction rules that the transaction triggered. + /// + /// Array containing all the transaction rules that the transaction triggered. + [JsonPropertyName("triggeredTransactionRules")] + public List? TriggeredTransactionRules { get { return this._TriggeredTransactionRulesOption; } set { this._TriggeredTransactionRulesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRulesResult {\n"); + sb.Append(" Advice: ").Append(Advice).Append("\n"); + sb.Append(" AllHardBlockRulesPassed: ").Append(AllHardBlockRulesPassed).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append(" TriggeredTransactionRules: ").Append(TriggeredTransactionRules).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRulesResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRulesResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option advice = default; + Option allHardBlockRulesPassed = default; + Option score = default; + Option?> triggeredTransactionRules = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "advice": + advice = new Option(utf8JsonReader.GetString()!); + break; + case "allHardBlockRulesPassed": + allHardBlockRulesPassed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "triggeredTransactionRules": + triggeredTransactionRules = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionRulesResult(advice, allHardBlockRulesPassed, score, triggeredTransactionRules); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRulesResult transactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRulesResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRulesResult transactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRulesResult._AdviceOption.IsSet) + if (transactionRulesResult.Advice != null) + writer.WriteString("advice", transactionRulesResult.Advice); + + if (transactionRulesResult._AllHardBlockRulesPassedOption.IsSet) + writer.WriteBoolean("allHardBlockRulesPassed", transactionRulesResult._AllHardBlockRulesPassedOption.Value!.Value); + + if (transactionRulesResult._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRulesResult._ScoreOption.Value!.Value); + + if (transactionRulesResult._TriggeredTransactionRulesOption.IsSet) + { + writer.WritePropertyName("triggeredTransactionRules"); + JsonSerializer.Serialize(writer, transactionRulesResult.TriggeredTransactionRules, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferData.cs b/Adyen/TransferWebhooks/Models/TransferData.cs new file mode 100644 index 000000000..9d115b8af --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferData.cs @@ -0,0 +1,2563 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferData. + /// + public partial class TransferData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// accountHolder + /// balanceAccount + /// The unique identifier of the balance platform. + /// The list of the latest balance statuses in the transfer. + /// categoryData + /// counterparty + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// directDebitInformation + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + /// The list of events leading up to the current status of the transfer. + /// executionDate + /// externalReason + /// The ID of the resource. + /// paymentInstrument + /// Additional information about the status of the transfer. + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// review + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + /// tracking + /// transactionRulesResult + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonConstructor] + public TransferData(Amount amount, CategoryEnum category, StatusEnum status, Option accountHolder = default, Option balanceAccount = default, Option balancePlatform = default, Option?> balances = default, Option categoryData = default, Option counterparty = default, Option createdAt = default, Option creationDate = default, Option description = default, Option directDebitInformation = default, Option direction = default, Option eventId = default, Option?> events = default, Option executionDate = default, Option externalReason = default, Option id = default, Option paymentInstrument = default, Option reason = default, Option reference = default, Option referenceForBeneficiary = default, Option review = default, Option sequenceNumber = default, Option tracking = default, Option transactionRulesResult = default, Option type = default, Option updatedAt = default) + { + Amount = amount; + Category = category; + Status = status; + _AccountHolderOption = accountHolder; + _BalanceAccountOption = balanceAccount; + _BalancePlatformOption = balancePlatform; + _BalancesOption = balances; + _CategoryDataOption = categoryData; + _CounterpartyOption = counterparty; + _CreatedAtOption = createdAt; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _DirectDebitInformationOption = directDebitInformation; + _DirectionOption = direction; + _EventIdOption = eventId; + _EventsOption = events; + _ExecutionDateOption = executionDate; + _ExternalReasonOption = externalReason; + _IdOption = id; + _PaymentInstrumentOption = paymentInstrument; + _ReasonOption = reason; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _ReviewOption = review; + _SequenceNumberOption = sequenceNumber; + _TrackingOption = tracking; + _TransactionRulesResultOption = transactionRulesResult; + _TypeOption = type; + _UpdatedAtOption = updatedAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferData() + { + } + + partial void OnCreated(); + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Card - card + /// + public static readonly CategoryEnum Card = new("card"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.IssuedCard - issuedCard + /// + public static readonly CategoryEnum IssuedCard = new("issuedCard"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + /// + /// CategoryEnum.TopUp - topUp + /// + public static readonly CategoryEnum TopUp = new("topUp"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "card" => CategoryEnum.Card, + "internal" => CategoryEnum.Internal, + "issuedCard" => CategoryEnum.IssuedCard, + "platformPayment" => CategoryEnum.PlatformPayment, + "topUp" => CategoryEnum.TopUp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Card) + return "card"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.IssuedCard) + return "issuedCard"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + if (value == CategoryEnum.TopUp) + return "topUp"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonPropertyName("category")] + public CategoryEnum Category { get; set; } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonConverter(typeof(DirectionEnumJsonConverter))] + public class DirectionEnum : IEnum + { + /// + /// Returns the value of the DirectionEnum. + /// + public string? Value { get; set; } + + /// + /// DirectionEnum.Incoming - incoming + /// + public static readonly DirectionEnum Incoming = new("incoming"); + + /// + /// DirectionEnum.Outgoing - outgoing + /// + public static readonly DirectionEnum Outgoing = new("outgoing"); + + private DirectionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DirectionEnum?(string? value) => value == null ? null : new DirectionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DirectionEnum? option) => option?.Value; + + public static bool operator ==(DirectionEnum? left, DirectionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DirectionEnum? left, DirectionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DirectionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DirectionEnum? FromStringOrDefault(string value) + { + return value switch { + "incoming" => DirectionEnum.Incoming, + "outgoing" => DirectionEnum.Outgoing, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DirectionEnum? value) + { + if (value == null) + return null; + + if (value == DirectionEnum.Incoming) + return "incoming"; + + if (value == DirectionEnum.Outgoing) + return "outgoing"; + + return null; + } + + /// + /// JsonConverter for writing DirectionEnum. + /// + public class DirectionEnumJsonConverter : JsonConverter + { + public override DirectionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DirectionEnum.FromStringOrDefault(value) ?? new DirectionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DirectionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DirectionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectionOption { get; private set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonPropertyName("direction")] + public DirectionEnum? Direction { get { return this._DirectionOption; } set { this._DirectionOption = new(value); } } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Payment - payment + /// + public static readonly TypeEnum Payment = new("payment"); + + /// + /// TypeEnum.Capture - capture + /// + public static readonly TypeEnum Capture = new("capture"); + + /// + /// TypeEnum.CaptureReversal - captureReversal + /// + public static readonly TypeEnum CaptureReversal = new("captureReversal"); + + /// + /// TypeEnum.Refund - refund + /// + public static readonly TypeEnum Refund = new("refund"); + + /// + /// TypeEnum.RefundReversal - refundReversal + /// + public static readonly TypeEnum RefundReversal = new("refundReversal"); + + /// + /// TypeEnum.Chargeback - chargeback + /// + public static readonly TypeEnum Chargeback = new("chargeback"); + + /// + /// TypeEnum.ChargebackCorrection - chargebackCorrection + /// + public static readonly TypeEnum ChargebackCorrection = new("chargebackCorrection"); + + /// + /// TypeEnum.ChargebackReversal - chargebackReversal + /// + public static readonly TypeEnum ChargebackReversal = new("chargebackReversal"); + + /// + /// TypeEnum.ChargebackReversalCorrection - chargebackReversalCorrection + /// + public static readonly TypeEnum ChargebackReversalCorrection = new("chargebackReversalCorrection"); + + /// + /// TypeEnum.SecondChargeback - secondChargeback + /// + public static readonly TypeEnum SecondChargeback = new("secondChargeback"); + + /// + /// TypeEnum.SecondChargebackCorrection - secondChargebackCorrection + /// + public static readonly TypeEnum SecondChargebackCorrection = new("secondChargebackCorrection"); + + /// + /// TypeEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly TypeEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// TypeEnum.AtmWithdrawalReversal - atmWithdrawalReversal + /// + public static readonly TypeEnum AtmWithdrawalReversal = new("atmWithdrawalReversal"); + + /// + /// TypeEnum.InternalTransfer - internalTransfer + /// + public static readonly TypeEnum InternalTransfer = new("internalTransfer"); + + /// + /// TypeEnum.InternalDirectDebit - internalDirectDebit + /// + public static readonly TypeEnum InternalDirectDebit = new("internalDirectDebit"); + + /// + /// TypeEnum.ManualCorrection - manualCorrection + /// + public static readonly TypeEnum ManualCorrection = new("manualCorrection"); + + /// + /// TypeEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly TypeEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// TypeEnum.DepositCorrection - depositCorrection + /// + public static readonly TypeEnum DepositCorrection = new("depositCorrection"); + + /// + /// TypeEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly TypeEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + /// + /// TypeEnum.BankDirectDebit - bankDirectDebit + /// + public static readonly TypeEnum BankDirectDebit = new("bankDirectDebit"); + + /// + /// TypeEnum.CardTransfer - cardTransfer + /// + public static readonly TypeEnum CardTransfer = new("cardTransfer"); + + /// + /// TypeEnum.MiscCost - miscCost + /// + public static readonly TypeEnum MiscCost = new("miscCost"); + + /// + /// TypeEnum.PaymentCost - paymentCost + /// + public static readonly TypeEnum PaymentCost = new("paymentCost"); + + /// + /// TypeEnum.Fee - fee + /// + public static readonly TypeEnum Fee = new("fee"); + + /// + /// TypeEnum.Leftover - leftover + /// + public static readonly TypeEnum Leftover = new("leftover"); + + /// + /// TypeEnum.Grant - grant + /// + public static readonly TypeEnum Grant = new("grant"); + + /// + /// TypeEnum.CapitalFundsCollection - capitalFundsCollection + /// + public static readonly TypeEnum CapitalFundsCollection = new("capitalFundsCollection"); + + /// + /// TypeEnum.CashOutInstruction - cashOutInstruction + /// + public static readonly TypeEnum CashOutInstruction = new("cashOutInstruction"); + + /// + /// TypeEnum.CashoutFee - cashoutFee + /// + public static readonly TypeEnum CashoutFee = new("cashoutFee"); + + /// + /// TypeEnum.CashoutRepayment - cashoutRepayment + /// + public static readonly TypeEnum CashoutRepayment = new("cashoutRepayment"); + + /// + /// TypeEnum.CashoutFunding - cashoutFunding + /// + public static readonly TypeEnum CashoutFunding = new("cashoutFunding"); + + /// + /// TypeEnum.Repayment - repayment + /// + public static readonly TypeEnum Repayment = new("repayment"); + + /// + /// TypeEnum.Installment - installment + /// + public static readonly TypeEnum Installment = new("installment"); + + /// + /// TypeEnum.InstallmentReversal - installmentReversal + /// + public static readonly TypeEnum InstallmentReversal = new("installmentReversal"); + + /// + /// TypeEnum.BalanceAdjustment - balanceAdjustment + /// + public static readonly TypeEnum BalanceAdjustment = new("balanceAdjustment"); + + /// + /// TypeEnum.BalanceRollover - balanceRollover + /// + public static readonly TypeEnum BalanceRollover = new("balanceRollover"); + + /// + /// TypeEnum.BalanceMigration - balanceMigration + /// + public static readonly TypeEnum BalanceMigration = new("balanceMigration"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "payment" => TypeEnum.Payment, + "capture" => TypeEnum.Capture, + "captureReversal" => TypeEnum.CaptureReversal, + "refund" => TypeEnum.Refund, + "refundReversal" => TypeEnum.RefundReversal, + "chargeback" => TypeEnum.Chargeback, + "chargebackCorrection" => TypeEnum.ChargebackCorrection, + "chargebackReversal" => TypeEnum.ChargebackReversal, + "chargebackReversalCorrection" => TypeEnum.ChargebackReversalCorrection, + "secondChargeback" => TypeEnum.SecondChargeback, + "secondChargebackCorrection" => TypeEnum.SecondChargebackCorrection, + "atmWithdrawal" => TypeEnum.AtmWithdrawal, + "atmWithdrawalReversal" => TypeEnum.AtmWithdrawalReversal, + "internalTransfer" => TypeEnum.InternalTransfer, + "internalDirectDebit" => TypeEnum.InternalDirectDebit, + "manualCorrection" => TypeEnum.ManualCorrection, + "invoiceDeduction" => TypeEnum.InvoiceDeduction, + "depositCorrection" => TypeEnum.DepositCorrection, + "reserveAdjustment" => TypeEnum.ReserveAdjustment, + "bankTransfer" => TypeEnum.BankTransfer, + "bankDirectDebit" => TypeEnum.BankDirectDebit, + "cardTransfer" => TypeEnum.CardTransfer, + "miscCost" => TypeEnum.MiscCost, + "paymentCost" => TypeEnum.PaymentCost, + "fee" => TypeEnum.Fee, + "leftover" => TypeEnum.Leftover, + "grant" => TypeEnum.Grant, + "capitalFundsCollection" => TypeEnum.CapitalFundsCollection, + "cashOutInstruction" => TypeEnum.CashOutInstruction, + "cashoutFee" => TypeEnum.CashoutFee, + "cashoutRepayment" => TypeEnum.CashoutRepayment, + "cashoutFunding" => TypeEnum.CashoutFunding, + "repayment" => TypeEnum.Repayment, + "installment" => TypeEnum.Installment, + "installmentReversal" => TypeEnum.InstallmentReversal, + "balanceAdjustment" => TypeEnum.BalanceAdjustment, + "balanceRollover" => TypeEnum.BalanceRollover, + "balanceMigration" => TypeEnum.BalanceMigration, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Payment) + return "payment"; + + if (value == TypeEnum.Capture) + return "capture"; + + if (value == TypeEnum.CaptureReversal) + return "captureReversal"; + + if (value == TypeEnum.Refund) + return "refund"; + + if (value == TypeEnum.RefundReversal) + return "refundReversal"; + + if (value == TypeEnum.Chargeback) + return "chargeback"; + + if (value == TypeEnum.ChargebackCorrection) + return "chargebackCorrection"; + + if (value == TypeEnum.ChargebackReversal) + return "chargebackReversal"; + + if (value == TypeEnum.ChargebackReversalCorrection) + return "chargebackReversalCorrection"; + + if (value == TypeEnum.SecondChargeback) + return "secondChargeback"; + + if (value == TypeEnum.SecondChargebackCorrection) + return "secondChargebackCorrection"; + + if (value == TypeEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == TypeEnum.AtmWithdrawalReversal) + return "atmWithdrawalReversal"; + + if (value == TypeEnum.InternalTransfer) + return "internalTransfer"; + + if (value == TypeEnum.InternalDirectDebit) + return "internalDirectDebit"; + + if (value == TypeEnum.ManualCorrection) + return "manualCorrection"; + + if (value == TypeEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == TypeEnum.DepositCorrection) + return "depositCorrection"; + + if (value == TypeEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == TypeEnum.BankDirectDebit) + return "bankDirectDebit"; + + if (value == TypeEnum.CardTransfer) + return "cardTransfer"; + + if (value == TypeEnum.MiscCost) + return "miscCost"; + + if (value == TypeEnum.PaymentCost) + return "paymentCost"; + + if (value == TypeEnum.Fee) + return "fee"; + + if (value == TypeEnum.Leftover) + return "leftover"; + + if (value == TypeEnum.Grant) + return "grant"; + + if (value == TypeEnum.CapitalFundsCollection) + return "capitalFundsCollection"; + + if (value == TypeEnum.CashOutInstruction) + return "cashOutInstruction"; + + if (value == TypeEnum.CashoutFee) + return "cashoutFee"; + + if (value == TypeEnum.CashoutRepayment) + return "cashoutRepayment"; + + if (value == TypeEnum.CashoutFunding) + return "cashoutFunding"; + + if (value == TypeEnum.Repayment) + return "repayment"; + + if (value == TypeEnum.Installment) + return "installment"; + + if (value == TypeEnum.InstallmentReversal) + return "installmentReversal"; + + if (value == TypeEnum.BalanceAdjustment) + return "balanceAdjustment"; + + if (value == TypeEnum.BalanceRollover) + return "balanceRollover"; + + if (value == TypeEnum.BalanceMigration) + return "balanceMigration"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference? BalanceAccount { get { return this._BalanceAccountOption; } set { this._BalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BalancesOption { get; private set; } + + /// + /// The list of the latest balance statuses in the transfer. + /// + /// The list of the latest balance statuses in the transfer. + [JsonPropertyName("balances")] + public List? Balances { get { return this._BalancesOption; } set { this._BalancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("categoryData")] + public TransferDataCategoryData? CategoryData { get { return this._CategoryDataOption; } set { this._CategoryDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public TransferNotificationCounterParty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + [Obsolete("Deprecated since Transfer webhooks v3. Use createdAt or updatedAt")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectDebitInformationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("directDebitInformation")] + public DirectDebitInformation? DirectDebitInformation { get { return this._DirectDebitInformationOption; } set { this._DirectDebitInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EventIdOption { get; private set; } + + /// + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + /// + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + [JsonPropertyName("eventId")] + public string? EventId { get { return this._EventIdOption; } set { this._EventIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventsOption { get; private set; } + + /// + /// The list of events leading up to the current status of the transfer. + /// + /// The list of events leading up to the current status of the transfer. + [JsonPropertyName("events")] + public List? Events { get { return this._EventsOption; } set { this._EventsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecutionDateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("executionDate")] + public ExecutionDate? ExecutionDate { get { return this._ExecutionDateOption; } set { this._ExecutionDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReasonOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalReason")] + public ExternalReason? ExternalReason { get { return this._ExternalReasonOption; } set { this._ExternalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReviewOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("review")] + public TransferReview? Review { get { return this._ReviewOption; } set { this._ReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SequenceNumberOption { get; private set; } + + /// + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + /// + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + [JsonPropertyName("sequenceNumber")] + public int? SequenceNumber { get { return this._SequenceNumberOption; } set { this._SequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tracking")] + public TransferDataTracking? Tracking { get { return this._TrackingOption; } set { this._TrackingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRulesResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRulesResult")] + public TransactionRulesResult? TransactionRulesResult { get { return this._TransactionRulesResultOption; } set { this._TransactionRulesResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdatedAtOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("updatedAt")] + public DateTimeOffset? UpdatedAt { get { return this._UpdatedAtOption; } set { this._UpdatedAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferData {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" CategoryData: ").Append(CategoryData).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DirectDebitInformation: ").Append(DirectDebitInformation).Append("\n"); + sb.Append(" Direction: ").Append(Direction).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Events: ").Append(Events).Append("\n"); + sb.Append(" ExecutionDate: ").Append(ExecutionDate).Append("\n"); + sb.Append(" ExternalReason: ").Append(ExternalReason).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Review: ").Append(Review).Append("\n"); + sb.Append(" SequenceNumber: ").Append(SequenceNumber).Append("\n"); + sb.Append(" Tracking: ").Append(Tracking).Append("\n"); + sb.Append(" TransactionRulesResult: ").Append(TransactionRulesResult).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdatedAt. + /// + public static string UpdatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option category = default; + Option status = default; + Option accountHolder = default; + Option balanceAccount = default; + Option balancePlatform = default; + Option?> balances = default; + Option categoryData = default; + Option counterparty = default; + Option createdAt = default; + Option creationDate = default; + Option description = default; + Option directDebitInformation = default; + Option direction = default; + Option eventId = default; + Option?> events = default; + Option executionDate = default; + Option externalReason = default; + Option id = default; + Option paymentInstrument = default; + Option reason = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option review = default; + Option sequenceNumber = default; + Option tracking = default; + Option transactionRulesResult = default; + Option type = default; + Option updatedAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(TransferData.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransferData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "balances": + balances = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "categoryData": + categoryData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "directDebitInformation": + directDebitInformation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "direction": + string? directionRawValue = utf8JsonReader.GetString(); + direction = new Option(TransferData.DirectionEnum.FromStringOrDefault(directionRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "events": + events = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "executionDate": + executionDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReason": + externalReason = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(TransferData.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "review": + review = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sequenceNumber": + sequenceNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "tracking": + tracking = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRulesResult": + transactionRulesResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "updatedAt": + updatedAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(amount)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(category)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(status)); + + return new TransferData(amount.Value!, category.Value!.Value!, status.Value!.Value!, accountHolder, balanceAccount, balancePlatform, balances, categoryData, counterparty, createdAt, creationDate, description, directDebitInformation, direction, eventId, events, executionDate, externalReason, id, paymentInstrument, reason, reference, referenceForBeneficiary, review, sequenceNumber, tracking, transactionRulesResult, type, updatedAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferData transferData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferData transferData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferData.Amount, jsonSerializerOptions); + if (transferData.Category != null) + { + string? categoryRawValue = TransferData.CategoryEnum.ToJsonValue(transferData.Category); + writer.WriteString("category", categoryRawValue); + } + + if (transferData.Status != null) + { + string? statusRawValue = TransferData.StatusEnum.ToJsonValue(transferData.Status); + writer.WriteString("status", statusRawValue); + } + + if (transferData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, transferData.AccountHolder, jsonSerializerOptions); + } + if (transferData._BalanceAccountOption.IsSet) + { + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, transferData.BalanceAccount, jsonSerializerOptions); + } + if (transferData._BalancePlatformOption.IsSet) + if (transferData.BalancePlatform != null) + writer.WriteString("balancePlatform", transferData.BalancePlatform); + + if (transferData._BalancesOption.IsSet) + { + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, transferData.Balances, jsonSerializerOptions); + } + if (transferData._CategoryDataOption.IsSet) + { + writer.WritePropertyName("categoryData"); + JsonSerializer.Serialize(writer, transferData.CategoryData, jsonSerializerOptions); + } + if (transferData._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, transferData.Counterparty, jsonSerializerOptions); + } + if (transferData._CreatedAtOption.IsSet) + writer.WriteString("createdAt", transferData._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (transferData._CreationDateOption.IsSet) + writer.WriteString("creationDate", transferData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (transferData._DescriptionOption.IsSet) + if (transferData.Description != null) + writer.WriteString("description", transferData.Description); + + if (transferData._DirectDebitInformationOption.IsSet) + { + writer.WritePropertyName("directDebitInformation"); + JsonSerializer.Serialize(writer, transferData.DirectDebitInformation, jsonSerializerOptions); + } + if (transferData._DirectionOption.IsSet && transferData.Direction != null) + { + string? directionRawValue = TransferData.DirectionEnum.ToJsonValue(transferData._DirectionOption.Value!.Value); + writer.WriteString("direction", directionRawValue); + } + + if (transferData._EventIdOption.IsSet) + if (transferData.EventId != null) + writer.WriteString("eventId", transferData.EventId); + + if (transferData._EventsOption.IsSet) + { + writer.WritePropertyName("events"); + JsonSerializer.Serialize(writer, transferData.Events, jsonSerializerOptions); + } + if (transferData._ExecutionDateOption.IsSet) + { + writer.WritePropertyName("executionDate"); + JsonSerializer.Serialize(writer, transferData.ExecutionDate, jsonSerializerOptions); + } + if (transferData._ExternalReasonOption.IsSet) + { + writer.WritePropertyName("externalReason"); + JsonSerializer.Serialize(writer, transferData.ExternalReason, jsonSerializerOptions); + } + if (transferData._IdOption.IsSet) + if (transferData.Id != null) + writer.WriteString("id", transferData.Id); + + if (transferData._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, transferData.PaymentInstrument, jsonSerializerOptions); + } + if (transferData._ReasonOption.IsSet && transferData.Reason != null) + { + string? reasonRawValue = TransferData.ReasonEnum.ToJsonValue(transferData._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (transferData._ReferenceOption.IsSet) + if (transferData.Reference != null) + writer.WriteString("reference", transferData.Reference); + + if (transferData._ReferenceForBeneficiaryOption.IsSet) + if (transferData.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transferData.ReferenceForBeneficiary); + + if (transferData._ReviewOption.IsSet) + { + writer.WritePropertyName("review"); + JsonSerializer.Serialize(writer, transferData.Review, jsonSerializerOptions); + } + if (transferData._SequenceNumberOption.IsSet) + writer.WriteNumber("sequenceNumber", transferData._SequenceNumberOption.Value!.Value); + + if (transferData._TrackingOption.IsSet) + { + writer.WritePropertyName("tracking"); + JsonSerializer.Serialize(writer, transferData.Tracking, jsonSerializerOptions); + } + if (transferData._TransactionRulesResultOption.IsSet) + { + writer.WritePropertyName("transactionRulesResult"); + JsonSerializer.Serialize(writer, transferData.TransactionRulesResult, jsonSerializerOptions); + } + if (transferData._TypeOption.IsSet && transferData.Type != null) + { + string? typeRawValue = TransferData.TypeEnum.ToJsonValue(transferData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (transferData._UpdatedAtOption.IsSet) + writer.WriteString("updatedAt", transferData._UpdatedAtOption.Value!.Value.ToString(UpdatedAtFormat)); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferDataCategoryData.cs b/Adyen/TransferWebhooks/Models/TransferDataCategoryData.cs new file mode 100644 index 000000000..03ea4df06 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferDataCategoryData.cs @@ -0,0 +1,253 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// The relevant data according to the transfer category.. + /// + public partial class TransferDataCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataCategoryData(BankCategoryData bankCategoryData) + { + BankCategoryData = bankCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataCategoryData(InternalCategoryData internalCategoryData) + { + InternalCategoryData = internalCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataCategoryData(IssuedCard issuedCard) + { + IssuedCard = issuedCard; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataCategoryData(PlatformPayment platformPayment) + { + PlatformPayment = platformPayment; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public BankCategoryData? BankCategoryData { get; set; } + + /// + /// .. + /// + public InternalCategoryData? InternalCategoryData { get; set; } + + /// + /// .. + /// + public IssuedCard? IssuedCard { get; set; } + + /// + /// .. + /// + public PlatformPayment? PlatformPayment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferDataCategoryData {\n"); + if (this.BankCategoryData != null) + sb.Append(BankCategoryData.ToString().Replace("\n", "\n ")); + if (this.InternalCategoryData != null) + sb.Append(InternalCategoryData.ToString().Replace("\n", "\n ")); + if (this.IssuedCard != null) + sb.Append(IssuedCard.ToString().Replace("\n", "\n ")); + if (this.PlatformPayment != null) + sb.Append(PlatformPayment.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferDataCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferDataCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + BankCategoryData? bankCategoryData = default; + InternalCategoryData? internalCategoryData = default; + IssuedCard? issuedCard = default; + PlatformPayment? platformPayment = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderBankCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBankCategoryData, jsonSerializerOptions, out bankCategoryData); + + Utf8JsonReader utf8JsonReaderInternalCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalCategoryData, jsonSerializerOptions, out internalCategoryData); + + Utf8JsonReader utf8JsonReaderIssuedCard = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIssuedCard, jsonSerializerOptions, out issuedCard); + + Utf8JsonReader utf8JsonReaderPlatformPayment = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPlatformPayment, jsonSerializerOptions, out platformPayment); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (bankCategoryData?.Type != null) + return new TransferDataCategoryData(bankCategoryData); + + if (internalCategoryData?.Type != null) + return new TransferDataCategoryData(internalCategoryData); + + if (issuedCard?.Type != null) + return new TransferDataCategoryData(issuedCard); + + if (platformPayment?.Type != null) + return new TransferDataCategoryData(platformPayment); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferDataCategoryData transferDataCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + if (transferDataCategoryData.BankCategoryData != null) + JsonSerializer.Serialize(writer, transferDataCategoryData.BankCategoryData, jsonSerializerOptions); + if (transferDataCategoryData.InternalCategoryData != null) + JsonSerializer.Serialize(writer, transferDataCategoryData.InternalCategoryData, jsonSerializerOptions); + if (transferDataCategoryData.IssuedCard != null) + JsonSerializer.Serialize(writer, transferDataCategoryData.IssuedCard, jsonSerializerOptions); + if (transferDataCategoryData.PlatformPayment != null) + JsonSerializer.Serialize(writer, transferDataCategoryData.PlatformPayment, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferDataCategoryData, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferDataCategoryData transferDataCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferDataTracking.cs b/Adyen/TransferWebhooks/Models/TransferDataTracking.cs new file mode 100644 index 000000000..07255b29d --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferDataTracking.cs @@ -0,0 +1,227 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// The latest tracking information of the transfer.. + /// + public partial class TransferDataTracking : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(ConfirmationTrackingData confirmationTrackingData) + { + ConfirmationTrackingData = confirmationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(EstimationTrackingData estimationTrackingData) + { + EstimationTrackingData = estimationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(InternalReviewTrackingData internalReviewTrackingData) + { + InternalReviewTrackingData = internalReviewTrackingData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public ConfirmationTrackingData? ConfirmationTrackingData { get; set; } + + /// + /// .. + /// + public EstimationTrackingData? EstimationTrackingData { get; set; } + + /// + /// .. + /// + public InternalReviewTrackingData? InternalReviewTrackingData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferDataTracking {\n"); + if (this.ConfirmationTrackingData != null) + sb.Append(ConfirmationTrackingData.ToString().Replace("\n", "\n ")); + if (this.EstimationTrackingData != null) + sb.Append(EstimationTrackingData.ToString().Replace("\n", "\n ")); + if (this.InternalReviewTrackingData != null) + sb.Append(InternalReviewTrackingData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferDataTrackingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferDataTracking Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ConfirmationTrackingData? confirmationTrackingData = default; + EstimationTrackingData? estimationTrackingData = default; + InternalReviewTrackingData? internalReviewTrackingData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderConfirmationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderConfirmationTrackingData, jsonSerializerOptions, out confirmationTrackingData); + + Utf8JsonReader utf8JsonReaderEstimationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEstimationTrackingData, jsonSerializerOptions, out estimationTrackingData); + + Utf8JsonReader utf8JsonReaderInternalReviewTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalReviewTrackingData, jsonSerializerOptions, out internalReviewTrackingData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (confirmationTrackingData?.Type != null) + return new TransferDataTracking(confirmationTrackingData); + + if (estimationTrackingData?.Type != null) + return new TransferDataTracking(estimationTrackingData); + + if (internalReviewTrackingData?.Type != null) + return new TransferDataTracking(internalReviewTrackingData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferDataTracking transferDataTracking, JsonSerializerOptions jsonSerializerOptions) + { + if (transferDataTracking.ConfirmationTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.ConfirmationTrackingData, jsonSerializerOptions); + if (transferDataTracking.EstimationTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.EstimationTrackingData, jsonSerializerOptions); + if (transferDataTracking.InternalReviewTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.InternalReviewTrackingData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferDataTracking, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferDataTracking transferDataTracking, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferEvent.cs b/Adyen/TransferWebhooks/Models/TransferEvent.cs new file mode 100644 index 000000000..6e2aa0987 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferEvent.cs @@ -0,0 +1,1731 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferEvent. + /// + public partial class TransferEvent : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + /// The date when the transfer request was sent. + /// The estimated time when the beneficiary should have access to the funds. + /// A list of event data. + /// externalReason + /// The unique identifier of the transfer event. + /// modification + /// The list of balance mutations per event. + /// originalAmount + /// The reason for the transfer status. + /// The status of the transfer event. + /// trackingData + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// The date when the tracking status was updated. + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + [JsonConstructor] + public TransferEvent(Option amount = default, Option?> amountAdjustments = default, Option arn = default, Option bookingDate = default, Option estimatedArrivalTime = default, Option?> eventsData = default, Option externalReason = default, Option id = default, Option modification = default, Option?> mutations = default, Option originalAmount = default, Option reason = default, Option status = default, Option trackingData = default, Option transactionId = default, Option type = default, Option updateDate = default, Option valueDate = default) + { + _AmountOption = amount; + _AmountAdjustmentsOption = amountAdjustments; + _ArnOption = arn; + _BookingDateOption = bookingDate; + _EstimatedArrivalTimeOption = estimatedArrivalTime; + _EventsDataOption = eventsData; + _ExternalReasonOption = externalReason; + _IdOption = id; + _ModificationOption = modification; + _MutationsOption = mutations; + _OriginalAmountOption = originalAmount; + _ReasonOption = reason; + _StatusOption = status; + _TrackingDataOption = trackingData; + _TransactionIdOption = transactionId; + _TypeOption = type; + _UpdateDateOption = updateDate; + _ValueDateOption = valueDate; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferEvent() + { + } + + partial void OnCreated(); + + /// + /// The reason for the transfer status. + /// + /// The reason for the transfer status. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason for the transfer status. + /// + /// The reason for the transfer status. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Accounting - accounting + /// + public static readonly TypeEnum Accounting = new("accounting"); + + /// + /// TypeEnum.Tracking - tracking + /// + public static readonly TypeEnum Tracking = new("tracking"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "accounting" => TypeEnum.Accounting, + "tracking" => TypeEnum.Tracking, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Accounting) + return "accounting"; + + if (value == TypeEnum.Tracking) + return "tracking"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AmountAdjustmentsOption { get; private set; } + + /// + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + /// + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + [JsonPropertyName("amountAdjustments")] + public List? AmountAdjustments { get { return this._AmountAdjustmentsOption; } set { this._AmountAdjustmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ArnOption { get; private set; } + + /// + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + /// + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + [JsonPropertyName("arn")] + public string? Arn { get { return this._ArnOption; } set { this._ArnOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BookingDateOption { get; private set; } + + /// + /// The date when the transfer request was sent. + /// + /// The date when the transfer request was sent. + [JsonPropertyName("bookingDate")] + public DateTimeOffset? BookingDate { get { return this._BookingDateOption; } set { this._BookingDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EstimatedArrivalTimeOption { get; private set; } + + /// + /// The estimated time when the beneficiary should have access to the funds. + /// + /// The estimated time when the beneficiary should have access to the funds. + [JsonPropertyName("estimatedArrivalTime")] + public DateTimeOffset? EstimatedArrivalTime { get { return this._EstimatedArrivalTimeOption; } set { this._EstimatedArrivalTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventsDataOption { get; private set; } + + /// + /// A list of event data. + /// + /// A list of event data. + [JsonPropertyName("eventsData")] + public List? EventsData { get { return this._EventsDataOption; } set { this._EventsDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReasonOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalReason")] + public ExternalReason? ExternalReason { get { return this._ExternalReasonOption; } set { this._ExternalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the transfer event. + /// + /// The unique identifier of the transfer event. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("modification")] + public Modification? Modification { get { return this._ModificationOption; } set { this._ModificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MutationsOption { get; private set; } + + /// + /// The list of balance mutations per event. + /// + /// The list of balance mutations per event. + [JsonPropertyName("mutations")] + public List? Mutations { get { return this._MutationsOption; } set { this._MutationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("originalAmount")] + public Amount? OriginalAmount { get { return this._OriginalAmountOption; } set { this._OriginalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("trackingData")] + public TransferEventTrackingData? TrackingData { get { return this._TrackingDataOption; } set { this._TrackingDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionIdOption { get; private set; } + + /// + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + /// + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + [JsonPropertyName("transactionId")] + public string? TransactionId { get { return this._TransactionIdOption; } set { this._TransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdateDateOption { get; private set; } + + /// + /// The date when the tracking status was updated. + /// + /// The date when the tracking status was updated. + [JsonPropertyName("updateDate")] + public DateTimeOffset? UpdateDate { get { return this._UpdateDateOption; } set { this._UpdateDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueDateOption { get; private set; } + + /// + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + /// + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + [JsonPropertyName("valueDate")] + public DateTimeOffset? ValueDate { get { return this._ValueDateOption; } set { this._ValueDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEvent {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" AmountAdjustments: ").Append(AmountAdjustments).Append("\n"); + sb.Append(" Arn: ").Append(Arn).Append("\n"); + sb.Append(" BookingDate: ").Append(BookingDate).Append("\n"); + sb.Append(" EstimatedArrivalTime: ").Append(EstimatedArrivalTime).Append("\n"); + sb.Append(" EventsData: ").Append(EventsData).Append("\n"); + sb.Append(" ExternalReason: ").Append(ExternalReason).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Modification: ").Append(Modification).Append("\n"); + sb.Append(" Mutations: ").Append(Mutations).Append("\n"); + sb.Append(" OriginalAmount: ").Append(OriginalAmount).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TrackingData: ").Append(TrackingData).Append("\n"); + sb.Append(" TransactionId: ").Append(TransactionId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UpdateDate: ").Append(UpdateDate).Append("\n"); + sb.Append(" ValueDate: ").Append(ValueDate).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventJsonConverter : JsonConverter + { + /// + /// The format to use to serialize BookingDate. + /// + public static string BookingDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize EstimatedArrivalTime. + /// + public static string EstimatedArrivalTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdateDate. + /// + public static string UpdateDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValueDate. + /// + public static string ValueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEvent Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option?> amountAdjustments = default; + Option arn = default; + Option bookingDate = default; + Option estimatedArrivalTime = default; + Option?> eventsData = default; + Option externalReason = default; + Option id = default; + Option modification = default; + Option?> mutations = default; + Option originalAmount = default; + Option reason = default; + Option status = default; + Option trackingData = default; + Option transactionId = default; + Option type = default; + Option updateDate = default; + Option valueDate = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amountAdjustments": + amountAdjustments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "arn": + arn = new Option(utf8JsonReader.GetString()!); + break; + case "bookingDate": + bookingDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "estimatedArrivalTime": + estimatedArrivalTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "eventsData": + eventsData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReason": + externalReason = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "modification": + modification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mutations": + mutations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalAmount": + originalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(TransferEvent.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransferEvent.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "trackingData": + trackingData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionId": + transactionId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferEvent.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "updateDate": + updateDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "valueDate": + valueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new TransferEvent(amount, amountAdjustments, arn, bookingDate, estimatedArrivalTime, eventsData, externalReason, id, modification, mutations, originalAmount, reason, status, trackingData, transactionId, type, updateDate, valueDate); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEvent transferEvent, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferEvent, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEvent transferEvent, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferEvent._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferEvent.Amount, jsonSerializerOptions); + } + if (transferEvent._AmountAdjustmentsOption.IsSet) + { + writer.WritePropertyName("amountAdjustments"); + JsonSerializer.Serialize(writer, transferEvent.AmountAdjustments, jsonSerializerOptions); + } + if (transferEvent._ArnOption.IsSet) + if (transferEvent.Arn != null) + writer.WriteString("arn", transferEvent.Arn); + + if (transferEvent._BookingDateOption.IsSet) + writer.WriteString("bookingDate", transferEvent._BookingDateOption.Value!.Value.ToString(BookingDateFormat)); + + if (transferEvent._EstimatedArrivalTimeOption.IsSet) + writer.WriteString("estimatedArrivalTime", transferEvent._EstimatedArrivalTimeOption.Value!.Value.ToString(EstimatedArrivalTimeFormat)); + + if (transferEvent._EventsDataOption.IsSet) + { + writer.WritePropertyName("eventsData"); + JsonSerializer.Serialize(writer, transferEvent.EventsData, jsonSerializerOptions); + } + if (transferEvent._ExternalReasonOption.IsSet) + { + writer.WritePropertyName("externalReason"); + JsonSerializer.Serialize(writer, transferEvent.ExternalReason, jsonSerializerOptions); + } + if (transferEvent._IdOption.IsSet) + if (transferEvent.Id != null) + writer.WriteString("id", transferEvent.Id); + + if (transferEvent._ModificationOption.IsSet) + { + writer.WritePropertyName("modification"); + JsonSerializer.Serialize(writer, transferEvent.Modification, jsonSerializerOptions); + } + if (transferEvent._MutationsOption.IsSet) + { + writer.WritePropertyName("mutations"); + JsonSerializer.Serialize(writer, transferEvent.Mutations, jsonSerializerOptions); + } + if (transferEvent._OriginalAmountOption.IsSet) + { + writer.WritePropertyName("originalAmount"); + JsonSerializer.Serialize(writer, transferEvent.OriginalAmount, jsonSerializerOptions); + } + if (transferEvent._ReasonOption.IsSet && transferEvent.Reason != null) + { + string? reasonRawValue = TransferEvent.ReasonEnum.ToJsonValue(transferEvent._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (transferEvent._StatusOption.IsSet && transferEvent.Status != null) + { + string? statusRawValue = TransferEvent.StatusEnum.ToJsonValue(transferEvent._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (transferEvent._TrackingDataOption.IsSet) + { + writer.WritePropertyName("trackingData"); + JsonSerializer.Serialize(writer, transferEvent.TrackingData, jsonSerializerOptions); + } + if (transferEvent._TransactionIdOption.IsSet) + if (transferEvent.TransactionId != null) + writer.WriteString("transactionId", transferEvent.TransactionId); + + if (transferEvent._TypeOption.IsSet && transferEvent.Type != null) + { + string? typeRawValue = TransferEvent.TypeEnum.ToJsonValue(transferEvent._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (transferEvent._UpdateDateOption.IsSet) + writer.WriteString("updateDate", transferEvent._UpdateDateOption.Value!.Value.ToString(UpdateDateFormat)); + + if (transferEvent._ValueDateOption.IsSet) + writer.WriteString("valueDate", transferEvent._ValueDateOption.Value!.Value.ToString(ValueDateFormat)); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferEventEventsDataInner.cs b/Adyen/TransferWebhooks/Models/TransferEventEventsDataInner.cs new file mode 100644 index 000000000..e1a377089 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferEventEventsDataInner.cs @@ -0,0 +1,201 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferEventEventsDataInner. + /// + public partial class TransferEventEventsDataInner : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventEventsDataInner(IssuingTransactionData issuingTransactionData) + { + IssuingTransactionData = issuingTransactionData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventEventsDataInner(MerchantPurchaseData merchantPurchaseData) + { + MerchantPurchaseData = merchantPurchaseData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public IssuingTransactionData? IssuingTransactionData { get; set; } + + /// + /// .. + /// + public MerchantPurchaseData? MerchantPurchaseData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEventEventsDataInner {\n"); + if (this.IssuingTransactionData != null) + sb.Append(IssuingTransactionData.ToString().Replace("\n", "\n ")); + if (this.MerchantPurchaseData != null) + sb.Append(MerchantPurchaseData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventEventsDataInnerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEventEventsDataInner Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + IssuingTransactionData? issuingTransactionData = default; + MerchantPurchaseData? merchantPurchaseData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderIssuingTransactionData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIssuingTransactionData, jsonSerializerOptions, out issuingTransactionData); + + Utf8JsonReader utf8JsonReaderMerchantPurchaseData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMerchantPurchaseData, jsonSerializerOptions, out merchantPurchaseData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (issuingTransactionData?.Type != null) + return new TransferEventEventsDataInner(issuingTransactionData); + + if (merchantPurchaseData?.Type != null) + return new TransferEventEventsDataInner(merchantPurchaseData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEventEventsDataInner transferEventEventsDataInner, JsonSerializerOptions jsonSerializerOptions) + { + if (transferEventEventsDataInner.IssuingTransactionData != null) + JsonSerializer.Serialize(writer, transferEventEventsDataInner.IssuingTransactionData, jsonSerializerOptions); + if (transferEventEventsDataInner.MerchantPurchaseData != null) + JsonSerializer.Serialize(writer, transferEventEventsDataInner.MerchantPurchaseData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferEventEventsDataInner, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEventEventsDataInner transferEventEventsDataInner, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferEventTrackingData.cs b/Adyen/TransferWebhooks/Models/TransferEventTrackingData.cs new file mode 100644 index 000000000..5f9610c4c --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferEventTrackingData.cs @@ -0,0 +1,227 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// Additional information for the tracking event.. + /// + public partial class TransferEventTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(ConfirmationTrackingData confirmationTrackingData) + { + ConfirmationTrackingData = confirmationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(EstimationTrackingData estimationTrackingData) + { + EstimationTrackingData = estimationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(InternalReviewTrackingData internalReviewTrackingData) + { + InternalReviewTrackingData = internalReviewTrackingData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public ConfirmationTrackingData? ConfirmationTrackingData { get; set; } + + /// + /// .. + /// + public EstimationTrackingData? EstimationTrackingData { get; set; } + + /// + /// .. + /// + public InternalReviewTrackingData? InternalReviewTrackingData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEventTrackingData {\n"); + if (this.ConfirmationTrackingData != null) + sb.Append(ConfirmationTrackingData.ToString().Replace("\n", "\n ")); + if (this.EstimationTrackingData != null) + sb.Append(EstimationTrackingData.ToString().Replace("\n", "\n ")); + if (this.InternalReviewTrackingData != null) + sb.Append(InternalReviewTrackingData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEventTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ConfirmationTrackingData? confirmationTrackingData = default; + EstimationTrackingData? estimationTrackingData = default; + InternalReviewTrackingData? internalReviewTrackingData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderConfirmationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderConfirmationTrackingData, jsonSerializerOptions, out confirmationTrackingData); + + Utf8JsonReader utf8JsonReaderEstimationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEstimationTrackingData, jsonSerializerOptions, out estimationTrackingData); + + Utf8JsonReader utf8JsonReaderInternalReviewTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalReviewTrackingData, jsonSerializerOptions, out internalReviewTrackingData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (confirmationTrackingData?.Type != null) + return new TransferEventTrackingData(confirmationTrackingData); + + if (estimationTrackingData?.Type != null) + return new TransferEventTrackingData(estimationTrackingData); + + if (internalReviewTrackingData?.Type != null) + return new TransferEventTrackingData(internalReviewTrackingData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEventTrackingData transferEventTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + if (transferEventTrackingData.ConfirmationTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.ConfirmationTrackingData, jsonSerializerOptions); + if (transferEventTrackingData.EstimationTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.EstimationTrackingData, jsonSerializerOptions); + if (transferEventTrackingData.InternalReviewTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.InternalReviewTrackingData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferEventTrackingData, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEventTrackingData transferEventTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferNotificationCounterParty.cs b/Adyen/TransferWebhooks/Models/TransferNotificationCounterParty.cs new file mode 100644 index 000000000..8d071bc69 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferNotificationCounterParty.cs @@ -0,0 +1,277 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferNotificationCounterParty. + /// + public partial class TransferNotificationCounterParty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// bankAccount + /// card + /// merchant + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonConstructor] + public TransferNotificationCounterParty(Option balanceAccountId = default, Option bankAccount = default, Option card = default, Option merchant = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _BankAccountOption = bankAccount; + _CardOption = card; + _MerchantOption = merchant; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationCounterParty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountV3? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public TransferNotificationMerchantData? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationCounterParty {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationCounterPartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationCounterParty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option bankAccount = default; + Option card = default; + Option merchant = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationCounterParty(balanceAccountId, bankAccount, card, merchant, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationCounterParty transferNotificationCounterParty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationCounterParty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationCounterParty transferNotificationCounterParty, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationCounterParty._BalanceAccountIdOption.IsSet) + if (transferNotificationCounterParty.BalanceAccountId != null) + writer.WriteString("balanceAccountId", transferNotificationCounterParty.BalanceAccountId); + + if (transferNotificationCounterParty._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.BankAccount, jsonSerializerOptions); + } + if (transferNotificationCounterParty._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.Card, jsonSerializerOptions); + } + if (transferNotificationCounterParty._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.Merchant, jsonSerializerOptions); + } + if (transferNotificationCounterParty._TransferInstrumentIdOption.IsSet) + if (transferNotificationCounterParty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", transferNotificationCounterParty.TransferInstrumentId); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferNotificationMerchantData.cs b/Adyen/TransferWebhooks/Models/TransferNotificationMerchantData.cs new file mode 100644 index 000000000..44a6f5546 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferNotificationMerchantData.cs @@ -0,0 +1,327 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferNotificationMerchantData. + /// + public partial class TransferNotificationMerchantData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the merchant's acquirer. + /// The city where the merchant is located. + /// The country where the merchant is located. + /// The merchant category code. + /// The unique identifier of the merchant. + /// The name of the merchant's shop or service. + /// The postal code of the merchant. + [JsonConstructor] + public TransferNotificationMerchantData(Option acquirerId = default, Option city = default, Option country = default, Option mcc = default, Option merchantId = default, Option name = default, Option postalCode = default) + { + _AcquirerIdOption = acquirerId; + _CityOption = city; + _CountryOption = country; + _MccOption = mcc; + _MerchantIdOption = merchantId; + _NameOption = name; + _PostalCodeOption = postalCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationMerchantData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerIdOption { get; private set; } + + /// + /// The unique identifier of the merchant's acquirer. + /// + /// The unique identifier of the merchant's acquirer. + [JsonPropertyName("acquirerId")] + public string? AcquirerId { get { return this._AcquirerIdOption; } set { this._AcquirerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city where the merchant is located. + /// + /// The city where the merchant is located. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The country where the merchant is located. + /// + /// The country where the merchant is located. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The merchant category code. + /// + /// The merchant category code. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant. + /// + /// The unique identifier of the merchant. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the merchant's shop or service. + /// + /// The name of the merchant's shop or service. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code of the merchant. + /// + /// The postal code of the merchant. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationMerchantData {\n"); + sb.Append(" AcquirerId: ").Append(AcquirerId).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationMerchantDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationMerchantData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerId = default; + Option city = default; + Option country = default; + Option mcc = default; + Option merchantId = default; + Option name = default; + Option postalCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerId": + acquirerId = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationMerchantData(acquirerId, city, country, mcc, merchantId, name, postalCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationMerchantData transferNotificationMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationMerchantData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationMerchantData transferNotificationMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationMerchantData._AcquirerIdOption.IsSet) + if (transferNotificationMerchantData.AcquirerId != null) + writer.WriteString("acquirerId", transferNotificationMerchantData.AcquirerId); + + if (transferNotificationMerchantData._CityOption.IsSet) + if (transferNotificationMerchantData.City != null) + writer.WriteString("city", transferNotificationMerchantData.City); + + if (transferNotificationMerchantData._CountryOption.IsSet) + if (transferNotificationMerchantData.Country != null) + writer.WriteString("country", transferNotificationMerchantData.Country); + + if (transferNotificationMerchantData._MccOption.IsSet) + if (transferNotificationMerchantData.Mcc != null) + writer.WriteString("mcc", transferNotificationMerchantData.Mcc); + + if (transferNotificationMerchantData._MerchantIdOption.IsSet) + if (transferNotificationMerchantData.MerchantId != null) + writer.WriteString("merchantId", transferNotificationMerchantData.MerchantId); + + if (transferNotificationMerchantData._NameOption.IsSet) + if (transferNotificationMerchantData.Name != null) + writer.WriteString("name", transferNotificationMerchantData.Name); + + if (transferNotificationMerchantData._PostalCodeOption.IsSet) + if (transferNotificationMerchantData.PostalCode != null) + writer.WriteString("postalCode", transferNotificationMerchantData.PostalCode); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferNotificationRequest.cs b/Adyen/TransferWebhooks/Models/TransferNotificationRequest.cs new file mode 100644 index 000000000..27f7c9cd4 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferNotificationRequest.cs @@ -0,0 +1,349 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferNotificationRequest. + /// + public partial class TransferNotificationRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// When the event was queued. + /// The type of webhook. + [JsonConstructor] + public TransferNotificationRequest(TransferData data, string environment, Option timestamp = default, Option type = default) + { + Data = data; + Environment = environment; + _TimestampOption = timestamp; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationRequest() + { + } + + partial void OnCreated(); + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BalancePlatformTransferCreated - balancePlatform.transfer.created + /// + public static readonly TypeEnum BalancePlatformTransferCreated = new("balancePlatform.transfer.created"); + + /// + /// TypeEnum.BalancePlatformTransferUpdated - balancePlatform.transfer.updated + /// + public static readonly TypeEnum BalancePlatformTransferUpdated = new("balancePlatform.transfer.updated"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "balancePlatform.transfer.created" => TypeEnum.BalancePlatformTransferCreated, + "balancePlatform.transfer.updated" => TypeEnum.BalancePlatformTransferUpdated, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BalancePlatformTransferCreated) + return "balancePlatform.transfer.created"; + + if (value == TypeEnum.BalancePlatformTransferUpdated) + return "balancePlatform.transfer.updated"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of webhook. + /// + /// The type of webhook. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("data")] + public TransferData Data { get; set; } + + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + /// + /// The environment from which the webhook originated. Possible values: **test**, **live**. + [JsonPropertyName("environment")] + public string Environment { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimestampOption { get; private set; } + + /// + /// When the event was queued. + /// + /// When the event was queued. + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this._TimestampOption; } set { this._TimestampOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationRequest {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" Environment: ").Append(Environment).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationRequestJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp. + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option data = default; + Option environment = default; + Option timestamp = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "data": + data = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "environment": + environment = new Option(utf8JsonReader.GetString()!); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferNotificationRequest.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TransferNotificationRequest.", nameof(data)); + + if (!environment.IsSet) + throw new ArgumentException("Property is required for class TransferNotificationRequest.", nameof(environment)); + + return new TransferNotificationRequest(data.Value!, environment.Value!, timestamp, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationRequest transferNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationRequest transferNotificationRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, transferNotificationRequest.Data, jsonSerializerOptions); + if (transferNotificationRequest.Environment != null) + writer.WriteString("environment", transferNotificationRequest.Environment); + + if (transferNotificationRequest._TimestampOption.IsSet) + writer.WriteString("timestamp", transferNotificationRequest._TimestampOption.Value!.Value.ToString(TimestampFormat)); + + if (transferNotificationRequest._TypeOption.IsSet && transferNotificationRequest.Type != null) + { + string? typeRawValue = TransferNotificationRequest.TypeEnum.ToJsonValue(transferNotificationRequest._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferNotificationValidationFact.cs b/Adyen/TransferWebhooks/Models/TransferNotificationValidationFact.cs new file mode 100644 index 000000000..d1568fe60 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferNotificationValidationFact.cs @@ -0,0 +1,202 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferNotificationValidationFact. + /// + public partial class TransferNotificationValidationFact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The evaluation result of the validation fact. + /// The type of the validation fact. + [JsonConstructor] + public TransferNotificationValidationFact(Option result = default, Option type = default) + { + _ResultOption = result; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationValidationFact() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The evaluation result of the validation fact. + /// + /// The evaluation result of the validation fact. + [JsonPropertyName("result")] + public string? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the validation fact. + /// + /// The type of the validation fact. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationValidationFact {\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationValidationFactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationValidationFact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option result = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationValidationFact(result, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationValidationFact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationValidationFact._ResultOption.IsSet) + if (transferNotificationValidationFact.Result != null) + writer.WriteString("result", transferNotificationValidationFact.Result); + + if (transferNotificationValidationFact._TypeOption.IsSet) + if (transferNotificationValidationFact.Type != null) + writer.WriteString("type", transferNotificationValidationFact.Type); + } + } +} diff --git a/Adyen/TransferWebhooks/Models/TransferReview.cs b/Adyen/TransferWebhooks/Models/TransferReview.cs new file mode 100644 index 000000000..416220980 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/TransferReview.cs @@ -0,0 +1,316 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// TransferReview. + /// + public partial class TransferReview : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonConstructor] + public TransferReview(Option numberOfApprovalsRequired = default, Option scaOnApproval = default) + { + _NumberOfApprovalsRequiredOption = numberOfApprovalsRequired; + _ScaOnApprovalOption = scaOnApproval; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferReview() + { + } + + partial void OnCreated(); + + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonConverter(typeof(ScaOnApprovalEnumJsonConverter))] + public class ScaOnApprovalEnum : IEnum + { + /// + /// Returns the value of the ScaOnApprovalEnum. + /// + public string? Value { get; set; } + + /// + /// ScaOnApprovalEnum.Completed - completed + /// + public static readonly ScaOnApprovalEnum Completed = new("completed"); + + /// + /// ScaOnApprovalEnum.NotApplicable - notApplicable + /// + public static readonly ScaOnApprovalEnum NotApplicable = new("notApplicable"); + + /// + /// ScaOnApprovalEnum.Required - required + /// + public static readonly ScaOnApprovalEnum Required = new("required"); + + private ScaOnApprovalEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ScaOnApprovalEnum?(string? value) => value == null ? null : new ScaOnApprovalEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ScaOnApprovalEnum? option) => option?.Value; + + public static bool operator ==(ScaOnApprovalEnum? left, ScaOnApprovalEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ScaOnApprovalEnum? left, ScaOnApprovalEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ScaOnApprovalEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ScaOnApprovalEnum? FromStringOrDefault(string value) + { + return value switch { + "completed" => ScaOnApprovalEnum.Completed, + "notApplicable" => ScaOnApprovalEnum.NotApplicable, + "required" => ScaOnApprovalEnum.Required, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ScaOnApprovalEnum? value) + { + if (value == null) + return null; + + if (value == ScaOnApprovalEnum.Completed) + return "completed"; + + if (value == ScaOnApprovalEnum.NotApplicable) + return "notApplicable"; + + if (value == ScaOnApprovalEnum.Required) + return "required"; + + return null; + } + + /// + /// JsonConverter for writing ScaOnApprovalEnum. + /// + public class ScaOnApprovalEnumJsonConverter : JsonConverter + { + public override ScaOnApprovalEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ScaOnApprovalEnum.FromStringOrDefault(value) ?? new ScaOnApprovalEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ScaOnApprovalEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ScaOnApprovalEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaOnApprovalOption { get; private set; } + + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonPropertyName("scaOnApproval")] + public ScaOnApprovalEnum? ScaOnApproval { get { return this._ScaOnApprovalOption; } set { this._ScaOnApprovalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOfApprovalsRequiredOption { get; private set; } + + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + [JsonPropertyName("numberOfApprovalsRequired")] + public int? NumberOfApprovalsRequired { get { return this._NumberOfApprovalsRequiredOption; } set { this._NumberOfApprovalsRequiredOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferReview {\n"); + sb.Append(" NumberOfApprovalsRequired: ").Append(NumberOfApprovalsRequired).Append("\n"); + sb.Append(" ScaOnApproval: ").Append(ScaOnApproval).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferReviewJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferReview Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option numberOfApprovalsRequired = default; + Option scaOnApproval = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "numberOfApprovalsRequired": + numberOfApprovalsRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "scaOnApproval": + string? scaOnApprovalRawValue = utf8JsonReader.GetString(); + scaOnApproval = new Option(TransferReview.ScaOnApprovalEnum.FromStringOrDefault(scaOnApprovalRawValue)); + break; + default: + break; + } + } + } + + + return new TransferReview(numberOfApprovalsRequired, scaOnApproval); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferReview transferReview, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferReview, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferReview transferReview, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferReview._NumberOfApprovalsRequiredOption.IsSet) + writer.WriteNumber("numberOfApprovalsRequired", transferReview._NumberOfApprovalsRequiredOption.Value!.Value); + + if (transferReview._ScaOnApprovalOption.IsSet && transferReview.ScaOnApproval != null) + { + string? scaOnApprovalRawValue = TransferReview.ScaOnApprovalEnum.ToJsonValue(transferReview._ScaOnApprovalOption.Value!.Value); + writer.WriteString("scaOnApproval", scaOnApprovalRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/UKLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/UKLocalAccountIdentification.cs new file mode 100644 index 000000000..822ec84f9 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/UKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// UKLocalAccountIdentification. + /// + public partial class UKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 8-digit bank account number, without separators or whitespace. + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **ukLocal** (default to TypeEnum.UkLocal) + [JsonConstructor] + public UKLocalAccountIdentification(string accountNumber, string sortCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + SortCode = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UkLocal - ukLocal + /// + public static readonly TypeEnum UkLocal = new("ukLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ukLocal" => TypeEnum.UkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UkLocal) + return "ukLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 8-digit bank account number, without separators or whitespace. + /// + /// The 8-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string SortCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 8.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 8.", new [] { "AccountNumber" }); + } + + // SortCode (string) maxLength + if (this.SortCode != null && this.SortCode.Length > 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be less than 6.", new [] { "SortCode" }); + } + + // SortCode (string) minLength + if (this.SortCode != null && this.SortCode.Length < 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be greater than 6.", new [] { "SortCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(accountNumber)); + + if (!sortCode.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(sortCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(type)); + + return new UKLocalAccountIdentification(accountNumber.Value!, sortCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uKLocalAccountIdentification.AccountNumber); + + if (uKLocalAccountIdentification.SortCode != null) + writer.WriteString("sortCode", uKLocalAccountIdentification.SortCode); + + if (uKLocalAccountIdentification.Type != null) + { + string? typeRawValue = UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/TransferWebhooks/Models/USLocalAccountIdentification.cs b/Adyen/TransferWebhooks/Models/USLocalAccountIdentification.cs new file mode 100644 index 000000000..f85cb9a84 --- /dev/null +++ b/Adyen/TransferWebhooks/Models/USLocalAccountIdentification.cs @@ -0,0 +1,464 @@ +// +/* + * Transfer webhooks + * + * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.TransferWebhooks.Client; + +namespace Adyen.TransferWebhooks.Models +{ + /// + /// USLocalAccountIdentification. + /// + public partial class USLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **usLocal** (default to TypeEnum.UsLocal) + [JsonConstructor] + public USLocalAccountIdentification(string accountNumber, string routingNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + RoutingNumber = routingNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsLocal - usLocal + /// + public static readonly TypeEnum UsLocal = new("usLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usLocal" => TypeEnum.UsLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsLocal) + return "usLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string RoutingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 18) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 18.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // RoutingNumber (string) maxLength + if (this.RoutingNumber != null && this.RoutingNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be less than 9.", new [] { "RoutingNumber" }); + } + + // RoutingNumber (string) minLength + if (this.RoutingNumber != null && this.RoutingNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be greater than 9.", new [] { "RoutingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option routingNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(USLocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(accountNumber)); + + if (!routingNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(routingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(type)); + + return new USLocalAccountIdentification(accountNumber.Value!, routingNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uSLocalAccountIdentification.AccountNumber); + + if (uSLocalAccountIdentification.RoutingNumber != null) + writer.WriteString("routingNumber", uSLocalAccountIdentification.RoutingNumber); + + if (uSLocalAccountIdentification._AccountTypeOption.IsSet && uSLocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (uSLocalAccountIdentification.Type != null) + { + string? typeRawValue = USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Client/ApiKeyToken.cs b/Adyen/Transfers/Client/ApiKeyToken.cs new file mode 100644 index 000000000..233ed16a7 --- /dev/null +++ b/Adyen/Transfers/Client/ApiKeyToken.cs @@ -0,0 +1,51 @@ +// + +#nullable enable + +using System; +using Adyen.Core.Auth; +using Adyen.Core.Client; + +namespace Adyen.Transfers.Client +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + public class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/Adyen/Transfers/Client/ClientUtils.cs b/Adyen/Transfers/Client/ClientUtils.cs new file mode 100644 index 000000000..4eb2da55c --- /dev/null +++ b/Adyen/Transfers/Client/ClientUtils.cs @@ -0,0 +1,440 @@ +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Adyen; +using Adyen.Core.Options; +using Adyen.Transfers.Models; +using Models = Adyen.Transfers.Models; +using System.Runtime.CompilerServices; + +namespace Adyen.Transfers.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is Models.AULocalAccountIdentification.TypeEnum aULocalAccountIdentificationTypeEnum) + return Models.AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentificationTypeEnum); + if (obj is Models.AdditionalBankIdentification.TypeEnum additionalBankIdentificationTypeEnum) + return Models.AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentificationTypeEnum); + if (obj is Models.AmountAdjustment.AmountAdjustmentTypeEnum amountAdjustmentAmountAdjustmentTypeEnum) + return Models.AmountAdjustment.AmountAdjustmentTypeEnum.ToJsonValue(amountAdjustmentAmountAdjustmentTypeEnum); + if (obj is Models.BRLocalAccountIdentification.TypeEnum bRLocalAccountIdentificationTypeEnum) + return Models.BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentificationTypeEnum); + if (obj is Models.BankCategoryData.PriorityEnum bankCategoryDataPriorityEnum) + return Models.BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryDataPriorityEnum); + if (obj is Models.BankCategoryData.TypeEnum bankCategoryDataTypeEnum) + return Models.BankCategoryData.TypeEnum.ToJsonValue(bankCategoryDataTypeEnum); + if (obj is Models.CALocalAccountIdentification.AccountTypeEnum cALocalAccountIdentificationAccountTypeEnum) + return Models.CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentificationAccountTypeEnum); + if (obj is Models.CALocalAccountIdentification.TypeEnum cALocalAccountIdentificationTypeEnum) + return Models.CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentificationTypeEnum); + if (obj is Models.CZLocalAccountIdentification.TypeEnum cZLocalAccountIdentificationTypeEnum) + return Models.CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentificationTypeEnum); + if (obj is Models.CapitalGrant.StatusEnum capitalGrantStatusEnum) + return Models.CapitalGrant.StatusEnum.ToJsonValue(capitalGrantStatusEnum); + if (obj is Models.ConfirmationTrackingData.StatusEnum confirmationTrackingDataStatusEnum) + return Models.ConfirmationTrackingData.StatusEnum.ToJsonValue(confirmationTrackingDataStatusEnum); + if (obj is Models.ConfirmationTrackingData.TypeEnum confirmationTrackingDataTypeEnum) + return Models.ConfirmationTrackingData.TypeEnum.ToJsonValue(confirmationTrackingDataTypeEnum); + if (obj is Models.DKLocalAccountIdentification.TypeEnum dKLocalAccountIdentificationTypeEnum) + return Models.DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentificationTypeEnum); + if (obj is Models.EstimationTrackingData.TypeEnum estimationTrackingDataTypeEnum) + return Models.EstimationTrackingData.TypeEnum.ToJsonValue(estimationTrackingDataTypeEnum); + if (obj is Models.HKLocalAccountIdentification.TypeEnum hKLocalAccountIdentificationTypeEnum) + return Models.HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentificationTypeEnum); + if (obj is Models.HULocalAccountIdentification.TypeEnum hULocalAccountIdentificationTypeEnum) + return Models.HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentificationTypeEnum); + if (obj is Models.IbanAccountIdentification.TypeEnum ibanAccountIdentificationTypeEnum) + return Models.IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentificationTypeEnum); + if (obj is Models.InternalCategoryData.TypeEnum internalCategoryDataTypeEnum) + return Models.InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryDataTypeEnum); + if (obj is Models.InternalReviewTrackingData.StatusEnum internalReviewTrackingDataStatusEnum) + return Models.InternalReviewTrackingData.StatusEnum.ToJsonValue(internalReviewTrackingDataStatusEnum); + if (obj is Models.InternalReviewTrackingData.ReasonEnum internalReviewTrackingDataReasonEnum) + return Models.InternalReviewTrackingData.ReasonEnum.ToJsonValue(internalReviewTrackingDataReasonEnum); + if (obj is Models.InternalReviewTrackingData.TypeEnum internalReviewTrackingDataTypeEnum) + return Models.InternalReviewTrackingData.TypeEnum.ToJsonValue(internalReviewTrackingDataTypeEnum); + if (obj is Models.IssuedCard.PanEntryModeEnum issuedCardPanEntryModeEnum) + return Models.IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCardPanEntryModeEnum); + if (obj is Models.IssuedCard.ProcessingTypeEnum issuedCardProcessingTypeEnum) + return Models.IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCardProcessingTypeEnum); + if (obj is Models.IssuedCard.TypeEnum issuedCardTypeEnum) + return Models.IssuedCard.TypeEnum.ToJsonValue(issuedCardTypeEnum); + if (obj is Models.IssuingTransactionData.TypeEnum issuingTransactionDataTypeEnum) + return Models.IssuingTransactionData.TypeEnum.ToJsonValue(issuingTransactionDataTypeEnum); + if (obj is Models.MerchantPurchaseData.TypeEnum merchantPurchaseDataTypeEnum) + return Models.MerchantPurchaseData.TypeEnum.ToJsonValue(merchantPurchaseDataTypeEnum); + if (obj is Models.Modification.StatusEnum modificationStatusEnum) + return Models.Modification.StatusEnum.ToJsonValue(modificationStatusEnum); + if (obj is Models.NOLocalAccountIdentification.TypeEnum nOLocalAccountIdentificationTypeEnum) + return Models.NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentificationTypeEnum); + if (obj is Models.NZLocalAccountIdentification.TypeEnum nZLocalAccountIdentificationTypeEnum) + return Models.NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentificationTypeEnum); + if (obj is Models.NumberAndBicAccountIdentification.TypeEnum numberAndBicAccountIdentificationTypeEnum) + return Models.NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentificationTypeEnum); + if (obj is Models.PLLocalAccountIdentification.TypeEnum pLLocalAccountIdentificationTypeEnum) + return Models.PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentificationTypeEnum); + if (obj is Models.PartyIdentification.TypeEnum partyIdentificationTypeEnum) + return Models.PartyIdentification.TypeEnum.ToJsonValue(partyIdentificationTypeEnum); + if (obj is Models.PlatformPayment.PlatformPaymentTypeEnum platformPaymentPlatformPaymentTypeEnum) + return Models.PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPaymentPlatformPaymentTypeEnum); + if (obj is Models.PlatformPayment.TypeEnum platformPaymentTypeEnum) + return Models.PlatformPayment.TypeEnum.ToJsonValue(platformPaymentTypeEnum); + if (obj is Models.ReturnTransferResponse.StatusEnum returnTransferResponseStatusEnum) + return Models.ReturnTransferResponse.StatusEnum.ToJsonValue(returnTransferResponseStatusEnum); + if (obj is Models.RoutingDetails.PriorityEnum routingDetailsPriorityEnum) + return Models.RoutingDetails.PriorityEnum.ToJsonValue(routingDetailsPriorityEnum); + if (obj is Models.SELocalAccountIdentification.TypeEnum sELocalAccountIdentificationTypeEnum) + return Models.SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentificationTypeEnum); + if (obj is Models.SGLocalAccountIdentification.TypeEnum sGLocalAccountIdentificationTypeEnum) + return Models.SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentificationTypeEnum); + if (obj is Models.Transaction.StatusEnum transactionStatusEnum) + return Models.Transaction.StatusEnum.ToJsonValue(transactionStatusEnum); + if (obj is Models.Transfer.CategoryEnum transferCategoryEnum) + return Models.Transfer.CategoryEnum.ToJsonValue(transferCategoryEnum); + if (obj is Models.Transfer.StatusEnum transferStatusEnum) + return Models.Transfer.StatusEnum.ToJsonValue(transferStatusEnum); + if (obj is Models.Transfer.DirectionEnum transferDirectionEnum) + return Models.Transfer.DirectionEnum.ToJsonValue(transferDirectionEnum); + if (obj is Models.Transfer.ReasonEnum transferReasonEnum) + return Models.Transfer.ReasonEnum.ToJsonValue(transferReasonEnum); + if (obj is Models.Transfer.TypeEnum transferTypeEnum) + return Models.Transfer.TypeEnum.ToJsonValue(transferTypeEnum); + if (obj is Models.TransferData.CategoryEnum transferDataCategoryEnum) + return Models.TransferData.CategoryEnum.ToJsonValue(transferDataCategoryEnum); + if (obj is Models.TransferData.StatusEnum transferDataStatusEnum) + return Models.TransferData.StatusEnum.ToJsonValue(transferDataStatusEnum); + if (obj is Models.TransferData.DirectionEnum transferDataDirectionEnum) + return Models.TransferData.DirectionEnum.ToJsonValue(transferDataDirectionEnum); + if (obj is Models.TransferData.ReasonEnum transferDataReasonEnum) + return Models.TransferData.ReasonEnum.ToJsonValue(transferDataReasonEnum); + if (obj is Models.TransferData.TypeEnum transferDataTypeEnum) + return Models.TransferData.TypeEnum.ToJsonValue(transferDataTypeEnum); + if (obj is Models.TransferEvent.ReasonEnum transferEventReasonEnum) + return Models.TransferEvent.ReasonEnum.ToJsonValue(transferEventReasonEnum); + if (obj is Models.TransferEvent.StatusEnum transferEventStatusEnum) + return Models.TransferEvent.StatusEnum.ToJsonValue(transferEventStatusEnum); + if (obj is Models.TransferEvent.TypeEnum transferEventTypeEnum) + return Models.TransferEvent.TypeEnum.ToJsonValue(transferEventTypeEnum); + if (obj is Models.TransferInfo.CategoryEnum transferInfoCategoryEnum) + return Models.TransferInfo.CategoryEnum.ToJsonValue(transferInfoCategoryEnum); + if (obj is Models.TransferInfo.PrioritiesEnum transferInfoPrioritiesEnum) + return TransferInfo.PrioritiesEnum.ToJsonValue(transferInfoPrioritiesEnum); + if (obj is Models.TransferInfo.PriorityEnum transferInfoPriorityEnum) + return Models.TransferInfo.PriorityEnum.ToJsonValue(transferInfoPriorityEnum); + if (obj is Models.TransferInfo.TypeEnum transferInfoTypeEnum) + return Models.TransferInfo.TypeEnum.ToJsonValue(transferInfoTypeEnum); + if (obj is Models.TransferReview.ScaOnApprovalEnum transferReviewScaOnApprovalEnum) + return Models.TransferReview.ScaOnApprovalEnum.ToJsonValue(transferReviewScaOnApprovalEnum); + if (obj is Models.UKLocalAccountIdentification.TypeEnum uKLocalAccountIdentificationTypeEnum) + return Models.UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentificationTypeEnum); + if (obj is Models.USLocalAccountIdentification.AccountTypeEnum uSLocalAccountIdentificationAccountTypeEnum) + return Models.USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentificationAccountTypeEnum); + if (obj is Models.USLocalAccountIdentification.TypeEnum uSLocalAccountIdentificationTypeEnum) + return Models.USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentificationTypeEnum); + if (obj is Models.UltimatePartyIdentification.TypeEnum ultimatePartyIdentificationTypeEnum) + return Models.UltimatePartyIdentification.TypeEnum.ToJsonValue(ultimatePartyIdentificationTypeEnum); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + /// + /// The X-API-Key header. + /// + X_API_Key, + /// + /// The clientKey header. + /// + ClientKey + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.X_API_Key => "X-API-Key", + ApiKeyHeader.ClientKey => "clientKey", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + + } +} diff --git a/Adyen/Transfers/Client/HostConfiguration.cs b/Adyen/Transfers/Client/HostConfiguration.cs new file mode 100644 index 000000000..323d6b094 --- /dev/null +++ b/Adyen/Transfers/Client/HostConfiguration.cs @@ -0,0 +1,224 @@ +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Transfers.Services; +using Adyen.Transfers.Client; +using Adyen.Transfers.Models; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Options; +using Adyen.Core.Converters; + +namespace Adyen.Transfers.Client +{ + /// + /// Provides hosting configuration for Transfers + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "https://balanceplatform-api-test.adyen.com/btl/v4"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AdditionalBankIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new AddressJsonConverter()); + _jsonOptions.Converters.Add(new AirlineJsonConverter()); + _jsonOptions.Converters.Add(new AmountJsonConverter()); + _jsonOptions.Converters.Add(new AmountAdjustmentJsonConverter()); + _jsonOptions.Converters.Add(new ApproveTransfersRequestJsonConverter()); + _jsonOptions.Converters.Add(new BRLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BalanceMutationJsonConverter()); + _jsonOptions.Converters.Add(new BankAccountV3JsonConverter()); + _jsonOptions.Converters.Add(new BankAccountV3AccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new BankCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new CALocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new CancelTransfersRequestJsonConverter()); + _jsonOptions.Converters.Add(new CapitalBalanceJsonConverter()); + _jsonOptions.Converters.Add(new CapitalGrantJsonConverter()); + _jsonOptions.Converters.Add(new CapitalGrantInfoJsonConverter()); + _jsonOptions.Converters.Add(new CapitalGrantsJsonConverter()); + _jsonOptions.Converters.Add(new CardJsonConverter()); + _jsonOptions.Converters.Add(new CardIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new ConfirmationTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyJsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyInfoV3JsonConverter()); + _jsonOptions.Converters.Add(new CounterpartyV3JsonConverter()); + _jsonOptions.Converters.Add(new DKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new DirectDebitInformationJsonConverter()); + _jsonOptions.Converters.Add(new EstimationTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new ExecutionDateJsonConverter()); + _jsonOptions.Converters.Add(new ExternalReasonJsonConverter()); + _jsonOptions.Converters.Add(new FeeJsonConverter()); + _jsonOptions.Converters.Add(new FindTransfersResponseJsonConverter()); + _jsonOptions.Converters.Add(new HKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new HULocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new IbanAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new InternalCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new InternalReviewTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new InvalidFieldJsonConverter()); + _jsonOptions.Converters.Add(new IssuedCardJsonConverter()); + _jsonOptions.Converters.Add(new IssuingTransactionDataJsonConverter()); + _jsonOptions.Converters.Add(new LegJsonConverter()); + _jsonOptions.Converters.Add(new LinkJsonConverter()); + _jsonOptions.Converters.Add(new LinksJsonConverter()); + _jsonOptions.Converters.Add(new LodgingJsonConverter()); + _jsonOptions.Converters.Add(new MerchantDataJsonConverter()); + _jsonOptions.Converters.Add(new MerchantPurchaseDataJsonConverter()); + _jsonOptions.Converters.Add(new ModificationJsonConverter()); + _jsonOptions.Converters.Add(new NOLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NZLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new NameLocationJsonConverter()); + _jsonOptions.Converters.Add(new NumberAndBicAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PLLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PartyIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new PaymentInstrumentJsonConverter()); + _jsonOptions.Converters.Add(new PlatformPaymentJsonConverter()); + _jsonOptions.Converters.Add(new RelayedAuthorisationDataJsonConverter()); + _jsonOptions.Converters.Add(new RepaymentJsonConverter()); + _jsonOptions.Converters.Add(new RepaymentTermJsonConverter()); + _jsonOptions.Converters.Add(new ResourceReferenceJsonConverter()); + _jsonOptions.Converters.Add(new RestServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new ReturnTransferRequestJsonConverter()); + _jsonOptions.Converters.Add(new ReturnTransferResponseJsonConverter()); + _jsonOptions.Converters.Add(new RoutingDetailsJsonConverter()); + _jsonOptions.Converters.Add(new SELocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new SGLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new ServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new ThreeDSecureJsonConverter()); + _jsonOptions.Converters.Add(new ThresholdRepaymentJsonConverter()); + _jsonOptions.Converters.Add(new TransactionJsonConverter()); + _jsonOptions.Converters.Add(new TransactionEventViolationJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleReferenceJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRuleSourceJsonConverter()); + _jsonOptions.Converters.Add(new TransactionRulesResultJsonConverter()); + _jsonOptions.Converters.Add(new TransactionSearchResponseJsonConverter()); + _jsonOptions.Converters.Add(new TransferJsonConverter()); + _jsonOptions.Converters.Add(new TransferCategoryDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferDataTrackingJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventEventsDataInnerJsonConverter()); + _jsonOptions.Converters.Add(new TransferEventTrackingDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferInfoJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationCounterPartyJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationMerchantDataJsonConverter()); + _jsonOptions.Converters.Add(new TransferNotificationValidationFactJsonConverter()); + _jsonOptions.Converters.Add(new TransferRequestReviewJsonConverter()); + _jsonOptions.Converters.Add(new TransferReviewJsonConverter()); + _jsonOptions.Converters.Add(new TransferServiceRestServiceErrorJsonConverter()); + _jsonOptions.Converters.Add(new TransferViewJsonConverter()); + _jsonOptions.Converters.Add(new UKLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new USLocalAccountIdentificationJsonConverter()); + _jsonOptions.Converters.Add(new UltimatePartyIdentificationJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration AddTransfersHttpClients(Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + builders.Add(_services.AddHttpClient(httpClientAction)); + + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + + return this; + } + } +} diff --git a/Adyen/Transfers/Client/JsonSerializerOptionsProvider.cs b/Adyen/Transfers/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000..dcd6e5af9 --- /dev/null +++ b/Adyen/Transfers/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Adyen.Transfers.Client +{ + /// + /// Provides the JsonSerializerOptions. + /// + public class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/Adyen/Transfers/Extensions/HostBuilderExtensions.cs b/Adyen/Transfers/Extensions/HostBuilderExtensions.cs new file mode 100644 index 000000000..59e1d5c1c --- /dev/null +++ b/Adyen/Transfers/Extensions/HostBuilderExtensions.cs @@ -0,0 +1,47 @@ +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Adyen.Transfers; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Extensions +{ + /// + /// Extension methods for IHostBuilder. + /// + public static class HostBuilderExtensions + { + /// + /// Add the Transfers API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder ConfigureTransfers(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.AddTransfersHttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/Adyen/Transfers/Extensions/ServiceCollectionExtensions.cs b/Adyen/Transfers/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..01355e287 --- /dev/null +++ b/Adyen/Transfers/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Adyen.Core.Auth; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Extensions +{ + /// + /// Extension methods for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Add the Adyen Transfers API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void AddTransfersServices(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.AddTransfersHttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/Adyen/Transfers/Models/AULocalAccountIdentification.cs b/Adyen/Transfers/Models/AULocalAccountIdentification.cs new file mode 100644 index 000000000..3a8dfd23c --- /dev/null +++ b/Adyen/Transfers/Models/AULocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// AULocalAccountIdentification. + /// + public partial class AULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// **auLocal** (default to TypeEnum.AuLocal) + [JsonConstructor] + public AULocalAccountIdentification(string accountNumber, string bsbCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BsbCode = bsbCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuLocal - auLocal + /// + public static readonly TypeEnum AuLocal = new("auLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auLocal" => TypeEnum.AuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuLocal) + return "auLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **auLocal** + /// + /// **auLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + /// + /// The 6-digit [Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or whitespace. + [JsonPropertyName("bsbCode")] + public string BsbCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BsbCode: ").Append(BsbCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 9.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // BsbCode (string) maxLength + if (this.BsbCode != null && this.BsbCode.Length > 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be less than 6.", new [] { "BsbCode" }); + } + + // BsbCode (string) minLength + if (this.BsbCode != null && this.BsbCode.Length < 6) + { + yield return new ValidationResult("Invalid value for BsbCode, length must be greater than 6.", new [] { "BsbCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bsbCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bsbCode": + bsbCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(accountNumber)); + + if (!bsbCode.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(bsbCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class AULocalAccountIdentification.", nameof(type)); + + return new AULocalAccountIdentification(accountNumber.Value!, bsbCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, aULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AULocalAccountIdentification aULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (aULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", aULocalAccountIdentification.AccountNumber); + + if (aULocalAccountIdentification.BsbCode != null) + writer.WriteString("bsbCode", aULocalAccountIdentification.BsbCode); + + if (aULocalAccountIdentification.Type != null) + { + string? typeRawValue = AULocalAccountIdentification.TypeEnum.ToJsonValue(aULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/AdditionalBankIdentification.cs b/Adyen/Transfers/Models/AdditionalBankIdentification.cs new file mode 100644 index 000000000..e23343d9d --- /dev/null +++ b/Adyen/Transfers/Models/AdditionalBankIdentification.cs @@ -0,0 +1,326 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// AdditionalBankIdentification. + /// + public partial class AdditionalBankIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The value of the additional bank identification. + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConstructor] + public AdditionalBankIdentification(Option code = default, Option type = default) + { + _CodeOption = code; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AdditionalBankIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.AuBsbCode - auBsbCode + /// + public static readonly TypeEnum AuBsbCode = new("auBsbCode"); + + /// + /// TypeEnum.CaRoutingNumber - caRoutingNumber + /// + public static readonly TypeEnum CaRoutingNumber = new("caRoutingNumber"); + + /// + /// TypeEnum.GbSortCode - gbSortCode + /// + public static readonly TypeEnum GbSortCode = new("gbSortCode"); + + /// + /// TypeEnum.UsRoutingNumber - usRoutingNumber + /// + public static readonly TypeEnum UsRoutingNumber = new("usRoutingNumber"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "auBsbCode" => TypeEnum.AuBsbCode, + "caRoutingNumber" => TypeEnum.CaRoutingNumber, + "gbSortCode" => TypeEnum.GbSortCode, + "usRoutingNumber" => TypeEnum.UsRoutingNumber, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.AuBsbCode) + return "auBsbCode"; + + if (value == TypeEnum.CaRoutingNumber) + return "caRoutingNumber"; + + if (value == TypeEnum.GbSortCode) + return "gbSortCode"; + + if (value == TypeEnum.UsRoutingNumber) + return "usRoutingNumber"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + /// + /// The type of additional bank identification, depending on the country. Possible values: * **auBsbCode**: The 6-digit [Australian Bank State Branch (BSB) code](https://en.wikipedia.org/wiki/Bank_state_branch), without separators or spaces. * **caRoutingNumber**: The 9-digit [Canadian routing number](https://en.wikipedia.org/wiki/Routing_number_(Canada)), in EFT format, without separators or spaces. * **gbSortCode**: The 6-digit [UK sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or spaces * **usRoutingNumber**: The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or spaces. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The value of the additional bank identification. + /// + /// The value of the additional bank identification. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalBankIdentification {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AdditionalBankIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AdditionalBankIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(AdditionalBankIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new AdditionalBankIdentification(code, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, additionalBankIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AdditionalBankIdentification additionalBankIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (additionalBankIdentification._CodeOption.IsSet) + if (additionalBankIdentification.Code != null) + writer.WriteString("code", additionalBankIdentification.Code); + + if (additionalBankIdentification._TypeOption.IsSet && additionalBankIdentification.Type != null) + { + string? typeRawValue = AdditionalBankIdentification.TypeEnum.ToJsonValue(additionalBankIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/Address.cs b/Adyen/Transfers/Models/Address.cs new file mode 100644 index 000000000..415f2cc7f --- /dev/null +++ b/Adyen/Transfers/Models/Address.cs @@ -0,0 +1,308 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Address. + /// + public partial class Address : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonConstructor] + public Address(string country, Option city = default, Option line1 = default, Option line2 = default, Option postalCode = default, Option stateOrProvince = default) + { + Country = country; + _CityOption = city; + _Line1Option = line1; + _Line2Option = line2; + _PostalCodeOption = postalCode; + _StateOrProvinceOption = stateOrProvince; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Address() + { + } + + partial void OnCreated(); + + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + /// + /// The two-character ISO 3166-1 alpha-2 country code. For example, **US**, **NL**, or **GB**. + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The name of the city. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line1Option { get; private set; } + + /// + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The first line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("line1")] + public string? Line1 { get { return this._Line1Option; } set { this._Line1Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _Line2Option { get; private set; } + + /// + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + /// + /// The second line of the street address. Supported characters: **[a-z] [A-Z] [0-9] . - — / # , ’ ° ( ) : ; [ ] & \\ |** and Space. > Required when the `category` is **card**. + [JsonPropertyName("line2")] + public string? Line2 { get { return this._Line2Option; } set { this._Line2Option = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + /// + /// The postal code. Maximum length: * 5 digits for an address in the US. * 10 characters for an address in all other countries. Supported characters: **[a-z] [A-Z] [0-9]** and Space. > Required for addresses in the US. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOrProvinceOption { get; private set; } + + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + /// + /// The two-letter ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. + [JsonPropertyName("stateOrProvince")] + public string? StateOrProvince { get { return this._StateOrProvinceOption; } set { this._StateOrProvinceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Address {\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Line1: ").Append(Line1).Append("\n"); + sb.Append(" Line2: ").Append(Line2).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // City (string) minLength + if (this.City != null && this.City.Length < 3) + { + yield return new ValidationResult("Invalid value for City, length must be greater than 3.", new [] { "City" }); + } + + // PostalCode (string) minLength + if (this.PostalCode != null && this.PostalCode.Length < 3) + { + yield return new ValidationResult("Invalid value for PostalCode, length must be greater than 3.", new [] { "PostalCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AddressJsonConverter : JsonConverter
+ { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Address Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option country = default; + Option city = default; + Option line1 = default; + Option line2 = default; + Option postalCode = default; + Option stateOrProvince = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "line1": + line1 = new Option(utf8JsonReader.GetString()!); + break; + case "line2": + line2 = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + case "stateOrProvince": + stateOrProvince = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!country.IsSet) + throw new ArgumentException("Property is required for class Address.", nameof(country)); + + return new Address(country.Value!, city, line1, line2, postalCode, stateOrProvince); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, address, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Address address, JsonSerializerOptions jsonSerializerOptions) + { + + if (address.Country != null) + writer.WriteString("country", address.Country); + + if (address._CityOption.IsSet) + if (address.City != null) + writer.WriteString("city", address.City); + + if (address._Line1Option.IsSet) + if (address.Line1 != null) + writer.WriteString("line1", address.Line1); + + if (address._Line2Option.IsSet) + if (address.Line2 != null) + writer.WriteString("line2", address.Line2); + + if (address._PostalCodeOption.IsSet) + if (address.PostalCode != null) + writer.WriteString("postalCode", address.PostalCode); + + if (address._StateOrProvinceOption.IsSet) + if (address.StateOrProvince != null) + writer.WriteString("stateOrProvince", address.StateOrProvince); + } + } +} diff --git a/Adyen/Transfers/Models/Airline.cs b/Adyen/Transfers/Models/Airline.cs new file mode 100644 index 000000000..12af974dc --- /dev/null +++ b/Adyen/Transfers/Models/Airline.cs @@ -0,0 +1,203 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Airline. + /// + public partial class Airline : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Details about the flight legs for this ticket. + /// The ticket's unique identifier + [JsonConstructor] + public Airline(Option?> legs = default, Option ticketNumber = default) + { + _LegsOption = legs; + _TicketNumberOption = ticketNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Airline() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LegsOption { get; private set; } + + /// + /// Details about the flight legs for this ticket. + /// + /// Details about the flight legs for this ticket. + [JsonPropertyName("legs")] + public List? Legs { get { return this._LegsOption; } set { this._LegsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TicketNumberOption { get; private set; } + + /// + /// The ticket's unique identifier + /// + /// The ticket's unique identifier + [JsonPropertyName("ticketNumber")] + public string? TicketNumber { get { return this._TicketNumberOption; } set { this._TicketNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Airline {\n"); + sb.Append(" Legs: ").Append(Legs).Append("\n"); + sb.Append(" TicketNumber: ").Append(TicketNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AirlineJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Airline Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> legs = default; + Option ticketNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "legs": + legs = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "ticketNumber": + ticketNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Airline(legs, ticketNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, airline, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Airline airline, JsonSerializerOptions jsonSerializerOptions) + { + + if (airline._LegsOption.IsSet) + { + writer.WritePropertyName("legs"); + JsonSerializer.Serialize(writer, airline.Legs, jsonSerializerOptions); + } + if (airline._TicketNumberOption.IsSet) + if (airline.TicketNumber != null) + writer.WriteString("ticketNumber", airline.TicketNumber); + } + } +} diff --git a/Adyen/Transfers/Models/Amount.cs b/Adyen/Transfers/Models/Amount.cs new file mode 100644 index 000000000..21a1e89d9 --- /dev/null +++ b/Adyen/Transfers/Models/Amount.cs @@ -0,0 +1,202 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Amount. + /// + public partial class Amount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonConstructor] + public Amount(string currency, long value) + { + Currency = currency; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Amount() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + [JsonPropertyName("value")] + public long Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Amount {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Currency (string) maxLength + if (this.Currency != null && this.Currency.Length > 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be less than 3.", new [] { "Currency" }); + } + + // Currency (string) minLength + if (this.Currency != null && this.Currency.Length < 3) + { + yield return new ValidationResult("Invalid value for Currency, length must be greater than 3.", new [] { "Currency" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Amount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(currency)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class Amount.", nameof(value)); + + return new Amount(currency.Value!, value.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amount, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Amount amount, JsonSerializerOptions jsonSerializerOptions) + { + + if (amount.Currency != null) + writer.WriteString("currency", amount.Currency); + + writer.WriteNumber("value", amount.Value); + } + } +} diff --git a/Adyen/Transfers/Models/AmountAdjustment.cs b/Adyen/Transfers/Models/AmountAdjustment.cs new file mode 100644 index 000000000..13fa53206 --- /dev/null +++ b/Adyen/Transfers/Models/AmountAdjustment.cs @@ -0,0 +1,350 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// AmountAdjustment. + /// + public partial class AmountAdjustment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// The basepoints associated with the applied markup. + [JsonConstructor] + public AmountAdjustment(Option amount = default, Option amountAdjustmentType = default, Option basepoints = default) + { + _AmountOption = amount; + _AmountAdjustmentTypeOption = amountAdjustmentType; + _BasepointsOption = basepoints; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public AmountAdjustment() + { + } + + partial void OnCreated(); + + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + [JsonConverter(typeof(AmountAdjustmentTypeEnumJsonConverter))] + public class AmountAdjustmentTypeEnum : IEnum + { + /// + /// Returns the value of the AmountAdjustmentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AmountAdjustmentTypeEnum.AtmMarkup - atmMarkup + /// + public static readonly AmountAdjustmentTypeEnum AtmMarkup = new("atmMarkup"); + + /// + /// AmountAdjustmentTypeEnum.AuthHoldReserve - authHoldReserve + /// + public static readonly AmountAdjustmentTypeEnum AuthHoldReserve = new("authHoldReserve"); + + /// + /// AmountAdjustmentTypeEnum.Exchange - exchange + /// + public static readonly AmountAdjustmentTypeEnum Exchange = new("exchange"); + + /// + /// AmountAdjustmentTypeEnum.ForexMarkup - forexMarkup + /// + public static readonly AmountAdjustmentTypeEnum ForexMarkup = new("forexMarkup"); + + private AmountAdjustmentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AmountAdjustmentTypeEnum?(string? value) => value == null ? null : new AmountAdjustmentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AmountAdjustmentTypeEnum? option) => option?.Value; + + public static bool operator ==(AmountAdjustmentTypeEnum? left, AmountAdjustmentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AmountAdjustmentTypeEnum? left, AmountAdjustmentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AmountAdjustmentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AmountAdjustmentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "atmMarkup" => AmountAdjustmentTypeEnum.AtmMarkup, + "authHoldReserve" => AmountAdjustmentTypeEnum.AuthHoldReserve, + "exchange" => AmountAdjustmentTypeEnum.Exchange, + "forexMarkup" => AmountAdjustmentTypeEnum.ForexMarkup, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AmountAdjustmentTypeEnum? value) + { + if (value == null) + return null; + + if (value == AmountAdjustmentTypeEnum.AtmMarkup) + return "atmMarkup"; + + if (value == AmountAdjustmentTypeEnum.AuthHoldReserve) + return "authHoldReserve"; + + if (value == AmountAdjustmentTypeEnum.Exchange) + return "exchange"; + + if (value == AmountAdjustmentTypeEnum.ForexMarkup) + return "forexMarkup"; + + return null; + } + + /// + /// JsonConverter for writing AmountAdjustmentTypeEnum. + /// + public class AmountAdjustmentTypeEnumJsonConverter : JsonConverter + { + public override AmountAdjustmentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AmountAdjustmentTypeEnum.FromStringOrDefault(value) ?? new AmountAdjustmentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AmountAdjustmentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AmountAdjustmentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountAdjustmentTypeOption { get; private set; } + + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + /// + /// The type of markup that is applied to an authorised payment. Possible values: **exchange**, **forexMarkup**, **authHoldReserve**, **atmMarkup**. + [JsonPropertyName("amountAdjustmentType")] + public AmountAdjustmentTypeEnum? AmountAdjustmentType { get { return this._AmountAdjustmentTypeOption; } set { this._AmountAdjustmentTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BasepointsOption { get; private set; } + + /// + /// The basepoints associated with the applied markup. + /// + /// The basepoints associated with the applied markup. + [JsonPropertyName("basepoints")] + public int? Basepoints { get { return this._BasepointsOption; } set { this._BasepointsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AmountAdjustment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" AmountAdjustmentType: ").Append(AmountAdjustmentType).Append("\n"); + sb.Append(" Basepoints: ").Append(Basepoints).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AmountAdjustmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override AmountAdjustment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option amountAdjustmentType = default; + Option basepoints = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amountAdjustmentType": + string? amountAdjustmentTypeRawValue = utf8JsonReader.GetString(); + amountAdjustmentType = new Option(AmountAdjustment.AmountAdjustmentTypeEnum.FromStringOrDefault(amountAdjustmentTypeRawValue)); + break; + case "basepoints": + basepoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new AmountAdjustment(amount, amountAdjustmentType, basepoints); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, AmountAdjustment amountAdjustment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, amountAdjustment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, AmountAdjustment amountAdjustment, JsonSerializerOptions jsonSerializerOptions) + { + + if (amountAdjustment._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, amountAdjustment.Amount, jsonSerializerOptions); + } + if (amountAdjustment._AmountAdjustmentTypeOption.IsSet && amountAdjustment.AmountAdjustmentType != null) + { + string? amountAdjustmentTypeRawValue = AmountAdjustment.AmountAdjustmentTypeEnum.ToJsonValue(amountAdjustment._AmountAdjustmentTypeOption.Value!.Value); + writer.WriteString("amountAdjustmentType", amountAdjustmentTypeRawValue); + } + + if (amountAdjustment._BasepointsOption.IsSet) + writer.WriteNumber("basepoints", amountAdjustment._BasepointsOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/ApproveTransfersRequest.cs b/Adyen/Transfers/Models/ApproveTransfersRequest.cs new file mode 100644 index 000000000..43df829f7 --- /dev/null +++ b/Adyen/Transfers/Models/ApproveTransfersRequest.cs @@ -0,0 +1,179 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ApproveTransfersRequest. + /// + public partial class ApproveTransfersRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the unique identifiers of the transfers that you want to approve. + [JsonConstructor] + public ApproveTransfersRequest(Option?> transferIds = default) + { + _TransferIdsOption = transferIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ApproveTransfersRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferIdsOption { get; private set; } + + /// + /// Contains the unique identifiers of the transfers that you want to approve. + /// + /// Contains the unique identifiers of the transfers that you want to approve. + [JsonPropertyName("transferIds")] + public List? TransferIds { get { return this._TransferIdsOption; } set { this._TransferIdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApproveTransfersRequest {\n"); + sb.Append(" TransferIds: ").Append(TransferIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ApproveTransfersRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ApproveTransfersRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transferIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferIds": + transferIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new ApproveTransfersRequest(transferIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ApproveTransfersRequest approveTransfersRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, approveTransfersRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ApproveTransfersRequest approveTransfersRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (approveTransfersRequest._TransferIdsOption.IsSet) + { + writer.WritePropertyName("transferIds"); + JsonSerializer.Serialize(writer, approveTransfersRequest.TransferIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/BRLocalAccountIdentification.cs b/Adyen/Transfers/Models/BRLocalAccountIdentification.cs new file mode 100644 index 000000000..cfdab95aa --- /dev/null +++ b/Adyen/Transfers/Models/BRLocalAccountIdentification.cs @@ -0,0 +1,402 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// BRLocalAccountIdentification. + /// + public partial class BRLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 3-digit bank code, with leading zeros. + /// The bank account branch number, without separators or whitespace. + /// The 8-digit ISPB, with leading zeros. + /// **brLocal** (default to TypeEnum.BrLocal) + [JsonConstructor] + public BRLocalAccountIdentification(string accountNumber, string bankCode, string branchNumber, Option ispb = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + BranchNumber = branchNumber; + _IspbOption = ispb; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BRLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BrLocal - brLocal + /// + public static readonly TypeEnum BrLocal = new("brLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "brLocal" => TypeEnum.BrLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BrLocal) + return "brLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **brLocal** + /// + /// **brLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit bank code, with leading zeros. + /// + /// The 3-digit bank code, with leading zeros. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// The bank account branch number, without separators or whitespace. + /// + /// The bank account branch number, without separators or whitespace. + [JsonPropertyName("branchNumber")] + public string BranchNumber { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IspbOption { get; private set; } + + /// + /// The 8-digit ISPB, with leading zeros. + /// + /// The 8-digit ISPB, with leading zeros. + [JsonPropertyName("ispb")] + public string? Ispb { get { return this._IspbOption; } set { this._IspbOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BRLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" BranchNumber: ").Append(BranchNumber).Append("\n"); + sb.Append(" Ispb: ").Append(Ispb).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 1.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 3.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 3) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 3.", new [] { "BankCode" }); + } + + // BranchNumber (string) maxLength + if (this.BranchNumber != null && this.BranchNumber.Length > 4) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be less than 4.", new [] { "BranchNumber" }); + } + + // BranchNumber (string) minLength + if (this.BranchNumber != null && this.BranchNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for BranchNumber, length must be greater than 1.", new [] { "BranchNumber" }); + } + + // Ispb (string) maxLength + if (this.Ispb != null && this.Ispb.Length > 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be less than 8.", new [] { "Ispb" }); + } + + // Ispb (string) minLength + if (this.Ispb != null && this.Ispb.Length < 8) + { + yield return new ValidationResult("Invalid value for Ispb, length must be greater than 8.", new [] { "Ispb" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BRLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BRLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option branchNumber = default; + Option ispb = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "branchNumber": + branchNumber = new Option(utf8JsonReader.GetString()!); + break; + case "ispb": + ispb = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BRLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(bankCode)); + + if (!branchNumber.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(branchNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BRLocalAccountIdentification.", nameof(type)); + + return new BRLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, branchNumber.Value!, ispb, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bRLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BRLocalAccountIdentification bRLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (bRLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", bRLocalAccountIdentification.AccountNumber); + + if (bRLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", bRLocalAccountIdentification.BankCode); + + if (bRLocalAccountIdentification.BranchNumber != null) + writer.WriteString("branchNumber", bRLocalAccountIdentification.BranchNumber); + + if (bRLocalAccountIdentification._IspbOption.IsSet) + if (bRLocalAccountIdentification.Ispb != null) + writer.WriteString("ispb", bRLocalAccountIdentification.Ispb); + + if (bRLocalAccountIdentification.Type != null) + { + string? typeRawValue = BRLocalAccountIdentification.TypeEnum.ToJsonValue(bRLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/BalanceMutation.cs b/Adyen/Transfers/Models/BalanceMutation.cs new file mode 100644 index 000000000..72c4f61a2 --- /dev/null +++ b/Adyen/Transfers/Models/BalanceMutation.cs @@ -0,0 +1,249 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// BalanceMutation. + /// + public partial class BalanceMutation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// The amount in the payment's currency that is debited or credited on the received accounting register. + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + [JsonConstructor] + public BalanceMutation(Option balance = default, Option currency = default, Option received = default, Option reserved = default) + { + _BalanceOption = balance; + _CurrencyOption = currency; + _ReceivedOption = received; + _ReservedOption = reserved; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BalanceMutation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the balance accounting register. + [JsonPropertyName("balance")] + public long? Balance { get { return this._BalanceOption; } set { this._BalanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CurrencyOption { get; private set; } + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string? Currency { get { return this._CurrencyOption; } set { this._CurrencyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReceivedOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the received accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the received accounting register. + [JsonPropertyName("received")] + public long? Received { get { return this._ReceivedOption; } set { this._ReceivedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReservedOption { get; private set; } + + /// + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + /// + /// The amount in the payment's currency that is debited or credited on the reserved accounting register. + [JsonPropertyName("reserved")] + public long? Reserved { get { return this._ReservedOption; } set { this._ReservedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BalanceMutation {\n"); + sb.Append(" Balance: ").Append(Balance).Append("\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Received: ").Append(Received).Append("\n"); + sb.Append(" Reserved: ").Append(Reserved).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BalanceMutationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BalanceMutation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balance = default; + Option currency = default; + Option received = default; + Option reserved = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balance": + balance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "received": + received = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "reserved": + reserved = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + + return new BalanceMutation(balance, currency, received, reserved); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BalanceMutation balanceMutation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, balanceMutation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BalanceMutation balanceMutation, JsonSerializerOptions jsonSerializerOptions) + { + + if (balanceMutation._BalanceOption.IsSet) + writer.WriteNumber("balance", balanceMutation._BalanceOption.Value!.Value); + + if (balanceMutation._CurrencyOption.IsSet) + if (balanceMutation.Currency != null) + writer.WriteString("currency", balanceMutation.Currency); + + if (balanceMutation._ReceivedOption.IsSet) + writer.WriteNumber("received", balanceMutation._ReceivedOption.Value!.Value); + + if (balanceMutation._ReservedOption.IsSet) + writer.WriteNumber("reserved", balanceMutation._ReservedOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/BankAccountV3.cs b/Adyen/Transfers/Models/BankAccountV3.cs new file mode 100644 index 000000000..d11c1e7f6 --- /dev/null +++ b/Adyen/Transfers/Models/BankAccountV3.cs @@ -0,0 +1,188 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// BankAccountV3. + /// + public partial class BankAccountV3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// accountIdentification + [JsonConstructor] + public BankAccountV3(PartyIdentification accountHolder, BankAccountV3AccountIdentification accountIdentification) + { + AccountHolder = accountHolder; + AccountIdentification = accountIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankAccountV3() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public PartyIdentification AccountHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("accountIdentification")] + public BankAccountV3AccountIdentification AccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountV3 {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" AccountIdentification: ").Append(AccountIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountV3JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountV3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option accountIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "accountIdentification": + accountIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountHolder.IsSet) + throw new ArgumentException("Property is required for class BankAccountV3.", nameof(accountHolder)); + + if (!accountIdentification.IsSet) + throw new ArgumentException("Property is required for class BankAccountV3.", nameof(accountIdentification)); + + return new BankAccountV3(accountHolder.Value!, accountIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountV3 bankAccountV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankAccountV3, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountV3 bankAccountV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, bankAccountV3.AccountHolder, jsonSerializerOptions); + writer.WritePropertyName("accountIdentification"); + JsonSerializer.Serialize(writer, bankAccountV3.AccountIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Transfers/Models/BankAccountV3AccountIdentification.cs b/Adyen/Transfers/Models/BankAccountV3AccountIdentification.cs new file mode 100644 index 000000000..2e8fc447b --- /dev/null +++ b/Adyen/Transfers/Models/BankAccountV3AccountIdentification.cs @@ -0,0 +1,565 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Contains the bank account details. The fields required in this object depend on the country of the bank account and the currency of the transfer.. + /// + public partial class BankAccountV3AccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(AULocalAccountIdentification aULocalAccountIdentification) + { + AULocalAccountIdentification = aULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(BRLocalAccountIdentification bRLocalAccountIdentification) + { + BRLocalAccountIdentification = bRLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(CALocalAccountIdentification cALocalAccountIdentification) + { + CALocalAccountIdentification = cALocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(CZLocalAccountIdentification cZLocalAccountIdentification) + { + CZLocalAccountIdentification = cZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(DKLocalAccountIdentification dKLocalAccountIdentification) + { + DKLocalAccountIdentification = dKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(HKLocalAccountIdentification hKLocalAccountIdentification) + { + HKLocalAccountIdentification = hKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(HULocalAccountIdentification hULocalAccountIdentification) + { + HULocalAccountIdentification = hULocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(IbanAccountIdentification ibanAccountIdentification) + { + IbanAccountIdentification = ibanAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NOLocalAccountIdentification nOLocalAccountIdentification) + { + NOLocalAccountIdentification = nOLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NZLocalAccountIdentification nZLocalAccountIdentification) + { + NZLocalAccountIdentification = nZLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(NumberAndBicAccountIdentification numberAndBicAccountIdentification) + { + NumberAndBicAccountIdentification = numberAndBicAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(PLLocalAccountIdentification pLLocalAccountIdentification) + { + PLLocalAccountIdentification = pLLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(SELocalAccountIdentification sELocalAccountIdentification) + { + SELocalAccountIdentification = sELocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(SGLocalAccountIdentification sGLocalAccountIdentification) + { + SGLocalAccountIdentification = sGLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(UKLocalAccountIdentification uKLocalAccountIdentification) + { + UKLocalAccountIdentification = uKLocalAccountIdentification; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BankAccountV3AccountIdentification(USLocalAccountIdentification uSLocalAccountIdentification) + { + USLocalAccountIdentification = uSLocalAccountIdentification; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public AULocalAccountIdentification? AULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public BRLocalAccountIdentification? BRLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CALocalAccountIdentification? CALocalAccountIdentification { get; set; } + + /// + /// .. + /// + public CZLocalAccountIdentification? CZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public DKLocalAccountIdentification? DKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HKLocalAccountIdentification? HKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public HULocalAccountIdentification? HULocalAccountIdentification { get; set; } + + /// + /// .. + /// + public IbanAccountIdentification? IbanAccountIdentification { get; set; } + + /// + /// .. + /// + public NOLocalAccountIdentification? NOLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NZLocalAccountIdentification? NZLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public NumberAndBicAccountIdentification? NumberAndBicAccountIdentification { get; set; } + + /// + /// .. + /// + public PLLocalAccountIdentification? PLLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SELocalAccountIdentification? SELocalAccountIdentification { get; set; } + + /// + /// .. + /// + public SGLocalAccountIdentification? SGLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public UKLocalAccountIdentification? UKLocalAccountIdentification { get; set; } + + /// + /// .. + /// + public USLocalAccountIdentification? USLocalAccountIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankAccountV3AccountIdentification {\n"); + if (this.AULocalAccountIdentification != null) + sb.Append(AULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.BRLocalAccountIdentification != null) + sb.Append(BRLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CALocalAccountIdentification != null) + sb.Append(CALocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.CZLocalAccountIdentification != null) + sb.Append(CZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.DKLocalAccountIdentification != null) + sb.Append(DKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HKLocalAccountIdentification != null) + sb.Append(HKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.HULocalAccountIdentification != null) + sb.Append(HULocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.IbanAccountIdentification != null) + sb.Append(IbanAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NOLocalAccountIdentification != null) + sb.Append(NOLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NZLocalAccountIdentification != null) + sb.Append(NZLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.NumberAndBicAccountIdentification != null) + sb.Append(NumberAndBicAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.PLLocalAccountIdentification != null) + sb.Append(PLLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SELocalAccountIdentification != null) + sb.Append(SELocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.SGLocalAccountIdentification != null) + sb.Append(SGLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.UKLocalAccountIdentification != null) + sb.Append(UKLocalAccountIdentification.ToString().Replace("\n", "\n ")); + if (this.USLocalAccountIdentification != null) + sb.Append(USLocalAccountIdentification.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankAccountV3AccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankAccountV3AccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + AULocalAccountIdentification? aULocalAccountIdentification = default; + BRLocalAccountIdentification? bRLocalAccountIdentification = default; + CALocalAccountIdentification? cALocalAccountIdentification = default; + CZLocalAccountIdentification? cZLocalAccountIdentification = default; + DKLocalAccountIdentification? dKLocalAccountIdentification = default; + HKLocalAccountIdentification? hKLocalAccountIdentification = default; + HULocalAccountIdentification? hULocalAccountIdentification = default; + IbanAccountIdentification? ibanAccountIdentification = default; + NOLocalAccountIdentification? nOLocalAccountIdentification = default; + NZLocalAccountIdentification? nZLocalAccountIdentification = default; + NumberAndBicAccountIdentification? numberAndBicAccountIdentification = default; + PLLocalAccountIdentification? pLLocalAccountIdentification = default; + SELocalAccountIdentification? sELocalAccountIdentification = default; + SGLocalAccountIdentification? sGLocalAccountIdentification = default; + UKLocalAccountIdentification? uKLocalAccountIdentification = default; + USLocalAccountIdentification? uSLocalAccountIdentification = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderAULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderAULocalAccountIdentification, jsonSerializerOptions, out aULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderBRLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBRLocalAccountIdentification, jsonSerializerOptions, out bRLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCALocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCALocalAccountIdentification, jsonSerializerOptions, out cALocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderCZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderCZLocalAccountIdentification, jsonSerializerOptions, out cZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderDKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderDKLocalAccountIdentification, jsonSerializerOptions, out dKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHKLocalAccountIdentification, jsonSerializerOptions, out hKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderHULocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderHULocalAccountIdentification, jsonSerializerOptions, out hULocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderIbanAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIbanAccountIdentification, jsonSerializerOptions, out ibanAccountIdentification); + + Utf8JsonReader utf8JsonReaderNOLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNOLocalAccountIdentification, jsonSerializerOptions, out nOLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNZLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNZLocalAccountIdentification, jsonSerializerOptions, out nZLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderNumberAndBicAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderNumberAndBicAccountIdentification, jsonSerializerOptions, out numberAndBicAccountIdentification); + + Utf8JsonReader utf8JsonReaderPLLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPLLocalAccountIdentification, jsonSerializerOptions, out pLLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSELocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSELocalAccountIdentification, jsonSerializerOptions, out sELocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderSGLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderSGLocalAccountIdentification, jsonSerializerOptions, out sGLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUKLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUKLocalAccountIdentification, jsonSerializerOptions, out uKLocalAccountIdentification); + + Utf8JsonReader utf8JsonReaderUSLocalAccountIdentification = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderUSLocalAccountIdentification, jsonSerializerOptions, out uSLocalAccountIdentification); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (aULocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(aULocalAccountIdentification); + + if (bRLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(bRLocalAccountIdentification); + + if (cALocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(cALocalAccountIdentification); + + if (cZLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(cZLocalAccountIdentification); + + if (dKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(dKLocalAccountIdentification); + + if (hKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(hKLocalAccountIdentification); + + if (hULocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(hULocalAccountIdentification); + + if (ibanAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(ibanAccountIdentification); + + if (nOLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(nOLocalAccountIdentification); + + if (nZLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(nZLocalAccountIdentification); + + if (numberAndBicAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(numberAndBicAccountIdentification); + + if (pLLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(pLLocalAccountIdentification); + + if (sELocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(sELocalAccountIdentification); + + if (sGLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(sGLocalAccountIdentification); + + if (uKLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(uKLocalAccountIdentification); + + if (uSLocalAccountIdentification?.Type != null) + return new BankAccountV3AccountIdentification(uSLocalAccountIdentification); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankAccountV3AccountIdentification bankAccountV3AccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + if (bankAccountV3AccountIdentification.AULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.AULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.BRLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.BRLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.CALocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.CALocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.CZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.CZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.DKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.DKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.HKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.HKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.HULocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.HULocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.IbanAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.IbanAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NOLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NOLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NZLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NZLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.NumberAndBicAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.NumberAndBicAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.PLLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.PLLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.SELocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.SELocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.SGLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.SGLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.UKLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.UKLocalAccountIdentification, jsonSerializerOptions); + if (bankAccountV3AccountIdentification.USLocalAccountIdentification != null) + JsonSerializer.Serialize(writer, bankAccountV3AccountIdentification.USLocalAccountIdentification, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, bankAccountV3AccountIdentification, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankAccountV3AccountIdentification bankAccountV3AccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Transfers/Models/BankCategoryData.cs b/Adyen/Transfers/Models/BankCategoryData.cs new file mode 100644 index 000000000..c0b716275 --- /dev/null +++ b/Adyen/Transfers/Models/BankCategoryData.cs @@ -0,0 +1,441 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// BankCategoryData. + /// + public partial class BankCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// **bank** (default to TypeEnum.Bank) + [JsonConstructor] + public BankCategoryData(Option priority = default, Option type = default) + { + _PriorityOption = priority; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public BankCategoryData() + { + } + + partial void OnCreated(); + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// **bank** + /// + /// **bank** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Bank - bank + /// + public static readonly TypeEnum Bank = new("bank"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => TypeEnum.Bank, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Bank) + return "bank"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **bank** + /// + /// **bank** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BankCategoryData {\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BankCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override BankCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option priority = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(BankCategoryData.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(BankCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new BankCategoryData(priority, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, bankCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BankCategoryData bankCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (bankCategoryData._PriorityOption.IsSet && bankCategoryData.Priority != null) + { + string? priorityRawValue = BankCategoryData.PriorityEnum.ToJsonValue(bankCategoryData._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (bankCategoryData._TypeOption.IsSet && bankCategoryData.Type != null) + { + string? typeRawValue = BankCategoryData.TypeEnum.ToJsonValue(bankCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/CALocalAccountIdentification.cs b/Adyen/Transfers/Models/CALocalAccountIdentification.cs new file mode 100644 index 000000000..731ceebb3 --- /dev/null +++ b/Adyen/Transfers/Models/CALocalAccountIdentification.cs @@ -0,0 +1,496 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CALocalAccountIdentification. + /// + public partial class CALocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// The 3-digit institution number, without separators or whitespace. + /// The 5-digit transit number, without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **caLocal** (default to TypeEnum.CaLocal) + [JsonConstructor] + public CALocalAccountIdentification(string accountNumber, string institutionNumber, string transitNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + InstitutionNumber = institutionNumber; + TransitNumber = transitNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CALocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CaLocal - caLocal + /// + public static readonly TypeEnum CaLocal = new("caLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "caLocal" => TypeEnum.CaLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CaLocal) + return "caLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **caLocal** + /// + /// **caLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + /// + /// The 5- to 12-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit institution number, without separators or whitespace. + /// + /// The 3-digit institution number, without separators or whitespace. + [JsonPropertyName("institutionNumber")] + public string InstitutionNumber { get; set; } + + /// + /// The 5-digit transit number, without separators or whitespace. + /// + /// The 5-digit transit number, without separators or whitespace. + [JsonPropertyName("transitNumber")] + public string TransitNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CALocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" InstitutionNumber: ").Append(InstitutionNumber).Append("\n"); + sb.Append(" TransitNumber: ").Append(TransitNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 12) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 12.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 5.", new [] { "AccountNumber" }); + } + + // InstitutionNumber (string) maxLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length > 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be less than 3.", new [] { "InstitutionNumber" }); + } + + // InstitutionNumber (string) minLength + if (this.InstitutionNumber != null && this.InstitutionNumber.Length < 3) + { + yield return new ValidationResult("Invalid value for InstitutionNumber, length must be greater than 3.", new [] { "InstitutionNumber" }); + } + + // TransitNumber (string) maxLength + if (this.TransitNumber != null && this.TransitNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be less than 5.", new [] { "TransitNumber" }); + } + + // TransitNumber (string) minLength + if (this.TransitNumber != null && this.TransitNumber.Length < 5) + { + yield return new ValidationResult("Invalid value for TransitNumber, length must be greater than 5.", new [] { "TransitNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CALocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CALocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option institutionNumber = default; + Option transitNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "institutionNumber": + institutionNumber = new Option(utf8JsonReader.GetString()!); + break; + case "transitNumber": + transitNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(CALocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CALocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(accountNumber)); + + if (!institutionNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(institutionNumber)); + + if (!transitNumber.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(transitNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CALocalAccountIdentification.", nameof(type)); + + return new CALocalAccountIdentification(accountNumber.Value!, institutionNumber.Value!, transitNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cALocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CALocalAccountIdentification cALocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cALocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cALocalAccountIdentification.AccountNumber); + + if (cALocalAccountIdentification.InstitutionNumber != null) + writer.WriteString("institutionNumber", cALocalAccountIdentification.InstitutionNumber); + + if (cALocalAccountIdentification.TransitNumber != null) + writer.WriteString("transitNumber", cALocalAccountIdentification.TransitNumber); + + if (cALocalAccountIdentification._AccountTypeOption.IsSet && cALocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = CALocalAccountIdentification.AccountTypeEnum.ToJsonValue(cALocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (cALocalAccountIdentification.Type != null) + { + string? typeRawValue = CALocalAccountIdentification.TypeEnum.ToJsonValue(cALocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/CZLocalAccountIdentification.cs b/Adyen/Transfers/Models/CZLocalAccountIdentification.cs new file mode 100644 index 000000000..bb8584472 --- /dev/null +++ b/Adyen/Transfers/Models/CZLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CZLocalAccountIdentification. + /// + public partial class CZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// **czLocal** (default to TypeEnum.CzLocal) + [JsonConstructor] + public CZLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.CzLocal - czLocal + /// + public static readonly TypeEnum CzLocal = new("czLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "czLocal" => TypeEnum.CzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.CzLocal) + return "czLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **czLocal** + /// + /// **czLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + /// + /// The 2- to 16-digit bank account number (Číslo účtu) in the following format: - The optional prefix (předčíslí). - The required second part (základní část) which must be at least two non-zero digits. Examples: - **19-123457** (with prefix) - **123457** (without prefix) - **000019-0000123457** (with prefix, normalized) - **000000-0000123457** (without prefix, normalized) + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + /// + /// The 4-digit bank code (Kód banky), without separators or whitespace. + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(CZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class CZLocalAccountIdentification.", nameof(type)); + + return new CZLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CZLocalAccountIdentification cZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", cZLocalAccountIdentification.AccountNumber); + + if (cZLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", cZLocalAccountIdentification.BankCode); + + if (cZLocalAccountIdentification.Type != null) + { + string? typeRawValue = CZLocalAccountIdentification.TypeEnum.ToJsonValue(cZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/CancelTransfersRequest.cs b/Adyen/Transfers/Models/CancelTransfersRequest.cs new file mode 100644 index 000000000..966b222a6 --- /dev/null +++ b/Adyen/Transfers/Models/CancelTransfersRequest.cs @@ -0,0 +1,179 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CancelTransfersRequest. + /// + public partial class CancelTransfersRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains the unique identifiers of the transfers that you want to cancel. + [JsonConstructor] + public CancelTransfersRequest(Option?> transferIds = default) + { + _TransferIdsOption = transferIds; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CancelTransfersRequest() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TransferIdsOption { get; private set; } + + /// + /// Contains the unique identifiers of the transfers that you want to cancel. + /// + /// Contains the unique identifiers of the transfers that you want to cancel. + [JsonPropertyName("transferIds")] + public List? TransferIds { get { return this._TransferIdsOption; } set { this._TransferIdsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CancelTransfersRequest {\n"); + sb.Append(" TransferIds: ").Append(TransferIds).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CancelTransfersRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CancelTransfersRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> transferIds = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "transferIds": + transferIds = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new CancelTransfersRequest(transferIds); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CancelTransfersRequest cancelTransfersRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cancelTransfersRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CancelTransfersRequest cancelTransfersRequest, JsonSerializerOptions jsonSerializerOptions) + { + + if (cancelTransfersRequest._TransferIdsOption.IsSet) + { + writer.WritePropertyName("transferIds"); + JsonSerializer.Serialize(writer, cancelTransfersRequest.TransferIds, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/CapitalBalance.cs b/Adyen/Transfers/Models/CapitalBalance.cs new file mode 100644 index 000000000..5c77422f1 --- /dev/null +++ b/Adyen/Transfers/Models/CapitalBalance.cs @@ -0,0 +1,228 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CapitalBalance. + /// + public partial class CapitalBalance : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// Fee amount. + /// Principal amount. + /// Total amount. A sum of principal amount and fee amount. + [JsonConstructor] + public CapitalBalance(string currency, long fee, long principal, long total) + { + Currency = currency; + Fee = fee; + Principal = principal; + Total = total; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalBalance() + { + } + + partial void OnCreated(); + + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). + [JsonPropertyName("currency")] + public string Currency { get; set; } + + /// + /// Fee amount. + /// + /// Fee amount. + [JsonPropertyName("fee")] + public long Fee { get; set; } + + /// + /// Principal amount. + /// + /// Principal amount. + [JsonPropertyName("principal")] + public long Principal { get; set; } + + /// + /// Total amount. A sum of principal amount and fee amount. + /// + /// Total amount. A sum of principal amount and fee amount. + [JsonPropertyName("total")] + public long Total { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalBalance {\n"); + sb.Append(" Currency: ").Append(Currency).Append("\n"); + sb.Append(" Fee: ").Append(Fee).Append("\n"); + sb.Append(" Principal: ").Append(Principal).Append("\n"); + sb.Append(" Total: ").Append(Total).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalBalanceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalBalance Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option currency = default; + Option fee = default; + Option principal = default; + Option total = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "currency": + currency = new Option(utf8JsonReader.GetString()!); + break; + case "fee": + fee = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "principal": + principal = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "total": + total = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!currency.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(currency)); + + if (!fee.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(fee)); + + if (!principal.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(principal)); + + if (!total.IsSet) + throw new ArgumentException("Property is required for class CapitalBalance.", nameof(total)); + + return new CapitalBalance(currency.Value!, fee.Value!.Value!, principal.Value!.Value!, total.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalBalance capitalBalance, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalBalance, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalBalance capitalBalance, JsonSerializerOptions jsonSerializerOptions) + { + + if (capitalBalance.Currency != null) + writer.WriteString("currency", capitalBalance.Currency); + + writer.WriteNumber("fee", capitalBalance.Fee); + + writer.WriteNumber("principal", capitalBalance.Principal); + + writer.WriteNumber("total", capitalBalance.Total); + } + } +} diff --git a/Adyen/Transfers/Models/CapitalGrant.cs b/Adyen/Transfers/Models/CapitalGrant.cs new file mode 100644 index 000000000..1a290ea7d --- /dev/null +++ b/Adyen/Transfers/Models/CapitalGrant.cs @@ -0,0 +1,493 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CapitalGrant. + /// + public partial class CapitalGrant : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balances + /// The identifier of the grant account used for the grant. + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + /// The identifier of the grant reference. + /// The current status of the grant. Possible values: **Pending**, **Active**, **Repaid**, **WrittenOff**, **Failed**, **Revoked**. + /// amount + /// counterparty + /// fee + /// repayment + [JsonConstructor] + public CapitalGrant(CapitalBalance balances, string grantAccountId, string grantOfferId, string id, StatusEnum status, Option amount = default, Option counterparty = default, Option fee = default, Option repayment = default) + { + Balances = balances; + GrantAccountId = grantAccountId; + GrantOfferId = grantOfferId; + Id = id; + Status = status; + _AmountOption = amount; + _CounterpartyOption = counterparty; + _FeeOption = fee; + _RepaymentOption = repayment; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalGrant() + { + } + + partial void OnCreated(); + + /// + /// The current status of the grant. Possible values: **Pending**, **Active**, **Repaid**, **WrittenOff**, **Failed**, **Revoked**. + /// + /// The current status of the grant. Possible values: **Pending**, **Active**, **Repaid**, **WrittenOff**, **Failed**, **Revoked**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Pending - Pending + /// + public static readonly StatusEnum Pending = new("Pending"); + + /// + /// StatusEnum.Active - Active + /// + public static readonly StatusEnum Active = new("Active"); + + /// + /// StatusEnum.Repaid - Repaid + /// + public static readonly StatusEnum Repaid = new("Repaid"); + + /// + /// StatusEnum.Failed - Failed + /// + public static readonly StatusEnum Failed = new("Failed"); + + /// + /// StatusEnum.WrittenOff - WrittenOff + /// + public static readonly StatusEnum WrittenOff = new("WrittenOff"); + + /// + /// StatusEnum.Revoked - Revoked + /// + public static readonly StatusEnum Revoked = new("Revoked"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "Pending" => StatusEnum.Pending, + "Active" => StatusEnum.Active, + "Repaid" => StatusEnum.Repaid, + "Failed" => StatusEnum.Failed, + "WrittenOff" => StatusEnum.WrittenOff, + "Revoked" => StatusEnum.Revoked, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Pending) + return "Pending"; + + if (value == StatusEnum.Active) + return "Active"; + + if (value == StatusEnum.Repaid) + return "Repaid"; + + if (value == StatusEnum.Failed) + return "Failed"; + + if (value == StatusEnum.WrittenOff) + return "WrittenOff"; + + if (value == StatusEnum.Revoked) + return "Revoked"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The current status of the grant. Possible values: **Pending**, **Active**, **Repaid**, **WrittenOff**, **Failed**, **Revoked**. + /// + /// The current status of the grant. Possible values: **Pending**, **Active**, **Repaid**, **WrittenOff**, **Failed**, **Revoked**. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("balances")] + public CapitalBalance Balances { get; set; } + + /// + /// The identifier of the grant account used for the grant. + /// + /// The identifier of the grant account used for the grant. + [JsonPropertyName("grantAccountId")] + public string GrantAccountId { get; set; } + + /// + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + /// + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + [JsonPropertyName("grantOfferId")] + public string GrantOfferId { get; set; } + + /// + /// The identifier of the grant reference. + /// + /// The identifier of the grant reference. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public Counterparty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FeeOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("fee")] + public Fee? Fee { get { return this._FeeOption; } set { this._FeeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RepaymentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("repayment")] + public Repayment? Repayment { get { return this._RepaymentOption; } set { this._RepaymentOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalGrant {\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" GrantAccountId: ").Append(GrantAccountId).Append("\n"); + sb.Append(" GrantOfferId: ").Append(GrantOfferId).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Fee: ").Append(Fee).Append("\n"); + sb.Append(" Repayment: ").Append(Repayment).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalGrantJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalGrant Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balances = default; + Option grantAccountId = default; + Option grantOfferId = default; + Option id = default; + Option status = default; + Option amount = default; + Option counterparty = default; + Option fee = default; + Option repayment = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balances": + balances = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "grantAccountId": + grantAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "grantOfferId": + grantOfferId = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(CapitalGrant.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "fee": + fee = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "repayment": + repayment = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!balances.IsSet) + throw new ArgumentException("Property is required for class CapitalGrant.", nameof(balances)); + + if (!grantAccountId.IsSet) + throw new ArgumentException("Property is required for class CapitalGrant.", nameof(grantAccountId)); + + if (!grantOfferId.IsSet) + throw new ArgumentException("Property is required for class CapitalGrant.", nameof(grantOfferId)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CapitalGrant.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class CapitalGrant.", nameof(status)); + + return new CapitalGrant(balances.Value!, grantAccountId.Value!, grantOfferId.Value!, id.Value!, status.Value!.Value!, amount, counterparty, fee, repayment); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalGrant capitalGrant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalGrant, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalGrant capitalGrant, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, capitalGrant.Balances, jsonSerializerOptions); + if (capitalGrant.GrantAccountId != null) + writer.WriteString("grantAccountId", capitalGrant.GrantAccountId); + + if (capitalGrant.GrantOfferId != null) + writer.WriteString("grantOfferId", capitalGrant.GrantOfferId); + + if (capitalGrant.Id != null) + writer.WriteString("id", capitalGrant.Id); + + if (capitalGrant.Status != null) + { + string? statusRawValue = CapitalGrant.StatusEnum.ToJsonValue(capitalGrant.Status); + writer.WriteString("status", statusRawValue); + } + + if (capitalGrant._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, capitalGrant.Amount, jsonSerializerOptions); + } + if (capitalGrant._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, capitalGrant.Counterparty, jsonSerializerOptions); + } + if (capitalGrant._FeeOption.IsSet) + { + writer.WritePropertyName("fee"); + JsonSerializer.Serialize(writer, capitalGrant.Fee, jsonSerializerOptions); + } + if (capitalGrant._RepaymentOption.IsSet) + { + writer.WritePropertyName("repayment"); + JsonSerializer.Serialize(writer, capitalGrant.Repayment, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/CapitalGrantInfo.cs b/Adyen/Transfers/Models/CapitalGrantInfo.cs new file mode 100644 index 000000000..b4a154488 --- /dev/null +++ b/Adyen/Transfers/Models/CapitalGrantInfo.cs @@ -0,0 +1,217 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CapitalGrantInfo. + /// + public partial class CapitalGrantInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the grant account used for the grant. + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + /// counterparty + [JsonConstructor] + public CapitalGrantInfo(string grantAccountId, string grantOfferId, Option counterparty = default) + { + GrantAccountId = grantAccountId; + GrantOfferId = grantOfferId; + _CounterpartyOption = counterparty; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalGrantInfo() + { + } + + partial void OnCreated(); + + /// + /// The identifier of the grant account used for the grant. + /// + /// The identifier of the grant account used for the grant. + [JsonPropertyName("grantAccountId")] + public string GrantAccountId { get; set; } + + /// + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + /// + /// The identifier of the grant offer that has been selected and from which the grant details will be used. + [JsonPropertyName("grantOfferId")] + public string GrantOfferId { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public Counterparty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalGrantInfo {\n"); + sb.Append(" GrantAccountId: ").Append(GrantAccountId).Append("\n"); + sb.Append(" GrantOfferId: ").Append(GrantOfferId).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalGrantInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalGrantInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option grantAccountId = default; + Option grantOfferId = default; + Option counterparty = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "grantAccountId": + grantAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "grantOfferId": + grantOfferId = new Option(utf8JsonReader.GetString()!); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!grantAccountId.IsSet) + throw new ArgumentException("Property is required for class CapitalGrantInfo.", nameof(grantAccountId)); + + if (!grantOfferId.IsSet) + throw new ArgumentException("Property is required for class CapitalGrantInfo.", nameof(grantOfferId)); + + return new CapitalGrantInfo(grantAccountId.Value!, grantOfferId.Value!, counterparty); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalGrantInfo capitalGrantInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalGrantInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalGrantInfo capitalGrantInfo, JsonSerializerOptions jsonSerializerOptions) + { + + if (capitalGrantInfo.GrantAccountId != null) + writer.WriteString("grantAccountId", capitalGrantInfo.GrantAccountId); + + if (capitalGrantInfo.GrantOfferId != null) + writer.WriteString("grantOfferId", capitalGrantInfo.GrantOfferId); + + if (capitalGrantInfo._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, capitalGrantInfo.Counterparty, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/CapitalGrants.cs b/Adyen/Transfers/Models/CapitalGrants.cs new file mode 100644 index 000000000..6073c459e --- /dev/null +++ b/Adyen/Transfers/Models/CapitalGrants.cs @@ -0,0 +1,171 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CapitalGrants. + /// + public partial class CapitalGrants : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the grant. + [JsonConstructor] + public CapitalGrants(List grants) + { + Grants = grants; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CapitalGrants() + { + } + + partial void OnCreated(); + + /// + /// The unique identifier of the grant. + /// + /// The unique identifier of the grant. + [JsonPropertyName("grants")] + public List Grants { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CapitalGrants {\n"); + sb.Append(" Grants: ").Append(Grants).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CapitalGrantsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CapitalGrants Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> grants = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "grants": + grants = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!grants.IsSet) + throw new ArgumentException("Property is required for class CapitalGrants.", nameof(grants)); + + return new CapitalGrants(grants.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CapitalGrants capitalGrants, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, capitalGrants, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CapitalGrants capitalGrants, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("grants"); + JsonSerializer.Serialize(writer, capitalGrants.Grants, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Transfers/Models/Card.cs b/Adyen/Transfers/Models/Card.cs new file mode 100644 index 000000000..0941582c2 --- /dev/null +++ b/Adyen/Transfers/Models/Card.cs @@ -0,0 +1,188 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Card. + /// + public partial class Card : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cardHolder + /// cardIdentification + [JsonConstructor] + public Card(PartyIdentification cardHolder, CardIdentification cardIdentification) + { + CardHolder = cardHolder; + CardIdentification = cardIdentification; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Card() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("cardHolder")] + public PartyIdentification CardHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("cardIdentification")] + public CardIdentification CardIdentification { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Card {\n"); + sb.Append(" CardHolder: ").Append(CardHolder).Append("\n"); + sb.Append(" CardIdentification: ").Append(CardIdentification).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Card Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option cardHolder = default; + Option cardIdentification = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "cardHolder": + cardHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "cardIdentification": + cardIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!cardHolder.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardHolder)); + + if (!cardIdentification.IsSet) + throw new ArgumentException("Property is required for class Card.", nameof(cardIdentification)); + + return new Card(cardHolder.Value!, cardIdentification.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, card, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Card card, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("cardHolder"); + JsonSerializer.Serialize(writer, card.CardHolder, jsonSerializerOptions); + writer.WritePropertyName("cardIdentification"); + JsonSerializer.Serialize(writer, card.CardIdentification, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Transfers/Models/CardIdentification.cs b/Adyen/Transfers/Models/CardIdentification.cs new file mode 100644 index 000000000..441076ef9 --- /dev/null +++ b/Adyen/Transfers/Models/CardIdentification.cs @@ -0,0 +1,399 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CardIdentification. + /// + public partial class CardIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// The expiry year of the card. Format: four digits. For example: 2020 + /// The issue number of the card. Applies only to some UK debit cards. + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + [JsonConstructor] + public CardIdentification(Option expiryMonth = default, Option expiryYear = default, Option issueNumber = default, Option number = default, Option startMonth = default, Option startYear = default, Option storedPaymentMethodId = default) + { + _ExpiryMonthOption = expiryMonth; + _ExpiryYearOption = expiryYear; + _IssueNumberOption = issueNumber; + _NumberOption = number; + _StartMonthOption = startMonth; + _StartYearOption = startYear; + _StoredPaymentMethodIdOption = storedPaymentMethodId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CardIdentification() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryMonthOption { get; private set; } + + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// + /// The expiry month of the card. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + [JsonPropertyName("expiryMonth")] + public string? ExpiryMonth { get { return this._ExpiryMonthOption; } set { this._ExpiryMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExpiryYearOption { get; private set; } + + /// + /// The expiry year of the card. Format: four digits. For example: 2020 + /// + /// The expiry year of the card. Format: four digits. For example: 2020 + [JsonPropertyName("expiryYear")] + public string? ExpiryYear { get { return this._ExpiryYearOption; } set { this._ExpiryYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IssueNumberOption { get; private set; } + + /// + /// The issue number of the card. Applies only to some UK debit cards. + /// + /// The issue number of the card. Applies only to some UK debit cards. + [JsonPropertyName("issueNumber")] + public string? IssueNumber { get { return this._IssueNumberOption; } set { this._IssueNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOption { get; private set; } + + /// + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + /// + /// The card number without any separators. For security, the response only includes the last four digits of the card number. + [JsonPropertyName("number")] + public string? Number { get { return this._NumberOption; } set { this._NumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartMonthOption { get; private set; } + + /// + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + /// + /// The month when the card was issued. Applies only to some UK debit cards. Format: two digits. Add a leading zero for single-digit months. For example: * 03 = March * 11 = November + [JsonPropertyName("startMonth")] + public string? StartMonth { get { return this._StartMonthOption; } set { this._StartMonthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StartYearOption { get; private set; } + + /// + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + /// + /// The year when the card was issued. Applies only to some UK debit cards. Format: four digits. For example: 2020 + [JsonPropertyName("startYear")] + public string? StartYear { get { return this._StartYearOption; } set { this._StartYearOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StoredPaymentMethodIdOption { get; private set; } + + /// + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + /// + /// The unique [token](/payouts/payout-service/pay-out-to-cards/manage-card-information#save-card-details) created to identify the counterparty. + [JsonPropertyName("storedPaymentMethodId")] + public string? StoredPaymentMethodId { get { return this._StoredPaymentMethodIdOption; } set { this._StoredPaymentMethodIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CardIdentification {\n"); + sb.Append(" ExpiryMonth: ").Append(ExpiryMonth).Append("\n"); + sb.Append(" ExpiryYear: ").Append(ExpiryYear).Append("\n"); + sb.Append(" IssueNumber: ").Append(IssueNumber).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" StartMonth: ").Append(StartMonth).Append("\n"); + sb.Append(" StartYear: ").Append(StartYear).Append("\n"); + sb.Append(" StoredPaymentMethodId: ").Append(StoredPaymentMethodId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // ExpiryMonth (string) maxLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be less than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryMonth (string) minLength + if (this.ExpiryMonth != null && this.ExpiryMonth.Length < 2) + { + yield return new ValidationResult("Invalid value for ExpiryMonth, length must be greater than 2.", new [] { "ExpiryMonth" }); + } + + // ExpiryYear (string) maxLength + if (this.ExpiryYear != null && this.ExpiryYear.Length > 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be less than 4.", new [] { "ExpiryYear" }); + } + + // ExpiryYear (string) minLength + if (this.ExpiryYear != null && this.ExpiryYear.Length < 4) + { + yield return new ValidationResult("Invalid value for ExpiryYear, length must be greater than 4.", new [] { "ExpiryYear" }); + } + + // IssueNumber (string) maxLength + if (this.IssueNumber != null && this.IssueNumber.Length > 2) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be less than 2.", new [] { "IssueNumber" }); + } + + // IssueNumber (string) minLength + if (this.IssueNumber != null && this.IssueNumber.Length < 1) + { + yield return new ValidationResult("Invalid value for IssueNumber, length must be greater than 1.", new [] { "IssueNumber" }); + } + + // Number (string) maxLength + if (this.Number != null && this.Number.Length > 19) + { + yield return new ValidationResult("Invalid value for Number, length must be less than 19.", new [] { "Number" }); + } + + // Number (string) minLength + if (this.Number != null && this.Number.Length < 4) + { + yield return new ValidationResult("Invalid value for Number, length must be greater than 4.", new [] { "Number" }); + } + + // StartMonth (string) maxLength + if (this.StartMonth != null && this.StartMonth.Length > 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be less than 2.", new [] { "StartMonth" }); + } + + // StartMonth (string) minLength + if (this.StartMonth != null && this.StartMonth.Length < 2) + { + yield return new ValidationResult("Invalid value for StartMonth, length must be greater than 2.", new [] { "StartMonth" }); + } + + // StartYear (string) maxLength + if (this.StartYear != null && this.StartYear.Length > 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be less than 4.", new [] { "StartYear" }); + } + + // StartYear (string) minLength + if (this.StartYear != null && this.StartYear.Length < 4) + { + yield return new ValidationResult("Invalid value for StartYear, length must be greater than 4.", new [] { "StartYear" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CardIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CardIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option expiryMonth = default; + Option expiryYear = default; + Option issueNumber = default; + Option number = default; + Option startMonth = default; + Option startYear = default; + Option storedPaymentMethodId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "expiryMonth": + expiryMonth = new Option(utf8JsonReader.GetString()!); + break; + case "expiryYear": + expiryYear = new Option(utf8JsonReader.GetString()!); + break; + case "issueNumber": + issueNumber = new Option(utf8JsonReader.GetString()!); + break; + case "number": + number = new Option(utf8JsonReader.GetString()!); + break; + case "startMonth": + startMonth = new Option(utf8JsonReader.GetString()!); + break; + case "startYear": + startYear = new Option(utf8JsonReader.GetString()!); + break; + case "storedPaymentMethodId": + storedPaymentMethodId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CardIdentification(expiryMonth, expiryYear, issueNumber, number, startMonth, startYear, storedPaymentMethodId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CardIdentification cardIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, cardIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CardIdentification cardIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (cardIdentification._ExpiryMonthOption.IsSet) + if (cardIdentification.ExpiryMonth != null) + writer.WriteString("expiryMonth", cardIdentification.ExpiryMonth); + + if (cardIdentification._ExpiryYearOption.IsSet) + if (cardIdentification.ExpiryYear != null) + writer.WriteString("expiryYear", cardIdentification.ExpiryYear); + + if (cardIdentification._IssueNumberOption.IsSet) + if (cardIdentification.IssueNumber != null) + writer.WriteString("issueNumber", cardIdentification.IssueNumber); + + if (cardIdentification._NumberOption.IsSet) + if (cardIdentification.Number != null) + writer.WriteString("number", cardIdentification.Number); + + if (cardIdentification._StartMonthOption.IsSet) + if (cardIdentification.StartMonth != null) + writer.WriteString("startMonth", cardIdentification.StartMonth); + + if (cardIdentification._StartYearOption.IsSet) + if (cardIdentification.StartYear != null) + writer.WriteString("startYear", cardIdentification.StartYear); + + if (cardIdentification._StoredPaymentMethodIdOption.IsSet) + if (cardIdentification.StoredPaymentMethodId != null) + writer.WriteString("storedPaymentMethodId", cardIdentification.StoredPaymentMethodId); + } + } +} diff --git a/Adyen/Transfers/Models/ConfirmationTrackingData.cs b/Adyen/Transfers/Models/ConfirmationTrackingData.cs new file mode 100644 index 000000000..b395519b2 --- /dev/null +++ b/Adyen/Transfers/Models/ConfirmationTrackingData.cs @@ -0,0 +1,396 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ConfirmationTrackingData. + /// + public partial class ConfirmationTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. (default to TypeEnum.Confirmation) + [JsonConstructor] + public ConfirmationTrackingData(StatusEnum status, TypeEnum type = default) + { + Status = status; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ConfirmationTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.Accepted - accepted + /// + public static readonly StatusEnum Accepted = new("accepted"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "credited" => StatusEnum.Credited, + "accepted" => StatusEnum.Accepted, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.Accepted) + return "accepted"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + /// + /// The status of the transfer. Possible values: - **credited**: the funds are credited to your user's transfer instrument or bank account.- **accepted**: the request is accepted by the integration. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Confirmation - confirmation + /// + public static readonly TypeEnum Confirmation = new("confirmation"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "confirmation" => TypeEnum.Confirmation, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Confirmation) + return "confirmation"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + /// + /// The type of the tracking event. Possible values: - **confirmation**: the transfer passed Adyen's internal review. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ConfirmationTrackingData {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ConfirmationTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ConfirmationTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(ConfirmationTrackingData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(ConfirmationTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ConfirmationTrackingData.", nameof(status)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ConfirmationTrackingData.", nameof(type)); + + return new ConfirmationTrackingData(status.Value!.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ConfirmationTrackingData confirmationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, confirmationTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ConfirmationTrackingData confirmationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + if (confirmationTrackingData.Status != null) + { + string? statusRawValue = ConfirmationTrackingData.StatusEnum.ToJsonValue(confirmationTrackingData.Status); + writer.WriteString("status", statusRawValue); + } + + if (confirmationTrackingData.Type != null) + { + string? typeRawValue = ConfirmationTrackingData.TypeEnum.ToJsonValue(confirmationTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/Counterparty.cs b/Adyen/Transfers/Models/Counterparty.cs new file mode 100644 index 000000000..84d55aa32 --- /dev/null +++ b/Adyen/Transfers/Models/Counterparty.cs @@ -0,0 +1,227 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Counterparty. + /// + public partial class Counterparty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the receiving account holder. The payout will default to the primary balance account of this account holder if no `balanceAccountId` is provided. + /// The identifier of the balance account that belongs to the receiving account holder. + /// The identifier of the transfer instrument that belongs to the legal entity of the account holder. + [JsonConstructor] + public Counterparty(Option accountHolderId = default, Option balanceAccountId = default, Option transferInstrumentId = default) + { + _AccountHolderIdOption = accountHolderId; + _BalanceAccountIdOption = balanceAccountId; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Counterparty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderIdOption { get; private set; } + + /// + /// The identifier of the receiving account holder. The payout will default to the primary balance account of this account holder if no `balanceAccountId` is provided. + /// + /// The identifier of the receiving account holder. The payout will default to the primary balance account of this account holder if no `balanceAccountId` is provided. + [JsonPropertyName("accountHolderId")] + public string? AccountHolderId { get { return this._AccountHolderIdOption; } set { this._AccountHolderIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The identifier of the balance account that belongs to the receiving account holder. + /// + /// The identifier of the balance account that belongs to the receiving account holder. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The identifier of the transfer instrument that belongs to the legal entity of the account holder. + /// + /// The identifier of the transfer instrument that belongs to the legal entity of the account holder. + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Counterparty {\n"); + sb.Append(" AccountHolderId: ").Append(AccountHolderId).Append("\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Counterparty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolderId = default; + Option balanceAccountId = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolderId": + accountHolderId = new Option(utf8JsonReader.GetString()!); + break; + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Counterparty(accountHolderId, balanceAccountId, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Counterparty counterparty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterparty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Counterparty counterparty, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterparty._AccountHolderIdOption.IsSet) + if (counterparty.AccountHolderId != null) + writer.WriteString("accountHolderId", counterparty.AccountHolderId); + + if (counterparty._BalanceAccountIdOption.IsSet) + if (counterparty.BalanceAccountId != null) + writer.WriteString("balanceAccountId", counterparty.BalanceAccountId); + + if (counterparty._TransferInstrumentIdOption.IsSet) + if (counterparty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", counterparty.TransferInstrumentId); + } + } +} diff --git a/Adyen/Transfers/Models/CounterpartyInfoV3.cs b/Adyen/Transfers/Models/CounterpartyInfoV3.cs new file mode 100644 index 000000000..28139dc1c --- /dev/null +++ b/Adyen/Transfers/Models/CounterpartyInfoV3.cs @@ -0,0 +1,252 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CounterpartyInfoV3. + /// + public partial class CounterpartyInfoV3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// bankAccount + /// card + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonConstructor] + public CounterpartyInfoV3(Option balanceAccountId = default, Option bankAccount = default, Option card = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _BankAccountOption = bankAccount; + _CardOption = card; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CounterpartyInfoV3() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountV3? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CounterpartyInfoV3 {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyInfoV3JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CounterpartyInfoV3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option bankAccount = default; + Option card = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CounterpartyInfoV3(balanceAccountId, bankAccount, card, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CounterpartyInfoV3 counterpartyInfoV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterpartyInfoV3, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CounterpartyInfoV3 counterpartyInfoV3, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterpartyInfoV3._BalanceAccountIdOption.IsSet) + if (counterpartyInfoV3.BalanceAccountId != null) + writer.WriteString("balanceAccountId", counterpartyInfoV3.BalanceAccountId); + + if (counterpartyInfoV3._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, counterpartyInfoV3.BankAccount, jsonSerializerOptions); + } + if (counterpartyInfoV3._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, counterpartyInfoV3.Card, jsonSerializerOptions); + } + if (counterpartyInfoV3._TransferInstrumentIdOption.IsSet) + if (counterpartyInfoV3.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", counterpartyInfoV3.TransferInstrumentId); + } + } +} diff --git a/Adyen/Transfers/Models/CounterpartyV3.cs b/Adyen/Transfers/Models/CounterpartyV3.cs new file mode 100644 index 000000000..7e1bf80e2 --- /dev/null +++ b/Adyen/Transfers/Models/CounterpartyV3.cs @@ -0,0 +1,277 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// CounterpartyV3. + /// + public partial class CounterpartyV3 : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// bankAccount + /// card + /// merchant + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonConstructor] + public CounterpartyV3(Option balanceAccountId = default, Option bankAccount = default, Option card = default, Option merchant = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _BankAccountOption = bankAccount; + _CardOption = card; + _MerchantOption = merchant; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public CounterpartyV3() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountV3? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public MerchantData? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CounterpartyV3 {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CounterpartyV3JsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override CounterpartyV3 Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option bankAccount = default; + Option card = default; + Option merchant = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new CounterpartyV3(balanceAccountId, bankAccount, card, merchant, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CounterpartyV3 counterpartyV3, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, counterpartyV3, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CounterpartyV3 counterpartyV3, JsonSerializerOptions jsonSerializerOptions) + { + + if (counterpartyV3._BalanceAccountIdOption.IsSet) + if (counterpartyV3.BalanceAccountId != null) + writer.WriteString("balanceAccountId", counterpartyV3.BalanceAccountId); + + if (counterpartyV3._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, counterpartyV3.BankAccount, jsonSerializerOptions); + } + if (counterpartyV3._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, counterpartyV3.Card, jsonSerializerOptions); + } + if (counterpartyV3._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, counterpartyV3.Merchant, jsonSerializerOptions); + } + if (counterpartyV3._TransferInstrumentIdOption.IsSet) + if (counterpartyV3.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", counterpartyV3.TransferInstrumentId); + } + } +} diff --git a/Adyen/Transfers/Models/DKLocalAccountIdentification.cs b/Adyen/Transfers/Models/DKLocalAccountIdentification.cs new file mode 100644 index 000000000..7fee5fc51 --- /dev/null +++ b/Adyen/Transfers/Models/DKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// DKLocalAccountIdentification. + /// + public partial class DKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// **dkLocal** (default to TypeEnum.DkLocal) + [JsonConstructor] + public DKLocalAccountIdentification(string accountNumber, string bankCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + BankCode = bankCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.DkLocal - dkLocal + /// + public static readonly TypeEnum DkLocal = new("dkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "dkLocal" => TypeEnum.DkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.DkLocal) + return "dkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **dkLocal** + /// + /// **dkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + /// + /// The 4-10 digits bank account number (Kontonummer) (without separators or whitespace). + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + /// + /// The 4-digit bank code (Registreringsnummer) (without separators or whitespace). + [JsonPropertyName("bankCode")] + public string BankCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" BankCode: ").Append(BankCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // BankCode (string) maxLength + if (this.BankCode != null && this.BankCode.Length > 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be less than 4.", new [] { "BankCode" }); + } + + // BankCode (string) minLength + if (this.BankCode != null && this.BankCode.Length < 4) + { + yield return new ValidationResult("Invalid value for BankCode, length must be greater than 4.", new [] { "BankCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bankCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bankCode": + bankCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(DKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(accountNumber)); + + if (!bankCode.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(bankCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class DKLocalAccountIdentification.", nameof(type)); + + return new DKLocalAccountIdentification(accountNumber.Value!, bankCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, dKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DKLocalAccountIdentification dKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (dKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", dKLocalAccountIdentification.AccountNumber); + + if (dKLocalAccountIdentification.BankCode != null) + writer.WriteString("bankCode", dKLocalAccountIdentification.BankCode); + + if (dKLocalAccountIdentification.Type != null) + { + string? typeRawValue = DKLocalAccountIdentification.TypeEnum.ToJsonValue(dKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/DirectDebitInformation.cs b/Adyen/Transfers/Models/DirectDebitInformation.cs new file mode 100644 index 000000000..cb08986c6 --- /dev/null +++ b/Adyen/Transfers/Models/DirectDebitInformation.cs @@ -0,0 +1,260 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// DirectDebitInformation. + /// + public partial class DirectDebitInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + /// The date when the funds are deducted from your user's balance account. + /// Your unique identifier for the direct debit mandate. + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + [JsonConstructor] + public DirectDebitInformation(Option dateOfSignature = default, Option dueDate = default, Option mandateId = default, Option sequenceType = default) + { + _DateOfSignatureOption = dateOfSignature; + _DueDateOption = dueDate; + _MandateIdOption = mandateId; + _SequenceTypeOption = sequenceType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public DirectDebitInformation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfSignatureOption { get; private set; } + + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + /// + /// The date when the direct debit mandate was accepted by your user, in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. + [JsonPropertyName("dateOfSignature")] + public DateTimeOffset? DateOfSignature { get { return this._DateOfSignatureOption; } set { this._DateOfSignatureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DueDateOption { get; private set; } + + /// + /// The date when the funds are deducted from your user's balance account. + /// + /// The date when the funds are deducted from your user's balance account. + [JsonPropertyName("dueDate")] + public DateTimeOffset? DueDate { get { return this._DueDateOption; } set { this._DueDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MandateIdOption { get; private set; } + + /// + /// Your unique identifier for the direct debit mandate. + /// + /// Your unique identifier for the direct debit mandate. + [JsonPropertyName("mandateId")] + public string? MandateId { get { return this._MandateIdOption; } set { this._MandateIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SequenceTypeOption { get; private set; } + + /// + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + /// + /// Identifies the direct debit transfer's type. Possible values: **OneOff**, **First**, **Recurring**, **Final**. + [JsonPropertyName("sequenceType")] + public string? SequenceType { get { return this._SequenceTypeOption; } set { this._SequenceTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DirectDebitInformation {\n"); + sb.Append(" DateOfSignature: ").Append(DateOfSignature).Append("\n"); + sb.Append(" DueDate: ").Append(DueDate).Append("\n"); + sb.Append(" MandateId: ").Append(MandateId).Append("\n"); + sb.Append(" SequenceType: ").Append(SequenceType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DirectDebitInformationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfSignature. + /// + public static string DateOfSignatureFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize DueDate. + /// + public static string DueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override DirectDebitInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option dateOfSignature = default; + Option dueDate = default; + Option mandateId = default; + Option sequenceType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "dateOfSignature": + dateOfSignature = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "dueDate": + dueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "mandateId": + mandateId = new Option(utf8JsonReader.GetString()!); + break; + case "sequenceType": + sequenceType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new DirectDebitInformation(dateOfSignature, dueDate, mandateId, sequenceType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DirectDebitInformation directDebitInformation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, directDebitInformation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DirectDebitInformation directDebitInformation, JsonSerializerOptions jsonSerializerOptions) + { + + if (directDebitInformation._DateOfSignatureOption.IsSet) + writer.WriteString("dateOfSignature", directDebitInformation._DateOfSignatureOption.Value!.Value.ToString(DateOfSignatureFormat)); + + if (directDebitInformation._DueDateOption.IsSet) + writer.WriteString("dueDate", directDebitInformation._DueDateOption.Value!.Value.ToString(DueDateFormat)); + + if (directDebitInformation._MandateIdOption.IsSet) + if (directDebitInformation.MandateId != null) + writer.WriteString("mandateId", directDebitInformation.MandateId); + + if (directDebitInformation._SequenceTypeOption.IsSet) + if (directDebitInformation.SequenceType != null) + writer.WriteString("sequenceType", directDebitInformation.SequenceType); + } + } +} diff --git a/Adyen/Transfers/Models/EstimationTrackingData.cs b/Adyen/Transfers/Models/EstimationTrackingData.cs new file mode 100644 index 000000000..b8268fa72 --- /dev/null +++ b/Adyen/Transfers/Models/EstimationTrackingData.cs @@ -0,0 +1,293 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// EstimationTrackingData. + /// + public partial class EstimationTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The estimated time the beneficiary should have access to the funds. + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. (default to TypeEnum.Estimation) + [JsonConstructor] + public EstimationTrackingData(DateTimeOffset estimatedArrivalTime, TypeEnum type = default) + { + EstimatedArrivalTime = estimatedArrivalTime; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public EstimationTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Estimation - estimation + /// + public static readonly TypeEnum Estimation = new("estimation"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "estimation" => TypeEnum.Estimation, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Estimation) + return "estimation"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + /// + /// The type of tracking event. Possible values: - **estimation**: the estimated date and time of when the funds will be credited has been determined. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The estimated time the beneficiary should have access to the funds. + /// + /// The estimated time the beneficiary should have access to the funds. + [JsonPropertyName("estimatedArrivalTime")] + public DateTimeOffset EstimatedArrivalTime { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EstimationTrackingData {\n"); + sb.Append(" EstimatedArrivalTime: ").Append(EstimatedArrivalTime).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class EstimationTrackingDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EstimatedArrivalTime. + /// + public static string EstimatedArrivalTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override EstimationTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option estimatedArrivalTime = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "estimatedArrivalTime": + estimatedArrivalTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(EstimationTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!estimatedArrivalTime.IsSet) + throw new ArgumentException("Property is required for class EstimationTrackingData.", nameof(estimatedArrivalTime)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class EstimationTrackingData.", nameof(type)); + + return new EstimationTrackingData(estimatedArrivalTime.Value!.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, EstimationTrackingData estimationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, estimationTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, EstimationTrackingData estimationTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteString("estimatedArrivalTime", estimationTrackingData.EstimatedArrivalTime.ToString(EstimatedArrivalTimeFormat)); + + if (estimationTrackingData.Type != null) + { + string? typeRawValue = EstimationTrackingData.TypeEnum.ToJsonValue(estimationTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/ExecutionDate.cs b/Adyen/Transfers/Models/ExecutionDate.cs new file mode 100644 index 000000000..4dd8d1967 --- /dev/null +++ b/Adyen/Transfers/Models/ExecutionDate.cs @@ -0,0 +1,206 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ExecutionDate. + /// + public partial class ExecutionDate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + [JsonConstructor] + public ExecutionDate(Option date = default, Option timezone = default) + { + _DateOption = date; + _TimezoneOption = timezone; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExecutionDate() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOption { get; private set; } + + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + /// + /// The date when the transfer will be processed. This date must be: * Within 30 days of the current date. * In the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html) **YYYY-MM-DD**. For example: 2025-01-31 + [JsonPropertyName("date")] + public DateOnly? Date { get { return this._DateOption; } set { this._DateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TimezoneOption { get; private set; } + + /// + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + /// + /// The timezone that applies to the execution date. Use a timezone identifier from the [tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Example: **America/Los_Angeles**. Default value: **Europe/Amsterdam**. + [JsonPropertyName("timezone")] + public string? Timezone { get { return this._TimezoneOption; } set { this._TimezoneOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExecutionDate {\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Timezone: ").Append(Timezone).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExecutionDateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Date. + /// + public static string DateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExecutionDate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option date = default; + Option timezone = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "date": + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "timezone": + timezone = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExecutionDate(date, timezone); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExecutionDate executionDate, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, executionDate, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExecutionDate executionDate, JsonSerializerOptions jsonSerializerOptions) + { + + if (executionDate._DateOption.IsSet) + writer.WriteString("date", executionDate._DateOption.Value!.Value.ToString(DateFormat)); + + if (executionDate._TimezoneOption.IsSet) + if (executionDate.Timezone != null) + writer.WriteString("timezone", executionDate.Timezone); + } + } +} diff --git a/Adyen/Transfers/Models/ExternalReason.cs b/Adyen/Transfers/Models/ExternalReason.cs new file mode 100644 index 000000000..6b98bcce9 --- /dev/null +++ b/Adyen/Transfers/Models/ExternalReason.cs @@ -0,0 +1,227 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ExternalReason. + /// + public partial class ExternalReason : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The reason code. + /// The description of the reason code. + /// The namespace for the reason code. + [JsonConstructor] + public ExternalReason(Option code = default, Option description = default, Option @namespace = default) + { + _CodeOption = code; + _DescriptionOption = description; + _NamespaceOption = @namespace; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ExternalReason() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CodeOption { get; private set; } + + /// + /// The reason code. + /// + /// The reason code. + [JsonPropertyName("code")] + public string? Code { get { return this._CodeOption; } set { this._CodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the reason code. + /// + /// The description of the reason code. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NamespaceOption { get; private set; } + + /// + /// The namespace for the reason code. + /// + /// The namespace for the reason code. + [JsonPropertyName("namespace")] + public string? Namespace { get { return this._NamespaceOption; } set { this._NamespaceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ExternalReason {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Namespace: ").Append(Namespace).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ExternalReasonJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ExternalReason Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option code = default; + Option description = default; + Option varNamespace = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "code": + code = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "namespace": + varNamespace = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ExternalReason(code, description, varNamespace); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ExternalReason externalReason, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, externalReason, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ExternalReason externalReason, JsonSerializerOptions jsonSerializerOptions) + { + + if (externalReason._CodeOption.IsSet) + if (externalReason.Code != null) + writer.WriteString("code", externalReason.Code); + + if (externalReason._DescriptionOption.IsSet) + if (externalReason.Description != null) + writer.WriteString("description", externalReason.Description); + + if (externalReason._NamespaceOption.IsSet) + if (externalReason.Namespace != null) + writer.WriteString("namespace", externalReason.Namespace); + } + } +} diff --git a/Adyen/Transfers/Models/Fee.cs b/Adyen/Transfers/Models/Fee.cs new file mode 100644 index 000000000..1f290b48e --- /dev/null +++ b/Adyen/Transfers/Models/Fee.cs @@ -0,0 +1,170 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Fee. + /// + public partial class Fee : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public Fee(Amount amount) + { + Amount = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Fee() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Fee {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FeeJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Fee Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Fee.", nameof(amount)); + + return new Fee(amount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Fee fee, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, fee, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Fee fee, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, fee.Amount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Transfers/Models/FindTransfersResponse.cs b/Adyen/Transfers/Models/FindTransfersResponse.cs new file mode 100644 index 000000000..44a195651 --- /dev/null +++ b/Adyen/Transfers/Models/FindTransfersResponse.cs @@ -0,0 +1,204 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// FindTransfersResponse. + /// + public partial class FindTransfersResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// Contains the transfers that match the query parameters. + [JsonConstructor] + public FindTransfersResponse(Option links = default, Option?> data = default) + { + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public FindTransfersResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Contains the transfers that match the query parameters. + /// + /// Contains the transfers that match the query parameters. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FindTransfersResponse {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class FindTransfersResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override FindTransfersResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new FindTransfersResponse(links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FindTransfersResponse findTransfersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, findTransfersResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, FindTransfersResponse findTransfersResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (findTransfersResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, findTransfersResponse.Links, jsonSerializerOptions); + } + if (findTransfersResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, findTransfersResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/HKLocalAccountIdentification.cs b/Adyen/Transfers/Models/HKLocalAccountIdentification.cs new file mode 100644 index 000000000..70fcdac2e --- /dev/null +++ b/Adyen/Transfers/Models/HKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// HKLocalAccountIdentification. + /// + public partial class HKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// The 3-digit clearing code, without separators or whitespace. + /// **hkLocal** (default to TypeEnum.HkLocal) + [JsonConstructor] + public HKLocalAccountIdentification(string accountNumber, string clearingCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingCode = clearingCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HkLocal - hkLocal + /// + public static readonly TypeEnum HkLocal = new("hkLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "hkLocal" => TypeEnum.HkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HkLocal) + return "hkLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **hkLocal** + /// + /// **hkLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + /// + /// The 9- to 17-digit bank account number, without separators or whitespace. Starts with the 3-digit branch code. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 3-digit clearing code, without separators or whitespace. + /// + /// The 3-digit clearing code, without separators or whitespace. + [JsonPropertyName("clearingCode")] + public string ClearingCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingCode: ").Append(ClearingCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 17) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 17.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 9.", new [] { "AccountNumber" }); + } + + // ClearingCode (string) maxLength + if (this.ClearingCode != null && this.ClearingCode.Length > 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be less than 3.", new [] { "ClearingCode" }); + } + + // ClearingCode (string) minLength + if (this.ClearingCode != null && this.ClearingCode.Length < 3) + { + yield return new ValidationResult("Invalid value for ClearingCode, length must be greater than 3.", new [] { "ClearingCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingCode": + clearingCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingCode.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(clearingCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HKLocalAccountIdentification.", nameof(type)); + + return new HKLocalAccountIdentification(accountNumber.Value!, clearingCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HKLocalAccountIdentification hKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hKLocalAccountIdentification.AccountNumber); + + if (hKLocalAccountIdentification.ClearingCode != null) + writer.WriteString("clearingCode", hKLocalAccountIdentification.ClearingCode); + + if (hKLocalAccountIdentification.Type != null) + { + string? typeRawValue = HKLocalAccountIdentification.TypeEnum.ToJsonValue(hKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/HULocalAccountIdentification.cs b/Adyen/Transfers/Models/HULocalAccountIdentification.cs new file mode 100644 index 000000000..5f9bb512f --- /dev/null +++ b/Adyen/Transfers/Models/HULocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// HULocalAccountIdentification. + /// + public partial class HULocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 24-digit bank account number, without separators or whitespace. + /// **huLocal** (default to TypeEnum.HuLocal) + [JsonConstructor] + public HULocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public HULocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.HuLocal - huLocal + /// + public static readonly TypeEnum HuLocal = new("huLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "huLocal" => TypeEnum.HuLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.HuLocal) + return "huLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **huLocal** + /// + /// **huLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 24-digit bank account number, without separators or whitespace. + /// + /// The 24-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HULocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 24.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 24) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 24.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HULocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override HULocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(HULocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class HULocalAccountIdentification.", nameof(type)); + + return new HULocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, hULocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HULocalAccountIdentification hULocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (hULocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", hULocalAccountIdentification.AccountNumber); + + if (hULocalAccountIdentification.Type != null) + { + string? typeRawValue = HULocalAccountIdentification.TypeEnum.ToJsonValue(hULocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/IbanAccountIdentification.cs b/Adyen/Transfers/Models/IbanAccountIdentification.cs new file mode 100644 index 000000000..2e0240165 --- /dev/null +++ b/Adyen/Transfers/Models/IbanAccountIdentification.cs @@ -0,0 +1,289 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// IbanAccountIdentification. + /// + public partial class IbanAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// **iban** (default to TypeEnum.Iban) + [JsonConstructor] + public IbanAccountIdentification(string iban, TypeEnum type = default) + { + Iban = iban; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IbanAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **iban** + /// + /// **iban** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Iban - iban + /// + public static readonly TypeEnum Iban = new("iban"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "iban" => TypeEnum.Iban, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Iban) + return "iban"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **iban** + /// + /// **iban** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + /// + /// The international bank account number as defined in the [ISO-13616](https://www.iso.org/standard/81090.html) standard. + [JsonPropertyName("iban")] + public string Iban { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IbanAccountIdentification {\n"); + sb.Append(" Iban: ").Append(Iban).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IbanAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IbanAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option iban = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "iban": + iban = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IbanAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!iban.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(iban)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IbanAccountIdentification.", nameof(type)); + + return new IbanAccountIdentification(iban.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ibanAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IbanAccountIdentification ibanAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ibanAccountIdentification.Iban != null) + writer.WriteString("iban", ibanAccountIdentification.Iban); + + if (ibanAccountIdentification.Type != null) + { + string? typeRawValue = IbanAccountIdentification.TypeEnum.ToJsonValue(ibanAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/InternalCategoryData.cs b/Adyen/Transfers/Models/InternalCategoryData.cs new file mode 100644 index 000000000..cb75ec83a --- /dev/null +++ b/Adyen/Transfers/Models/InternalCategoryData.cs @@ -0,0 +1,324 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// InternalCategoryData. + /// + public partial class InternalCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// **internal** (default to TypeEnum.Internal) + [JsonConstructor] + public InternalCategoryData(Option modificationMerchantReference = default, Option modificationPspReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternalCategoryData() + { + } + + partial void OnCreated(); + + /// + /// **internal** + /// + /// **internal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Internal - internal + /// + public static readonly TypeEnum Internal = new("internal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "internal" => TypeEnum.Internal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Internal) + return "internal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **internal** + /// + /// **internal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternalCategoryData {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternalCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternalCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InternalCategoryData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new InternalCategoryData(modificationMerchantReference, modificationPspReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internalCategoryData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternalCategoryData internalCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + if (internalCategoryData._ModificationMerchantReferenceOption.IsSet) + if (internalCategoryData.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", internalCategoryData.ModificationMerchantReference); + + if (internalCategoryData._ModificationPspReferenceOption.IsSet) + if (internalCategoryData.ModificationPspReference != null) + writer.WriteString("modificationPspReference", internalCategoryData.ModificationPspReference); + + if (internalCategoryData._TypeOption.IsSet && internalCategoryData.Type != null) + { + string? typeRawValue = InternalCategoryData.TypeEnum.ToJsonValue(internalCategoryData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/InternalReviewTrackingData.cs b/Adyen/Transfers/Models/InternalReviewTrackingData.cs new file mode 100644 index 000000000..f773905a9 --- /dev/null +++ b/Adyen/Transfers/Models/InternalReviewTrackingData.cs @@ -0,0 +1,518 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// InternalReviewTrackingData. + /// + public partial class InternalReviewTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. (default to TypeEnum.InternalReview) + [JsonConstructor] + public InternalReviewTrackingData(StatusEnum status, Option reason = default, TypeEnum type = default) + { + Status = status; + _ReasonOption = reason; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InternalReviewTrackingData() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "pending" => StatusEnum.Pending, + "failed" => StatusEnum.Failed, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Pending) + return "pending"; + + if (value == StatusEnum.Failed) + return "failed"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + /// + /// The status of the transfer. Possible values: - **pending**: the transfer is under internal review by Adyen. - **failed**: the transfer failed Adyen's internal review. For details, see `reason`. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.RefusedForRegulatoryReasons - refusedForRegulatoryReasons + /// + public static readonly ReasonEnum RefusedForRegulatoryReasons = new("refusedForRegulatoryReasons"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "refusedForRegulatoryReasons" => ReasonEnum.RefusedForRegulatoryReasons, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.RefusedForRegulatoryReasons) + return "refusedForRegulatoryReasons"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + /// + /// The reason why the transfer failed Adyen's internal review. Possible values: - **refusedForRegulatoryReasons**: the transfer does not comply with Adyen's risk policy. For more information, [contact the Support Team](https://www.adyen.help/hc/en-us/requests/new). + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.InternalReview - internalReview + /// + public static readonly TypeEnum InternalReview = new("internalReview"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "internalReview" => TypeEnum.InternalReview, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.InternalReview) + return "internalReview"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + /// + /// The type of tracking event. Possible values: - **internalReview**: the transfer was flagged because it does not comply with Adyen's risk policy. + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InternalReviewTrackingData {\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InternalReviewTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InternalReviewTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option status = default; + Option reason = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(InternalReviewTrackingData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(InternalReviewTrackingData.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(InternalReviewTrackingData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!status.IsSet) + throw new ArgumentException("Property is required for class InternalReviewTrackingData.", nameof(status)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class InternalReviewTrackingData.", nameof(type)); + + return new InternalReviewTrackingData(status.Value!.Value!, reason, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InternalReviewTrackingData internalReviewTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, internalReviewTrackingData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InternalReviewTrackingData internalReviewTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + if (internalReviewTrackingData.Status != null) + { + string? statusRawValue = InternalReviewTrackingData.StatusEnum.ToJsonValue(internalReviewTrackingData.Status); + writer.WriteString("status", statusRawValue); + } + + if (internalReviewTrackingData._ReasonOption.IsSet && internalReviewTrackingData.Reason != null) + { + string? reasonRawValue = InternalReviewTrackingData.ReasonEnum.ToJsonValue(internalReviewTrackingData._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (internalReviewTrackingData.Type != null) + { + string? typeRawValue = InternalReviewTrackingData.TypeEnum.ToJsonValue(internalReviewTrackingData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/InvalidField.cs b/Adyen/Transfers/Models/InvalidField.cs new file mode 100644 index 000000000..d60d49118 --- /dev/null +++ b/Adyen/Transfers/Models/InvalidField.cs @@ -0,0 +1,211 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// InvalidField. + /// + public partial class InvalidField : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Description of the validation error. + /// The field that has an invalid value. + /// The invalid value. + [JsonConstructor] + public InvalidField(string message, string name, string value) + { + Message = message; + Name = name; + Value = value; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public InvalidField() + { + } + + partial void OnCreated(); + + /// + /// Description of the validation error. + /// + /// Description of the validation error. + [JsonPropertyName("message")] + public string Message { get; set; } + + /// + /// The field that has an invalid value. + /// + /// The field that has an invalid value. + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The invalid value. + /// + /// The invalid value. + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class InvalidField {\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Value: ").Append(Value).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class InvalidFieldJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override InvalidField Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option message = default; + Option name = default; + Option value = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "value": + value = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!message.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(message)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(name)); + + if (!value.IsSet) + throw new ArgumentException("Property is required for class InvalidField.", nameof(value)); + + return new InvalidField(message.Value!, name.Value!, value.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, invalidField, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, InvalidField invalidField, JsonSerializerOptions jsonSerializerOptions) + { + + if (invalidField.Message != null) + writer.WriteString("message", invalidField.Message); + + if (invalidField.Name != null) + writer.WriteString("name", invalidField.Name); + + if (invalidField.Value != null) + writer.WriteString("value", invalidField.Value); + } + } +} diff --git a/Adyen/Transfers/Models/IssuedCard.cs b/Adyen/Transfers/Models/IssuedCard.cs new file mode 100644 index 000000000..f1c1e4dca --- /dev/null +++ b/Adyen/Transfers/Models/IssuedCard.cs @@ -0,0 +1,787 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// IssuedCard. + /// + public partial class IssuedCard : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// relayedAuthorisationData + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// threeDSecure + /// **issuedCard** (default to TypeEnum.IssuedCard) + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonConstructor] + public IssuedCard(Option authorisationType = default, Option panEntryMode = default, Option processingType = default, Option relayedAuthorisationData = default, Option schemeTraceId = default, Option schemeUniqueTransactionId = default, Option threeDSecure = default, Option type = default, Option?> validationFacts = default) + { + _AuthorisationTypeOption = authorisationType; + _PanEntryModeOption = panEntryMode; + _ProcessingTypeOption = processingType; + _RelayedAuthorisationDataOption = relayedAuthorisationData; + _SchemeTraceIdOption = schemeTraceId; + _SchemeUniqueTransactionIdOption = schemeUniqueTransactionId; + _ThreeDSecureOption = threeDSecure; + _TypeOption = type; + _ValidationFactsOption = validationFacts; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IssuedCard() + { + } + + partial void OnCreated(); + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonConverter(typeof(PanEntryModeEnumJsonConverter))] + public class PanEntryModeEnum : IEnum + { + /// + /// Returns the value of the PanEntryModeEnum. + /// + public string? Value { get; set; } + + /// + /// PanEntryModeEnum.Chip - chip + /// + public static readonly PanEntryModeEnum Chip = new("chip"); + + /// + /// PanEntryModeEnum.Cof - cof + /// + public static readonly PanEntryModeEnum Cof = new("cof"); + + /// + /// PanEntryModeEnum.Contactless - contactless + /// + public static readonly PanEntryModeEnum Contactless = new("contactless"); + + /// + /// PanEntryModeEnum.Ecommerce - ecommerce + /// + public static readonly PanEntryModeEnum Ecommerce = new("ecommerce"); + + /// + /// PanEntryModeEnum.Magstripe - magstripe + /// + public static readonly PanEntryModeEnum Magstripe = new("magstripe"); + + /// + /// PanEntryModeEnum.Manual - manual + /// + public static readonly PanEntryModeEnum Manual = new("manual"); + + /// + /// PanEntryModeEnum.Token - token + /// + public static readonly PanEntryModeEnum Token = new("token"); + + private PanEntryModeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PanEntryModeEnum?(string? value) => value == null ? null : new PanEntryModeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PanEntryModeEnum? option) => option?.Value; + + public static bool operator ==(PanEntryModeEnum? left, PanEntryModeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PanEntryModeEnum? left, PanEntryModeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PanEntryModeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PanEntryModeEnum? FromStringOrDefault(string value) + { + return value switch { + "chip" => PanEntryModeEnum.Chip, + "cof" => PanEntryModeEnum.Cof, + "contactless" => PanEntryModeEnum.Contactless, + "ecommerce" => PanEntryModeEnum.Ecommerce, + "magstripe" => PanEntryModeEnum.Magstripe, + "manual" => PanEntryModeEnum.Manual, + "token" => PanEntryModeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PanEntryModeEnum? value) + { + if (value == null) + return null; + + if (value == PanEntryModeEnum.Chip) + return "chip"; + + if (value == PanEntryModeEnum.Cof) + return "cof"; + + if (value == PanEntryModeEnum.Contactless) + return "contactless"; + + if (value == PanEntryModeEnum.Ecommerce) + return "ecommerce"; + + if (value == PanEntryModeEnum.Magstripe) + return "magstripe"; + + if (value == PanEntryModeEnum.Manual) + return "manual"; + + if (value == PanEntryModeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing PanEntryModeEnum. + /// + public class PanEntryModeEnumJsonConverter : JsonConverter + { + public override PanEntryModeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PanEntryModeEnum.FromStringOrDefault(value) ?? new PanEntryModeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PanEntryModeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PanEntryModeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PanEntryModeOption { get; private set; } + + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + /// + /// Indicates the method used for entering the PAN to initiate a transaction. Possible values: **manual**, **chip**, **magstripe**, **contactless**, **cof**, **ecommerce**, **token**. + [JsonPropertyName("panEntryMode")] + public PanEntryModeEnum? PanEntryMode { get { return this._PanEntryModeOption; } set { this._PanEntryModeOption = new(value); } } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonConverter(typeof(ProcessingTypeEnumJsonConverter))] + public class ProcessingTypeEnum : IEnum + { + /// + /// Returns the value of the ProcessingTypeEnum. + /// + public string? Value { get; set; } + + /// + /// ProcessingTypeEnum.AtmWithdraw - atmWithdraw + /// + public static readonly ProcessingTypeEnum AtmWithdraw = new("atmWithdraw"); + + /// + /// ProcessingTypeEnum.BalanceInquiry - balanceInquiry + /// + public static readonly ProcessingTypeEnum BalanceInquiry = new("balanceInquiry"); + + /// + /// ProcessingTypeEnum.Ecommerce - ecommerce + /// + public static readonly ProcessingTypeEnum Ecommerce = new("ecommerce"); + + /// + /// ProcessingTypeEnum.Moto - moto + /// + public static readonly ProcessingTypeEnum Moto = new("moto"); + + /// + /// ProcessingTypeEnum.Pos - pos + /// + public static readonly ProcessingTypeEnum Pos = new("pos"); + + /// + /// ProcessingTypeEnum.PurchaseWithCashback - purchaseWithCashback + /// + public static readonly ProcessingTypeEnum PurchaseWithCashback = new("purchaseWithCashback"); + + /// + /// ProcessingTypeEnum.Recurring - recurring + /// + public static readonly ProcessingTypeEnum Recurring = new("recurring"); + + /// + /// ProcessingTypeEnum.Token - token + /// + public static readonly ProcessingTypeEnum Token = new("token"); + + private ProcessingTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ProcessingTypeEnum?(string? value) => value == null ? null : new ProcessingTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ProcessingTypeEnum? option) => option?.Value; + + public static bool operator ==(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ProcessingTypeEnum? left, ProcessingTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ProcessingTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ProcessingTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "atmWithdraw" => ProcessingTypeEnum.AtmWithdraw, + "balanceInquiry" => ProcessingTypeEnum.BalanceInquiry, + "ecommerce" => ProcessingTypeEnum.Ecommerce, + "moto" => ProcessingTypeEnum.Moto, + "pos" => ProcessingTypeEnum.Pos, + "purchaseWithCashback" => ProcessingTypeEnum.PurchaseWithCashback, + "recurring" => ProcessingTypeEnum.Recurring, + "token" => ProcessingTypeEnum.Token, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ProcessingTypeEnum? value) + { + if (value == null) + return null; + + if (value == ProcessingTypeEnum.AtmWithdraw) + return "atmWithdraw"; + + if (value == ProcessingTypeEnum.BalanceInquiry) + return "balanceInquiry"; + + if (value == ProcessingTypeEnum.Ecommerce) + return "ecommerce"; + + if (value == ProcessingTypeEnum.Moto) + return "moto"; + + if (value == ProcessingTypeEnum.Pos) + return "pos"; + + if (value == ProcessingTypeEnum.PurchaseWithCashback) + return "purchaseWithCashback"; + + if (value == ProcessingTypeEnum.Recurring) + return "recurring"; + + if (value == ProcessingTypeEnum.Token) + return "token"; + + return null; + } + + /// + /// JsonConverter for writing ProcessingTypeEnum. + /// + public class ProcessingTypeEnumJsonConverter : JsonConverter + { + public override ProcessingTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ProcessingTypeEnum.FromStringOrDefault(value) ?? new ProcessingTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ProcessingTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ProcessingTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ProcessingTypeOption { get; private set; } + + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + /// + /// Contains information about how the payment was processed. For example, **ecommerce** for online or **pos** for in-person payments. + [JsonPropertyName("processingType")] + public ProcessingTypeEnum? ProcessingType { get { return this._ProcessingTypeOption; } set { this._ProcessingTypeOption = new(value); } } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IssuedCard - issuedCard + /// + public static readonly TypeEnum IssuedCard = new("issuedCard"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "issuedCard" => TypeEnum.IssuedCard, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IssuedCard) + return "issuedCard"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **issuedCard** + /// + /// **issuedCard** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AuthorisationTypeOption { get; private set; } + + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + /// + /// The authorisation type. For example, **defaultAuthorisation**, **preAuthorisation**, **finalAuthorisation** + [JsonPropertyName("authorisationType")] + public string? AuthorisationType { get { return this._AuthorisationTypeOption; } set { this._AuthorisationTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RelayedAuthorisationDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("relayedAuthorisationData")] + public RelayedAuthorisationData? RelayedAuthorisationData { get { return this._RelayedAuthorisationDataOption; } set { this._RelayedAuthorisationDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeTraceIdOption { get; private set; } + + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + /// + /// The identifier of the original payment. This ID is provided by the scheme and can be alphanumeric or numeric, depending on the scheme. The `schemeTraceID` should refer to an original `schemeUniqueTransactionID` provided in an earlier payment (not necessarily processed by Adyen). A `schemeTraceId` is typically available for authorization adjustments or recurring payments. + [JsonPropertyName("schemeTraceId")] + public string? SchemeTraceId { get { return this._SchemeTraceIdOption; } set { this._SchemeTraceIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SchemeUniqueTransactionIdOption { get; private set; } + + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + /// + /// The unique identifier created by the scheme. This ID can be alphanumeric or numeric depending on the scheme. + [JsonPropertyName("schemeUniqueTransactionId")] + public string? SchemeUniqueTransactionId { get { return this._SchemeUniqueTransactionIdOption; } set { this._SchemeUniqueTransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThreeDSecureOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threeDSecure")] + public ThreeDSecure? ThreeDSecure { get { return this._ThreeDSecureOption; } set { this._ThreeDSecureOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _ValidationFactsOption { get; private set; } + + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + /// + /// The evaluation of the validation facts. See [validation checks](https://docs.adyen.com/issuing/validation-checks) for more information. + [JsonPropertyName("validationFacts")] + public List? ValidationFacts { get { return this._ValidationFactsOption; } set { this._ValidationFactsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IssuedCard {\n"); + sb.Append(" AuthorisationType: ").Append(AuthorisationType).Append("\n"); + sb.Append(" PanEntryMode: ").Append(PanEntryMode).Append("\n"); + sb.Append(" ProcessingType: ").Append(ProcessingType).Append("\n"); + sb.Append(" RelayedAuthorisationData: ").Append(RelayedAuthorisationData).Append("\n"); + sb.Append(" SchemeTraceId: ").Append(SchemeTraceId).Append("\n"); + sb.Append(" SchemeUniqueTransactionId: ").Append(SchemeUniqueTransactionId).Append("\n"); + sb.Append(" ThreeDSecure: ").Append(ThreeDSecure).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ValidationFacts: ").Append(ValidationFacts).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IssuedCardJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IssuedCard Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option authorisationType = default; + Option panEntryMode = default; + Option processingType = default; + Option relayedAuthorisationData = default; + Option schemeTraceId = default; + Option schemeUniqueTransactionId = default; + Option threeDSecure = default; + Option type = default; + Option?> validationFacts = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "authorisationType": + authorisationType = new Option(utf8JsonReader.GetString()!); + break; + case "panEntryMode": + string? panEntryModeRawValue = utf8JsonReader.GetString(); + panEntryMode = new Option(IssuedCard.PanEntryModeEnum.FromStringOrDefault(panEntryModeRawValue)); + break; + case "processingType": + string? processingTypeRawValue = utf8JsonReader.GetString(); + processingType = new Option(IssuedCard.ProcessingTypeEnum.FromStringOrDefault(processingTypeRawValue)); + break; + case "relayedAuthorisationData": + relayedAuthorisationData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "schemeTraceId": + schemeTraceId = new Option(utf8JsonReader.GetString()!); + break; + case "schemeUniqueTransactionId": + schemeUniqueTransactionId = new Option(utf8JsonReader.GetString()!); + break; + case "threeDSecure": + threeDSecure = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IssuedCard.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "validationFacts": + validationFacts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new IssuedCard(authorisationType, panEntryMode, processingType, relayedAuthorisationData, schemeTraceId, schemeUniqueTransactionId, threeDSecure, type, validationFacts); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, issuedCard, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IssuedCard issuedCard, JsonSerializerOptions jsonSerializerOptions) + { + + if (issuedCard._AuthorisationTypeOption.IsSet) + if (issuedCard.AuthorisationType != null) + writer.WriteString("authorisationType", issuedCard.AuthorisationType); + + if (issuedCard._PanEntryModeOption.IsSet && issuedCard.PanEntryMode != null) + { + string? panEntryModeRawValue = IssuedCard.PanEntryModeEnum.ToJsonValue(issuedCard._PanEntryModeOption.Value!.Value); + writer.WriteString("panEntryMode", panEntryModeRawValue); + } + + if (issuedCard._ProcessingTypeOption.IsSet && issuedCard.ProcessingType != null) + { + string? processingTypeRawValue = IssuedCard.ProcessingTypeEnum.ToJsonValue(issuedCard._ProcessingTypeOption.Value!.Value); + writer.WriteString("processingType", processingTypeRawValue); + } + + if (issuedCard._RelayedAuthorisationDataOption.IsSet) + { + writer.WritePropertyName("relayedAuthorisationData"); + JsonSerializer.Serialize(writer, issuedCard.RelayedAuthorisationData, jsonSerializerOptions); + } + if (issuedCard._SchemeTraceIdOption.IsSet) + if (issuedCard.SchemeTraceId != null) + writer.WriteString("schemeTraceId", issuedCard.SchemeTraceId); + + if (issuedCard._SchemeUniqueTransactionIdOption.IsSet) + if (issuedCard.SchemeUniqueTransactionId != null) + writer.WriteString("schemeUniqueTransactionId", issuedCard.SchemeUniqueTransactionId); + + if (issuedCard._ThreeDSecureOption.IsSet) + { + writer.WritePropertyName("threeDSecure"); + JsonSerializer.Serialize(writer, issuedCard.ThreeDSecure, jsonSerializerOptions); + } + if (issuedCard._TypeOption.IsSet && issuedCard.Type != null) + { + string? typeRawValue = IssuedCard.TypeEnum.ToJsonValue(issuedCard._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (issuedCard._ValidationFactsOption.IsSet) + { + writer.WritePropertyName("validationFacts"); + JsonSerializer.Serialize(writer, issuedCard.ValidationFacts, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/IssuingTransactionData.cs b/Adyen/Transfers/Models/IssuingTransactionData.cs new file mode 100644 index 000000000..1c0c899cd --- /dev/null +++ b/Adyen/Transfers/Models/IssuingTransactionData.cs @@ -0,0 +1,294 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// IssuingTransactionData. + /// + public partial class IssuingTransactionData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// captureCycleId associated with transfer event. + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data (default to TypeEnum.IssuingTransactionData) + [JsonConstructor] + public IssuingTransactionData(Option captureCycleId = default, TypeEnum type = default) + { + _CaptureCycleIdOption = captureCycleId; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public IssuingTransactionData() + { + } + + partial void OnCreated(); + + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.IssuingTransactionData - issuingTransactionData + /// + public static readonly TypeEnum IssuingTransactionData = new("issuingTransactionData"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "issuingTransactionData" => TypeEnum.IssuingTransactionData, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.IssuingTransactionData) + return "issuingTransactionData"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + /// + /// The type of events data. Possible values: - **issuingTransactionData**: issuing transaction data + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CaptureCycleIdOption { get; private set; } + + /// + /// captureCycleId associated with transfer event. + /// + /// captureCycleId associated with transfer event. + [JsonPropertyName("captureCycleId")] + public string? CaptureCycleId { get { return this._CaptureCycleIdOption; } set { this._CaptureCycleIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IssuingTransactionData {\n"); + sb.Append(" CaptureCycleId: ").Append(CaptureCycleId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class IssuingTransactionDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override IssuingTransactionData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option captureCycleId = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "captureCycleId": + captureCycleId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(IssuingTransactionData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class IssuingTransactionData.", nameof(type)); + + return new IssuingTransactionData(captureCycleId, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, IssuingTransactionData issuingTransactionData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, issuingTransactionData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, IssuingTransactionData issuingTransactionData, JsonSerializerOptions jsonSerializerOptions) + { + + if (issuingTransactionData._CaptureCycleIdOption.IsSet) + if (issuingTransactionData.CaptureCycleId != null) + writer.WriteString("captureCycleId", issuingTransactionData.CaptureCycleId); + + if (issuingTransactionData.Type != null) + { + string? typeRawValue = IssuingTransactionData.TypeEnum.ToJsonValue(issuingTransactionData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/Leg.cs b/Adyen/Transfers/Models/Leg.cs new file mode 100644 index 000000000..a880d0446 --- /dev/null +++ b/Adyen/Transfers/Models/Leg.cs @@ -0,0 +1,302 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Leg. + /// + public partial class Leg : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + /// The basic fare code for this leg. + /// IATA code of the carrier operating the flight. + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + /// The flight departure date. + /// The flight identifier. + [JsonConstructor] + public Leg(Option arrivalAirportCode = default, Option basicFareCode = default, Option carrierCode = default, Option departureAirportCode = default, Option departureDate = default, Option flightNumber = default) + { + _ArrivalAirportCodeOption = arrivalAirportCode; + _BasicFareCodeOption = basicFareCode; + _CarrierCodeOption = carrierCode; + _DepartureAirportCodeOption = departureAirportCode; + _DepartureDateOption = departureDate; + _FlightNumberOption = flightNumber; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Leg() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ArrivalAirportCodeOption { get; private set; } + + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + /// + /// The IATA 3-letter airport code of the destination airport. This field is required if the airline data includes leg details. + [JsonPropertyName("arrivalAirportCode")] + public string? ArrivalAirportCode { get { return this._ArrivalAirportCodeOption; } set { this._ArrivalAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BasicFareCodeOption { get; private set; } + + /// + /// The basic fare code for this leg. + /// + /// The basic fare code for this leg. + [JsonPropertyName("basicFareCode")] + public string? BasicFareCode { get { return this._BasicFareCodeOption; } set { this._BasicFareCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CarrierCodeOption { get; private set; } + + /// + /// IATA code of the carrier operating the flight. + /// + /// IATA code of the carrier operating the flight. + [JsonPropertyName("carrierCode")] + public string? CarrierCode { get { return this._CarrierCodeOption; } set { this._CarrierCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureAirportCodeOption { get; private set; } + + /// + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + /// + /// The IATA three-letter airport code of the departure airport. This field is required if the airline data includes leg details + [JsonPropertyName("departureAirportCode")] + public string? DepartureAirportCode { get { return this._DepartureAirportCodeOption; } set { this._DepartureAirportCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DepartureDateOption { get; private set; } + + /// + /// The flight departure date. + /// + /// The flight departure date. + [JsonPropertyName("departureDate")] + public string? DepartureDate { get { return this._DepartureDateOption; } set { this._DepartureDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FlightNumberOption { get; private set; } + + /// + /// The flight identifier. + /// + /// The flight identifier. + [JsonPropertyName("flightNumber")] + public string? FlightNumber { get { return this._FlightNumberOption; } set { this._FlightNumberOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Leg {\n"); + sb.Append(" ArrivalAirportCode: ").Append(ArrivalAirportCode).Append("\n"); + sb.Append(" BasicFareCode: ").Append(BasicFareCode).Append("\n"); + sb.Append(" CarrierCode: ").Append(CarrierCode).Append("\n"); + sb.Append(" DepartureAirportCode: ").Append(DepartureAirportCode).Append("\n"); + sb.Append(" DepartureDate: ").Append(DepartureDate).Append("\n"); + sb.Append(" FlightNumber: ").Append(FlightNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LegJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Leg Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option arrivalAirportCode = default; + Option basicFareCode = default; + Option carrierCode = default; + Option departureAirportCode = default; + Option departureDate = default; + Option flightNumber = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "arrivalAirportCode": + arrivalAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "basicFareCode": + basicFareCode = new Option(utf8JsonReader.GetString()!); + break; + case "carrierCode": + carrierCode = new Option(utf8JsonReader.GetString()!); + break; + case "departureAirportCode": + departureAirportCode = new Option(utf8JsonReader.GetString()!); + break; + case "departureDate": + departureDate = new Option(utf8JsonReader.GetString()!); + break; + case "flightNumber": + flightNumber = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Leg(arrivalAirportCode, basicFareCode, carrierCode, departureAirportCode, departureDate, flightNumber); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, leg, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Leg leg, JsonSerializerOptions jsonSerializerOptions) + { + + if (leg._ArrivalAirportCodeOption.IsSet) + if (leg.ArrivalAirportCode != null) + writer.WriteString("arrivalAirportCode", leg.ArrivalAirportCode); + + if (leg._BasicFareCodeOption.IsSet) + if (leg.BasicFareCode != null) + writer.WriteString("basicFareCode", leg.BasicFareCode); + + if (leg._CarrierCodeOption.IsSet) + if (leg.CarrierCode != null) + writer.WriteString("carrierCode", leg.CarrierCode); + + if (leg._DepartureAirportCodeOption.IsSet) + if (leg.DepartureAirportCode != null) + writer.WriteString("departureAirportCode", leg.DepartureAirportCode); + + if (leg._DepartureDateOption.IsSet) + if (leg.DepartureDate != null) + writer.WriteString("departureDate", leg.DepartureDate); + + if (leg._FlightNumberOption.IsSet) + if (leg.FlightNumber != null) + writer.WriteString("flightNumber", leg.FlightNumber); + } + } +} diff --git a/Adyen/Transfers/Models/Link.cs b/Adyen/Transfers/Models/Link.cs new file mode 100644 index 000000000..f21491a1e --- /dev/null +++ b/Adyen/Transfers/Models/Link.cs @@ -0,0 +1,177 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Link. + /// + public partial class Link : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The link to the resource. + [JsonConstructor] + public Link(Option href = default) + { + _HrefOption = href; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Link() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _HrefOption { get; private set; } + + /// + /// The link to the resource. + /// + /// The link to the resource. + [JsonPropertyName("href")] + public string? Href { get { return this._HrefOption; } set { this._HrefOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Link {\n"); + sb.Append(" Href: ").Append(Href).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LinkJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Link Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option href = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "href": + href = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Link(href); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Link link, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, link, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Link link, JsonSerializerOptions jsonSerializerOptions) + { + + if (link._HrefOption.IsSet) + if (link.Href != null) + writer.WriteString("href", link.Href); + } + } +} diff --git a/Adyen/Transfers/Models/Links.cs b/Adyen/Transfers/Models/Links.cs new file mode 100644 index 000000000..07db7833e --- /dev/null +++ b/Adyen/Transfers/Models/Links.cs @@ -0,0 +1,203 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Links. + /// + public partial class Links : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// next + /// prev + [JsonConstructor] + public Links(Option next = default, Option prev = default) + { + _NextOption = next; + _PrevOption = prev; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Links() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NextOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("next")] + public Link? Next { get { return this._NextOption; } set { this._NextOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PrevOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("prev")] + public Link? Prev { get { return this._PrevOption; } set { this._PrevOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Links {\n"); + sb.Append(" Next: ").Append(Next).Append("\n"); + sb.Append(" Prev: ").Append(Prev).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LinksJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Links Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option next = default; + Option prev = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "next": + next = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "prev": + prev = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new Links(next, prev); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Links links, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, links, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Links links, JsonSerializerOptions jsonSerializerOptions) + { + + if (links._NextOption.IsSet) + { + writer.WritePropertyName("next"); + JsonSerializer.Serialize(writer, links.Next, jsonSerializerOptions); + } + if (links._PrevOption.IsSet) + { + writer.WritePropertyName("prev"); + JsonSerializer.Serialize(writer, links.Prev, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/Lodging.cs b/Adyen/Transfers/Models/Lodging.cs new file mode 100644 index 000000000..f4b2eb5bf --- /dev/null +++ b/Adyen/Transfers/Models/Lodging.cs @@ -0,0 +1,201 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Lodging. + /// + public partial class Lodging : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The check-in date. + /// The total number of nights the room is booked for. + [JsonConstructor] + public Lodging(Option checkInDate = default, Option numberOfNights = default) + { + _CheckInDateOption = checkInDate; + _NumberOfNightsOption = numberOfNights; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Lodging() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CheckInDateOption { get; private set; } + + /// + /// The check-in date. + /// + /// The check-in date. + [JsonPropertyName("checkInDate")] + public string? CheckInDate { get { return this._CheckInDateOption; } set { this._CheckInDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOfNightsOption { get; private set; } + + /// + /// The total number of nights the room is booked for. + /// + /// The total number of nights the room is booked for. + [JsonPropertyName("numberOfNights")] + public int? NumberOfNights { get { return this._NumberOfNightsOption; } set { this._NumberOfNightsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Lodging {\n"); + sb.Append(" CheckInDate: ").Append(CheckInDate).Append("\n"); + sb.Append(" NumberOfNights: ").Append(NumberOfNights).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LodgingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Lodging Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option checkInDate = default; + Option numberOfNights = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "checkInDate": + checkInDate = new Option(utf8JsonReader.GetString()!); + break; + case "numberOfNights": + numberOfNights = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new Lodging(checkInDate, numberOfNights); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Lodging lodging, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, lodging, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Lodging lodging, JsonSerializerOptions jsonSerializerOptions) + { + + if (lodging._CheckInDateOption.IsSet) + if (lodging.CheckInDate != null) + writer.WriteString("checkInDate", lodging.CheckInDate); + + if (lodging._NumberOfNightsOption.IsSet) + writer.WriteNumber("numberOfNights", lodging._NumberOfNightsOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/MerchantData.cs b/Adyen/Transfers/Models/MerchantData.cs new file mode 100644 index 000000000..024fe13a0 --- /dev/null +++ b/Adyen/Transfers/Models/MerchantData.cs @@ -0,0 +1,277 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// MerchantData. + /// + public partial class MerchantData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the merchant's acquirer. + /// The merchant category code. + /// The unique identifier of the merchant. + /// nameLocation + /// The postal code of the merchant. + [JsonConstructor] + public MerchantData(Option acquirerId = default, Option mcc = default, Option merchantId = default, Option nameLocation = default, Option postalCode = default) + { + _AcquirerIdOption = acquirerId; + _MccOption = mcc; + _MerchantIdOption = merchantId; + _NameLocationOption = nameLocation; + _PostalCodeOption = postalCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerIdOption { get; private set; } + + /// + /// The unique identifier of the merchant's acquirer. + /// + /// The unique identifier of the merchant's acquirer. + [JsonPropertyName("acquirerId")] + public string? AcquirerId { get { return this._AcquirerIdOption; } set { this._AcquirerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The merchant category code. + /// + /// The merchant category code. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant. + /// + /// The unique identifier of the merchant. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameLocationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("nameLocation")] + public NameLocation? NameLocation { get { return this._NameLocationOption; } set { this._NameLocationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code of the merchant. + /// + /// The postal code of the merchant. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantData {\n"); + sb.Append(" AcquirerId: ").Append(AcquirerId).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" NameLocation: ").Append(NameLocation).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerId = default; + Option mcc = default; + Option merchantId = default; + Option nameLocation = default; + Option postalCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerId": + acquirerId = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "nameLocation": + nameLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new MerchantData(acquirerId, mcc, merchantId, nameLocation, postalCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantData merchantData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantData merchantData, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantData._AcquirerIdOption.IsSet) + if (merchantData.AcquirerId != null) + writer.WriteString("acquirerId", merchantData.AcquirerId); + + if (merchantData._MccOption.IsSet) + if (merchantData.Mcc != null) + writer.WriteString("mcc", merchantData.Mcc); + + if (merchantData._MerchantIdOption.IsSet) + if (merchantData.MerchantId != null) + writer.WriteString("merchantId", merchantData.MerchantId); + + if (merchantData._NameLocationOption.IsSet) + { + writer.WritePropertyName("nameLocation"); + JsonSerializer.Serialize(writer, merchantData.NameLocation, jsonSerializerOptions); + } + if (merchantData._PostalCodeOption.IsSet) + if (merchantData.PostalCode != null) + writer.WriteString("postalCode", merchantData.PostalCode); + } + } +} diff --git a/Adyen/Transfers/Models/MerchantPurchaseData.cs b/Adyen/Transfers/Models/MerchantPurchaseData.cs new file mode 100644 index 000000000..26fc04693 --- /dev/null +++ b/Adyen/Transfers/Models/MerchantPurchaseData.cs @@ -0,0 +1,320 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// MerchantPurchaseData. + /// + public partial class MerchantPurchaseData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// airline + /// Lodging information. + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data (default to TypeEnum.MerchantPurchaseData) + [JsonConstructor] + public MerchantPurchaseData(Option airline = default, Option?> lodging = default, TypeEnum type = default) + { + _AirlineOption = airline; + _LodgingOption = lodging; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public MerchantPurchaseData() + { + } + + partial void OnCreated(); + + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.MerchantPurchaseData - merchantPurchaseData + /// + public static readonly TypeEnum MerchantPurchaseData = new("merchantPurchaseData"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "merchantPurchaseData" => TypeEnum.MerchantPurchaseData, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.MerchantPurchaseData) + return "merchantPurchaseData"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + /// + /// The type of events data. Possible values: - **merchantPurchaseData**: merchant purchase data + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AirlineOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("airline")] + public Airline? Airline { get { return this._AirlineOption; } set { this._AirlineOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _LodgingOption { get; private set; } + + /// + /// Lodging information. + /// + /// Lodging information. + [JsonPropertyName("lodging")] + public List? Lodging { get { return this._LodgingOption; } set { this._LodgingOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MerchantPurchaseData {\n"); + sb.Append(" Airline: ").Append(Airline).Append("\n"); + sb.Append(" Lodging: ").Append(Lodging).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class MerchantPurchaseDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override MerchantPurchaseData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option airline = default; + Option?> lodging = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "airline": + airline = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "lodging": + lodging = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(MerchantPurchaseData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class MerchantPurchaseData.", nameof(type)); + + return new MerchantPurchaseData(airline, lodging, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, MerchantPurchaseData merchantPurchaseData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, merchantPurchaseData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, MerchantPurchaseData merchantPurchaseData, JsonSerializerOptions jsonSerializerOptions) + { + + if (merchantPurchaseData._AirlineOption.IsSet) + { + writer.WritePropertyName("airline"); + JsonSerializer.Serialize(writer, merchantPurchaseData.Airline, jsonSerializerOptions); + } + if (merchantPurchaseData._LodgingOption.IsSet) + { + writer.WritePropertyName("lodging"); + JsonSerializer.Serialize(writer, merchantPurchaseData.Lodging, jsonSerializerOptions); + } + if (merchantPurchaseData.Type != null) + { + string? typeRawValue = MerchantPurchaseData.TypeEnum.ToJsonValue(merchantPurchaseData.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/Modification.cs b/Adyen/Transfers/Models/Modification.cs new file mode 100644 index 000000000..88032bd43 --- /dev/null +++ b/Adyen/Transfers/Models/Modification.cs @@ -0,0 +1,968 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Modification. + /// + public partial class Modification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The direction of the money movement. + /// Our reference for the modification. + /// Your reference for the modification, used internally within your platform. + /// The status of the transfer event. + /// The type of transfer modification. + [JsonConstructor] + public Modification(Option direction = default, Option id = default, Option reference = default, Option status = default, Option type = default) + { + _DirectionOption = direction; + _IdOption = id; + _ReferenceOption = reference; + _StatusOption = status; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Modification() + { + } + + partial void OnCreated(); + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectionOption { get; private set; } + + /// + /// The direction of the money movement. + /// + /// The direction of the money movement. + [JsonPropertyName("direction")] + public string? Direction { get { return this._DirectionOption; } set { this._DirectionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// Our reference for the modification. + /// + /// Our reference for the modification. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the modification, used internally within your platform. + /// + /// Your reference for the modification, used internally within your platform. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer modification. + /// + /// The type of transfer modification. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Modification {\n"); + sb.Append(" Direction: ").Append(Direction).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ModificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Modification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option direction = default; + Option id = default; + Option reference = default; + Option status = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "direction": + direction = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Modification.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new Modification(direction, id, reference, status, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Modification modification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, modification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Modification modification, JsonSerializerOptions jsonSerializerOptions) + { + + if (modification._DirectionOption.IsSet) + if (modification.Direction != null) + writer.WriteString("direction", modification.Direction); + + if (modification._IdOption.IsSet) + if (modification.Id != null) + writer.WriteString("id", modification.Id); + + if (modification._ReferenceOption.IsSet) + if (modification.Reference != null) + writer.WriteString("reference", modification.Reference); + + if (modification._StatusOption.IsSet && modification.Status != null) + { + string? statusRawValue = Modification.StatusEnum.ToJsonValue(modification._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (modification._TypeOption.IsSet) + if (modification.Type != null) + writer.WriteString("type", modification.Type); + } + } +} diff --git a/Adyen/Transfers/Models/NOLocalAccountIdentification.cs b/Adyen/Transfers/Models/NOLocalAccountIdentification.cs new file mode 100644 index 000000000..74c76f26c --- /dev/null +++ b/Adyen/Transfers/Models/NOLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// NOLocalAccountIdentification. + /// + public partial class NOLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 11-digit bank account number, without separators or whitespace. + /// **noLocal** (default to TypeEnum.NoLocal) + [JsonConstructor] + public NOLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NOLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NoLocal - noLocal + /// + public static readonly TypeEnum NoLocal = new("noLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "noLocal" => TypeEnum.NoLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NoLocal) + return "noLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **noLocal** + /// + /// **noLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 11-digit bank account number, without separators or whitespace. + /// + /// The 11-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NOLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 11.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 11) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 11.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NOLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NOLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NOLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NOLocalAccountIdentification.", nameof(type)); + + return new NOLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nOLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NOLocalAccountIdentification nOLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nOLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nOLocalAccountIdentification.AccountNumber); + + if (nOLocalAccountIdentification.Type != null) + { + string? typeRawValue = NOLocalAccountIdentification.TypeEnum.ToJsonValue(nOLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/NZLocalAccountIdentification.cs b/Adyen/Transfers/Models/NZLocalAccountIdentification.cs new file mode 100644 index 000000000..dd957187b --- /dev/null +++ b/Adyen/Transfers/Models/NZLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// NZLocalAccountIdentification. + /// + public partial class NZLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// **nzLocal** (default to TypeEnum.NzLocal) + [JsonConstructor] + public NZLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NZLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NzLocal - nzLocal + /// + public static readonly TypeEnum NzLocal = new("nzLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "nzLocal" => TypeEnum.NzLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NzLocal) + return "nzLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **nzLocal** + /// + /// **nzLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + /// + /// The 15-16 digit bank account number. The first 2 digits are the bank number, the next 4 digits are the branch number, the next 7 digits are the account number, and the final 2-3 digits are the suffix. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NZLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 16) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 16.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 15) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 15.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NZLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NZLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NZLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NZLocalAccountIdentification.", nameof(type)); + + return new NZLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nZLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NZLocalAccountIdentification nZLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (nZLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", nZLocalAccountIdentification.AccountNumber); + + if (nZLocalAccountIdentification.Type != null) + { + string? typeRawValue = NZLocalAccountIdentification.TypeEnum.ToJsonValue(nZLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/NameLocation.cs b/Adyen/Transfers/Models/NameLocation.cs new file mode 100644 index 000000000..2ed122088 --- /dev/null +++ b/Adyen/Transfers/Models/NameLocation.cs @@ -0,0 +1,302 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// NameLocation. + /// + public partial class NameLocation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The city where the merchant is located. + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + /// The name of the merchant's shop or service. + /// The raw data. + /// The state where the merchant is located. + [JsonConstructor] + public NameLocation(Option city = default, Option country = default, Option countryOfOrigin = default, Option name = default, Option rawData = default, Option state = default) + { + _CityOption = city; + _CountryOption = country; + _CountryOfOriginOption = countryOfOrigin; + _NameOption = name; + _RawDataOption = rawData; + _StateOption = state; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NameLocation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city where the merchant is located. + /// + /// The city where the merchant is located. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + /// + /// The country where the merchant is located in [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOfOriginOption { get; private set; } + + /// + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + /// + /// The home country in [three-digit country code](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format, used for government-controlled merchants such as embassies. + [JsonPropertyName("countryOfOrigin")] + public string? CountryOfOrigin { get { return this._CountryOfOriginOption; } set { this._CountryOfOriginOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the merchant's shop or service. + /// + /// The name of the merchant's shop or service. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RawDataOption { get; private set; } + + /// + /// The raw data. + /// + /// The raw data. + [JsonPropertyName("rawData")] + public string? RawData { get { return this._RawDataOption; } set { this._RawDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StateOption { get; private set; } + + /// + /// The state where the merchant is located. + /// + /// The state where the merchant is located. + [JsonPropertyName("state")] + public string? State { get { return this._StateOption; } set { this._StateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NameLocation {\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" CountryOfOrigin: ").Append(CountryOfOrigin).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" RawData: ").Append(RawData).Append("\n"); + sb.Append(" State: ").Append(State).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NameLocationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NameLocation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option city = default; + Option country = default; + Option countryOfOrigin = default; + Option name = default; + Option rawData = default; + Option state = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "countryOfOrigin": + countryOfOrigin = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "rawData": + rawData = new Option(utf8JsonReader.GetString()!); + break; + case "state": + state = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new NameLocation(city, country, countryOfOrigin, name, rawData, state); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NameLocation nameLocation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, nameLocation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NameLocation nameLocation, JsonSerializerOptions jsonSerializerOptions) + { + + if (nameLocation._CityOption.IsSet) + if (nameLocation.City != null) + writer.WriteString("city", nameLocation.City); + + if (nameLocation._CountryOption.IsSet) + if (nameLocation.Country != null) + writer.WriteString("country", nameLocation.Country); + + if (nameLocation._CountryOfOriginOption.IsSet) + if (nameLocation.CountryOfOrigin != null) + writer.WriteString("countryOfOrigin", nameLocation.CountryOfOrigin); + + if (nameLocation._NameOption.IsSet) + if (nameLocation.Name != null) + writer.WriteString("name", nameLocation.Name); + + if (nameLocation._RawDataOption.IsSet) + if (nameLocation.RawData != null) + writer.WriteString("rawData", nameLocation.RawData); + + if (nameLocation._StateOption.IsSet) + if (nameLocation.State != null) + writer.WriteString("state", nameLocation.State); + } + } +} diff --git a/Adyen/Transfers/Models/NumberAndBicAccountIdentification.cs b/Adyen/Transfers/Models/NumberAndBicAccountIdentification.cs new file mode 100644 index 000000000..bf4ea1435 --- /dev/null +++ b/Adyen/Transfers/Models/NumberAndBicAccountIdentification.cs @@ -0,0 +1,352 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// NumberAndBicAccountIdentification. + /// + public partial class NumberAndBicAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// additionalBankIdentification + /// **numberAndBic** (default to TypeEnum.NumberAndBic) + [JsonConstructor] + public NumberAndBicAccountIdentification(string accountNumber, string bic, Option additionalBankIdentification = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _AdditionalBankIdentificationOption = additionalBankIdentification; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public NumberAndBicAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.NumberAndBic - numberAndBic + /// + public static readonly TypeEnum NumberAndBic = new("numberAndBic"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "numberAndBic" => TypeEnum.NumberAndBic, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.NumberAndBic) + return "numberAndBic"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **numberAndBic** + /// + /// **numberAndBic** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + /// + /// The bank account number, without separators or whitespace. The length and format depends on the bank or country. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdditionalBankIdentificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("additionalBankIdentification")] + public AdditionalBankIdentification? AdditionalBankIdentification { get { return this._AdditionalBankIdentificationOption; } set { this._AdditionalBankIdentificationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberAndBicAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" AdditionalBankIdentification: ").Append(AdditionalBankIdentification).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 34) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 34.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NumberAndBicAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override NumberAndBicAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option additionalBankIdentification = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "additionalBankIdentification": + additionalBankIdentification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(NumberAndBicAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(bic)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class NumberAndBicAccountIdentification.", nameof(type)); + + return new NumberAndBicAccountIdentification(accountNumber.Value!, bic.Value!, additionalBankIdentification, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, numberAndBicAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NumberAndBicAccountIdentification numberAndBicAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (numberAndBicAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", numberAndBicAccountIdentification.AccountNumber); + + if (numberAndBicAccountIdentification.Bic != null) + writer.WriteString("bic", numberAndBicAccountIdentification.Bic); + + if (numberAndBicAccountIdentification._AdditionalBankIdentificationOption.IsSet) + { + writer.WritePropertyName("additionalBankIdentification"); + JsonSerializer.Serialize(writer, numberAndBicAccountIdentification.AdditionalBankIdentification, jsonSerializerOptions); + } + if (numberAndBicAccountIdentification.Type != null) + { + string? typeRawValue = NumberAndBicAccountIdentification.TypeEnum.ToJsonValue(numberAndBicAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/PLLocalAccountIdentification.cs b/Adyen/Transfers/Models/PLLocalAccountIdentification.cs new file mode 100644 index 000000000..ae24a6b12 --- /dev/null +++ b/Adyen/Transfers/Models/PLLocalAccountIdentification.cs @@ -0,0 +1,301 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// PLLocalAccountIdentification. + /// + public partial class PLLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// **plLocal** (default to TypeEnum.PlLocal) + [JsonConstructor] + public PLLocalAccountIdentification(string accountNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PLLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlLocal - plLocal + /// + public static readonly TypeEnum PlLocal = new("plLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "plLocal" => TypeEnum.PlLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlLocal) + return "plLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **plLocal** + /// + /// **plLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + /// + /// The 26-digit bank account number ([Numer rachunku](https://pl.wikipedia.org/wiki/Numer_Rachunku_Bankowego)), without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PLLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 26.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 26) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 26.", new [] { "AccountNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PLLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PLLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PLLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(accountNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class PLLocalAccountIdentification.", nameof(type)); + + return new PLLocalAccountIdentification(accountNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, pLLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PLLocalAccountIdentification pLLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (pLLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", pLLocalAccountIdentification.AccountNumber); + + if (pLLocalAccountIdentification.Type != null) + { + string? typeRawValue = PLLocalAccountIdentification.TypeEnum.ToJsonValue(pLLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/PartyIdentification.cs b/Adyen/Transfers/Models/PartyIdentification.cs new file mode 100644 index 000000000..e64332e25 --- /dev/null +++ b/Adyen/Transfers/Models/PartyIdentification.cs @@ -0,0 +1,514 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// PartyIdentification. + /// + public partial class PartyIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// The email address of the organization or individual. Maximum length: 254 characters. + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. (default to TypeEnum.Unknown) + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonConstructor] + public PartyIdentification(Option address = default, Option dateOfBirth = default, Option email = default, Option firstName = default, Option fullName = default, Option lastName = default, Option reference = default, Option type = default, Option url = default) + { + _AddressOption = address; + _DateOfBirthOption = dateOfBirth; + _EmailOption = email; + _FirstNameOption = firstName; + _FullNameOption = fullName; + _LastNameOption = lastName; + _ReferenceOption = reference; + _TypeOption = type; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PartyIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.Unknown - unknown + /// + public static readonly TypeEnum Unknown = new("unknown"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "unknown" => TypeEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public Address? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullNameOption { get; private set; } + + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + [JsonPropertyName("fullName")] + public string? FullName { get { return this._FullNameOption; } set { this._FullNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PartyIdentification {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" FullName: ").Append(FullName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) maxLength + if (this.Email != null && this.Email.Length > 254) + { + yield return new ValidationResult("Invalid value for Email, length must be less than 254.", new [] { "Email" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + // Url (string) maxLength + if (this.Url != null && this.Url.Length > 255) + { + yield return new ValidationResult("Invalid value for Url, length must be less than 255.", new [] { "Url" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PartyIdentificationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PartyIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option dateOfBirth = default; + Option email = default; + Option firstName = default; + Option fullName = default; + Option lastName = default; + Option reference = default; + Option type = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "fullName": + fullName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PartyIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PartyIdentification(address, dateOfBirth, email, firstName, fullName, lastName, reference, type, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PartyIdentification partyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, partyIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PartyIdentification partyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (partyIdentification._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, partyIdentification.Address, jsonSerializerOptions); + } + if (partyIdentification._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", partyIdentification._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (partyIdentification._EmailOption.IsSet) + if (partyIdentification.Email != null) + writer.WriteString("email", partyIdentification.Email); + + if (partyIdentification._FirstNameOption.IsSet) + if (partyIdentification.FirstName != null) + writer.WriteString("firstName", partyIdentification.FirstName); + + if (partyIdentification._FullNameOption.IsSet) + if (partyIdentification.FullName != null) + writer.WriteString("fullName", partyIdentification.FullName); + + if (partyIdentification._LastNameOption.IsSet) + if (partyIdentification.LastName != null) + writer.WriteString("lastName", partyIdentification.LastName); + + if (partyIdentification._ReferenceOption.IsSet) + if (partyIdentification.Reference != null) + writer.WriteString("reference", partyIdentification.Reference); + + if (partyIdentification._TypeOption.IsSet && partyIdentification.Type != null) + { + string? typeRawValue = PartyIdentification.TypeEnum.ToJsonValue(partyIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (partyIdentification._UrlOption.IsSet) + if (partyIdentification.Url != null) + writer.WriteString("url", partyIdentification.Url); + } + } +} diff --git a/Adyen/Transfers/Models/PaymentInstrument.cs b/Adyen/Transfers/Models/PaymentInstrument.cs new file mode 100644 index 000000000..8aa1c677a --- /dev/null +++ b/Adyen/Transfers/Models/PaymentInstrument.cs @@ -0,0 +1,252 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// PaymentInstrument. + /// + public partial class PaymentInstrument : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + /// The type of wallet that the network token is associated with. + [JsonConstructor] + public PaymentInstrument(Option description = default, Option id = default, Option reference = default, Option tokenType = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + _TokenTypeOption = tokenType; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PaymentInstrument() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TokenTypeOption { get; private set; } + + /// + /// The type of wallet that the network token is associated with. + /// + /// The type of wallet that the network token is associated with. + [JsonPropertyName("tokenType")] + public string? TokenType { get { return this._TokenTypeOption; } set { this._TokenTypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PaymentInstrument {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" TokenType: ").Append(TokenType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PaymentInstrumentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PaymentInstrument Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + Option tokenType = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "tokenType": + tokenType = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new PaymentInstrument(description, id, reference, tokenType); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, paymentInstrument, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PaymentInstrument paymentInstrument, JsonSerializerOptions jsonSerializerOptions) + { + + if (paymentInstrument._DescriptionOption.IsSet) + if (paymentInstrument.Description != null) + writer.WriteString("description", paymentInstrument.Description); + + if (paymentInstrument._IdOption.IsSet) + if (paymentInstrument.Id != null) + writer.WriteString("id", paymentInstrument.Id); + + if (paymentInstrument._ReferenceOption.IsSet) + if (paymentInstrument.Reference != null) + writer.WriteString("reference", paymentInstrument.Reference); + + if (paymentInstrument._TokenTypeOption.IsSet) + if (paymentInstrument.TokenType != null) + writer.WriteString("tokenType", paymentInstrument.TokenType); + } + } +} diff --git a/Adyen/Transfers/Models/PlatformPayment.cs b/Adyen/Transfers/Models/PlatformPayment.cs new file mode 100644 index 000000000..048531f81 --- /dev/null +++ b/Adyen/Transfers/Models/PlatformPayment.cs @@ -0,0 +1,640 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// PlatformPayment. + /// + public partial class PlatformPayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The capture's merchant reference included in the transfer. + /// The capture reference included in the transfer. + /// The payment's merchant reference included in the transfer. + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// The payment reference included in the transfer. + /// **platformPayment** (default to TypeEnum.PlatformPayment) + [JsonConstructor] + public PlatformPayment(Option modificationMerchantReference = default, Option modificationPspReference = default, Option paymentMerchantReference = default, Option platformPaymentType = default, Option pspPaymentReference = default, Option type = default) + { + _ModificationMerchantReferenceOption = modificationMerchantReference; + _ModificationPspReferenceOption = modificationPspReference; + _PaymentMerchantReferenceOption = paymentMerchantReference; + _PlatformPaymentTypeOption = platformPaymentType; + _PspPaymentReferenceOption = pspPaymentReference; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public PlatformPayment() + { + } + + partial void OnCreated(); + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonConverter(typeof(PlatformPaymentTypeEnumJsonConverter))] + public class PlatformPaymentTypeEnum : IEnum + { + /// + /// Returns the value of the PlatformPaymentTypeEnum. + /// + public string? Value { get; set; } + + /// + /// PlatformPaymentTypeEnum.AcquiringFees - AcquiringFees + /// + public static readonly PlatformPaymentTypeEnum AcquiringFees = new("AcquiringFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenCommission - AdyenCommission + /// + public static readonly PlatformPaymentTypeEnum AdyenCommission = new("AdyenCommission"); + + /// + /// PlatformPaymentTypeEnum.AdyenFees - AdyenFees + /// + public static readonly PlatformPaymentTypeEnum AdyenFees = new("AdyenFees"); + + /// + /// PlatformPaymentTypeEnum.AdyenMarkup - AdyenMarkup + /// + public static readonly PlatformPaymentTypeEnum AdyenMarkup = new("AdyenMarkup"); + + /// + /// PlatformPaymentTypeEnum.BalanceAccount - BalanceAccount + /// + public static readonly PlatformPaymentTypeEnum BalanceAccount = new("BalanceAccount"); + + /// + /// PlatformPaymentTypeEnum.ChargebackRemainder - ChargebackRemainder + /// + public static readonly PlatformPaymentTypeEnum ChargebackRemainder = new("ChargebackRemainder"); + + /// + /// PlatformPaymentTypeEnum.Commission - Commission + /// + public static readonly PlatformPaymentTypeEnum Commission = new("Commission"); + + /// + /// PlatformPaymentTypeEnum.DCCPlatformCommission - DCCPlatformCommission + /// + public static readonly PlatformPaymentTypeEnum DCCPlatformCommission = new("DCCPlatformCommission"); + + /// + /// PlatformPaymentTypeEnum.Default - Default + /// + public static readonly PlatformPaymentTypeEnum Default = new("Default"); + + /// + /// PlatformPaymentTypeEnum.Interchange - Interchange + /// + public static readonly PlatformPaymentTypeEnum Interchange = new("Interchange"); + + /// + /// PlatformPaymentTypeEnum.PaymentFee - PaymentFee + /// + public static readonly PlatformPaymentTypeEnum PaymentFee = new("PaymentFee"); + + /// + /// PlatformPaymentTypeEnum.Remainder - Remainder + /// + public static readonly PlatformPaymentTypeEnum Remainder = new("Remainder"); + + /// + /// PlatformPaymentTypeEnum.SchemeFee - SchemeFee + /// + public static readonly PlatformPaymentTypeEnum SchemeFee = new("SchemeFee"); + + /// + /// PlatformPaymentTypeEnum.Surcharge - Surcharge + /// + public static readonly PlatformPaymentTypeEnum Surcharge = new("Surcharge"); + + /// + /// PlatformPaymentTypeEnum.Tip - Tip + /// + public static readonly PlatformPaymentTypeEnum Tip = new("Tip"); + + /// + /// PlatformPaymentTypeEnum.TopUp - TopUp + /// + public static readonly PlatformPaymentTypeEnum TopUp = new("TopUp"); + + /// + /// PlatformPaymentTypeEnum.VAT - VAT + /// + public static readonly PlatformPaymentTypeEnum VAT = new("VAT"); + + private PlatformPaymentTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PlatformPaymentTypeEnum?(string? value) => value == null ? null : new PlatformPaymentTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PlatformPaymentTypeEnum? option) => option?.Value; + + public static bool operator ==(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PlatformPaymentTypeEnum? left, PlatformPaymentTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PlatformPaymentTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PlatformPaymentTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "AcquiringFees" => PlatformPaymentTypeEnum.AcquiringFees, + "AdyenCommission" => PlatformPaymentTypeEnum.AdyenCommission, + "AdyenFees" => PlatformPaymentTypeEnum.AdyenFees, + "AdyenMarkup" => PlatformPaymentTypeEnum.AdyenMarkup, + "BalanceAccount" => PlatformPaymentTypeEnum.BalanceAccount, + "ChargebackRemainder" => PlatformPaymentTypeEnum.ChargebackRemainder, + "Commission" => PlatformPaymentTypeEnum.Commission, + "DCCPlatformCommission" => PlatformPaymentTypeEnum.DCCPlatformCommission, + "Default" => PlatformPaymentTypeEnum.Default, + "Interchange" => PlatformPaymentTypeEnum.Interchange, + "PaymentFee" => PlatformPaymentTypeEnum.PaymentFee, + "Remainder" => PlatformPaymentTypeEnum.Remainder, + "SchemeFee" => PlatformPaymentTypeEnum.SchemeFee, + "Surcharge" => PlatformPaymentTypeEnum.Surcharge, + "Tip" => PlatformPaymentTypeEnum.Tip, + "TopUp" => PlatformPaymentTypeEnum.TopUp, + "VAT" => PlatformPaymentTypeEnum.VAT, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PlatformPaymentTypeEnum? value) + { + if (value == null) + return null; + + if (value == PlatformPaymentTypeEnum.AcquiringFees) + return "AcquiringFees"; + + if (value == PlatformPaymentTypeEnum.AdyenCommission) + return "AdyenCommission"; + + if (value == PlatformPaymentTypeEnum.AdyenFees) + return "AdyenFees"; + + if (value == PlatformPaymentTypeEnum.AdyenMarkup) + return "AdyenMarkup"; + + if (value == PlatformPaymentTypeEnum.BalanceAccount) + return "BalanceAccount"; + + if (value == PlatformPaymentTypeEnum.ChargebackRemainder) + return "ChargebackRemainder"; + + if (value == PlatformPaymentTypeEnum.Commission) + return "Commission"; + + if (value == PlatformPaymentTypeEnum.DCCPlatformCommission) + return "DCCPlatformCommission"; + + if (value == PlatformPaymentTypeEnum.Default) + return "Default"; + + if (value == PlatformPaymentTypeEnum.Interchange) + return "Interchange"; + + if (value == PlatformPaymentTypeEnum.PaymentFee) + return "PaymentFee"; + + if (value == PlatformPaymentTypeEnum.Remainder) + return "Remainder"; + + if (value == PlatformPaymentTypeEnum.SchemeFee) + return "SchemeFee"; + + if (value == PlatformPaymentTypeEnum.Surcharge) + return "Surcharge"; + + if (value == PlatformPaymentTypeEnum.Tip) + return "Tip"; + + if (value == PlatformPaymentTypeEnum.TopUp) + return "TopUp"; + + if (value == PlatformPaymentTypeEnum.VAT) + return "VAT"; + + return null; + } + + /// + /// JsonConverter for writing PlatformPaymentTypeEnum. + /// + public class PlatformPaymentTypeEnumJsonConverter : JsonConverter + { + public override PlatformPaymentTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PlatformPaymentTypeEnum.FromStringOrDefault(value) ?? new PlatformPaymentTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PlatformPaymentTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PlatformPaymentTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PlatformPaymentTypeOption { get; private set; } + + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + /// + /// Specifies the nature of the transfer. This parameter helps categorize transfers so you can reconcile transactions at a later time, using the Balance Platform Accounting Report for [marketplaces](https://docs.adyen.com/marketplaces/reports-and-fees/balance-platform-accounting-report/) or [platforms](https://docs.adyen.com/platforms/reports-and-fees/balance-platform-accounting-report/). Possible values: * **AcquiringFees**: the acquiring fee (the aggregated amount of interchange and scheme fee) incurred on a transaction. * **AdyenCommission**: the transaction fee due to Adyen under [blended rates](https://www.adyen.com/knowledge-hub/guides/payments-training-guide/get-the-best-from-your-card-processing). * **AdyenFees**: all transaction fees due to Adyen. This is the aggregated amount of Adyen's commission and markup. * **AdyenMarkup**: the transaction fee due to Adyen under [Interchange++ pricing](https://www.adyen.com/pricing). * **BalanceAccount**: the amount booked to your user after the deduction of the relevant fees. * **Commission**: your platform's or marketplace's commission on a transaction. * **DCCPlatformCommission**: the Dynamic Currency Conversion (DCC) fee on a transaction. * **Interchange**: the interchange fee (fee paid to the issuer) incurred on a transaction. * **PaymentFee**: the aggregated amount of all transaction fees. * **Remainder**: the leftover amount after currency conversion. * **SchemeFee**: the scheme fee incurred on a transaction. * **Surcharge**: the surcharge paid by the customer on a transaction. * **Tip**: the tip paid by the customer. * **TopUp**: an incoming transfer to top up your user's balance account. * **VAT**: the value-added tax charged on the payment. + [JsonPropertyName("platformPaymentType")] + public PlatformPaymentTypeEnum? PlatformPaymentType { get { return this._PlatformPaymentTypeOption; } set { this._PlatformPaymentTypeOption = new(value); } } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.PlatformPayment - platformPayment + /// + public static readonly TypeEnum PlatformPayment = new("platformPayment"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "platformPayment" => TypeEnum.PlatformPayment, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.PlatformPayment) + return "platformPayment"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **platformPayment** + /// + /// **platformPayment** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationMerchantReferenceOption { get; private set; } + + /// + /// The capture's merchant reference included in the transfer. + /// + /// The capture's merchant reference included in the transfer. + [JsonPropertyName("modificationMerchantReference")] + public string? ModificationMerchantReference { get { return this._ModificationMerchantReferenceOption; } set { this._ModificationMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationPspReferenceOption { get; private set; } + + /// + /// The capture reference included in the transfer. + /// + /// The capture reference included in the transfer. + [JsonPropertyName("modificationPspReference")] + public string? ModificationPspReference { get { return this._ModificationPspReferenceOption; } set { this._ModificationPspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentMerchantReferenceOption { get; private set; } + + /// + /// The payment's merchant reference included in the transfer. + /// + /// The payment's merchant reference included in the transfer. + [JsonPropertyName("paymentMerchantReference")] + public string? PaymentMerchantReference { get { return this._PaymentMerchantReferenceOption; } set { this._PaymentMerchantReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspPaymentReferenceOption { get; private set; } + + /// + /// The payment reference included in the transfer. + /// + /// The payment reference included in the transfer. + [JsonPropertyName("pspPaymentReference")] + public string? PspPaymentReference { get { return this._PspPaymentReferenceOption; } set { this._PspPaymentReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PlatformPayment {\n"); + sb.Append(" ModificationMerchantReference: ").Append(ModificationMerchantReference).Append("\n"); + sb.Append(" ModificationPspReference: ").Append(ModificationPspReference).Append("\n"); + sb.Append(" PaymentMerchantReference: ").Append(PaymentMerchantReference).Append("\n"); + sb.Append(" PlatformPaymentType: ").Append(PlatformPaymentType).Append("\n"); + sb.Append(" PspPaymentReference: ").Append(PspPaymentReference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PlatformPaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override PlatformPayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option modificationMerchantReference = default; + Option modificationPspReference = default; + Option paymentMerchantReference = default; + Option platformPaymentType = default; + Option pspPaymentReference = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "modificationMerchantReference": + modificationMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "modificationPspReference": + modificationPspReference = new Option(utf8JsonReader.GetString()!); + break; + case "paymentMerchantReference": + paymentMerchantReference = new Option(utf8JsonReader.GetString()!); + break; + case "platformPaymentType": + string? platformPaymentTypeRawValue = utf8JsonReader.GetString(); + platformPaymentType = new Option(PlatformPayment.PlatformPaymentTypeEnum.FromStringOrDefault(platformPaymentTypeRawValue)); + break; + case "pspPaymentReference": + pspPaymentReference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(PlatformPayment.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + + return new PlatformPayment(modificationMerchantReference, modificationPspReference, paymentMerchantReference, platformPaymentType, pspPaymentReference, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, platformPayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PlatformPayment platformPayment, JsonSerializerOptions jsonSerializerOptions) + { + + if (platformPayment._ModificationMerchantReferenceOption.IsSet) + if (platformPayment.ModificationMerchantReference != null) + writer.WriteString("modificationMerchantReference", platformPayment.ModificationMerchantReference); + + if (platformPayment._ModificationPspReferenceOption.IsSet) + if (platformPayment.ModificationPspReference != null) + writer.WriteString("modificationPspReference", platformPayment.ModificationPspReference); + + if (platformPayment._PaymentMerchantReferenceOption.IsSet) + if (platformPayment.PaymentMerchantReference != null) + writer.WriteString("paymentMerchantReference", platformPayment.PaymentMerchantReference); + + if (platformPayment._PlatformPaymentTypeOption.IsSet && platformPayment.PlatformPaymentType != null) + { + string? platformPaymentTypeRawValue = PlatformPayment.PlatformPaymentTypeEnum.ToJsonValue(platformPayment._PlatformPaymentTypeOption.Value!.Value); + writer.WriteString("platformPaymentType", platformPaymentTypeRawValue); + } + + if (platformPayment._PspPaymentReferenceOption.IsSet) + if (platformPayment.PspPaymentReference != null) + writer.WriteString("pspPaymentReference", platformPayment.PspPaymentReference); + + if (platformPayment._TypeOption.IsSet && platformPayment.Type != null) + { + string? typeRawValue = PlatformPayment.TypeEnum.ToJsonValue(platformPayment._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/RelayedAuthorisationData.cs b/Adyen/Transfers/Models/RelayedAuthorisationData.cs new file mode 100644 index 000000000..26619ecfa --- /dev/null +++ b/Adyen/Transfers/Models/RelayedAuthorisationData.cs @@ -0,0 +1,203 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// RelayedAuthorisationData. + /// + public partial class RelayedAuthorisationData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// Your reference for the relayed authorisation data. + [JsonConstructor] + public RelayedAuthorisationData(Option?> metadata = default, Option reference = default) + { + _MetadataOption = metadata; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RelayedAuthorisationData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MetadataOption { get; private set; } + + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + /// + /// Contains key-value pairs of your references and descriptions, for example, `customId`:`your-own-custom-field-12345`. + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this._MetadataOption; } set { this._MetadataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the relayed authorisation data. + /// + /// Your reference for the relayed authorisation data. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RelayedAuthorisationData {\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RelayedAuthorisationDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RelayedAuthorisationData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> metadata = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RelayedAuthorisationData(metadata, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, relayedAuthorisationData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RelayedAuthorisationData relayedAuthorisationData, JsonSerializerOptions jsonSerializerOptions) + { + + if (relayedAuthorisationData._MetadataOption.IsSet) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, relayedAuthorisationData.Metadata, jsonSerializerOptions); + } + if (relayedAuthorisationData._ReferenceOption.IsSet) + if (relayedAuthorisationData.Reference != null) + writer.WriteString("reference", relayedAuthorisationData.Reference); + } + } +} diff --git a/Adyen/Transfers/Models/Repayment.cs b/Adyen/Transfers/Models/Repayment.cs new file mode 100644 index 000000000..21742183d --- /dev/null +++ b/Adyen/Transfers/Models/Repayment.cs @@ -0,0 +1,221 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Repayment. + /// + public partial class Repayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + /// term + /// threshold + [JsonConstructor] + public Repayment(int basisPoints, Option term = default, Option threshold = default) + { + BasisPoints = basisPoints; + _TermOption = term; + _ThresholdOption = threshold; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Repayment() + { + } + + partial void OnCreated(); + + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + /// + /// The repayment that is deducted daily from incoming net volume, in [basis points](https://www.investopedia.com/terms/b/basispoint.asp). + [JsonPropertyName("basisPoints")] + public int BasisPoints { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TermOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("term")] + public RepaymentTerm? Term { get { return this._TermOption; } set { this._TermOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ThresholdOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("threshold")] + public ThresholdRepayment? Threshold { get { return this._ThresholdOption; } set { this._ThresholdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Repayment {\n"); + sb.Append(" BasisPoints: ").Append(BasisPoints).Append("\n"); + sb.Append(" Term: ").Append(Term).Append("\n"); + sb.Append(" Threshold: ").Append(Threshold).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RepaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Repayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option basisPoints = default; + Option term = default; + Option threshold = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "basisPoints": + basisPoints = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "term": + term = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "threshold": + threshold = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!basisPoints.IsSet) + throw new ArgumentException("Property is required for class Repayment.", nameof(basisPoints)); + + return new Repayment(basisPoints.Value!.Value!, term, threshold); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Repayment repayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, repayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Repayment repayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("basisPoints", repayment.BasisPoints); + + if (repayment._TermOption.IsSet) + { + writer.WritePropertyName("term"); + JsonSerializer.Serialize(writer, repayment.Term, jsonSerializerOptions); + } + if (repayment._ThresholdOption.IsSet) + { + writer.WritePropertyName("threshold"); + JsonSerializer.Serialize(writer, repayment.Threshold, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/RepaymentTerm.cs b/Adyen/Transfers/Models/RepaymentTerm.cs new file mode 100644 index 000000000..35d19675e --- /dev/null +++ b/Adyen/Transfers/Models/RepaymentTerm.cs @@ -0,0 +1,194 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// RepaymentTerm. + /// + public partial class RepaymentTerm : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The estimated term for repaying the grant, in days. + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + [JsonConstructor] + public RepaymentTerm(int estimatedDays, Option maximumDays = default) + { + EstimatedDays = estimatedDays; + _MaximumDaysOption = maximumDays; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RepaymentTerm() + { + } + + partial void OnCreated(); + + /// + /// The estimated term for repaying the grant, in days. + /// + /// The estimated term for repaying the grant, in days. + [JsonPropertyName("estimatedDays")] + public int EstimatedDays { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MaximumDaysOption { get; private set; } + + /// + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + /// + /// The maximum term for repaying the grant, in days. Only applies when `contractType` is **loan**. + [JsonPropertyName("maximumDays")] + public int? MaximumDays { get { return this._MaximumDaysOption; } set { this._MaximumDaysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RepaymentTerm {\n"); + sb.Append(" EstimatedDays: ").Append(EstimatedDays).Append("\n"); + sb.Append(" MaximumDays: ").Append(MaximumDays).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RepaymentTermJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RepaymentTerm Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option estimatedDays = default; + Option maximumDays = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "estimatedDays": + estimatedDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "maximumDays": + maximumDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!estimatedDays.IsSet) + throw new ArgumentException("Property is required for class RepaymentTerm.", nameof(estimatedDays)); + + return new RepaymentTerm(estimatedDays.Value!.Value!, maximumDays); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RepaymentTerm repaymentTerm, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, repaymentTerm, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RepaymentTerm repaymentTerm, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteNumber("estimatedDays", repaymentTerm.EstimatedDays); + + if (repaymentTerm._MaximumDaysOption.IsSet) + writer.WriteNumber("maximumDays", repaymentTerm._MaximumDaysOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/ResourceReference.cs b/Adyen/Transfers/Models/ResourceReference.cs new file mode 100644 index 000000000..b360f0467 --- /dev/null +++ b/Adyen/Transfers/Models/ResourceReference.cs @@ -0,0 +1,227 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ResourceReference. + /// + public partial class ResourceReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The reference for the resource. + [JsonConstructor] + public ResourceReference(Option description = default, Option id = default, Option reference = default) + { + _DescriptionOption = description; + _IdOption = id; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ResourceReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ResourceReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ResourceReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ResourceReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ResourceReference(description, id, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, resourceReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ResourceReference resourceReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (resourceReference._DescriptionOption.IsSet) + if (resourceReference.Description != null) + writer.WriteString("description", resourceReference.Description); + + if (resourceReference._IdOption.IsSet) + if (resourceReference.Id != null) + writer.WriteString("id", resourceReference.Id); + + if (resourceReference._ReferenceOption.IsSet) + if (resourceReference.Reference != null) + writer.WriteString("reference", resourceReference.Reference); + } + } +} diff --git a/Adyen/Transfers/Models/RestServiceError.cs b/Adyen/Transfers/Models/RestServiceError.cs new file mode 100644 index 000000000..e9bfe0194 --- /dev/null +++ b/Adyen/Transfers/Models/RestServiceError.cs @@ -0,0 +1,352 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// RestServiceError. + /// + public partial class RestServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// A code that identifies the problem type. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// A unique URI that identifies the specific occurrence of the problem. + /// Detailed explanation of each validation error, when applicable. + /// A unique reference for the request, essentially the same as `pspReference`. + /// response + [JsonConstructor] + public RestServiceError(string detail, string errorCode, int status, string title, string type, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option response = default) + { + Detail = detail; + ErrorCode = errorCode; + Status = status; + Title = title; + Type = type; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _ResponseOption = response; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RestServiceError() + { + } + + partial void OnCreated(); + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string Detail { get; set; } + + /// + /// A code that identifies the problem type. + /// + /// A code that identifies the problem type. + [JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A unique URI that identifies the specific occurrence of the problem. + /// + /// A unique URI that identifies the specific occurrence of the problem. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Detailed explanation of each validation error, when applicable. + /// + /// Detailed explanation of each validation error, when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// A unique reference for the request, essentially the same as `pspReference`. + /// + /// A unique reference for the request, essentially the same as `pspReference`. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("response")] + public Object? Response { get { return this._ResponseOption; } set { this._ResponseOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RestServiceError {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RestServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RestServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option status = default; + Option title = default; + Option type = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option response = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "response": + response = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!detail.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(detail)); + + if (!errorCode.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(errorCode)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(status)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(title)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class RestServiceError.", nameof(type)); + + return new RestServiceError(detail.Value!, errorCode.Value!, status.Value!.Value!, title.Value!, type.Value!, instance, invalidFields, requestId, response); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, restServiceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RestServiceError restServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (restServiceError.Detail != null) + writer.WriteString("detail", restServiceError.Detail); + + if (restServiceError.ErrorCode != null) + writer.WriteString("errorCode", restServiceError.ErrorCode); + + writer.WriteNumber("status", restServiceError.Status); + + if (restServiceError.Title != null) + writer.WriteString("title", restServiceError.Title); + + if (restServiceError.Type != null) + writer.WriteString("type", restServiceError.Type); + + if (restServiceError._InstanceOption.IsSet) + if (restServiceError.Instance != null) + writer.WriteString("instance", restServiceError.Instance); + + if (restServiceError._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, restServiceError.InvalidFields, jsonSerializerOptions); + } + if (restServiceError._RequestIdOption.IsSet) + if (restServiceError.RequestId != null) + writer.WriteString("requestId", restServiceError.RequestId); + + if (restServiceError._ResponseOption.IsSet) + { + writer.WritePropertyName("response"); + JsonSerializer.Serialize(writer, restServiceError.Response, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/ReturnTransferRequest.cs b/Adyen/Transfers/Models/ReturnTransferRequest.cs new file mode 100644 index 000000000..432f9e598 --- /dev/null +++ b/Adyen/Transfers/Models/ReturnTransferRequest.cs @@ -0,0 +1,200 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ReturnTransferRequest. + /// + public partial class ReturnTransferRequest : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// Your internal reference for the return. If you don't provide this in the request, Adyen generates a unique reference. This reference is used in all communication with you about the instruction status. We recommend using a unique value per instruction. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). + [JsonConstructor] + public ReturnTransferRequest(Amount amount, Option reference = default) + { + Amount = amount; + _ReferenceOption = reference; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReturnTransferRequest() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your internal reference for the return. If you don't provide this in the request, Adyen generates a unique reference. This reference is used in all communication with you about the instruction status. We recommend using a unique value per instruction. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). + /// + /// Your internal reference for the return. If you don't provide this in the request, Adyen generates a unique reference. This reference is used in all communication with you about the instruction status. We recommend using a unique value per instruction. If you need to provide multiple references for a transaction, separate them with hyphens (\"-\"). + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReturnTransferRequest {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReturnTransferRequestJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReturnTransferRequest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option reference = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class ReturnTransferRequest.", nameof(amount)); + + return new ReturnTransferRequest(amount.Value!, reference); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReturnTransferRequest returnTransferRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, returnTransferRequest, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReturnTransferRequest returnTransferRequest, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, returnTransferRequest.Amount, jsonSerializerOptions); + if (returnTransferRequest._ReferenceOption.IsSet) + if (returnTransferRequest.Reference != null) + writer.WriteString("reference", returnTransferRequest.Reference); + } + } +} diff --git a/Adyen/Transfers/Models/ReturnTransferResponse.cs b/Adyen/Transfers/Models/ReturnTransferResponse.cs new file mode 100644 index 000000000..f3d386780 --- /dev/null +++ b/Adyen/Transfers/Models/ReturnTransferResponse.cs @@ -0,0 +1,358 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ReturnTransferResponse. + /// + public partial class ReturnTransferResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the return. + /// Your internal reference for the return. + /// The resulting status of the return. Possible values: **Authorised**, **Declined**. + /// The unique identifier of the original transfer. + [JsonConstructor] + public ReturnTransferResponse(Option id = default, Option reference = default, Option status = default, Option transferId = default) + { + _IdOption = id; + _ReferenceOption = reference; + _StatusOption = status; + _TransferIdOption = transferId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ReturnTransferResponse() + { + } + + partial void OnCreated(); + + /// + /// The resulting status of the return. Possible values: **Authorised**, **Declined**. + /// + /// The resulting status of the return. Possible values: **Authorised**, **Declined**. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Authorised - Authorised + /// + public static readonly StatusEnum Authorised = new("Authorised"); + + /// + /// StatusEnum.Declined - Declined + /// + public static readonly StatusEnum Declined = new("Declined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "Authorised" => StatusEnum.Authorised, + "Declined" => StatusEnum.Declined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Authorised) + return "Authorised"; + + if (value == StatusEnum.Declined) + return "Declined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The resulting status of the return. Possible values: **Authorised**, **Declined**. + /// + /// The resulting status of the return. Possible values: **Authorised**, **Declined**. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the return. + /// + /// The unique identifier of the return. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your internal reference for the return. + /// + /// Your internal reference for the return. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferIdOption { get; private set; } + + /// + /// The unique identifier of the original transfer. + /// + /// The unique identifier of the original transfer. + [JsonPropertyName("transferId")] + public string? TransferId { get { return this._TransferIdOption; } set { this._TransferIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReturnTransferResponse {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TransferId: ").Append(TransferId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ReturnTransferResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ReturnTransferResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option reference = default; + Option status = default; + Option transferId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(ReturnTransferResponse.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "transferId": + transferId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ReturnTransferResponse(id, reference, status, transferId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ReturnTransferResponse returnTransferResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, returnTransferResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ReturnTransferResponse returnTransferResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (returnTransferResponse._IdOption.IsSet) + if (returnTransferResponse.Id != null) + writer.WriteString("id", returnTransferResponse.Id); + + if (returnTransferResponse._ReferenceOption.IsSet) + if (returnTransferResponse.Reference != null) + writer.WriteString("reference", returnTransferResponse.Reference); + + if (returnTransferResponse._StatusOption.IsSet && returnTransferResponse.Status != null) + { + string? statusRawValue = ReturnTransferResponse.StatusEnum.ToJsonValue(returnTransferResponse._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (returnTransferResponse._TransferIdOption.IsSet) + if (returnTransferResponse.TransferId != null) + writer.WriteString("transferId", returnTransferResponse.TransferId); + } + } +} diff --git a/Adyen/Transfers/Models/RoutingDetails.cs b/Adyen/Transfers/Models/RoutingDetails.cs new file mode 100644 index 000000000..1c771b5ef --- /dev/null +++ b/Adyen/Transfers/Models/RoutingDetails.cs @@ -0,0 +1,394 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// RoutingDetails. + /// + public partial class RoutingDetails : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// A code that identifies the problem type. + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// A short, human-readable summary of the problem type. + [JsonConstructor] + public RoutingDetails(Option detail = default, Option errorCode = default, Option priority = default, Option title = default) + { + _DetailOption = detail; + _ErrorCodeOption = errorCode; + _PriorityOption = priority; + _TitleOption = title; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public RoutingDetails() + { + } + + partial void OnCreated(); + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DetailOption { get; private set; } + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string? Detail { get { return this._DetailOption; } set { this._DetailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// A code that identifies the problem type. + /// + /// A code that identifies the problem type. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TitleOption { get; private set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string? Title { get { return this._TitleOption; } set { this._TitleOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RoutingDetails {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RoutingDetailsJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override RoutingDetails Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option priority = default; + Option title = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(RoutingDetails.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new RoutingDetails(detail, errorCode, priority, title); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RoutingDetails routingDetails, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, routingDetails, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, RoutingDetails routingDetails, JsonSerializerOptions jsonSerializerOptions) + { + + if (routingDetails._DetailOption.IsSet) + if (routingDetails.Detail != null) + writer.WriteString("detail", routingDetails.Detail); + + if (routingDetails._ErrorCodeOption.IsSet) + if (routingDetails.ErrorCode != null) + writer.WriteString("errorCode", routingDetails.ErrorCode); + + if (routingDetails._PriorityOption.IsSet && routingDetails.Priority != null) + { + string? priorityRawValue = RoutingDetails.PriorityEnum.ToJsonValue(routingDetails._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (routingDetails._TitleOption.IsSet) + if (routingDetails.Title != null) + writer.WriteString("title", routingDetails.Title); + } + } +} diff --git a/Adyen/Transfers/Models/SELocalAccountIdentification.cs b/Adyen/Transfers/Models/SELocalAccountIdentification.cs new file mode 100644 index 000000000..2df2181b9 --- /dev/null +++ b/Adyen/Transfers/Models/SELocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// SELocalAccountIdentification. + /// + public partial class SELocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// **seLocal** (default to TypeEnum.SeLocal) + [JsonConstructor] + public SELocalAccountIdentification(string accountNumber, string clearingNumber, TypeEnum type = default) + { + AccountNumber = accountNumber; + ClearingNumber = clearingNumber; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SELocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SeLocal - seLocal + /// + public static readonly TypeEnum SeLocal = new("seLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "seLocal" => TypeEnum.SeLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SeLocal) + return "seLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **seLocal** + /// + /// **seLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + /// + /// The 7- to 10-digit bank account number ([Bankkontonummer](https://sv.wikipedia.org/wiki/Bankkonto)), without the clearing number, separators, or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + /// + /// The 4- to 5-digit clearing number ([Clearingnummer](https://sv.wikipedia.org/wiki/Clearingnummer)), without separators or whitespace. + [JsonPropertyName("clearingNumber")] + public string ClearingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SELocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" ClearingNumber: ").Append(ClearingNumber).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 10) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 10.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 7) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 7.", new [] { "AccountNumber" }); + } + + // ClearingNumber (string) maxLength + if (this.ClearingNumber != null && this.ClearingNumber.Length > 5) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be less than 5.", new [] { "ClearingNumber" }); + } + + // ClearingNumber (string) minLength + if (this.ClearingNumber != null && this.ClearingNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for ClearingNumber, length must be greater than 4.", new [] { "ClearingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SELocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SELocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option clearingNumber = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "clearingNumber": + clearingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SELocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(accountNumber)); + + if (!clearingNumber.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(clearingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class SELocalAccountIdentification.", nameof(type)); + + return new SELocalAccountIdentification(accountNumber.Value!, clearingNumber.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sELocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SELocalAccountIdentification sELocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sELocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sELocalAccountIdentification.AccountNumber); + + if (sELocalAccountIdentification.ClearingNumber != null) + writer.WriteString("clearingNumber", sELocalAccountIdentification.ClearingNumber); + + if (sELocalAccountIdentification.Type != null) + { + string? typeRawValue = SELocalAccountIdentification.TypeEnum.ToJsonValue(sELocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/SGLocalAccountIdentification.cs b/Adyen/Transfers/Models/SGLocalAccountIdentification.cs new file mode 100644 index 000000000..2c20ae8a9 --- /dev/null +++ b/Adyen/Transfers/Models/SGLocalAccountIdentification.cs @@ -0,0 +1,337 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// SGLocalAccountIdentification. + /// + public partial class SGLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// The bank's 8- or 11-character BIC or SWIFT code. + /// **sgLocal** (default to TypeEnum.SgLocal) + [JsonConstructor] + public SGLocalAccountIdentification(string accountNumber, string bic, Option type = default) + { + AccountNumber = accountNumber; + Bic = bic; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public SGLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.SgLocal - sgLocal + /// + public static readonly TypeEnum SgLocal = new("sgLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "sgLocal" => TypeEnum.SgLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.SgLocal) + return "sgLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// **sgLocal** + /// + /// **sgLocal** + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + /// + /// The 4- to 19-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + /// + /// The bank's 8- or 11-character BIC or SWIFT code. + [JsonPropertyName("bic")] + public string Bic { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SGLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" Bic: ").Append(Bic).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 19) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 19.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 4) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 4.", new [] { "AccountNumber" }); + } + + // Bic (string) maxLength + if (this.Bic != null && this.Bic.Length > 11) + { + yield return new ValidationResult("Invalid value for Bic, length must be less than 11.", new [] { "Bic" }); + } + + // Bic (string) minLength + if (this.Bic != null && this.Bic.Length < 8) + { + yield return new ValidationResult("Invalid value for Bic, length must be greater than 8.", new [] { "Bic" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class SGLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override SGLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option bic = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "bic": + bic = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(SGLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(accountNumber)); + + if (!bic.IsSet) + throw new ArgumentException("Property is required for class SGLocalAccountIdentification.", nameof(bic)); + + return new SGLocalAccountIdentification(accountNumber.Value!, bic.Value!, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, sGLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, SGLocalAccountIdentification sGLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (sGLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", sGLocalAccountIdentification.AccountNumber); + + if (sGLocalAccountIdentification.Bic != null) + writer.WriteString("bic", sGLocalAccountIdentification.Bic); + + if (sGLocalAccountIdentification._TypeOption.IsSet && sGLocalAccountIdentification.Type != null) + { + string? typeRawValue = SGLocalAccountIdentification.TypeEnum.ToJsonValue(sGLocalAccountIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/ServiceError.cs b/Adyen/Transfers/Models/ServiceError.cs new file mode 100644 index 000000000..5a7ea628f --- /dev/null +++ b/Adyen/Transfers/Models/ServiceError.cs @@ -0,0 +1,276 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ServiceError. + /// + public partial class ServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The error code mapped to the error message. + /// The category of the error. + /// A short explanation of the issue. + /// The PSP reference of the payment. + /// The HTTP response status. + [JsonConstructor] + public ServiceError(Option errorCode = default, Option errorType = default, Option message = default, Option pspReference = default, Option status = default) + { + _ErrorCodeOption = errorCode; + _ErrorTypeOption = errorType; + _MessageOption = message; + _PspReferenceOption = pspReference; + _StatusOption = status; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ServiceError() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorCodeOption { get; private set; } + + /// + /// The error code mapped to the error message. + /// + /// The error code mapped to the error message. + [JsonPropertyName("errorCode")] + public string? ErrorCode { get { return this._ErrorCodeOption; } set { this._ErrorCodeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ErrorTypeOption { get; private set; } + + /// + /// The category of the error. + /// + /// The category of the error. + [JsonPropertyName("errorType")] + public string? ErrorType { get { return this._ErrorTypeOption; } set { this._ErrorTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MessageOption { get; private set; } + + /// + /// A short explanation of the issue. + /// + /// A short explanation of the issue. + [JsonPropertyName("message")] + public string? Message { get { return this._MessageOption; } set { this._MessageOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PspReferenceOption { get; private set; } + + /// + /// The PSP reference of the payment. + /// + /// The PSP reference of the payment. + [JsonPropertyName("pspReference")] + public string? PspReference { get { return this._PspReferenceOption; } set { this._PspReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The HTTP response status. + /// + /// The HTTP response status. + [JsonPropertyName("status")] + public int? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ServiceError {\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" ErrorType: ").Append(ErrorType).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" PspReference: ").Append(PspReference).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option errorCode = default; + Option errorType = default; + Option message = default; + Option pspReference = default; + Option status = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "errorType": + errorType = new Option(utf8JsonReader.GetString()!); + break; + case "message": + message = new Option(utf8JsonReader.GetString()!); + break; + case "pspReference": + pspReference = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new ServiceError(errorCode, errorType, message, pspReference, status); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, serviceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ServiceError serviceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (serviceError._ErrorCodeOption.IsSet) + if (serviceError.ErrorCode != null) + writer.WriteString("errorCode", serviceError.ErrorCode); + + if (serviceError._ErrorTypeOption.IsSet) + if (serviceError.ErrorType != null) + writer.WriteString("errorType", serviceError.ErrorType); + + if (serviceError._MessageOption.IsSet) + if (serviceError.Message != null) + writer.WriteString("message", serviceError.Message); + + if (serviceError._PspReferenceOption.IsSet) + if (serviceError.PspReference != null) + writer.WriteString("pspReference", serviceError.PspReference); + + if (serviceError._StatusOption.IsSet) + writer.WriteNumber("status", serviceError._StatusOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/ThreeDSecure.cs b/Adyen/Transfers/Models/ThreeDSecure.cs new file mode 100644 index 000000000..45232154c --- /dev/null +++ b/Adyen/Transfers/Models/ThreeDSecure.cs @@ -0,0 +1,177 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ThreeDSecure. + /// + public partial class ThreeDSecure : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The transaction identifier for the Access Control Server + [JsonConstructor] + public ThreeDSecure(Option acsTransactionId = default) + { + _AcsTransactionIdOption = acsTransactionId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThreeDSecure() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcsTransactionIdOption { get; private set; } + + /// + /// The transaction identifier for the Access Control Server + /// + /// The transaction identifier for the Access Control Server + [JsonPropertyName("acsTransactionId")] + public string? AcsTransactionId { get { return this._AcsTransactionIdOption; } set { this._AcsTransactionIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThreeDSecure {\n"); + sb.Append(" AcsTransactionId: ").Append(AcsTransactionId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThreeDSecureJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThreeDSecure Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acsTransactionId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acsTransactionId": + acsTransactionId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new ThreeDSecure(acsTransactionId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, threeDSecure, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThreeDSecure threeDSecure, JsonSerializerOptions jsonSerializerOptions) + { + + if (threeDSecure._AcsTransactionIdOption.IsSet) + if (threeDSecure.AcsTransactionId != null) + writer.WriteString("acsTransactionId", threeDSecure.AcsTransactionId); + } + } +} diff --git a/Adyen/Transfers/Models/ThresholdRepayment.cs b/Adyen/Transfers/Models/ThresholdRepayment.cs new file mode 100644 index 000000000..871de64be --- /dev/null +++ b/Adyen/Transfers/Models/ThresholdRepayment.cs @@ -0,0 +1,170 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// ThresholdRepayment. + /// + public partial class ThresholdRepayment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + [JsonConstructor] + public ThresholdRepayment(Amount amount) + { + Amount = amount; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public ThresholdRepayment() + { + } + + partial void OnCreated(); + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ThresholdRepayment {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ThresholdRepaymentJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override ThresholdRepayment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class ThresholdRepayment.", nameof(amount)); + + return new ThresholdRepayment(amount.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ThresholdRepayment thresholdRepayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, thresholdRepayment, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ThresholdRepayment thresholdRepayment, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, thresholdRepayment.Amount, jsonSerializerOptions); + } + } +} diff --git a/Adyen/Transfers/Models/Transaction.cs b/Adyen/Transfers/Models/Transaction.cs new file mode 100644 index 000000000..7b51cec31 --- /dev/null +++ b/Adyen/Transfers/Models/Transaction.cs @@ -0,0 +1,550 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Transaction. + /// + public partial class Transaction : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// accountHolder + /// amount + /// balanceAccount + /// The unique identifier of the balance platform. + /// The date the transaction was booked into the balance account. + /// The unique identifier of the transaction. + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// The date the transfer amount becomes available in the balance account. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// The `description` from the `/transfers` request. + /// paymentInstrument + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + /// transfer + [JsonConstructor] + public Transaction(ResourceReference accountHolder, Amount amount, ResourceReference balanceAccount, string balancePlatform, DateTimeOffset bookingDate, string id, StatusEnum status, DateTimeOffset valueDate, Option creationDate = default, Option description = default, Option paymentInstrument = default, Option referenceForBeneficiary = default, Option transfer = default) + { + AccountHolder = accountHolder; + Amount = amount; + BalanceAccount = balanceAccount; + BalancePlatform = balancePlatform; + BookingDate = bookingDate; + Id = id; + Status = status; + ValueDate = valueDate; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _PaymentInstrumentOption = paymentInstrument; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _TransferOption = transfer; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Transaction() + { + } + + partial void OnCreated(); + + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.Pending - pending + /// + public static readonly StatusEnum Pending = new("pending"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "booked" => StatusEnum.Booked, + "pending" => StatusEnum.Pending, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.Pending) + return "pending"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + /// + /// The status of the transaction. Possible values: * **pending**: The transaction is still pending. * **booked**: The transaction has been booked to the balance account. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference AccountHolder { get; set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference BalanceAccount { get; set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string BalancePlatform { get; set; } + + /// + /// The date the transaction was booked into the balance account. + /// + /// The date the transaction was booked into the balance account. + [JsonPropertyName("bookingDate")] + public DateTimeOffset BookingDate { get; set; } + + /// + /// The unique identifier of the transaction. + /// + /// The unique identifier of the transaction. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The date the transfer amount becomes available in the balance account. + /// + /// The date the transfer amount becomes available in the balance account. + [JsonPropertyName("valueDate")] + public DateTimeOffset ValueDate { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2025-03-19T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The `description` from the `/transfers` request. + /// + /// The `description` from the `/transfers` request. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + /// + /// The reference sent to or received from the counterparty. * For outgoing funds, this is the [`referenceForBeneficiary`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__resParam_referenceForBeneficiary) from the [`/transfers`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_referenceForBeneficiary) request. * For incoming funds, this is the reference from the sender. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transfer")] + public TransferView? Transfer { get { return this._TransferOption; } set { this._TransferOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Transaction {\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" BookingDate: ").Append(BookingDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" ValueDate: ").Append(ValueDate).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Transfer: ").Append(Transfer).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionJsonConverter : JsonConverter + { + /// + /// The format to use to serialize BookingDate. + /// + public static string BookingDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValueDate. + /// + public static string ValueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Transaction Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountHolder = default; + Option amount = default; + Option balanceAccount = default; + Option balancePlatform = default; + Option bookingDate = default; + Option id = default; + Option status = default; + Option valueDate = default; + Option creationDate = default; + Option description = default; + Option paymentInstrument = default; + Option referenceForBeneficiary = default; + Option transfer = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "bookingDate": + bookingDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Transaction.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "valueDate": + valueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "transfer": + transfer = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!accountHolder.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(accountHolder)); + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(amount)); + + if (!balanceAccount.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(balanceAccount)); + + if (!balancePlatform.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(balancePlatform)); + + if (!bookingDate.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(bookingDate)); + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(id)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(status)); + + if (!valueDate.IsSet) + throw new ArgumentException("Property is required for class Transaction.", nameof(valueDate)); + + return new Transaction(accountHolder.Value!, amount.Value!, balanceAccount.Value!, balancePlatform.Value!, bookingDate.Value!.Value!, id.Value!, status.Value!.Value!, valueDate.Value!.Value!, creationDate, description, paymentInstrument, referenceForBeneficiary, transfer); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Transaction transaction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transaction, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Transaction transaction, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, transaction.AccountHolder, jsonSerializerOptions); + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transaction.Amount, jsonSerializerOptions); + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, transaction.BalanceAccount, jsonSerializerOptions); + if (transaction.BalancePlatform != null) + writer.WriteString("balancePlatform", transaction.BalancePlatform); + + writer.WriteString("bookingDate", transaction.BookingDate.ToString(BookingDateFormat)); + + if (transaction.Id != null) + writer.WriteString("id", transaction.Id); + + if (transaction.Status != null) + { + string? statusRawValue = Transaction.StatusEnum.ToJsonValue(transaction.Status); + writer.WriteString("status", statusRawValue); + } + + writer.WriteString("valueDate", transaction.ValueDate.ToString(ValueDateFormat)); + + if (transaction._CreationDateOption.IsSet) + writer.WriteString("creationDate", transaction._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (transaction._DescriptionOption.IsSet) + if (transaction.Description != null) + writer.WriteString("description", transaction.Description); + + if (transaction._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, transaction.PaymentInstrument, jsonSerializerOptions); + } + if (transaction._ReferenceForBeneficiaryOption.IsSet) + if (transaction.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transaction.ReferenceForBeneficiary); + + if (transaction._TransferOption.IsSet) + { + writer.WritePropertyName("transfer"); + JsonSerializer.Serialize(writer, transaction.Transfer, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransactionEventViolation.cs b/Adyen/Transfers/Models/TransactionEventViolation.cs new file mode 100644 index 000000000..73f612c0c --- /dev/null +++ b/Adyen/Transfers/Models/TransactionEventViolation.cs @@ -0,0 +1,228 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransactionEventViolation. + /// + public partial class TransactionEventViolation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// An explanation about why the transaction rule failed. + /// transactionRule + /// transactionRuleSource + [JsonConstructor] + public TransactionEventViolation(Option reason = default, Option transactionRule = default, Option transactionRuleSource = default) + { + _ReasonOption = reason; + _TransactionRuleOption = transactionRule; + _TransactionRuleSourceOption = transactionRuleSource; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionEventViolation() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// An explanation about why the transaction rule failed. + /// + /// An explanation about why the transaction rule failed. + [JsonPropertyName("reason")] + public string? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRule")] + public TransactionRuleReference? TransactionRule { get { return this._TransactionRuleOption; } set { this._TransactionRuleOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRuleSourceOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRuleSource")] + public TransactionRuleSource? TransactionRuleSource { get { return this._TransactionRuleSourceOption; } set { this._TransactionRuleSourceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionEventViolation {\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" TransactionRule: ").Append(TransactionRule).Append("\n"); + sb.Append(" TransactionRuleSource: ").Append(TransactionRuleSource).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionEventViolationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionEventViolation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reason = default; + Option transactionRule = default; + Option transactionRuleSource = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reason": + reason = new Option(utf8JsonReader.GetString()!); + break; + case "transactionRule": + transactionRule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRuleSource": + transactionRuleSource = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionEventViolation(reason, transactionRule, transactionRuleSource); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionEventViolation transactionEventViolation, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionEventViolation, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionEventViolation transactionEventViolation, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionEventViolation._ReasonOption.IsSet) + if (transactionEventViolation.Reason != null) + writer.WriteString("reason", transactionEventViolation.Reason); + + if (transactionEventViolation._TransactionRuleOption.IsSet) + { + writer.WritePropertyName("transactionRule"); + JsonSerializer.Serialize(writer, transactionEventViolation.TransactionRule, jsonSerializerOptions); + } + if (transactionEventViolation._TransactionRuleSourceOption.IsSet) + { + writer.WritePropertyName("transactionRuleSource"); + JsonSerializer.Serialize(writer, transactionEventViolation.TransactionRuleSource, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransactionRuleReference.cs b/Adyen/Transfers/Models/TransactionRuleReference.cs new file mode 100644 index 000000000..94c2194b6 --- /dev/null +++ b/Adyen/Transfers/Models/TransactionRuleReference.cs @@ -0,0 +1,276 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransactionRuleReference. + /// + public partial class TransactionRuleReference : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The description of the resource. + /// The unique identifier of the resource. + /// The outcome type of the rule. + /// The reference for the resource. + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + [JsonConstructor] + public TransactionRuleReference(Option description = default, Option id = default, Option outcomeType = default, Option reference = default, Option score = default) + { + _DescriptionOption = description; + _IdOption = id; + _OutcomeTypeOption = outcomeType; + _ReferenceOption = reference; + _ScoreOption = score; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleReference() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// The description of the resource. + /// + /// The description of the resource. + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the resource. + /// + /// The unique identifier of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OutcomeTypeOption { get; private set; } + + /// + /// The outcome type of the rule. + /// + /// The outcome type of the rule. + [JsonPropertyName("outcomeType")] + public string? OutcomeType { get { return this._OutcomeTypeOption; } set { this._OutcomeTypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// The reference for the resource. + /// + /// The reference for the resource. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + /// + /// The transaction score determined by the rule. Returned only when `outcomeType` is **scoreBased**. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleReference {\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" OutcomeType: ").Append(OutcomeType).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleReferenceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleReference Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option description = default; + Option id = default; + Option outcomeType = default; + Option reference = default; + Option score = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "outcomeType": + outcomeType = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + + return new TransactionRuleReference(description, id, outcomeType, reference, score); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleReference transactionRuleReference, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleReference, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleReference transactionRuleReference, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleReference._DescriptionOption.IsSet) + if (transactionRuleReference.Description != null) + writer.WriteString("description", transactionRuleReference.Description); + + if (transactionRuleReference._IdOption.IsSet) + if (transactionRuleReference.Id != null) + writer.WriteString("id", transactionRuleReference.Id); + + if (transactionRuleReference._OutcomeTypeOption.IsSet) + if (transactionRuleReference.OutcomeType != null) + writer.WriteString("outcomeType", transactionRuleReference.OutcomeType); + + if (transactionRuleReference._ReferenceOption.IsSet) + if (transactionRuleReference.Reference != null) + writer.WriteString("reference", transactionRuleReference.Reference); + + if (transactionRuleReference._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRuleReference._ScoreOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/TransactionRuleSource.cs b/Adyen/Transfers/Models/TransactionRuleSource.cs new file mode 100644 index 000000000..da31bd32c --- /dev/null +++ b/Adyen/Transfers/Models/TransactionRuleSource.cs @@ -0,0 +1,202 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransactionRuleSource. + /// + public partial class TransactionRuleSource : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// ID of the resource, when applicable. + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonConstructor] + public TransactionRuleSource(Option id = default, Option type = default) + { + _IdOption = id; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRuleSource() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// ID of the resource, when applicable. + /// + /// ID of the resource, when applicable. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + /// + /// Indicates the type of resource for which the transaction rule is defined. Possible values: * **PaymentInstrumentGroup** * **PaymentInstrument** * **BalancePlatform** * **EntityUsageConfiguration** * **PlatformRule**: The transaction rule is a platform-wide rule imposed by Adyen. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRuleSource {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRuleSourceJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRuleSource Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransactionRuleSource(id, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRuleSource transactionRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRuleSource, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRuleSource transactionRuleSource, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRuleSource._IdOption.IsSet) + if (transactionRuleSource.Id != null) + writer.WriteString("id", transactionRuleSource.Id); + + if (transactionRuleSource._TypeOption.IsSet) + if (transactionRuleSource.Type != null) + writer.WriteString("type", transactionRuleSource.Type); + } + } +} diff --git a/Adyen/Transfers/Models/TransactionRulesResult.cs b/Adyen/Transfers/Models/TransactionRulesResult.cs new file mode 100644 index 000000000..6ebc7a2d1 --- /dev/null +++ b/Adyen/Transfers/Models/TransactionRulesResult.cs @@ -0,0 +1,252 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransactionRulesResult. + /// + public partial class TransactionRulesResult : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The advice given by the Risk analysis. + /// Indicates whether the transaction passed the evaluation for all hardblock rules + /// The score of the Risk analysis. + /// Array containing all the transaction rules that the transaction triggered. + [JsonConstructor] + public TransactionRulesResult(Option advice = default, Option allHardBlockRulesPassed = default, Option score = default, Option?> triggeredTransactionRules = default) + { + _AdviceOption = advice; + _AllHardBlockRulesPassedOption = allHardBlockRulesPassed; + _ScoreOption = score; + _TriggeredTransactionRulesOption = triggeredTransactionRules; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionRulesResult() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AdviceOption { get; private set; } + + /// + /// The advice given by the Risk analysis. + /// + /// The advice given by the Risk analysis. + [JsonPropertyName("advice")] + public string? Advice { get { return this._AdviceOption; } set { this._AdviceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AllHardBlockRulesPassedOption { get; private set; } + + /// + /// Indicates whether the transaction passed the evaluation for all hardblock rules + /// + /// Indicates whether the transaction passed the evaluation for all hardblock rules + [JsonPropertyName("allHardBlockRulesPassed")] + public bool? AllHardBlockRulesPassed { get { return this._AllHardBlockRulesPassedOption; } set { this._AllHardBlockRulesPassedOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScoreOption { get; private set; } + + /// + /// The score of the Risk analysis. + /// + /// The score of the Risk analysis. + [JsonPropertyName("score")] + public int? Score { get { return this._ScoreOption; } set { this._ScoreOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _TriggeredTransactionRulesOption { get; private set; } + + /// + /// Array containing all the transaction rules that the transaction triggered. + /// + /// Array containing all the transaction rules that the transaction triggered. + [JsonPropertyName("triggeredTransactionRules")] + public List? TriggeredTransactionRules { get { return this._TriggeredTransactionRulesOption; } set { this._TriggeredTransactionRulesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionRulesResult {\n"); + sb.Append(" Advice: ").Append(Advice).Append("\n"); + sb.Append(" AllHardBlockRulesPassed: ").Append(AllHardBlockRulesPassed).Append("\n"); + sb.Append(" Score: ").Append(Score).Append("\n"); + sb.Append(" TriggeredTransactionRules: ").Append(TriggeredTransactionRules).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionRulesResultJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionRulesResult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option advice = default; + Option allHardBlockRulesPassed = default; + Option score = default; + Option?> triggeredTransactionRules = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "advice": + advice = new Option(utf8JsonReader.GetString()!); + break; + case "allHardBlockRulesPassed": + allHardBlockRulesPassed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "score": + score = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "triggeredTransactionRules": + triggeredTransactionRules = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionRulesResult(advice, allHardBlockRulesPassed, score, triggeredTransactionRules); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionRulesResult transactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionRulesResult, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionRulesResult transactionRulesResult, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionRulesResult._AdviceOption.IsSet) + if (transactionRulesResult.Advice != null) + writer.WriteString("advice", transactionRulesResult.Advice); + + if (transactionRulesResult._AllHardBlockRulesPassedOption.IsSet) + writer.WriteBoolean("allHardBlockRulesPassed", transactionRulesResult._AllHardBlockRulesPassedOption.Value!.Value); + + if (transactionRulesResult._ScoreOption.IsSet) + writer.WriteNumber("score", transactionRulesResult._ScoreOption.Value!.Value); + + if (transactionRulesResult._TriggeredTransactionRulesOption.IsSet) + { + writer.WritePropertyName("triggeredTransactionRules"); + JsonSerializer.Serialize(writer, transactionRulesResult.TriggeredTransactionRules, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransactionSearchResponse.cs b/Adyen/Transfers/Models/TransactionSearchResponse.cs new file mode 100644 index 000000000..439ad5182 --- /dev/null +++ b/Adyen/Transfers/Models/TransactionSearchResponse.cs @@ -0,0 +1,204 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransactionSearchResponse. + /// + public partial class TransactionSearchResponse : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// links + /// Contains the transactions that match the query parameters. + [JsonConstructor] + public TransactionSearchResponse(Option links = default, Option?> data = default) + { + _LinksOption = links; + _DataOption = data; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransactionSearchResponse() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LinksOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("_links")] + public Links? Links { get { return this._LinksOption; } set { this._LinksOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _DataOption { get; private set; } + + /// + /// Contains the transactions that match the query parameters. + /// + /// Contains the transactions that match the query parameters. + [JsonPropertyName("data")] + public List? Data { get { return this._DataOption; } set { this._DataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransactionSearchResponse {\n"); + sb.Append(" Links: ").Append(Links).Append("\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransactionSearchResponseJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransactionSearchResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option links = default; + Option?> data = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "_links": + links = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + + return new TransactionSearchResponse(links, data); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransactionSearchResponse transactionSearchResponse, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transactionSearchResponse, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransactionSearchResponse transactionSearchResponse, JsonSerializerOptions jsonSerializerOptions) + { + + if (transactionSearchResponse._LinksOption.IsSet) + { + writer.WritePropertyName("_links"); + JsonSerializer.Serialize(writer, transactionSearchResponse.Links, jsonSerializerOptions); + } + if (transactionSearchResponse._DataOption.IsSet) + { + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, transactionSearchResponse.Data, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/Transfer.cs b/Adyen/Transfers/Models/Transfer.cs new file mode 100644 index 000000000..0493f9ead --- /dev/null +++ b/Adyen/Transfers/Models/Transfer.cs @@ -0,0 +1,2326 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Transfer. + /// + public partial class Transfer : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// counterparty + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// accountHolder + /// balanceAccount + /// categoryData + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// directDebitInformation + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// executionDate + /// The ID of the resource. + /// paymentInstrument + /// Additional information about the status of the transfer. + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// review + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonConstructor] + public Transfer(Amount amount, CategoryEnum category, CounterpartyV3 counterparty, StatusEnum status, Option accountHolder = default, Option balanceAccount = default, Option categoryData = default, Option createdAt = default, Option creationDate = default, Option description = default, Option directDebitInformation = default, Option direction = default, Option executionDate = default, Option id = default, Option paymentInstrument = default, Option reason = default, Option reference = default, Option referenceForBeneficiary = default, Option review = default, Option type = default) + { + Amount = amount; + Category = category; + Counterparty = counterparty; + Status = status; + _AccountHolderOption = accountHolder; + _BalanceAccountOption = balanceAccount; + _CategoryDataOption = categoryData; + _CreatedAtOption = createdAt; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _DirectDebitInformationOption = directDebitInformation; + _DirectionOption = direction; + _ExecutionDateOption = executionDate; + _IdOption = id; + _PaymentInstrumentOption = paymentInstrument; + _ReasonOption = reason; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _ReviewOption = review; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public Transfer() + { + } + + partial void OnCreated(); + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Card - card + /// + public static readonly CategoryEnum Card = new("card"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.IssuedCard - issuedCard + /// + public static readonly CategoryEnum IssuedCard = new("issuedCard"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + /// + /// CategoryEnum.TopUp - topUp + /// + public static readonly CategoryEnum TopUp = new("topUp"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "card" => CategoryEnum.Card, + "internal" => CategoryEnum.Internal, + "issuedCard" => CategoryEnum.IssuedCard, + "platformPayment" => CategoryEnum.PlatformPayment, + "topUp" => CategoryEnum.TopUp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Card) + return "card"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.IssuedCard) + return "issuedCard"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + if (value == CategoryEnum.TopUp) + return "topUp"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonPropertyName("category")] + public CategoryEnum Category { get; set; } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonConverter(typeof(DirectionEnumJsonConverter))] + public class DirectionEnum : IEnum + { + /// + /// Returns the value of the DirectionEnum. + /// + public string? Value { get; set; } + + /// + /// DirectionEnum.Incoming - incoming + /// + public static readonly DirectionEnum Incoming = new("incoming"); + + /// + /// DirectionEnum.Outgoing - outgoing + /// + public static readonly DirectionEnum Outgoing = new("outgoing"); + + private DirectionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DirectionEnum?(string? value) => value == null ? null : new DirectionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DirectionEnum? option) => option?.Value; + + public static bool operator ==(DirectionEnum? left, DirectionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DirectionEnum? left, DirectionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DirectionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DirectionEnum? FromStringOrDefault(string value) + { + return value switch { + "incoming" => DirectionEnum.Incoming, + "outgoing" => DirectionEnum.Outgoing, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DirectionEnum? value) + { + if (value == null) + return null; + + if (value == DirectionEnum.Incoming) + return "incoming"; + + if (value == DirectionEnum.Outgoing) + return "outgoing"; + + return null; + } + + /// + /// JsonConverter for writing DirectionEnum. + /// + public class DirectionEnumJsonConverter : JsonConverter + { + public override DirectionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DirectionEnum.FromStringOrDefault(value) ?? new DirectionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DirectionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DirectionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectionOption { get; private set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonPropertyName("direction")] + public DirectionEnum? Direction { get { return this._DirectionOption; } set { this._DirectionOption = new(value); } } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Payment - payment + /// + public static readonly TypeEnum Payment = new("payment"); + + /// + /// TypeEnum.Capture - capture + /// + public static readonly TypeEnum Capture = new("capture"); + + /// + /// TypeEnum.CaptureReversal - captureReversal + /// + public static readonly TypeEnum CaptureReversal = new("captureReversal"); + + /// + /// TypeEnum.Refund - refund + /// + public static readonly TypeEnum Refund = new("refund"); + + /// + /// TypeEnum.RefundReversal - refundReversal + /// + public static readonly TypeEnum RefundReversal = new("refundReversal"); + + /// + /// TypeEnum.Chargeback - chargeback + /// + public static readonly TypeEnum Chargeback = new("chargeback"); + + /// + /// TypeEnum.ChargebackCorrection - chargebackCorrection + /// + public static readonly TypeEnum ChargebackCorrection = new("chargebackCorrection"); + + /// + /// TypeEnum.ChargebackReversal - chargebackReversal + /// + public static readonly TypeEnum ChargebackReversal = new("chargebackReversal"); + + /// + /// TypeEnum.ChargebackReversalCorrection - chargebackReversalCorrection + /// + public static readonly TypeEnum ChargebackReversalCorrection = new("chargebackReversalCorrection"); + + /// + /// TypeEnum.SecondChargeback - secondChargeback + /// + public static readonly TypeEnum SecondChargeback = new("secondChargeback"); + + /// + /// TypeEnum.SecondChargebackCorrection - secondChargebackCorrection + /// + public static readonly TypeEnum SecondChargebackCorrection = new("secondChargebackCorrection"); + + /// + /// TypeEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly TypeEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// TypeEnum.AtmWithdrawalReversal - atmWithdrawalReversal + /// + public static readonly TypeEnum AtmWithdrawalReversal = new("atmWithdrawalReversal"); + + /// + /// TypeEnum.InternalTransfer - internalTransfer + /// + public static readonly TypeEnum InternalTransfer = new("internalTransfer"); + + /// + /// TypeEnum.InternalDirectDebit - internalDirectDebit + /// + public static readonly TypeEnum InternalDirectDebit = new("internalDirectDebit"); + + /// + /// TypeEnum.ManualCorrection - manualCorrection + /// + public static readonly TypeEnum ManualCorrection = new("manualCorrection"); + + /// + /// TypeEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly TypeEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// TypeEnum.DepositCorrection - depositCorrection + /// + public static readonly TypeEnum DepositCorrection = new("depositCorrection"); + + /// + /// TypeEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly TypeEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + /// + /// TypeEnum.BankDirectDebit - bankDirectDebit + /// + public static readonly TypeEnum BankDirectDebit = new("bankDirectDebit"); + + /// + /// TypeEnum.CardTransfer - cardTransfer + /// + public static readonly TypeEnum CardTransfer = new("cardTransfer"); + + /// + /// TypeEnum.MiscCost - miscCost + /// + public static readonly TypeEnum MiscCost = new("miscCost"); + + /// + /// TypeEnum.PaymentCost - paymentCost + /// + public static readonly TypeEnum PaymentCost = new("paymentCost"); + + /// + /// TypeEnum.Fee - fee + /// + public static readonly TypeEnum Fee = new("fee"); + + /// + /// TypeEnum.Leftover - leftover + /// + public static readonly TypeEnum Leftover = new("leftover"); + + /// + /// TypeEnum.Grant - grant + /// + public static readonly TypeEnum Grant = new("grant"); + + /// + /// TypeEnum.CapitalFundsCollection - capitalFundsCollection + /// + public static readonly TypeEnum CapitalFundsCollection = new("capitalFundsCollection"); + + /// + /// TypeEnum.CashOutInstruction - cashOutInstruction + /// + public static readonly TypeEnum CashOutInstruction = new("cashOutInstruction"); + + /// + /// TypeEnum.CashoutFee - cashoutFee + /// + public static readonly TypeEnum CashoutFee = new("cashoutFee"); + + /// + /// TypeEnum.CashoutRepayment - cashoutRepayment + /// + public static readonly TypeEnum CashoutRepayment = new("cashoutRepayment"); + + /// + /// TypeEnum.CashoutFunding - cashoutFunding + /// + public static readonly TypeEnum CashoutFunding = new("cashoutFunding"); + + /// + /// TypeEnum.Repayment - repayment + /// + public static readonly TypeEnum Repayment = new("repayment"); + + /// + /// TypeEnum.Installment - installment + /// + public static readonly TypeEnum Installment = new("installment"); + + /// + /// TypeEnum.InstallmentReversal - installmentReversal + /// + public static readonly TypeEnum InstallmentReversal = new("installmentReversal"); + + /// + /// TypeEnum.BalanceAdjustment - balanceAdjustment + /// + public static readonly TypeEnum BalanceAdjustment = new("balanceAdjustment"); + + /// + /// TypeEnum.BalanceRollover - balanceRollover + /// + public static readonly TypeEnum BalanceRollover = new("balanceRollover"); + + /// + /// TypeEnum.BalanceMigration - balanceMigration + /// + public static readonly TypeEnum BalanceMigration = new("balanceMigration"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "payment" => TypeEnum.Payment, + "capture" => TypeEnum.Capture, + "captureReversal" => TypeEnum.CaptureReversal, + "refund" => TypeEnum.Refund, + "refundReversal" => TypeEnum.RefundReversal, + "chargeback" => TypeEnum.Chargeback, + "chargebackCorrection" => TypeEnum.ChargebackCorrection, + "chargebackReversal" => TypeEnum.ChargebackReversal, + "chargebackReversalCorrection" => TypeEnum.ChargebackReversalCorrection, + "secondChargeback" => TypeEnum.SecondChargeback, + "secondChargebackCorrection" => TypeEnum.SecondChargebackCorrection, + "atmWithdrawal" => TypeEnum.AtmWithdrawal, + "atmWithdrawalReversal" => TypeEnum.AtmWithdrawalReversal, + "internalTransfer" => TypeEnum.InternalTransfer, + "internalDirectDebit" => TypeEnum.InternalDirectDebit, + "manualCorrection" => TypeEnum.ManualCorrection, + "invoiceDeduction" => TypeEnum.InvoiceDeduction, + "depositCorrection" => TypeEnum.DepositCorrection, + "reserveAdjustment" => TypeEnum.ReserveAdjustment, + "bankTransfer" => TypeEnum.BankTransfer, + "bankDirectDebit" => TypeEnum.BankDirectDebit, + "cardTransfer" => TypeEnum.CardTransfer, + "miscCost" => TypeEnum.MiscCost, + "paymentCost" => TypeEnum.PaymentCost, + "fee" => TypeEnum.Fee, + "leftover" => TypeEnum.Leftover, + "grant" => TypeEnum.Grant, + "capitalFundsCollection" => TypeEnum.CapitalFundsCollection, + "cashOutInstruction" => TypeEnum.CashOutInstruction, + "cashoutFee" => TypeEnum.CashoutFee, + "cashoutRepayment" => TypeEnum.CashoutRepayment, + "cashoutFunding" => TypeEnum.CashoutFunding, + "repayment" => TypeEnum.Repayment, + "installment" => TypeEnum.Installment, + "installmentReversal" => TypeEnum.InstallmentReversal, + "balanceAdjustment" => TypeEnum.BalanceAdjustment, + "balanceRollover" => TypeEnum.BalanceRollover, + "balanceMigration" => TypeEnum.BalanceMigration, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Payment) + return "payment"; + + if (value == TypeEnum.Capture) + return "capture"; + + if (value == TypeEnum.CaptureReversal) + return "captureReversal"; + + if (value == TypeEnum.Refund) + return "refund"; + + if (value == TypeEnum.RefundReversal) + return "refundReversal"; + + if (value == TypeEnum.Chargeback) + return "chargeback"; + + if (value == TypeEnum.ChargebackCorrection) + return "chargebackCorrection"; + + if (value == TypeEnum.ChargebackReversal) + return "chargebackReversal"; + + if (value == TypeEnum.ChargebackReversalCorrection) + return "chargebackReversalCorrection"; + + if (value == TypeEnum.SecondChargeback) + return "secondChargeback"; + + if (value == TypeEnum.SecondChargebackCorrection) + return "secondChargebackCorrection"; + + if (value == TypeEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == TypeEnum.AtmWithdrawalReversal) + return "atmWithdrawalReversal"; + + if (value == TypeEnum.InternalTransfer) + return "internalTransfer"; + + if (value == TypeEnum.InternalDirectDebit) + return "internalDirectDebit"; + + if (value == TypeEnum.ManualCorrection) + return "manualCorrection"; + + if (value == TypeEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == TypeEnum.DepositCorrection) + return "depositCorrection"; + + if (value == TypeEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == TypeEnum.BankDirectDebit) + return "bankDirectDebit"; + + if (value == TypeEnum.CardTransfer) + return "cardTransfer"; + + if (value == TypeEnum.MiscCost) + return "miscCost"; + + if (value == TypeEnum.PaymentCost) + return "paymentCost"; + + if (value == TypeEnum.Fee) + return "fee"; + + if (value == TypeEnum.Leftover) + return "leftover"; + + if (value == TypeEnum.Grant) + return "grant"; + + if (value == TypeEnum.CapitalFundsCollection) + return "capitalFundsCollection"; + + if (value == TypeEnum.CashOutInstruction) + return "cashOutInstruction"; + + if (value == TypeEnum.CashoutFee) + return "cashoutFee"; + + if (value == TypeEnum.CashoutRepayment) + return "cashoutRepayment"; + + if (value == TypeEnum.CashoutFunding) + return "cashoutFunding"; + + if (value == TypeEnum.Repayment) + return "repayment"; + + if (value == TypeEnum.Installment) + return "installment"; + + if (value == TypeEnum.InstallmentReversal) + return "installmentReversal"; + + if (value == TypeEnum.BalanceAdjustment) + return "balanceAdjustment"; + + if (value == TypeEnum.BalanceRollover) + return "balanceRollover"; + + if (value == TypeEnum.BalanceMigration) + return "balanceMigration"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public CounterpartyV3 Counterparty { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference? BalanceAccount { get { return this._BalanceAccountOption; } set { this._BalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("categoryData")] + public TransferCategoryData? CategoryData { get { return this._CategoryDataOption; } set { this._CategoryDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + [Obsolete("Deprecated since Transfers API v3. Use createdAt or updatedAt")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectDebitInformationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("directDebitInformation")] + public DirectDebitInformation? DirectDebitInformation { get { return this._DirectDebitInformationOption; } set { this._DirectDebitInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecutionDateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("executionDate")] + public ExecutionDate? ExecutionDate { get { return this._ExecutionDateOption; } set { this._ExecutionDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReviewOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("review")] + public TransferReview? Review { get { return this._ReviewOption; } set { this._ReviewOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Transfer {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" CategoryData: ").Append(CategoryData).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DirectDebitInformation: ").Append(DirectDebitInformation).Append("\n"); + sb.Append(" Direction: ").Append(Direction).Append("\n"); + sb.Append(" ExecutionDate: ").Append(ExecutionDate).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Review: ").Append(Review).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override Transfer Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option category = default; + Option counterparty = default; + Option status = default; + Option accountHolder = default; + Option balanceAccount = default; + Option categoryData = default; + Option createdAt = default; + Option creationDate = default; + Option description = default; + Option directDebitInformation = default; + Option direction = default; + Option executionDate = default; + Option id = default; + Option paymentInstrument = default; + Option reason = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option review = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(Transfer.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(Transfer.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "categoryData": + categoryData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "directDebitInformation": + directDebitInformation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "direction": + string? directionRawValue = utf8JsonReader.GetString(); + direction = new Option(Transfer.DirectionEnum.FromStringOrDefault(directionRawValue)); + break; + case "executionDate": + executionDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(Transfer.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "review": + review = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(Transfer.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class Transfer.", nameof(amount)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class Transfer.", nameof(category)); + + if (!counterparty.IsSet) + throw new ArgumentException("Property is required for class Transfer.", nameof(counterparty)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class Transfer.", nameof(status)); + + return new Transfer(amount.Value!, category.Value!.Value!, counterparty.Value!, status.Value!.Value!, accountHolder, balanceAccount, categoryData, createdAt, creationDate, description, directDebitInformation, direction, executionDate, id, paymentInstrument, reason, reference, referenceForBeneficiary, review, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Transfer transfer, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transfer, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Transfer transfer, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transfer.Amount, jsonSerializerOptions); + if (transfer.Category != null) + { + string? categoryRawValue = Transfer.CategoryEnum.ToJsonValue(transfer.Category); + writer.WriteString("category", categoryRawValue); + } + + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, transfer.Counterparty, jsonSerializerOptions); + if (transfer.Status != null) + { + string? statusRawValue = Transfer.StatusEnum.ToJsonValue(transfer.Status); + writer.WriteString("status", statusRawValue); + } + + if (transfer._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, transfer.AccountHolder, jsonSerializerOptions); + } + if (transfer._BalanceAccountOption.IsSet) + { + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, transfer.BalanceAccount, jsonSerializerOptions); + } + if (transfer._CategoryDataOption.IsSet) + { + writer.WritePropertyName("categoryData"); + JsonSerializer.Serialize(writer, transfer.CategoryData, jsonSerializerOptions); + } + if (transfer._CreatedAtOption.IsSet) + writer.WriteString("createdAt", transfer._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (transfer._CreationDateOption.IsSet) + writer.WriteString("creationDate", transfer._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (transfer._DescriptionOption.IsSet) + if (transfer.Description != null) + writer.WriteString("description", transfer.Description); + + if (transfer._DirectDebitInformationOption.IsSet) + { + writer.WritePropertyName("directDebitInformation"); + JsonSerializer.Serialize(writer, transfer.DirectDebitInformation, jsonSerializerOptions); + } + if (transfer._DirectionOption.IsSet && transfer.Direction != null) + { + string? directionRawValue = Transfer.DirectionEnum.ToJsonValue(transfer._DirectionOption.Value!.Value); + writer.WriteString("direction", directionRawValue); + } + + if (transfer._ExecutionDateOption.IsSet) + { + writer.WritePropertyName("executionDate"); + JsonSerializer.Serialize(writer, transfer.ExecutionDate, jsonSerializerOptions); + } + if (transfer._IdOption.IsSet) + if (transfer.Id != null) + writer.WriteString("id", transfer.Id); + + if (transfer._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, transfer.PaymentInstrument, jsonSerializerOptions); + } + if (transfer._ReasonOption.IsSet && transfer.Reason != null) + { + string? reasonRawValue = Transfer.ReasonEnum.ToJsonValue(transfer._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (transfer._ReferenceOption.IsSet) + if (transfer.Reference != null) + writer.WriteString("reference", transfer.Reference); + + if (transfer._ReferenceForBeneficiaryOption.IsSet) + if (transfer.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transfer.ReferenceForBeneficiary); + + if (transfer._ReviewOption.IsSet) + { + writer.WritePropertyName("review"); + JsonSerializer.Serialize(writer, transfer.Review, jsonSerializerOptions); + } + if (transfer._TypeOption.IsSet && transfer.Type != null) + { + string? typeRawValue = Transfer.TypeEnum.ToJsonValue(transfer._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransferCategoryData.cs b/Adyen/Transfers/Models/TransferCategoryData.cs new file mode 100644 index 000000000..2281ed15b --- /dev/null +++ b/Adyen/Transfers/Models/TransferCategoryData.cs @@ -0,0 +1,253 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// The relevant data according to the transfer category.. + /// + public partial class TransferCategoryData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferCategoryData(BankCategoryData bankCategoryData) + { + BankCategoryData = bankCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferCategoryData(InternalCategoryData internalCategoryData) + { + InternalCategoryData = internalCategoryData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferCategoryData(IssuedCard issuedCard) + { + IssuedCard = issuedCard; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferCategoryData(PlatformPayment platformPayment) + { + PlatformPayment = platformPayment; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public BankCategoryData? BankCategoryData { get; set; } + + /// + /// .. + /// + public InternalCategoryData? InternalCategoryData { get; set; } + + /// + /// .. + /// + public IssuedCard? IssuedCard { get; set; } + + /// + /// .. + /// + public PlatformPayment? PlatformPayment { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferCategoryData {\n"); + if (this.BankCategoryData != null) + sb.Append(BankCategoryData.ToString().Replace("\n", "\n ")); + if (this.InternalCategoryData != null) + sb.Append(InternalCategoryData.ToString().Replace("\n", "\n ")); + if (this.IssuedCard != null) + sb.Append(IssuedCard.ToString().Replace("\n", "\n ")); + if (this.PlatformPayment != null) + sb.Append(PlatformPayment.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferCategoryDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferCategoryData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + BankCategoryData? bankCategoryData = default; + InternalCategoryData? internalCategoryData = default; + IssuedCard? issuedCard = default; + PlatformPayment? platformPayment = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderBankCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderBankCategoryData, jsonSerializerOptions, out bankCategoryData); + + Utf8JsonReader utf8JsonReaderInternalCategoryData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalCategoryData, jsonSerializerOptions, out internalCategoryData); + + Utf8JsonReader utf8JsonReaderIssuedCard = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIssuedCard, jsonSerializerOptions, out issuedCard); + + Utf8JsonReader utf8JsonReaderPlatformPayment = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderPlatformPayment, jsonSerializerOptions, out platformPayment); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (bankCategoryData?.Type != null) + return new TransferCategoryData(bankCategoryData); + + if (internalCategoryData?.Type != null) + return new TransferCategoryData(internalCategoryData); + + if (issuedCard?.Type != null) + return new TransferCategoryData(issuedCard); + + if (platformPayment?.Type != null) + return new TransferCategoryData(platformPayment); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferCategoryData transferCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + if (transferCategoryData.BankCategoryData != null) + JsonSerializer.Serialize(writer, transferCategoryData.BankCategoryData, jsonSerializerOptions); + if (transferCategoryData.InternalCategoryData != null) + JsonSerializer.Serialize(writer, transferCategoryData.InternalCategoryData, jsonSerializerOptions); + if (transferCategoryData.IssuedCard != null) + JsonSerializer.Serialize(writer, transferCategoryData.IssuedCard, jsonSerializerOptions); + if (transferCategoryData.PlatformPayment != null) + JsonSerializer.Serialize(writer, transferCategoryData.PlatformPayment, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferCategoryData, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferCategoryData transferCategoryData, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Transfers/Models/TransferData.cs b/Adyen/Transfers/Models/TransferData.cs new file mode 100644 index 000000000..cb1e09588 --- /dev/null +++ b/Adyen/Transfers/Models/TransferData.cs @@ -0,0 +1,2563 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferData. + /// + public partial class TransferData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// accountHolder + /// balanceAccount + /// The unique identifier of the balance platform. + /// The list of the latest balance statuses in the transfer. + /// categoryData + /// counterparty + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// directDebitInformation + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + /// The list of events leading up to the current status of the transfer. + /// executionDate + /// externalReason + /// The ID of the resource. + /// paymentInstrument + /// Additional information about the status of the transfer. + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// review + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + /// tracking + /// transactionRulesResult + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonConstructor] + public TransferData(Amount amount, CategoryEnum category, StatusEnum status, Option accountHolder = default, Option balanceAccount = default, Option balancePlatform = default, Option?> balances = default, Option categoryData = default, Option counterparty = default, Option createdAt = default, Option creationDate = default, Option description = default, Option directDebitInformation = default, Option direction = default, Option eventId = default, Option?> events = default, Option executionDate = default, Option externalReason = default, Option id = default, Option paymentInstrument = default, Option reason = default, Option reference = default, Option referenceForBeneficiary = default, Option review = default, Option sequenceNumber = default, Option tracking = default, Option transactionRulesResult = default, Option type = default, Option updatedAt = default) + { + Amount = amount; + Category = category; + Status = status; + _AccountHolderOption = accountHolder; + _BalanceAccountOption = balanceAccount; + _BalancePlatformOption = balancePlatform; + _BalancesOption = balances; + _CategoryDataOption = categoryData; + _CounterpartyOption = counterparty; + _CreatedAtOption = createdAt; + _CreationDateOption = creationDate; + _DescriptionOption = description; + _DirectDebitInformationOption = directDebitInformation; + _DirectionOption = direction; + _EventIdOption = eventId; + _EventsOption = events; + _ExecutionDateOption = executionDate; + _ExternalReasonOption = externalReason; + _IdOption = id; + _PaymentInstrumentOption = paymentInstrument; + _ReasonOption = reason; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _ReviewOption = review; + _SequenceNumberOption = sequenceNumber; + _TrackingOption = tracking; + _TransactionRulesResultOption = transactionRulesResult; + _TypeOption = type; + _UpdatedAtOption = updatedAt; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferData() + { + } + + partial void OnCreated(); + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Card - card + /// + public static readonly CategoryEnum Card = new("card"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.IssuedCard - issuedCard + /// + public static readonly CategoryEnum IssuedCard = new("issuedCard"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + /// + /// CategoryEnum.TopUp - topUp + /// + public static readonly CategoryEnum TopUp = new("topUp"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "card" => CategoryEnum.Card, + "internal" => CategoryEnum.Internal, + "issuedCard" => CategoryEnum.IssuedCard, + "platformPayment" => CategoryEnum.PlatformPayment, + "topUp" => CategoryEnum.TopUp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Card) + return "card"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.IssuedCard) + return "issuedCard"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + if (value == CategoryEnum.TopUp) + return "topUp"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonPropertyName("category")] + public CategoryEnum Category { get; set; } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + /// + /// The result of the transfer. For example: - **received**: an outgoing transfer request is created. - **authorised**: the transfer request is authorized and the funds are reserved. - **booked**: the funds are deducted from your user's balance account. - **failed**: the transfer is rejected by the counterparty's bank. - **returned**: the transfer is returned by the counterparty's bank. + [JsonPropertyName("status")] + public StatusEnum Status { get; set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonConverter(typeof(DirectionEnumJsonConverter))] + public class DirectionEnum : IEnum + { + /// + /// Returns the value of the DirectionEnum. + /// + public string? Value { get; set; } + + /// + /// DirectionEnum.Incoming - incoming + /// + public static readonly DirectionEnum Incoming = new("incoming"); + + /// + /// DirectionEnum.Outgoing - outgoing + /// + public static readonly DirectionEnum Outgoing = new("outgoing"); + + private DirectionEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator DirectionEnum?(string? value) => value == null ? null : new DirectionEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(DirectionEnum? option) => option?.Value; + + public static bool operator ==(DirectionEnum? left, DirectionEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(DirectionEnum? left, DirectionEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is DirectionEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static DirectionEnum? FromStringOrDefault(string value) + { + return value switch { + "incoming" => DirectionEnum.Incoming, + "outgoing" => DirectionEnum.Outgoing, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(DirectionEnum? value) + { + if (value == null) + return null; + + if (value == DirectionEnum.Incoming) + return "incoming"; + + if (value == DirectionEnum.Outgoing) + return "outgoing"; + + return null; + } + + /// + /// JsonConverter for writing DirectionEnum. + /// + public class DirectionEnumJsonConverter : JsonConverter + { + public override DirectionEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : DirectionEnum.FromStringOrDefault(value) ?? new DirectionEnum(value); + } + + public override void Write(Utf8JsonWriter writer, DirectionEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(DirectionEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectionOption { get; private set; } + + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + /// + /// The direction of the transfer. Possible values: **incoming**, **outgoing**. + [JsonPropertyName("direction")] + public DirectionEnum? Direction { get { return this._DirectionOption; } set { this._DirectionOption = new(value); } } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// Additional information about the status of the transfer. + /// + /// Additional information about the status of the transfer. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Payment - payment + /// + public static readonly TypeEnum Payment = new("payment"); + + /// + /// TypeEnum.Capture - capture + /// + public static readonly TypeEnum Capture = new("capture"); + + /// + /// TypeEnum.CaptureReversal - captureReversal + /// + public static readonly TypeEnum CaptureReversal = new("captureReversal"); + + /// + /// TypeEnum.Refund - refund + /// + public static readonly TypeEnum Refund = new("refund"); + + /// + /// TypeEnum.RefundReversal - refundReversal + /// + public static readonly TypeEnum RefundReversal = new("refundReversal"); + + /// + /// TypeEnum.Chargeback - chargeback + /// + public static readonly TypeEnum Chargeback = new("chargeback"); + + /// + /// TypeEnum.ChargebackCorrection - chargebackCorrection + /// + public static readonly TypeEnum ChargebackCorrection = new("chargebackCorrection"); + + /// + /// TypeEnum.ChargebackReversal - chargebackReversal + /// + public static readonly TypeEnum ChargebackReversal = new("chargebackReversal"); + + /// + /// TypeEnum.ChargebackReversalCorrection - chargebackReversalCorrection + /// + public static readonly TypeEnum ChargebackReversalCorrection = new("chargebackReversalCorrection"); + + /// + /// TypeEnum.SecondChargeback - secondChargeback + /// + public static readonly TypeEnum SecondChargeback = new("secondChargeback"); + + /// + /// TypeEnum.SecondChargebackCorrection - secondChargebackCorrection + /// + public static readonly TypeEnum SecondChargebackCorrection = new("secondChargebackCorrection"); + + /// + /// TypeEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly TypeEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// TypeEnum.AtmWithdrawalReversal - atmWithdrawalReversal + /// + public static readonly TypeEnum AtmWithdrawalReversal = new("atmWithdrawalReversal"); + + /// + /// TypeEnum.InternalTransfer - internalTransfer + /// + public static readonly TypeEnum InternalTransfer = new("internalTransfer"); + + /// + /// TypeEnum.InternalDirectDebit - internalDirectDebit + /// + public static readonly TypeEnum InternalDirectDebit = new("internalDirectDebit"); + + /// + /// TypeEnum.ManualCorrection - manualCorrection + /// + public static readonly TypeEnum ManualCorrection = new("manualCorrection"); + + /// + /// TypeEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly TypeEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// TypeEnum.DepositCorrection - depositCorrection + /// + public static readonly TypeEnum DepositCorrection = new("depositCorrection"); + + /// + /// TypeEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly TypeEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + /// + /// TypeEnum.BankDirectDebit - bankDirectDebit + /// + public static readonly TypeEnum BankDirectDebit = new("bankDirectDebit"); + + /// + /// TypeEnum.CardTransfer - cardTransfer + /// + public static readonly TypeEnum CardTransfer = new("cardTransfer"); + + /// + /// TypeEnum.MiscCost - miscCost + /// + public static readonly TypeEnum MiscCost = new("miscCost"); + + /// + /// TypeEnum.PaymentCost - paymentCost + /// + public static readonly TypeEnum PaymentCost = new("paymentCost"); + + /// + /// TypeEnum.Fee - fee + /// + public static readonly TypeEnum Fee = new("fee"); + + /// + /// TypeEnum.Leftover - leftover + /// + public static readonly TypeEnum Leftover = new("leftover"); + + /// + /// TypeEnum.Grant - grant + /// + public static readonly TypeEnum Grant = new("grant"); + + /// + /// TypeEnum.CapitalFundsCollection - capitalFundsCollection + /// + public static readonly TypeEnum CapitalFundsCollection = new("capitalFundsCollection"); + + /// + /// TypeEnum.CashOutInstruction - cashOutInstruction + /// + public static readonly TypeEnum CashOutInstruction = new("cashOutInstruction"); + + /// + /// TypeEnum.CashoutFee - cashoutFee + /// + public static readonly TypeEnum CashoutFee = new("cashoutFee"); + + /// + /// TypeEnum.CashoutRepayment - cashoutRepayment + /// + public static readonly TypeEnum CashoutRepayment = new("cashoutRepayment"); + + /// + /// TypeEnum.CashoutFunding - cashoutFunding + /// + public static readonly TypeEnum CashoutFunding = new("cashoutFunding"); + + /// + /// TypeEnum.Repayment - repayment + /// + public static readonly TypeEnum Repayment = new("repayment"); + + /// + /// TypeEnum.Installment - installment + /// + public static readonly TypeEnum Installment = new("installment"); + + /// + /// TypeEnum.InstallmentReversal - installmentReversal + /// + public static readonly TypeEnum InstallmentReversal = new("installmentReversal"); + + /// + /// TypeEnum.BalanceAdjustment - balanceAdjustment + /// + public static readonly TypeEnum BalanceAdjustment = new("balanceAdjustment"); + + /// + /// TypeEnum.BalanceRollover - balanceRollover + /// + public static readonly TypeEnum BalanceRollover = new("balanceRollover"); + + /// + /// TypeEnum.BalanceMigration - balanceMigration + /// + public static readonly TypeEnum BalanceMigration = new("balanceMigration"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "payment" => TypeEnum.Payment, + "capture" => TypeEnum.Capture, + "captureReversal" => TypeEnum.CaptureReversal, + "refund" => TypeEnum.Refund, + "refundReversal" => TypeEnum.RefundReversal, + "chargeback" => TypeEnum.Chargeback, + "chargebackCorrection" => TypeEnum.ChargebackCorrection, + "chargebackReversal" => TypeEnum.ChargebackReversal, + "chargebackReversalCorrection" => TypeEnum.ChargebackReversalCorrection, + "secondChargeback" => TypeEnum.SecondChargeback, + "secondChargebackCorrection" => TypeEnum.SecondChargebackCorrection, + "atmWithdrawal" => TypeEnum.AtmWithdrawal, + "atmWithdrawalReversal" => TypeEnum.AtmWithdrawalReversal, + "internalTransfer" => TypeEnum.InternalTransfer, + "internalDirectDebit" => TypeEnum.InternalDirectDebit, + "manualCorrection" => TypeEnum.ManualCorrection, + "invoiceDeduction" => TypeEnum.InvoiceDeduction, + "depositCorrection" => TypeEnum.DepositCorrection, + "reserveAdjustment" => TypeEnum.ReserveAdjustment, + "bankTransfer" => TypeEnum.BankTransfer, + "bankDirectDebit" => TypeEnum.BankDirectDebit, + "cardTransfer" => TypeEnum.CardTransfer, + "miscCost" => TypeEnum.MiscCost, + "paymentCost" => TypeEnum.PaymentCost, + "fee" => TypeEnum.Fee, + "leftover" => TypeEnum.Leftover, + "grant" => TypeEnum.Grant, + "capitalFundsCollection" => TypeEnum.CapitalFundsCollection, + "cashOutInstruction" => TypeEnum.CashOutInstruction, + "cashoutFee" => TypeEnum.CashoutFee, + "cashoutRepayment" => TypeEnum.CashoutRepayment, + "cashoutFunding" => TypeEnum.CashoutFunding, + "repayment" => TypeEnum.Repayment, + "installment" => TypeEnum.Installment, + "installmentReversal" => TypeEnum.InstallmentReversal, + "balanceAdjustment" => TypeEnum.BalanceAdjustment, + "balanceRollover" => TypeEnum.BalanceRollover, + "balanceMigration" => TypeEnum.BalanceMigration, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Payment) + return "payment"; + + if (value == TypeEnum.Capture) + return "capture"; + + if (value == TypeEnum.CaptureReversal) + return "captureReversal"; + + if (value == TypeEnum.Refund) + return "refund"; + + if (value == TypeEnum.RefundReversal) + return "refundReversal"; + + if (value == TypeEnum.Chargeback) + return "chargeback"; + + if (value == TypeEnum.ChargebackCorrection) + return "chargebackCorrection"; + + if (value == TypeEnum.ChargebackReversal) + return "chargebackReversal"; + + if (value == TypeEnum.ChargebackReversalCorrection) + return "chargebackReversalCorrection"; + + if (value == TypeEnum.SecondChargeback) + return "secondChargeback"; + + if (value == TypeEnum.SecondChargebackCorrection) + return "secondChargebackCorrection"; + + if (value == TypeEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == TypeEnum.AtmWithdrawalReversal) + return "atmWithdrawalReversal"; + + if (value == TypeEnum.InternalTransfer) + return "internalTransfer"; + + if (value == TypeEnum.InternalDirectDebit) + return "internalDirectDebit"; + + if (value == TypeEnum.ManualCorrection) + return "manualCorrection"; + + if (value == TypeEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == TypeEnum.DepositCorrection) + return "depositCorrection"; + + if (value == TypeEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == TypeEnum.BankDirectDebit) + return "bankDirectDebit"; + + if (value == TypeEnum.CardTransfer) + return "cardTransfer"; + + if (value == TypeEnum.MiscCost) + return "miscCost"; + + if (value == TypeEnum.PaymentCost) + return "paymentCost"; + + if (value == TypeEnum.Fee) + return "fee"; + + if (value == TypeEnum.Leftover) + return "leftover"; + + if (value == TypeEnum.Grant) + return "grant"; + + if (value == TypeEnum.CapitalFundsCollection) + return "capitalFundsCollection"; + + if (value == TypeEnum.CashOutInstruction) + return "cashOutInstruction"; + + if (value == TypeEnum.CashoutFee) + return "cashoutFee"; + + if (value == TypeEnum.CashoutRepayment) + return "cashoutRepayment"; + + if (value == TypeEnum.CashoutFunding) + return "cashoutFunding"; + + if (value == TypeEnum.Repayment) + return "repayment"; + + if (value == TypeEnum.Installment) + return "installment"; + + if (value == TypeEnum.InstallmentReversal) + return "installmentReversal"; + + if (value == TypeEnum.BalanceAdjustment) + return "balanceAdjustment"; + + if (value == TypeEnum.BalanceRollover) + return "balanceRollover"; + + if (value == TypeEnum.BalanceMigration) + return "balanceMigration"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + /// + /// The type of transfer or transaction. For example, **refund**, **payment**, **internalTransfer**, **bankTransfer**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountHolderOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("accountHolder")] + public ResourceReference? AccountHolder { get { return this._AccountHolderOption; } set { this._AccountHolderOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("balanceAccount")] + public ResourceReference? BalanceAccount { get { return this._BalanceAccountOption; } set { this._BalanceAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalancePlatformOption { get; private set; } + + /// + /// The unique identifier of the balance platform. + /// + /// The unique identifier of the balance platform. + [JsonPropertyName("balancePlatform")] + public string? BalancePlatform { get { return this._BalancePlatformOption; } set { this._BalancePlatformOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _BalancesOption { get; private set; } + + /// + /// The list of the latest balance statuses in the transfer. + /// + /// The list of the latest balance statuses in the transfer. + [JsonPropertyName("balances")] + public List? Balances { get { return this._BalancesOption; } set { this._BalancesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("categoryData")] + public TransferCategoryData? CategoryData { get { return this._CategoryDataOption; } set { this._CategoryDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CounterpartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public TransferNotificationCounterParty? Counterparty { get { return this._CounterpartyOption; } set { this._CounterpartyOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreatedAtOption { get; private set; } + + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the transfer was created, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("createdAt")] + public DateTimeOffset? CreatedAt { get { return this._CreatedAtOption; } set { this._CreatedAtOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CreationDateOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("creationDate")] + [Obsolete("Deprecated since Transfers API v3. Use createdAt or updatedAt")] + public DateTimeOffset? CreationDate { get { return this._CreationDateOption; } set { this._CreationDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DirectDebitInformationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("directDebitInformation")] + public DirectDebitInformation? DirectDebitInformation { get { return this._DirectDebitInformationOption; } set { this._DirectDebitInformationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EventIdOption { get; private set; } + + /// + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + /// + /// The unique identifier of the latest transfer event. Included only when the `category` is **issuedCard**. + [JsonPropertyName("eventId")] + public string? EventId { get { return this._EventIdOption; } set { this._EventIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventsOption { get; private set; } + + /// + /// The list of events leading up to the current status of the transfer. + /// + /// The list of events leading up to the current status of the transfer. + [JsonPropertyName("events")] + public List? Events { get { return this._EventsOption; } set { this._EventsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecutionDateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("executionDate")] + public ExecutionDate? ExecutionDate { get { return this._ExecutionDateOption; } set { this._ExecutionDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReasonOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalReason")] + public ExternalReason? ExternalReason { get { return this._ExternalReasonOption; } set { this._ExternalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("paymentInstrument")] + public PaymentInstrument? PaymentInstrument { get { return this._PaymentInstrumentOption; } set { this._PaymentInstrumentOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both the source and recipient of funds. Supported characters: **a-z**, **A-Z**, **0-9**.The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReviewOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("review")] + public TransferReview? Review { get { return this._ReviewOption; } set { this._ReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _SequenceNumberOption { get; private set; } + + /// + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + /// + /// The sequence number of the transfer webhook. The numbers start from 1 and increase with each new webhook for a specific transfer. The sequence number can help you restore the correct sequence of events even if they arrive out of order. + [JsonPropertyName("sequenceNumber")] + public int? SequenceNumber { get { return this._SequenceNumberOption; } set { this._SequenceNumberOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("tracking")] + public TransferDataTracking? Tracking { get { return this._TrackingOption; } set { this._TrackingOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionRulesResultOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("transactionRulesResult")] + public TransactionRulesResult? TransactionRulesResult { get { return this._TransactionRulesResultOption; } set { this._TransactionRulesResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdatedAtOption { get; private set; } + + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + /// + /// The date and time when the event was triggered, in ISO 8601 extended format. For example, **2020-12-18T10:15:30+01:00**. + [JsonPropertyName("updatedAt")] + public DateTimeOffset? UpdatedAt { get { return this._UpdatedAtOption; } set { this._UpdatedAtOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferData {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" AccountHolder: ").Append(AccountHolder).Append("\n"); + sb.Append(" BalanceAccount: ").Append(BalanceAccount).Append("\n"); + sb.Append(" BalancePlatform: ").Append(BalancePlatform).Append("\n"); + sb.Append(" Balances: ").Append(Balances).Append("\n"); + sb.Append(" CategoryData: ").Append(CategoryData).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); + sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DirectDebitInformation: ").Append(DirectDebitInformation).Append("\n"); + sb.Append(" Direction: ").Append(Direction).Append("\n"); + sb.Append(" EventId: ").Append(EventId).Append("\n"); + sb.Append(" Events: ").Append(Events).Append("\n"); + sb.Append(" ExecutionDate: ").Append(ExecutionDate).Append("\n"); + sb.Append(" ExternalReason: ").Append(ExternalReason).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PaymentInstrument: ").Append(PaymentInstrument).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Review: ").Append(Review).Append("\n"); + sb.Append(" SequenceNumber: ").Append(SequenceNumber).Append("\n"); + sb.Append(" Tracking: ").Append(Tracking).Append("\n"); + sb.Append(" TransactionRulesResult: ").Append(TransactionRulesResult).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferDataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize CreatedAt. + /// + public static string CreatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize CreationDate. + /// + public static string CreationDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdatedAt. + /// + public static string UpdatedAtFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option category = default; + Option status = default; + Option accountHolder = default; + Option balanceAccount = default; + Option balancePlatform = default; + Option?> balances = default; + Option categoryData = default; + Option counterparty = default; + Option createdAt = default; + Option creationDate = default; + Option description = default; + Option directDebitInformation = default; + Option direction = default; + Option eventId = default; + Option?> events = default; + Option executionDate = default; + Option externalReason = default; + Option id = default; + Option paymentInstrument = default; + Option reason = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option review = default; + Option sequenceNumber = default; + Option tracking = default; + Option transactionRulesResult = default; + Option type = default; + Option updatedAt = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(TransferData.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransferData.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "accountHolder": + accountHolder = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccount": + balanceAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balancePlatform": + balancePlatform = new Option(utf8JsonReader.GetString()!); + break; + case "balances": + balances = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "categoryData": + categoryData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "createdAt": + createdAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "creationDate": + creationDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "directDebitInformation": + directDebitInformation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "direction": + string? directionRawValue = utf8JsonReader.GetString(); + direction = new Option(TransferData.DirectionEnum.FromStringOrDefault(directionRawValue)); + break; + case "eventId": + eventId = new Option(utf8JsonReader.GetString()!); + break; + case "events": + events = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "executionDate": + executionDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReason": + externalReason = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "paymentInstrument": + paymentInstrument = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(TransferData.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "review": + review = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sequenceNumber": + sequenceNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "tracking": + tracking = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionRulesResult": + transactionRulesResult = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferData.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "updatedAt": + updatedAt = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(amount)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(category)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class TransferData.", nameof(status)); + + return new TransferData(amount.Value!, category.Value!.Value!, status.Value!.Value!, accountHolder, balanceAccount, balancePlatform, balances, categoryData, counterparty, createdAt, creationDate, description, directDebitInformation, direction, eventId, events, executionDate, externalReason, id, paymentInstrument, reason, reference, referenceForBeneficiary, review, sequenceNumber, tracking, transactionRulesResult, type, updatedAt); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferData transferData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferData transferData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferData.Amount, jsonSerializerOptions); + if (transferData.Category != null) + { + string? categoryRawValue = TransferData.CategoryEnum.ToJsonValue(transferData.Category); + writer.WriteString("category", categoryRawValue); + } + + if (transferData.Status != null) + { + string? statusRawValue = TransferData.StatusEnum.ToJsonValue(transferData.Status); + writer.WriteString("status", statusRawValue); + } + + if (transferData._AccountHolderOption.IsSet) + { + writer.WritePropertyName("accountHolder"); + JsonSerializer.Serialize(writer, transferData.AccountHolder, jsonSerializerOptions); + } + if (transferData._BalanceAccountOption.IsSet) + { + writer.WritePropertyName("balanceAccount"); + JsonSerializer.Serialize(writer, transferData.BalanceAccount, jsonSerializerOptions); + } + if (transferData._BalancePlatformOption.IsSet) + if (transferData.BalancePlatform != null) + writer.WriteString("balancePlatform", transferData.BalancePlatform); + + if (transferData._BalancesOption.IsSet) + { + writer.WritePropertyName("balances"); + JsonSerializer.Serialize(writer, transferData.Balances, jsonSerializerOptions); + } + if (transferData._CategoryDataOption.IsSet) + { + writer.WritePropertyName("categoryData"); + JsonSerializer.Serialize(writer, transferData.CategoryData, jsonSerializerOptions); + } + if (transferData._CounterpartyOption.IsSet) + { + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, transferData.Counterparty, jsonSerializerOptions); + } + if (transferData._CreatedAtOption.IsSet) + writer.WriteString("createdAt", transferData._CreatedAtOption.Value!.Value.ToString(CreatedAtFormat)); + + if (transferData._CreationDateOption.IsSet) + writer.WriteString("creationDate", transferData._CreationDateOption.Value!.Value.ToString(CreationDateFormat)); + + if (transferData._DescriptionOption.IsSet) + if (transferData.Description != null) + writer.WriteString("description", transferData.Description); + + if (transferData._DirectDebitInformationOption.IsSet) + { + writer.WritePropertyName("directDebitInformation"); + JsonSerializer.Serialize(writer, transferData.DirectDebitInformation, jsonSerializerOptions); + } + if (transferData._DirectionOption.IsSet && transferData.Direction != null) + { + string? directionRawValue = TransferData.DirectionEnum.ToJsonValue(transferData._DirectionOption.Value!.Value); + writer.WriteString("direction", directionRawValue); + } + + if (transferData._EventIdOption.IsSet) + if (transferData.EventId != null) + writer.WriteString("eventId", transferData.EventId); + + if (transferData._EventsOption.IsSet) + { + writer.WritePropertyName("events"); + JsonSerializer.Serialize(writer, transferData.Events, jsonSerializerOptions); + } + if (transferData._ExecutionDateOption.IsSet) + { + writer.WritePropertyName("executionDate"); + JsonSerializer.Serialize(writer, transferData.ExecutionDate, jsonSerializerOptions); + } + if (transferData._ExternalReasonOption.IsSet) + { + writer.WritePropertyName("externalReason"); + JsonSerializer.Serialize(writer, transferData.ExternalReason, jsonSerializerOptions); + } + if (transferData._IdOption.IsSet) + if (transferData.Id != null) + writer.WriteString("id", transferData.Id); + + if (transferData._PaymentInstrumentOption.IsSet) + { + writer.WritePropertyName("paymentInstrument"); + JsonSerializer.Serialize(writer, transferData.PaymentInstrument, jsonSerializerOptions); + } + if (transferData._ReasonOption.IsSet && transferData.Reason != null) + { + string? reasonRawValue = TransferData.ReasonEnum.ToJsonValue(transferData._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (transferData._ReferenceOption.IsSet) + if (transferData.Reference != null) + writer.WriteString("reference", transferData.Reference); + + if (transferData._ReferenceForBeneficiaryOption.IsSet) + if (transferData.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transferData.ReferenceForBeneficiary); + + if (transferData._ReviewOption.IsSet) + { + writer.WritePropertyName("review"); + JsonSerializer.Serialize(writer, transferData.Review, jsonSerializerOptions); + } + if (transferData._SequenceNumberOption.IsSet) + writer.WriteNumber("sequenceNumber", transferData._SequenceNumberOption.Value!.Value); + + if (transferData._TrackingOption.IsSet) + { + writer.WritePropertyName("tracking"); + JsonSerializer.Serialize(writer, transferData.Tracking, jsonSerializerOptions); + } + if (transferData._TransactionRulesResultOption.IsSet) + { + writer.WritePropertyName("transactionRulesResult"); + JsonSerializer.Serialize(writer, transferData.TransactionRulesResult, jsonSerializerOptions); + } + if (transferData._TypeOption.IsSet && transferData.Type != null) + { + string? typeRawValue = TransferData.TypeEnum.ToJsonValue(transferData._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (transferData._UpdatedAtOption.IsSet) + writer.WriteString("updatedAt", transferData._UpdatedAtOption.Value!.Value.ToString(UpdatedAtFormat)); + } + } +} diff --git a/Adyen/Transfers/Models/TransferDataTracking.cs b/Adyen/Transfers/Models/TransferDataTracking.cs new file mode 100644 index 000000000..6adf614c0 --- /dev/null +++ b/Adyen/Transfers/Models/TransferDataTracking.cs @@ -0,0 +1,227 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// The latest tracking information of the transfer.. + /// + public partial class TransferDataTracking : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(ConfirmationTrackingData confirmationTrackingData) + { + ConfirmationTrackingData = confirmationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(EstimationTrackingData estimationTrackingData) + { + EstimationTrackingData = estimationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferDataTracking(InternalReviewTrackingData internalReviewTrackingData) + { + InternalReviewTrackingData = internalReviewTrackingData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public ConfirmationTrackingData? ConfirmationTrackingData { get; set; } + + /// + /// .. + /// + public EstimationTrackingData? EstimationTrackingData { get; set; } + + /// + /// .. + /// + public InternalReviewTrackingData? InternalReviewTrackingData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferDataTracking {\n"); + if (this.ConfirmationTrackingData != null) + sb.Append(ConfirmationTrackingData.ToString().Replace("\n", "\n ")); + if (this.EstimationTrackingData != null) + sb.Append(EstimationTrackingData.ToString().Replace("\n", "\n ")); + if (this.InternalReviewTrackingData != null) + sb.Append(InternalReviewTrackingData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferDataTrackingJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferDataTracking Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ConfirmationTrackingData? confirmationTrackingData = default; + EstimationTrackingData? estimationTrackingData = default; + InternalReviewTrackingData? internalReviewTrackingData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderConfirmationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderConfirmationTrackingData, jsonSerializerOptions, out confirmationTrackingData); + + Utf8JsonReader utf8JsonReaderEstimationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEstimationTrackingData, jsonSerializerOptions, out estimationTrackingData); + + Utf8JsonReader utf8JsonReaderInternalReviewTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalReviewTrackingData, jsonSerializerOptions, out internalReviewTrackingData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (confirmationTrackingData?.Type != null) + return new TransferDataTracking(confirmationTrackingData); + + if (estimationTrackingData?.Type != null) + return new TransferDataTracking(estimationTrackingData); + + if (internalReviewTrackingData?.Type != null) + return new TransferDataTracking(internalReviewTrackingData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferDataTracking transferDataTracking, JsonSerializerOptions jsonSerializerOptions) + { + if (transferDataTracking.ConfirmationTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.ConfirmationTrackingData, jsonSerializerOptions); + if (transferDataTracking.EstimationTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.EstimationTrackingData, jsonSerializerOptions); + if (transferDataTracking.InternalReviewTrackingData != null) + JsonSerializer.Serialize(writer, transferDataTracking.InternalReviewTrackingData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferDataTracking, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferDataTracking transferDataTracking, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Transfers/Models/TransferEvent.cs b/Adyen/Transfers/Models/TransferEvent.cs new file mode 100644 index 000000000..8babc7aef --- /dev/null +++ b/Adyen/Transfers/Models/TransferEvent.cs @@ -0,0 +1,1731 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferEvent. + /// + public partial class TransferEvent : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + /// The date when the transfer request was sent. + /// The estimated time when the beneficiary should have access to the funds. + /// A list of event data. + /// externalReason + /// The unique identifier of the transfer event. + /// modification + /// The list of balance mutations per event. + /// originalAmount + /// The reason for the transfer status. + /// The status of the transfer event. + /// trackingData + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// The date when the tracking status was updated. + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + [JsonConstructor] + public TransferEvent(Option amount = default, Option?> amountAdjustments = default, Option arn = default, Option bookingDate = default, Option estimatedArrivalTime = default, Option?> eventsData = default, Option externalReason = default, Option id = default, Option modification = default, Option?> mutations = default, Option originalAmount = default, Option reason = default, Option status = default, Option trackingData = default, Option transactionId = default, Option type = default, Option updateDate = default, Option valueDate = default) + { + _AmountOption = amount; + _AmountAdjustmentsOption = amountAdjustments; + _ArnOption = arn; + _BookingDateOption = bookingDate; + _EstimatedArrivalTimeOption = estimatedArrivalTime; + _EventsDataOption = eventsData; + _ExternalReasonOption = externalReason; + _IdOption = id; + _ModificationOption = modification; + _MutationsOption = mutations; + _OriginalAmountOption = originalAmount; + _ReasonOption = reason; + _StatusOption = status; + _TrackingDataOption = trackingData; + _TransactionIdOption = transactionId; + _TypeOption = type; + _UpdateDateOption = updateDate; + _ValueDateOption = valueDate; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferEvent() + { + } + + partial void OnCreated(); + + /// + /// The reason for the transfer status. + /// + /// The reason for the transfer status. + [JsonConverter(typeof(ReasonEnumJsonConverter))] + public class ReasonEnum : IEnum + { + /// + /// Returns the value of the ReasonEnum. + /// + public string? Value { get; set; } + + /// + /// ReasonEnum.AccountHierarchyNotActive - accountHierarchyNotActive + /// + public static readonly ReasonEnum AccountHierarchyNotActive = new("accountHierarchyNotActive"); + + /// + /// ReasonEnum.AmountLimitExceeded - amountLimitExceeded + /// + public static readonly ReasonEnum AmountLimitExceeded = new("amountLimitExceeded"); + + /// + /// ReasonEnum.ApprovalExpired - approvalExpired + /// + public static readonly ReasonEnum ApprovalExpired = new("approvalExpired"); + + /// + /// ReasonEnum.Approved - approved + /// + public static readonly ReasonEnum Approved = new("approved"); + + /// + /// ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule - balanceAccountTemporarilyBlockedByTransactionRule + /// + public static readonly ReasonEnum BalanceAccountTemporarilyBlockedByTransactionRule = new("balanceAccountTemporarilyBlockedByTransactionRule"); + + /// + /// ReasonEnum.CounterpartyAccountBlocked - counterpartyAccountBlocked + /// + public static readonly ReasonEnum CounterpartyAccountBlocked = new("counterpartyAccountBlocked"); + + /// + /// ReasonEnum.CounterpartyAccountClosed - counterpartyAccountClosed + /// + public static readonly ReasonEnum CounterpartyAccountClosed = new("counterpartyAccountClosed"); + + /// + /// ReasonEnum.CounterpartyAccountNotFound - counterpartyAccountNotFound + /// + public static readonly ReasonEnum CounterpartyAccountNotFound = new("counterpartyAccountNotFound"); + + /// + /// ReasonEnum.CounterpartyAddressRequired - counterpartyAddressRequired + /// + public static readonly ReasonEnum CounterpartyAddressRequired = new("counterpartyAddressRequired"); + + /// + /// ReasonEnum.CounterpartyBankTimedOut - counterpartyBankTimedOut + /// + public static readonly ReasonEnum CounterpartyBankTimedOut = new("counterpartyBankTimedOut"); + + /// + /// ReasonEnum.CounterpartyBankUnavailable - counterpartyBankUnavailable + /// + public static readonly ReasonEnum CounterpartyBankUnavailable = new("counterpartyBankUnavailable"); + + /// + /// ReasonEnum.Declined - declined + /// + public static readonly ReasonEnum Declined = new("declined"); + + /// + /// ReasonEnum.DeclinedByTransactionRule - declinedByTransactionRule + /// + public static readonly ReasonEnum DeclinedByTransactionRule = new("declinedByTransactionRule"); + + /// + /// ReasonEnum.DirectDebitNotSupported - directDebitNotSupported + /// + public static readonly ReasonEnum DirectDebitNotSupported = new("directDebitNotSupported"); + + /// + /// ReasonEnum.Error - error + /// + public static readonly ReasonEnum Error = new("error"); + + /// + /// ReasonEnum.NotEnoughBalance - notEnoughBalance + /// + public static readonly ReasonEnum NotEnoughBalance = new("notEnoughBalance"); + + /// + /// ReasonEnum.Pending - pending + /// + public static readonly ReasonEnum Pending = new("pending"); + + /// + /// ReasonEnum.PendingApproval - pendingApproval + /// + public static readonly ReasonEnum PendingApproval = new("pendingApproval"); + + /// + /// ReasonEnum.PendingExecution - pendingExecution + /// + public static readonly ReasonEnum PendingExecution = new("pendingExecution"); + + /// + /// ReasonEnum.RefusedByCounterpartyBank - refusedByCounterpartyBank + /// + public static readonly ReasonEnum RefusedByCounterpartyBank = new("refusedByCounterpartyBank"); + + /// + /// ReasonEnum.RefusedByCustomer - refusedByCustomer + /// + public static readonly ReasonEnum RefusedByCustomer = new("refusedByCustomer"); + + /// + /// ReasonEnum.RouteNotFound - routeNotFound + /// + public static readonly ReasonEnum RouteNotFound = new("routeNotFound"); + + /// + /// ReasonEnum.ScaFailed - scaFailed + /// + public static readonly ReasonEnum ScaFailed = new("scaFailed"); + + /// + /// ReasonEnum.TransferInstrumentDoesNotExist - transferInstrumentDoesNotExist + /// + public static readonly ReasonEnum TransferInstrumentDoesNotExist = new("transferInstrumentDoesNotExist"); + + /// + /// ReasonEnum.Unknown - unknown + /// + public static readonly ReasonEnum Unknown = new("unknown"); + + private ReasonEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ReasonEnum?(string? value) => value == null ? null : new ReasonEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ReasonEnum? option) => option?.Value; + + public static bool operator ==(ReasonEnum? left, ReasonEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ReasonEnum? left, ReasonEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ReasonEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ReasonEnum? FromStringOrDefault(string value) + { + return value switch { + "accountHierarchyNotActive" => ReasonEnum.AccountHierarchyNotActive, + "amountLimitExceeded" => ReasonEnum.AmountLimitExceeded, + "approvalExpired" => ReasonEnum.ApprovalExpired, + "approved" => ReasonEnum.Approved, + "balanceAccountTemporarilyBlockedByTransactionRule" => ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule, + "counterpartyAccountBlocked" => ReasonEnum.CounterpartyAccountBlocked, + "counterpartyAccountClosed" => ReasonEnum.CounterpartyAccountClosed, + "counterpartyAccountNotFound" => ReasonEnum.CounterpartyAccountNotFound, + "counterpartyAddressRequired" => ReasonEnum.CounterpartyAddressRequired, + "counterpartyBankTimedOut" => ReasonEnum.CounterpartyBankTimedOut, + "counterpartyBankUnavailable" => ReasonEnum.CounterpartyBankUnavailable, + "declined" => ReasonEnum.Declined, + "declinedByTransactionRule" => ReasonEnum.DeclinedByTransactionRule, + "directDebitNotSupported" => ReasonEnum.DirectDebitNotSupported, + "error" => ReasonEnum.Error, + "notEnoughBalance" => ReasonEnum.NotEnoughBalance, + "pending" => ReasonEnum.Pending, + "pendingApproval" => ReasonEnum.PendingApproval, + "pendingExecution" => ReasonEnum.PendingExecution, + "refusedByCounterpartyBank" => ReasonEnum.RefusedByCounterpartyBank, + "refusedByCustomer" => ReasonEnum.RefusedByCustomer, + "routeNotFound" => ReasonEnum.RouteNotFound, + "scaFailed" => ReasonEnum.ScaFailed, + "transferInstrumentDoesNotExist" => ReasonEnum.TransferInstrumentDoesNotExist, + "unknown" => ReasonEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ReasonEnum? value) + { + if (value == null) + return null; + + if (value == ReasonEnum.AccountHierarchyNotActive) + return "accountHierarchyNotActive"; + + if (value == ReasonEnum.AmountLimitExceeded) + return "amountLimitExceeded"; + + if (value == ReasonEnum.ApprovalExpired) + return "approvalExpired"; + + if (value == ReasonEnum.Approved) + return "approved"; + + if (value == ReasonEnum.BalanceAccountTemporarilyBlockedByTransactionRule) + return "balanceAccountTemporarilyBlockedByTransactionRule"; + + if (value == ReasonEnum.CounterpartyAccountBlocked) + return "counterpartyAccountBlocked"; + + if (value == ReasonEnum.CounterpartyAccountClosed) + return "counterpartyAccountClosed"; + + if (value == ReasonEnum.CounterpartyAccountNotFound) + return "counterpartyAccountNotFound"; + + if (value == ReasonEnum.CounterpartyAddressRequired) + return "counterpartyAddressRequired"; + + if (value == ReasonEnum.CounterpartyBankTimedOut) + return "counterpartyBankTimedOut"; + + if (value == ReasonEnum.CounterpartyBankUnavailable) + return "counterpartyBankUnavailable"; + + if (value == ReasonEnum.Declined) + return "declined"; + + if (value == ReasonEnum.DeclinedByTransactionRule) + return "declinedByTransactionRule"; + + if (value == ReasonEnum.DirectDebitNotSupported) + return "directDebitNotSupported"; + + if (value == ReasonEnum.Error) + return "error"; + + if (value == ReasonEnum.NotEnoughBalance) + return "notEnoughBalance"; + + if (value == ReasonEnum.Pending) + return "pending"; + + if (value == ReasonEnum.PendingApproval) + return "pendingApproval"; + + if (value == ReasonEnum.PendingExecution) + return "pendingExecution"; + + if (value == ReasonEnum.RefusedByCounterpartyBank) + return "refusedByCounterpartyBank"; + + if (value == ReasonEnum.RefusedByCustomer) + return "refusedByCustomer"; + + if (value == ReasonEnum.RouteNotFound) + return "routeNotFound"; + + if (value == ReasonEnum.ScaFailed) + return "scaFailed"; + + if (value == ReasonEnum.TransferInstrumentDoesNotExist) + return "transferInstrumentDoesNotExist"; + + if (value == ReasonEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing ReasonEnum. + /// + public class ReasonEnumJsonConverter : JsonConverter + { + public override ReasonEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ReasonEnum.FromStringOrDefault(value) ?? new ReasonEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ReasonEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ReasonEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReasonOption { get; private set; } + + /// + /// The reason for the transfer status. + /// + /// The reason for the transfer status. + [JsonPropertyName("reason")] + public ReasonEnum? Reason { get { return this._ReasonOption; } set { this._ReasonOption = new(value); } } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonConverter(typeof(StatusEnumJsonConverter))] + public class StatusEnum : IEnum + { + /// + /// Returns the value of the StatusEnum. + /// + public string? Value { get; set; } + + /// + /// StatusEnum.ApprovalPending - approvalPending + /// + public static readonly StatusEnum ApprovalPending = new("approvalPending"); + + /// + /// StatusEnum.AtmWithdrawal - atmWithdrawal + /// + public static readonly StatusEnum AtmWithdrawal = new("atmWithdrawal"); + + /// + /// StatusEnum.AtmWithdrawalReversalPending - atmWithdrawalReversalPending + /// + public static readonly StatusEnum AtmWithdrawalReversalPending = new("atmWithdrawalReversalPending"); + + /// + /// StatusEnum.AtmWithdrawalReversed - atmWithdrawalReversed + /// + public static readonly StatusEnum AtmWithdrawalReversed = new("atmWithdrawalReversed"); + + /// + /// StatusEnum.AuthAdjustmentAuthorised - authAdjustmentAuthorised + /// + public static readonly StatusEnum AuthAdjustmentAuthorised = new("authAdjustmentAuthorised"); + + /// + /// StatusEnum.AuthAdjustmentError - authAdjustmentError + /// + public static readonly StatusEnum AuthAdjustmentError = new("authAdjustmentError"); + + /// + /// StatusEnum.AuthAdjustmentRefused - authAdjustmentRefused + /// + public static readonly StatusEnum AuthAdjustmentRefused = new("authAdjustmentRefused"); + + /// + /// StatusEnum.Authorised - authorised + /// + public static readonly StatusEnum Authorised = new("authorised"); + + /// + /// StatusEnum.BankTransfer - bankTransfer + /// + public static readonly StatusEnum BankTransfer = new("bankTransfer"); + + /// + /// StatusEnum.BankTransferPending - bankTransferPending + /// + public static readonly StatusEnum BankTransferPending = new("bankTransferPending"); + + /// + /// StatusEnum.Booked - booked + /// + public static readonly StatusEnum Booked = new("booked"); + + /// + /// StatusEnum.BookingPending - bookingPending + /// + public static readonly StatusEnum BookingPending = new("bookingPending"); + + /// + /// StatusEnum.Cancelled - cancelled + /// + public static readonly StatusEnum Cancelled = new("cancelled"); + + /// + /// StatusEnum.CapturePending - capturePending + /// + public static readonly StatusEnum CapturePending = new("capturePending"); + + /// + /// StatusEnum.CaptureReversalPending - captureReversalPending + /// + public static readonly StatusEnum CaptureReversalPending = new("captureReversalPending"); + + /// + /// StatusEnum.CaptureReversed - captureReversed + /// + public static readonly StatusEnum CaptureReversed = new("captureReversed"); + + /// + /// StatusEnum.Captured - captured + /// + public static readonly StatusEnum Captured = new("captured"); + + /// + /// StatusEnum.CapturedExternally - capturedExternally + /// + public static readonly StatusEnum CapturedExternally = new("capturedExternally"); + + /// + /// StatusEnum.Chargeback - chargeback + /// + public static readonly StatusEnum Chargeback = new("chargeback"); + + /// + /// StatusEnum.ChargebackExternally - chargebackExternally + /// + public static readonly StatusEnum ChargebackExternally = new("chargebackExternally"); + + /// + /// StatusEnum.ChargebackPending - chargebackPending + /// + public static readonly StatusEnum ChargebackPending = new("chargebackPending"); + + /// + /// StatusEnum.ChargebackReversalPending - chargebackReversalPending + /// + public static readonly StatusEnum ChargebackReversalPending = new("chargebackReversalPending"); + + /// + /// StatusEnum.ChargebackReversed - chargebackReversed + /// + public static readonly StatusEnum ChargebackReversed = new("chargebackReversed"); + + /// + /// StatusEnum.Credited - credited + /// + public static readonly StatusEnum Credited = new("credited"); + + /// + /// StatusEnum.DepositCorrection - depositCorrection + /// + public static readonly StatusEnum DepositCorrection = new("depositCorrection"); + + /// + /// StatusEnum.DepositCorrectionPending - depositCorrectionPending + /// + public static readonly StatusEnum DepositCorrectionPending = new("depositCorrectionPending"); + + /// + /// StatusEnum.Dispute - dispute + /// + public static readonly StatusEnum Dispute = new("dispute"); + + /// + /// StatusEnum.DisputeClosed - disputeClosed + /// + public static readonly StatusEnum DisputeClosed = new("disputeClosed"); + + /// + /// StatusEnum.DisputeExpired - disputeExpired + /// + public static readonly StatusEnum DisputeExpired = new("disputeExpired"); + + /// + /// StatusEnum.DisputeNeedsReview - disputeNeedsReview + /// + public static readonly StatusEnum DisputeNeedsReview = new("disputeNeedsReview"); + + /// + /// StatusEnum.Error - error + /// + public static readonly StatusEnum Error = new("error"); + + /// + /// StatusEnum.Expired - expired + /// + public static readonly StatusEnum Expired = new("expired"); + + /// + /// StatusEnum.Failed - failed + /// + public static readonly StatusEnum Failed = new("failed"); + + /// + /// StatusEnum.Fee - fee + /// + public static readonly StatusEnum Fee = new("fee"); + + /// + /// StatusEnum.FeePending - feePending + /// + public static readonly StatusEnum FeePending = new("feePending"); + + /// + /// StatusEnum.InternalTransfer - internalTransfer + /// + public static readonly StatusEnum InternalTransfer = new("internalTransfer"); + + /// + /// StatusEnum.InternalTransferPending - internalTransferPending + /// + public static readonly StatusEnum InternalTransferPending = new("internalTransferPending"); + + /// + /// StatusEnum.InvoiceDeduction - invoiceDeduction + /// + public static readonly StatusEnum InvoiceDeduction = new("invoiceDeduction"); + + /// + /// StatusEnum.InvoiceDeductionPending - invoiceDeductionPending + /// + public static readonly StatusEnum InvoiceDeductionPending = new("invoiceDeductionPending"); + + /// + /// StatusEnum.ManualCorrectionPending - manualCorrectionPending + /// + public static readonly StatusEnum ManualCorrectionPending = new("manualCorrectionPending"); + + /// + /// StatusEnum.ManuallyCorrected - manuallyCorrected + /// + public static readonly StatusEnum ManuallyCorrected = new("manuallyCorrected"); + + /// + /// StatusEnum.MatchedStatement - matchedStatement + /// + public static readonly StatusEnum MatchedStatement = new("matchedStatement"); + + /// + /// StatusEnum.MatchedStatementPending - matchedStatementPending + /// + public static readonly StatusEnum MatchedStatementPending = new("matchedStatementPending"); + + /// + /// StatusEnum.MerchantPayin - merchantPayin + /// + public static readonly StatusEnum MerchantPayin = new("merchantPayin"); + + /// + /// StatusEnum.MerchantPayinPending - merchantPayinPending + /// + public static readonly StatusEnum MerchantPayinPending = new("merchantPayinPending"); + + /// + /// StatusEnum.MerchantPayinReversed - merchantPayinReversed + /// + public static readonly StatusEnum MerchantPayinReversed = new("merchantPayinReversed"); + + /// + /// StatusEnum.MerchantPayinReversedPending - merchantPayinReversedPending + /// + public static readonly StatusEnum MerchantPayinReversedPending = new("merchantPayinReversedPending"); + + /// + /// StatusEnum.MiscCost - miscCost + /// + public static readonly StatusEnum MiscCost = new("miscCost"); + + /// + /// StatusEnum.MiscCostPending - miscCostPending + /// + public static readonly StatusEnum MiscCostPending = new("miscCostPending"); + + /// + /// StatusEnum.PaymentCost - paymentCost + /// + public static readonly StatusEnum PaymentCost = new("paymentCost"); + + /// + /// StatusEnum.PaymentCostPending - paymentCostPending + /// + public static readonly StatusEnum PaymentCostPending = new("paymentCostPending"); + + /// + /// StatusEnum.PendingApproval - pendingApproval + /// + public static readonly StatusEnum PendingApproval = new("pendingApproval"); + + /// + /// StatusEnum.PendingExecution - pendingExecution + /// + public static readonly StatusEnum PendingExecution = new("pendingExecution"); + + /// + /// StatusEnum.Received - received + /// + public static readonly StatusEnum Received = new("received"); + + /// + /// StatusEnum.RefundPending - refundPending + /// + public static readonly StatusEnum RefundPending = new("refundPending"); + + /// + /// StatusEnum.RefundReversalPending - refundReversalPending + /// + public static readonly StatusEnum RefundReversalPending = new("refundReversalPending"); + + /// + /// StatusEnum.RefundReversed - refundReversed + /// + public static readonly StatusEnum RefundReversed = new("refundReversed"); + + /// + /// StatusEnum.Refunded - refunded + /// + public static readonly StatusEnum Refunded = new("refunded"); + + /// + /// StatusEnum.RefundedExternally - refundedExternally + /// + public static readonly StatusEnum RefundedExternally = new("refundedExternally"); + + /// + /// StatusEnum.Refused - refused + /// + public static readonly StatusEnum Refused = new("refused"); + + /// + /// StatusEnum.Rejected - rejected + /// + public static readonly StatusEnum Rejected = new("rejected"); + + /// + /// StatusEnum.ReserveAdjustment - reserveAdjustment + /// + public static readonly StatusEnum ReserveAdjustment = new("reserveAdjustment"); + + /// + /// StatusEnum.ReserveAdjustmentPending - reserveAdjustmentPending + /// + public static readonly StatusEnum ReserveAdjustmentPending = new("reserveAdjustmentPending"); + + /// + /// StatusEnum.Returned - returned + /// + public static readonly StatusEnum Returned = new("returned"); + + /// + /// StatusEnum.SecondChargeback - secondChargeback + /// + public static readonly StatusEnum SecondChargeback = new("secondChargeback"); + + /// + /// StatusEnum.SecondChargebackPending - secondChargebackPending + /// + public static readonly StatusEnum SecondChargebackPending = new("secondChargebackPending"); + + /// + /// StatusEnum.Undefined - undefined + /// + public static readonly StatusEnum Undefined = new("undefined"); + + private StatusEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator StatusEnum?(string? value) => value == null ? null : new StatusEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(StatusEnum? option) => option?.Value; + + public static bool operator ==(StatusEnum? left, StatusEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(StatusEnum? left, StatusEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is StatusEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static StatusEnum? FromStringOrDefault(string value) + { + return value switch { + "approvalPending" => StatusEnum.ApprovalPending, + "atmWithdrawal" => StatusEnum.AtmWithdrawal, + "atmWithdrawalReversalPending" => StatusEnum.AtmWithdrawalReversalPending, + "atmWithdrawalReversed" => StatusEnum.AtmWithdrawalReversed, + "authAdjustmentAuthorised" => StatusEnum.AuthAdjustmentAuthorised, + "authAdjustmentError" => StatusEnum.AuthAdjustmentError, + "authAdjustmentRefused" => StatusEnum.AuthAdjustmentRefused, + "authorised" => StatusEnum.Authorised, + "bankTransfer" => StatusEnum.BankTransfer, + "bankTransferPending" => StatusEnum.BankTransferPending, + "booked" => StatusEnum.Booked, + "bookingPending" => StatusEnum.BookingPending, + "cancelled" => StatusEnum.Cancelled, + "capturePending" => StatusEnum.CapturePending, + "captureReversalPending" => StatusEnum.CaptureReversalPending, + "captureReversed" => StatusEnum.CaptureReversed, + "captured" => StatusEnum.Captured, + "capturedExternally" => StatusEnum.CapturedExternally, + "chargeback" => StatusEnum.Chargeback, + "chargebackExternally" => StatusEnum.ChargebackExternally, + "chargebackPending" => StatusEnum.ChargebackPending, + "chargebackReversalPending" => StatusEnum.ChargebackReversalPending, + "chargebackReversed" => StatusEnum.ChargebackReversed, + "credited" => StatusEnum.Credited, + "depositCorrection" => StatusEnum.DepositCorrection, + "depositCorrectionPending" => StatusEnum.DepositCorrectionPending, + "dispute" => StatusEnum.Dispute, + "disputeClosed" => StatusEnum.DisputeClosed, + "disputeExpired" => StatusEnum.DisputeExpired, + "disputeNeedsReview" => StatusEnum.DisputeNeedsReview, + "error" => StatusEnum.Error, + "expired" => StatusEnum.Expired, + "failed" => StatusEnum.Failed, + "fee" => StatusEnum.Fee, + "feePending" => StatusEnum.FeePending, + "internalTransfer" => StatusEnum.InternalTransfer, + "internalTransferPending" => StatusEnum.InternalTransferPending, + "invoiceDeduction" => StatusEnum.InvoiceDeduction, + "invoiceDeductionPending" => StatusEnum.InvoiceDeductionPending, + "manualCorrectionPending" => StatusEnum.ManualCorrectionPending, + "manuallyCorrected" => StatusEnum.ManuallyCorrected, + "matchedStatement" => StatusEnum.MatchedStatement, + "matchedStatementPending" => StatusEnum.MatchedStatementPending, + "merchantPayin" => StatusEnum.MerchantPayin, + "merchantPayinPending" => StatusEnum.MerchantPayinPending, + "merchantPayinReversed" => StatusEnum.MerchantPayinReversed, + "merchantPayinReversedPending" => StatusEnum.MerchantPayinReversedPending, + "miscCost" => StatusEnum.MiscCost, + "miscCostPending" => StatusEnum.MiscCostPending, + "paymentCost" => StatusEnum.PaymentCost, + "paymentCostPending" => StatusEnum.PaymentCostPending, + "pendingApproval" => StatusEnum.PendingApproval, + "pendingExecution" => StatusEnum.PendingExecution, + "received" => StatusEnum.Received, + "refundPending" => StatusEnum.RefundPending, + "refundReversalPending" => StatusEnum.RefundReversalPending, + "refundReversed" => StatusEnum.RefundReversed, + "refunded" => StatusEnum.Refunded, + "refundedExternally" => StatusEnum.RefundedExternally, + "refused" => StatusEnum.Refused, + "rejected" => StatusEnum.Rejected, + "reserveAdjustment" => StatusEnum.ReserveAdjustment, + "reserveAdjustmentPending" => StatusEnum.ReserveAdjustmentPending, + "returned" => StatusEnum.Returned, + "secondChargeback" => StatusEnum.SecondChargeback, + "secondChargebackPending" => StatusEnum.SecondChargebackPending, + "undefined" => StatusEnum.Undefined, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(StatusEnum? value) + { + if (value == null) + return null; + + if (value == StatusEnum.ApprovalPending) + return "approvalPending"; + + if (value == StatusEnum.AtmWithdrawal) + return "atmWithdrawal"; + + if (value == StatusEnum.AtmWithdrawalReversalPending) + return "atmWithdrawalReversalPending"; + + if (value == StatusEnum.AtmWithdrawalReversed) + return "atmWithdrawalReversed"; + + if (value == StatusEnum.AuthAdjustmentAuthorised) + return "authAdjustmentAuthorised"; + + if (value == StatusEnum.AuthAdjustmentError) + return "authAdjustmentError"; + + if (value == StatusEnum.AuthAdjustmentRefused) + return "authAdjustmentRefused"; + + if (value == StatusEnum.Authorised) + return "authorised"; + + if (value == StatusEnum.BankTransfer) + return "bankTransfer"; + + if (value == StatusEnum.BankTransferPending) + return "bankTransferPending"; + + if (value == StatusEnum.Booked) + return "booked"; + + if (value == StatusEnum.BookingPending) + return "bookingPending"; + + if (value == StatusEnum.Cancelled) + return "cancelled"; + + if (value == StatusEnum.CapturePending) + return "capturePending"; + + if (value == StatusEnum.CaptureReversalPending) + return "captureReversalPending"; + + if (value == StatusEnum.CaptureReversed) + return "captureReversed"; + + if (value == StatusEnum.Captured) + return "captured"; + + if (value == StatusEnum.CapturedExternally) + return "capturedExternally"; + + if (value == StatusEnum.Chargeback) + return "chargeback"; + + if (value == StatusEnum.ChargebackExternally) + return "chargebackExternally"; + + if (value == StatusEnum.ChargebackPending) + return "chargebackPending"; + + if (value == StatusEnum.ChargebackReversalPending) + return "chargebackReversalPending"; + + if (value == StatusEnum.ChargebackReversed) + return "chargebackReversed"; + + if (value == StatusEnum.Credited) + return "credited"; + + if (value == StatusEnum.DepositCorrection) + return "depositCorrection"; + + if (value == StatusEnum.DepositCorrectionPending) + return "depositCorrectionPending"; + + if (value == StatusEnum.Dispute) + return "dispute"; + + if (value == StatusEnum.DisputeClosed) + return "disputeClosed"; + + if (value == StatusEnum.DisputeExpired) + return "disputeExpired"; + + if (value == StatusEnum.DisputeNeedsReview) + return "disputeNeedsReview"; + + if (value == StatusEnum.Error) + return "error"; + + if (value == StatusEnum.Expired) + return "expired"; + + if (value == StatusEnum.Failed) + return "failed"; + + if (value == StatusEnum.Fee) + return "fee"; + + if (value == StatusEnum.FeePending) + return "feePending"; + + if (value == StatusEnum.InternalTransfer) + return "internalTransfer"; + + if (value == StatusEnum.InternalTransferPending) + return "internalTransferPending"; + + if (value == StatusEnum.InvoiceDeduction) + return "invoiceDeduction"; + + if (value == StatusEnum.InvoiceDeductionPending) + return "invoiceDeductionPending"; + + if (value == StatusEnum.ManualCorrectionPending) + return "manualCorrectionPending"; + + if (value == StatusEnum.ManuallyCorrected) + return "manuallyCorrected"; + + if (value == StatusEnum.MatchedStatement) + return "matchedStatement"; + + if (value == StatusEnum.MatchedStatementPending) + return "matchedStatementPending"; + + if (value == StatusEnum.MerchantPayin) + return "merchantPayin"; + + if (value == StatusEnum.MerchantPayinPending) + return "merchantPayinPending"; + + if (value == StatusEnum.MerchantPayinReversed) + return "merchantPayinReversed"; + + if (value == StatusEnum.MerchantPayinReversedPending) + return "merchantPayinReversedPending"; + + if (value == StatusEnum.MiscCost) + return "miscCost"; + + if (value == StatusEnum.MiscCostPending) + return "miscCostPending"; + + if (value == StatusEnum.PaymentCost) + return "paymentCost"; + + if (value == StatusEnum.PaymentCostPending) + return "paymentCostPending"; + + if (value == StatusEnum.PendingApproval) + return "pendingApproval"; + + if (value == StatusEnum.PendingExecution) + return "pendingExecution"; + + if (value == StatusEnum.Received) + return "received"; + + if (value == StatusEnum.RefundPending) + return "refundPending"; + + if (value == StatusEnum.RefundReversalPending) + return "refundReversalPending"; + + if (value == StatusEnum.RefundReversed) + return "refundReversed"; + + if (value == StatusEnum.Refunded) + return "refunded"; + + if (value == StatusEnum.RefundedExternally) + return "refundedExternally"; + + if (value == StatusEnum.Refused) + return "refused"; + + if (value == StatusEnum.Rejected) + return "rejected"; + + if (value == StatusEnum.ReserveAdjustment) + return "reserveAdjustment"; + + if (value == StatusEnum.ReserveAdjustmentPending) + return "reserveAdjustmentPending"; + + if (value == StatusEnum.Returned) + return "returned"; + + if (value == StatusEnum.SecondChargeback) + return "secondChargeback"; + + if (value == StatusEnum.SecondChargebackPending) + return "secondChargebackPending"; + + if (value == StatusEnum.Undefined) + return "undefined"; + + return null; + } + + /// + /// JsonConverter for writing StatusEnum. + /// + public class StatusEnumJsonConverter : JsonConverter + { + public override StatusEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : StatusEnum.FromStringOrDefault(value) ?? new StatusEnum(value); + } + + public override void Write(Utf8JsonWriter writer, StatusEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(StatusEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _StatusOption { get; private set; } + + /// + /// The status of the transfer event. + /// + /// The status of the transfer event. + [JsonPropertyName("status")] + public StatusEnum? Status { get { return this._StatusOption; } set { this._StatusOption = new(value); } } + + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Accounting - accounting + /// + public static readonly TypeEnum Accounting = new("accounting"); + + /// + /// TypeEnum.Tracking - tracking + /// + public static readonly TypeEnum Tracking = new("tracking"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "accounting" => TypeEnum.Accounting, + "tracking" => TypeEnum.Tracking, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Accounting) + return "accounting"; + + if (value == TypeEnum.Tracking) + return "tracking"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + /// + /// The type of the transfer event. Possible values: **accounting**, **tracking**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount? Amount { get { return this._AmountOption; } set { this._AmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _AmountAdjustmentsOption { get; private set; } + + /// + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + /// + /// The amount adjustments in this transfer. Only applicable for [issuing](https://docs.adyen.com/issuing/) integrations. + [JsonPropertyName("amountAdjustments")] + public List? AmountAdjustments { get { return this._AmountAdjustmentsOption; } set { this._AmountAdjustmentsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ArnOption { get; private set; } + + /// + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + /// + /// Scheme unique arn identifier useful for tracing captures, chargebacks, refunds, etc. + [JsonPropertyName("arn")] + public string? Arn { get { return this._ArnOption; } set { this._ArnOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BookingDateOption { get; private set; } + + /// + /// The date when the transfer request was sent. + /// + /// The date when the transfer request was sent. + [JsonPropertyName("bookingDate")] + public DateTimeOffset? BookingDate { get { return this._BookingDateOption; } set { this._BookingDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EstimatedArrivalTimeOption { get; private set; } + + /// + /// The estimated time when the beneficiary should have access to the funds. + /// + /// The estimated time when the beneficiary should have access to the funds. + [JsonPropertyName("estimatedArrivalTime")] + public DateTimeOffset? EstimatedArrivalTime { get { return this._EstimatedArrivalTimeOption; } set { this._EstimatedArrivalTimeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _EventsDataOption { get; private set; } + + /// + /// A list of event data. + /// + /// A list of event data. + [JsonPropertyName("eventsData")] + public List? EventsData { get { return this._EventsDataOption; } set { this._EventsDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExternalReasonOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("externalReason")] + public ExternalReason? ExternalReason { get { return this._ExternalReasonOption; } set { this._ExternalReasonOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The unique identifier of the transfer event. + /// + /// The unique identifier of the transfer event. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ModificationOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("modification")] + public Modification? Modification { get { return this._ModificationOption; } set { this._ModificationOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _MutationsOption { get; private set; } + + /// + /// The list of balance mutations per event. + /// + /// The list of balance mutations per event. + [JsonPropertyName("mutations")] + public List? Mutations { get { return this._MutationsOption; } set { this._MutationsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _OriginalAmountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("originalAmount")] + public Amount? OriginalAmount { get { return this._OriginalAmountOption; } set { this._OriginalAmountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TrackingDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("trackingData")] + public TransferEventTrackingData? TrackingData { get { return this._TrackingDataOption; } set { this._TrackingDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransactionIdOption { get; private set; } + + /// + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + /// + /// The id of the transaction that is related to this accounting event. Only sent for events of type **accounting** where the balance changes. + [JsonPropertyName("transactionId")] + public string? TransactionId { get { return this._TransactionIdOption; } set { this._TransactionIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UpdateDateOption { get; private set; } + + /// + /// The date when the tracking status was updated. + /// + /// The date when the tracking status was updated. + [JsonPropertyName("updateDate")] + public DateTimeOffset? UpdateDate { get { return this._UpdateDateOption; } set { this._UpdateDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ValueDateOption { get; private set; } + + /// + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + /// + /// The date when the funds are expected to be deducted from or credited to the balance account. This date can be in either the past or future. + [JsonPropertyName("valueDate")] + public DateTimeOffset? ValueDate { get { return this._ValueDateOption; } set { this._ValueDateOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEvent {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" AmountAdjustments: ").Append(AmountAdjustments).Append("\n"); + sb.Append(" Arn: ").Append(Arn).Append("\n"); + sb.Append(" BookingDate: ").Append(BookingDate).Append("\n"); + sb.Append(" EstimatedArrivalTime: ").Append(EstimatedArrivalTime).Append("\n"); + sb.Append(" EventsData: ").Append(EventsData).Append("\n"); + sb.Append(" ExternalReason: ").Append(ExternalReason).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Modification: ").Append(Modification).Append("\n"); + sb.Append(" Mutations: ").Append(Mutations).Append("\n"); + sb.Append(" OriginalAmount: ").Append(OriginalAmount).Append("\n"); + sb.Append(" Reason: ").Append(Reason).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" TrackingData: ").Append(TrackingData).Append("\n"); + sb.Append(" TransactionId: ").Append(TransactionId).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UpdateDate: ").Append(UpdateDate).Append("\n"); + sb.Append(" ValueDate: ").Append(ValueDate).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventJsonConverter : JsonConverter + { + /// + /// The format to use to serialize BookingDate. + /// + public static string BookingDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize EstimatedArrivalTime. + /// + public static string EstimatedArrivalTimeFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize UpdateDate. + /// + public static string UpdateDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize ValueDate. + /// + public static string ValueDateFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEvent Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option?> amountAdjustments = default; + Option arn = default; + Option bookingDate = default; + Option estimatedArrivalTime = default; + Option?> eventsData = default; + Option externalReason = default; + Option id = default; + Option modification = default; + Option?> mutations = default; + Option originalAmount = default; + Option reason = default; + Option status = default; + Option trackingData = default; + Option transactionId = default; + Option type = default; + Option updateDate = default; + Option valueDate = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "amountAdjustments": + amountAdjustments = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "arn": + arn = new Option(utf8JsonReader.GetString()!); + break; + case "bookingDate": + bookingDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "estimatedArrivalTime": + estimatedArrivalTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "eventsData": + eventsData = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "externalReason": + externalReason = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "modification": + modification = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "mutations": + mutations = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "originalAmount": + originalAmount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "reason": + string? reasonRawValue = utf8JsonReader.GetString(); + reason = new Option(TransferEvent.ReasonEnum.FromStringOrDefault(reasonRawValue)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + status = new Option(TransferEvent.StatusEnum.FromStringOrDefault(statusRawValue)); + break; + case "trackingData": + trackingData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transactionId": + transactionId = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferEvent.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "updateDate": + updateDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "valueDate": + valueDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + + return new TransferEvent(amount, amountAdjustments, arn, bookingDate, estimatedArrivalTime, eventsData, externalReason, id, modification, mutations, originalAmount, reason, status, trackingData, transactionId, type, updateDate, valueDate); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEvent transferEvent, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferEvent, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEvent transferEvent, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferEvent._AmountOption.IsSet) + { + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferEvent.Amount, jsonSerializerOptions); + } + if (transferEvent._AmountAdjustmentsOption.IsSet) + { + writer.WritePropertyName("amountAdjustments"); + JsonSerializer.Serialize(writer, transferEvent.AmountAdjustments, jsonSerializerOptions); + } + if (transferEvent._ArnOption.IsSet) + if (transferEvent.Arn != null) + writer.WriteString("arn", transferEvent.Arn); + + if (transferEvent._BookingDateOption.IsSet) + writer.WriteString("bookingDate", transferEvent._BookingDateOption.Value!.Value.ToString(BookingDateFormat)); + + if (transferEvent._EstimatedArrivalTimeOption.IsSet) + writer.WriteString("estimatedArrivalTime", transferEvent._EstimatedArrivalTimeOption.Value!.Value.ToString(EstimatedArrivalTimeFormat)); + + if (transferEvent._EventsDataOption.IsSet) + { + writer.WritePropertyName("eventsData"); + JsonSerializer.Serialize(writer, transferEvent.EventsData, jsonSerializerOptions); + } + if (transferEvent._ExternalReasonOption.IsSet) + { + writer.WritePropertyName("externalReason"); + JsonSerializer.Serialize(writer, transferEvent.ExternalReason, jsonSerializerOptions); + } + if (transferEvent._IdOption.IsSet) + if (transferEvent.Id != null) + writer.WriteString("id", transferEvent.Id); + + if (transferEvent._ModificationOption.IsSet) + { + writer.WritePropertyName("modification"); + JsonSerializer.Serialize(writer, transferEvent.Modification, jsonSerializerOptions); + } + if (transferEvent._MutationsOption.IsSet) + { + writer.WritePropertyName("mutations"); + JsonSerializer.Serialize(writer, transferEvent.Mutations, jsonSerializerOptions); + } + if (transferEvent._OriginalAmountOption.IsSet) + { + writer.WritePropertyName("originalAmount"); + JsonSerializer.Serialize(writer, transferEvent.OriginalAmount, jsonSerializerOptions); + } + if (transferEvent._ReasonOption.IsSet && transferEvent.Reason != null) + { + string? reasonRawValue = TransferEvent.ReasonEnum.ToJsonValue(transferEvent._ReasonOption.Value!.Value); + writer.WriteString("reason", reasonRawValue); + } + + if (transferEvent._StatusOption.IsSet && transferEvent.Status != null) + { + string? statusRawValue = TransferEvent.StatusEnum.ToJsonValue(transferEvent._StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + } + + if (transferEvent._TrackingDataOption.IsSet) + { + writer.WritePropertyName("trackingData"); + JsonSerializer.Serialize(writer, transferEvent.TrackingData, jsonSerializerOptions); + } + if (transferEvent._TransactionIdOption.IsSet) + if (transferEvent.TransactionId != null) + writer.WriteString("transactionId", transferEvent.TransactionId); + + if (transferEvent._TypeOption.IsSet && transferEvent.Type != null) + { + string? typeRawValue = TransferEvent.TypeEnum.ToJsonValue(transferEvent._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (transferEvent._UpdateDateOption.IsSet) + writer.WriteString("updateDate", transferEvent._UpdateDateOption.Value!.Value.ToString(UpdateDateFormat)); + + if (transferEvent._ValueDateOption.IsSet) + writer.WriteString("valueDate", transferEvent._ValueDateOption.Value!.Value.ToString(ValueDateFormat)); + } + } +} diff --git a/Adyen/Transfers/Models/TransferEventEventsDataInner.cs b/Adyen/Transfers/Models/TransferEventEventsDataInner.cs new file mode 100644 index 000000000..87a95b429 --- /dev/null +++ b/Adyen/Transfers/Models/TransferEventEventsDataInner.cs @@ -0,0 +1,201 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferEventEventsDataInner. + /// + public partial class TransferEventEventsDataInner : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventEventsDataInner(IssuingTransactionData issuingTransactionData) + { + IssuingTransactionData = issuingTransactionData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventEventsDataInner(MerchantPurchaseData merchantPurchaseData) + { + MerchantPurchaseData = merchantPurchaseData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public IssuingTransactionData? IssuingTransactionData { get; set; } + + /// + /// .. + /// + public MerchantPurchaseData? MerchantPurchaseData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEventEventsDataInner {\n"); + if (this.IssuingTransactionData != null) + sb.Append(IssuingTransactionData.ToString().Replace("\n", "\n ")); + if (this.MerchantPurchaseData != null) + sb.Append(MerchantPurchaseData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventEventsDataInnerJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEventEventsDataInner Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + IssuingTransactionData? issuingTransactionData = default; + MerchantPurchaseData? merchantPurchaseData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderIssuingTransactionData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderIssuingTransactionData, jsonSerializerOptions, out issuingTransactionData); + + Utf8JsonReader utf8JsonReaderMerchantPurchaseData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderMerchantPurchaseData, jsonSerializerOptions, out merchantPurchaseData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (issuingTransactionData?.Type != null) + return new TransferEventEventsDataInner(issuingTransactionData); + + if (merchantPurchaseData?.Type != null) + return new TransferEventEventsDataInner(merchantPurchaseData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEventEventsDataInner transferEventEventsDataInner, JsonSerializerOptions jsonSerializerOptions) + { + if (transferEventEventsDataInner.IssuingTransactionData != null) + JsonSerializer.Serialize(writer, transferEventEventsDataInner.IssuingTransactionData, jsonSerializerOptions); + if (transferEventEventsDataInner.MerchantPurchaseData != null) + JsonSerializer.Serialize(writer, transferEventEventsDataInner.MerchantPurchaseData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferEventEventsDataInner, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEventEventsDataInner transferEventEventsDataInner, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Transfers/Models/TransferEventTrackingData.cs b/Adyen/Transfers/Models/TransferEventTrackingData.cs new file mode 100644 index 000000000..64830f67f --- /dev/null +++ b/Adyen/Transfers/Models/TransferEventTrackingData.cs @@ -0,0 +1,227 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// Additional information for the tracking event.. + /// + public partial class TransferEventTrackingData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(ConfirmationTrackingData confirmationTrackingData) + { + ConfirmationTrackingData = confirmationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(EstimationTrackingData estimationTrackingData) + { + EstimationTrackingData = estimationTrackingData; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public TransferEventTrackingData(InternalReviewTrackingData internalReviewTrackingData) + { + InternalReviewTrackingData = internalReviewTrackingData; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// .. + /// + public ConfirmationTrackingData? ConfirmationTrackingData { get; set; } + + /// + /// .. + /// + public EstimationTrackingData? EstimationTrackingData { get; set; } + + /// + /// .. + /// + public InternalReviewTrackingData? InternalReviewTrackingData { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferEventTrackingData {\n"); + if (this.ConfirmationTrackingData != null) + sb.Append(ConfirmationTrackingData.ToString().Replace("\n", "\n ")); + if (this.EstimationTrackingData != null) + sb.Append(EstimationTrackingData.ToString().Replace("\n", "\n ")); + if (this.InternalReviewTrackingData != null) + sb.Append(InternalReviewTrackingData.ToString().Replace("\n", "\n ")); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferEventTrackingDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferEventTrackingData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + ConfirmationTrackingData? confirmationTrackingData = default; + EstimationTrackingData? estimationTrackingData = default; + InternalReviewTrackingData? internalReviewTrackingData = default; + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + Utf8JsonReader utf8JsonReaderConfirmationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderConfirmationTrackingData, jsonSerializerOptions, out confirmationTrackingData); + + Utf8JsonReader utf8JsonReaderEstimationTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderEstimationTrackingData, jsonSerializerOptions, out estimationTrackingData); + + Utf8JsonReader utf8JsonReaderInternalReviewTrackingData = utf8JsonReader; + ClientUtils.TryDeserialize(ref utf8JsonReaderInternalReviewTrackingData, jsonSerializerOptions, out internalReviewTrackingData); + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + default: + break; + } + } + } + + if (confirmationTrackingData?.Type != null) + return new TransferEventTrackingData(confirmationTrackingData); + + if (estimationTrackingData?.Type != null) + return new TransferEventTrackingData(estimationTrackingData); + + if (internalReviewTrackingData?.Type != null) + return new TransferEventTrackingData(internalReviewTrackingData); + + throw new JsonException(); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferEventTrackingData transferEventTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + if (transferEventTrackingData.ConfirmationTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.ConfirmationTrackingData, jsonSerializerOptions); + if (transferEventTrackingData.EstimationTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.EstimationTrackingData, jsonSerializerOptions); + if (transferEventTrackingData.InternalReviewTrackingData != null) + JsonSerializer.Serialize(writer, transferEventTrackingData.InternalReviewTrackingData, jsonSerializerOptions); + /* + writer.WriteStartObject(); + */ + WriteProperties(writer, transferEventTrackingData, jsonSerializerOptions); + /* + writer.WriteEndObject(); + */ + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferEventTrackingData transferEventTrackingData, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/Adyen/Transfers/Models/TransferInfo.cs b/Adyen/Transfers/Models/TransferInfo.cs new file mode 100644 index 000000000..9a9e4743c --- /dev/null +++ b/Adyen/Transfers/Models/TransferInfo.cs @@ -0,0 +1,1034 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferInfo. + /// + public partial class TransferInfo : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// amount + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// counterparty + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount** assigned to the balance account, you must specify the [payment instrument ID](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id) of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// executionDate + /// The unique identifier of the source [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount**, you must specify the payment instrument ID of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities. Adyen will try to pay out using the priority you list first. If that's not possible, it moves on to the next option in the order of your provided priorities. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Required for transfers with `category` **bank**. For more details, see [fallback priorities](https://docs.adyen.com/payouts/payout-service/payout-to-users/#fallback-priorities). + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both parties involved in the funds movement. Supported characters: **a-z**, **A-Z**, **0-9**. The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// review + /// The type of transfer. Possible values: - **bankTransfer**: for push transfers to a transfer instrument or a bank account. The `category` must be **bank**. - **internalTransfer**: for push transfers between balance accounts. The `category` must be **internal**. - **internalDirectDebit**: for pull transfers (direct debits) between balance accounts. The `category` must be **internal**. + /// ultimateParty + [JsonConstructor] + public TransferInfo(Amount amount, CategoryEnum category, CounterpartyInfoV3 counterparty, Option balanceAccountId = default, Option description = default, Option executionDate = default, Option paymentInstrumentId = default, Option?> priorities = default, Option priority = default, Option reference = default, Option referenceForBeneficiary = default, Option review = default, Option type = default, Option ultimateParty = default) + { + Amount = amount; + Category = category; + Counterparty = counterparty; + _BalanceAccountIdOption = balanceAccountId; + _DescriptionOption = description; + _ExecutionDateOption = executionDate; + _PaymentInstrumentIdOption = paymentInstrumentId; + _PrioritiesOption = priorities; + _PriorityOption = priority; + _ReferenceOption = reference; + _ReferenceForBeneficiaryOption = referenceForBeneficiary; + _ReviewOption = review; + _TypeOption = type; + _UltimatePartyOption = ultimateParty; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferInfo() + { + } + + partial void OnCreated(); + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonConverter(typeof(CategoryEnumJsonConverter))] + public class CategoryEnum : IEnum + { + /// + /// Returns the value of the CategoryEnum. + /// + public string? Value { get; set; } + + /// + /// CategoryEnum.Bank - bank + /// + public static readonly CategoryEnum Bank = new("bank"); + + /// + /// CategoryEnum.Card - card + /// + public static readonly CategoryEnum Card = new("card"); + + /// + /// CategoryEnum.Internal - internal + /// + public static readonly CategoryEnum Internal = new("internal"); + + /// + /// CategoryEnum.IssuedCard - issuedCard + /// + public static readonly CategoryEnum IssuedCard = new("issuedCard"); + + /// + /// CategoryEnum.PlatformPayment - platformPayment + /// + public static readonly CategoryEnum PlatformPayment = new("platformPayment"); + + /// + /// CategoryEnum.TopUp - topUp + /// + public static readonly CategoryEnum TopUp = new("topUp"); + + private CategoryEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator CategoryEnum?(string? value) => value == null ? null : new CategoryEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(CategoryEnum? option) => option?.Value; + + public static bool operator ==(CategoryEnum? left, CategoryEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(CategoryEnum? left, CategoryEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is CategoryEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static CategoryEnum? FromStringOrDefault(string value) + { + return value switch { + "bank" => CategoryEnum.Bank, + "card" => CategoryEnum.Card, + "internal" => CategoryEnum.Internal, + "issuedCard" => CategoryEnum.IssuedCard, + "platformPayment" => CategoryEnum.PlatformPayment, + "topUp" => CategoryEnum.TopUp, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(CategoryEnum? value) + { + if (value == null) + return null; + + if (value == CategoryEnum.Bank) + return "bank"; + + if (value == CategoryEnum.Card) + return "card"; + + if (value == CategoryEnum.Internal) + return "internal"; + + if (value == CategoryEnum.IssuedCard) + return "issuedCard"; + + if (value == CategoryEnum.PlatformPayment) + return "platformPayment"; + + if (value == CategoryEnum.TopUp) + return "topUp"; + + return null; + } + + /// + /// JsonConverter for writing CategoryEnum. + /// + public class CategoryEnumJsonConverter : JsonConverter + { + public override CategoryEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : CategoryEnum.FromStringOrDefault(value) ?? new CategoryEnum(value); + } + + public override void Write(Utf8JsonWriter writer, CategoryEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(CategoryEnum.ToJsonValue(value)); + } + } + } + + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + /// + /// The category of the transfer. Possible values: - **bank**: a transfer involving a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **card**: a transfer involving a third-party card. - **internal**: a transfer between [balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: a transfer initiated by an Adyen-issued card. - **platformPayment**: funds movements related to payments that are acquired for your users. - **topUp**: an incoming transfer initiated by your user to top up their balance account. + [JsonPropertyName("category")] + public CategoryEnum Category { get; set; } + + /// + /// Defines Priorities. + /// + [JsonConverter(typeof(PrioritiesEnumJsonConverter))] + public class PrioritiesEnum : IEnum + { + /// + /// Returns the value of the PrioritiesEnum. + /// + public string? Value { get; set; } + + /// + /// PrioritiesEnum.CrossBorder - crossBorder + /// + public static readonly PrioritiesEnum CrossBorder = new("crossBorder"); + + /// + /// PrioritiesEnum.Fast - fast + /// + public static readonly PrioritiesEnum Fast = new("fast"); + + /// + /// PrioritiesEnum.Instant - instant + /// + public static readonly PrioritiesEnum Instant = new("instant"); + + /// + /// PrioritiesEnum.Internal - internal + /// + public static readonly PrioritiesEnum Internal = new("internal"); + + /// + /// PrioritiesEnum.Regular - regular + /// + public static readonly PrioritiesEnum Regular = new("regular"); + + /// + /// PrioritiesEnum.Wire - wire + /// + public static readonly PrioritiesEnum Wire = new("wire"); + + private PrioritiesEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PrioritiesEnum?(string? value) => value == null ? null : new PrioritiesEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PrioritiesEnum? option) => option?.Value; + + public static bool operator ==(PrioritiesEnum? left, PrioritiesEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PrioritiesEnum? left, PrioritiesEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PrioritiesEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PrioritiesEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PrioritiesEnum.CrossBorder, + "fast" => PrioritiesEnum.Fast, + "instant" => PrioritiesEnum.Instant, + "internal" => PrioritiesEnum.Internal, + "regular" => PrioritiesEnum.Regular, + "wire" => PrioritiesEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PrioritiesEnum? value) + { + if (value == null) + return null; + + if (value == PrioritiesEnum.CrossBorder) + return "crossBorder"; + + if (value == PrioritiesEnum.Fast) + return "fast"; + + if (value == PrioritiesEnum.Instant) + return "instant"; + + if (value == PrioritiesEnum.Internal) + return "internal"; + + if (value == PrioritiesEnum.Regular) + return "regular"; + + if (value == PrioritiesEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PrioritiesEnum. + /// + public class PrioritiesEnumJsonConverter : JsonConverter + { + public override PrioritiesEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PrioritiesEnum.FromStringOrDefault(value) ?? new PrioritiesEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PrioritiesEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PrioritiesEnum.ToJsonValue(value)); + } + } + } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonConverter(typeof(PriorityEnumJsonConverter))] + public class PriorityEnum : IEnum + { + /// + /// Returns the value of the PriorityEnum. + /// + public string? Value { get; set; } + + /// + /// PriorityEnum.CrossBorder - crossBorder + /// + public static readonly PriorityEnum CrossBorder = new("crossBorder"); + + /// + /// PriorityEnum.Fast - fast + /// + public static readonly PriorityEnum Fast = new("fast"); + + /// + /// PriorityEnum.Instant - instant + /// + public static readonly PriorityEnum Instant = new("instant"); + + /// + /// PriorityEnum.Internal - internal + /// + public static readonly PriorityEnum Internal = new("internal"); + + /// + /// PriorityEnum.Regular - regular + /// + public static readonly PriorityEnum Regular = new("regular"); + + /// + /// PriorityEnum.Wire - wire + /// + public static readonly PriorityEnum Wire = new("wire"); + + private PriorityEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator PriorityEnum?(string? value) => value == null ? null : new PriorityEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(PriorityEnum? option) => option?.Value; + + public static bool operator ==(PriorityEnum? left, PriorityEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(PriorityEnum? left, PriorityEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is PriorityEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static PriorityEnum? FromStringOrDefault(string value) + { + return value switch { + "crossBorder" => PriorityEnum.CrossBorder, + "fast" => PriorityEnum.Fast, + "instant" => PriorityEnum.Instant, + "internal" => PriorityEnum.Internal, + "regular" => PriorityEnum.Regular, + "wire" => PriorityEnum.Wire, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(PriorityEnum? value) + { + if (value == null) + return null; + + if (value == PriorityEnum.CrossBorder) + return "crossBorder"; + + if (value == PriorityEnum.Fast) + return "fast"; + + if (value == PriorityEnum.Instant) + return "instant"; + + if (value == PriorityEnum.Internal) + return "internal"; + + if (value == PriorityEnum.Regular) + return "regular"; + + if (value == PriorityEnum.Wire) + return "wire"; + + return null; + } + + /// + /// JsonConverter for writing PriorityEnum. + /// + public class PriorityEnumJsonConverter : JsonConverter + { + public override PriorityEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : PriorityEnum.FromStringOrDefault(value) ?? new PriorityEnum(value); + } + + public override void Write(Utf8JsonWriter writer, PriorityEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(PriorityEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PriorityOption { get; private set; } + + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + /// + /// The priority for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. Required for transfers with `category` **bank**. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). + [JsonPropertyName("priority")] + public PriorityEnum? Priority { get { return this._PriorityOption; } set { this._PriorityOption = new(value); } } + + /// + /// The type of transfer. Possible values: - **bankTransfer**: for push transfers to a transfer instrument or a bank account. The `category` must be **bank**. - **internalTransfer**: for push transfers between balance accounts. The `category` must be **internal**. - **internalDirectDebit**: for pull transfers (direct debits) between balance accounts. The `category` must be **internal**. + /// + /// The type of transfer. Possible values: - **bankTransfer**: for push transfers to a transfer instrument or a bank account. The `category` must be **bank**. - **internalTransfer**: for push transfers between balance accounts. The `category` must be **internal**. - **internalDirectDebit**: for pull transfers (direct debits) between balance accounts. The `category` must be **internal**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.BankTransfer - bankTransfer + /// + public static readonly TypeEnum BankTransfer = new("bankTransfer"); + + /// + /// TypeEnum.InternalTransfer - internalTransfer + /// + public static readonly TypeEnum InternalTransfer = new("internalTransfer"); + + /// + /// TypeEnum.InternalDirectDebit - internalDirectDebit + /// + public static readonly TypeEnum InternalDirectDebit = new("internalDirectDebit"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "bankTransfer" => TypeEnum.BankTransfer, + "internalTransfer" => TypeEnum.InternalTransfer, + "internalDirectDebit" => TypeEnum.InternalDirectDebit, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.BankTransfer) + return "bankTransfer"; + + if (value == TypeEnum.InternalTransfer) + return "internalTransfer"; + + if (value == TypeEnum.InternalDirectDebit) + return "internalDirectDebit"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of transfer. Possible values: - **bankTransfer**: for push transfers to a transfer instrument or a bank account. The `category` must be **bank**. - **internalTransfer**: for push transfers between balance accounts. The `category` must be **internal**. - **internalDirectDebit**: for pull transfers (direct debits) between balance accounts. The `category` must be **internal**. + /// + /// The type of transfer. Possible values: - **bankTransfer**: for push transfers to a transfer instrument or a bank account. The `category` must be **bank**. - **internalTransfer**: for push transfers between balance accounts. The `category` must be **internal**. - **internalDirectDebit**: for pull transfers (direct debits) between balance accounts. The `category` must be **internal**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// . + /// + [JsonPropertyName("amount")] + public Amount Amount { get; set; } + + /// + /// . + /// + [JsonPropertyName("counterparty")] + public CounterpartyInfoV3 Counterparty { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount** assigned to the balance account, you must specify the [payment instrument ID](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id) of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + /// + /// The unique identifier of the source [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount** assigned to the balance account, you must specify the [payment instrument ID](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id) of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DescriptionOption { get; private set; } + + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + /// + /// Your description for the transfer. It is used by most banks as the transfer description. We recommend sending a maximum of 140 characters, otherwise the description may be truncated. Supported characters: **[a-z] [A-Z] [0-9] / - ?** **: ( ) . , ' + Space** Supported characters for **regular** and **fast** transfers to a US counterparty: **[a-z] [A-Z] [0-9] & $ % # @** **~ = + - _ ' \" ! ?** + [JsonPropertyName("description")] + public string? Description { get { return this._DescriptionOption; } set { this._DescriptionOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ExecutionDateOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("executionDate")] + public ExecutionDate? ExecutionDate { get { return this._ExecutionDateOption; } set { this._ExecutionDateOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PaymentInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the source [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount**, you must specify the payment instrument ID of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + /// + /// The unique identifier of the source [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/paymentInstruments#responses-200-id). If you want to make a transfer using a **virtual** **bankAccount**, you must specify the payment instrument ID of the **virtual** **bankAccount**. If you only specify a balance account ID, Adyen uses the default **physical** **bankAccount** payment instrument assigned to the balance account. + [JsonPropertyName("paymentInstrumentId")] + public string? PaymentInstrumentId { get { return this._PaymentInstrumentIdOption; } set { this._PaymentInstrumentIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _PrioritiesOption { get; private set; } + + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities. Adyen will try to pay out using the priority you list first. If that's not possible, it moves on to the next option in the order of your provided priorities. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Required for transfers with `category` **bank**. For more details, see [fallback priorities](https://docs.adyen.com/payouts/payout-service/payout-to-users/#fallback-priorities). + /// + /// The list of priorities for the bank transfer. This sets the speed at which the transfer is sent and the fees that you have to pay. You can provide multiple priorities. Adyen will try to pay out using the priority you list first. If that's not possible, it moves on to the next option in the order of your provided priorities. Possible values: * **regular**: for normal, low-value transactions. * **fast**: a faster way to transfer funds, but the fees are higher. Recommended for high-priority, low-value transactions. * **wire**: the fastest way to transfer funds, but this has the highest fees. Recommended for high-priority, high-value transactions. * **instant**: for instant funds transfers within the United States and in [SEPA locations](https://www.ecb.europa.eu/paym/integration/retail/sepa/html/index.en.html). * **crossBorder**: for high-value transfers to a recipient in a different country. * **internal**: for transfers to an Adyen-issued business bank account (by bank account number/IBAN). Required for transfers with `category` **bank**. For more details, see [fallback priorities](https://docs.adyen.com/payouts/payout-service/payout-to-users/#fallback-priorities). + [JsonPropertyName("priorities")] + public List? Priorities { get { return this._PrioritiesOption; } set { this._PrioritiesOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + /// + /// Your reference for the transfer, used internally within your platform. If you don't provide this in the request, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceForBeneficiaryOption { get; private set; } + + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both parties involved in the funds movement. Supported characters: **a-z**, **A-Z**, **0-9**. The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + /// + /// A reference that is sent to the recipient. This reference is also sent in all webhooks related to the transfer, so you can use it to track statuses for both parties involved in the funds movement. Supported characters: **a-z**, **A-Z**, **0-9**. The maximum length depends on the `category`. - **internal**: 80 characters - **bank**: 35 characters when transferring to an IBAN, 15 characters for others. + [JsonPropertyName("referenceForBeneficiary")] + public string? ReferenceForBeneficiary { get { return this._ReferenceForBeneficiaryOption; } set { this._ReferenceForBeneficiaryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReviewOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("review")] + public TransferRequestReview? Review { get { return this._ReviewOption; } set { this._ReviewOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UltimatePartyOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("ultimateParty")] + public UltimatePartyIdentification? UltimateParty { get { return this._UltimatePartyOption; } set { this._UltimatePartyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferInfo {\n"); + sb.Append(" Amount: ").Append(Amount).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Counterparty: ").Append(Counterparty).Append("\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExecutionDate: ").Append(ExecutionDate).Append("\n"); + sb.Append(" PaymentInstrumentId: ").Append(PaymentInstrumentId).Append("\n"); + sb.Append(" Priorities: ").Append(Priorities).Append("\n"); + sb.Append(" Priority: ").Append(Priority).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" ReferenceForBeneficiary: ").Append(ReferenceForBeneficiary).Append("\n"); + sb.Append(" Review: ").Append(Review).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" UltimateParty: ").Append(UltimateParty).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Description (string) maxLength + if (this.Description != null && this.Description.Length > 140) + { + yield return new ValidationResult("Invalid value for Description, length must be less than 140.", new [] { "Description" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 80) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 80.", new [] { "Reference" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferInfoJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferInfo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option amount = default; + Option category = default; + Option counterparty = default; + Option balanceAccountId = default; + Option description = default; + Option executionDate = default; + Option paymentInstrumentId = default; + Option?> priorities = default; + Option priority = default; + Option reference = default; + Option referenceForBeneficiary = default; + Option review = default; + Option type = default; + Option ultimateParty = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "amount": + amount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + category = new Option(TransferInfo.CategoryEnum.FromStringOrDefault(categoryRawValue)); + break; + case "counterparty": + counterparty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "executionDate": + executionDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "paymentInstrumentId": + paymentInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + case "priorities": + priorities = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "priority": + string? priorityRawValue = utf8JsonReader.GetString(); + priority = new Option(TransferInfo.PriorityEnum.FromStringOrDefault(priorityRawValue)); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "referenceForBeneficiary": + referenceForBeneficiary = new Option(utf8JsonReader.GetString()!); + break; + case "review": + review = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(TransferInfo.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "ultimateParty": + ultimateParty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!amount.IsSet) + throw new ArgumentException("Property is required for class TransferInfo.", nameof(amount)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class TransferInfo.", nameof(category)); + + if (!counterparty.IsSet) + throw new ArgumentException("Property is required for class TransferInfo.", nameof(counterparty)); + + return new TransferInfo(amount.Value!, category.Value!.Value!, counterparty.Value!, balanceAccountId, description, executionDate, paymentInstrumentId, priorities, priority, reference, referenceForBeneficiary, review, type, ultimateParty); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferInfo transferInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferInfo, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferInfo transferInfo, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WritePropertyName("amount"); + JsonSerializer.Serialize(writer, transferInfo.Amount, jsonSerializerOptions); + if (transferInfo.Category != null) + { + string? categoryRawValue = TransferInfo.CategoryEnum.ToJsonValue(transferInfo.Category); + writer.WriteString("category", categoryRawValue); + } + + writer.WritePropertyName("counterparty"); + JsonSerializer.Serialize(writer, transferInfo.Counterparty, jsonSerializerOptions); + if (transferInfo._BalanceAccountIdOption.IsSet) + if (transferInfo.BalanceAccountId != null) + writer.WriteString("balanceAccountId", transferInfo.BalanceAccountId); + + if (transferInfo._DescriptionOption.IsSet) + if (transferInfo.Description != null) + writer.WriteString("description", transferInfo.Description); + + if (transferInfo._ExecutionDateOption.IsSet) + { + writer.WritePropertyName("executionDate"); + JsonSerializer.Serialize(writer, transferInfo.ExecutionDate, jsonSerializerOptions); + } + if (transferInfo._PaymentInstrumentIdOption.IsSet) + if (transferInfo.PaymentInstrumentId != null) + writer.WriteString("paymentInstrumentId", transferInfo.PaymentInstrumentId); + + if (transferInfo._PrioritiesOption.IsSet) + { + writer.WritePropertyName("priorities"); + JsonSerializer.Serialize(writer, transferInfo.Priorities, jsonSerializerOptions); + } + if (transferInfo._PriorityOption.IsSet && transferInfo.Priority != null) + { + string? priorityRawValue = TransferInfo.PriorityEnum.ToJsonValue(transferInfo._PriorityOption.Value!.Value); + writer.WriteString("priority", priorityRawValue); + } + + if (transferInfo._ReferenceOption.IsSet) + if (transferInfo.Reference != null) + writer.WriteString("reference", transferInfo.Reference); + + if (transferInfo._ReferenceForBeneficiaryOption.IsSet) + if (transferInfo.ReferenceForBeneficiary != null) + writer.WriteString("referenceForBeneficiary", transferInfo.ReferenceForBeneficiary); + + if (transferInfo._ReviewOption.IsSet) + { + writer.WritePropertyName("review"); + JsonSerializer.Serialize(writer, transferInfo.Review, jsonSerializerOptions); + } + if (transferInfo._TypeOption.IsSet && transferInfo.Type != null) + { + string? typeRawValue = TransferInfo.TypeEnum.ToJsonValue(transferInfo._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (transferInfo._UltimatePartyOption.IsSet) + { + writer.WritePropertyName("ultimateParty"); + JsonSerializer.Serialize(writer, transferInfo.UltimateParty, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransferNotificationCounterParty.cs b/Adyen/Transfers/Models/TransferNotificationCounterParty.cs new file mode 100644 index 000000000..527f67e3a --- /dev/null +++ b/Adyen/Transfers/Models/TransferNotificationCounterParty.cs @@ -0,0 +1,277 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferNotificationCounterParty. + /// + public partial class TransferNotificationCounterParty : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// bankAccount + /// card + /// merchant + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonConstructor] + public TransferNotificationCounterParty(Option balanceAccountId = default, Option bankAccount = default, Option card = default, Option merchant = default, Option transferInstrumentId = default) + { + _BalanceAccountIdOption = balanceAccountId; + _BankAccountOption = bankAccount; + _CardOption = card; + _MerchantOption = merchant; + _TransferInstrumentIdOption = transferInstrumentId; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationCounterParty() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BalanceAccountIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + /// + /// The unique identifier of the counterparty [balance account](https://docs.adyen.com/api-explorer/balanceplatform/latest/post/balanceAccounts#responses-200-id). + [JsonPropertyName("balanceAccountId")] + public string? BalanceAccountId { get { return this._BalanceAccountIdOption; } set { this._BalanceAccountIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _BankAccountOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("bankAccount")] + public BankAccountV3? BankAccount { get { return this._BankAccountOption; } set { this._BankAccountOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CardOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("card")] + public Card? Card { get { return this._CardOption; } set { this._CardOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("merchant")] + public TransferNotificationMerchantData? Merchant { get { return this._MerchantOption; } set { this._MerchantOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TransferInstrumentIdOption { get; private set; } + + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + /// + /// The unique identifier of the counterparty [transfer instrument](https://docs.adyen.com/api-explorer/legalentity/latest/post/transferInstruments#responses-200-id). + [JsonPropertyName("transferInstrumentId")] + public string? TransferInstrumentId { get { return this._TransferInstrumentIdOption; } set { this._TransferInstrumentIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationCounterParty {\n"); + sb.Append(" BalanceAccountId: ").Append(BalanceAccountId).Append("\n"); + sb.Append(" BankAccount: ").Append(BankAccount).Append("\n"); + sb.Append(" Card: ").Append(Card).Append("\n"); + sb.Append(" Merchant: ").Append(Merchant).Append("\n"); + sb.Append(" TransferInstrumentId: ").Append(TransferInstrumentId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationCounterPartyJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationCounterParty Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceAccountId = default; + Option bankAccount = default; + Option card = default; + Option merchant = default; + Option transferInstrumentId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "balanceAccountId": + balanceAccountId = new Option(utf8JsonReader.GetString()!); + break; + case "bankAccount": + bankAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "card": + card = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "merchant": + merchant = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "transferInstrumentId": + transferInstrumentId = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationCounterParty(balanceAccountId, bankAccount, card, merchant, transferInstrumentId); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationCounterParty transferNotificationCounterParty, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationCounterParty, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationCounterParty transferNotificationCounterParty, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationCounterParty._BalanceAccountIdOption.IsSet) + if (transferNotificationCounterParty.BalanceAccountId != null) + writer.WriteString("balanceAccountId", transferNotificationCounterParty.BalanceAccountId); + + if (transferNotificationCounterParty._BankAccountOption.IsSet) + { + writer.WritePropertyName("bankAccount"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.BankAccount, jsonSerializerOptions); + } + if (transferNotificationCounterParty._CardOption.IsSet) + { + writer.WritePropertyName("card"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.Card, jsonSerializerOptions); + } + if (transferNotificationCounterParty._MerchantOption.IsSet) + { + writer.WritePropertyName("merchant"); + JsonSerializer.Serialize(writer, transferNotificationCounterParty.Merchant, jsonSerializerOptions); + } + if (transferNotificationCounterParty._TransferInstrumentIdOption.IsSet) + if (transferNotificationCounterParty.TransferInstrumentId != null) + writer.WriteString("transferInstrumentId", transferNotificationCounterParty.TransferInstrumentId); + } + } +} diff --git a/Adyen/Transfers/Models/TransferNotificationMerchantData.cs b/Adyen/Transfers/Models/TransferNotificationMerchantData.cs new file mode 100644 index 000000000..18b35e9fd --- /dev/null +++ b/Adyen/Transfers/Models/TransferNotificationMerchantData.cs @@ -0,0 +1,327 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferNotificationMerchantData. + /// + public partial class TransferNotificationMerchantData : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the merchant's acquirer. + /// The city where the merchant is located. + /// The country where the merchant is located. + /// The merchant category code. + /// The unique identifier of the merchant. + /// The name of the merchant's shop or service. + /// The postal code of the merchant. + [JsonConstructor] + public TransferNotificationMerchantData(Option acquirerId = default, Option city = default, Option country = default, Option mcc = default, Option merchantId = default, Option name = default, Option postalCode = default) + { + _AcquirerIdOption = acquirerId; + _CityOption = city; + _CountryOption = country; + _MccOption = mcc; + _MerchantIdOption = merchantId; + _NameOption = name; + _PostalCodeOption = postalCode; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationMerchantData() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AcquirerIdOption { get; private set; } + + /// + /// The unique identifier of the merchant's acquirer. + /// + /// The unique identifier of the merchant's acquirer. + [JsonPropertyName("acquirerId")] + public string? AcquirerId { get { return this._AcquirerIdOption; } set { this._AcquirerIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CityOption { get; private set; } + + /// + /// The city where the merchant is located. + /// + /// The city where the merchant is located. + [JsonPropertyName("city")] + public string? City { get { return this._CityOption; } set { this._CityOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CountryOption { get; private set; } + + /// + /// The country where the merchant is located. + /// + /// The country where the merchant is located. + [JsonPropertyName("country")] + public string? Country { get { return this._CountryOption; } set { this._CountryOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MccOption { get; private set; } + + /// + /// The merchant category code. + /// + /// The merchant category code. + [JsonPropertyName("mcc")] + public string? Mcc { get { return this._MccOption; } set { this._MccOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _MerchantIdOption { get; private set; } + + /// + /// The unique identifier of the merchant. + /// + /// The unique identifier of the merchant. + [JsonPropertyName("merchantId")] + public string? MerchantId { get { return this._MerchantIdOption; } set { this._MerchantIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NameOption { get; private set; } + + /// + /// The name of the merchant's shop or service. + /// + /// The name of the merchant's shop or service. + [JsonPropertyName("name")] + public string? Name { get { return this._NameOption; } set { this._NameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _PostalCodeOption { get; private set; } + + /// + /// The postal code of the merchant. + /// + /// The postal code of the merchant. + [JsonPropertyName("postalCode")] + public string? PostalCode { get { return this._PostalCodeOption; } set { this._PostalCodeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationMerchantData {\n"); + sb.Append(" AcquirerId: ").Append(AcquirerId).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Mcc: ").Append(Mcc).Append("\n"); + sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationMerchantDataJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationMerchantData Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option acquirerId = default; + Option city = default; + Option country = default; + Option mcc = default; + Option merchantId = default; + Option name = default; + Option postalCode = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "acquirerId": + acquirerId = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "mcc": + mcc = new Option(utf8JsonReader.GetString()!); + break; + case "merchantId": + merchantId = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "postalCode": + postalCode = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationMerchantData(acquirerId, city, country, mcc, merchantId, name, postalCode); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationMerchantData transferNotificationMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationMerchantData, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationMerchantData transferNotificationMerchantData, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationMerchantData._AcquirerIdOption.IsSet) + if (transferNotificationMerchantData.AcquirerId != null) + writer.WriteString("acquirerId", transferNotificationMerchantData.AcquirerId); + + if (transferNotificationMerchantData._CityOption.IsSet) + if (transferNotificationMerchantData.City != null) + writer.WriteString("city", transferNotificationMerchantData.City); + + if (transferNotificationMerchantData._CountryOption.IsSet) + if (transferNotificationMerchantData.Country != null) + writer.WriteString("country", transferNotificationMerchantData.Country); + + if (transferNotificationMerchantData._MccOption.IsSet) + if (transferNotificationMerchantData.Mcc != null) + writer.WriteString("mcc", transferNotificationMerchantData.Mcc); + + if (transferNotificationMerchantData._MerchantIdOption.IsSet) + if (transferNotificationMerchantData.MerchantId != null) + writer.WriteString("merchantId", transferNotificationMerchantData.MerchantId); + + if (transferNotificationMerchantData._NameOption.IsSet) + if (transferNotificationMerchantData.Name != null) + writer.WriteString("name", transferNotificationMerchantData.Name); + + if (transferNotificationMerchantData._PostalCodeOption.IsSet) + if (transferNotificationMerchantData.PostalCode != null) + writer.WriteString("postalCode", transferNotificationMerchantData.PostalCode); + } + } +} diff --git a/Adyen/Transfers/Models/TransferNotificationValidationFact.cs b/Adyen/Transfers/Models/TransferNotificationValidationFact.cs new file mode 100644 index 000000000..d1e30e4fe --- /dev/null +++ b/Adyen/Transfers/Models/TransferNotificationValidationFact.cs @@ -0,0 +1,202 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferNotificationValidationFact. + /// + public partial class TransferNotificationValidationFact : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The evaluation result of the validation fact. + /// The type of the validation fact. + [JsonConstructor] + public TransferNotificationValidationFact(Option result = default, Option type = default) + { + _ResultOption = result; + _TypeOption = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferNotificationValidationFact() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResultOption { get; private set; } + + /// + /// The evaluation result of the validation fact. + /// + /// The evaluation result of the validation fact. + [JsonPropertyName("result")] + public string? Result { get { return this._ResultOption; } set { this._ResultOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of the validation fact. + /// + /// The type of the validation fact. + [JsonPropertyName("type")] + public string? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferNotificationValidationFact {\n"); + sb.Append(" Result: ").Append(Result).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferNotificationValidationFactJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferNotificationValidationFact Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option result = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "result": + result = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new TransferNotificationValidationFact(result, type); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferNotificationValidationFact, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferNotificationValidationFact transferNotificationValidationFact, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferNotificationValidationFact._ResultOption.IsSet) + if (transferNotificationValidationFact.Result != null) + writer.WriteString("result", transferNotificationValidationFact.Result); + + if (transferNotificationValidationFact._TypeOption.IsSet) + if (transferNotificationValidationFact.Type != null) + writer.WriteString("type", transferNotificationValidationFact.Type); + } + } +} diff --git a/Adyen/Transfers/Models/TransferRequestReview.cs b/Adyen/Transfers/Models/TransferRequestReview.cs new file mode 100644 index 000000000..66d0b00a4 --- /dev/null +++ b/Adyen/Transfers/Models/TransferRequestReview.cs @@ -0,0 +1,200 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferRequestReview. + /// + public partial class TransferRequestReview : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Specifies the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// Specifies whether you will initiate Strong Customer Authentication (SCA) in thePOST [/transfers/approve](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) request. Only applies to transfers made with an Adyen [business account](https://docs.adyen.com/platforms/business-accounts). + [JsonConstructor] + public TransferRequestReview(Option numberOfApprovalsRequired = default, Option scaOnApproval = default) + { + _NumberOfApprovalsRequiredOption = numberOfApprovalsRequired; + _ScaOnApprovalOption = scaOnApproval; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferRequestReview() + { + } + + partial void OnCreated(); + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOfApprovalsRequiredOption { get; private set; } + + /// + /// Specifies the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// + /// Specifies the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + [JsonPropertyName("numberOfApprovalsRequired")] + public int? NumberOfApprovalsRequired { get { return this._NumberOfApprovalsRequiredOption; } set { this._NumberOfApprovalsRequiredOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaOnApprovalOption { get; private set; } + + /// + /// Specifies whether you will initiate Strong Customer Authentication (SCA) in thePOST [/transfers/approve](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) request. Only applies to transfers made with an Adyen [business account](https://docs.adyen.com/platforms/business-accounts). + /// + /// Specifies whether you will initiate Strong Customer Authentication (SCA) in thePOST [/transfers/approve](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) request. Only applies to transfers made with an Adyen [business account](https://docs.adyen.com/platforms/business-accounts). + [JsonPropertyName("scaOnApproval")] + public bool? ScaOnApproval { get { return this._ScaOnApprovalOption; } set { this._ScaOnApprovalOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferRequestReview {\n"); + sb.Append(" NumberOfApprovalsRequired: ").Append(NumberOfApprovalsRequired).Append("\n"); + sb.Append(" ScaOnApproval: ").Append(ScaOnApproval).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferRequestReviewJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferRequestReview Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option numberOfApprovalsRequired = default; + Option scaOnApproval = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "numberOfApprovalsRequired": + numberOfApprovalsRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "scaOnApproval": + scaOnApproval = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + + return new TransferRequestReview(numberOfApprovalsRequired, scaOnApproval); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferRequestReview transferRequestReview, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferRequestReview, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferRequestReview transferRequestReview, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferRequestReview._NumberOfApprovalsRequiredOption.IsSet) + writer.WriteNumber("numberOfApprovalsRequired", transferRequestReview._NumberOfApprovalsRequiredOption.Value!.Value); + + if (transferRequestReview._ScaOnApprovalOption.IsSet) + writer.WriteBoolean("scaOnApproval", transferRequestReview._ScaOnApprovalOption.Value!.Value); + } + } +} diff --git a/Adyen/Transfers/Models/TransferReview.cs b/Adyen/Transfers/Models/TransferReview.cs new file mode 100644 index 000000000..5f6b4919b --- /dev/null +++ b/Adyen/Transfers/Models/TransferReview.cs @@ -0,0 +1,316 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferReview. + /// + public partial class TransferReview : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonConstructor] + public TransferReview(Option numberOfApprovalsRequired = default, Option scaOnApproval = default) + { + _NumberOfApprovalsRequiredOption = numberOfApprovalsRequired; + _ScaOnApprovalOption = scaOnApproval; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferReview() + { + } + + partial void OnCreated(); + + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonConverter(typeof(ScaOnApprovalEnumJsonConverter))] + public class ScaOnApprovalEnum : IEnum + { + /// + /// Returns the value of the ScaOnApprovalEnum. + /// + public string? Value { get; set; } + + /// + /// ScaOnApprovalEnum.Completed - completed + /// + public static readonly ScaOnApprovalEnum Completed = new("completed"); + + /// + /// ScaOnApprovalEnum.NotApplicable - notApplicable + /// + public static readonly ScaOnApprovalEnum NotApplicable = new("notApplicable"); + + /// + /// ScaOnApprovalEnum.Required - required + /// + public static readonly ScaOnApprovalEnum Required = new("required"); + + private ScaOnApprovalEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator ScaOnApprovalEnum?(string? value) => value == null ? null : new ScaOnApprovalEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(ScaOnApprovalEnum? option) => option?.Value; + + public static bool operator ==(ScaOnApprovalEnum? left, ScaOnApprovalEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(ScaOnApprovalEnum? left, ScaOnApprovalEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is ScaOnApprovalEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static ScaOnApprovalEnum? FromStringOrDefault(string value) + { + return value switch { + "completed" => ScaOnApprovalEnum.Completed, + "notApplicable" => ScaOnApprovalEnum.NotApplicable, + "required" => ScaOnApprovalEnum.Required, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(ScaOnApprovalEnum? value) + { + if (value == null) + return null; + + if (value == ScaOnApprovalEnum.Completed) + return "completed"; + + if (value == ScaOnApprovalEnum.NotApplicable) + return "notApplicable"; + + if (value == ScaOnApprovalEnum.Required) + return "required"; + + return null; + } + + /// + /// JsonConverter for writing ScaOnApprovalEnum. + /// + public class ScaOnApprovalEnumJsonConverter : JsonConverter + { + public override ScaOnApprovalEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : ScaOnApprovalEnum.FromStringOrDefault(value) ?? new ScaOnApprovalEnum(value); + } + + public override void Write(Utf8JsonWriter writer, ScaOnApprovalEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(ScaOnApprovalEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ScaOnApprovalOption { get; private set; } + + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + /// + /// Shows the status of the Strong Customer Authentication (SCA) process. Possible values: **required**, **notApplicable**. + [JsonPropertyName("scaOnApproval")] + public ScaOnApprovalEnum? ScaOnApproval { get { return this._ScaOnApprovalOption; } set { this._ScaOnApprovalOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _NumberOfApprovalsRequiredOption { get; private set; } + + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + /// + /// Shows the number of [approvals](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers/approve) required to process the transfer. + [JsonPropertyName("numberOfApprovalsRequired")] + public int? NumberOfApprovalsRequired { get { return this._NumberOfApprovalsRequiredOption; } set { this._NumberOfApprovalsRequiredOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferReview {\n"); + sb.Append(" NumberOfApprovalsRequired: ").Append(NumberOfApprovalsRequired).Append("\n"); + sb.Append(" ScaOnApproval: ").Append(ScaOnApproval).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferReviewJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferReview Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option numberOfApprovalsRequired = default; + Option scaOnApproval = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "numberOfApprovalsRequired": + numberOfApprovalsRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "scaOnApproval": + string? scaOnApprovalRawValue = utf8JsonReader.GetString(); + scaOnApproval = new Option(TransferReview.ScaOnApprovalEnum.FromStringOrDefault(scaOnApprovalRawValue)); + break; + default: + break; + } + } + } + + + return new TransferReview(numberOfApprovalsRequired, scaOnApproval); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferReview transferReview, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferReview, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferReview transferReview, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferReview._NumberOfApprovalsRequiredOption.IsSet) + writer.WriteNumber("numberOfApprovalsRequired", transferReview._NumberOfApprovalsRequiredOption.Value!.Value); + + if (transferReview._ScaOnApprovalOption.IsSet && transferReview.ScaOnApproval != null) + { + string? scaOnApprovalRawValue = TransferReview.ScaOnApprovalEnum.ToJsonValue(transferReview._ScaOnApprovalOption.Value!.Value); + writer.WriteString("scaOnApproval", scaOnApprovalRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransferServiceRestServiceError.cs b/Adyen/Transfers/Models/TransferServiceRestServiceError.cs new file mode 100644 index 000000000..a48527459 --- /dev/null +++ b/Adyen/Transfers/Models/TransferServiceRestServiceError.cs @@ -0,0 +1,378 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferServiceRestServiceError. + /// + public partial class TransferServiceRestServiceError : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// A code that identifies the problem type. + /// The HTTP status code. + /// A short, human-readable summary of the problem type. + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// A unique URI that identifies the specific occurrence of the problem. + /// Detailed explanation of each validation error, when applicable. + /// A unique reference for the request, essentially the same as `pspReference`. + /// response + /// Detailed explanation of each attempt to route the transfer with the priorities from the request. + [JsonConstructor] + public TransferServiceRestServiceError(string detail, string errorCode, int status, string title, string type, Option instance = default, Option?> invalidFields = default, Option requestId = default, Option response = default, Option?> routingDetails = default) + { + Detail = detail; + ErrorCode = errorCode; + Status = status; + Title = title; + Type = type; + _InstanceOption = instance; + _InvalidFieldsOption = invalidFields; + _RequestIdOption = requestId; + _ResponseOption = response; + _RoutingDetailsOption = routingDetails; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferServiceRestServiceError() + { + } + + partial void OnCreated(); + + /// + /// A human-readable explanation specific to this occurrence of the problem. + /// + /// A human-readable explanation specific to this occurrence of the problem. + [JsonPropertyName("detail")] + public string Detail { get; set; } + + /// + /// A code that identifies the problem type. + /// + /// A code that identifies the problem type. + [JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// The HTTP status code. + /// + /// The HTTP status code. + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// A short, human-readable summary of the problem type. + /// + /// A short, human-readable summary of the problem type. + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + /// + /// A URI that identifies the problem type, pointing to human-readable documentation on this problem type. + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _InstanceOption { get; private set; } + + /// + /// A unique URI that identifies the specific occurrence of the problem. + /// + /// A unique URI that identifies the specific occurrence of the problem. + [JsonPropertyName("instance")] + public string? Instance { get { return this._InstanceOption; } set { this._InstanceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _InvalidFieldsOption { get; private set; } + + /// + /// Detailed explanation of each validation error, when applicable. + /// + /// Detailed explanation of each validation error, when applicable. + [JsonPropertyName("invalidFields")] + public List? InvalidFields { get { return this._InvalidFieldsOption; } set { this._InvalidFieldsOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _RequestIdOption { get; private set; } + + /// + /// A unique reference for the request, essentially the same as `pspReference`. + /// + /// A unique reference for the request, essentially the same as `pspReference`. + [JsonPropertyName("requestId")] + public string? RequestId { get { return this._RequestIdOption; } set { this._RequestIdOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ResponseOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("response")] + public Object? Response { get { return this._ResponseOption; } set { this._ResponseOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> _RoutingDetailsOption { get; private set; } + + /// + /// Detailed explanation of each attempt to route the transfer with the priorities from the request. + /// + /// Detailed explanation of each attempt to route the transfer with the priorities from the request. + [JsonPropertyName("routingDetails")] + public List? RoutingDetails { get { return this._RoutingDetailsOption; } set { this._RoutingDetailsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferServiceRestServiceError {\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" ErrorCode: ").Append(ErrorCode).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n"); + sb.Append(" RequestId: ").Append(RequestId).Append("\n"); + sb.Append(" Response: ").Append(Response).Append("\n"); + sb.Append(" RoutingDetails: ").Append(RoutingDetails).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferServiceRestServiceErrorJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferServiceRestServiceError Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option detail = default; + Option errorCode = default; + Option status = default; + Option title = default; + Option type = default; + Option instance = default; + Option?> invalidFields = default; + Option requestId = default; + Option response = default; + Option?> routingDetails = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "errorCode": + errorCode = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "invalidFields": + invalidFields = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "requestId": + requestId = new Option(utf8JsonReader.GetString()!); + break; + case "response": + response = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "routingDetails": + routingDetails = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!detail.IsSet) + throw new ArgumentException("Property is required for class TransferServiceRestServiceError.", nameof(detail)); + + if (!errorCode.IsSet) + throw new ArgumentException("Property is required for class TransferServiceRestServiceError.", nameof(errorCode)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class TransferServiceRestServiceError.", nameof(status)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class TransferServiceRestServiceError.", nameof(title)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class TransferServiceRestServiceError.", nameof(type)); + + return new TransferServiceRestServiceError(detail.Value!, errorCode.Value!, status.Value!.Value!, title.Value!, type.Value!, instance, invalidFields, requestId, response, routingDetails); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferServiceRestServiceError transferServiceRestServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferServiceRestServiceError, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferServiceRestServiceError transferServiceRestServiceError, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferServiceRestServiceError.Detail != null) + writer.WriteString("detail", transferServiceRestServiceError.Detail); + + if (transferServiceRestServiceError.ErrorCode != null) + writer.WriteString("errorCode", transferServiceRestServiceError.ErrorCode); + + writer.WriteNumber("status", transferServiceRestServiceError.Status); + + if (transferServiceRestServiceError.Title != null) + writer.WriteString("title", transferServiceRestServiceError.Title); + + if (transferServiceRestServiceError.Type != null) + writer.WriteString("type", transferServiceRestServiceError.Type); + + if (transferServiceRestServiceError._InstanceOption.IsSet) + if (transferServiceRestServiceError.Instance != null) + writer.WriteString("instance", transferServiceRestServiceError.Instance); + + if (transferServiceRestServiceError._InvalidFieldsOption.IsSet) + { + writer.WritePropertyName("invalidFields"); + JsonSerializer.Serialize(writer, transferServiceRestServiceError.InvalidFields, jsonSerializerOptions); + } + if (transferServiceRestServiceError._RequestIdOption.IsSet) + if (transferServiceRestServiceError.RequestId != null) + writer.WriteString("requestId", transferServiceRestServiceError.RequestId); + + if (transferServiceRestServiceError._ResponseOption.IsSet) + { + writer.WritePropertyName("response"); + JsonSerializer.Serialize(writer, transferServiceRestServiceError.Response, jsonSerializerOptions); + } + if (transferServiceRestServiceError._RoutingDetailsOption.IsSet) + { + writer.WritePropertyName("routingDetails"); + JsonSerializer.Serialize(writer, transferServiceRestServiceError.RoutingDetails, jsonSerializerOptions); + } + } + } +} diff --git a/Adyen/Transfers/Models/TransferView.cs b/Adyen/Transfers/Models/TransferView.cs new file mode 100644 index 000000000..ff311c6dd --- /dev/null +++ b/Adyen/Transfers/Models/TransferView.cs @@ -0,0 +1,221 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// TransferView. + /// + public partial class TransferView : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + /// categoryData + /// The ID of the resource. + [JsonConstructor] + public TransferView(string reference, Option categoryData = default, Option id = default) + { + Reference = reference; + _CategoryDataOption = categoryData; + _IdOption = id; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public TransferView() + { + } + + partial void OnCreated(); + + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + /// + /// The [`reference`](https://docs.adyen.com/api-explorer/#/transfers/latest/post/transfers__reqParam_reference) from the `/transfers` request. If you haven't provided any, Adyen generates a unique reference. + [JsonPropertyName("reference")] + public string Reference { get; set; } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _CategoryDataOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("categoryData")] + public TransferCategoryData? CategoryData { get { return this._CategoryDataOption; } set { this._CategoryDataOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _IdOption { get; private set; } + + /// + /// The ID of the resource. + /// + /// The ID of the resource. + [JsonPropertyName("id")] + public string? Id { get { return this._IdOption; } set { this._IdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TransferView {\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" CategoryData: ").Append(CategoryData).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TransferViewJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override TransferView Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option reference = default; + Option categoryData = default; + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "categoryData": + categoryData = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!reference.IsSet) + throw new ArgumentException("Property is required for class TransferView.", nameof(reference)); + + return new TransferView(reference.Value!, categoryData, id); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TransferView transferView, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, transferView, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TransferView transferView, JsonSerializerOptions jsonSerializerOptions) + { + + if (transferView.Reference != null) + writer.WriteString("reference", transferView.Reference); + + if (transferView._CategoryDataOption.IsSet) + { + writer.WritePropertyName("categoryData"); + JsonSerializer.Serialize(writer, transferView.CategoryData, jsonSerializerOptions); + } + if (transferView._IdOption.IsSet) + if (transferView.Id != null) + writer.WriteString("id", transferView.Id); + } + } +} diff --git a/Adyen/Transfers/Models/UKLocalAccountIdentification.cs b/Adyen/Transfers/Models/UKLocalAccountIdentification.cs new file mode 100644 index 000000000..ece2f73d6 --- /dev/null +++ b/Adyen/Transfers/Models/UKLocalAccountIdentification.cs @@ -0,0 +1,333 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// UKLocalAccountIdentification. + /// + public partial class UKLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The 8-digit bank account number, without separators or whitespace. + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// **ukLocal** (default to TypeEnum.UkLocal) + [JsonConstructor] + public UKLocalAccountIdentification(string accountNumber, string sortCode, TypeEnum type = default) + { + AccountNumber = accountNumber; + SortCode = sortCode; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UKLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UkLocal - ukLocal + /// + public static readonly TypeEnum UkLocal = new("ukLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "ukLocal" => TypeEnum.UkLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UkLocal) + return "ukLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **ukLocal** + /// + /// **ukLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The 8-digit bank account number, without separators or whitespace. + /// + /// The 8-digit bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + /// + /// The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. + [JsonPropertyName("sortCode")] + public string SortCode { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UKLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" SortCode: ").Append(SortCode).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 8.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 8) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 8.", new [] { "AccountNumber" }); + } + + // SortCode (string) maxLength + if (this.SortCode != null && this.SortCode.Length > 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be less than 6.", new [] { "SortCode" }); + } + + // SortCode (string) minLength + if (this.SortCode != null && this.SortCode.Length < 6) + { + yield return new ValidationResult("Invalid value for SortCode, length must be greater than 6.", new [] { "SortCode" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UKLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UKLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option sortCode = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "sortCode": + sortCode = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UKLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(accountNumber)); + + if (!sortCode.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(sortCode)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class UKLocalAccountIdentification.", nameof(type)); + + return new UKLocalAccountIdentification(accountNumber.Value!, sortCode.Value!, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uKLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UKLocalAccountIdentification uKLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uKLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uKLocalAccountIdentification.AccountNumber); + + if (uKLocalAccountIdentification.SortCode != null) + writer.WriteString("sortCode", uKLocalAccountIdentification.SortCode); + + if (uKLocalAccountIdentification.Type != null) + { + string? typeRawValue = UKLocalAccountIdentification.TypeEnum.ToJsonValue(uKLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/USLocalAccountIdentification.cs b/Adyen/Transfers/Models/USLocalAccountIdentification.cs new file mode 100644 index 000000000..dd8c8acc6 --- /dev/null +++ b/Adyen/Transfers/Models/USLocalAccountIdentification.cs @@ -0,0 +1,464 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// USLocalAccountIdentification. + /// + public partial class USLocalAccountIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// The bank account number, without separators or whitespace. + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. (default to AccountTypeEnum.Checking) + /// **usLocal** (default to TypeEnum.UsLocal) + [JsonConstructor] + public USLocalAccountIdentification(string accountNumber, string routingNumber, Option accountType = default, TypeEnum type = default) + { + AccountNumber = accountNumber; + RoutingNumber = routingNumber; + _AccountTypeOption = accountType; + Type = type; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public USLocalAccountIdentification() + { + } + + partial void OnCreated(); + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonConverter(typeof(AccountTypeEnumJsonConverter))] + public class AccountTypeEnum : IEnum + { + /// + /// Returns the value of the AccountTypeEnum. + /// + public string? Value { get; set; } + + /// + /// AccountTypeEnum.Checking - checking + /// + public static readonly AccountTypeEnum Checking = new("checking"); + + /// + /// AccountTypeEnum.Savings - savings + /// + public static readonly AccountTypeEnum Savings = new("savings"); + + private AccountTypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator AccountTypeEnum?(string? value) => value == null ? null : new AccountTypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(AccountTypeEnum? option) => option?.Value; + + public static bool operator ==(AccountTypeEnum? left, AccountTypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(AccountTypeEnum? left, AccountTypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is AccountTypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static AccountTypeEnum? FromStringOrDefault(string value) + { + return value switch { + "checking" => AccountTypeEnum.Checking, + "savings" => AccountTypeEnum.Savings, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(AccountTypeEnum? value) + { + if (value == null) + return null; + + if (value == AccountTypeEnum.Checking) + return "checking"; + + if (value == AccountTypeEnum.Savings) + return "savings"; + + return null; + } + + /// + /// JsonConverter for writing AccountTypeEnum. + /// + public class AccountTypeEnumJsonConverter : JsonConverter + { + public override AccountTypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : AccountTypeEnum.FromStringOrDefault(value) ?? new AccountTypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, AccountTypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(AccountTypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AccountTypeOption { get; private set; } + + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + /// + /// The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. + [JsonPropertyName("accountType")] + public AccountTypeEnum? AccountType { get { return this._AccountTypeOption; } set { this._AccountTypeOption = new(value); } } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.UsLocal - usLocal + /// + public static readonly TypeEnum UsLocal = new("usLocal"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "usLocal" => TypeEnum.UsLocal, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.UsLocal) + return "usLocal"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// **usLocal** + /// + /// **usLocal** + [JsonPropertyName("type")] + public TypeEnum Type { get; set; } + + /// + /// The bank account number, without separators or whitespace. + /// + /// The bank account number, without separators or whitespace. + [JsonPropertyName("accountNumber")] + public string AccountNumber { get; set; } + + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + /// + /// The 9-digit [routing number](https://en.wikipedia.org/wiki/ABA_routing_transit_number), without separators or whitespace. + [JsonPropertyName("routingNumber")] + public string RoutingNumber { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class USLocalAccountIdentification {\n"); + sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); + sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); + sb.Append(" AccountType: ").Append(AccountType).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // AccountNumber (string) maxLength + if (this.AccountNumber != null && this.AccountNumber.Length > 18) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be less than 18.", new [] { "AccountNumber" }); + } + + // AccountNumber (string) minLength + if (this.AccountNumber != null && this.AccountNumber.Length < 2) + { + yield return new ValidationResult("Invalid value for AccountNumber, length must be greater than 2.", new [] { "AccountNumber" }); + } + + // RoutingNumber (string) maxLength + if (this.RoutingNumber != null && this.RoutingNumber.Length > 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be less than 9.", new [] { "RoutingNumber" }); + } + + // RoutingNumber (string) minLength + if (this.RoutingNumber != null && this.RoutingNumber.Length < 9) + { + yield return new ValidationResult("Invalid value for RoutingNumber, length must be greater than 9.", new [] { "RoutingNumber" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class USLocalAccountIdentificationJsonConverter : JsonConverter + { + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override USLocalAccountIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option accountNumber = default; + Option routingNumber = default; + Option accountType = default; + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "accountNumber": + accountNumber = new Option(utf8JsonReader.GetString()!); + break; + case "routingNumber": + routingNumber = new Option(utf8JsonReader.GetString()!); + break; + case "accountType": + string? accountTypeRawValue = utf8JsonReader.GetString(); + accountType = new Option(USLocalAccountIdentification.AccountTypeEnum.FromStringOrDefault(accountTypeRawValue)); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(USLocalAccountIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!accountNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(accountNumber)); + + if (!routingNumber.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(routingNumber)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class USLocalAccountIdentification.", nameof(type)); + + return new USLocalAccountIdentification(accountNumber.Value!, routingNumber.Value!, accountType, type.Value!.Value!); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, uSLocalAccountIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, USLocalAccountIdentification uSLocalAccountIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (uSLocalAccountIdentification.AccountNumber != null) + writer.WriteString("accountNumber", uSLocalAccountIdentification.AccountNumber); + + if (uSLocalAccountIdentification.RoutingNumber != null) + writer.WriteString("routingNumber", uSLocalAccountIdentification.RoutingNumber); + + if (uSLocalAccountIdentification._AccountTypeOption.IsSet && uSLocalAccountIdentification.AccountType != null) + { + string? accountTypeRawValue = USLocalAccountIdentification.AccountTypeEnum.ToJsonValue(uSLocalAccountIdentification._AccountTypeOption.Value!.Value); + writer.WriteString("accountType", accountTypeRawValue); + } + + if (uSLocalAccountIdentification.Type != null) + { + string? typeRawValue = USLocalAccountIdentification.TypeEnum.ToJsonValue(uSLocalAccountIdentification.Type); + writer.WriteString("type", typeRawValue); + } + } + } +} diff --git a/Adyen/Transfers/Models/UltimatePartyIdentification.cs b/Adyen/Transfers/Models/UltimatePartyIdentification.cs new file mode 100644 index 000000000..9d931315a --- /dev/null +++ b/Adyen/Transfers/Models/UltimatePartyIdentification.cs @@ -0,0 +1,514 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Adyen.Core; +using Adyen.Transfers.Client; + +namespace Adyen.Transfers.Models +{ + /// + /// UltimatePartyIdentification. + /// + public partial class UltimatePartyIdentification : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// address + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// The email address of the organization or individual. Maximum length: 254 characters. + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. (default to TypeEnum.Unknown) + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonConstructor] + public UltimatePartyIdentification(Option address = default, Option dateOfBirth = default, Option email = default, Option firstName = default, Option fullName = default, Option lastName = default, Option reference = default, Option type = default, Option url = default) + { + _AddressOption = address; + _DateOfBirthOption = dateOfBirth; + _EmailOption = email; + _FirstNameOption = firstName; + _FullNameOption = fullName; + _LastNameOption = lastName; + _ReferenceOption = reference; + _TypeOption = type; + _UrlOption = url; + OnCreated(); + } + + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + public UltimatePartyIdentification() + { + } + + partial void OnCreated(); + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonConverter(typeof(TypeEnumJsonConverter))] + public class TypeEnum : IEnum + { + /// + /// Returns the value of the TypeEnum. + /// + public string? Value { get; set; } + + /// + /// TypeEnum.Individual - individual + /// + public static readonly TypeEnum Individual = new("individual"); + + /// + /// TypeEnum.Organization - organization + /// + public static readonly TypeEnum Organization = new("organization"); + + /// + /// TypeEnum.Unknown - unknown + /// + public static readonly TypeEnum Unknown = new("unknown"); + + private TypeEnum(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator TypeEnum?(string? value) => value == null ? null : new TypeEnum(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?(TypeEnum? option) => option?.Value; + + public static bool operator ==(TypeEnum? left, TypeEnum? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=(TypeEnum? left, TypeEnum? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is TypeEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + /// + /// Returns a . + /// + /// + /// or null. + public static TypeEnum? FromStringOrDefault(string value) + { + return value switch { + "individual" => TypeEnum.Individual, + "organization" => TypeEnum.Organization, + "unknown" => TypeEnum.Unknown, + _ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + /// + public static string? ToJsonValue(TypeEnum? value) + { + if (value == null) + return null; + + if (value == TypeEnum.Individual) + return "individual"; + + if (value == TypeEnum.Organization) + return "organization"; + + if (value == TypeEnum.Unknown) + return "unknown"; + + return null; + } + + /// + /// JsonConverter for writing TypeEnum. + /// + public class TypeEnumJsonConverter : JsonConverter + { + public override TypeEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : TypeEnum.FromStringOrDefault(value) ?? new TypeEnum(value); + } + + public override void Write(Utf8JsonWriter writer, TypeEnum value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue(TypeEnum.ToJsonValue(value)); + } + } + } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _TypeOption { get; private set; } + + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + /// + /// The type of entity that owns the bank account or card. Possible values: **individual**, **organization**, or **unknown**. Required when `category` is **card**. In this case, the value must be **individual**. + [JsonPropertyName("type")] + public TypeEnum? Type { get { return this._TypeOption; } set { this._TypeOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _AddressOption { get; private set; } + + /// + /// . + /// + [JsonPropertyName("address")] + public Address? Address { get { return this._AddressOption; } set { this._AddressOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _DateOfBirthOption { get; private set; } + + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + /// + /// The date of birth of the individual in [ISO-8601](https://www.w3.org/TR/NOTE-datetime) format. For example, **YYYY-MM-DD**. Allowed only when `type` is **individual**. + [JsonPropertyName("dateOfBirth")] + public DateOnly? DateOfBirth { get { return this._DateOfBirthOption; } set { this._DateOfBirthOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _EmailOption { get; private set; } + + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + /// + /// The email address of the organization or individual. Maximum length: 254 characters. + [JsonPropertyName("email")] + public string? Email { get { return this._EmailOption; } set { this._EmailOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FirstNameOption { get; private set; } + + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The first name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("firstName")] + public string? FirstName { get { return this._FirstNameOption; } set { this._FirstNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _FullNameOption { get; private set; } + + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + /// + /// The full name of the entity that owns the bank account or card. Supported characters: [a-z] [A-Z] [0-9] , . ; : - — / \\ + & ! ? @ ( ) \" ' and space. Required when `category` is **bank**. + [JsonPropertyName("fullName")] + public string? FullName { get { return this._FullNameOption; } set { this._FullNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _LastNameOption { get; private set; } + + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + /// + /// The last name of the individual. Supported characters: [a-z] [A-Z] - . / — and space. This parameter is: - Allowed only when `type` is **individual**. - Required when `category` is **card**. + [JsonPropertyName("lastName")] + public string? LastName { get { return this._LastNameOption; } set { this._LastNameOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _ReferenceOption { get; private set; } + + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + /// + /// A unique reference to identify the party or counterparty involved in the transfer. For example, your client's unique wallet or payee ID. Required when you include `cardIdentification.storedPaymentMethodId`. + [JsonPropertyName("reference")] + public string? Reference { get { return this._ReferenceOption; } set { this._ReferenceOption = new(value); } } + + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option _UrlOption { get; private set; } + + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + /// + /// The URL of the organization or individual. Maximum length: 255 characters. + [JsonPropertyName("url")] + public string? Url { get { return this._UrlOption; } set { this._UrlOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UltimatePartyIdentification {\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" DateOfBirth: ").Append(DateOfBirth).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" FullName: ").Append(FullName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Reference: ").Append(Reference).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Url: ").Append(Url).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) maxLength + if (this.Email != null && this.Email.Length > 254) + { + yield return new ValidationResult("Invalid value for Email, length must be less than 254.", new [] { "Email" }); + } + + // Reference (string) maxLength + if (this.Reference != null && this.Reference.Length > 150) + { + yield return new ValidationResult("Invalid value for Reference, length must be less than 150.", new [] { "Reference" }); + } + + // Url (string) maxLength + if (this.Url != null && this.Url.Length > 255) + { + yield return new ValidationResult("Invalid value for Url, length must be less than 255.", new [] { "Url" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UltimatePartyIdentificationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize DateOfBirth. + /// + public static string DateOfBirthFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override UltimatePartyIdentification Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option address = default; + Option dateOfBirth = default; + Option email = default; + Option firstName = default; + Option fullName = default; + Option lastName = default; + Option reference = default; + Option type = default; + Option url = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + case "address": + address = new Option(JsonSerializer.Deserialize
(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "dateOfBirth": + dateOfBirth = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "email": + email = new Option(utf8JsonReader.GetString()!); + break; + case "firstName": + firstName = new Option(utf8JsonReader.GetString()!); + break; + case "fullName": + fullName = new Option(utf8JsonReader.GetString()!); + break; + case "lastName": + lastName = new Option(utf8JsonReader.GetString()!); + break; + case "reference": + reference = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + type = new Option(UltimatePartyIdentification.TypeEnum.FromStringOrDefault(typeRawValue)); + break; + case "url": + url = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + + return new UltimatePartyIdentification(address, dateOfBirth, email, firstName, fullName, lastName, reference, type, url); + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UltimatePartyIdentification ultimatePartyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + writer.WriteStartObject(); + + WriteProperties(writer, ultimatePartyIdentification, jsonSerializerOptions); + + writer.WriteEndObject(); + + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UltimatePartyIdentification ultimatePartyIdentification, JsonSerializerOptions jsonSerializerOptions) + { + + if (ultimatePartyIdentification._AddressOption.IsSet) + { + writer.WritePropertyName("address"); + JsonSerializer.Serialize(writer, ultimatePartyIdentification.Address, jsonSerializerOptions); + } + if (ultimatePartyIdentification._DateOfBirthOption.IsSet) + writer.WriteString("dateOfBirth", ultimatePartyIdentification._DateOfBirthOption.Value!.Value.ToString(DateOfBirthFormat)); + + if (ultimatePartyIdentification._EmailOption.IsSet) + if (ultimatePartyIdentification.Email != null) + writer.WriteString("email", ultimatePartyIdentification.Email); + + if (ultimatePartyIdentification._FirstNameOption.IsSet) + if (ultimatePartyIdentification.FirstName != null) + writer.WriteString("firstName", ultimatePartyIdentification.FirstName); + + if (ultimatePartyIdentification._FullNameOption.IsSet) + if (ultimatePartyIdentification.FullName != null) + writer.WriteString("fullName", ultimatePartyIdentification.FullName); + + if (ultimatePartyIdentification._LastNameOption.IsSet) + if (ultimatePartyIdentification.LastName != null) + writer.WriteString("lastName", ultimatePartyIdentification.LastName); + + if (ultimatePartyIdentification._ReferenceOption.IsSet) + if (ultimatePartyIdentification.Reference != null) + writer.WriteString("reference", ultimatePartyIdentification.Reference); + + if (ultimatePartyIdentification._TypeOption.IsSet && ultimatePartyIdentification.Type != null) + { + string? typeRawValue = UltimatePartyIdentification.TypeEnum.ToJsonValue(ultimatePartyIdentification._TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); + } + + if (ultimatePartyIdentification._UrlOption.IsSet) + if (ultimatePartyIdentification.Url != null) + writer.WriteString("url", ultimatePartyIdentification.Url); + } + } +} diff --git a/Adyen/Transfers/Services/CapitalService.cs b/Adyen/Transfers/Services/CapitalService.cs new file mode 100644 index 000000000..e1b2b3ec0 --- /dev/null +++ b/Adyen/Transfers/Services/CapitalService.cs @@ -0,0 +1,1546 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Transfers.Client; +using Adyen.Transfers.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Transfers.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ICapitalService : IAdyenApiService + { + /// + /// The class containing the events. + /// + CapitalServiceEvents Events { get; } + + /// + /// Get a capital account + /// + /// + /// Returns a list of grants with status and outstanding balances. + /// + /// Thrown when fails to make API call. + /// The counterparty account holder id. + /// . + /// . + /// of . + [Obsolete("Deprecated since Transfers API v4. Use the `/grants` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/get/grants) instead.")] + Task GetCapitalAccountAsync(Option counterpartyAccountHolderId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get grant reference details + /// + /// + /// Returns the details of a capital account specified in the path. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant. + /// . + /// . + /// of . + [Obsolete("Deprecated since Transfers API v4. Use the `/grants/{grantId}` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/get/grants/(grantId)) instead.")] + Task GetGrantReferenceDetailsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Request a grant payout + /// + /// + /// Requests the payout of the selected grant offer. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + [Obsolete("Deprecated since Transfers API v4. Use the `/grants` endpoint from the [Capital API](https://docs.adyen.com/api-explorer/capital/latest/post/grants) instead.")] + Task RequestGrantPayoutAsync(CapitalGrantInfo capitalGrantInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetCapitalAccountApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetGrantReferenceDetailsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IRequestGrantPayoutApiResponse : Adyen.Core.Client.IApiResponse, IOk, IBadRequest, IUnauthorized, IForbidden, INotFound, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class CapitalServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetCapitalAccount; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetCapitalAccount; + + internal void ExecuteOnGetCapitalAccount(CapitalService.GetCapitalAccountApiResponse apiResponse) + { + OnGetCapitalAccount?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCapitalAccount(Exception exception) + { + OnErrorGetCapitalAccount?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetGrantReferenceDetails; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetGrantReferenceDetails; + + internal void ExecuteOnGetGrantReferenceDetails(CapitalService.GetGrantReferenceDetailsApiResponse apiResponse) + { + OnGetGrantReferenceDetails?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetGrantReferenceDetails(Exception exception) + { + OnErrorGetGrantReferenceDetails?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnRequestGrantPayout; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorRequestGrantPayout; + + internal void ExecuteOnRequestGrantPayout(CapitalService.RequestGrantPayoutApiResponse apiResponse) + { + OnRequestGrantPayout?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRequestGrantPayout(Exception exception) + { + OnErrorRequestGrantPayout?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class CapitalService : ICapitalService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public CapitalServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public CapitalService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, CapitalServiceEvents capitalServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = capitalServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get a capital account Returns a list of grants with status and outstanding balances. + /// + /// Thrown when fails to make API call. + /// The counterparty account holder id. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetCapitalAccountAsync(Option counterpartyAccountHolderId = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grants" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grants"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (counterpartyAccountHolderId.IsSet) + parseQueryString["counterpartyAccountHolderId"] = ClientUtils.ParameterToString(counterpartyAccountHolderId.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetCapitalAccountApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grants", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetCapitalAccount(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetCapitalAccount(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetCapitalAccountApiResponse : Adyen.Core.Client.ApiResponse, IGetCapitalAccountApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCapitalAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetCapitalAccountApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.CapitalGrants? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.CapitalGrants? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Transfers.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.Transfers.Models.RestServiceError? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get grant reference details Returns the details of a capital account specified in the path. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the grant. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetGrantReferenceDetailsAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grants/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grants/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetGrantReferenceDetailsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grants/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetGrantReferenceDetails(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetGrantReferenceDetails(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetGrantReferenceDetailsApiResponse : Adyen.Core.Client.ApiResponse, IGetGrantReferenceDetailsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantReferenceDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetGrantReferenceDetailsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.CapitalGrant? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.CapitalGrant? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Transfers.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.Transfers.Models.RestServiceError? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Request a grant payout Requests the payout of the selected grant offer. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task RequestGrantPayoutAsync(CapitalGrantInfo capitalGrantInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/grants" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/grants"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (capitalGrantInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(capitalGrantInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + RequestGrantPayoutApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/grants", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnRequestGrantPayout(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorRequestGrantPayout(exception); + throw; + } + } + + /// + /// The . + /// + public partial class RequestGrantPayoutApiResponse : Adyen.Core.Client.ApiResponse, IRequestGrantPayoutApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestGrantPayoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public RequestGrantPayoutApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.CapitalGrant? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.CapitalGrant? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest. + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest. + /// + /// + public Adyen.Transfers.Models.RestServiceError? BadRequest() + { + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeBadRequestResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = BadRequest(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound. + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound. + /// + /// + public Adyen.Transfers.Models.RestServiceError? NotFound() + { + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeNotFoundResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = NotFound(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Transfers/Services/TransactionsService.cs b/Adyen/Transfers/Services/TransactionsService.cs new file mode 100644 index 000000000..73871a383 --- /dev/null +++ b/Adyen/Transfers/Services/TransactionsService.cs @@ -0,0 +1,912 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Transfers.Client; +using Adyen.Transfers.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Transfers.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransactionsService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransactionsServiceEvents Events { get; } + + /// + /// Get all transactions + /// + /// + /// >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Returns all the transactions related to a balance account, account holder, or balance platform. When making this request, you must include at least one of the following: - `balanceAccountId` - `accountHolderId` - `balancePlatform`. This endpoint supports cursor-based pagination. The response returns the first page of results, and returns links to the next and previous pages when applicable. You can use the links to page through the results. + /// + /// Thrown when fails to make API call. + /// Only include transactions that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// Only include transactions that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. + /// The `cursor` returned in the links of the previous response. + /// Determines the sort order of the returned transactions. The sort order is based on the creation date of the transaction. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. + /// The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. + /// . + /// . + /// of . + Task GetAllTransactionsAsync(DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option paymentInstrumentId = default, Option accountHolderId = default, Option balanceAccountId = default, Option cursor = default, Option sortOrder = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a transaction + /// + /// + /// >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Returns a transaction. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction. + /// . + /// . + /// of . + Task GetTransactionAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IGetAllTransactionsApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTransactionApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransactionsServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransactions; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransactions; + + internal void ExecuteOnGetAllTransactions(TransactionsService.GetAllTransactionsApiResponse apiResponse) + { + OnGetAllTransactions?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransactions(Exception exception) + { + OnErrorGetAllTransactions?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransaction; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransaction; + + internal void ExecuteOnGetTransaction(TransactionsService.GetTransactionApiResponse apiResponse) + { + OnGetTransaction?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransaction(Exception exception) + { + OnErrorGetTransaction?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransactionsService : ITransactionsService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransactionsServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransactionsService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransactionsServiceEvents transactionsServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transactionsServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Get all transactions >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Returns all the transactions related to a balance account, account holder, or balance platform. When making this request, you must include at least one of the following: - `balanceAccountId` - `accountHolderId` - `balancePlatform`. This endpoint supports cursor-based pagination. The response returns the first page of results, and returns links to the next and previous pages when applicable. You can use the links to page through the results. + /// + /// Thrown when fails to make API call. + /// Only include transactions that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// Only include transactions that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. () + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. () + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. () + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. () + /// The `cursor` returned in the links of the previous response. () + /// Determines the sort order of the returned transactions. The sort order is based on the creation date of the transaction. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. () + /// The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransactionsAsync(DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option paymentInstrumentId = default, Option accountHolderId = default, Option balanceAccountId = default, Option cursor = default, Option sortOrder = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactions" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactions"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["createdSince"] = ClientUtils.ParameterToString(createdSince); + parseQueryString["createdUntil"] = ClientUtils.ParameterToString(createdUntil); + + if (balancePlatform.IsSet) + parseQueryString["balancePlatform"] = ClientUtils.ParameterToString(balancePlatform.Value); + + if (paymentInstrumentId.IsSet) + parseQueryString["paymentInstrumentId"] = ClientUtils.ParameterToString(paymentInstrumentId.Value); + + if (accountHolderId.IsSet) + parseQueryString["accountHolderId"] = ClientUtils.ParameterToString(accountHolderId.Value); + + if (balanceAccountId.IsSet) + parseQueryString["balanceAccountId"] = ClientUtils.ParameterToString(balanceAccountId.Value); + + if (cursor.IsSet) + parseQueryString["cursor"] = ClientUtils.ParameterToString(cursor.Value); + + if (sortOrder.IsSet) + parseQueryString["sortOrder"] = ClientUtils.ParameterToString(sortOrder.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransactionsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactions", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransactions(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransactions(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransactionsApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransactionsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransactionsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.TransactionSearchResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransactionSearchResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a transaction >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Returns a transaction. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transaction. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransactionAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transactions/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transactions/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTransactionApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transactions/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransaction(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransaction(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTransactionApiResponse : Adyen.Core.Client.ApiResponse, IGetTransactionApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransactionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransactionApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.Transaction? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.Transaction? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.RestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.RestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.RestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.RestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Transfers/Services/TransfersService.cs b/Adyen/Transfers/Services/TransfersService.cs new file mode 100644 index 000000000..ef76955e8 --- /dev/null +++ b/Adyen/Transfers/Services/TransfersService.cs @@ -0,0 +1,2481 @@ +// +/* + * Transfers API + * + * >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. The Transfers API provides endpoints that you can use to transfer funds, whether when paying out to a transfer instrument for [marketplaces](https://docs.adyen.com/marketplaces/payout-to-users/on-demand-payouts) or [platforms](https://docs.adyen.com/platforms/payout-to-users/on-demand-payouts), [sending funds to third parties](https://docs.adyen.com/platforms/business-accounts/send-receive-funds) for users with business bank accounts, or to [request a payout for a grant offer](https://docs.adyen.com/platforms/capital). The API also supports use cases for [getting transactions for business bank accounts](https://docs.adyen.com/platforms/business-accounts/transactions-api) and getting [outstanding balances](https://docs.adyen.com/platforms/capital#get-balances) for one or more grants on your platform. ## Authentication Each request to the Transfers API must be signed with an API key. Generate an API key in your Customer Area if you have a [platform setup](https://docs.adyen.com/platforms/manage-access/api-credentials-web-service/#generate-api-key) or [marketplace setup](https://docs.adyen.com/marketplaces/manage-access/api-credentials-web-service/#generate-api-key). If you have an Adyen Issuing integration, [generate an API key](https://docs.adyen.com/issuing/manage-access/api-credentials-web-service/#generate-api-key) in your Balance Platform Customer Area. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Roles and permissions To use the Transfers API, you need an additional role for your API credential. Transfers must also be enabled for the source balance account. Your Adyen contact will set up the roles and permissions for you. ## Versioning The Transfers API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/btl/v4/transfers ``` ## Going live When going live, generate an API key in your [live Customer Area](https://ca-live.adyen.com/ca/) if you have an Adyen for Platforms integration or [live Balance Platform Customer Area](https://balanceplatform-live.adyen.com/balanceplatform/) if you have an Adyen Issuing integration. You can then use the API key to send requests to `https://balanceplatform-api-live.adyen.com/btl/v4`. + * + * The version of the OpenAPI document: 4 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Adyen.Core; +using Adyen.Core.Auth; +using Adyen.Core.Client; +using Adyen.Core.Client.Extensions; +using Adyen.Transfers.Client; +using Adyen.Transfers.Models; +using System.Diagnostics.CodeAnalysis; + +namespace Adyen.Transfers.Services +{ + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + public interface ITransfersService : IAdyenApiService + { + /// + /// The class containing the events. + /// + TransfersServiceEvents Events { get; } + + /// + /// Approve initiated transfers + /// + /// + /// Initiates the approval of a list of transfers that triggered an additional [review](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers#request-review). Adyen sends the outcome of the approval request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Approve** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// Header for authenticating through SCA - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task ApproveInitiatedTransfersAsync(ApproveTransfersRequest approveTransfersRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Cancel initiated transfers + /// + /// + /// Initiates the cancellation of a list of transfers that triggered an additional [review](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers#request-review). Adyen sends the outcome of the cancel request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Approve** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task CancelInitiatedTransfersAsync(CancelTransfersRequest cancelTransfersRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get all transfers + /// + /// + /// Returns all the transfers related to a balance account, account holder, or balance platform. When making this request, you must include at least one of the following: - `balanceAccountId` - `accountHolderId` - `balancePlatform`. This endpoint supports cursor-based pagination. The response returns the first page of results, and returns links to the next and previous pages when applicable. You can use the links to page through the results. + /// + /// Thrown when fails to make API call. + /// Only include transfers that have been created on or after this point in time. The value must be in ISO 8601 format and not earlier than 6 months before the `createdUntil` date. For example, **2021-05-30T15:07:40Z**. + /// Only include transfers that have been created on or before this point in time. The value must be in ISO 8601 format and not later than 6 months after the `createdSince` date. For example, **2021-05-30T15:07:40Z**. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. + /// The reference you provided in the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) request + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: Transfer initiated by a Adyen-issued card. - **platformPayment**: Fund movements related to payments that are acquired for your users. + /// Determines the sort order of the returned transfers. The sort order is based on the creation date of the transfers. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. + /// The `cursor` returned in the links of the previous response. + /// The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. + /// . + /// . + /// of . + Task GetAllTransfersAsync(DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option accountHolderId = default, Option balanceAccountId = default, Option paymentInstrumentId = default, Option reference = default, Option category = default, Option sortOrder = default, Option cursor = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a transfer + /// + /// + /// Returns the details of a specified transfer. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the transfer. + /// . + /// . + /// of . + Task GetTransferAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Return a transfer + /// + /// + /// Initiates the return of previously transferred funds without creating a new `transferId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer to be returned. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task ReturnTransferAsync(string transferId, ReturnTransferRequest returnTransferRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Transfer funds + /// + /// + /// >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Starts a request to transfer funds to: - [Balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts) - [Transfer instruments](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) - [Third-party bank accounts](https://docs.adyen.com/payouts/payout-service/pay-out-to-bank-accounts) - [Third-party cards](https://docs.adyen.com/payouts/payout-service/pay-out-to-cards) Adyen sends the outcome of the transfer request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Webservice Initiate** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). - Pass this header parameter using . + /// Header for authenticating through SCA - Pass this header parameter using . + /// + /// . + /// . + /// of . + Task TransferFundsAsync(TransferInfo transferInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default); + + } + + /// + /// The , wraps . + /// + public interface IApproveInitiatedTransfersApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ICancelInitiatedTransfersApiResponse : Adyen.Core.Client.IApiResponse, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetAllTransfersApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IGetTransferApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface IReturnTransferApiResponse : Adyen.Core.Client.IApiResponse, IOk, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 200 Ok. + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// The , wraps . + /// + public interface ITransferFundsApiResponse : Adyen.Core.Client.IApiResponse, IAccepted, IUnauthorized, IForbidden, IUnprocessableContent, IInternalServerError + { + /// + /// Returns true if the response is 202 Accepted. + /// + /// + bool IsAccepted { get; } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + bool IsUnauthorized { get; } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + bool IsUnprocessableContent { get; } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + bool IsInternalServerError { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public class TransfersServiceEvents + { + /// + /// The event raised after the server response. + /// + public event EventHandler? OnApproveInitiatedTransfers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorApproveInitiatedTransfers; + + internal void ExecuteOnApproveInitiatedTransfers(TransfersService.ApproveInitiatedTransfersApiResponse apiResponse) + { + OnApproveInitiatedTransfers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorApproveInitiatedTransfers(Exception exception) + { + OnErrorApproveInitiatedTransfers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnCancelInitiatedTransfers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorCancelInitiatedTransfers; + + internal void ExecuteOnCancelInitiatedTransfers(TransfersService.CancelInitiatedTransfersApiResponse apiResponse) + { + OnCancelInitiatedTransfers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCancelInitiatedTransfers(Exception exception) + { + OnErrorCancelInitiatedTransfers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetAllTransfers; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetAllTransfers; + + internal void ExecuteOnGetAllTransfers(TransfersService.GetAllTransfersApiResponse apiResponse) + { + OnGetAllTransfers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetAllTransfers(Exception exception) + { + OnErrorGetAllTransfers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnGetTransfer; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorGetTransfer; + + internal void ExecuteOnGetTransfer(TransfersService.GetTransferApiResponse apiResponse) + { + OnGetTransfer?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTransfer(Exception exception) + { + OnErrorGetTransfer?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnReturnTransfer; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorReturnTransfer; + + internal void ExecuteOnReturnTransfer(TransfersService.ReturnTransferApiResponse apiResponse) + { + OnReturnTransfer?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorReturnTransfer(Exception exception) + { + OnErrorReturnTransfer?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response. + /// + public event EventHandler? OnTransferFunds; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler? OnErrorTransferFunds; + + internal void ExecuteOnTransferFunds(TransfersService.TransferFundsApiResponse apiResponse) + { + OnTransferFunds?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTransferFunds(Exception exception) + { + OnErrorTransferFunds?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + public sealed partial class TransfersService : ITransfersService + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public TransfersServiceEvents Events { get; } + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + public TransfersService(ILogger logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TransfersServiceEvents transfersServiceEvents, + ITokenProvider apiKeyProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger() : logger; + HttpClient = httpClient; + Events = transfersServiceEvents; + ApiKeyProvider = apiKeyProvider; + } + + /// + /// Approve initiated transfers Initiates the approval of a list of transfers that triggered an additional [review](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers#request-review). Adyen sends the outcome of the approval request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Approve** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// Header for authenticating through SCA () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ApproveInitiatedTransfersAsync(ApproveTransfersRequest approveTransfersRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers/approve" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers/approve"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (approveTransfersRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(approveTransfersRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ApproveInitiatedTransfersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers/approve", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnApproveInitiatedTransfers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorApproveInitiatedTransfers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ApproveInitiatedTransfersApiResponse : Adyen.Core.Client.ApiResponse, IApproveInitiatedTransfersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApproveInitiatedTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApproveInitiatedTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Cancel initiated transfers Initiates the cancellation of a list of transfers that triggered an additional [review](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers#request-review). Adyen sends the outcome of the cancel request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Approve** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task CancelInitiatedTransfersAsync(CancelTransfersRequest cancelTransfersRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers/cancel" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers/cancel"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (cancelTransfersRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(cancelTransfersRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + CancelInitiatedTransfersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers/cancel", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnCancelInitiatedTransfers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorCancelInitiatedTransfers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class CancelInitiatedTransfersApiResponse : Adyen.Core.Client.ApiResponse, ICancelInitiatedTransfersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelInitiatedTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public CancelInitiatedTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get all transfers Returns all the transfers related to a balance account, account holder, or balance platform. When making this request, you must include at least one of the following: - `balanceAccountId` - `accountHolderId` - `balancePlatform`. This endpoint supports cursor-based pagination. The response returns the first page of results, and returns links to the next and previous pages when applicable. You can use the links to page through the results. + /// + /// Thrown when fails to make API call. + /// Only include transfers that have been created on or after this point in time. The value must be in ISO 8601 format and not earlier than 6 months before the `createdUntil` date. For example, **2021-05-30T15:07:40Z**. + /// Only include transfers that have been created on or before this point in time. The value must be in ISO 8601 format and not later than 6 months after the `createdSince` date. For example, **2021-05-30T15:07:40Z**. + /// The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. () + /// The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. () + /// The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. () + /// The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. () + /// The reference you provided in the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) request () + /// The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: Transfer initiated by a Adyen-issued card. - **platformPayment**: Fund movements related to payments that are acquired for your users. () + /// Determines the sort order of the returned transfers. The sort order is based on the creation date of the transfers. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. () + /// The `cursor` returned in the links of the previous response. () + /// The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetAllTransfersAsync(DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option accountHolderId = default, Option balanceAccountId = default, Option paymentInstrumentId = default, Option reference = default, Option category = default, Option sortOrder = default, Option cursor = default, Option limit = default, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + parseQueryString["createdSince"] = ClientUtils.ParameterToString(createdSince); + parseQueryString["createdUntil"] = ClientUtils.ParameterToString(createdUntil); + + if (balancePlatform.IsSet) + parseQueryString["balancePlatform"] = ClientUtils.ParameterToString(balancePlatform.Value); + + if (accountHolderId.IsSet) + parseQueryString["accountHolderId"] = ClientUtils.ParameterToString(accountHolderId.Value); + + if (balanceAccountId.IsSet) + parseQueryString["balanceAccountId"] = ClientUtils.ParameterToString(balanceAccountId.Value); + + if (paymentInstrumentId.IsSet) + parseQueryString["paymentInstrumentId"] = ClientUtils.ParameterToString(paymentInstrumentId.Value); + + if (reference.IsSet) + parseQueryString["reference"] = ClientUtils.ParameterToString(reference.Value); + + if (category.IsSet) + parseQueryString["category"] = ClientUtils.ParameterToString(category.Value); + + if (sortOrder.IsSet) + parseQueryString["sortOrder"] = ClientUtils.ParameterToString(sortOrder.Value); + + if (cursor.IsSet) + parseQueryString["cursor"] = ClientUtils.ParameterToString(cursor.Value); + + if (limit.IsSet) + parseQueryString["limit"] = ClientUtils.ParameterToString(limit.Value); + + uriBuilder.Query = parseQueryString.ToString(); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetAllTransfersApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetAllTransfers(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetAllTransfers(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetAllTransfersApiResponse : Adyen.Core.Client.ApiResponse, IGetAllTransfersApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetAllTransfersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.FindTransfersResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.FindTransfersResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Get a transfer Returns the details of a specified transfer. + /// + /// Thrown when fails to make API call. + /// Unique identifier of the transfer. + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task GetTransferAsync(string id, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers/{id}"); + uriBuilder.Path = uriBuilder.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Get; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + GetTransferApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers/{id}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnGetTransfer(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorGetTransfer(exception); + throw; + } + } + + /// + /// The . + /// + public partial class GetTransferApiResponse : Adyen.Core.Client.ApiResponse, IGetTransferApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public GetTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.TransferData? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferData? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Return a transfer Initiates the return of previously transferred funds without creating a new `transferId`. + /// + /// Thrown when fails to make API call. + /// The unique identifier of the transfer to be returned. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task ReturnTransferAsync(string transferId, ReturnTransferRequest returnTransferRequest, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers/{transferId}/returns" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers/{transferId}/returns"); + uriBuilder.Path = uriBuilder.Path.Replace("%7BtransferId%7D", Uri.EscapeDataString(transferId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (returnTransferRequest as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(returnTransferRequest, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + ReturnTransferApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers/{transferId}/returns", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnReturnTransfer(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorReturnTransfer(exception); + throw; + } + } + + /// + /// The . + /// + public partial class ReturnTransferApiResponse : Adyen.Core.Client.ApiResponse, IReturnTransferApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReturnTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ReturnTransferApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok. + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok. + /// + /// + public Adyen.Transfers.Models.ReturnTransferResponse? Ok() + { + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeOkResponse([NotNullWhen(true)]out Adyen.Transfers.Models.ReturnTransferResponse? result) + { + result = null; + + try + { + result = Ok(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + /// + /// Transfer funds >Versions 1 and 2 of the Transfers API are deprecated. If you are just starting your implementation, use the latest version. Starts a request to transfer funds to: - [Balance accounts](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts) - [Transfer instruments](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments) - [Third-party bank accounts](https://docs.adyen.com/payouts/payout-service/pay-out-to-bank-accounts) - [Third-party cards](https://docs.adyen.com/payouts/payout-service/pay-out-to-cards) Adyen sends the outcome of the transfer request through webhooks. To use this endpoint: - Your API credential must have the **TransferService Webservice Initiate** [role](https://docs.adyen.com/platforms/manage-access/webservice-roles/?tab=transfers_3). - The account holder must have the required [capabilities](https://docs.adyen.com/platforms/verification-overview/capabilities). Reach out to your Adyen contact to set up these permissions. + /// + /// Thrown when fails to make API call. + /// A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). () Pass this header parameter in . + /// Header for authenticating through SCA () Pass this header parameter in . + /// () + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task TransferFundsAsync(TransferInfo transferInfo, RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + uriBuilder.Host = HttpClient.BaseAddress!.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/transfers" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "/transfers"); + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + httpRequestMessage.Content = (transferInfo as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(transferInfo, _jsonSerializerOptions)); + + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + httpRequestMessage.RequestUri = uriBuilder.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string? contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + string[] accepts = new string[] { + "application/json" + }; + + string? accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + + httpRequestMessage.Method = HttpMethod.Post; + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLogger = LoggerFactory.CreateLogger(); + TransferFundsApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponse = new(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "/transfers", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOnTransferFunds(apiResponse); + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnErrorTransferFunds(exception); + throw; + } + } + + /// + /// The . + /// + public partial class TransferFundsApiResponse : Adyen.Core.Client.ApiResponse, ITransferFundsApiResponse + { + /// + /// The logger for . + /// + public ILogger Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TransferFundsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public TransferFundsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 202 Accepted. + /// + /// + public bool IsAccepted => 202 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 202 Accepted. + /// + /// + public Adyen.Transfers.Models.Transfer? Accepted() + { + return IsAccepted + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 202 Accepted and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeAcceptedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.Transfer? result) + { + result = null; + + try + { + result = Accepted(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)202); + } + + return result != null; + } + + /// + /// Returns true if the response is 401 Unauthorized. + /// + /// + public bool IsUnauthorized => 401 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 401 Unauthorized. + /// + /// + public Adyen.Transfers.Models.ServiceError? Unauthorized() + { + return IsUnauthorized + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 401 Unauthorized and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnauthorizedResponse([NotNullWhen(true)]out Adyen.Transfers.Models.ServiceError? result) + { + result = null; + + try + { + result = Unauthorized(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)401); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden. + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? Forbidden() + { + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeForbiddenResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = Forbidden(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent. + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? UnprocessableContent() + { + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeUnprocessableContentResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)422); + } + + return result != null; + } + + /// + /// Returns true if the response is 500 InternalServerError. + /// + /// + public bool IsInternalServerError => 500 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 500 InternalServerError. + /// + /// + public Adyen.Transfers.Models.TransferServiceRestServiceError? InternalServerError() + { + return IsInternalServerError + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 500 InternalServerError and the deserialized response is not null. + /// + /// + /// + public bool TryDeserializeInternalServerErrorResponse([NotNullWhen(true)]out Adyen.Transfers.Models.TransferServiceRestServiceError? result) + { + result = null; + + try + { + result = InternalServerError(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode)500); + } + + return result != null; + } + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + } +} diff --git a/Adyen/Util/ByteArrayConverter.cs b/Adyen/Util/ByteArrayConverter.cs deleted file mode 100644 index e10849389..000000000 --- a/Adyen/Util/ByteArrayConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Text; -using Newtonsoft.Json; - -namespace Adyen.Util -{ - internal class ByteArrayConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return objectType == typeof(byte[]); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) - return null; - return Encoding.UTF8.GetBytes((string)reader.Value); - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - byte[] bytes = (byte[])value; - writer.WriteValue(Encoding.UTF8.GetString(bytes)); - } - - } -} \ No newline at end of file diff --git a/Adyen/Util/JsonOperation.cs b/Adyen/Util/JsonOperation.cs deleted file mode 100644 index cfee35d6f..000000000 --- a/Adyen/Util/JsonOperation.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Newtonsoft.Json; - -namespace Adyen.Util -{ - public class JsonOperation - { - /// - /// Deserialize to an object T - /// - /// - /// - /// - public static T Deserialize(string response) - { - var jsonSettings = new JsonSerializerSettings(); - jsonSettings.Converters.Add(new ByteArrayConverter()); - - return JsonConvert.DeserializeObject(response, jsonSettings); - } - - public static string SerializeRequest(object request) - { - var jsonSettings = new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Include, - }; - jsonSettings.Converters.Add(new ByteArrayConverter()); - return JsonConvert.SerializeObject(request, Formatting.None, jsonSettings); - } - } -} diff --git a/Adyen/Util/Util.cs b/Adyen/Util/Util.cs deleted file mode 100644 index 710fd1a85..000000000 --- a/Adyen/Util/Util.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace Adyen.Util -{ - public class Util - { - public static string CalculateSessionValidity() - { - //+1day - var dateTime=DateTime.Now.AddDays(1); - return String.Format("{0:s}", dateTime); - - } - } -} diff --git a/Adyen/Webhooks/BalancePlatformWebhookHandler.cs b/Adyen/Webhooks/BalancePlatformWebhookHandler.cs deleted file mode 100644 index 1e4a72b4e..000000000 --- a/Adyen/Webhooks/BalancePlatformWebhookHandler.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using Adyen.Model.AcsWebhooks; -using Adyen.Model.ReportWebhooks; -using Adyen.Model.ConfigurationWebhooks; -using Adyen.Model.NegativeBalanceWarningWebhooks; -using Adyen.Model.TransactionWebhooks; -using Adyen.Model.TransferWebhooks; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Adyen.Webhooks -{ - public class BalancePlatformWebhookHandler - { - /// - /// Deserializes to a generic banking webhook from the . Use this either to catch the - /// webhook type if unknown or if the explicit type is not required. - /// - /// The json payload of the webhook. - /// The parsed webhook packaged in a dynamic object. - /// Throws when json is invalid. - public dynamic GetGenericBalancePlatformWebhook(string jsonPayload) - { - if (GetAuthenticationNotificationRequest(jsonPayload, out AuthenticationNotificationRequest authenticationNotificationRequest)) - { - return authenticationNotificationRequest; - } - - if (GetAccountHolderNotificationRequest(jsonPayload, out AccountHolderNotificationRequest accountHolderNotificationRequest)) - { - return accountHolderNotificationRequest; - } - - if (GetBalanceAccountNotificationRequest(jsonPayload, out BalanceAccountNotificationRequest balanceAccountNotificationRequest)) - { - return balanceAccountNotificationRequest; - } - - if (GetCardOrderNotificationRequest(jsonPayload, out CardOrderNotificationRequest cardOrderNotificationRequest)) - { - return cardOrderNotificationRequest; - } - - if (GetNegativeBalanceCompensationWarningNotificationRequest(jsonPayload, out NegativeBalanceCompensationWarningNotificationRequest negativeBalanceCompensationWarningNotificationRequest)) - { - return negativeBalanceCompensationWarningNotificationRequest; - } - - if (GetPaymentNotificationRequest(jsonPayload, out PaymentNotificationRequest paymentNotificationRequest)) - { - return paymentNotificationRequest; - } - - if (GetSweepConfigurationNotificationRequest(jsonPayload, out SweepConfigurationNotificationRequest sweepConfigurationNotificationRequest)) - { - return sweepConfigurationNotificationRequest; - } - - if (GetReportNotificationRequest(jsonPayload, out ReportNotificationRequest reportNotificationRequest)) - { - return reportNotificationRequest; - } - if (GetTransferNotificationRequest(jsonPayload, out TransferNotificationRequest transferNotificationRequest)) - { - return transferNotificationRequest; - } - if (GetTransactionNotificationRequestV4(jsonPayload, out TransactionNotificationRequestV4 transactionNotificationRequestV4)) - { - return transactionNotificationRequestV4; - } - throw new JsonReaderException("Could not parse webhook"); - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetAuthenticationNotificationRequest(string jsonPayload, out AuthenticationNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetAccountHolderNotificationRequest(string jsonPayload, out AccountHolderNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetBalanceAccountNotificationRequest(string jsonPayload, out BalanceAccountNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetCardOrderNotificationRequest(string jsonPayload, out CardOrderNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetPaymentNotificationRequest(string jsonPayload, out PaymentNotificationRequest result) // This class-name is confusing as it's referring to a paymentInstrument -> Rename to PaymentInstrumentNotificationRequest? - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetSweepConfigurationNotificationRequest(string jsonPayload, out SweepConfigurationNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook.> - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetReportNotificationRequest(string jsonPayload, out ReportNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetTransferNotificationRequest(string jsonPayload, out TransferNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetTransactionNotificationRequestV4(string jsonPayload, out TransactionNotificationRequestV4 result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetNegativeBalanceCompensationWarningNotificationRequest(string jsonPayload, out NegativeBalanceCompensationWarningNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Check if the JSON pyload contains TypeEnum value. - /// - /// The string JSON payload. - /// The TypeEnum of the class. - /// True if the enum is present. - private static bool ContainsValue(string jsonPayload) where T : struct, IConvertible - { - // Retrieve type from payload - JToken typeToken = JObject.Parse(jsonPayload).GetValue("type"); - string type = typeToken?.Value(); - List memberInfos = typeof(T).GetTypeInfo().DeclaredMembers.ToList(); - return memberInfos.Any(memberInfo => memberInfo?.GetCustomAttribute()?.Value == type); - } - } -} \ No newline at end of file diff --git a/Adyen/Util/HMACValidator.cs b/Adyen/Webhooks/HmacValidator.cs similarity index 69% rename from Adyen/Util/HMACValidator.cs rename to Adyen/Webhooks/HmacValidator.cs index b3da7fc34..9a1ef71c4 100644 --- a/Adyen/Util/HMACValidator.cs +++ b/Adyen/Webhooks/HmacValidator.cs @@ -1,123 +1,97 @@ -using System; -using System.Collections.Generic; -using System.Security.Cryptography; -using System.Text; -using Adyen.Model.Notification; - -namespace Adyen.Util -{ - public class HmacValidator - { - private const string HmacSignature = "hmacSignature"; - - // Computes the Base64 encoded signature using the HMAC algorithm with the HMACSHA256 hashing function. - public string CalculateHmac(string payload, string hmacKey) - { - byte[] key = PackH(hmacKey); - byte[] data = Encoding.UTF8.GetBytes(payload); - - try - { - using (HMACSHA256 hmac = new HMACSHA256(key)) - { - // Compute the hmac on input data bytes - byte[] rawHmac = hmac.ComputeHash(data); - - // Base64-encode the hmac - return Convert.ToBase64String(rawHmac); - } - } - catch (Exception e) - { - throw new Exception("Failed to generate HMAC : " + e.Message); - } - } - - public string CalculateHmac(NotificationRequestItem notificationRequestItem, string hmacKey) - { - var notificationRequestItemData = GetDataToSign(notificationRequestItem); - return CalculateHmac(notificationRequestItemData, hmacKey); - } - - private byte[] PackH(string hex) - { - if ((hex.Length % 2) == 1) - { - hex += '0'; - } - - byte[] bytes = new byte[hex.Length / 2]; - for (int i = 0; i < hex.Length; i += 2) - { - bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); - } - - return bytes; - } - - public string GetDataToSign(NotificationRequestItem notificationRequestItem) - { - var amount = notificationRequestItem.Amount; - var signedDataList = new List - { - notificationRequestItem.PspReference, - notificationRequestItem.OriginalReference, - notificationRequestItem.MerchantAccountCode, - notificationRequestItem.MerchantReference, - Convert.ToString(amount.Value), - amount.Currency, - notificationRequestItem.EventCode, - notificationRequestItem.Success.ToString().ToLower() - }; - return String.Join(":", signedDataList); - } - - /// - /// Validates a regular webhook with the given . - /// - /// . - /// The HMAC key, retrieved from the Adyen Customer Area. - /// A return value indicates the HMAC validation succeeded. - public bool IsValidHmac(NotificationRequestItem notificationRequestItem, string hmacKey) - { - if (notificationRequestItem.AdditionalData == null) - { - return false; - } - - if (!notificationRequestItem.AdditionalData.ContainsKey(HmacSignature)) - { - return false; - } - var expectedSign = CalculateHmac(notificationRequestItem, hmacKey); - var merchantSign = notificationRequestItem.AdditionalData[HmacSignature]; - return string.Equals(expectedSign, merchantSign); - } - - - /// - /// Validates a balance platform and management webhook payload with the given and . - /// - /// The HMAC signature, retrieved from the request header. - /// The HMAC key, retrieved from the Adyen Customer Area. - /// The webhook payload. - /// A return value indicates the HMAC validation succeeded. - public bool IsValidWebhook(string hmacSignature, string hmacKey, string payload) - { - var calculatedSign = CalculateHmac(payload, hmacKey); - return TimeSafeEquals(Encoding.UTF8.GetBytes(hmacSignature), Encoding.UTF8.GetBytes(calculatedSign)); - } - - /// - /// This method compares two bytestrings in constant time based on length of shortest bytestring to prevent timing attacks. - /// - /// True if different. - private static bool TimeSafeEquals(byte[] a, byte[] b) - { - uint diff = (uint)a.Length ^ (uint)b.Length; - for (int i = 0; i < a.Length && i < b.Length; i++) { diff |= (uint)(a[i] ^ b[i]); } - return diff == 0; - } - } -} - +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using System.Text; +using Adyen.Webhooks.Models; + +namespace Adyen.Util +{ + public class HmacValidator + { + private const string HmacSignature = "hmacSignature"; + + // Computes the Base64 encoded signature using the HMAC algorithm with the HMACSHA256 hashing function. + public string CalculateHmac(string payload, string hmacKey) + { + byte[] key = PackH(hmacKey); + byte[] data = Encoding.UTF8.GetBytes(payload); + + try + { + using (HMACSHA256 hmac = new HMACSHA256(key)) + { + // Compute the hmac on input data bytes + byte[] rawHmac = hmac.ComputeHash(data); + + // Base64-encode the hmac + return Convert.ToBase64String(rawHmac); + } + } + catch (Exception e) + { + throw new Exception("Failed to generate HMAC : " + e.Message); + } + } + + public string CalculateHmac(NotificationRequestItem notificationRequestItem, string hmacKey) + { + var notificationRequestItemData = GetDataToSign(notificationRequestItem); + return CalculateHmac(notificationRequestItemData, hmacKey); + } + + private byte[] PackH(string hex) + { + if ((hex.Length % 2) == 1) + { + hex += '0'; + } + + byte[] bytes = new byte[hex.Length / 2]; + for (int i = 0; i < hex.Length; i += 2) + { + bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); + } + + return bytes; + } + + public string GetDataToSign(NotificationRequestItem notificationRequestItem) + { + var amount = notificationRequestItem.Amount; + var signedDataList = new List + { + notificationRequestItem.PspReference, + notificationRequestItem.OriginalReference, + notificationRequestItem.MerchantAccountCode, + notificationRequestItem.MerchantReference, + Convert.ToString(amount.Value), + amount.Currency, + notificationRequestItem.EventCode, + notificationRequestItem.Success.ToString().ToLower() + }; + return String.Join(":", signedDataList); + } + + /// + /// Validates a regular webhook with the given . + /// + /// . + /// The HMAC key, retrieved from the Adyen Customer Area. + /// A return value indicates the HMAC validation succeeded. + public bool IsValidHmac(NotificationRequestItem notificationRequestItem, string hmacKey) + { + if (notificationRequestItem.AdditionalData == null) + { + return false; + } + + if (!notificationRequestItem.AdditionalData.ContainsKey(HmacSignature)) + { + return false; + } + var expectedSign = CalculateHmac(notificationRequestItem, hmacKey); + var merchantSign = notificationRequestItem.AdditionalData[HmacSignature]; + return string.Equals(expectedSign, merchantSign); + } + } +} diff --git a/Adyen/Webhooks/ManagementWebhookHandler.cs b/Adyen/Webhooks/ManagementWebhookHandler.cs deleted file mode 100644 index fbc8b1ee8..000000000 --- a/Adyen/Webhooks/ManagementWebhookHandler.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; -using Adyen.Model.ManagementWebhooks; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Adyen.Webhooks -{ - public class ManagementWebhookHandler - { - /// - /// Deserializes to a generic management webhook from the . Use this either to catch the - /// webhook type if unknown or if the explicit type is not required. - /// - /// The json payload of the webhook. - /// The parsed webhook packaged in a dynamic object. - /// Throws when json is invalid. - public dynamic GetGenericManagementWebhook(string jsonPayload) - { - if (GetMerchantCreatedNotificationRequest(jsonPayload, out var merchantCreatedNotificationRequest)) - { - return merchantCreatedNotificationRequest; - } - - if (GetMerchantUpdatedNotificationRequest(jsonPayload, out var merchantUpdatedNotificationRequest)) - { - return merchantUpdatedNotificationRequest; - } - - if (GetPaymentMethodCreatedNotificationRequest(jsonPayload, out var paymentMethodCreatedNotificationRequest)) - { - return paymentMethodCreatedNotificationRequest; - } - - if (GetPaymentMethodRequestRemovedNotificationRequest(jsonPayload, out var PaymentMethodRequestRemovedNotificationRequest)) - { - return PaymentMethodRequestRemovedNotificationRequest; - } - - if (GetPaymentMethodScheduledForRemovalNotificationRequest(jsonPayload, out var PaymentMethodScheduledForRemovalNotificationRequest)) - { - return PaymentMethodScheduledForRemovalNotificationRequest; - } - - throw new JsonReaderException("Could not parse webhook"); - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetMerchantCreatedNotificationRequest(string jsonPayload, out MerchantCreatedNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetMerchantUpdatedNotificationRequest(string jsonPayload, out MerchantUpdatedNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetPaymentMethodCreatedNotificationRequest(string jsonPayload, out PaymentMethodCreatedNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetPaymentMethodRequestRemovedNotificationRequest(string jsonPayload, out PaymentMethodRequestRemovedNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - /// - /// Deserializes from the . - /// - /// The json payload of the webhook. - /// . - /// A return value indicates whether the deserialization succeeded. - /// Throws when json is invalid. - public bool GetPaymentMethodScheduledForRemovalNotificationRequest(string jsonPayload, out PaymentMethodScheduledForRemovalNotificationRequest result) - { - result = null; - if (!ContainsValue(jsonPayload)) return false; - result = JsonConvert.DeserializeObject(jsonPayload); - return true; - } - - // Check if the contains TypeEnum value - private static bool ContainsValue(string jsonPayload) where T : struct, IConvertible - { - // Retrieve type from payload - JToken typeToken = JObject.Parse(jsonPayload).GetValue("type"); - string type = typeToken?.Value(); - - // Search for type in .TypeEnum - List list = new List(); - var members = typeof(T) - .GetTypeInfo() - .DeclaredMembers; - foreach (var member in members) - { - var val = member?.GetCustomAttribute(false)?.Value; - if (!string.IsNullOrEmpty(val)) - list.Add(val); - } - - return list.Contains(type); - } - } -} \ No newline at end of file diff --git a/Adyen/Webhooks/Models/Amount.cs b/Adyen/Webhooks/Models/Amount.cs new file mode 100644 index 000000000..05fcc574a --- /dev/null +++ b/Adyen/Webhooks/Models/Amount.cs @@ -0,0 +1,29 @@ +namespace Adyen.Webhooks.Models +{ + /// + /// The Amount, used for webhooks + /// + public class Amount + { + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// + public string Currency { get; set; } + + /// + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + /// + public long? Value { get; set; } + + /// + /// Initializes a new instance of the class for webhooks. + /// + /// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes#currency-codes). + /// The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes#minor-units). + public Amount(string currency = default(string), long? value = default(long?)) + { + this.Currency = currency; + this.Value = value; + } + } +} \ No newline at end of file diff --git a/Adyen/Model/Notification/NotificationRequest.cs b/Adyen/Webhooks/Models/NotificationRequest.cs similarity index 84% rename from Adyen/Model/Notification/NotificationRequest.cs rename to Adyen/Webhooks/Models/NotificationRequest.cs index 038da3cba..64b6c0b32 100644 --- a/Adyen/Model/Notification/NotificationRequest.cs +++ b/Adyen/Webhooks/Models/NotificationRequest.cs @@ -1,61 +1,61 @@ -#region License -// /* -// * ###### -// * ###### -// * ############ ####( ###### #####. ###### ############ ############ -// * ############# #####( ###### #####. ###### ############# ############# -// * ###### #####( ###### #####. ###### ##### ###### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ###### -// * ############# ############# ############# ############# ##### ###### -// * ############ ############ ############# ############ ##### ###### -// * ###### -// * ############# -// * ############ -// * -// * Adyen Dotnet API Library -// * -// * Copyright (c) 2020 Adyen B.V. -// * This file is open source and available under the MIT license. -// * See the LICENSE file for more info. -// */ -#endregion - -using Newtonsoft.Json; -using System.Collections.Generic; -using System.Text; - -namespace Adyen.Model.Notification -{ - public class NotificationRequest - { - public string Live { get; set; } - - [JsonProperty("NotificationItems")] - public List NotificationItemContainers { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class NotificationRequest {\n"); - sb.Append(" Live: ").Append(this.Live).Append("\n"); - sb.Append(" NotificationItemContainers: ").Append(NotificationItemContainers).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - } -} +#region License +// /* +// * ###### +// * ###### +// * ############ ####( ###### #####. ###### ############ ############ +// * ############# #####( ###### #####. ###### ############# ############# +// * ###### #####( ###### #####. ###### ##### ###### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ###### +// * ############# ############# ############# ############# ##### ###### +// * ############ ############ ############# ############ ##### ###### +// * ###### +// * ############# +// * ############ +// * +// * Adyen Dotnet API Library +// * +// * Copyright (c) 2020 Adyen B.V. +// * This file is open source and available under the MIT license. +// * See the LICENSE file for more info. +// */ +#endregion + +using Newtonsoft.Json; +using System.Collections.Generic; +using System.Text; + +namespace Adyen.Webhooks.Models +{ + public class NotificationRequest + { + public string Live { get; set; } + + [JsonProperty("NotificationItems")] + public List NotificationItemContainers { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// String presentation of the object. + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class NotificationRequest {\n"); + sb.Append(" Live: ").Append(this.Live).Append("\n"); + sb.Append(" NotificationItemContainers: ").Append(NotificationItemContainers).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + + /// + /// Returns the JSON string presentation of the object. + /// + /// JSON string presentation of the object. + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + } +} diff --git a/Adyen/Model/Notification/NotificationRequestConst.cs b/Adyen/Webhooks/Models/NotificationRequestConstants.cs similarity index 96% rename from Adyen/Model/Notification/NotificationRequestConst.cs rename to Adyen/Webhooks/Models/NotificationRequestConstants.cs index bcbe9af48..796c14dd9 100644 --- a/Adyen/Model/Notification/NotificationRequestConst.cs +++ b/Adyen/Webhooks/Models/NotificationRequestConstants.cs @@ -1,68 +1,68 @@ -#region License -// /* -// * ###### -// * ###### -// * ############ ####( ###### #####. ###### ############ ############ -// * ############# #####( ###### #####. ###### ############# ############# -// * ###### #####( ###### #####. ###### ##### ###### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ###### -// * ############# ############# ############# ############# ##### ###### -// * ############ ############ ############# ############ ##### ###### -// * ###### -// * ############# -// * ############ -// * -// * Adyen Dotnet API Library -// * -// * Copyright (c) 2020 Adyen B.V. -// * This file is open source and available under the MIT license. -// * See the LICENSE file for more info. -// */ -#endregion - -namespace Adyen.Model.Notification -{ - public class NotificationRequestConst - { - //Event codes - public const string EventCodeAuthorisation = "AUTHORISATION"; - public const string EventCodeAuthorisationAdjustment = "AUTHORISATION_ADJUSTMENT"; - public const string EventCodeCancellation = "CANCELLATION"; - public const string EventCodeCancelOrRefund = "CANCEL_OR_REFUND"; - public const string EventCodeCapture = "CAPTURE"; - public const string EventCodeCaptureFailed = "CAPTURE_FAILED"; - public const string EventCodeChargeback = "CHARGEBACK"; - public const string EventCodeChargebackReversed = "CHARGEBACK_REVERSED"; - public const string EventCodeHandledExternally = "HANDLED_EXTERNALLY"; - public const string EventCodeManualReviewAccept = "MANUAL_REVIEW_ACCEPT"; - public const string EventCodeManualReviewReject = "MANUAL_REVIEW_REJECT"; - public const string EventCodeNotificationOfChargeback = "NOTIFICATION_OF_CHARGEBACK"; - public const string EventCodeNotificationOfFraud = "NOTIFICATION_OF_FRAUD"; - public const string EventCodeOfferClosed = "OFFER_CLOSED"; - public const string EventCodeOrderClosed = "ORDER_CLOSED"; - public const string EventCodeOrderOpened = "ORDER_OPENED"; - public const string EventCodePaidoutReversed = "PAIDOUT_REVERSED"; - public const string EventCodePayoutDecline = "PAYOUT_DECLINE"; - public const string EventCodePayoutExpire = "PAYOUT_EXPIRE"; - public const string EventCodePayoutThirdparty = "PAYOUT_THIRDPARTY"; - public const string EventCodePending = "PENDING"; - public const string EventCodePostponedRefund = "POSTPONED_REFUND"; - public const string EventCodePrearbitrationLost = "PREARBITRATION_LOST"; - public const string EventCodePrearbitrationWon = "PREARBITRATION_WON"; - public const string EventCodeProcessRetry = "PROCESS_RETRY"; - public const string EventCodeRecurringContract = "RECURRING_CONTRACT"; - public const string EventCodeRefund = "REFUND"; - public const string EventCodeRefundedReversed = "REFUNDED_REVERSED"; - public const string EventCodeRefundFailed = "REFUND_FAILED"; - public const string EventCodeRefundWithData = "REFUND_WITH_DATA"; - public const string EventCodeReportAvailable = "REPORT_AVAILABLE"; - public const string EventCodeRequestForInformation = "REQUEST_FOR_INFORMATION"; - public const string EventCodeSecondChargeback = "SECOND_CHARGEBACK"; - public const string EventCodeVoidPendingRefund = "VOID_PENDING_REFUND"; - - //Additional Data - public const string AdditionalDataTotalFraudScore = "totalFraudScore"; - public const string AdditionalDataFraudCheckPattern = "fraudCheck-(\\d+)-([A-Za-z0-9]+)"; - } +#region License +// /* +// * ###### +// * ###### +// * ############ ####( ###### #####. ###### ############ ############ +// * ############# #####( ###### #####. ###### ############# ############# +// * ###### #####( ###### #####. ###### ##### ###### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ###### +// * ############# ############# ############# ############# ##### ###### +// * ############ ############ ############# ############ ##### ###### +// * ###### +// * ############# +// * ############ +// * +// * Adyen Dotnet API Library +// * +// * Copyright (c) 2020 Adyen B.V. +// * This file is open source and available under the MIT license. +// * See the LICENSE file for more info. +// */ +#endregion + +namespace Adyen.Webhooks.Models +{ + public class NotificationRequestConstants + { + //Event codes + public const string EventCodeAuthorisation = "AUTHORISATION"; + public const string EventCodeAuthorisationAdjustment = "AUTHORISATION_ADJUSTMENT"; + public const string EventCodeCancellation = "CANCELLATION"; + public const string EventCodeCancelOrRefund = "CANCEL_OR_REFUND"; + public const string EventCodeCapture = "CAPTURE"; + public const string EventCodeCaptureFailed = "CAPTURE_FAILED"; + public const string EventCodeChargeback = "CHARGEBACK"; + public const string EventCodeChargebackReversed = "CHARGEBACK_REVERSED"; + public const string EventCodeHandledExternally = "HANDLED_EXTERNALLY"; + public const string EventCodeManualReviewAccept = "MANUAL_REVIEW_ACCEPT"; + public const string EventCodeManualReviewReject = "MANUAL_REVIEW_REJECT"; + public const string EventCodeNotificationOfChargeback = "NOTIFICATION_OF_CHARGEBACK"; + public const string EventCodeNotificationOfFraud = "NOTIFICATION_OF_FRAUD"; + public const string EventCodeOfferClosed = "OFFER_CLOSED"; + public const string EventCodeOrderClosed = "ORDER_CLOSED"; + public const string EventCodeOrderOpened = "ORDER_OPENED"; + public const string EventCodePaidoutReversed = "PAIDOUT_REVERSED"; + public const string EventCodePayoutDecline = "PAYOUT_DECLINE"; + public const string EventCodePayoutExpire = "PAYOUT_EXPIRE"; + public const string EventCodePayoutThirdparty = "PAYOUT_THIRDPARTY"; + public const string EventCodePending = "PENDING"; + public const string EventCodePostponedRefund = "POSTPONED_REFUND"; + public const string EventCodePrearbitrationLost = "PREARBITRATION_LOST"; + public const string EventCodePrearbitrationWon = "PREARBITRATION_WON"; + public const string EventCodeProcessRetry = "PROCESS_RETRY"; + public const string EventCodeRecurringContract = "RECURRING_CONTRACT"; + public const string EventCodeRefund = "REFUND"; + public const string EventCodeRefundedReversed = "REFUNDED_REVERSED"; + public const string EventCodeRefundFailed = "REFUND_FAILED"; + public const string EventCodeRefundWithData = "REFUND_WITH_DATA"; + public const string EventCodeReportAvailable = "REPORT_AVAILABLE"; + public const string EventCodeRequestForInformation = "REQUEST_FOR_INFORMATION"; + public const string EventCodeSecondChargeback = "SECOND_CHARGEBACK"; + public const string EventCodeVoidPendingRefund = "VOID_PENDING_REFUND"; + + //Additional Data + public const string AdditionalDataTotalFraudScore = "totalFraudScore"; + public const string AdditionalDataFraudCheckPattern = "fraudCheck-(\\d+)-([A-Za-z0-9]+)"; + } } \ No newline at end of file diff --git a/Adyen/Model/Notification/NotificationRequestItem.cs b/Adyen/Webhooks/Models/NotificationRequestItem.cs similarity index 94% rename from Adyen/Model/Notification/NotificationRequestItem.cs rename to Adyen/Webhooks/Models/NotificationRequestItem.cs index 153a43583..9efa46c4d 100644 --- a/Adyen/Model/Notification/NotificationRequestItem.cs +++ b/Adyen/Webhooks/Models/NotificationRequestItem.cs @@ -1,44 +1,43 @@ -#region License -// /* -// * ###### -// * ###### -// * ############ ####( ###### #####. ###### ############ ############ -// * ############# #####( ###### #####. ###### ############# ############# -// * ###### #####( ###### #####. ###### ##### ###### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ###### -// * ############# ############# ############# ############# ##### ###### -// * ############ ############ ############# ############ ##### ###### -// * ###### -// * ############# -// * ############ -// * -// * Adyen Dotnet API Library -// * -// * Copyright (c) 2020 Adyen B.V. -// * This file is open source and available under the MIT license. -// * See the LICENSE file for more info. -// */ -#endregion - -using System.Collections.Generic; -using Adyen.Model.Checkout; - -namespace Adyen.Model.Notification -{ - public class NotificationRequestItem - { - public Amount Amount { get; set; } - public string EventCode { get; set; } - public string EventDate { get; set; } - public string MerchantAccountCode { get; set; } - public string MerchantReference { get; set; } - public string OriginalReference { get; set; } - public string PspReference { get; set; } - public string Reason { get; set; } - public bool Success { get; set; } - public string PaymentMethod { get; set; } - public List Operations { get; set; } - public Dictionary AdditionalData { get; set; } - } +#region License +// /* +// * ###### +// * ###### +// * ############ ####( ###### #####. ###### ############ ############ +// * ############# #####( ###### #####. ###### ############# ############# +// * ###### #####( ###### #####. ###### ##### ###### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ###### +// * ############# ############# ############# ############# ##### ###### +// * ############ ############ ############# ############ ##### ###### +// * ###### +// * ############# +// * ############ +// * +// * Adyen Dotnet API Library +// * +// * Copyright (c) 2020 Adyen B.V. +// * This file is open source and available under the MIT license. +// * See the LICENSE file for more info. +// */ +#endregion + +using System.Collections.Generic; + +namespace Adyen.Webhooks.Models +{ + public class NotificationRequestItem + { + public Amount Amount { get; set; } + public string EventCode { get; set; } + public string EventDate { get; set; } + public string MerchantAccountCode { get; set; } + public string MerchantReference { get; set; } + public string OriginalReference { get; set; } + public string PspReference { get; set; } + public string Reason { get; set; } + public bool Success { get; set; } + public string PaymentMethod { get; set; } + public List Operations { get; set; } + public Dictionary AdditionalData { get; set; } + } } \ No newline at end of file diff --git a/Adyen/Model/Notification/NotificationRequestItemContainer.cs b/Adyen/Webhooks/Models/NotificationRequestItemContainer.cs similarity index 95% rename from Adyen/Model/Notification/NotificationRequestItemContainer.cs rename to Adyen/Webhooks/Models/NotificationRequestItemContainer.cs index 01ea102cd..f5a78114f 100644 --- a/Adyen/Model/Notification/NotificationRequestItemContainer.cs +++ b/Adyen/Webhooks/Models/NotificationRequestItemContainer.cs @@ -1,46 +1,45 @@ -#region License -// /* -// * ###### -// * ###### -// * ############ ####( ###### #####. ###### ############ ############ -// * ############# #####( ###### #####. ###### ############# ############# -// * ###### #####( ###### #####. ###### ##### ###### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### -// * ###### ###### #####( ###### #####. ###### ##### ##### ###### -// * ############# ############# ############# ############# ##### ###### -// * ############ ############ ############# ############ ##### ###### -// * ###### -// * ############# -// * ############ -// * -// * Adyen Dotnet API Library -// * -// * Copyright (c) 2020 Adyen B.V. -// * This file is open source and available under the MIT license. -// * See the LICENSE file for more info. -// */ -#endregion - -using Adyen.Util; -using System.Text; - -namespace Adyen.Model.Notification -{ - using Newtonsoft.Json; - - public class NotificationRequestItemContainer - { - [JsonProperty("NotificationRequestItem")] - public NotificationRequestItem NotificationItem { get; set; } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class NotificationRequestItemContainer {\n"); - - sb.Append(" notificationItem: ").Append(NotificationItem).Append("\n"); - sb.Append("}"); - return sb.ToString(); - } - } +#region License +// /* +// * ###### +// * ###### +// * ############ ####( ###### #####. ###### ############ ############ +// * ############# #####( ###### #####. ###### ############# ############# +// * ###### #####( ###### #####. ###### ##### ###### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### +// * ###### ###### #####( ###### #####. ###### ##### ##### ###### +// * ############# ############# ############# ############# ##### ###### +// * ############ ############ ############# ############ ##### ###### +// * ###### +// * ############# +// * ############ +// * +// * Adyen Dotnet API Library +// * +// * Copyright (c) 2020 Adyen B.V. +// * This file is open source and available under the MIT license. +// * See the LICENSE file for more info. +// */ +#endregion + +using Adyen.Util; +using System.Text; + +namespace Adyen.Webhooks.Models +{ + using Newtonsoft.Json; + + public class NotificationRequestItemContainer + { + [JsonProperty("NotificationRequestItem")] + public NotificationRequestItem NotificationItem { get; set; } + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NotificationRequestItemContainer {\n"); + sb.Append(" notificationItem: ").Append(NotificationItem).Append("\n"); + sb.Append("}"); + return sb.ToString(); + } + } } \ No newline at end of file diff --git a/Adyen/Webhooks/WebhookHandler.cs b/Adyen/Webhooks/WebhookHandler.cs index 690c3cbff..ac6edddde 100644 --- a/Adyen/Webhooks/WebhookHandler.cs +++ b/Adyen/Webhooks/WebhookHandler.cs @@ -1,13 +1,50 @@ -using Adyen.Model.Notification; +using System.Text; using Adyen.Util; +using Adyen.Webhooks.Models; +using Newtonsoft.Json; namespace Adyen.Webhooks { + /// + /// Utility function to deserialize . + /// public class WebhookHandler { - public NotificationRequest HandleNotificationRequest(string jsonRequest) + /// + /// Deserializes a object. + /// + /// The JSON payload. + /// . + /// . + public NotificationRequest HandleNotificationRequest(string jsonRequest, JsonSerializerSettings jsonSerializerSettings = null) { - return JsonOperation.Deserialize(jsonRequest); + if (jsonSerializerSettings == null) + { + jsonSerializerSettings = new JsonSerializerSettings(); + jsonSerializerSettings.Converters.Add(new ByteArrayConverter()); + } + return JsonConvert.DeserializeObject(jsonRequest, jsonSerializerSettings); + } + } + + internal class ByteArrayConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return objectType == typeof(byte[]); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + return null; + return Encoding.UTF8.GetBytes((string)reader.Value); + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + byte[] bytes = (byte[])value; + writer.WriteValue(Encoding.UTF8.GetString(bytes)); } } } diff --git a/docs/BalanceControl/BalanceControlService.md b/docs/BalanceControl/BalanceControlService.md new file mode 100644 index 000000000..59d7a69a6 --- /dev/null +++ b/docs/BalanceControl/BalanceControlService.md @@ -0,0 +1,78 @@ +## Adyen.BalanceControl.Services.BalanceControlService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/BalanceControl/v1** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalanceControl.Extensions; +using Adyen.BalanceControl.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalanceControl((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBalanceControlService balanceControlService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**BalanceTransfer**](BalanceControlService.md#balancetransfer) | **POST** /balanceTransfer | Start a balance transfer | + + +### **POST** **/balanceTransfer** + +Start a balance transfer + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceTransferRequest** | **BalanceTransferRequest** | | + +#### Example usage + +```csharp +using Adyen.BalanceControl.Models; +using Adyen.BalanceControl.Services; + +// Example `BalanceControlService.BalanceTransfer` usage: +// Provide the following values: balanceTransferRequest +IBalanceTransferResponse response = await balanceControlService.BalanceTransferAsync( + BalanceTransferRequest balanceTransferRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceTransferResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceTransferResponse]() + + diff --git a/docs/BalancePlatform/AccountHoldersService.md b/docs/BalancePlatform/AccountHoldersService.md new file mode 100644 index 000000000..8b899bcdc --- /dev/null +++ b/docs/BalancePlatform/AccountHoldersService.md @@ -0,0 +1,264 @@ +## Adyen.BalancePlatform.Services.AccountHoldersService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAccountHoldersService accountHoldersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateAccountHolder**](AccountHoldersService.md#createaccountholder) | **POST** /accountHolders | Create an account holder | +| [**GetAccountHolder**](AccountHoldersService.md#getaccountholder) | **GET** /accountHolders/{id} | Get an account holder | +| [**GetAllBalanceAccountsOfAccountHolder**](AccountHoldersService.md#getallbalanceaccountsofaccountholder) | **GET** /accountHolders/{id}/balanceAccounts | Get all balance accounts of an account holder | +| [**GetAllTransactionRulesForAccountHolder**](AccountHoldersService.md#getalltransactionrulesforaccountholder) | **GET** /accountHolders/{id}/transactionRules | Get all transaction rules for an account holder | +| [**GetTaxForm**](AccountHoldersService.md#gettaxform) | **GET** /accountHolders/{id}/taxForms | Get a tax form | +| [**UpdateAccountHolder**](AccountHoldersService.md#updateaccountholder) | **PATCH** /accountHolders/{id} | Update an account holder | + + +### **POST** **/accountHolders** + +Create an account holder + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **accountHolderInfo** | **AccountHolderInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.CreateAccountHolder` usage: +// Provide the following values: accountHolderInfo +IAccountHolder response = await accountHoldersService.CreateAccountHolderAsync( + AccountHolderInfo accountHolderInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AccountHolder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AccountHolder]() + + + +### **GET** **/accountHolders/{id}** + +Get an account holder + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the account holder. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.GetAccountHolder` usage: +// Provide the following values: id +IAccountHolder response = await accountHoldersService.GetAccountHolderAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AccountHolder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AccountHolder]() + + + +### **GET** **/accountHolders/{id}/balanceAccounts** + +Get all balance accounts of an account holder + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the account holder. | +| **offset** | [int] | The number of items that you want to skip. | +| **limit** | [int] | The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.GetAllBalanceAccountsOfAccountHolder` usage: +// Provide the following values: id, offset, limit +IPaginatedBalanceAccountsResponse response = await accountHoldersService.GetAllBalanceAccountsOfAccountHolderAsync( + string id, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaginatedBalanceAccountsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaginatedBalanceAccountsResponse]() + + + +### **GET** **/accountHolders/{id}/transactionRules** + +Get all transaction rules for an account holder + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the account holder. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.GetAllTransactionRulesForAccountHolder` usage: +// Provide the following values: id +ITransactionRulesResponse response = await accountHoldersService.GetAllTransactionRulesForAccountHolderAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRulesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRulesResponse]() + + + +### **GET** **/accountHolders/{id}/taxForms** + +Get a tax form + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the account holder. | +| **formType** | [string] | The type of tax form you want to retrieve. Accepted values are **US1099k** and **US1099nec** | +| **year** | [int] | The tax year in YYYY format for the tax form you want to retrieve | +| **legalEntityId** | [string] | The legal entity reference whose tax form you want to retrieve | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.GetTaxForm` usage: +// Provide the following values: id, formType, year, legalEntityId +IGetTaxFormResponse response = await accountHoldersService.GetTaxFormAsync( + string id, string formType, int year, Option legalEntityId = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetTaxFormResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetTaxFormResponse]() + + + +### **PATCH** **/accountHolders/{id}** + +Update an account holder + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the account holder. | +| **accountHolderUpdateRequest** | **AccountHolderUpdateRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AccountHoldersService.UpdateAccountHolder` usage: +// Provide the following values: id, accountHolderUpdateRequest +IAccountHolder response = await accountHoldersService.UpdateAccountHolderAsync( + string id, AccountHolderUpdateRequest accountHolderUpdateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AccountHolder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AccountHolder]() + + diff --git a/docs/BalancePlatform/AuthorizedCardUsersService.md b/docs/BalancePlatform/AuthorizedCardUsersService.md new file mode 100644 index 000000000..a108cd1ed --- /dev/null +++ b/docs/BalancePlatform/AuthorizedCardUsersService.md @@ -0,0 +1,188 @@ +## Adyen.BalancePlatform.Services.AuthorizedCardUsersService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAuthorizedCardUsersService authorizedCardUsersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateAuthorisedCardUsers**](AuthorizedCardUsersService.md#createauthorisedcardusers) | **POST** /paymentInstruments/{paymentInstrumentId}/authorisedCardUsers | Create authorized users for a card. | +| [**DeleteAuthorisedCardUsers**](AuthorizedCardUsersService.md#deleteauthorisedcardusers) | **DELETE** /paymentInstruments/{paymentInstrumentId}/authorisedCardUsers | Delete the authorized users for a card. | +| [**GetAllAuthorisedCardUsers**](AuthorizedCardUsersService.md#getallauthorisedcardusers) | **GET** /paymentInstruments/{paymentInstrumentId}/authorisedCardUsers | Get authorized users for a card. | +| [**UpdateAuthorisedCardUsers**](AuthorizedCardUsersService.md#updateauthorisedcardusers) | **PATCH** /paymentInstruments/{paymentInstrumentId}/authorisedCardUsers | Update the authorized users for a card. | + + +### **POST** **/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers** + +Create authorized users for a card. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentId** | [string] | | +| **authorisedCardUsers** | **AuthorisedCardUsers** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AuthorizedCardUsersService.CreateAuthorisedCardUsers` usage: +// Provide the following values: paymentInstrumentId, authorisedCardUsers +await authorizedCardUsersService.CreateAuthorisedCardUsersAsync( + string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **DELETE** **/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers** + +Delete the authorized users for a card. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentId** | [string] | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AuthorizedCardUsersService.DeleteAuthorisedCardUsers` usage: +// Provide the following values: paymentInstrumentId +await authorizedCardUsersService.DeleteAuthorisedCardUsersAsync( + string paymentInstrumentId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers** + +Get authorized users for a card. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentId** | [string] | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AuthorizedCardUsersService.GetAllAuthorisedCardUsers` usage: +// Provide the following values: paymentInstrumentId +IAuthorisedCardUsers response = await authorizedCardUsersService.GetAllAuthorisedCardUsersAsync( + string paymentInstrumentId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AuthorisedCardUsers result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AuthorisedCardUsers]() + + + +### **PATCH** **/paymentInstruments/{paymentInstrumentId}/authorisedCardUsers** + +Update the authorized users for a card. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentId** | [string] | | +| **authorisedCardUsers** | **AuthorisedCardUsers** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `AuthorizedCardUsersService.UpdateAuthorisedCardUsers` usage: +// Provide the following values: paymentInstrumentId, authorisedCardUsers +await authorizedCardUsersService.UpdateAuthorisedCardUsersAsync( + string paymentInstrumentId, AuthorisedCardUsers authorisedCardUsers, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/BalancePlatform/BalanceAccountsService.md b/docs/BalancePlatform/BalanceAccountsService.md new file mode 100644 index 000000000..cbbad58fe --- /dev/null +++ b/docs/BalancePlatform/BalanceAccountsService.md @@ -0,0 +1,413 @@ +## Adyen.BalancePlatform.Services.BalanceAccountsService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBalanceAccountsService balanceAccountsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateBalanceAccount**](BalanceAccountsService.md#createbalanceaccount) | **POST** /balanceAccounts | Create a balance account | +| [**CreateSweep**](BalanceAccountsService.md#createsweep) | **POST** /balanceAccounts/{balanceAccountId}/sweeps | Create a sweep | +| [**DeleteSweep**](BalanceAccountsService.md#deletesweep) | **DELETE** /balanceAccounts/{balanceAccountId}/sweeps/{sweepId} | Delete a sweep | +| [**GetAllSweepsForBalanceAccount**](BalanceAccountsService.md#getallsweepsforbalanceaccount) | **GET** /balanceAccounts/{balanceAccountId}/sweeps | Get all sweeps for a balance account | +| [**GetAllTransactionRulesForBalanceAccount**](BalanceAccountsService.md#getalltransactionrulesforbalanceaccount) | **GET** /balanceAccounts/{id}/transactionRules | Get all transaction rules for a balance account | +| [**GetBalanceAccount**](BalanceAccountsService.md#getbalanceaccount) | **GET** /balanceAccounts/{id} | Get a balance account | +| [**GetPaymentInstrumentsLinkedToBalanceAccount**](BalanceAccountsService.md#getpaymentinstrumentslinkedtobalanceaccount) | **GET** /balanceAccounts/{id}/paymentInstruments | Get payment instruments linked to a balance account | +| [**GetSweep**](BalanceAccountsService.md#getsweep) | **GET** /balanceAccounts/{balanceAccountId}/sweeps/{sweepId} | Get a sweep | +| [**UpdateBalanceAccount**](BalanceAccountsService.md#updatebalanceaccount) | **PATCH** /balanceAccounts/{id} | Update a balance account | +| [**UpdateSweep**](BalanceAccountsService.md#updatesweep) | **PATCH** /balanceAccounts/{balanceAccountId}/sweeps/{sweepId} | Update a sweep | + + +### **POST** **/balanceAccounts** + +Create a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountInfo** | **BalanceAccountInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.CreateBalanceAccount` usage: +// Provide the following values: balanceAccountInfo +IBalanceAccount response = await balanceAccountsService.CreateBalanceAccountAsync( + BalanceAccountInfo balanceAccountInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceAccount result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceAccount]() + + + +### **POST** **/balanceAccounts/{balanceAccountId}/sweeps** + +Create a sweep + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountId** | [string] | The unique identifier of the balance account. | +| **createSweepConfigurationV2** | **CreateSweepConfigurationV2** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.CreateSweep` usage: +// Provide the following values: balanceAccountId, createSweepConfigurationV2 +ISweepConfigurationV2 response = await balanceAccountsService.CreateSweepAsync( + string balanceAccountId, CreateSweepConfigurationV2 createSweepConfigurationV2, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SweepConfigurationV2 result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SweepConfigurationV2]() + + + +### **DELETE** **/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}** + +Delete a sweep + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountId** | [string] | The unique identifier of the balance account. | +| **sweepId** | [string] | The unique identifier of the sweep. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.DeleteSweep` usage: +// Provide the following values: balanceAccountId, sweepId +await balanceAccountsService.DeleteSweepAsync( + string balanceAccountId, string sweepId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/balanceAccounts/{balanceAccountId}/sweeps** + +Get all sweeps for a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountId** | [string] | The unique identifier of the balance account. | +| **offset** | [int] | The number of items that you want to skip. | +| **limit** | [int] | The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.GetAllSweepsForBalanceAccount` usage: +// Provide the following values: balanceAccountId, offset, limit +IBalanceSweepConfigurationsResponse response = await balanceAccountsService.GetAllSweepsForBalanceAccountAsync( + string balanceAccountId, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceSweepConfigurationsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceSweepConfigurationsResponse]() + + + +### **GET** **/balanceAccounts/{id}/transactionRules** + +Get all transaction rules for a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.GetAllTransactionRulesForBalanceAccount` usage: +// Provide the following values: id +ITransactionRulesResponse response = await balanceAccountsService.GetAllTransactionRulesForBalanceAccountAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRulesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRulesResponse]() + + + +### **GET** **/balanceAccounts/{id}** + +Get a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.GetBalanceAccount` usage: +// Provide the following values: id +IBalanceAccount response = await balanceAccountsService.GetBalanceAccountAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceAccount result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceAccount]() + + + +### **GET** **/balanceAccounts/{id}/paymentInstruments** + +Get payment instruments linked to a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **offset** | [int] | The number of items that you want to skip. | +| **limit** | [int] | The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. | +| **status** | [string] | The status of the payment instruments that you want to get. By default, the response includes payment instruments with any status. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.GetPaymentInstrumentsLinkedToBalanceAccount` usage: +// Provide the following values: id, offset, limit, status +IPaginatedPaymentInstrumentsResponse response = await balanceAccountsService.GetPaymentInstrumentsLinkedToBalanceAccountAsync( + string id, Option offset = default, Option limit = default, Option status = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaginatedPaymentInstrumentsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaginatedPaymentInstrumentsResponse]() + + + +### **GET** **/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}** + +Get a sweep + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountId** | [string] | The unique identifier of the balance account. | +| **sweepId** | [string] | The unique identifier of the sweep. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.GetSweep` usage: +// Provide the following values: balanceAccountId, sweepId +ISweepConfigurationV2 response = await balanceAccountsService.GetSweepAsync( + string balanceAccountId, string sweepId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SweepConfigurationV2 result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SweepConfigurationV2]() + + + +### **PATCH** **/balanceAccounts/{id}** + +Update a balance account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **balanceAccountUpdateRequest** | **BalanceAccountUpdateRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.UpdateBalanceAccount` usage: +// Provide the following values: id, balanceAccountUpdateRequest +IBalanceAccount response = await balanceAccountsService.UpdateBalanceAccountAsync( + string id, BalanceAccountUpdateRequest balanceAccountUpdateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceAccount result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceAccount]() + + + +### **PATCH** **/balanceAccounts/{balanceAccountId}/sweeps/{sweepId}** + +Update a sweep + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balanceAccountId** | [string] | The unique identifier of the balance account. | +| **sweepId** | [string] | The unique identifier of the sweep. | +| **updateSweepConfigurationV2** | **UpdateSweepConfigurationV2** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalanceAccountsService.UpdateSweep` usage: +// Provide the following values: balanceAccountId, sweepId, updateSweepConfigurationV2 +ISweepConfigurationV2 response = await balanceAccountsService.UpdateSweepAsync( + string balanceAccountId, string sweepId, UpdateSweepConfigurationV2 updateSweepConfigurationV2, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SweepConfigurationV2 result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SweepConfigurationV2]() + + diff --git a/docs/BalancePlatform/BalancesService.md b/docs/BalancePlatform/BalancesService.md new file mode 100644 index 000000000..804b42ba7 --- /dev/null +++ b/docs/BalancePlatform/BalancesService.md @@ -0,0 +1,232 @@ +## Adyen.BalancePlatform.Services.BalancesService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBalancesService balancesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateWebhookSetting**](BalancesService.md#createwebhooksetting) | **POST** /balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings | Create a balance webhook setting | +| [**DeleteWebhookSetting**](BalancesService.md#deletewebhooksetting) | **DELETE** /balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId} | Delete a balance webhook setting by id | +| [**GetAllWebhookSettings**](BalancesService.md#getallwebhooksettings) | **GET** /balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings | Get all balance webhook settings | +| [**GetWebhookSetting**](BalancesService.md#getwebhooksetting) | **GET** /balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId} | Get a balance webhook setting by id | +| [**UpdateWebhookSetting**](BalancesService.md#updatewebhooksetting) | **PATCH** /balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId} | Update a balance webhook setting by id | + + +### **POST** **/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings** + +Create a balance webhook setting + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balancePlatformId** | [string] | The unique identifier of the balance platform. | +| **webhookId** | [string] | The unique identifier of the balance webhook. | +| **balanceWebhookSettingInfo** | **BalanceWebhookSettingInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalancesService.CreateWebhookSetting` usage: +// Provide the following values: balancePlatformId, webhookId, balanceWebhookSettingInfo +IWebhookSetting response = await balancesService.CreateWebhookSettingAsync( + string balancePlatformId, string webhookId, BalanceWebhookSettingInfo balanceWebhookSettingInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out WebhookSetting result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[WebhookSetting]() + + + +### **DELETE** **/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}** + +Delete a balance webhook setting by id + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balancePlatformId** | [string] | The unique identifier of the balance platform. | +| **webhookId** | [string] | The unique identifier of the balance webhook. | +| **settingId** | [string] | The unique identifier of the balance webhook setting. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalancesService.DeleteWebhookSetting` usage: +// Provide the following values: balancePlatformId, webhookId, settingId +await balancesService.DeleteWebhookSettingAsync( + string balancePlatformId, string webhookId, string settingId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings** + +Get all balance webhook settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balancePlatformId** | [string] | The unique identifier of the balance platform. | +| **webhookId** | [string] | The unique identifier of the balance webhook. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalancesService.GetAllWebhookSettings` usage: +// Provide the following values: balancePlatformId, webhookId +IWebhookSettings response = await balancesService.GetAllWebhookSettingsAsync( + string balancePlatformId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out WebhookSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[WebhookSettings]() + + + +### **GET** **/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}** + +Get a balance webhook setting by id + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balancePlatformId** | [string] | The unique identifier of the balance platform. | +| **webhookId** | [string] | The unique identifier of the balance webhook. | +| **settingId** | [string] | The unique identifier of the balance webhook setting. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalancesService.GetWebhookSetting` usage: +// Provide the following values: balancePlatformId, webhookId, settingId +IWebhookSetting response = await balancesService.GetWebhookSettingAsync( + string balancePlatformId, string webhookId, string settingId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out WebhookSetting result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[WebhookSetting]() + + + +### **PATCH** **/balancePlatforms/{balancePlatformId}/webhooks/{webhookId}/settings/{settingId}** + +Update a balance webhook setting by id + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **balancePlatformId** | [string] | The unique identifier of the balance platform. | +| **webhookId** | [string] | The unique identifier of the balance webhook. | +| **settingId** | [string] | The unique identifier of the balance webhook setting. | +| **balanceWebhookSettingInfoUpdate** | **BalanceWebhookSettingInfoUpdate** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BalancesService.UpdateWebhookSetting` usage: +// Provide the following values: balancePlatformId, webhookId, settingId, balanceWebhookSettingInfoUpdate +IWebhookSetting response = await balancesService.UpdateWebhookSettingAsync( + string balancePlatformId, string webhookId, string settingId, BalanceWebhookSettingInfoUpdate balanceWebhookSettingInfoUpdate, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out WebhookSetting result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[WebhookSetting]() + + diff --git a/docs/BalancePlatform/BankAccountValidationService.md b/docs/BalancePlatform/BankAccountValidationService.md new file mode 100644 index 000000000..1ce325bf6 --- /dev/null +++ b/docs/BalancePlatform/BankAccountValidationService.md @@ -0,0 +1,78 @@ +## Adyen.BalancePlatform.Services.BankAccountValidationService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBankAccountValidationService bankAccountValidationService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ValidateBankAccountIdentification**](BankAccountValidationService.md#validatebankaccountidentification) | **POST** /validateBankAccountIdentification | Validate a bank account | + + +### **POST** **/validateBankAccountIdentification** + +Validate a bank account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **bankAccountIdentificationValidationRequest** | **BankAccountIdentificationValidationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `BankAccountValidationService.ValidateBankAccountIdentification` usage: +// Provide the following values: bankAccountIdentificationValidationRequest +await bankAccountValidationService.ValidateBankAccountIdentificationAsync( + BankAccountIdentificationValidationRequest bankAccountIdentificationValidationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/BalancePlatform/CardOrdersService.md b/docs/BalancePlatform/CardOrdersService.md new file mode 100644 index 000000000..ce35445d7 --- /dev/null +++ b/docs/BalancePlatform/CardOrdersService.md @@ -0,0 +1,126 @@ +## Adyen.BalancePlatform.Services.CardOrdersService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ICardOrdersService cardOrdersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetCardOrderItems**](CardOrdersService.md#getcardorderitems) | **GET** /cardorders/{id}/items | Get card order items | +| [**ListCardOrders**](CardOrdersService.md#listcardorders) | **GET** /cardorders | Get a list of card orders | + + +### **GET** **/cardorders/{id}/items** + +Get card order items + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the card order. | +| **offset** | [int] | Specifies the position of an element in a list of card orders. The response includes a list of card order items that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card order items. | +| **limit** | [int] | The number of card order items returned per page. **Default:** 10. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `CardOrdersService.GetCardOrderItems` usage: +// Provide the following values: id, offset, limit +IPaginatedGetCardOrderItemResponse response = await cardOrdersService.GetCardOrderItemsAsync( + string id, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaginatedGetCardOrderItemResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaginatedGetCardOrderItemResponse]() + + + +### **GET** **/cardorders** + +Get a list of card orders + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the card order. | +| **cardManufacturingProfileId** | [string] | The unique identifier of the card manufacturer profile. | +| **status** | [string] | The status of the card order. | +| **txVariantCode** | [string] | The unique code of the card manufacturer profile. Possible values: **mcmaestro**, **mc**, **visa**, **mcdebit**. | +| **createdSince** | [DateTimeOffset] | Only include card orders that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **createdUntil** | [DateTimeOffset] | Only include card orders that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **lockedSince** | [DateTimeOffset] | Only include card orders that have been locked on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **lockedUntil** | [DateTimeOffset] | Only include card orders that have been locked on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **serviceCenter** | [string] | The service center at which the card is issued. The value is case-sensitive. | +| **offset** | [int] | Specifies the position of an element in a list of card orders. The response includes a list of card orders that starts at the specified offset. **Default:** 0, which means that the response contains all the elements in the list of card orders. | +| **limit** | [int] | The number of card orders returned per page. **Default:** 10. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `CardOrdersService.ListCardOrders` usage: +// Provide the following values: id, cardManufacturingProfileId, status, txVariantCode, createdSince, createdUntil, lockedSince, lockedUntil, serviceCenter, offset, limit +IPaginatedGetCardOrderResponse response = await cardOrdersService.ListCardOrdersAsync( + Option id = default, Option cardManufacturingProfileId = default, Option status = default, Option txVariantCode = default, Option createdSince = default, Option createdUntil = default, Option lockedSince = default, Option lockedUntil = default, Option serviceCenter = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaginatedGetCardOrderResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaginatedGetCardOrderResponse]() + + diff --git a/docs/BalancePlatform/GrantAccountsService.md b/docs/BalancePlatform/GrantAccountsService.md new file mode 100644 index 000000000..928a15810 --- /dev/null +++ b/docs/BalancePlatform/GrantAccountsService.md @@ -0,0 +1,78 @@ +## Adyen.BalancePlatform.Services.GrantAccountsService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IGrantAccountsService grantAccountsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetGrantAccount**](GrantAccountsService.md#getgrantaccount) | **GET** /grantAccounts/{id} | Get a grant account | + + +### **GET** **/grantAccounts/{id}** + +Get a grant account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the grant account. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `GrantAccountsService.GetGrantAccount` usage: +// Provide the following values: id +ICapitalGrantAccount response = await grantAccountsService.GetGrantAccountAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CapitalGrantAccount result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CapitalGrantAccount]() + + diff --git a/docs/BalancePlatform/GrantOffersService.md b/docs/BalancePlatform/GrantOffersService.md new file mode 100644 index 000000000..1052d3a7c --- /dev/null +++ b/docs/BalancePlatform/GrantOffersService.md @@ -0,0 +1,114 @@ +## Adyen.BalancePlatform.Services.GrantOffersService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IGrantOffersService grantOffersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetAllAvailableGrantOffers**](GrantOffersService.md#getallavailablegrantoffers) | **GET** /grantOffers | Get all available grant offers | +| [**GetGrantOffer**](GrantOffersService.md#getgrantoffer) | **GET** /grantOffers/{grantOfferId} | Get a grant offer | + + +### **GET** **/grantOffers** + +Get all available grant offers + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **accountHolderId** | [string] | The unique identifier of the grant account. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `GrantOffersService.GetAllAvailableGrantOffers` usage: +// Provide the following values: accountHolderId +IGrantOffers response = await grantOffersService.GetAllAvailableGrantOffersAsync( + string accountHolderId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GrantOffers result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GrantOffers]() + + + +### **GET** **/grantOffers/{grantOfferId}** + +Get a grant offer + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **grantOfferId** | [string] | The unique identifier of the grant offer. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `GrantOffersService.GetGrantOffer` usage: +// Provide the following values: grantOfferId +IGrantOffer response = await grantOffersService.GetGrantOfferAsync( + string grantOfferId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GrantOffer result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GrantOffer]() + + diff --git a/docs/BalancePlatform/ManageCardPINService.md b/docs/BalancePlatform/ManageCardPINService.md new file mode 100644 index 000000000..1e76ef363 --- /dev/null +++ b/docs/BalancePlatform/ManageCardPINService.md @@ -0,0 +1,151 @@ +## Adyen.BalancePlatform.Services.ManageCardPINService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IManageCardPINService manageCardPINService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ChangeCardPin**](ManageCardPINService.md#changecardpin) | **POST** /pins/change | Change a card PIN | +| [**PublicKey**](ManageCardPINService.md#publickey) | **GET** /publicKey | Get an RSA public key | +| [**RevealCardPin**](ManageCardPINService.md#revealcardpin) | **POST** /pins/reveal | Reveal a card PIN | + + +### **POST** **/pins/change** + +Change a card PIN + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **pinChangeRequest** | **PinChangeRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageCardPINService.ChangeCardPin` usage: +// Provide the following values: pinChangeRequest +IPinChangeResponse response = await manageCardPINService.ChangeCardPinAsync( + PinChangeRequest pinChangeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PinChangeResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PinChangeResponse]() + + + +### **GET** **/publicKey** + +Get an RSA public key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **purpose** | [string] | The purpose of the public key. Possible values: **pinChange**, **pinReveal**, **panReveal**. Default value: **pinReveal**. | +| **format** | [string] | The encoding format of public key. Possible values: **jwk**, **pem**. Default value: **pem**. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageCardPINService.PublicKey` usage: +// Provide the following values: purpose, format +IPublicKeyResponse response = await manageCardPINService.PublicKeyAsync( + Option purpose = default, Option format = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PublicKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PublicKeyResponse]() + + + +### **POST** **/pins/reveal** + +Reveal a card PIN + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **revealPinRequest** | **RevealPinRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageCardPINService.RevealCardPin` usage: +// Provide the following values: revealPinRequest +IRevealPinResponse response = await manageCardPINService.RevealCardPinAsync( + RevealPinRequest revealPinRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out RevealPinResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[RevealPinResponse]() + + diff --git a/docs/BalancePlatform/ManageSCADevicesService.md b/docs/BalancePlatform/ManageSCADevicesService.md new file mode 100644 index 000000000..14f62387b --- /dev/null +++ b/docs/BalancePlatform/ManageSCADevicesService.md @@ -0,0 +1,264 @@ +## Adyen.BalancePlatform.Services.ManageSCADevicesService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IManageSCADevicesService manageSCADevicesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CompleteAssociationBetweenScaDeviceAndResource**](ManageSCADevicesService.md#completeassociationbetweenscadeviceandresource) | **PATCH** /registeredDevices/{deviceId}/associations | Complete an association between an SCA device and a resource | +| [**CompleteRegistrationOfScaDevice**](ManageSCADevicesService.md#completeregistrationofscadevice) | **PATCH** /registeredDevices/{id} | Complete the registration of an SCA device | +| [**DeleteRegistrationOfScaDevice**](ManageSCADevicesService.md#deleteregistrationofscadevice) | **DELETE** /registeredDevices/{id} | Delete a registration of an SCA device | +| [**InitiateAssociationBetweenScaDeviceAndResource**](ManageSCADevicesService.md#initiateassociationbetweenscadeviceandresource) | **POST** /registeredDevices/{deviceId}/associations | Initiate an association between an SCA device and a resource | +| [**InitiateRegistrationOfScaDevice**](ManageSCADevicesService.md#initiateregistrationofscadevice) | **POST** /registeredDevices | Initiate the registration of an SCA device | +| [**ListRegisteredScaDevices**](ManageSCADevicesService.md#listregisteredscadevices) | **GET** /registeredDevices | Get a list of registered SCA devices | + + +### **PATCH** **/registeredDevices/{deviceId}/associations** + +Complete an association between an SCA device and a resource + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **deviceId** | [string] | The unique identifier of the SCA device that you are associating with a resource. | +| **associationFinaliseRequest** | **AssociationFinaliseRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.CompleteAssociationBetweenScaDeviceAndResource` usage: +// Provide the following values: deviceId, associationFinaliseRequest +IAssociationFinaliseResponse response = await manageSCADevicesService.CompleteAssociationBetweenScaDeviceAndResourceAsync( + string deviceId, AssociationFinaliseRequest associationFinaliseRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AssociationFinaliseResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AssociationFinaliseResponse]() + + + +### **PATCH** **/registeredDevices/{id}** + +Complete the registration of an SCA device + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the SCA device. You obtain this `id` in the response of a POST&nbsp;[/registeredDevices](https://docs.adyen.com/api-explorer/balanceplatform/2/post/registeredDevices#responses-200-id) request. | +| **registerSCARequest** | **RegisterSCARequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.CompleteRegistrationOfScaDevice` usage: +// Provide the following values: id, registerSCARequest +IRegisterSCAFinalResponse response = await manageSCADevicesService.CompleteRegistrationOfScaDeviceAsync( + string id, RegisterSCARequest registerSCARequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out RegisterSCAFinalResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[RegisterSCAFinalResponse]() + + + +### **DELETE** **/registeredDevices/{id}** + +Delete a registration of an SCA device + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the SCA device. | +| **paymentInstrumentId** | [string] | The unique identifier of the payment instrument linked to the SCA device. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.DeleteRegistrationOfScaDevice` usage: +// Provide the following values: id, paymentInstrumentId +await manageSCADevicesService.DeleteRegistrationOfScaDeviceAsync( + string id, string paymentInstrumentId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **POST** **/registeredDevices/{deviceId}/associations** + +Initiate an association between an SCA device and a resource + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **deviceId** | [string] | The unique identifier of the SCA device that you are associating with a resource. | +| **associationInitiateRequest** | **AssociationInitiateRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.InitiateAssociationBetweenScaDeviceAndResource` usage: +// Provide the following values: deviceId, associationInitiateRequest +IAssociationInitiateResponse response = await manageSCADevicesService.InitiateAssociationBetweenScaDeviceAndResourceAsync( + string deviceId, AssociationInitiateRequest associationInitiateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AssociationInitiateResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AssociationInitiateResponse]() + + + +### **POST** **/registeredDevices** + +Initiate the registration of an SCA device + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **registerSCARequest** | **RegisterSCARequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.InitiateRegistrationOfScaDevice` usage: +// Provide the following values: registerSCARequest +IRegisterSCAResponse response = await manageSCADevicesService.InitiateRegistrationOfScaDeviceAsync( + RegisterSCARequest registerSCARequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out RegisterSCAResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[RegisterSCAResponse]() + + + +### **GET** **/registeredDevices** + +Get a list of registered SCA devices + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentId** | [string] | The unique identifier of a payment instrument. It limits the returned list to SCA devices associated to this payment instrument. | +| **pageNumber** | [int] | The index of the page to retrieve. The index of the first page is 0 (zero). Default: 0. | +| **pageSize** | [int] | The number of items to have on a page. Default: 20. Maximum: 100. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `ManageSCADevicesService.ListRegisteredScaDevices` usage: +// Provide the following values: paymentInstrumentId, pageNumber, pageSize +ISearchRegisteredDevicesResponse response = await manageSCADevicesService.ListRegisteredScaDevicesAsync( + string paymentInstrumentId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SearchRegisteredDevicesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SearchRegisteredDevicesResponse]() + + diff --git a/docs/BalancePlatform/NetworkTokensService.md b/docs/BalancePlatform/NetworkTokensService.md new file mode 100644 index 000000000..65b45a32c --- /dev/null +++ b/docs/BalancePlatform/NetworkTokensService.md @@ -0,0 +1,115 @@ +## Adyen.BalancePlatform.Services.NetworkTokensService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + INetworkTokensService networkTokensService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetNetworkToken**](NetworkTokensService.md#getnetworktoken) | **GET** /networkTokens/{networkTokenId} | Get a network token | +| [**UpdateNetworkToken**](NetworkTokensService.md#updatenetworktoken) | **PATCH** /networkTokens/{networkTokenId} | Update a network token | + + +### **GET** **/networkTokens/{networkTokenId}** + +Get a network token + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **networkTokenId** | [string] | The unique identifier of the network token. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `NetworkTokensService.GetNetworkToken` usage: +// Provide the following values: networkTokenId +IGetNetworkTokenResponse response = await networkTokensService.GetNetworkTokenAsync( + string networkTokenId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetNetworkTokenResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetNetworkTokenResponse]() + + + +### **PATCH** **/networkTokens/{networkTokenId}** + +Update a network token + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **networkTokenId** | [string] | The unique identifier of the network token. | +| **updateNetworkTokenRequest** | **UpdateNetworkTokenRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `NetworkTokensService.UpdateNetworkToken` usage: +// Provide the following values: networkTokenId, updateNetworkTokenRequest +await networkTokensService.UpdateNetworkTokenAsync( + string networkTokenId, UpdateNetworkTokenRequest updateNetworkTokenRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/BalancePlatform/PaymentInstrumentGroupsService.md b/docs/BalancePlatform/PaymentInstrumentGroupsService.md new file mode 100644 index 000000000..a8f9888c7 --- /dev/null +++ b/docs/BalancePlatform/PaymentInstrumentGroupsService.md @@ -0,0 +1,150 @@ +## Adyen.BalancePlatform.Services.PaymentInstrumentGroupsService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentInstrumentGroupsService paymentInstrumentGroupsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreatePaymentInstrumentGroup**](PaymentInstrumentGroupsService.md#createpaymentinstrumentgroup) | **POST** /paymentInstrumentGroups | Create a payment instrument group | +| [**GetAllTransactionRulesForPaymentInstrumentGroup**](PaymentInstrumentGroupsService.md#getalltransactionrulesforpaymentinstrumentgroup) | **GET** /paymentInstrumentGroups/{id}/transactionRules | Get all transaction rules for a payment instrument group | +| [**GetPaymentInstrumentGroup**](PaymentInstrumentGroupsService.md#getpaymentinstrumentgroup) | **GET** /paymentInstrumentGroups/{id} | Get a payment instrument group | + + +### **POST** **/paymentInstrumentGroups** + +Create a payment instrument group + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentGroupInfo** | **PaymentInstrumentGroupInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentGroupsService.CreatePaymentInstrumentGroup` usage: +// Provide the following values: paymentInstrumentGroupInfo +IPaymentInstrumentGroup response = await paymentInstrumentGroupsService.CreatePaymentInstrumentGroupAsync( + PaymentInstrumentGroupInfo paymentInstrumentGroupInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrumentGroup result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrumentGroup]() + + + +### **GET** **/paymentInstrumentGroups/{id}/transactionRules** + +Get all transaction rules for a payment instrument group + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument group. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentGroupsService.GetAllTransactionRulesForPaymentInstrumentGroup` usage: +// Provide the following values: id +ITransactionRulesResponse response = await paymentInstrumentGroupsService.GetAllTransactionRulesForPaymentInstrumentGroupAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRulesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRulesResponse]() + + + +### **GET** **/paymentInstrumentGroups/{id}** + +Get a payment instrument group + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument group. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentGroupsService.GetPaymentInstrumentGroup` usage: +// Provide the following values: id +IPaymentInstrumentGroup response = await paymentInstrumentGroupsService.GetPaymentInstrumentGroupAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrumentGroup result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrumentGroup]() + + diff --git a/docs/BalancePlatform/PaymentInstrumentsService.md b/docs/BalancePlatform/PaymentInstrumentsService.md new file mode 100644 index 000000000..004f1aaf5 --- /dev/null +++ b/docs/BalancePlatform/PaymentInstrumentsService.md @@ -0,0 +1,368 @@ +## Adyen.BalancePlatform.Services.PaymentInstrumentsService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentInstrumentsService paymentInstrumentsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateNetworkTokenProvisioningData**](PaymentInstrumentsService.md#createnetworktokenprovisioningdata) | **POST** /paymentInstruments/{id}/networkTokenActivationData | Create network token provisioning data | +| [**CreatePaymentInstrument**](PaymentInstrumentsService.md#createpaymentinstrument) | **POST** /paymentInstruments | Create a payment instrument | +| [**GetAllTransactionRulesForPaymentInstrument**](PaymentInstrumentsService.md#getalltransactionrulesforpaymentinstrument) | **GET** /paymentInstruments/{id}/transactionRules | Get all transaction rules for a payment instrument | +| [**GetNetworkTokenActivationData**](PaymentInstrumentsService.md#getnetworktokenactivationdata) | **GET** /paymentInstruments/{id}/networkTokenActivationData | Get network token activation data | +| [**GetPanOfPaymentInstrument**](PaymentInstrumentsService.md#getpanofpaymentinstrument) | **GET** /paymentInstruments/{id}/reveal | Get the PAN of a payment instrument | +| [**GetPaymentInstrument**](PaymentInstrumentsService.md#getpaymentinstrument) | **GET** /paymentInstruments/{id} | Get a payment instrument | +| [**ListNetworkTokens**](PaymentInstrumentsService.md#listnetworktokens) | **GET** /paymentInstruments/{id}/networkTokens | List network tokens | +| [**RevealDataOfPaymentInstrument**](PaymentInstrumentsService.md#revealdataofpaymentinstrument) | **POST** /paymentInstruments/reveal | Reveal the data of a payment instrument | +| [**UpdatePaymentInstrument**](PaymentInstrumentsService.md#updatepaymentinstrument) | **PATCH** /paymentInstruments/{id} | Update a payment instrument | + + +### **POST** **/paymentInstruments/{id}/networkTokenActivationData** + +Create network token provisioning data + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | +| **networkTokenActivationDataRequest** | **NetworkTokenActivationDataRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.CreateNetworkTokenProvisioningData` usage: +// Provide the following values: id, networkTokenActivationDataRequest +INetworkTokenActivationDataResponse response = await paymentInstrumentsService.CreateNetworkTokenProvisioningDataAsync( + string id, NetworkTokenActivationDataRequest networkTokenActivationDataRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out NetworkTokenActivationDataResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[NetworkTokenActivationDataResponse]() + + + +### **POST** **/paymentInstruments** + +Create a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentInfo** | **PaymentInstrumentInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.CreatePaymentInstrument` usage: +// Provide the following values: paymentInstrumentInfo +IPaymentInstrument response = await paymentInstrumentsService.CreatePaymentInstrumentAsync( + PaymentInstrumentInfo paymentInstrumentInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrument]() + + + +### **GET** **/paymentInstruments/{id}/transactionRules** + +Get all transaction rules for a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.GetAllTransactionRulesForPaymentInstrument` usage: +// Provide the following values: id +ITransactionRulesResponse response = await paymentInstrumentsService.GetAllTransactionRulesForPaymentInstrumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRulesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRulesResponse]() + + + +### **GET** **/paymentInstruments/{id}/networkTokenActivationData** + +Get network token activation data + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.GetNetworkTokenActivationData` usage: +// Provide the following values: id +INetworkTokenActivationDataResponse response = await paymentInstrumentsService.GetNetworkTokenActivationDataAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out NetworkTokenActivationDataResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[NetworkTokenActivationDataResponse]() + + + +### **GET** **/paymentInstruments/{id}/reveal** + +Get the PAN of a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.GetPanOfPaymentInstrument` usage: +// Provide the following values: id +IPaymentInstrumentRevealInfo response = await paymentInstrumentsService.GetPanOfPaymentInstrumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrumentRevealInfo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrumentRevealInfo]() + + + +### **GET** **/paymentInstruments/{id}** + +Get a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.GetPaymentInstrument` usage: +// Provide the following values: id +IPaymentInstrument response = await paymentInstrumentsService.GetPaymentInstrumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrument]() + + + +### **GET** **/paymentInstruments/{id}/networkTokens** + +List network tokens + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.ListNetworkTokens` usage: +// Provide the following values: id +IListNetworkTokensResponse response = await paymentInstrumentsService.ListNetworkTokensAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListNetworkTokensResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListNetworkTokensResponse]() + + + +### **POST** **/paymentInstruments/reveal** + +Reveal the data of a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentInstrumentRevealRequest** | **PaymentInstrumentRevealRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.RevealDataOfPaymentInstrument` usage: +// Provide the following values: paymentInstrumentRevealRequest +IPaymentInstrumentRevealResponse response = await paymentInstrumentsService.RevealDataOfPaymentInstrumentAsync( + PaymentInstrumentRevealRequest paymentInstrumentRevealRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentInstrumentRevealResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentInstrumentRevealResponse]() + + + +### **PATCH** **/paymentInstruments/{id}** + +Update a payment instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the payment instrument. | +| **paymentInstrumentUpdateRequest** | **PaymentInstrumentUpdateRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PaymentInstrumentsService.UpdatePaymentInstrument` usage: +// Provide the following values: id, paymentInstrumentUpdateRequest +IUpdatePaymentInstrument response = await paymentInstrumentsService.UpdatePaymentInstrumentAsync( + string id, PaymentInstrumentUpdateRequest paymentInstrumentUpdateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out UpdatePaymentInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[UpdatePaymentInstrument]() + + diff --git a/docs/BalancePlatform/PlatformService.md b/docs/BalancePlatform/PlatformService.md new file mode 100644 index 000000000..aee7d9592 --- /dev/null +++ b/docs/BalancePlatform/PlatformService.md @@ -0,0 +1,152 @@ +## Adyen.BalancePlatform.Services.PlatformService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPlatformService platformService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetAllAccountHoldersUnderBalancePlatform**](PlatformService.md#getallaccountholdersunderbalanceplatform) | **GET** /balancePlatforms/{id}/accountHolders | Get all account holders under a balance platform | +| [**GetAllTransactionRulesForBalancePlatform**](PlatformService.md#getalltransactionrulesforbalanceplatform) | **GET** /balancePlatforms/{id}/transactionRules | Get all transaction rules for a balance platform | +| [**GetBalancePlatform**](PlatformService.md#getbalanceplatform) | **GET** /balancePlatforms/{id} | Get a balance platform | + + +### **GET** **/balancePlatforms/{id}/accountHolders** + +Get all account holders under a balance platform + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | +| **offset** | [int] | The number of items that you want to skip. | +| **limit** | [int] | The number of items returned per page, maximum 100 items. By default, the response returns 10 items per page. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PlatformService.GetAllAccountHoldersUnderBalancePlatform` usage: +// Provide the following values: id, offset, limit +IPaginatedAccountHoldersResponse response = await platformService.GetAllAccountHoldersUnderBalancePlatformAsync( + string id, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaginatedAccountHoldersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaginatedAccountHoldersResponse]() + + + +### **GET** **/balancePlatforms/{id}/transactionRules** + +Get all transaction rules for a balance platform + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PlatformService.GetAllTransactionRulesForBalancePlatform` usage: +// Provide the following values: id +ITransactionRulesResponse response = await platformService.GetAllTransactionRulesForBalancePlatformAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRulesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRulesResponse]() + + + +### **GET** **/balancePlatforms/{id}** + +Get a balance platform + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `PlatformService.GetBalancePlatform` usage: +// Provide the following values: id +IBalancePlatform response = await platformService.GetBalancePlatformAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalancePlatform result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalancePlatform]() + + diff --git a/docs/BalancePlatform/SCAAssociationManagementService.md b/docs/BalancePlatform/SCAAssociationManagementService.md new file mode 100644 index 000000000..ef492b828 --- /dev/null +++ b/docs/BalancePlatform/SCAAssociationManagementService.md @@ -0,0 +1,155 @@ +## Adyen.BalancePlatform.Services.SCAAssociationManagementService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ISCAAssociationManagementService sCAAssociationManagementService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ApproveAssociation**](SCAAssociationManagementService.md#approveassociation) | **PATCH** /scaAssociations | Approve a pending approval association | +| [**ListAssociations**](SCAAssociationManagementService.md#listassociations) | **GET** /scaAssociations | Get a list of devices associated with an entity | +| [**RemoveAssociation**](SCAAssociationManagementService.md#removeassociation) | **DELETE** /scaAssociations | Delete association to devices | + + +### **PATCH** **/scaAssociations** + +Approve a pending approval association + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **wWWAuthenticate** | [string] | The header for authenticating through SCA. | +| **approveAssociationRequest** | **ApproveAssociationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCAAssociationManagementService.ApproveAssociation` usage: +// Provide the following values: [HeaderParameter] wWWAuthenticate, approveAssociationRequest +IApproveAssociationResponse response = await sCAAssociationManagementService.ApproveAssociationAsync( + ApproveAssociationRequest approveAssociationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ApproveAssociationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ApproveAssociationResponse]() + + + +### **GET** **/scaAssociations** + +Get a list of devices associated with an entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **entityType** | [ScaEntityType] | The type of entity you want to retrieve a list of associations for. Possible values: **accountHolder** or **paymentInstrument**. | +| **entityId** | [string] | The unique identifier of the entity. | +| **pageSize** | [int] | The number of items to have on a page. Default: **5**. | +| **pageNumber** | [int] | The index of the page to retrieve. The index of the first page is **0** (zero). Default: **0**. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCAAssociationManagementService.ListAssociations` usage: +// Provide the following values: entityType, entityId, pageSize, pageNumber +IListAssociationsResponse response = await sCAAssociationManagementService.ListAssociationsAsync( + ScaEntityType entityType, string entityId, int pageSize, int pageNumber, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListAssociationsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListAssociationsResponse]() + + + +### **DELETE** **/scaAssociations** + +Delete association to devices + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **wWWAuthenticate** | [string] | The header for authenticating through SCA. | +| **removeAssociationRequest** | **RemoveAssociationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCAAssociationManagementService.RemoveAssociation` usage: +// Provide the following values: [HeaderParameter] wWWAuthenticate, removeAssociationRequest +await sCAAssociationManagementService.RemoveAssociationAsync( + RemoveAssociationRequest removeAssociationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/BalancePlatform/SCADeviceManagementService.md b/docs/BalancePlatform/SCADeviceManagementService.md new file mode 100644 index 000000000..eb0c058c2 --- /dev/null +++ b/docs/BalancePlatform/SCADeviceManagementService.md @@ -0,0 +1,152 @@ +## Adyen.BalancePlatform.Services.SCADeviceManagementService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ISCADeviceManagementService sCADeviceManagementService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**BeginScaDeviceRegistration**](SCADeviceManagementService.md#beginscadeviceregistration) | **POST** /scaDevices | Begin SCA device registration | +| [**FinishScaDeviceRegistration**](SCADeviceManagementService.md#finishscadeviceregistration) | **PATCH** /scaDevices/{deviceId} | Finish registration process for a SCA device | +| [**SubmitScaAssociation**](SCADeviceManagementService.md#submitscaassociation) | **POST** /scaDevices/{deviceId}/scaAssociations | Create a new SCA association for a device | + + +### **POST** **/scaDevices** + +Begin SCA device registration + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **beginScaDeviceRegistrationRequest** | **BeginScaDeviceRegistrationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCADeviceManagementService.BeginScaDeviceRegistration` usage: +// Provide the following values: beginScaDeviceRegistrationRequest +IBeginScaDeviceRegistrationResponse response = await sCADeviceManagementService.BeginScaDeviceRegistrationAsync( + BeginScaDeviceRegistrationRequest beginScaDeviceRegistrationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BeginScaDeviceRegistrationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BeginScaDeviceRegistrationResponse]() + + + +### **PATCH** **/scaDevices/{deviceId}** + +Finish registration process for a SCA device + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **deviceId** | [string] | The unique identifier of the SCA device that you are associating with a resource. | +| **finishScaDeviceRegistrationRequest** | **FinishScaDeviceRegistrationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCADeviceManagementService.FinishScaDeviceRegistration` usage: +// Provide the following values: deviceId, finishScaDeviceRegistrationRequest +IFinishScaDeviceRegistrationResponse response = await sCADeviceManagementService.FinishScaDeviceRegistrationAsync( + string deviceId, FinishScaDeviceRegistrationRequest finishScaDeviceRegistrationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out FinishScaDeviceRegistrationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[FinishScaDeviceRegistrationResponse]() + + + +### **POST** **/scaDevices/{deviceId}/scaAssociations** + +Create a new SCA association for a device + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **deviceId** | [string] | The unique identifier of the SCA device that you are associating with a resource. | +| **submitScaAssociationRequest** | **SubmitScaAssociationRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `SCADeviceManagementService.SubmitScaAssociation` usage: +// Provide the following values: deviceId, submitScaAssociationRequest +ISubmitScaAssociationResponse response = await sCADeviceManagementService.SubmitScaAssociationAsync( + string deviceId, SubmitScaAssociationRequest submitScaAssociationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SubmitScaAssociationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SubmitScaAssociationResponse]() + + diff --git a/docs/BalancePlatform/TransactionRulesService.md b/docs/BalancePlatform/TransactionRulesService.md new file mode 100644 index 000000000..f467abdd5 --- /dev/null +++ b/docs/BalancePlatform/TransactionRulesService.md @@ -0,0 +1,187 @@ +## Adyen.BalancePlatform.Services.TransactionRulesService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransactionRulesService transactionRulesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateTransactionRule**](TransactionRulesService.md#createtransactionrule) | **POST** /transactionRules | Create a transaction rule | +| [**DeleteTransactionRule**](TransactionRulesService.md#deletetransactionrule) | **DELETE** /transactionRules/{transactionRuleId} | Delete a transaction rule | +| [**GetTransactionRule**](TransactionRulesService.md#gettransactionrule) | **GET** /transactionRules/{transactionRuleId} | Get a transaction rule | +| [**UpdateTransactionRule**](TransactionRulesService.md#updatetransactionrule) | **PATCH** /transactionRules/{transactionRuleId} | Update a transaction rule | + + +### **POST** **/transactionRules** + +Create a transaction rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transactionRuleInfo** | **TransactionRuleInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransactionRulesService.CreateTransactionRule` usage: +// Provide the following values: transactionRuleInfo +ITransactionRule response = await transactionRulesService.CreateTransactionRuleAsync( + TransactionRuleInfo transactionRuleInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRule result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRule]() + + + +### **DELETE** **/transactionRules/{transactionRuleId}** + +Delete a transaction rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transactionRuleId** | [string] | The unique identifier of the transaction rule. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransactionRulesService.DeleteTransactionRule` usage: +// Provide the following values: transactionRuleId +ITransactionRule response = await transactionRulesService.DeleteTransactionRuleAsync( + string transactionRuleId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRule result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRule]() + + + +### **GET** **/transactionRules/{transactionRuleId}** + +Get a transaction rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transactionRuleId** | [string] | The unique identifier of the transaction rule. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransactionRulesService.GetTransactionRule` usage: +// Provide the following values: transactionRuleId +ITransactionRuleResponse response = await transactionRulesService.GetTransactionRuleAsync( + string transactionRuleId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRuleResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRuleResponse]() + + + +### **PATCH** **/transactionRules/{transactionRuleId}** + +Update a transaction rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transactionRuleId** | [string] | The unique identifier of the transaction rule. | +| **transactionRuleInfo** | **TransactionRuleInfo** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransactionRulesService.UpdateTransactionRule` usage: +// Provide the following values: transactionRuleId, transactionRuleInfo +ITransactionRule response = await transactionRulesService.UpdateTransactionRuleAsync( + string transactionRuleId, TransactionRuleInfo transactionRuleInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionRule result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionRule]() + + diff --git a/docs/BalancePlatform/TransferLimitsBalanceAccountLevelService.md b/docs/BalancePlatform/TransferLimitsBalanceAccountLevelService.md new file mode 100644 index 000000000..6fbb02c33 --- /dev/null +++ b/docs/BalancePlatform/TransferLimitsBalanceAccountLevelService.md @@ -0,0 +1,269 @@ +## Adyen.BalancePlatform.Services.TransferLimitsBalanceAccountLevelService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransferLimitsBalanceAccountLevelService transferLimitsBalanceAccountLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ApprovePendingTransferLimits**](TransferLimitsBalanceAccountLevelService.md#approvependingtransferlimits) | **POST** /balanceAccounts/{id}/transferLimits/approve | Approve pending transfer limits | +| [**CreateTransferLimit**](TransferLimitsBalanceAccountLevelService.md#createtransferlimit) | **POST** /balanceAccounts/{id}/transferLimits | Create a transfer limit | +| [**DeletePendingTransferLimit**](TransferLimitsBalanceAccountLevelService.md#deletependingtransferlimit) | **DELETE** /balanceAccounts/{id}/transferLimits/{transferLimitId} | Delete a scheduled or pending transfer limit | +| [**GetCurrentTransferLimits**](TransferLimitsBalanceAccountLevelService.md#getcurrenttransferlimits) | **GET** /balanceAccounts/{id}/transferLimits/current | Get all current transfer limits | +| [**GetSpecificTransferLimit**](TransferLimitsBalanceAccountLevelService.md#getspecifictransferlimit) | **GET** /balanceAccounts/{id}/transferLimits/{transferLimitId} | Get the details of a transfer limit | +| [**GetTransferLimits**](TransferLimitsBalanceAccountLevelService.md#gettransferlimits) | **GET** /balanceAccounts/{id}/transferLimits | Filter and view the transfer limits | + + +### **POST** **/balanceAccounts/{id}/transferLimits/approve** + +Approve pending transfer limits + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **approveTransferLimitRequest** | **ApproveTransferLimitRequest** | | +| **wWWAuthenticate** | [string] | Header for authenticating using SCA. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.ApprovePendingTransferLimits` usage: +// Provide the following values: id, approveTransferLimitRequest, [HeaderParameter] wWWAuthenticate +await transferLimitsBalanceAccountLevelService.ApprovePendingTransferLimitsAsync( + string id, ApproveTransferLimitRequest approveTransferLimitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **POST** **/balanceAccounts/{id}/transferLimits** + +Create a transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **createTransferLimitRequest** | **CreateTransferLimitRequest** | | +| **wWWAuthenticate** | [string] | Header for authenticating through SCA | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.CreateTransferLimit` usage: +// Provide the following values: id, createTransferLimitRequest, [HeaderParameter] wWWAuthenticate +ITransferLimit response = await transferLimitsBalanceAccountLevelService.CreateTransferLimitAsync( + string id, CreateTransferLimitRequest createTransferLimitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimit result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimit]() + + + +### **DELETE** **/balanceAccounts/{id}/transferLimits/{transferLimitId}** + +Delete a scheduled or pending transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **transferLimitId** | [string] | The unique identifier of the transfer limit. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.DeletePendingTransferLimit` usage: +// Provide the following values: id, transferLimitId +await transferLimitsBalanceAccountLevelService.DeletePendingTransferLimitAsync( + string id, string transferLimitId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/balanceAccounts/{id}/transferLimits/current** + +Get all current transfer limits + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **scope** | [Scope] | The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. | +| **transferType** | [TransferType] | The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.GetCurrentTransferLimits` usage: +// Provide the following values: id, scope, transferType +ITransferLimitListResponse response = await transferLimitsBalanceAccountLevelService.GetCurrentTransferLimitsAsync( + string id, Option scope = default, Option transferType = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimitListResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimitListResponse]() + + + +### **GET** **/balanceAccounts/{id}/transferLimits/{transferLimitId}** + +Get the details of a transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **transferLimitId** | [string] | The unique identifier of the transfer limit. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.GetSpecificTransferLimit` usage: +// Provide the following values: id, transferLimitId +ITransferLimit response = await transferLimitsBalanceAccountLevelService.GetSpecificTransferLimitAsync( + string id, string transferLimitId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimit result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimit]() + + + +### **GET** **/balanceAccounts/{id}/transferLimits** + +Filter and view the transfer limits + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance account. | +| **scope** | [Scope] | The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. | +| **transferType** | [TransferType] | The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. | +| **status** | [LimitStatus] | The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalanceAccountLevelService.GetTransferLimits` usage: +// Provide the following values: id, scope, transferType, status +ITransferLimitListResponse response = await transferLimitsBalanceAccountLevelService.GetTransferLimitsAsync( + string id, Option scope = default, Option transferType = default, Option status = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimitListResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimitListResponse]() + + diff --git a/docs/BalancePlatform/TransferLimitsBalancePlatformLevelService.md b/docs/BalancePlatform/TransferLimitsBalancePlatformLevelService.md new file mode 100644 index 000000000..d1d00b178 --- /dev/null +++ b/docs/BalancePlatform/TransferLimitsBalancePlatformLevelService.md @@ -0,0 +1,192 @@ +## Adyen.BalancePlatform.Services.TransferLimitsBalancePlatformLevelService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransferLimitsBalancePlatformLevelService transferLimitsBalancePlatformLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateTransferLimit**](TransferLimitsBalancePlatformLevelService.md#createtransferlimit) | **POST** /balancePlatforms/{id}/transferLimits | Create a transfer limit | +| [**DeletePendingTransferLimit**](TransferLimitsBalancePlatformLevelService.md#deletependingtransferlimit) | **DELETE** /balancePlatforms/{id}/transferLimits/{transferLimitId} | Delete a scheduled or pending transfer limit | +| [**GetSpecificTransferLimit**](TransferLimitsBalancePlatformLevelService.md#getspecifictransferlimit) | **GET** /balancePlatforms/{id}/transferLimits/{transferLimitId} | Get the details of a transfer limit | +| [**GetTransferLimits**](TransferLimitsBalancePlatformLevelService.md#gettransferlimits) | **GET** /balancePlatforms/{id}/transferLimits | Filter and view the transfer limits | + + +### **POST** **/balancePlatforms/{id}/transferLimits** + +Create a transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | +| **createTransferLimitRequest** | **CreateTransferLimitRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalancePlatformLevelService.CreateTransferLimit` usage: +// Provide the following values: id, createTransferLimitRequest +ITransferLimit response = await transferLimitsBalancePlatformLevelService.CreateTransferLimitAsync( + string id, CreateTransferLimitRequest createTransferLimitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimit result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimit]() + + + +### **DELETE** **/balancePlatforms/{id}/transferLimits/{transferLimitId}** + +Delete a scheduled or pending transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | +| **transferLimitId** | [string] | The unique identifier of the transfer limit. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalancePlatformLevelService.DeletePendingTransferLimit` usage: +// Provide the following values: id, transferLimitId +await transferLimitsBalancePlatformLevelService.DeletePendingTransferLimitAsync( + string id, string transferLimitId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/balancePlatforms/{id}/transferLimits/{transferLimitId}** + +Get the details of a transfer limit + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | +| **transferLimitId** | [string] | The unique identifier of the transfer limit. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalancePlatformLevelService.GetSpecificTransferLimit` usage: +// Provide the following values: id, transferLimitId +ITransferLimit response = await transferLimitsBalancePlatformLevelService.GetSpecificTransferLimitAsync( + string id, string transferLimitId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimit result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimit]() + + + +### **GET** **/balancePlatforms/{id}/transferLimits** + +Filter and view the transfer limits + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the balance platform. | +| **scope** | [Scope] | The scope to which the transfer limit applies. Possible values: * **perTransaction**: you set a maximum amount for each transfer made from the balance account or balance platform. * **perDay**: you set a maximum total amount for all transfers made from the balance account or balance platform in a day. | +| **transferType** | [TransferType] | The type of transfer to which the limit applies. Possible values: * **instant**: the limit applies to transfers with an **instant** priority. * **all**: the limit applies to all transfers, regardless of priority. | +| **status** | [LimitStatus] | The status of the transfer limit. Possible values: * **active**: the limit is currently active. * **inactive**: the limit is currently inactive. * **pendingSCA**: the limit is pending until your user performs SCA. * **scheduled**: the limit is scheduled to become active at a future date. | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferLimitsBalancePlatformLevelService.GetTransferLimits` usage: +// Provide the following values: id, scope, transferType, status +ITransferLimitListResponse response = await transferLimitsBalancePlatformLevelService.GetTransferLimitsAsync( + string id, Option scope = default, Option transferType = default, Option status = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferLimitListResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferLimitListResponse]() + + diff --git a/docs/BalancePlatform/TransferRoutesService.md b/docs/BalancePlatform/TransferRoutesService.md new file mode 100644 index 000000000..1c41875d6 --- /dev/null +++ b/docs/BalancePlatform/TransferRoutesService.md @@ -0,0 +1,78 @@ +## Adyen.BalancePlatform.Services.TransferRoutesService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/bcl/v2** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BalancePlatform.Extensions; +using Adyen.BalancePlatform.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBalancePlatform((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransferRoutesService transferRoutesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CalculateTransferRoutes**](TransferRoutesService.md#calculatetransferroutes) | **POST** /transferRoutes/calculate | Calculate transfer routes | + + +### **POST** **/transferRoutes/calculate** + +Calculate transfer routes + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transferRouteRequest** | **TransferRouteRequest** | | + +#### Example usage + +```csharp +using Adyen.BalancePlatform.Models; +using Adyen.BalancePlatform.Services; + +// Example `TransferRoutesService.CalculateTransferRoutes` usage: +// Provide the following values: transferRouteRequest +ITransferRouteResponse response = await transferRoutesService.CalculateTransferRoutesAsync( + TransferRouteRequest transferRouteRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferRouteResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferRouteResponse]() + + diff --git a/docs/BinLookup/BinLookupService.md b/docs/BinLookup/BinLookupService.md new file mode 100644 index 000000000..8645e39e7 --- /dev/null +++ b/docs/BinLookup/BinLookupService.md @@ -0,0 +1,114 @@ +## Adyen.BinLookup.Services.BinLookupService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/BinLookup/v54** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.BinLookup.Extensions; +using Adyen.BinLookup.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureBinLookup((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBinLookupService binLookupService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**Get3dsAvailability**](BinLookupService.md#get3dsavailability) | **POST** /get3dsAvailability | Check if 3D Secure is available | +| [**GetCostEstimate**](BinLookupService.md#getcostestimate) | **POST** /getCostEstimate | Get a fees cost estimate | + + +### **POST** **/get3dsAvailability** + +Check if 3D Secure is available + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **threeDSAvailabilityRequest** | **ThreeDSAvailabilityRequest** | | + +#### Example usage + +```csharp +using Adyen.BinLookup.Models; +using Adyen.BinLookup.Services; + +// Example `BinLookupService.Get3dsAvailability` usage: +// Provide the following values: threeDSAvailabilityRequest +IThreeDSAvailabilityResponse response = await binLookupService.Get3dsAvailabilityAsync( + ThreeDSAvailabilityRequest threeDSAvailabilityRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ThreeDSAvailabilityResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ThreeDSAvailabilityResponse]() + + + +### **POST** **/getCostEstimate** + +Get a fees cost estimate + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **costEstimateRequest** | **CostEstimateRequest** | | + +#### Example usage + +```csharp +using Adyen.BinLookup.Models; +using Adyen.BinLookup.Services; + +// Example `BinLookupService.GetCostEstimate` usage: +// Provide the following values: costEstimateRequest +ICostEstimateResponse response = await binLookupService.GetCostEstimateAsync( + CostEstimateRequest costEstimateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CostEstimateResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CostEstimateResponse]() + + diff --git a/docs/Checkout/DonationsService.md b/docs/Checkout/DonationsService.md new file mode 100644 index 000000000..41af41a44 --- /dev/null +++ b/docs/Checkout/DonationsService.md @@ -0,0 +1,116 @@ +## Adyen.Checkout.Services.DonationsService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IDonationsService donationsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**DonationCampaigns**](DonationsService.md#donationcampaigns) | **POST** /donationCampaigns | Get a list of donation campaigns. | +| [**Donations**](DonationsService.md#donations) | **POST** /donations | Make a donation | + + +### **POST** **/donationCampaigns** + +Get a list of donation campaigns. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **donationCampaignsRequest** | **DonationCampaignsRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `DonationsService.DonationCampaigns` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, donationCampaignsRequest +IDonationCampaignsResponse response = await donationsService.DonationCampaignsAsync( + DonationCampaignsRequest donationCampaignsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DonationCampaignsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DonationCampaignsResponse]() + + + +### **POST** **/donations** + +Make a donation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **donationPaymentRequest** | **DonationPaymentRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `DonationsService.Donations` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, donationPaymentRequest +IDonationPaymentResponse response = await donationsService.DonationsAsync( + DonationPaymentRequest donationPaymentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DonationPaymentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DonationPaymentResponse]() + + diff --git a/docs/Checkout/ModificationsService.md b/docs/Checkout/ModificationsService.md new file mode 100644 index 000000000..9dc180f90 --- /dev/null +++ b/docs/Checkout/ModificationsService.md @@ -0,0 +1,269 @@ +## Adyen.Checkout.Services.ModificationsService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IModificationsService modificationsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CancelAuthorisedPayment**](ModificationsService.md#cancelauthorisedpayment) | **POST** /cancels | Cancel an authorised payment | +| [**CancelAuthorisedPaymentByPspReference**](ModificationsService.md#cancelauthorisedpaymentbypspreference) | **POST** /payments/{paymentPspReference}/cancels | Cancel an authorised payment | +| [**CaptureAuthorisedPayment**](ModificationsService.md#captureauthorisedpayment) | **POST** /payments/{paymentPspReference}/captures | Capture an authorised payment | +| [**RefundCapturedPayment**](ModificationsService.md#refundcapturedpayment) | **POST** /payments/{paymentPspReference}/refunds | Refund a captured payment | +| [**RefundOrCancelPayment**](ModificationsService.md#refundorcancelpayment) | **POST** /payments/{paymentPspReference}/reversals | Refund or cancel a payment | +| [**UpdateAuthorisedAmount**](ModificationsService.md#updateauthorisedamount) | **POST** /payments/{paymentPspReference}/amountUpdates | Update an authorised amount | + + +### **POST** **/cancels** + +Cancel an authorised payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **standalonePaymentCancelRequest** | **StandalonePaymentCancelRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.CancelAuthorisedPayment` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, standalonePaymentCancelRequest +IStandalonePaymentCancelResponse response = await modificationsService.CancelAuthorisedPaymentAsync( + StandalonePaymentCancelRequest standalonePaymentCancelRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StandalonePaymentCancelResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StandalonePaymentCancelResponse]() + + + +### **POST** **/payments/{paymentPspReference}/cancels** + +Cancel an authorised payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentPspReference** | [string] | The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to cancel. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentCancelRequest** | **PaymentCancelRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.CancelAuthorisedPaymentByPspReference` usage: +// Provide the following values: paymentPspReference, [HeaderParameter] idempotencyKey, paymentCancelRequest +IPaymentCancelResponse response = await modificationsService.CancelAuthorisedPaymentByPspReferenceAsync( + string paymentPspReference, PaymentCancelRequest paymentCancelRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentCancelResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentCancelResponse]() + + + +### **POST** **/payments/{paymentPspReference}/captures** + +Capture an authorised payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentPspReference** | [string] | The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to capture. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentCaptureRequest** | **PaymentCaptureRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.CaptureAuthorisedPayment` usage: +// Provide the following values: paymentPspReference, [HeaderParameter] idempotencyKey, paymentCaptureRequest +IPaymentCaptureResponse response = await modificationsService.CaptureAuthorisedPaymentAsync( + string paymentPspReference, PaymentCaptureRequest paymentCaptureRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentCaptureResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentCaptureResponse]() + + + +### **POST** **/payments/{paymentPspReference}/refunds** + +Refund a captured payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentPspReference** | [string] | The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to refund. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentRefundRequest** | **PaymentRefundRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.RefundCapturedPayment` usage: +// Provide the following values: paymentPspReference, [HeaderParameter] idempotencyKey, paymentRefundRequest +IPaymentRefundResponse response = await modificationsService.RefundCapturedPaymentAsync( + string paymentPspReference, PaymentRefundRequest paymentRefundRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentRefundResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentRefundResponse]() + + + +### **POST** **/payments/{paymentPspReference}/reversals** + +Refund or cancel a payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentPspReference** | [string] | The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment that you want to reverse. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentReversalRequest** | **PaymentReversalRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.RefundOrCancelPayment` usage: +// Provide the following values: paymentPspReference, [HeaderParameter] idempotencyKey, paymentReversalRequest +IPaymentReversalResponse response = await modificationsService.RefundOrCancelPaymentAsync( + string paymentPspReference, PaymentReversalRequest paymentReversalRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentReversalResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentReversalResponse]() + + + +### **POST** **/payments/{paymentPspReference}/amountUpdates** + +Update an authorised amount + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentPspReference** | [string] | The [`pspReference`](https://docs.adyen.com/api-explorer/Checkout/latest/post/payments#responses-200-pspReference) of the payment. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentAmountUpdateRequest** | **PaymentAmountUpdateRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `ModificationsService.UpdateAuthorisedAmount` usage: +// Provide the following values: paymentPspReference, [HeaderParameter] idempotencyKey, paymentAmountUpdateRequest +IPaymentAmountUpdateResponse response = await modificationsService.UpdateAuthorisedAmountAsync( + string paymentPspReference, PaymentAmountUpdateRequest paymentAmountUpdateRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentAmountUpdateResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentAmountUpdateResponse]() + + diff --git a/docs/Checkout/OrdersService.md b/docs/Checkout/OrdersService.md new file mode 100644 index 000000000..fad642524 --- /dev/null +++ b/docs/Checkout/OrdersService.md @@ -0,0 +1,153 @@ +## Adyen.Checkout.Services.OrdersService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IOrdersService ordersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CancelOrder**](OrdersService.md#cancelorder) | **POST** /orders/cancel | Cancel an order | +| [**GetBalanceOfGiftCard**](OrdersService.md#getbalanceofgiftcard) | **POST** /paymentMethods/balance | Get the balance of a gift card | +| [**Orders**](OrdersService.md#orders) | **POST** /orders | Create an order | + + +### **POST** **/orders/cancel** + +Cancel an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **cancelOrderRequest** | **CancelOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `OrdersService.CancelOrder` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, cancelOrderRequest +ICancelOrderResponse response = await ordersService.CancelOrderAsync( + CancelOrderRequest cancelOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CancelOrderResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CancelOrderResponse]() + + + +### **POST** **/paymentMethods/balance** + +Get the balance of a gift card + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **balanceCheckRequest** | **BalanceCheckRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `OrdersService.GetBalanceOfGiftCard` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, balanceCheckRequest +IBalanceCheckResponse response = await ordersService.GetBalanceOfGiftCardAsync( + BalanceCheckRequest balanceCheckRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BalanceCheckResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BalanceCheckResponse]() + + + +### **POST** **/orders** + +Create an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **createOrderRequest** | **CreateOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `OrdersService.Orders` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, createOrderRequest +ICreateOrderResponse response = await ordersService.OrdersAsync( + CreateOrderRequest createOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateOrderResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateOrderResponse]() + + diff --git a/docs/Checkout/PaymentLinksService.md b/docs/Checkout/PaymentLinksService.md new file mode 100644 index 000000000..577da7892 --- /dev/null +++ b/docs/Checkout/PaymentLinksService.md @@ -0,0 +1,152 @@ +## Adyen.Checkout.Services.PaymentLinksService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentLinksService paymentLinksService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetPaymentLink**](PaymentLinksService.md#getpaymentlink) | **GET** /paymentLinks/{linkId} | Get a payment link | +| [**PaymentLinks**](PaymentLinksService.md#paymentlinks) | **POST** /paymentLinks | Create a payment link | +| [**UpdatePaymentLink**](PaymentLinksService.md#updatepaymentlink) | **PATCH** /paymentLinks/{linkId} | Update the status of a payment link | + + +### **GET** **/paymentLinks/{linkId}** + +Get a payment link + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **linkId** | [string] | Unique identifier of the payment link. | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentLinksService.GetPaymentLink` usage: +// Provide the following values: linkId +IPaymentLinkResponse response = await paymentLinksService.GetPaymentLinkAsync( + string linkId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentLinkResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentLinkResponse]() + + + +### **POST** **/paymentLinks** + +Create a payment link + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentLinkRequest** | **PaymentLinkRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentLinksService.PaymentLinks` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, paymentLinkRequest +IPaymentLinkResponse response = await paymentLinksService.PaymentLinksAsync( + PaymentLinkRequest paymentLinkRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentLinkResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentLinkResponse]() + + + +### **PATCH** **/paymentLinks/{linkId}** + +Update the status of a payment link + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **linkId** | [string] | Unique identifier of the payment link. | +| **updatePaymentLinkRequest** | **UpdatePaymentLinkRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentLinksService.UpdatePaymentLink` usage: +// Provide the following values: linkId, updatePaymentLinkRequest +IPaymentLinkResponse response = await paymentLinksService.UpdatePaymentLinkAsync( + string linkId, UpdatePaymentLinkRequest updatePaymentLinkRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentLinkResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentLinkResponse]() + + diff --git a/docs/Checkout/PaymentsService.md b/docs/Checkout/PaymentsService.md new file mode 100644 index 000000000..dbd1e8e19 --- /dev/null +++ b/docs/Checkout/PaymentsService.md @@ -0,0 +1,264 @@ +## Adyen.Checkout.Services.PaymentsService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentsService paymentsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CardDetails**](PaymentsService.md#carddetails) | **POST** /cardDetails | Get the brands and other details of a card | +| [**GetResultOfPaymentSession**](PaymentsService.md#getresultofpaymentsession) | **GET** /sessions/{sessionId} | Get the result of a payment session | +| [**PaymentMethods**](PaymentsService.md#paymentmethods) | **POST** /paymentMethods | Get a list of available payment methods | +| [**Payments**](PaymentsService.md#payments) | **POST** /payments | Start a transaction | +| [**PaymentsDetails**](PaymentsService.md#paymentsdetails) | **POST** /payments/details | Submit details for a payment | +| [**Sessions**](PaymentsService.md#sessions) | **POST** /sessions | Create a payment session | + + +### **POST** **/cardDetails** + +Get the brands and other details of a card + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **cardDetailsRequest** | **CardDetailsRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.CardDetails` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, cardDetailsRequest +ICardDetailsResponse response = await paymentsService.CardDetailsAsync( + CardDetailsRequest cardDetailsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CardDetailsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CardDetailsResponse]() + + + +### **GET** **/sessions/{sessionId}** + +Get the result of a payment session + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **sessionId** | [string] | A unique identifier of the session. | +| **sessionResult** | [string] | The `sessionResult` value from the Drop-in or Component. | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.GetResultOfPaymentSession` usage: +// Provide the following values: sessionId, sessionResult +ISessionResultResponse response = await paymentsService.GetResultOfPaymentSessionAsync( + string sessionId, string sessionResult, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SessionResultResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SessionResultResponse]() + + + +### **POST** **/paymentMethods** + +Get a list of available payment methods + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentMethodsRequest** | **PaymentMethodsRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.PaymentMethods` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, paymentMethodsRequest +IPaymentMethodsResponse response = await paymentsService.PaymentMethodsAsync( + PaymentMethodsRequest paymentMethodsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentMethodsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentMethodsResponse]() + + + +### **POST** **/payments** + +Start a transaction + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentRequest** | **PaymentRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.Payments` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, paymentRequest +IPaymentResponse response = await paymentsService.PaymentsAsync( + PaymentRequest paymentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentResponse]() + + + +### **POST** **/payments/details** + +Submit details for a payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paymentDetailsRequest** | **PaymentDetailsRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.PaymentsDetails` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, paymentDetailsRequest +IPaymentDetailsResponse response = await paymentsService.PaymentsDetailsAsync( + PaymentDetailsRequest paymentDetailsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentDetailsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentDetailsResponse]() + + + +### **POST** **/sessions** + +Create a payment session + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **createCheckoutSessionRequest** | **CreateCheckoutSessionRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `PaymentsService.Sessions` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, createCheckoutSessionRequest +ICreateCheckoutSessionResponse response = await paymentsService.SessionsAsync( + CreateCheckoutSessionRequest createCheckoutSessionRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateCheckoutSessionResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateCheckoutSessionResponse]() + + diff --git a/docs/Checkout/RecurringService.md b/docs/Checkout/RecurringService.md new file mode 100644 index 000000000..a6a86c6ed --- /dev/null +++ b/docs/Checkout/RecurringService.md @@ -0,0 +1,154 @@ +## Adyen.Checkout.Services.RecurringService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IRecurringService recurringService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**DeleteTokenForStoredPaymentDetails**](RecurringService.md#deletetokenforstoredpaymentdetails) | **DELETE** /storedPaymentMethods/{storedPaymentMethodId} | Delete a token for stored payment details | +| [**GetTokensForStoredPaymentDetails**](RecurringService.md#gettokensforstoredpaymentdetails) | **GET** /storedPaymentMethods | Get tokens for stored payment details | +| [**StoredPaymentMethods**](RecurringService.md#storedpaymentmethods) | **POST** /storedPaymentMethods | Create a token to store payment details | + + +### **DELETE** **/storedPaymentMethods/{storedPaymentMethodId}** + +Delete a token for stored payment details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedPaymentMethodId** | [string] | The unique identifier of the token. | +| **shopperReference** | [string] | Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. | +| **merchantAccount** | [string] | Your merchant account. | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `RecurringService.DeleteTokenForStoredPaymentDetails` usage: +// Provide the following values: storedPaymentMethodId, shopperReference, merchantAccount +await recurringService.DeleteTokenForStoredPaymentDetailsAsync( + string storedPaymentMethodId, string shopperReference, string merchantAccount, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/storedPaymentMethods** + +Get tokens for stored payment details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **shopperReference** | [string] | Your reference to uniquely identify this shopper, for example user ID or account ID. Minimum length: 3 characters. > Your reference must not include personally identifiable information (PII), for example name or email address. | +| **merchantAccount** | [string] | Your merchant account. | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `RecurringService.GetTokensForStoredPaymentDetails` usage: +// Provide the following values: shopperReference, merchantAccount +IListStoredPaymentMethodsResponse response = await recurringService.GetTokensForStoredPaymentDetailsAsync( + Option shopperReference = default, Option merchantAccount = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListStoredPaymentMethodsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListStoredPaymentMethodsResponse]() + + + +### **POST** **/storedPaymentMethods** + +Create a token to store payment details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **storedPaymentMethodRequest** | **StoredPaymentMethodRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `RecurringService.StoredPaymentMethods` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, storedPaymentMethodRequest +IStoredPaymentMethodResource response = await recurringService.StoredPaymentMethodsAsync( + StoredPaymentMethodRequest storedPaymentMethodRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredPaymentMethodResource result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredPaymentMethodResource]() + + diff --git a/docs/Checkout/UtilityService.md b/docs/Checkout/UtilityService.md new file mode 100644 index 000000000..e8d33eb0a --- /dev/null +++ b/docs/Checkout/UtilityService.md @@ -0,0 +1,189 @@ +## Adyen.Checkout.Services.UtilityService + +#### API Base-Path: **https://checkout-test.adyen.com/v71** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Checkout.Extensions; +using Adyen.Checkout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureCheckout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IUtilityService utilityService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetApplePaySession**](UtilityService.md#getapplepaysession) | **POST** /applePay/sessions | Get an Apple Pay session | +| [**OriginKeys**](UtilityService.md#originkeys) | **POST** /originKeys | Create originKey values for domains | +| [**UpdatesOrderForPaypalExpressCheckout**](UtilityService.md#updatesorderforpaypalexpresscheckout) | **POST** /paypal/updateOrder | Updates the order for PayPal Express Checkout | +| [**ValidateShopperId**](UtilityService.md#validateshopperid) | **POST** /validateShopperId | Validates shopper Id | + + +### **POST** **/applePay/sessions** + +Get an Apple Pay session + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **applePaySessionRequest** | **ApplePaySessionRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `UtilityService.GetApplePaySession` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, applePaySessionRequest +IApplePaySessionResponse response = await utilityService.GetApplePaySessionAsync( + ApplePaySessionRequest applePaySessionRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ApplePaySessionResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ApplePaySessionResponse]() + + + +### **POST** **/originKeys** + +Create originKey values for domains + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **utilityRequest** | **UtilityRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `UtilityService.OriginKeys` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, utilityRequest +IUtilityResponse response = await utilityService.OriginKeysAsync( + UtilityRequest utilityRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out UtilityResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[UtilityResponse]() + + + +### **POST** **/paypal/updateOrder** + +Updates the order for PayPal Express Checkout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **paypalUpdateOrderRequest** | **PaypalUpdateOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `UtilityService.UpdatesOrderForPaypalExpressCheckout` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, paypalUpdateOrderRequest +IPaypalUpdateOrderResponse response = await utilityService.UpdatesOrderForPaypalExpressCheckoutAsync( + PaypalUpdateOrderRequest paypalUpdateOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaypalUpdateOrderResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaypalUpdateOrderResponse]() + + + +### **POST** **/validateShopperId** + +Validates shopper Id + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **validateShopperIdRequest** | **ValidateShopperIdRequest** | | + +#### Example usage + +```csharp +using Adyen.Checkout.Models; +using Adyen.Checkout.Services; + +// Example `UtilityService.ValidateShopperId` usage: +// Provide the following values: validateShopperIdRequest +IValidateShopperIdResponse response = await utilityService.ValidateShopperIdAsync( + ValidateShopperIdRequest validateShopperIdRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ValidateShopperIdResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ValidateShopperIdResponse]() + + diff --git a/docs/DataProtection/DataProtectionService.md b/docs/DataProtection/DataProtectionService.md new file mode 100644 index 000000000..ca82ed616 --- /dev/null +++ b/docs/DataProtection/DataProtectionService.md @@ -0,0 +1,78 @@ +## Adyen.DataProtection.Services.DataProtectionService + +#### API Base-Path: **https://ca-test.adyen.com/ca/services/DataProtectionService/v1** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.DataProtection.Extensions; +using Adyen.DataProtection.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureDataProtection((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IDataProtectionService dataProtectionService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**RequestSubjectErasure**](DataProtectionService.md#requestsubjecterasure) | **POST** /requestSubjectErasure | Submit a Subject Erasure Request. | + + +### **POST** **/requestSubjectErasure** + +Submit a Subject Erasure Request. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **subjectErasureByPspReferenceRequest** | **SubjectErasureByPspReferenceRequest** | | + +#### Example usage + +```csharp +using Adyen.DataProtection.Models; +using Adyen.DataProtection.Services; + +// Example `DataProtectionService.RequestSubjectErasure` usage: +// Provide the following values: subjectErasureByPspReferenceRequest +ISubjectErasureResponse response = await dataProtectionService.RequestSubjectErasureAsync( + SubjectErasureByPspReferenceRequest subjectErasureByPspReferenceRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SubjectErasureResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SubjectErasureResponse]() + + diff --git a/docs/Disputes/DisputesService.md b/docs/Disputes/DisputesService.md new file mode 100644 index 000000000..c02c82476 --- /dev/null +++ b/docs/Disputes/DisputesService.md @@ -0,0 +1,222 @@ +## Adyen.Disputes.Services.DisputesService + +#### API Base-Path: **https://ca-test.adyen.com/ca/services/DisputeService/v30** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Disputes.Extensions; +using Adyen.Disputes.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureDisputes((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IDisputesService disputesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AcceptDispute**](DisputesService.md#acceptdispute) | **POST** /acceptDispute | Accept a dispute | +| [**DefendDispute**](DisputesService.md#defenddispute) | **POST** /defendDispute | Defend a dispute | +| [**DeleteDisputeDefenseDocument**](DisputesService.md#deletedisputedefensedocument) | **POST** /deleteDisputeDefenseDocument | Delete a defense document | +| [**RetrieveApplicableDefenseReasons**](DisputesService.md#retrieveapplicabledefensereasons) | **POST** /retrieveApplicableDefenseReasons | Get applicable defense reasons | +| [**SupplyDefenseDocument**](DisputesService.md#supplydefensedocument) | **POST** /supplyDefenseDocument | Supply a defense document | + + +### **POST** **/acceptDispute** + +Accept a dispute + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **acceptDisputeRequest** | **AcceptDisputeRequest** | | + +#### Example usage + +```csharp +using Adyen.Disputes.Models; +using Adyen.Disputes.Services; + +// Example `DisputesService.AcceptDispute` usage: +// Provide the following values: acceptDisputeRequest +IAcceptDisputeResponse response = await disputesService.AcceptDisputeAsync( + AcceptDisputeRequest acceptDisputeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AcceptDisputeResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AcceptDisputeResponse]() + + + +### **POST** **/defendDispute** + +Defend a dispute + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **defendDisputeRequest** | **DefendDisputeRequest** | | + +#### Example usage + +```csharp +using Adyen.Disputes.Models; +using Adyen.Disputes.Services; + +// Example `DisputesService.DefendDispute` usage: +// Provide the following values: defendDisputeRequest +IDefendDisputeResponse response = await disputesService.DefendDisputeAsync( + DefendDisputeRequest defendDisputeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DefendDisputeResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DefendDisputeResponse]() + + + +### **POST** **/deleteDisputeDefenseDocument** + +Delete a defense document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **deleteDefenseDocumentRequest** | **DeleteDefenseDocumentRequest** | | + +#### Example usage + +```csharp +using Adyen.Disputes.Models; +using Adyen.Disputes.Services; + +// Example `DisputesService.DeleteDisputeDefenseDocument` usage: +// Provide the following values: deleteDefenseDocumentRequest +IDeleteDefenseDocumentResponse response = await disputesService.DeleteDisputeDefenseDocumentAsync( + DeleteDefenseDocumentRequest deleteDefenseDocumentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DeleteDefenseDocumentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DeleteDefenseDocumentResponse]() + + + +### **POST** **/retrieveApplicableDefenseReasons** + +Get applicable defense reasons + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **defenseReasonsRequest** | **DefenseReasonsRequest** | | + +#### Example usage + +```csharp +using Adyen.Disputes.Models; +using Adyen.Disputes.Services; + +// Example `DisputesService.RetrieveApplicableDefenseReasons` usage: +// Provide the following values: defenseReasonsRequest +IDefenseReasonsResponse response = await disputesService.RetrieveApplicableDefenseReasonsAsync( + DefenseReasonsRequest defenseReasonsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DefenseReasonsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DefenseReasonsResponse]() + + + +### **POST** **/supplyDefenseDocument** + +Supply a defense document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **supplyDefenseDocumentRequest** | **SupplyDefenseDocumentRequest** | | + +#### Example usage + +```csharp +using Adyen.Disputes.Models; +using Adyen.Disputes.Services; + +// Example `DisputesService.SupplyDefenseDocument` usage: +// Provide the following values: supplyDefenseDocumentRequest +ISupplyDefenseDocumentResponse response = await disputesService.SupplyDefenseDocumentAsync( + SupplyDefenseDocumentRequest supplyDefenseDocumentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SupplyDefenseDocumentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SupplyDefenseDocumentResponse]() + + diff --git a/docs/LegalEntityManagement/BusinessLinesService.md b/docs/LegalEntityManagement/BusinessLinesService.md new file mode 100644 index 000000000..981395b13 --- /dev/null +++ b/docs/LegalEntityManagement/BusinessLinesService.md @@ -0,0 +1,187 @@ +## Adyen.LegalEntityManagement.Services.BusinessLinesService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IBusinessLinesService businessLinesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateBusinessLine**](BusinessLinesService.md#createbusinessline) | **POST** /businessLines | Create a business line | +| [**DeleteBusinessLine**](BusinessLinesService.md#deletebusinessline) | **DELETE** /businessLines/{id} | Delete a business line | +| [**GetBusinessLine**](BusinessLinesService.md#getbusinessline) | **GET** /businessLines/{id} | Get a business line | +| [**UpdateBusinessLine**](BusinessLinesService.md#updatebusinessline) | **PATCH** /businessLines/{id} | Update a business line | + + +### **POST** **/businessLines** + +Create a business line + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **businessLineInfo** | **BusinessLineInfo** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `BusinessLinesService.CreateBusinessLine` usage: +// Provide the following values: businessLineInfo +IBusinessLine response = await businessLinesService.CreateBusinessLineAsync( + BusinessLineInfo businessLineInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BusinessLine result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BusinessLine]() + + + +### **DELETE** **/businessLines/{id}** + +Delete a business line + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the business line to be deleted. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `BusinessLinesService.DeleteBusinessLine` usage: +// Provide the following values: id +await businessLinesService.DeleteBusinessLineAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/businessLines/{id}** + +Get a business line + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the business line. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `BusinessLinesService.GetBusinessLine` usage: +// Provide the following values: id +IBusinessLine response = await businessLinesService.GetBusinessLineAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BusinessLine result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BusinessLine]() + + + +### **PATCH** **/businessLines/{id}** + +Update a business line + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the business line. | +| **businessLineInfoUpdate** | **BusinessLineInfoUpdate** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `BusinessLinesService.UpdateBusinessLine` usage: +// Provide the following values: id, businessLineInfoUpdate +IBusinessLine response = await businessLinesService.UpdateBusinessLineAsync( + string id, BusinessLineInfoUpdate businessLineInfoUpdate, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BusinessLine result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BusinessLine]() + + diff --git a/docs/LegalEntityManagement/DocumentsService.md b/docs/LegalEntityManagement/DocumentsService.md new file mode 100644 index 000000000..b910e1546 --- /dev/null +++ b/docs/LegalEntityManagement/DocumentsService.md @@ -0,0 +1,190 @@ +## Adyen.LegalEntityManagement.Services.DocumentsService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IDocumentsService documentsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**DeleteDocument**](DocumentsService.md#deletedocument) | **DELETE** /documents/{id} | Delete a document | +| [**GetDocument**](DocumentsService.md#getdocument) | **GET** /documents/{id} | Get a document | +| [**UpdateDocument**](DocumentsService.md#updatedocument) | **PATCH** /documents/{id} | Update a document | +| [**UploadDocumentForVerificationChecks**](DocumentsService.md#uploaddocumentforverificationchecks) | **POST** /documents | Upload a document for verification checks | + + +### **DELETE** **/documents/{id}** + +Delete a document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the document to be deleted. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `DocumentsService.DeleteDocument` usage: +// Provide the following values: id +await documentsService.DeleteDocumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/documents/{id}** + +Get a document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the document. | +| **skipContent** | [bool] | Do not load document content while fetching the document. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `DocumentsService.GetDocument` usage: +// Provide the following values: id, skipContent +IDocument response = await documentsService.GetDocumentAsync( + string id, Option skipContent = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Document result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Document]() + + + +### **PATCH** **/documents/{id}** + +Update a document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the document to be updated. | +| **xRequestedVerificationCode** | [string] | Use the requested verification code 0_0001 to resolve any suberrors associated with the document. Requested verification codes can only be used in your test environment. | +| **document** | **Document** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `DocumentsService.UpdateDocument` usage: +// Provide the following values: id, [HeaderParameter] xRequestedVerificationCode, document +IDocument response = await documentsService.UpdateDocumentAsync( + string id, Document document, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Document result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Document]() + + + +### **POST** **/documents** + +Upload a document for verification checks + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **xRequestedVerificationCode** | [string] | Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. | +| **document** | **Document** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `DocumentsService.UploadDocumentForVerificationChecks` usage: +// Provide the following values: [HeaderParameter] xRequestedVerificationCode, document +IDocument response = await documentsService.UploadDocumentForVerificationChecksAsync( + Document document, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Document result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Document]() + + diff --git a/docs/LegalEntityManagement/HostedOnboardingService.md b/docs/LegalEntityManagement/HostedOnboardingService.md new file mode 100644 index 000000000..b63597001 --- /dev/null +++ b/docs/LegalEntityManagement/HostedOnboardingService.md @@ -0,0 +1,147 @@ +## Adyen.LegalEntityManagement.Services.HostedOnboardingService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IHostedOnboardingService hostedOnboardingService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetLinkToAdyenhostedOnboardingPage**](HostedOnboardingService.md#getlinktoadyenhostedonboardingpage) | **POST** /legalEntities/{id}/onboardingLinks | Get a link to an Adyen-hosted onboarding page | +| [**GetOnboardingLinkTheme**](HostedOnboardingService.md#getonboardinglinktheme) | **GET** /themes/{id} | Get an onboarding link theme | +| [**ListHostedOnboardingPageThemes**](HostedOnboardingService.md#listhostedonboardingpagethemes) | **GET** /themes | Get a list of hosted onboarding page themes | + + +### **POST** **/legalEntities/{id}/onboardingLinks** + +Get a link to an Adyen-hosted onboarding page + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity | +| **onboardingLinkInfo** | **OnboardingLinkInfo** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `HostedOnboardingService.GetLinkToAdyenhostedOnboardingPage` usage: +// Provide the following values: id, onboardingLinkInfo +IOnboardingLink response = await hostedOnboardingService.GetLinkToAdyenhostedOnboardingPageAsync( + string id, OnboardingLinkInfo onboardingLinkInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out OnboardingLink result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[OnboardingLink]() + + + +### **GET** **/themes/{id}** + +Get an onboarding link theme + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the theme | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `HostedOnboardingService.GetOnboardingLinkTheme` usage: +// Provide the following values: id +IOnboardingTheme response = await hostedOnboardingService.GetOnboardingLinkThemeAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out OnboardingTheme result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[OnboardingTheme]() + + + +### **GET** **/themes** + +Get a list of hosted onboarding page themes + +#### Parameters +This endpoint does not need any parameter. +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `HostedOnboardingService.ListHostedOnboardingPageThemes` usage: +// Provide the following values: +IOnboardingThemes response = await hostedOnboardingService.ListHostedOnboardingPageThemesAsync( + + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out OnboardingThemes result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[OnboardingThemes]() + + diff --git a/docs/LegalEntityManagement/LegalEntitiesService.md b/docs/LegalEntityManagement/LegalEntitiesService.md new file mode 100644 index 000000000..c90da569c --- /dev/null +++ b/docs/LegalEntityManagement/LegalEntitiesService.md @@ -0,0 +1,261 @@ +## Adyen.LegalEntityManagement.Services.LegalEntitiesService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ILegalEntitiesService legalEntitiesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CheckLegalEntitysVerificationErrors**](LegalEntitiesService.md#checklegalentitysverificationerrors) | **POST** /legalEntities/{id}/checkVerificationErrors | Check a legal entity's verification errors | +| [**ConfirmDataReview**](LegalEntitiesService.md#confirmdatareview) | **POST** /legalEntities/{id}/confirmDataReview | Confirm data review | +| [**CreateLegalEntity**](LegalEntitiesService.md#createlegalentity) | **POST** /legalEntities | Create a legal entity | +| [**GetAllBusinessLinesUnderLegalEntity**](LegalEntitiesService.md#getallbusinesslinesunderlegalentity) | **GET** /legalEntities/{id}/businessLines | Get all business lines under a legal entity | +| [**GetLegalEntity**](LegalEntitiesService.md#getlegalentity) | **GET** /legalEntities/{id} | Get a legal entity | +| [**UpdateLegalEntity**](LegalEntitiesService.md#updatelegalentity) | **PATCH** /legalEntities/{id} | Update a legal entity | + + +### **POST** **/legalEntities/{id}/checkVerificationErrors** + +Check a legal entity's verification errors + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.CheckLegalEntitysVerificationErrors` usage: +// Provide the following values: id +IVerificationErrors response = await legalEntitiesService.CheckLegalEntitysVerificationErrorsAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out VerificationErrors result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[VerificationErrors]() + + + +### **POST** **/legalEntities/{id}/confirmDataReview** + +Confirm data review + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.ConfirmDataReview` usage: +// Provide the following values: id +IDataReviewConfirmationResponse response = await legalEntitiesService.ConfirmDataReviewAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DataReviewConfirmationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DataReviewConfirmationResponse]() + + + +### **POST** **/legalEntities** + +Create a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **xRequestedVerificationCode** | [string] | Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. | +| **legalEntityInfoRequiredType** | **LegalEntityInfoRequiredType** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.CreateLegalEntity` usage: +// Provide the following values: [HeaderParameter] xRequestedVerificationCode, legalEntityInfoRequiredType +ILegalEntity response = await legalEntitiesService.CreateLegalEntityAsync( + LegalEntityInfoRequiredType legalEntityInfoRequiredType, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out LegalEntity result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[LegalEntity]() + + + +### **GET** **/legalEntities/{id}/businessLines** + +Get all business lines under a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.GetAllBusinessLinesUnderLegalEntity` usage: +// Provide the following values: id +IBusinessLines response = await legalEntitiesService.GetAllBusinessLinesUnderLegalEntityAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BusinessLines result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BusinessLines]() + + + +### **GET** **/legalEntities/{id}** + +Get a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.GetLegalEntity` usage: +// Provide the following values: id +ILegalEntity response = await legalEntitiesService.GetLegalEntityAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out LegalEntity result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[LegalEntity]() + + + +### **PATCH** **/legalEntities/{id}** + +Update a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. | +| **xRequestedVerificationCode** | [string] | Use the requested verification code 0_0001 to resolve any suberrors associated with the legal entity. Requested verification codes can only be used in your test environment. | +| **legalEntityInfo** | **LegalEntityInfo** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `LegalEntitiesService.UpdateLegalEntity` usage: +// Provide the following values: id, [HeaderParameter] xRequestedVerificationCode, legalEntityInfo +ILegalEntity response = await legalEntitiesService.UpdateLegalEntityAsync( + string id, LegalEntityInfo legalEntityInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out LegalEntity result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[LegalEntity]() + + diff --git a/docs/LegalEntityManagement/PCIQuestionnairesService.md b/docs/LegalEntityManagement/PCIQuestionnairesService.md new file mode 100644 index 000000000..d15e4c328 --- /dev/null +++ b/docs/LegalEntityManagement/PCIQuestionnairesService.md @@ -0,0 +1,226 @@ +## Adyen.LegalEntityManagement.Services.PCIQuestionnairesService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPCIQuestionnairesService pCIQuestionnairesService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CalculatePciStatusOfLegalEntity**](PCIQuestionnairesService.md#calculatepcistatusoflegalentity) | **POST** /legalEntities/{id}/pciQuestionnaires/signingRequired | Calculate PCI status of a legal entity | +| [**GeneratePciQuestionnaire**](PCIQuestionnairesService.md#generatepciquestionnaire) | **POST** /legalEntities/{id}/pciQuestionnaires/generatePciTemplates | Generate PCI questionnaire | +| [**GetPciQuestionnaire**](PCIQuestionnairesService.md#getpciquestionnaire) | **GET** /legalEntities/{id}/pciQuestionnaires/{pciid} | Get PCI questionnaire | +| [**GetPciQuestionnaireDetails**](PCIQuestionnairesService.md#getpciquestionnairedetails) | **GET** /legalEntities/{id}/pciQuestionnaires | Get PCI questionnaire details | +| [**SignPciQuestionnaire**](PCIQuestionnairesService.md#signpciquestionnaire) | **POST** /legalEntities/{id}/pciQuestionnaires/signPciTemplates | Sign PCI questionnaire | + + +### **POST** **/legalEntities/{id}/pciQuestionnaires/signingRequired** + +Calculate PCI status of a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity to calculate PCI status. | +| **calculatePciStatusRequest** | **CalculatePciStatusRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `PCIQuestionnairesService.CalculatePciStatusOfLegalEntity` usage: +// Provide the following values: id, calculatePciStatusRequest +ICalculatePciStatusResponse response = await pCIQuestionnairesService.CalculatePciStatusOfLegalEntityAsync( + string id, CalculatePciStatusRequest calculatePciStatusRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CalculatePciStatusResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CalculatePciStatusResponse]() + + + +### **POST** **/legalEntities/{id}/pciQuestionnaires/generatePciTemplates** + +Generate PCI questionnaire + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity to get PCI questionnaire information. | +| **generatePciDescriptionRequest** | **GeneratePciDescriptionRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `PCIQuestionnairesService.GeneratePciQuestionnaire` usage: +// Provide the following values: id, generatePciDescriptionRequest +IGeneratePciDescriptionResponse response = await pCIQuestionnairesService.GeneratePciQuestionnaireAsync( + string id, GeneratePciDescriptionRequest generatePciDescriptionRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GeneratePciDescriptionResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GeneratePciDescriptionResponse]() + + + +### **GET** **/legalEntities/{id}/pciQuestionnaires/{pciid}** + +Get PCI questionnaire + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The legal entity ID of the individual who signed the PCI questionnaire. | +| **pciid** | [string] | The unique identifier of the signed PCI questionnaire. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `PCIQuestionnairesService.GetPciQuestionnaire` usage: +// Provide the following values: id, pciid +IGetPciQuestionnaireResponse response = await pCIQuestionnairesService.GetPciQuestionnaireAsync( + string id, string pciid, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetPciQuestionnaireResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetPciQuestionnaireResponse]() + + + +### **GET** **/legalEntities/{id}/pciQuestionnaires** + +Get PCI questionnaire details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity to get PCI questionnaire information. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `PCIQuestionnairesService.GetPciQuestionnaireDetails` usage: +// Provide the following values: id +IGetPciQuestionnaireInfosResponse response = await pCIQuestionnairesService.GetPciQuestionnaireDetailsAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetPciQuestionnaireInfosResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetPciQuestionnaireInfosResponse]() + + + +### **POST** **/legalEntities/{id}/pciQuestionnaires/signPciTemplates** + +Sign PCI questionnaire + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The legal entity ID of the user that has a contractual relationship with your platform. | +| **pciSigningRequest** | **PciSigningRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `PCIQuestionnairesService.SignPciQuestionnaire` usage: +// Provide the following values: id, pciSigningRequest +IPciSigningResponse response = await pCIQuestionnairesService.SignPciQuestionnaireAsync( + string id, PciSigningRequest pciSigningRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PciSigningResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PciSigningResponse]() + + diff --git a/docs/LegalEntityManagement/TaxEDeliveryConsentService.md b/docs/LegalEntityManagement/TaxEDeliveryConsentService.md new file mode 100644 index 000000000..e3ca75019 --- /dev/null +++ b/docs/LegalEntityManagement/TaxEDeliveryConsentService.md @@ -0,0 +1,115 @@ +## Adyen.LegalEntityManagement.Services.TaxEDeliveryConsentService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITaxEDeliveryConsentService taxEDeliveryConsentService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CheckStatusOfConsentForElectronicDeliveryOfTaxForms**](TaxEDeliveryConsentService.md#checkstatusofconsentforelectronicdeliveryoftaxforms) | **POST** /legalEntities/{id}/checkTaxElectronicDeliveryConsent | Check the status of consent for electronic delivery of tax forms | +| [**SetConsentStatusForElectronicDeliveryOfTaxForms**](TaxEDeliveryConsentService.md#setconsentstatusforelectronicdeliveryoftaxforms) | **POST** /legalEntities/{id}/setTaxElectronicDeliveryConsent | Set the consent status for electronic delivery of tax forms | + + +### **POST** **/legalEntities/{id}/checkTaxElectronicDeliveryConsent** + +Check the status of consent for electronic delivery of tax forms + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TaxEDeliveryConsentService.CheckStatusOfConsentForElectronicDeliveryOfTaxForms` usage: +// Provide the following values: id +ICheckTaxElectronicDeliveryConsentResponse response = await taxEDeliveryConsentService.CheckStatusOfConsentForElectronicDeliveryOfTaxFormsAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CheckTaxElectronicDeliveryConsentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CheckTaxElectronicDeliveryConsentResponse]() + + + +### **POST** **/legalEntities/{id}/setTaxElectronicDeliveryConsent** + +Set the consent status for electronic delivery of tax forms + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | +| **setTaxElectronicDeliveryConsentRequest** | **SetTaxElectronicDeliveryConsentRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TaxEDeliveryConsentService.SetConsentStatusForElectronicDeliveryOfTaxForms` usage: +// Provide the following values: id, setTaxElectronicDeliveryConsentRequest +await taxEDeliveryConsentService.SetConsentStatusForElectronicDeliveryOfTaxFormsAsync( + string id, SetTaxElectronicDeliveryConsentRequest setTaxElectronicDeliveryConsentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/LegalEntityManagement/TermsOfServiceService.md b/docs/LegalEntityManagement/TermsOfServiceService.md new file mode 100644 index 000000000..a9fb1933f --- /dev/null +++ b/docs/LegalEntityManagement/TermsOfServiceService.md @@ -0,0 +1,227 @@ +## Adyen.LegalEntityManagement.Services.TermsOfServiceService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITermsOfServiceService termsOfServiceService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AcceptTermsOfService**](TermsOfServiceService.md#accepttermsofservice) | **PATCH** /legalEntities/{id}/termsOfService/{termsofservicedocumentid} | Accept Terms of Service | +| [**GetAcceptedTermsOfServiceDocument**](TermsOfServiceService.md#getacceptedtermsofservicedocument) | **GET** /legalEntities/{id}/acceptedTermsOfServiceDocument/{termsofserviceacceptancereference} | Get accepted Terms of Service document | +| [**GetTermsOfServiceDocument**](TermsOfServiceService.md#gettermsofservicedocument) | **POST** /legalEntities/{id}/termsOfService | Get Terms of Service document | +| [**GetTermsOfServiceInformationForLegalEntity**](TermsOfServiceService.md#gettermsofserviceinformationforlegalentity) | **GET** /legalEntities/{id}/termsOfServiceAcceptanceInfos | Get Terms of Service information for a legal entity | +| [**GetTermsOfServiceStatus**](TermsOfServiceService.md#gettermsofservicestatus) | **GET** /legalEntities/{id}/termsOfServiceStatus | Get Terms of Service status | + + +### **PATCH** **/legalEntities/{id}/termsOfService/{termsofservicedocumentid}** + +Accept Terms of Service + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. For legal representatives of individuals, this is the ID of the individual. | +| **termsofservicedocumentid** | [string] | The unique identifier of the Terms of Service document. | +| **acceptTermsOfServiceRequest** | **AcceptTermsOfServiceRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TermsOfServiceService.AcceptTermsOfService` usage: +// Provide the following values: id, termsofservicedocumentid, acceptTermsOfServiceRequest +IAcceptTermsOfServiceResponse response = await termsOfServiceService.AcceptTermsOfServiceAsync( + string id, string termsofservicedocumentid, AcceptTermsOfServiceRequest acceptTermsOfServiceRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AcceptTermsOfServiceResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AcceptTermsOfServiceResponse]() + + + +### **GET** **/legalEntities/{id}/acceptedTermsOfServiceDocument/{termsofserviceacceptancereference}** + +Get accepted Terms of Service document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorship, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | +| **termsofserviceacceptancereference** | [string] | An Adyen-generated reference for the accepted Terms of Service. | +| **termsOfServiceDocumentFormat** | [string] | The format of the Terms of Service document. Possible values: **JSON**, **PDF**, or **TXT** | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TermsOfServiceService.GetAcceptedTermsOfServiceDocument` usage: +// Provide the following values: id, termsofserviceacceptancereference, termsOfServiceDocumentFormat +IGetAcceptedTermsOfServiceDocumentResponse response = await termsOfServiceService.GetAcceptedTermsOfServiceDocumentAsync( + string id, string termsofserviceacceptancereference, Option termsOfServiceDocumentFormat = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetAcceptedTermsOfServiceDocumentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetAcceptedTermsOfServiceDocumentResponse]() + + + +### **POST** **/legalEntities/{id}/termsOfService** + +Get Terms of Service document + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | +| **getTermsOfServiceDocumentRequest** | **GetTermsOfServiceDocumentRequest** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TermsOfServiceService.GetTermsOfServiceDocument` usage: +// Provide the following values: id, getTermsOfServiceDocumentRequest +IGetTermsOfServiceDocumentResponse response = await termsOfServiceService.GetTermsOfServiceDocumentAsync( + string id, GetTermsOfServiceDocumentRequest getTermsOfServiceDocumentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetTermsOfServiceDocumentResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetTermsOfServiceDocumentResponse]() + + + +### **GET** **/legalEntities/{id}/termsOfServiceAcceptanceInfos** + +Get Terms of Service information for a legal entity + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TermsOfServiceService.GetTermsOfServiceInformationForLegalEntity` usage: +// Provide the following values: id +IGetTermsOfServiceAcceptanceInfosResponse response = await termsOfServiceService.GetTermsOfServiceInformationForLegalEntityAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetTermsOfServiceAcceptanceInfosResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetTermsOfServiceAcceptanceInfosResponse]() + + + +### **GET** **/legalEntities/{id}/termsOfServiceStatus** + +Get Terms of Service status + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the legal entity. For sole proprietorships, this is the individual legal entity ID of the owner. For organizations, this is the ID of the organization. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TermsOfServiceService.GetTermsOfServiceStatus` usage: +// Provide the following values: id +ICalculateTermsOfServiceStatusResponse response = await termsOfServiceService.GetTermsOfServiceStatusAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CalculateTermsOfServiceStatusResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CalculateTermsOfServiceStatusResponse]() + + diff --git a/docs/LegalEntityManagement/TransferInstrumentsService.md b/docs/LegalEntityManagement/TransferInstrumentsService.md new file mode 100644 index 000000000..92d46e3c6 --- /dev/null +++ b/docs/LegalEntityManagement/TransferInstrumentsService.md @@ -0,0 +1,189 @@ +## Adyen.LegalEntityManagement.Services.TransferInstrumentsService + +#### API Base-Path: **https://kyc-test.adyen.com/lem/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.LegalEntityManagement.Extensions; +using Adyen.LegalEntityManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureLegalEntityManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransferInstrumentsService transferInstrumentsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateTransferInstrument**](TransferInstrumentsService.md#createtransferinstrument) | **POST** /transferInstruments | Create a transfer instrument | +| [**DeleteTransferInstrument**](TransferInstrumentsService.md#deletetransferinstrument) | **DELETE** /transferInstruments/{id} | Delete a transfer instrument | +| [**GetTransferInstrument**](TransferInstrumentsService.md#gettransferinstrument) | **GET** /transferInstruments/{id} | Get a transfer instrument | +| [**UpdateTransferInstrument**](TransferInstrumentsService.md#updatetransferinstrument) | **PATCH** /transferInstruments/{id} | Update a transfer instrument | + + +### **POST** **/transferInstruments** + +Create a transfer instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **xRequestedVerificationCode** | [string] | Use a suberror code as your requested verification code. You can include one code at a time in your request header. Requested verification codes can only be used in your test environment. | +| **transferInstrumentInfo** | **TransferInstrumentInfo** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TransferInstrumentsService.CreateTransferInstrument` usage: +// Provide the following values: [HeaderParameter] xRequestedVerificationCode, transferInstrumentInfo +ITransferInstrument response = await transferInstrumentsService.CreateTransferInstrumentAsync( + TransferInstrumentInfo transferInstrumentInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferInstrument]() + + + +### **DELETE** **/transferInstruments/{id}** + +Delete a transfer instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the transfer instrument to be deleted. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TransferInstrumentsService.DeleteTransferInstrument` usage: +// Provide the following values: id +await transferInstrumentsService.DeleteTransferInstrumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/transferInstruments/{id}** + +Get a transfer instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the transfer instrument. | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TransferInstrumentsService.GetTransferInstrument` usage: +// Provide the following values: id +ITransferInstrument response = await transferInstrumentsService.GetTransferInstrumentAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferInstrument]() + + + +### **PATCH** **/transferInstruments/{id}** + +Update a transfer instrument + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the transfer instrument. | +| **xRequestedVerificationCode** | [string] | Use the requested verification code 0_0001 to resolve any suberrors associated with the transfer instrument. Requested verification codes can only be used in your test environment. | +| **transferInstrumentInfo** | **TransferInstrumentInfo** | | + +#### Example usage + +```csharp +using Adyen.LegalEntityManagement.Models; +using Adyen.LegalEntityManagement.Services; + +// Example `TransferInstrumentsService.UpdateTransferInstrument` usage: +// Provide the following values: id, [HeaderParameter] xRequestedVerificationCode, transferInstrumentInfo +ITransferInstrument response = await transferInstrumentsService.UpdateTransferInstrumentAsync( + string id, TransferInstrumentInfo transferInstrumentInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferInstrument result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferInstrument]() + + diff --git a/docs/Management/APICredentialsCompanyLevelService.md b/docs/Management/APICredentialsCompanyLevelService.md new file mode 100644 index 000000000..403ad47f0 --- /dev/null +++ b/docs/Management/APICredentialsCompanyLevelService.md @@ -0,0 +1,192 @@ +## Adyen.Management.Services.APICredentialsCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAPICredentialsCompanyLevelService aPICredentialsCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateApiCredential**](APICredentialsCompanyLevelService.md#createapicredential) | **POST** /companies/{companyId}/apiCredentials | Create an API credential. | +| [**GetApiCredential**](APICredentialsCompanyLevelService.md#getapicredential) | **GET** /companies/{companyId}/apiCredentials/{apiCredentialId} | Get an API credential | +| [**ListApiCredentials**](APICredentialsCompanyLevelService.md#listapicredentials) | **GET** /companies/{companyId}/apiCredentials | Get a list of API credentials | +| [**UpdateApiCredential**](APICredentialsCompanyLevelService.md#updateapicredential) | **PATCH** /companies/{companyId}/apiCredentials/{apiCredentialId} | Update an API credential. | + + +### **POST** **/companies/{companyId}/apiCredentials** + +Create an API credential. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **createCompanyApiCredentialRequest** | **CreateCompanyApiCredentialRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsCompanyLevelService.CreateApiCredential` usage: +// Provide the following values: companyId, createCompanyApiCredentialRequest +ICreateCompanyApiCredentialResponse response = await aPICredentialsCompanyLevelService.CreateApiCredentialAsync( + string companyId, CreateCompanyApiCredentialRequest createCompanyApiCredentialRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateCompanyApiCredentialResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateCompanyApiCredentialResponse]() + + + +### **GET** **/companies/{companyId}/apiCredentials/{apiCredentialId}** + +Get an API credential + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsCompanyLevelService.GetApiCredential` usage: +// Provide the following values: companyId, apiCredentialId +ICompanyApiCredential response = await aPICredentialsCompanyLevelService.GetApiCredentialAsync( + string companyId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CompanyApiCredential result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CompanyApiCredential]() + + + +### **GET** **/companies/{companyId}/apiCredentials** + +Get a list of API credentials + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsCompanyLevelService.ListApiCredentials` usage: +// Provide the following values: companyId, pageNumber, pageSize +IListCompanyApiCredentialsResponse response = await aPICredentialsCompanyLevelService.ListApiCredentialsAsync( + string companyId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListCompanyApiCredentialsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListCompanyApiCredentialsResponse]() + + + +### **PATCH** **/companies/{companyId}/apiCredentials/{apiCredentialId}** + +Update an API credential. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **updateCompanyApiCredentialRequest** | **UpdateCompanyApiCredentialRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsCompanyLevelService.UpdateApiCredential` usage: +// Provide the following values: companyId, apiCredentialId, updateCompanyApiCredentialRequest +ICompanyApiCredential response = await aPICredentialsCompanyLevelService.UpdateApiCredentialAsync( + string companyId, string apiCredentialId, UpdateCompanyApiCredentialRequest updateCompanyApiCredentialRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CompanyApiCredential result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CompanyApiCredential]() + + diff --git a/docs/Management/APICredentialsMerchantLevelService.md b/docs/Management/APICredentialsMerchantLevelService.md new file mode 100644 index 000000000..a988dc7e1 --- /dev/null +++ b/docs/Management/APICredentialsMerchantLevelService.md @@ -0,0 +1,192 @@ +## Adyen.Management.Services.APICredentialsMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAPICredentialsMerchantLevelService aPICredentialsMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateApiCredential**](APICredentialsMerchantLevelService.md#createapicredential) | **POST** /merchants/{merchantId}/apiCredentials | Create an API credential | +| [**GetApiCredential**](APICredentialsMerchantLevelService.md#getapicredential) | **GET** /merchants/{merchantId}/apiCredentials/{apiCredentialId} | Get an API credential | +| [**ListApiCredentials**](APICredentialsMerchantLevelService.md#listapicredentials) | **GET** /merchants/{merchantId}/apiCredentials | Get a list of API credentials | +| [**UpdateApiCredential**](APICredentialsMerchantLevelService.md#updateapicredential) | **PATCH** /merchants/{merchantId}/apiCredentials/{apiCredentialId} | Update an API credential | + + +### **POST** **/merchants/{merchantId}/apiCredentials** + +Create an API credential + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **createMerchantApiCredentialRequest** | **CreateMerchantApiCredentialRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsMerchantLevelService.CreateApiCredential` usage: +// Provide the following values: merchantId, createMerchantApiCredentialRequest +ICreateApiCredentialResponse response = await aPICredentialsMerchantLevelService.CreateApiCredentialAsync( + string merchantId, CreateMerchantApiCredentialRequest createMerchantApiCredentialRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateApiCredentialResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateApiCredentialResponse]() + + + +### **GET** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}** + +Get an API credential + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsMerchantLevelService.GetApiCredential` usage: +// Provide the following values: merchantId, apiCredentialId +IApiCredential response = await aPICredentialsMerchantLevelService.GetApiCredentialAsync( + string merchantId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ApiCredential result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ApiCredential]() + + + +### **GET** **/merchants/{merchantId}/apiCredentials** + +Get a list of API credentials + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsMerchantLevelService.ListApiCredentials` usage: +// Provide the following values: merchantId, pageNumber, pageSize +IListMerchantApiCredentialsResponse response = await aPICredentialsMerchantLevelService.ListApiCredentialsAsync( + string merchantId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListMerchantApiCredentialsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListMerchantApiCredentialsResponse]() + + + +### **PATCH** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}** + +Update an API credential + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **updateMerchantApiCredentialRequest** | **UpdateMerchantApiCredentialRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APICredentialsMerchantLevelService.UpdateApiCredential` usage: +// Provide the following values: merchantId, apiCredentialId, updateMerchantApiCredentialRequest +IApiCredential response = await aPICredentialsMerchantLevelService.UpdateApiCredentialAsync( + string merchantId, string apiCredentialId, UpdateMerchantApiCredentialRequest updateMerchantApiCredentialRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ApiCredential result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ApiCredential]() + + diff --git a/docs/Management/APIKeyCompanyLevelService.md b/docs/Management/APIKeyCompanyLevelService.md new file mode 100644 index 000000000..1aa09ce70 --- /dev/null +++ b/docs/Management/APIKeyCompanyLevelService.md @@ -0,0 +1,79 @@ +## Adyen.Management.Services.APIKeyCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAPIKeyCompanyLevelService aPIKeyCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateNewApiKey**](APIKeyCompanyLevelService.md#generatenewapikey) | **POST** /companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey | Generate new API key | + + +### **POST** **/companies/{companyId}/apiCredentials/{apiCredentialId}/generateApiKey** + +Generate new API key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APIKeyCompanyLevelService.GenerateNewApiKey` usage: +// Provide the following values: companyId, apiCredentialId +IGenerateApiKeyResponse response = await aPIKeyCompanyLevelService.GenerateNewApiKeyAsync( + string companyId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateApiKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateApiKeyResponse]() + + diff --git a/docs/Management/APIKeyMerchantLevelService.md b/docs/Management/APIKeyMerchantLevelService.md new file mode 100644 index 000000000..be4b34e36 --- /dev/null +++ b/docs/Management/APIKeyMerchantLevelService.md @@ -0,0 +1,79 @@ +## Adyen.Management.Services.APIKeyMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAPIKeyMerchantLevelService aPIKeyMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateNewApiKey**](APIKeyMerchantLevelService.md#generatenewapikey) | **POST** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey | Generate new API key | + + +### **POST** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateApiKey** + +Generate new API key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `APIKeyMerchantLevelService.GenerateNewApiKey` usage: +// Provide the following values: merchantId, apiCredentialId +IGenerateApiKeyResponse response = await aPIKeyMerchantLevelService.GenerateNewApiKeyAsync( + string merchantId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateApiKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateApiKeyResponse]() + + diff --git a/docs/Management/AccountCompanyLevelService.md b/docs/Management/AccountCompanyLevelService.md new file mode 100644 index 000000000..d4daaa4c6 --- /dev/null +++ b/docs/Management/AccountCompanyLevelService.md @@ -0,0 +1,153 @@ +## Adyen.Management.Services.AccountCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAccountCompanyLevelService accountCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetCompanyAccount**](AccountCompanyLevelService.md#getcompanyaccount) | **GET** /companies/{companyId} | Get a company account | +| [**ListCompanyAccounts**](AccountCompanyLevelService.md#listcompanyaccounts) | **GET** /companies | Get a list of company accounts | +| [**ListMerchantAccounts**](AccountCompanyLevelService.md#listmerchantaccounts) | **GET** /companies/{companyId}/merchants | Get a list of merchant accounts | + + +### **GET** **/companies/{companyId}** + +Get a company account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountCompanyLevelService.GetCompanyAccount` usage: +// Provide the following values: companyId +ICompany response = await accountCompanyLevelService.GetCompanyAccountAsync( + string companyId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Company result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Company]() + + + +### **GET** **/companies** + +Get a list of company accounts + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountCompanyLevelService.ListCompanyAccounts` usage: +// Provide the following values: pageNumber, pageSize +IListCompanyResponse response = await accountCompanyLevelService.ListCompanyAccountsAsync( + Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListCompanyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListCompanyResponse]() + + + +### **GET** **/companies/{companyId}/merchants** + +Get a list of merchant accounts + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountCompanyLevelService.ListMerchantAccounts` usage: +// Provide the following values: companyId, pageNumber, pageSize +IListMerchantResponse response = await accountCompanyLevelService.ListMerchantAccountsAsync( + string companyId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListMerchantResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListMerchantResponse]() + + diff --git a/docs/Management/AccountMerchantLevelService.md b/docs/Management/AccountMerchantLevelService.md new file mode 100644 index 000000000..9a12e799d --- /dev/null +++ b/docs/Management/AccountMerchantLevelService.md @@ -0,0 +1,187 @@ +## Adyen.Management.Services.AccountMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAccountMerchantLevelService accountMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateMerchantAccount**](AccountMerchantLevelService.md#createmerchantaccount) | **POST** /merchants | Create a merchant account | +| [**GetMerchantAccount**](AccountMerchantLevelService.md#getmerchantaccount) | **GET** /merchants/{merchantId} | Get a merchant account | +| [**ListMerchantAccounts**](AccountMerchantLevelService.md#listmerchantaccounts) | **GET** /merchants | Get a list of merchant accounts | +| [**RequestToActivateMerchantAccount**](AccountMerchantLevelService.md#requesttoactivatemerchantaccount) | **POST** /merchants/{merchantId}/activate | Request to activate a merchant account | + + +### **POST** **/merchants** + +Create a merchant account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createMerchantRequest** | **CreateMerchantRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountMerchantLevelService.CreateMerchantAccount` usage: +// Provide the following values: createMerchantRequest +ICreateMerchantResponse response = await accountMerchantLevelService.CreateMerchantAccountAsync( + CreateMerchantRequest createMerchantRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateMerchantResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateMerchantResponse]() + + + +### **GET** **/merchants/{merchantId}** + +Get a merchant account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountMerchantLevelService.GetMerchantAccount` usage: +// Provide the following values: merchantId +IMerchant response = await accountMerchantLevelService.GetMerchantAccountAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Merchant result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Merchant]() + + + +### **GET** **/merchants** + +Get a list of merchant accounts + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountMerchantLevelService.ListMerchantAccounts` usage: +// Provide the following values: pageNumber, pageSize +IListMerchantResponse response = await accountMerchantLevelService.ListMerchantAccountsAsync( + Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListMerchantResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListMerchantResponse]() + + + +### **POST** **/merchants/{merchantId}/activate** + +Request to activate a merchant account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountMerchantLevelService.RequestToActivateMerchantAccount` usage: +// Provide the following values: merchantId +IRequestActivationResponse response = await accountMerchantLevelService.RequestToActivateMerchantAccountAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out RequestActivationResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[RequestActivationResponse]() + + diff --git a/docs/Management/AccountStoreLevelService.md b/docs/Management/AccountStoreLevelService.md new file mode 100644 index 000000000..c56c6c210 --- /dev/null +++ b/docs/Management/AccountStoreLevelService.md @@ -0,0 +1,341 @@ +## Adyen.Management.Services.AccountStoreLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAccountStoreLevelService accountStoreLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateStore**](AccountStoreLevelService.md#createstore) | **POST** /stores | Create a store | +| [**CreateStoreByMerchantId**](AccountStoreLevelService.md#createstorebymerchantid) | **POST** /merchants/{merchantId}/stores | Create a store | +| [**GetStore**](AccountStoreLevelService.md#getstore) | **GET** /merchants/{merchantId}/stores/{storeId} | Get a store | +| [**GetStoreById**](AccountStoreLevelService.md#getstorebyid) | **GET** /stores/{storeId} | Get a store | +| [**ListStores**](AccountStoreLevelService.md#liststores) | **GET** /stores | Get a list of stores | +| [**ListStoresByMerchantId**](AccountStoreLevelService.md#liststoresbymerchantid) | **GET** /merchants/{merchantId}/stores | Get a list of stores | +| [**UpdateStore**](AccountStoreLevelService.md#updatestore) | **PATCH** /merchants/{merchantId}/stores/{storeId} | Update a store | +| [**UpdateStoreById**](AccountStoreLevelService.md#updatestorebyid) | **PATCH** /stores/{storeId} | Update a store | + + +### **POST** **/stores** + +Create a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeCreationWithMerchantCodeRequest** | **StoreCreationWithMerchantCodeRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.CreateStore` usage: +// Provide the following values: storeCreationWithMerchantCodeRequest +IStore response = await accountStoreLevelService.CreateStoreAsync( + StoreCreationWithMerchantCodeRequest storeCreationWithMerchantCodeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + + +### **POST** **/merchants/{merchantId}/stores** + +Create a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeCreationRequest** | **StoreCreationRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.CreateStoreByMerchantId` usage: +// Provide the following values: merchantId, storeCreationRequest +IStore response = await accountStoreLevelService.CreateStoreByMerchantIdAsync( + string merchantId, StoreCreationRequest storeCreationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + + +### **GET** **/merchants/{merchantId}/stores/{storeId}** + +Get a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeId** | [string] | The unique identifier of the store. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.GetStore` usage: +// Provide the following values: merchantId, storeId +IStore response = await accountStoreLevelService.GetStoreAsync( + string merchantId, string storeId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + + +### **GET** **/stores/{storeId}** + +Get a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.GetStoreById` usage: +// Provide the following values: storeId +IStore response = await accountStoreLevelService.GetStoreByIdAsync( + string storeId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + + +### **GET** **/stores** + +Get a list of stores + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | +| **reference** | [string] | The reference of the store. | +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.ListStores` usage: +// Provide the following values: pageNumber, pageSize, reference, merchantId +IListStoresResponse response = await accountStoreLevelService.ListStoresAsync( + Option pageNumber = default, Option pageSize = default, Option reference = default, Option merchantId = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListStoresResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListStoresResponse]() + + + +### **GET** **/merchants/{merchantId}/stores** + +Get a list of stores + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | +| **reference** | [string] | The reference of the store. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.ListStoresByMerchantId` usage: +// Provide the following values: merchantId, pageNumber, pageSize, reference +IListStoresResponse response = await accountStoreLevelService.ListStoresByMerchantIdAsync( + string merchantId, Option pageNumber = default, Option pageSize = default, Option reference = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListStoresResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListStoresResponse]() + + + +### **PATCH** **/merchants/{merchantId}/stores/{storeId}** + +Update a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeId** | [string] | The unique identifier of the store. | +| **updateStoreRequest** | **UpdateStoreRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.UpdateStore` usage: +// Provide the following values: merchantId, storeId, updateStoreRequest +IStore response = await accountStoreLevelService.UpdateStoreAsync( + string merchantId, string storeId, UpdateStoreRequest updateStoreRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + + +### **PATCH** **/stores/{storeId}** + +Update a store + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | +| **updateStoreRequest** | **UpdateStoreRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AccountStoreLevelService.UpdateStoreById` usage: +// Provide the following values: storeId, updateStoreRequest +IStore response = await accountStoreLevelService.UpdateStoreByIdAsync( + string storeId, UpdateStoreRequest updateStoreRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Store result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Store]() + + diff --git a/docs/Management/AllowedOriginsCompanyLevelService.md b/docs/Management/AllowedOriginsCompanyLevelService.md new file mode 100644 index 000000000..ecc2c0ab8 --- /dev/null +++ b/docs/Management/AllowedOriginsCompanyLevelService.md @@ -0,0 +1,193 @@ +## Adyen.Management.Services.AllowedOriginsCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAllowedOriginsCompanyLevelService allowedOriginsCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateAllowedOrigin**](AllowedOriginsCompanyLevelService.md#createallowedorigin) | **POST** /companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins | Create an allowed origin | +| [**DeleteAllowedOrigin**](AllowedOriginsCompanyLevelService.md#deleteallowedorigin) | **DELETE** /companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId} | Delete an allowed origin | +| [**GetAllowedOrigin**](AllowedOriginsCompanyLevelService.md#getallowedorigin) | **GET** /companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId} | Get an allowed origin | +| [**ListAllowedOrigins**](AllowedOriginsCompanyLevelService.md#listallowedorigins) | **GET** /companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins | Get a list of allowed origins | + + +### **POST** **/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins** + +Create an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **allowedOrigin** | **AllowedOrigin** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsCompanyLevelService.CreateAllowedOrigin` usage: +// Provide the following values: companyId, apiCredentialId, allowedOrigin +IAllowedOrigin response = await allowedOriginsCompanyLevelService.CreateAllowedOriginAsync( + string companyId, string apiCredentialId, AllowedOrigin allowedOrigin, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **DELETE** **/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}** + +Delete an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsCompanyLevelService.DeleteAllowedOrigin` usage: +// Provide the following values: companyId, apiCredentialId, originId +await allowedOriginsCompanyLevelService.DeleteAllowedOriginAsync( + string companyId, string apiCredentialId, string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}** + +Get an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsCompanyLevelService.GetAllowedOrigin` usage: +// Provide the following values: companyId, apiCredentialId, originId +IAllowedOrigin response = await allowedOriginsCompanyLevelService.GetAllowedOriginAsync( + string companyId, string apiCredentialId, string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **GET** **/companies/{companyId}/apiCredentials/{apiCredentialId}/allowedOrigins** + +Get a list of allowed origins + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsCompanyLevelService.ListAllowedOrigins` usage: +// Provide the following values: companyId, apiCredentialId +IAllowedOriginsResponse response = await allowedOriginsCompanyLevelService.ListAllowedOriginsAsync( + string companyId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOriginsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOriginsResponse]() + + diff --git a/docs/Management/AllowedOriginsMerchantLevelService.md b/docs/Management/AllowedOriginsMerchantLevelService.md new file mode 100644 index 000000000..8ab62f9f9 --- /dev/null +++ b/docs/Management/AllowedOriginsMerchantLevelService.md @@ -0,0 +1,193 @@ +## Adyen.Management.Services.AllowedOriginsMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAllowedOriginsMerchantLevelService allowedOriginsMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateAllowedOrigin**](AllowedOriginsMerchantLevelService.md#createallowedorigin) | **POST** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins | Create an allowed origin | +| [**DeleteAllowedOrigin**](AllowedOriginsMerchantLevelService.md#deleteallowedorigin) | **DELETE** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId} | Delete an allowed origin | +| [**GetAllowedOrigin**](AllowedOriginsMerchantLevelService.md#getallowedorigin) | **GET** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId} | Get an allowed origin | +| [**ListAllowedOrigins**](AllowedOriginsMerchantLevelService.md#listallowedorigins) | **GET** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins | Get a list of allowed origins | + + +### **POST** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins** + +Create an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **allowedOrigin** | **AllowedOrigin** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsMerchantLevelService.CreateAllowedOrigin` usage: +// Provide the following values: merchantId, apiCredentialId, allowedOrigin +IAllowedOrigin response = await allowedOriginsMerchantLevelService.CreateAllowedOriginAsync( + string merchantId, string apiCredentialId, AllowedOrigin allowedOrigin, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **DELETE** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}** + +Delete an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsMerchantLevelService.DeleteAllowedOrigin` usage: +// Provide the following values: merchantId, apiCredentialId, originId +await allowedOriginsMerchantLevelService.DeleteAllowedOriginAsync( + string merchantId, string apiCredentialId, string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins/{originId}** + +Get an allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsMerchantLevelService.GetAllowedOrigin` usage: +// Provide the following values: merchantId, apiCredentialId, originId +IAllowedOrigin response = await allowedOriginsMerchantLevelService.GetAllowedOriginAsync( + string merchantId, string apiCredentialId, string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **GET** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/allowedOrigins** + +Get a list of allowed origins + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AllowedOriginsMerchantLevelService.ListAllowedOrigins` usage: +// Provide the following values: merchantId, apiCredentialId +IAllowedOriginsResponse response = await allowedOriginsMerchantLevelService.ListAllowedOriginsAsync( + string merchantId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOriginsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOriginsResponse]() + + diff --git a/docs/Management/AndroidFilesCompanyLevelService.md b/docs/Management/AndroidFilesCompanyLevelService.md new file mode 100644 index 000000000..bb71c2254 --- /dev/null +++ b/docs/Management/AndroidFilesCompanyLevelService.md @@ -0,0 +1,267 @@ +## Adyen.Management.Services.AndroidFilesCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IAndroidFilesCompanyLevelService androidFilesCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetAndroidApp**](AndroidFilesCompanyLevelService.md#getandroidapp) | **GET** /companies/{companyId}/androidApps/{id} | Get Android app | +| [**ListAndroidApps**](AndroidFilesCompanyLevelService.md#listandroidapps) | **GET** /companies/{companyId}/androidApps | Get a list of Android apps | +| [**ListAndroidCertificates**](AndroidFilesCompanyLevelService.md#listandroidcertificates) | **GET** /companies/{companyId}/androidCertificates | Get a list of Android certificates | +| [**ReprocessAndroidApp**](AndroidFilesCompanyLevelService.md#reprocessandroidapp) | **PATCH** /companies/{companyId}/androidApps/{id} | Reprocess Android App | +| [**UploadAndroidApp**](AndroidFilesCompanyLevelService.md#uploadandroidapp) | **POST** /companies/{companyId}/androidApps | Upload Android App | +| [**UploadAndroidCertificate**](AndroidFilesCompanyLevelService.md#uploadandroidcertificate) | **POST** /companies/{companyId}/androidCertificates | Upload Android Certificate | + + +### **GET** **/companies/{companyId}/androidApps/{id}** + +Get Android app + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **id** | [string] | The unique identifier of the app. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.GetAndroidApp` usage: +// Provide the following values: companyId, id +IAndroidApp response = await androidFilesCompanyLevelService.GetAndroidAppAsync( + string companyId, string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AndroidApp result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AndroidApp]() + + + +### **GET** **/companies/{companyId}/androidApps** + +Get a list of Android apps + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 20 items on a page. | +| **packageName** | [string] | The package name that uniquely identifies the Android app. | +| **versionCode** | [int] | The version number of the app. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.ListAndroidApps` usage: +// Provide the following values: companyId, pageNumber, pageSize, packageName, versionCode +IAndroidAppsResponse response = await androidFilesCompanyLevelService.ListAndroidAppsAsync( + string companyId, Option pageNumber = default, Option pageSize = default, Option packageName = default, Option versionCode = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AndroidAppsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AndroidAppsResponse]() + + + +### **GET** **/companies/{companyId}/androidCertificates** + +Get a list of Android certificates + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 20 items on a page. | +| **certificateName** | [string] | The name of the certificate. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.ListAndroidCertificates` usage: +// Provide the following values: companyId, pageNumber, pageSize, certificateName +IAndroidCertificatesResponse response = await androidFilesCompanyLevelService.ListAndroidCertificatesAsync( + string companyId, Option pageNumber = default, Option pageSize = default, Option certificateName = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AndroidCertificatesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AndroidCertificatesResponse]() + + + +### **PATCH** **/companies/{companyId}/androidApps/{id}** + +Reprocess Android App + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **id** | [string] | The unique identifier of the app. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.ReprocessAndroidApp` usage: +// Provide the following values: companyId, id +IReprocessAndroidAppResponse response = await androidFilesCompanyLevelService.ReprocessAndroidAppAsync( + string companyId, string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ReprocessAndroidAppResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ReprocessAndroidAppResponse]() + + + +### **POST** **/companies/{companyId}/androidApps** + +Upload Android App + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.UploadAndroidApp` usage: +// Provide the following values: companyId +IUploadAndroidAppResponse response = await androidFilesCompanyLevelService.UploadAndroidAppAsync( + string companyId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out UploadAndroidAppResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[UploadAndroidAppResponse]() + + + +### **POST** **/companies/{companyId}/androidCertificates** + +Upload Android Certificate + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `AndroidFilesCompanyLevelService.UploadAndroidCertificate` usage: +// Provide the following values: companyId +IUploadAndroidCertificateResponse response = await androidFilesCompanyLevelService.UploadAndroidCertificateAsync( + string companyId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out UploadAndroidCertificateResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[UploadAndroidCertificateResponse]() + + diff --git a/docs/Management/ClientKeyCompanyLevelService.md b/docs/Management/ClientKeyCompanyLevelService.md new file mode 100644 index 000000000..66507e79d --- /dev/null +++ b/docs/Management/ClientKeyCompanyLevelService.md @@ -0,0 +1,79 @@ +## Adyen.Management.Services.ClientKeyCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IClientKeyCompanyLevelService clientKeyCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateNewClientKey**](ClientKeyCompanyLevelService.md#generatenewclientkey) | **POST** /companies/{companyId}/apiCredentials/{apiCredentialId}/generateClientKey | Generate new client key | + + +### **POST** **/companies/{companyId}/apiCredentials/{apiCredentialId}/generateClientKey** + +Generate new client key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `ClientKeyCompanyLevelService.GenerateNewClientKey` usage: +// Provide the following values: companyId, apiCredentialId +IGenerateClientKeyResponse response = await clientKeyCompanyLevelService.GenerateNewClientKeyAsync( + string companyId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateClientKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateClientKeyResponse]() + + diff --git a/docs/Management/ClientKeyMerchantLevelService.md b/docs/Management/ClientKeyMerchantLevelService.md new file mode 100644 index 000000000..42e732077 --- /dev/null +++ b/docs/Management/ClientKeyMerchantLevelService.md @@ -0,0 +1,79 @@ +## Adyen.Management.Services.ClientKeyMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IClientKeyMerchantLevelService clientKeyMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateNewClientKey**](ClientKeyMerchantLevelService.md#generatenewclientkey) | **POST** /merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateClientKey | Generate new client key | + + +### **POST** **/merchants/{merchantId}/apiCredentials/{apiCredentialId}/generateClientKey** + +Generate new client key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **apiCredentialId** | [string] | Unique identifier of the API credential. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `ClientKeyMerchantLevelService.GenerateNewClientKey` usage: +// Provide the following values: merchantId, apiCredentialId +IGenerateClientKeyResponse response = await clientKeyMerchantLevelService.GenerateNewClientKeyAsync( + string merchantId, string apiCredentialId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateClientKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateClientKeyResponse]() + + diff --git a/docs/Management/MyAPICredentialService.md b/docs/Management/MyAPICredentialService.md new file mode 100644 index 000000000..8ce63af09 --- /dev/null +++ b/docs/Management/MyAPICredentialService.md @@ -0,0 +1,246 @@ +## Adyen.Management.Services.MyAPICredentialService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IMyAPICredentialService myAPICredentialService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AddAllowedOrigin**](MyAPICredentialService.md#addallowedorigin) | **POST** /me/allowedOrigins | Add allowed origin | +| [**GenerateClientKey**](MyAPICredentialService.md#generateclientkey) | **POST** /me/generateClientKey | Generate a client key | +| [**GetAllowedOriginDetails**](MyAPICredentialService.md#getallowedorigindetails) | **GET** /me/allowedOrigins/{originId} | Get allowed origin details | +| [**GetAllowedOrigins**](MyAPICredentialService.md#getallowedorigins) | **GET** /me/allowedOrigins | Get allowed origins | +| [**GetApiCredentialDetails**](MyAPICredentialService.md#getapicredentialdetails) | **GET** /me | Get API credential details | +| [**RemoveAllowedOrigin**](MyAPICredentialService.md#removeallowedorigin) | **DELETE** /me/allowedOrigins/{originId} | Remove allowed origin | + + +### **POST** **/me/allowedOrigins** + +Add allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createAllowedOriginRequest** | **CreateAllowedOriginRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.AddAllowedOrigin` usage: +// Provide the following values: createAllowedOriginRequest +IAllowedOrigin response = await myAPICredentialService.AddAllowedOriginAsync( + CreateAllowedOriginRequest createAllowedOriginRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **POST** **/me/generateClientKey** + +Generate a client key + +#### Parameters +This endpoint does not need any parameter. +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.GenerateClientKey` usage: +// Provide the following values: +IGenerateClientKeyResponse response = await myAPICredentialService.GenerateClientKeyAsync( + + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateClientKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateClientKeyResponse]() + + + +### **GET** **/me/allowedOrigins/{originId}** + +Get allowed origin details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.GetAllowedOriginDetails` usage: +// Provide the following values: originId +IAllowedOrigin response = await myAPICredentialService.GetAllowedOriginDetailsAsync( + string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOrigin result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOrigin]() + + + +### **GET** **/me/allowedOrigins** + +Get allowed origins + +#### Parameters +This endpoint does not need any parameter. +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.GetAllowedOrigins` usage: +// Provide the following values: +IAllowedOriginsResponse response = await myAPICredentialService.GetAllowedOriginsAsync( + + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AllowedOriginsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AllowedOriginsResponse]() + + + +### **GET** **/me** + +Get API credential details + +#### Parameters +This endpoint does not need any parameter. +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.GetApiCredentialDetails` usage: +// Provide the following values: +IMeApiCredential response = await myAPICredentialService.GetApiCredentialDetailsAsync( + + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out MeApiCredential result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[MeApiCredential]() + + + +### **DELETE** **/me/allowedOrigins/{originId}** + +Remove allowed origin + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **originId** | [string] | Unique identifier of the allowed origin. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `MyAPICredentialService.RemoveAllowedOrigin` usage: +// Provide the following values: originId +await myAPICredentialService.RemoveAllowedOriginAsync( + string originId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/Management/PaymentMethodsMerchantLevelService.md b/docs/Management/PaymentMethodsMerchantLevelService.md new file mode 100644 index 000000000..b259d6aa0 --- /dev/null +++ b/docs/Management/PaymentMethodsMerchantLevelService.md @@ -0,0 +1,269 @@ +## Adyen.Management.Services.PaymentMethodsMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentMethodsMerchantLevelService paymentMethodsMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AddApplePayDomain**](PaymentMethodsMerchantLevelService.md#addapplepaydomain) | **POST** /merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/addApplePayDomains | Add an Apple Pay domain | +| [**GetAllPaymentMethods**](PaymentMethodsMerchantLevelService.md#getallpaymentmethods) | **GET** /merchants/{merchantId}/paymentMethodSettings | Get all payment methods | +| [**GetApplePayDomains**](PaymentMethodsMerchantLevelService.md#getapplepaydomains) | **GET** /merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/getApplePayDomains | Get Apple Pay domains | +| [**GetPaymentMethodDetails**](PaymentMethodsMerchantLevelService.md#getpaymentmethoddetails) | **GET** /merchants/{merchantId}/paymentMethodSettings/{paymentMethodId} | Get payment method details | +| [**RequestPaymentMethod**](PaymentMethodsMerchantLevelService.md#requestpaymentmethod) | **POST** /merchants/{merchantId}/paymentMethodSettings | Request a payment method | +| [**UpdatePaymentMethod**](PaymentMethodsMerchantLevelService.md#updatepaymentmethod) | **PATCH** /merchants/{merchantId}/paymentMethodSettings/{paymentMethodId} | Update a payment method | + + +### **POST** **/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/addApplePayDomains** + +Add an Apple Pay domain + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **paymentMethodId** | [string] | The unique identifier of the payment method. | +| **applePayInfo** | **ApplePayInfo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.AddApplePayDomain` usage: +// Provide the following values: merchantId, paymentMethodId, applePayInfo +await paymentMethodsMerchantLevelService.AddApplePayDomainAsync( + string merchantId, string paymentMethodId, ApplePayInfo applePayInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/merchants/{merchantId}/paymentMethodSettings** + +Get all payment methods + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeId** | [string] | The unique identifier of the store for which to return the payment methods. | +| **businessLineId** | [string] | The unique identifier of the Business Line for which to return the payment methods. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | +| **pageNumber** | [int] | The number of the page to fetch. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.GetAllPaymentMethods` usage: +// Provide the following values: merchantId, storeId, businessLineId, pageSize, pageNumber +IPaymentMethodResponse response = await paymentMethodsMerchantLevelService.GetAllPaymentMethodsAsync( + string merchantId, Option storeId = default, Option businessLineId = default, Option pageSize = default, Option pageNumber = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentMethodResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentMethodResponse]() + + + +### **GET** **/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}/getApplePayDomains** + +Get Apple Pay domains + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **paymentMethodId** | [string] | The unique identifier of the payment method. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.GetApplePayDomains` usage: +// Provide the following values: merchantId, paymentMethodId +IApplePayInfo response = await paymentMethodsMerchantLevelService.GetApplePayDomainsAsync( + string merchantId, string paymentMethodId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ApplePayInfo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ApplePayInfo]() + + + +### **GET** **/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}** + +Get payment method details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **paymentMethodId** | [string] | The unique identifier of the payment method. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.GetPaymentMethodDetails` usage: +// Provide the following values: merchantId, paymentMethodId +IPaymentMethod response = await paymentMethodsMerchantLevelService.GetPaymentMethodDetailsAsync( + string merchantId, string paymentMethodId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentMethod result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentMethod]() + + + +### **POST** **/merchants/{merchantId}/paymentMethodSettings** + +Request a payment method + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **paymentMethodSetupInfo** | **PaymentMethodSetupInfo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.RequestPaymentMethod` usage: +// Provide the following values: merchantId, paymentMethodSetupInfo +IPaymentMethod response = await paymentMethodsMerchantLevelService.RequestPaymentMethodAsync( + string merchantId, PaymentMethodSetupInfo paymentMethodSetupInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentMethod result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentMethod]() + + + +### **PATCH** **/merchants/{merchantId}/paymentMethodSettings/{paymentMethodId}** + +Update a payment method + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **paymentMethodId** | [string] | The unique identifier of the payment method. | +| **updatePaymentMethodInfo** | **UpdatePaymentMethodInfo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PaymentMethodsMerchantLevelService.UpdatePaymentMethod` usage: +// Provide the following values: merchantId, paymentMethodId, updatePaymentMethodInfo +IPaymentMethod response = await paymentMethodsMerchantLevelService.UpdatePaymentMethodAsync( + string merchantId, string paymentMethodId, UpdatePaymentMethodInfo updatePaymentMethodInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentMethod result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentMethod]() + + diff --git a/docs/Management/PayoutSettingsMerchantLevelService.md b/docs/Management/PayoutSettingsMerchantLevelService.md new file mode 100644 index 000000000..4606e5545 --- /dev/null +++ b/docs/Management/PayoutSettingsMerchantLevelService.md @@ -0,0 +1,227 @@ +## Adyen.Management.Services.PayoutSettingsMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPayoutSettingsMerchantLevelService payoutSettingsMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AddPayoutSetting**](PayoutSettingsMerchantLevelService.md#addpayoutsetting) | **POST** /merchants/{merchantId}/payoutSettings | Add a payout setting | +| [**DeletePayoutSetting**](PayoutSettingsMerchantLevelService.md#deletepayoutsetting) | **DELETE** /merchants/{merchantId}/payoutSettings/{payoutSettingsId} | Delete a payout setting | +| [**GetPayoutSetting**](PayoutSettingsMerchantLevelService.md#getpayoutsetting) | **GET** /merchants/{merchantId}/payoutSettings/{payoutSettingsId} | Get a payout setting | +| [**ListPayoutSettings**](PayoutSettingsMerchantLevelService.md#listpayoutsettings) | **GET** /merchants/{merchantId}/payoutSettings | Get a list of payout settings | +| [**UpdatePayoutSetting**](PayoutSettingsMerchantLevelService.md#updatepayoutsetting) | **PATCH** /merchants/{merchantId}/payoutSettings/{payoutSettingsId} | Update a payout setting | + + +### **POST** **/merchants/{merchantId}/payoutSettings** + +Add a payout setting + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **payoutSettingsRequest** | **PayoutSettingsRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PayoutSettingsMerchantLevelService.AddPayoutSetting` usage: +// Provide the following values: merchantId, payoutSettingsRequest +IPayoutSettings response = await payoutSettingsMerchantLevelService.AddPayoutSettingAsync( + string merchantId, PayoutSettingsRequest payoutSettingsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PayoutSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PayoutSettings]() + + + +### **DELETE** **/merchants/{merchantId}/payoutSettings/{payoutSettingsId}** + +Delete a payout setting + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **payoutSettingsId** | [string] | The unique identifier of the payout setting. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PayoutSettingsMerchantLevelService.DeletePayoutSetting` usage: +// Provide the following values: merchantId, payoutSettingsId +await payoutSettingsMerchantLevelService.DeletePayoutSettingAsync( + string merchantId, string payoutSettingsId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/merchants/{merchantId}/payoutSettings/{payoutSettingsId}** + +Get a payout setting + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **payoutSettingsId** | [string] | The unique identifier of the payout setting. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PayoutSettingsMerchantLevelService.GetPayoutSetting` usage: +// Provide the following values: merchantId, payoutSettingsId +IPayoutSettings response = await payoutSettingsMerchantLevelService.GetPayoutSettingAsync( + string merchantId, string payoutSettingsId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PayoutSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PayoutSettings]() + + + +### **GET** **/merchants/{merchantId}/payoutSettings** + +Get a list of payout settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PayoutSettingsMerchantLevelService.ListPayoutSettings` usage: +// Provide the following values: merchantId +IPayoutSettingsResponse response = await payoutSettingsMerchantLevelService.ListPayoutSettingsAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PayoutSettingsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PayoutSettingsResponse]() + + + +### **PATCH** **/merchants/{merchantId}/payoutSettings/{payoutSettingsId}** + +Update a payout setting + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **payoutSettingsId** | [string] | The unique identifier of the payout setting. | +| **updatePayoutSettingsRequest** | **UpdatePayoutSettingsRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `PayoutSettingsMerchantLevelService.UpdatePayoutSetting` usage: +// Provide the following values: merchantId, payoutSettingsId, updatePayoutSettingsRequest +IPayoutSettings response = await payoutSettingsMerchantLevelService.UpdatePayoutSettingAsync( + string merchantId, string payoutSettingsId, UpdatePayoutSettingsRequest updatePayoutSettingsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PayoutSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PayoutSettings]() + + diff --git a/docs/Management/SplitConfigurationMerchantLevelService.md b/docs/Management/SplitConfigurationMerchantLevelService.md new file mode 100644 index 000000000..2e918c736 --- /dev/null +++ b/docs/Management/SplitConfigurationMerchantLevelService.md @@ -0,0 +1,382 @@ +## Adyen.Management.Services.SplitConfigurationMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ISplitConfigurationMerchantLevelService splitConfigurationMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateRule**](SplitConfigurationMerchantLevelService.md#createrule) | **POST** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId} | Create a rule | +| [**CreateSplitConfiguration**](SplitConfigurationMerchantLevelService.md#createsplitconfiguration) | **POST** /merchants/{merchantId}/splitConfigurations | Create a split configuration profile | +| [**DeleteSplitConfiguration**](SplitConfigurationMerchantLevelService.md#deletesplitconfiguration) | **DELETE** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId} | Delete a split configuration profile | +| [**DeleteSplitConfigurationRule**](SplitConfigurationMerchantLevelService.md#deletesplitconfigurationrule) | **DELETE** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId} | Delete a rule | +| [**GetSplitConfiguration**](SplitConfigurationMerchantLevelService.md#getsplitconfiguration) | **GET** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId} | Get a split configuration profile | +| [**ListSplitConfigurations**](SplitConfigurationMerchantLevelService.md#listsplitconfigurations) | **GET** /merchants/{merchantId}/splitConfigurations | Get a list of split configuration profiles | +| [**UpdateSplitConditions**](SplitConfigurationMerchantLevelService.md#updatesplitconditions) | **PATCH** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId} | Update the split conditions | +| [**UpdateSplitConfigurationDescription**](SplitConfigurationMerchantLevelService.md#updatesplitconfigurationdescription) | **PATCH** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId} | Update the description of the split configuration profile | +| [**UpdateSplitLogic**](SplitConfigurationMerchantLevelService.md#updatesplitlogic) | **PATCH** /merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}/splitLogic/{splitLogicId} | Update the split logic | + + +### **POST** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}** + +Create a rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | +| **splitConfigurationRule** | **SplitConfigurationRule** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.CreateRule` usage: +// Provide the following values: merchantId, splitConfigurationId, splitConfigurationRule +ISplitConfiguration response = await splitConfigurationMerchantLevelService.CreateRuleAsync( + string merchantId, string splitConfigurationId, SplitConfigurationRule splitConfigurationRule, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **POST** **/merchants/{merchantId}/splitConfigurations** + +Create a split configuration profile + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfiguration** | **SplitConfiguration** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.CreateSplitConfiguration` usage: +// Provide the following values: merchantId, splitConfiguration +ISplitConfiguration response = await splitConfigurationMerchantLevelService.CreateSplitConfigurationAsync( + string merchantId, SplitConfiguration splitConfiguration, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **DELETE** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}** + +Delete a split configuration profile + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.DeleteSplitConfiguration` usage: +// Provide the following values: merchantId, splitConfigurationId +ISplitConfiguration response = await splitConfigurationMerchantLevelService.DeleteSplitConfigurationAsync( + string merchantId, string splitConfigurationId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **DELETE** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}** + +Delete a rule + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | +| **ruleId** | [string] | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.DeleteSplitConfigurationRule` usage: +// Provide the following values: merchantId, splitConfigurationId, ruleId +ISplitConfiguration response = await splitConfigurationMerchantLevelService.DeleteSplitConfigurationRuleAsync( + string merchantId, string splitConfigurationId, string ruleId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **GET** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}** + +Get a split configuration profile + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.GetSplitConfiguration` usage: +// Provide the following values: merchantId, splitConfigurationId +ISplitConfiguration response = await splitConfigurationMerchantLevelService.GetSplitConfigurationAsync( + string merchantId, string splitConfigurationId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **GET** **/merchants/{merchantId}/splitConfigurations** + +Get a list of split configuration profiles + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.ListSplitConfigurations` usage: +// Provide the following values: merchantId +ISplitConfigurationList response = await splitConfigurationMerchantLevelService.ListSplitConfigurationsAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfigurationList result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfigurationList]() + + + +### **PATCH** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}** + +Update the split conditions + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The identifier of the split configuration. | +| **ruleId** | [string] | The unique identifier of the split configuration rule. | +| **updateSplitConfigurationRuleRequest** | **UpdateSplitConfigurationRuleRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.UpdateSplitConditions` usage: +// Provide the following values: merchantId, splitConfigurationId, ruleId, updateSplitConfigurationRuleRequest +ISplitConfiguration response = await splitConfigurationMerchantLevelService.UpdateSplitConditionsAsync( + string merchantId, string splitConfigurationId, string ruleId, UpdateSplitConfigurationRuleRequest updateSplitConfigurationRuleRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **PATCH** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}** + +Update the description of the split configuration profile + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | +| **updateSplitConfigurationRequest** | **UpdateSplitConfigurationRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.UpdateSplitConfigurationDescription` usage: +// Provide the following values: merchantId, splitConfigurationId, updateSplitConfigurationRequest +ISplitConfiguration response = await splitConfigurationMerchantLevelService.UpdateSplitConfigurationDescriptionAsync( + string merchantId, string splitConfigurationId, UpdateSplitConfigurationRequest updateSplitConfigurationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + + +### **PATCH** **/merchants/{merchantId}/splitConfigurations/{splitConfigurationId}/rules/{ruleId}/splitLogic/{splitLogicId}** + +Update the split logic + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **splitConfigurationId** | [string] | The unique identifier of the split configuration. | +| **ruleId** | [string] | The unique identifier of the split configuration rule. | +| **splitLogicId** | [string] | The unique identifier of the split configuration split. | +| **updateSplitConfigurationLogicRequest** | **UpdateSplitConfigurationLogicRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `SplitConfigurationMerchantLevelService.UpdateSplitLogic` usage: +// Provide the following values: merchantId, splitConfigurationId, ruleId, splitLogicId, updateSplitConfigurationLogicRequest +ISplitConfiguration response = await splitConfigurationMerchantLevelService.UpdateSplitLogicAsync( + string merchantId, string splitConfigurationId, string ruleId, string splitLogicId, UpdateSplitConfigurationLogicRequest updateSplitConfigurationLogicRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SplitConfiguration result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SplitConfiguration]() + + diff --git a/docs/Management/TerminalActionsCompanyLevelService.md b/docs/Management/TerminalActionsCompanyLevelService.md new file mode 100644 index 000000000..48a409c0c --- /dev/null +++ b/docs/Management/TerminalActionsCompanyLevelService.md @@ -0,0 +1,119 @@ +## Adyen.Management.Services.TerminalActionsCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalActionsCompanyLevelService terminalActionsCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetTerminalAction**](TerminalActionsCompanyLevelService.md#getterminalaction) | **GET** /companies/{companyId}/terminalActions/{actionId} | Get terminal action | +| [**ListTerminalActions**](TerminalActionsCompanyLevelService.md#listterminalactions) | **GET** /companies/{companyId}/terminalActions | Get a list of terminal actions | + + +### **GET** **/companies/{companyId}/terminalActions/{actionId}** + +Get terminal action + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **actionId** | [string] | The unique identifier of the terminal action. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalActionsCompanyLevelService.GetTerminalAction` usage: +// Provide the following values: companyId, actionId +IExternalTerminalAction response = await terminalActionsCompanyLevelService.GetTerminalActionAsync( + string companyId, string actionId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ExternalTerminalAction result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ExternalTerminalAction]() + + + +### **GET** **/companies/{companyId}/terminalActions** + +Get a list of terminal actions + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 20 items on a page. | +| **status** | [string] | Returns terminal actions with the specified status. Allowed values: **pending**, **successful**, **failed**, **cancelled**, **tryLater**. | +| **type** | [string] | Returns terminal actions of the specified type. Allowed values: **InstallAndroidApp**, **UninstallAndroidApp**, **InstallAndroidCertificate**, **UninstallAndroidCertificate**. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalActionsCompanyLevelService.ListTerminalActions` usage: +// Provide the following values: companyId, pageNumber, pageSize, status, type +IListExternalTerminalActionsResponse response = await terminalActionsCompanyLevelService.ListTerminalActionsAsync( + string companyId, Option pageNumber = default, Option pageSize = default, Option status = default, Option type = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListExternalTerminalActionsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListExternalTerminalActionsResponse]() + + diff --git a/docs/Management/TerminalActionsTerminalLevelService.md b/docs/Management/TerminalActionsTerminalLevelService.md new file mode 100644 index 000000000..797584e40 --- /dev/null +++ b/docs/Management/TerminalActionsTerminalLevelService.md @@ -0,0 +1,78 @@ +## Adyen.Management.Services.TerminalActionsTerminalLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalActionsTerminalLevelService terminalActionsTerminalLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateTerminalAction**](TerminalActionsTerminalLevelService.md#createterminalaction) | **POST** /terminals/scheduleActions | Create a terminal action | + + +### **POST** **/terminals/scheduleActions** + +Create a terminal action + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **scheduleTerminalActionsRequest** | **ScheduleTerminalActionsRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalActionsTerminalLevelService.CreateTerminalAction` usage: +// Provide the following values: scheduleTerminalActionsRequest +IScheduleTerminalActionsResponse response = await terminalActionsTerminalLevelService.CreateTerminalActionAsync( + ScheduleTerminalActionsRequest scheduleTerminalActionsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ScheduleTerminalActionsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ScheduleTerminalActionsResponse]() + + diff --git a/docs/Management/TerminalOrdersCompanyLevelService.md b/docs/Management/TerminalOrdersCompanyLevelService.md new file mode 100644 index 000000000..648d2e5ff --- /dev/null +++ b/docs/Management/TerminalOrdersCompanyLevelService.md @@ -0,0 +1,420 @@ +## Adyen.Management.Services.TerminalOrdersCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalOrdersCompanyLevelService terminalOrdersCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CancelOrder**](TerminalOrdersCompanyLevelService.md#cancelorder) | **POST** /companies/{companyId}/terminalOrders/{orderId}/cancel | Cancel an order | +| [**CreateOrder**](TerminalOrdersCompanyLevelService.md#createorder) | **POST** /companies/{companyId}/terminalOrders | Create an order | +| [**CreateShippingLocation**](TerminalOrdersCompanyLevelService.md#createshippinglocation) | **POST** /companies/{companyId}/shippingLocations | Create a shipping location | +| [**GetOrder**](TerminalOrdersCompanyLevelService.md#getorder) | **GET** /companies/{companyId}/terminalOrders/{orderId} | Get an order | +| [**ListBillingEntities**](TerminalOrdersCompanyLevelService.md#listbillingentities) | **GET** /companies/{companyId}/billingEntities | Get a list of billing entities | +| [**ListOrders**](TerminalOrdersCompanyLevelService.md#listorders) | **GET** /companies/{companyId}/terminalOrders | Get a list of orders | +| [**ListShippingLocations**](TerminalOrdersCompanyLevelService.md#listshippinglocations) | **GET** /companies/{companyId}/shippingLocations | Get a list of shipping locations | +| [**ListTerminalModels**](TerminalOrdersCompanyLevelService.md#listterminalmodels) | **GET** /companies/{companyId}/terminalModels | Get a list of terminal models | +| [**ListTerminalProducts**](TerminalOrdersCompanyLevelService.md#listterminalproducts) | **GET** /companies/{companyId}/terminalProducts | Get a list of terminal products | +| [**UpdateOrder**](TerminalOrdersCompanyLevelService.md#updateorder) | **PATCH** /companies/{companyId}/terminalOrders/{orderId} | Update an order | + + +### **POST** **/companies/{companyId}/terminalOrders/{orderId}/cancel** + +Cancel an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **orderId** | [string] | The unique identifier of the order. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.CancelOrder` usage: +// Provide the following values: companyId, orderId +ITerminalOrder response = await terminalOrdersCompanyLevelService.CancelOrderAsync( + string companyId, string orderId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **POST** **/companies/{companyId}/terminalOrders** + +Create an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **terminalOrderRequest** | **TerminalOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.CreateOrder` usage: +// Provide the following values: companyId, terminalOrderRequest +ITerminalOrder response = await terminalOrdersCompanyLevelService.CreateOrderAsync( + string companyId, TerminalOrderRequest terminalOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **POST** **/companies/{companyId}/shippingLocations** + +Create a shipping location + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **shippingLocation** | **ShippingLocation** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.CreateShippingLocation` usage: +// Provide the following values: companyId, shippingLocation +IShippingLocation response = await terminalOrdersCompanyLevelService.CreateShippingLocationAsync( + string companyId, ShippingLocation shippingLocation, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ShippingLocation result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ShippingLocation]() + + + +### **GET** **/companies/{companyId}/terminalOrders/{orderId}** + +Get an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **orderId** | [string] | The unique identifier of the order. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.GetOrder` usage: +// Provide the following values: companyId, orderId +ITerminalOrder response = await terminalOrdersCompanyLevelService.GetOrderAsync( + string companyId, string orderId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **GET** **/companies/{companyId}/billingEntities** + +Get a list of billing entities + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **name** | [string] | The name of the billing entity. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.ListBillingEntities` usage: +// Provide the following values: companyId, name +IBillingEntitiesResponse response = await terminalOrdersCompanyLevelService.ListBillingEntitiesAsync( + string companyId, Option name = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BillingEntitiesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BillingEntitiesResponse]() + + + +### **GET** **/companies/{companyId}/terminalOrders** + +Get a list of orders + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **customerOrderReference** | [string] | Your purchase order number. | +| **status** | [string] | The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. | +| **offset** | [int] | The number of orders to skip. | +| **limit** | [int] | The number of orders to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.ListOrders` usage: +// Provide the following values: companyId, customerOrderReference, status, offset, limit +ITerminalOrdersResponse response = await terminalOrdersCompanyLevelService.ListOrdersAsync( + string companyId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrdersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrdersResponse]() + + + +### **GET** **/companies/{companyId}/shippingLocations** + +Get a list of shipping locations + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **name** | [string] | The name of the shipping location. | +| **offset** | [int] | The number of locations to skip. | +| **limit** | [int] | The number of locations to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.ListShippingLocations` usage: +// Provide the following values: companyId, name, offset, limit +IShippingLocationsResponse response = await terminalOrdersCompanyLevelService.ListShippingLocationsAsync( + string companyId, Option name = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ShippingLocationsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ShippingLocationsResponse]() + + + +### **GET** **/companies/{companyId}/terminalModels** + +Get a list of terminal models + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.ListTerminalModels` usage: +// Provide the following values: companyId +ITerminalModelsResponse response = await terminalOrdersCompanyLevelService.ListTerminalModelsAsync( + string companyId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalModelsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalModelsResponse]() + + + +### **GET** **/companies/{companyId}/terminalProducts** + +Get a list of terminal products + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **country** | [string] | The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** | +| **terminalModelId** | [string] | The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) response. For example, **Verifone.M400** | +| **offset** | [int] | The number of products to skip. | +| **limit** | [int] | The number of products to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.ListTerminalProducts` usage: +// Provide the following values: companyId, country, terminalModelId, offset, limit +ITerminalProductsResponse response = await terminalOrdersCompanyLevelService.ListTerminalProductsAsync( + string companyId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalProductsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalProductsResponse]() + + + +### **PATCH** **/companies/{companyId}/terminalOrders/{orderId}** + +Update an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **orderId** | [string] | The unique identifier of the order. | +| **terminalOrderRequest** | **TerminalOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersCompanyLevelService.UpdateOrder` usage: +// Provide the following values: companyId, orderId, terminalOrderRequest +ITerminalOrder response = await terminalOrdersCompanyLevelService.UpdateOrderAsync( + string companyId, string orderId, TerminalOrderRequest terminalOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + diff --git a/docs/Management/TerminalOrdersMerchantLevelService.md b/docs/Management/TerminalOrdersMerchantLevelService.md new file mode 100644 index 000000000..84d3272e7 --- /dev/null +++ b/docs/Management/TerminalOrdersMerchantLevelService.md @@ -0,0 +1,420 @@ +## Adyen.Management.Services.TerminalOrdersMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalOrdersMerchantLevelService terminalOrdersMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CancelOrder**](TerminalOrdersMerchantLevelService.md#cancelorder) | **POST** /merchants/{merchantId}/terminalOrders/{orderId}/cancel | Cancel an order | +| [**CreateOrder**](TerminalOrdersMerchantLevelService.md#createorder) | **POST** /merchants/{merchantId}/terminalOrders | Create an order | +| [**CreateShippingLocation**](TerminalOrdersMerchantLevelService.md#createshippinglocation) | **POST** /merchants/{merchantId}/shippingLocations | Create a shipping location | +| [**GetOrder**](TerminalOrdersMerchantLevelService.md#getorder) | **GET** /merchants/{merchantId}/terminalOrders/{orderId} | Get an order | +| [**ListBillingEntities**](TerminalOrdersMerchantLevelService.md#listbillingentities) | **GET** /merchants/{merchantId}/billingEntities | Get a list of billing entities | +| [**ListOrders**](TerminalOrdersMerchantLevelService.md#listorders) | **GET** /merchants/{merchantId}/terminalOrders | Get a list of orders | +| [**ListShippingLocations**](TerminalOrdersMerchantLevelService.md#listshippinglocations) | **GET** /merchants/{merchantId}/shippingLocations | Get a list of shipping locations | +| [**ListTerminalModels**](TerminalOrdersMerchantLevelService.md#listterminalmodels) | **GET** /merchants/{merchantId}/terminalModels | Get a list of terminal models | +| [**ListTerminalProducts**](TerminalOrdersMerchantLevelService.md#listterminalproducts) | **GET** /merchants/{merchantId}/terminalProducts | Get a list of terminal products | +| [**UpdateOrder**](TerminalOrdersMerchantLevelService.md#updateorder) | **PATCH** /merchants/{merchantId}/terminalOrders/{orderId} | Update an order | + + +### **POST** **/merchants/{merchantId}/terminalOrders/{orderId}/cancel** + +Cancel an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **orderId** | [string] | The unique identifier of the order. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.CancelOrder` usage: +// Provide the following values: merchantId, orderId +ITerminalOrder response = await terminalOrdersMerchantLevelService.CancelOrderAsync( + string merchantId, string orderId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **POST** **/merchants/{merchantId}/terminalOrders** + +Create an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **terminalOrderRequest** | **TerminalOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.CreateOrder` usage: +// Provide the following values: merchantId, terminalOrderRequest +ITerminalOrder response = await terminalOrdersMerchantLevelService.CreateOrderAsync( + string merchantId, TerminalOrderRequest terminalOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **POST** **/merchants/{merchantId}/shippingLocations** + +Create a shipping location + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **shippingLocation** | **ShippingLocation** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.CreateShippingLocation` usage: +// Provide the following values: merchantId, shippingLocation +IShippingLocation response = await terminalOrdersMerchantLevelService.CreateShippingLocationAsync( + string merchantId, ShippingLocation shippingLocation, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ShippingLocation result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ShippingLocation]() + + + +### **GET** **/merchants/{merchantId}/terminalOrders/{orderId}** + +Get an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **orderId** | [string] | The unique identifier of the order. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.GetOrder` usage: +// Provide the following values: merchantId, orderId +ITerminalOrder response = await terminalOrdersMerchantLevelService.GetOrderAsync( + string merchantId, string orderId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + + +### **GET** **/merchants/{merchantId}/billingEntities** + +Get a list of billing entities + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **name** | [string] | The name of the billing entity. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.ListBillingEntities` usage: +// Provide the following values: merchantId, name +IBillingEntitiesResponse response = await terminalOrdersMerchantLevelService.ListBillingEntitiesAsync( + string merchantId, Option name = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BillingEntitiesResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BillingEntitiesResponse]() + + + +### **GET** **/merchants/{merchantId}/terminalOrders** + +Get a list of orders + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | | +| **customerOrderReference** | [string] | Your purchase order number. | +| **status** | [string] | The order status. Possible values (not case-sensitive): Placed, Confirmed, Cancelled, Shipped, Delivered. | +| **offset** | [int] | The number of orders to skip. | +| **limit** | [int] | The number of orders to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.ListOrders` usage: +// Provide the following values: merchantId, customerOrderReference, status, offset, limit +ITerminalOrdersResponse response = await terminalOrdersMerchantLevelService.ListOrdersAsync( + string merchantId, Option customerOrderReference = default, Option status = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrdersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrdersResponse]() + + + +### **GET** **/merchants/{merchantId}/shippingLocations** + +Get a list of shipping locations + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **name** | [string] | The name of the shipping location. | +| **offset** | [int] | The number of locations to skip. | +| **limit** | [int] | The number of locations to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.ListShippingLocations` usage: +// Provide the following values: merchantId, name, offset, limit +IShippingLocationsResponse response = await terminalOrdersMerchantLevelService.ListShippingLocationsAsync( + string merchantId, Option name = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ShippingLocationsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ShippingLocationsResponse]() + + + +### **GET** **/merchants/{merchantId}/terminalModels** + +Get a list of terminal models + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.ListTerminalModels` usage: +// Provide the following values: merchantId +ITerminalModelsResponse response = await terminalOrdersMerchantLevelService.ListTerminalModelsAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalModelsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalModelsResponse]() + + + +### **GET** **/merchants/{merchantId}/terminalProducts** + +Get a list of terminal products + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **country** | [string] | The country to return products for, in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. For example, **US** | +| **terminalModelId** | [string] | The terminal model to return products for. Use the ID returned in the [GET `/terminalModels`](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/merchants/{merchantId}/terminalModels) response. For example, **Verifone.M400** | +| **offset** | [int] | The number of products to skip. | +| **limit** | [int] | The number of products to return. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.ListTerminalProducts` usage: +// Provide the following values: merchantId, country, terminalModelId, offset, limit +ITerminalProductsResponse response = await terminalOrdersMerchantLevelService.ListTerminalProductsAsync( + string merchantId, string country, Option terminalModelId = default, Option offset = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalProductsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalProductsResponse]() + + + +### **PATCH** **/merchants/{merchantId}/terminalOrders/{orderId}** + +Update an order + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **orderId** | [string] | The unique identifier of the order. | +| **terminalOrderRequest** | **TerminalOrderRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalOrdersMerchantLevelService.UpdateOrder` usage: +// Provide the following values: merchantId, orderId, terminalOrderRequest +ITerminalOrder response = await terminalOrdersMerchantLevelService.UpdateOrderAsync( + string merchantId, string orderId, TerminalOrderRequest terminalOrderRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalOrder result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalOrder]() + + diff --git a/docs/Management/TerminalSettingsCompanyLevelService.md b/docs/Management/TerminalSettingsCompanyLevelService.md new file mode 100644 index 000000000..e7223a122 --- /dev/null +++ b/docs/Management/TerminalSettingsCompanyLevelService.md @@ -0,0 +1,190 @@ +## Adyen.Management.Services.TerminalSettingsCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalSettingsCompanyLevelService terminalSettingsCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetTerminalLogo**](TerminalSettingsCompanyLevelService.md#getterminallogo) | **GET** /companies/{companyId}/terminalLogos | Get the terminal logo | +| [**GetTerminalSettings**](TerminalSettingsCompanyLevelService.md#getterminalsettings) | **GET** /companies/{companyId}/terminalSettings | Get terminal settings | +| [**UpdateTerminalLogo**](TerminalSettingsCompanyLevelService.md#updateterminallogo) | **PATCH** /companies/{companyId}/terminalLogos | Update the terminal logo | +| [**UpdateTerminalSettings**](TerminalSettingsCompanyLevelService.md#updateterminalsettings) | **PATCH** /companies/{companyId}/terminalSettings | Update terminal settings | + + +### **GET** **/companies/{companyId}/terminalLogos** + +Get the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsCompanyLevelService.GetTerminalLogo` usage: +// Provide the following values: companyId, model +ILogo response = await terminalSettingsCompanyLevelService.GetTerminalLogoAsync( + string companyId, string model, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **GET** **/companies/{companyId}/terminalSettings** + +Get terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsCompanyLevelService.GetTerminalSettings` usage: +// Provide the following values: companyId +ITerminalSettings response = await terminalSettingsCompanyLevelService.GetTerminalSettingsAsync( + string companyId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **PATCH** **/companies/{companyId}/terminalLogos** + +Update the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | +| **logo** | **Logo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsCompanyLevelService.UpdateTerminalLogo` usage: +// Provide the following values: companyId, model, logo +ILogo response = await terminalSettingsCompanyLevelService.UpdateTerminalLogoAsync( + string companyId, string model, Logo logo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **PATCH** **/companies/{companyId}/terminalSettings** + +Update terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **terminalSettings** | **TerminalSettings** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsCompanyLevelService.UpdateTerminalSettings` usage: +// Provide the following values: companyId, terminalSettings +ITerminalSettings response = await terminalSettingsCompanyLevelService.UpdateTerminalSettingsAsync( + string companyId, TerminalSettings terminalSettings, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + diff --git a/docs/Management/TerminalSettingsMerchantLevelService.md b/docs/Management/TerminalSettingsMerchantLevelService.md new file mode 100644 index 000000000..2146d960b --- /dev/null +++ b/docs/Management/TerminalSettingsMerchantLevelService.md @@ -0,0 +1,190 @@ +## Adyen.Management.Services.TerminalSettingsMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalSettingsMerchantLevelService terminalSettingsMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetTerminalLogo**](TerminalSettingsMerchantLevelService.md#getterminallogo) | **GET** /merchants/{merchantId}/terminalLogos | Get the terminal logo | +| [**GetTerminalSettings**](TerminalSettingsMerchantLevelService.md#getterminalsettings) | **GET** /merchants/{merchantId}/terminalSettings | Get terminal settings | +| [**UpdateTerminalLogo**](TerminalSettingsMerchantLevelService.md#updateterminallogo) | **PATCH** /merchants/{merchantId}/terminalLogos | Update the terminal logo | +| [**UpdateTerminalSettings**](TerminalSettingsMerchantLevelService.md#updateterminalsettings) | **PATCH** /merchants/{merchantId}/terminalSettings | Update terminal settings | + + +### **GET** **/merchants/{merchantId}/terminalLogos** + +Get the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsMerchantLevelService.GetTerminalLogo` usage: +// Provide the following values: merchantId, model +ILogo response = await terminalSettingsMerchantLevelService.GetTerminalLogoAsync( + string merchantId, string model, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **GET** **/merchants/{merchantId}/terminalSettings** + +Get terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsMerchantLevelService.GetTerminalSettings` usage: +// Provide the following values: merchantId +ITerminalSettings response = await terminalSettingsMerchantLevelService.GetTerminalSettingsAsync( + string merchantId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **PATCH** **/merchants/{merchantId}/terminalLogos** + +Update the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **model** | [string] | The terminal model. Allowed values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | +| **logo** | **Logo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsMerchantLevelService.UpdateTerminalLogo` usage: +// Provide the following values: merchantId, model, logo +ILogo response = await terminalSettingsMerchantLevelService.UpdateTerminalLogoAsync( + string merchantId, string model, Logo logo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **PATCH** **/merchants/{merchantId}/terminalSettings** + +Update terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **terminalSettings** | **TerminalSettings** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsMerchantLevelService.UpdateTerminalSettings` usage: +// Provide the following values: merchantId, terminalSettings +ITerminalSettings response = await terminalSettingsMerchantLevelService.UpdateTerminalSettingsAsync( + string merchantId, TerminalSettings terminalSettings, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + diff --git a/docs/Management/TerminalSettingsStoreLevelService.md b/docs/Management/TerminalSettingsStoreLevelService.md new file mode 100644 index 000000000..ed4a9f34b --- /dev/null +++ b/docs/Management/TerminalSettingsStoreLevelService.md @@ -0,0 +1,342 @@ +## Adyen.Management.Services.TerminalSettingsStoreLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalSettingsStoreLevelService terminalSettingsStoreLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetTerminalLogo**](TerminalSettingsStoreLevelService.md#getterminallogo) | **GET** /merchants/{merchantId}/stores/{reference}/terminalLogos | Get the terminal logo | +| [**GetTerminalLogoByStoreId**](TerminalSettingsStoreLevelService.md#getterminallogobystoreid) | **GET** /stores/{storeId}/terminalLogos | Get the terminal logo | +| [**GetTerminalSettings**](TerminalSettingsStoreLevelService.md#getterminalsettings) | **GET** /merchants/{merchantId}/stores/{reference}/terminalSettings | Get terminal settings | +| [**GetTerminalSettingsByStoreId**](TerminalSettingsStoreLevelService.md#getterminalsettingsbystoreid) | **GET** /stores/{storeId}/terminalSettings | Get terminal settings | +| [**UpdateTerminalLogo**](TerminalSettingsStoreLevelService.md#updateterminallogo) | **PATCH** /merchants/{merchantId}/stores/{reference}/terminalLogos | Update the terminal logo | +| [**UpdateTerminalLogoByStoreId**](TerminalSettingsStoreLevelService.md#updateterminallogobystoreid) | **PATCH** /stores/{storeId}/terminalLogos | Update the terminal logo | +| [**UpdateTerminalSettings**](TerminalSettingsStoreLevelService.md#updateterminalsettings) | **PATCH** /merchants/{merchantId}/stores/{reference}/terminalSettings | Update terminal settings | +| [**UpdateTerminalSettingsByStoreId**](TerminalSettingsStoreLevelService.md#updateterminalsettingsbystoreid) | **PATCH** /stores/{storeId}/terminalSettings | Update terminal settings | + + +### **GET** **/merchants/{merchantId}/stores/{reference}/terminalLogos** + +Get the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **reference** | [string] | The reference that identifies the store. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.GetTerminalLogo` usage: +// Provide the following values: merchantId, reference, model +ILogo response = await terminalSettingsStoreLevelService.GetTerminalLogoAsync( + string merchantId, string reference, string model, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **GET** **/stores/{storeId}/terminalLogos** + +Get the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.GetTerminalLogoByStoreId` usage: +// Provide the following values: storeId, model +ILogo response = await terminalSettingsStoreLevelService.GetTerminalLogoByStoreIdAsync( + string storeId, string model, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **GET** **/merchants/{merchantId}/stores/{reference}/terminalSettings** + +Get terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **reference** | [string] | The reference that identifies the store. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.GetTerminalSettings` usage: +// Provide the following values: merchantId, reference +ITerminalSettings response = await terminalSettingsStoreLevelService.GetTerminalSettingsAsync( + string merchantId, string reference, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **GET** **/stores/{storeId}/terminalSettings** + +Get terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.GetTerminalSettingsByStoreId` usage: +// Provide the following values: storeId +ITerminalSettings response = await terminalSettingsStoreLevelService.GetTerminalSettingsByStoreIdAsync( + string storeId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **PATCH** **/merchants/{merchantId}/stores/{reference}/terminalLogos** + +Update the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **reference** | [string] | The reference that identifies the store. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T | +| **logo** | **Logo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.UpdateTerminalLogo` usage: +// Provide the following values: merchantId, reference, model, logo +ILogo response = await terminalSettingsStoreLevelService.UpdateTerminalLogoAsync( + string merchantId, string reference, string model, Logo logo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **PATCH** **/stores/{storeId}/terminalLogos** + +Update the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | +| **model** | [string] | The terminal model. Possible values: E355, VX675WIFIBT, VX680, VX690, VX700, VX820, M400, MX925, P400Plus, UX300, UX410, V200cPlus, V240mPlus, V400cPlus, V400m, e280, e285, e285p, S1E, S1EL, S1F2, S1L, S1U, S7T. | +| **logo** | **Logo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.UpdateTerminalLogoByStoreId` usage: +// Provide the following values: storeId, model, logo +ILogo response = await terminalSettingsStoreLevelService.UpdateTerminalLogoByStoreIdAsync( + string storeId, string model, Logo logo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **PATCH** **/merchants/{merchantId}/stores/{reference}/terminalSettings** + +Update terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **reference** | [string] | The reference that identifies the store. | +| **terminalSettings** | **TerminalSettings** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.UpdateTerminalSettings` usage: +// Provide the following values: merchantId, reference, terminalSettings +ITerminalSettings response = await terminalSettingsStoreLevelService.UpdateTerminalSettingsAsync( + string merchantId, string reference, TerminalSettings terminalSettings, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **PATCH** **/stores/{storeId}/terminalSettings** + +Update terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeId** | [string] | The unique identifier of the store. | +| **terminalSettings** | **TerminalSettings** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsStoreLevelService.UpdateTerminalSettingsByStoreId` usage: +// Provide the following values: storeId, terminalSettings +ITerminalSettings response = await terminalSettingsStoreLevelService.UpdateTerminalSettingsByStoreIdAsync( + string storeId, TerminalSettings terminalSettings, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + diff --git a/docs/Management/TerminalSettingsTerminalLevelService.md b/docs/Management/TerminalSettingsTerminalLevelService.md new file mode 100644 index 000000000..7de210933 --- /dev/null +++ b/docs/Management/TerminalSettingsTerminalLevelService.md @@ -0,0 +1,188 @@ +## Adyen.Management.Services.TerminalSettingsTerminalLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalSettingsTerminalLevelService terminalSettingsTerminalLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetTerminalLogo**](TerminalSettingsTerminalLevelService.md#getterminallogo) | **GET** /terminals/{terminalId}/terminalLogos | Get the terminal logo | +| [**GetTerminalSettings**](TerminalSettingsTerminalLevelService.md#getterminalsettings) | **GET** /terminals/{terminalId}/terminalSettings | Get terminal settings | +| [**UpdateLogo**](TerminalSettingsTerminalLevelService.md#updatelogo) | **PATCH** /terminals/{terminalId}/terminalLogos | Update the logo | +| [**UpdateTerminalSettings**](TerminalSettingsTerminalLevelService.md#updateterminalsettings) | **PATCH** /terminals/{terminalId}/terminalSettings | Update terminal settings | + + +### **GET** **/terminals/{terminalId}/terminalLogos** + +Get the terminal logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **terminalId** | [string] | The unique identifier of the payment terminal. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsTerminalLevelService.GetTerminalLogo` usage: +// Provide the following values: terminalId +ILogo response = await terminalSettingsTerminalLevelService.GetTerminalLogoAsync( + string terminalId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **GET** **/terminals/{terminalId}/terminalSettings** + +Get terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **terminalId** | [string] | The unique identifier of the payment terminal. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsTerminalLevelService.GetTerminalSettings` usage: +// Provide the following values: terminalId +ITerminalSettings response = await terminalSettingsTerminalLevelService.GetTerminalSettingsAsync( + string terminalId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + + +### **PATCH** **/terminals/{terminalId}/terminalLogos** + +Update the logo + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **terminalId** | [string] | The unique identifier of the payment terminal. | +| **logo** | **Logo** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsTerminalLevelService.UpdateLogo` usage: +// Provide the following values: terminalId, logo +ILogo response = await terminalSettingsTerminalLevelService.UpdateLogoAsync( + string terminalId, Logo logo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Logo result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Logo]() + + + +### **PATCH** **/terminals/{terminalId}/terminalSettings** + +Update terminal settings + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **terminalId** | [string] | The unique identifier of the payment terminal. | +| **terminalSettings** | **TerminalSettings** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalSettingsTerminalLevelService.UpdateTerminalSettings` usage: +// Provide the following values: terminalId, terminalSettings +ITerminalSettings response = await terminalSettingsTerminalLevelService.UpdateTerminalSettingsAsync( + string terminalId, TerminalSettings terminalSettings, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TerminalSettings result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TerminalSettings]() + + diff --git a/docs/Management/TerminalsTerminalLevelService.md b/docs/Management/TerminalsTerminalLevelService.md new file mode 100644 index 000000000..2550dfb89 --- /dev/null +++ b/docs/Management/TerminalsTerminalLevelService.md @@ -0,0 +1,122 @@ +## Adyen.Management.Services.TerminalsTerminalLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITerminalsTerminalLevelService terminalsTerminalLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ListTerminals**](TerminalsTerminalLevelService.md#listterminals) | **GET** /terminals | Get a list of terminals | +| [**ReassignTerminal**](TerminalsTerminalLevelService.md#reassignterminal) | **POST** /terminals/{terminalId}/reassign | Reassign a terminal | + + +### **GET** **/terminals** + +Get a list of terminals + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **searchQuery** | [string] | Returns terminals with an ID that contains the specified string. If present, other query parameters are ignored. | +| **otpQuery** | [string] | Returns one or more terminals associated with the one-time passwords specified in the request. If this query parameter is used, other query parameters are ignored. | +| **countries** | [string] | Returns terminals located in the countries specified by their [two-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). | +| **merchantIds** | [string] | Returns terminals that belong to the merchant accounts specified by their unique merchant account ID. | +| **storeIds** | [string] | Returns terminals that are assigned to the [stores](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/stores) specified by their unique store ID. | +| **brandModels** | [string] | Returns terminals of the [models](https://docs.adyen.com/api-explorer/#/ManagementService/latest/get/companies/{companyId}/terminalModels) specified in the format *brand.model*. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 20 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalsTerminalLevelService.ListTerminals` usage: +// Provide the following values: searchQuery, otpQuery, countries, merchantIds, storeIds, brandModels, pageNumber, pageSize +IListTerminalsResponse response = await terminalsTerminalLevelService.ListTerminalsAsync( + Option searchQuery = default, Option otpQuery = default, Option countries = default, Option merchantIds = default, Option storeIds = default, Option brandModels = default, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListTerminalsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListTerminalsResponse]() + + + +### **POST** **/terminals/{terminalId}/reassign** + +Reassign a terminal + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **terminalId** | [string] | The unique identifier of the payment terminal. | +| **terminalReassignmentRequest** | **TerminalReassignmentRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `TerminalsTerminalLevelService.ReassignTerminal` usage: +// Provide the following values: terminalId, terminalReassignmentRequest +await terminalsTerminalLevelService.ReassignTerminalAsync( + string terminalId, TerminalReassignmentRequest terminalReassignmentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/Management/UsersCompanyLevelService.md b/docs/Management/UsersCompanyLevelService.md new file mode 100644 index 000000000..4a77f96fc --- /dev/null +++ b/docs/Management/UsersCompanyLevelService.md @@ -0,0 +1,193 @@ +## Adyen.Management.Services.UsersCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IUsersCompanyLevelService usersCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateNewUser**](UsersCompanyLevelService.md#createnewuser) | **POST** /companies/{companyId}/users | Create a new user | +| [**GetUserDetails**](UsersCompanyLevelService.md#getuserdetails) | **GET** /companies/{companyId}/users/{userId} | Get user details | +| [**ListUsers**](UsersCompanyLevelService.md#listusers) | **GET** /companies/{companyId}/users | Get a list of users | +| [**UpdateUserDetails**](UsersCompanyLevelService.md#updateuserdetails) | **PATCH** /companies/{companyId}/users/{userId} | Update user details | + + +### **POST** **/companies/{companyId}/users** + +Create a new user + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **createCompanyUserRequest** | **CreateCompanyUserRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersCompanyLevelService.CreateNewUser` usage: +// Provide the following values: companyId, createCompanyUserRequest +ICreateCompanyUserResponse response = await usersCompanyLevelService.CreateNewUserAsync( + string companyId, CreateCompanyUserRequest createCompanyUserRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateCompanyUserResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateCompanyUserResponse]() + + + +### **GET** **/companies/{companyId}/users/{userId}** + +Get user details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **userId** | [string] | The unique identifier of the user. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersCompanyLevelService.GetUserDetails` usage: +// Provide the following values: companyId, userId +ICompanyUser response = await usersCompanyLevelService.GetUserDetailsAsync( + string companyId, string userId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CompanyUser result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CompanyUser]() + + + +### **GET** **/companies/{companyId}/users** + +Get a list of users + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **pageNumber** | [int] | The number of the page to return. | +| **pageSize** | [int] | The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. | +| **username** | [string] | The partial or complete username to select all users that match. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersCompanyLevelService.ListUsers` usage: +// Provide the following values: companyId, pageNumber, pageSize, username +IListCompanyUsersResponse response = await usersCompanyLevelService.ListUsersAsync( + string companyId, Option pageNumber = default, Option pageSize = default, Option username = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListCompanyUsersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListCompanyUsersResponse]() + + + +### **PATCH** **/companies/{companyId}/users/{userId}** + +Update user details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **userId** | [string] | The unique identifier of the user. | +| **updateCompanyUserRequest** | **UpdateCompanyUserRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersCompanyLevelService.UpdateUserDetails` usage: +// Provide the following values: companyId, userId, updateCompanyUserRequest +ICompanyUser response = await usersCompanyLevelService.UpdateUserDetailsAsync( + string companyId, string userId, UpdateCompanyUserRequest updateCompanyUserRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CompanyUser result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CompanyUser]() + + diff --git a/docs/Management/UsersMerchantLevelService.md b/docs/Management/UsersMerchantLevelService.md new file mode 100644 index 000000000..b389367ef --- /dev/null +++ b/docs/Management/UsersMerchantLevelService.md @@ -0,0 +1,193 @@ +## Adyen.Management.Services.UsersMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IUsersMerchantLevelService usersMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateNewUser**](UsersMerchantLevelService.md#createnewuser) | **POST** /merchants/{merchantId}/users | Create a new user | +| [**GetUserDetails**](UsersMerchantLevelService.md#getuserdetails) | **GET** /merchants/{merchantId}/users/{userId} | Get user details | +| [**ListUsers**](UsersMerchantLevelService.md#listusers) | **GET** /merchants/{merchantId}/users | Get a list of users | +| [**UpdateUser**](UsersMerchantLevelService.md#updateuser) | **PATCH** /merchants/{merchantId}/users/{userId} | Update a user | + + +### **POST** **/merchants/{merchantId}/users** + +Create a new user + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | Unique identifier of the merchant. | +| **createMerchantUserRequest** | **CreateMerchantUserRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersMerchantLevelService.CreateNewUser` usage: +// Provide the following values: merchantId, createMerchantUserRequest +ICreateUserResponse response = await usersMerchantLevelService.CreateNewUserAsync( + string merchantId, CreateMerchantUserRequest createMerchantUserRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateUserResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateUserResponse]() + + + +### **GET** **/merchants/{merchantId}/users/{userId}** + +Get user details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | Unique identifier of the merchant. | +| **userId** | [string] | Unique identifier of the user. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersMerchantLevelService.GetUserDetails` usage: +// Provide the following values: merchantId, userId +IUser response = await usersMerchantLevelService.GetUserDetailsAsync( + string merchantId, string userId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out User result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[User]() + + + +### **GET** **/merchants/{merchantId}/users** + +Get a list of users + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | Unique identifier of the merchant. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page. Maximum value is **100**. The default is **10** items on a page. | +| **username** | [string] | The partial or complete username to select all users that match. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersMerchantLevelService.ListUsers` usage: +// Provide the following values: merchantId, pageNumber, pageSize, username +IListMerchantUsersResponse response = await usersMerchantLevelService.ListUsersAsync( + string merchantId, Option pageNumber = default, Option pageSize = default, Option username = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListMerchantUsersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListMerchantUsersResponse]() + + + +### **PATCH** **/merchants/{merchantId}/users/{userId}** + +Update a user + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | Unique identifier of the merchant. | +| **userId** | [string] | Unique identifier of the user. | +| **updateMerchantUserRequest** | **UpdateMerchantUserRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `UsersMerchantLevelService.UpdateUser` usage: +// Provide the following values: merchantId, userId, updateMerchantUserRequest +IUser response = await usersMerchantLevelService.UpdateUserAsync( + string merchantId, string userId, UpdateMerchantUserRequest updateMerchantUserRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out User result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[User]() + + diff --git a/docs/Management/WebhooksCompanyLevelService.md b/docs/Management/WebhooksCompanyLevelService.md new file mode 100644 index 000000000..eef61e94e --- /dev/null +++ b/docs/Management/WebhooksCompanyLevelService.md @@ -0,0 +1,304 @@ +## Adyen.Management.Services.WebhooksCompanyLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IWebhooksCompanyLevelService webhooksCompanyLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateHmacKey**](WebhooksCompanyLevelService.md#generatehmackey) | **POST** /companies/{companyId}/webhooks/{webhookId}/generateHmac | Generate an HMAC key | +| [**GetWebhook**](WebhooksCompanyLevelService.md#getwebhook) | **GET** /companies/{companyId}/webhooks/{webhookId} | Get a webhook | +| [**ListAllWebhooks**](WebhooksCompanyLevelService.md#listallwebhooks) | **GET** /companies/{companyId}/webhooks | List all webhooks | +| [**RemoveWebhook**](WebhooksCompanyLevelService.md#removewebhook) | **DELETE** /companies/{companyId}/webhooks/{webhookId} | Remove a webhook | +| [**SetUpWebhook**](WebhooksCompanyLevelService.md#setupwebhook) | **POST** /companies/{companyId}/webhooks | Set up a webhook | +| [**TestWebhook**](WebhooksCompanyLevelService.md#testwebhook) | **POST** /companies/{companyId}/webhooks/{webhookId}/test | Test a webhook | +| [**UpdateWebhook**](WebhooksCompanyLevelService.md#updatewebhook) | **PATCH** /companies/{companyId}/webhooks/{webhookId} | Update a webhook | + + +### **POST** **/companies/{companyId}/webhooks/{webhookId}/generateHmac** + +Generate an HMAC key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.GenerateHmacKey` usage: +// Provide the following values: companyId, webhookId +IGenerateHmacKeyResponse response = await webhooksCompanyLevelService.GenerateHmacKeyAsync( + string companyId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateHmacKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateHmacKeyResponse]() + + + +### **GET** **/companies/{companyId}/webhooks/{webhookId}** + +Get a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.GetWebhook` usage: +// Provide the following values: companyId, webhookId +IWebhook response = await webhooksCompanyLevelService.GetWebhookAsync( + string companyId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + + +### **GET** **/companies/{companyId}/webhooks** + +List all webhooks + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.ListAllWebhooks` usage: +// Provide the following values: companyId, pageNumber, pageSize +IListWebhooksResponse response = await webhooksCompanyLevelService.ListAllWebhooksAsync( + string companyId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListWebhooksResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListWebhooksResponse]() + + + +### **DELETE** **/companies/{companyId}/webhooks/{webhookId}** + +Remove a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.RemoveWebhook` usage: +// Provide the following values: companyId, webhookId +await webhooksCompanyLevelService.RemoveWebhookAsync( + string companyId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **POST** **/companies/{companyId}/webhooks** + +Set up a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | Unique identifier of the [company account](https://docs.adyen.com/account/account-structure#company-account). | +| **createCompanyWebhookRequest** | **CreateCompanyWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.SetUpWebhook` usage: +// Provide the following values: companyId, createCompanyWebhookRequest +IWebhook response = await webhooksCompanyLevelService.SetUpWebhookAsync( + string companyId, CreateCompanyWebhookRequest createCompanyWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + + +### **POST** **/companies/{companyId}/webhooks/{webhookId}/test** + +Test a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | +| **testCompanyWebhookRequest** | **TestCompanyWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.TestWebhook` usage: +// Provide the following values: companyId, webhookId, testCompanyWebhookRequest +ITestWebhookResponse response = await webhooksCompanyLevelService.TestWebhookAsync( + string companyId, string webhookId, TestCompanyWebhookRequest testCompanyWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TestWebhookResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TestWebhookResponse]() + + + +### **PATCH** **/companies/{companyId}/webhooks/{webhookId}** + +Update a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **companyId** | [string] | The unique identifier of the company account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | +| **updateCompanyWebhookRequest** | **UpdateCompanyWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksCompanyLevelService.UpdateWebhook` usage: +// Provide the following values: companyId, webhookId, updateCompanyWebhookRequest +IWebhook response = await webhooksCompanyLevelService.UpdateWebhookAsync( + string companyId, string webhookId, UpdateCompanyWebhookRequest updateCompanyWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + diff --git a/docs/Management/WebhooksMerchantLevelService.md b/docs/Management/WebhooksMerchantLevelService.md new file mode 100644 index 000000000..932a7dffa --- /dev/null +++ b/docs/Management/WebhooksMerchantLevelService.md @@ -0,0 +1,304 @@ +## Adyen.Management.Services.WebhooksMerchantLevelService + +#### API Base-Path: **https://management-test.adyen.com/v3** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Management.Extensions; +using Adyen.Management.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IWebhooksMerchantLevelService webhooksMerchantLevelService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GenerateHmacKey**](WebhooksMerchantLevelService.md#generatehmackey) | **POST** /merchants/{merchantId}/webhooks/{webhookId}/generateHmac | Generate an HMAC key | +| [**GetWebhook**](WebhooksMerchantLevelService.md#getwebhook) | **GET** /merchants/{merchantId}/webhooks/{webhookId} | Get a webhook | +| [**ListAllWebhooks**](WebhooksMerchantLevelService.md#listallwebhooks) | **GET** /merchants/{merchantId}/webhooks | List all webhooks | +| [**RemoveWebhook**](WebhooksMerchantLevelService.md#removewebhook) | **DELETE** /merchants/{merchantId}/webhooks/{webhookId} | Remove a webhook | +| [**SetUpWebhook**](WebhooksMerchantLevelService.md#setupwebhook) | **POST** /merchants/{merchantId}/webhooks | Set up a webhook | +| [**TestWebhook**](WebhooksMerchantLevelService.md#testwebhook) | **POST** /merchants/{merchantId}/webhooks/{webhookId}/test | Test a webhook | +| [**UpdateWebhook**](WebhooksMerchantLevelService.md#updatewebhook) | **PATCH** /merchants/{merchantId}/webhooks/{webhookId} | Update a webhook | + + +### **POST** **/merchants/{merchantId}/webhooks/{webhookId}/generateHmac** + +Generate an HMAC key + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **webhookId** | [string] | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.GenerateHmacKey` usage: +// Provide the following values: merchantId, webhookId +IGenerateHmacKeyResponse response = await webhooksMerchantLevelService.GenerateHmacKeyAsync( + string merchantId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GenerateHmacKeyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GenerateHmacKeyResponse]() + + + +### **GET** **/merchants/{merchantId}/webhooks/{webhookId}** + +Get a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.GetWebhook` usage: +// Provide the following values: merchantId, webhookId +IWebhook response = await webhooksMerchantLevelService.GetWebhookAsync( + string merchantId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + + +### **GET** **/merchants/{merchantId}/webhooks** + +List all webhooks + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **pageNumber** | [int] | The number of the page to fetch. | +| **pageSize** | [int] | The number of items to have on a page, maximum 100. The default is 10 items on a page. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.ListAllWebhooks` usage: +// Provide the following values: merchantId, pageNumber, pageSize +IListWebhooksResponse response = await webhooksMerchantLevelService.ListAllWebhooksAsync( + string merchantId, Option pageNumber = default, Option pageSize = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ListWebhooksResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ListWebhooksResponse]() + + + +### **DELETE** **/merchants/{merchantId}/webhooks/{webhookId}** + +Remove a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.RemoveWebhook` usage: +// Provide the following values: merchantId, webhookId +await webhooksMerchantLevelService.RemoveWebhookAsync( + string merchantId, string webhookId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **POST** **/merchants/{merchantId}/webhooks** + +Set up a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **createMerchantWebhookRequest** | **CreateMerchantWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.SetUpWebhook` usage: +// Provide the following values: merchantId, createMerchantWebhookRequest +IWebhook response = await webhooksMerchantLevelService.SetUpWebhookAsync( + string merchantId, CreateMerchantWebhookRequest createMerchantWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + + +### **POST** **/merchants/{merchantId}/webhooks/{webhookId}/test** + +Test a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | +| **testWebhookRequest** | **TestWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.TestWebhook` usage: +// Provide the following values: merchantId, webhookId, testWebhookRequest +ITestWebhookResponse response = await webhooksMerchantLevelService.TestWebhookAsync( + string merchantId, string webhookId, TestWebhookRequest testWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TestWebhookResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TestWebhookResponse]() + + + +### **PATCH** **/merchants/{merchantId}/webhooks/{webhookId}** + +Update a webhook + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **webhookId** | [string] | Unique identifier of the webhook configuration. | +| **updateMerchantWebhookRequest** | **UpdateMerchantWebhookRequest** | | + +#### Example usage + +```csharp +using Adyen.Management.Models; +using Adyen.Management.Services; + +// Example `WebhooksMerchantLevelService.UpdateWebhook` usage: +// Provide the following values: merchantId, webhookId, updateMerchantWebhookRequest +IWebhook response = await webhooksMerchantLevelService.UpdateWebhookAsync( + string merchantId, string webhookId, UpdateMerchantWebhookRequest updateMerchantWebhookRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Webhook result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Webhook]() + + diff --git a/docs/Payment/ModificationsService.md b/docs/Payment/ModificationsService.md new file mode 100644 index 000000000..035c046af --- /dev/null +++ b/docs/Payment/ModificationsService.md @@ -0,0 +1,330 @@ +## Adyen.Payment.Services.ModificationsService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Payment/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Payment.Extensions; +using Adyen.Payment.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePayment((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IModificationsService modificationsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AdjustAuthorisation**](ModificationsService.md#adjustauthorisation) | **POST** /adjustAuthorisation | Change the authorised amount | +| [**Cancel**](ModificationsService.md#cancel) | **POST** /cancel | Cancel an authorisation | +| [**CancelOrRefund**](ModificationsService.md#cancelorrefund) | **POST** /cancelOrRefund | Cancel or refund a payment | +| [**Capture**](ModificationsService.md#capture) | **POST** /capture | Capture an authorisation | +| [**Donate**](ModificationsService.md#donate) | **POST** /donate | Create a donation | +| [**Refund**](ModificationsService.md#refund) | **POST** /refund | Refund a captured payment | +| [**TechnicalCancel**](ModificationsService.md#technicalcancel) | **POST** /technicalCancel | Cancel an authorisation using your reference | +| [**VoidPendingRefund**](ModificationsService.md#voidpendingrefund) | **POST** /voidPendingRefund | Cancel an in-person refund | + + +### **POST** **/adjustAuthorisation** + +Change the authorised amount + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **adjustAuthorisationRequest** | **AdjustAuthorisationRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.AdjustAuthorisation` usage: +// Provide the following values: adjustAuthorisationRequest +IModificationResult response = await modificationsService.AdjustAuthorisationAsync( + AdjustAuthorisationRequest adjustAuthorisationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/cancel** + +Cancel an authorisation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **cancelRequest** | **CancelRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.Cancel` usage: +// Provide the following values: cancelRequest +IModificationResult response = await modificationsService.CancelAsync( + CancelRequest cancelRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/cancelOrRefund** + +Cancel or refund a payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **cancelOrRefundRequest** | **CancelOrRefundRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.CancelOrRefund` usage: +// Provide the following values: cancelOrRefundRequest +IModificationResult response = await modificationsService.CancelOrRefundAsync( + CancelOrRefundRequest cancelOrRefundRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/capture** + +Capture an authorisation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **captureRequest** | **CaptureRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.Capture` usage: +// Provide the following values: captureRequest +IModificationResult response = await modificationsService.CaptureAsync( + CaptureRequest captureRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/donate** + +Create a donation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **donationRequest** | **DonationRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.Donate` usage: +// Provide the following values: donationRequest +IModificationResult response = await modificationsService.DonateAsync( + DonationRequest donationRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/refund** + +Refund a captured payment + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **refundRequest** | **RefundRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.Refund` usage: +// Provide the following values: refundRequest +IModificationResult response = await modificationsService.RefundAsync( + RefundRequest refundRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/technicalCancel** + +Cancel an authorisation using your reference + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **technicalCancelRequest** | **TechnicalCancelRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.TechnicalCancel` usage: +// Provide the following values: technicalCancelRequest +IModificationResult response = await modificationsService.TechnicalCancelAsync( + TechnicalCancelRequest technicalCancelRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + + +### **POST** **/voidPendingRefund** + +Cancel an in-person refund + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **voidPendingRefundRequest** | **VoidPendingRefundRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `ModificationsService.VoidPendingRefund` usage: +// Provide the following values: voidPendingRefundRequest +IModificationResult response = await modificationsService.VoidPendingRefundAsync( + VoidPendingRefundRequest voidPendingRefundRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModificationResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModificationResult]() + + diff --git a/docs/Payment/PaymentsService.md b/docs/Payment/PaymentsService.md new file mode 100644 index 000000000..802402d1f --- /dev/null +++ b/docs/Payment/PaymentsService.md @@ -0,0 +1,222 @@ +## Adyen.Payment.Services.PaymentsService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Payment/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Payment.Extensions; +using Adyen.Payment.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePayment((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentsService paymentsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**Authorise**](PaymentsService.md#authorise) | **POST** /authorise | Create an authorisation | +| [**Authorise3d**](PaymentsService.md#authorise3d) | **POST** /authorise3d | Complete a 3DS authorisation | +| [**Authorise3ds2**](PaymentsService.md#authorise3ds2) | **POST** /authorise3ds2 | Complete a 3DS2 authorisation | +| [**GetAuthenticationResult**](PaymentsService.md#getauthenticationresult) | **POST** /getAuthenticationResult | Get the 3DS authentication result | +| [**Retrieve3ds2Result**](PaymentsService.md#retrieve3ds2result) | **POST** /retrieve3ds2Result | Get the 3DS2 authentication result | + + +### **POST** **/authorise** + +Create an authorisation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentRequest** | **PaymentRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `PaymentsService.Authorise` usage: +// Provide the following values: paymentRequest +IPaymentResult response = await paymentsService.AuthoriseAsync( + PaymentRequest paymentRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentResult]() + + + +### **POST** **/authorise3d** + +Complete a 3DS authorisation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentRequest3d** | **PaymentRequest3d** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `PaymentsService.Authorise3d` usage: +// Provide the following values: paymentRequest3d +IPaymentResult response = await paymentsService.Authorise3dAsync( + PaymentRequest3d paymentRequest3d, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentResult]() + + + +### **POST** **/authorise3ds2** + +Complete a 3DS2 authorisation + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **paymentRequest3ds2** | **PaymentRequest3ds2** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `PaymentsService.Authorise3ds2` usage: +// Provide the following values: paymentRequest3ds2 +IPaymentResult response = await paymentsService.Authorise3ds2Async( + PaymentRequest3ds2 paymentRequest3ds2, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentResult]() + + + +### **POST** **/getAuthenticationResult** + +Get the 3DS authentication result + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **authenticationResultRequest** | **AuthenticationResultRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `PaymentsService.GetAuthenticationResult` usage: +// Provide the following values: authenticationResultRequest +IAuthenticationResultResponse response = await paymentsService.GetAuthenticationResultAsync( + AuthenticationResultRequest authenticationResultRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AuthenticationResultResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AuthenticationResultResponse]() + + + +### **POST** **/retrieve3ds2Result** + +Get the 3DS2 authentication result + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **threeDS2ResultRequest** | **ThreeDS2ResultRequest** | | + +#### Example usage + +```csharp +using Adyen.Payment.Models; +using Adyen.Payment.Services; + +// Example `PaymentsService.Retrieve3ds2Result` usage: +// Provide the following values: threeDS2ResultRequest +IThreeDS2ResultResponse response = await paymentsService.Retrieve3ds2ResultAsync( + ThreeDS2ResultRequest threeDS2ResultRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ThreeDS2ResultResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ThreeDS2ResultResponse]() + + diff --git a/docs/PaymentsApp/PaymentsAppService.md b/docs/PaymentsApp/PaymentsAppService.md new file mode 100644 index 000000000..9f38034a9 --- /dev/null +++ b/docs/PaymentsApp/PaymentsAppService.md @@ -0,0 +1,233 @@ +## Adyen.PaymentsApp.Services.PaymentsAppService + +#### API Base-Path: **https://management-live.adyen.com/v1** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.PaymentsApp.Extensions; +using Adyen.PaymentsApp.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePaymentsApp((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPaymentsAppService paymentsAppService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GeneratePaymentsAppBoardingTokenForMerchant**](PaymentsAppService.md#generatepaymentsappboardingtokenformerchant) | **POST** /merchants/{merchantId}/generatePaymentsAppBoardingToken | Create a boarding token - merchant level | +| [**GeneratePaymentsAppBoardingTokenForStore**](PaymentsAppService.md#generatepaymentsappboardingtokenforstore) | **POST** /merchants/{merchantId}/stores/{storeId}/generatePaymentsAppBoardingToken | Create a boarding token - store level | +| [**ListPaymentsAppForMerchant**](PaymentsAppService.md#listpaymentsappformerchant) | **GET** /merchants/{merchantId}/paymentsApps | Get a list of Payments Apps - merchant level | +| [**ListPaymentsAppForStore**](PaymentsAppService.md#listpaymentsappforstore) | **GET** /merchants/{merchantId}/stores/{storeId}/paymentsApps | Get a list of Payments Apps - store level | +| [**RevokePaymentsApp**](PaymentsAppService.md#revokepaymentsapp) | **POST** /merchants/{merchantId}/paymentsApps/{installationId}/revoke | Revoke Payments App instance authentication | + + +### **POST** **/merchants/{merchantId}/generatePaymentsAppBoardingToken** + +Create a boarding token - merchant level + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **boardingTokenRequest** | **BoardingTokenRequest** | | + +#### Example usage + +```csharp +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Services; + +// Example `PaymentsAppService.GeneratePaymentsAppBoardingTokenForMerchant` usage: +// Provide the following values: merchantId, boardingTokenRequest +IBoardingTokenResponse response = await paymentsAppService.GeneratePaymentsAppBoardingTokenForMerchantAsync( + string merchantId, BoardingTokenRequest boardingTokenRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BoardingTokenResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BoardingTokenResponse]() + + + +### **POST** **/merchants/{merchantId}/stores/{storeId}/generatePaymentsAppBoardingToken** + +Create a boarding token - store level + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeId** | [string] | The unique identifier of the store. | +| **boardingTokenRequest** | **BoardingTokenRequest** | | + +#### Example usage + +```csharp +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Services; + +// Example `PaymentsAppService.GeneratePaymentsAppBoardingTokenForStore` usage: +// Provide the following values: merchantId, storeId, boardingTokenRequest +IBoardingTokenResponse response = await paymentsAppService.GeneratePaymentsAppBoardingTokenForStoreAsync( + string merchantId, string storeId, BoardingTokenRequest boardingTokenRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out BoardingTokenResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[BoardingTokenResponse]() + + + +### **GET** **/merchants/{merchantId}/paymentsApps** + +Get a list of Payments Apps - merchant level + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **statuses** | [string] | The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** | +| **limit** | [int] | The number of items to return. | +| **offset** | [long] | The number of items to skip. | + +#### Example usage + +```csharp +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Services; + +// Example `PaymentsAppService.ListPaymentsAppForMerchant` usage: +// Provide the following values: merchantId, statuses, limit, offset +IPaymentsAppResponse response = await paymentsAppService.ListPaymentsAppForMerchantAsync( + string merchantId, Option statuses = default, Option limit = default, Option offset = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentsAppResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentsAppResponse]() + + + +### **GET** **/merchants/{merchantId}/stores/{storeId}/paymentsApps** + +Get a list of Payments Apps - store level + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **storeId** | [string] | The unique identifier of the store. | +| **statuses** | [string] | The status of the Payments App. Comma-separated list of one or more values. If no value is provided, the list returns all statuses. Possible values: * **BOARDING** * **BOARDED** * **REVOKED** | +| **limit** | [int] | The number of items to return. | +| **offset** | [long] | The number of items to skip. | + +#### Example usage + +```csharp +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Services; + +// Example `PaymentsAppService.ListPaymentsAppForStore` usage: +// Provide the following values: merchantId, storeId, statuses, limit, offset +IPaymentsAppResponse response = await paymentsAppService.ListPaymentsAppForStoreAsync( + string merchantId, string storeId, Option statuses = default, Option limit = default, Option offset = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PaymentsAppResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PaymentsAppResponse]() + + + +### **POST** **/merchants/{merchantId}/paymentsApps/{installationId}/revoke** + +Revoke Payments App instance authentication + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **merchantId** | [string] | The unique identifier of the merchant account. | +| **installationId** | [string] | The unique identifier of the Payments App instance on a device. | + +#### Example usage + +```csharp +using Adyen.PaymentsApp.Models; +using Adyen.PaymentsApp.Services; + +// Example `PaymentsAppService.RevokePaymentsApp` usage: +// Provide the following values: merchantId, installationId +await paymentsAppService.RevokePaymentsAppAsync( + string merchantId, string installationId, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + diff --git a/docs/Payout/InitializationService.md b/docs/Payout/InitializationService.md new file mode 100644 index 000000000..7a06fbba1 --- /dev/null +++ b/docs/Payout/InitializationService.md @@ -0,0 +1,150 @@ +## Adyen.Payout.Services.InitializationService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Payout/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Payout.Extensions; +using Adyen.Payout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePayout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IInitializationService initializationService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**StoreDetail**](InitializationService.md#storedetail) | **POST** /storeDetail | Store payout details | +| [**StoreDetailAndSubmitThirdParty**](InitializationService.md#storedetailandsubmitthirdparty) | **POST** /storeDetailAndSubmitThirdParty | Store details and submit a payout | +| [**SubmitThirdParty**](InitializationService.md#submitthirdparty) | **POST** /submitThirdParty | Submit a payout | + + +### **POST** **/storeDetail** + +Store payout details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeDetailRequest** | **StoreDetailRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `InitializationService.StoreDetail` usage: +// Provide the following values: storeDetailRequest +IStoreDetailResponse response = await initializationService.StoreDetailAsync( + StoreDetailRequest storeDetailRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoreDetailResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoreDetailResponse]() + + + +### **POST** **/storeDetailAndSubmitThirdParty** + +Store details and submit a payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storeDetailAndSubmitRequest** | **StoreDetailAndSubmitRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `InitializationService.StoreDetailAndSubmitThirdParty` usage: +// Provide the following values: storeDetailAndSubmitRequest +IStoreDetailAndSubmitResponse response = await initializationService.StoreDetailAndSubmitThirdPartyAsync( + StoreDetailAndSubmitRequest storeDetailAndSubmitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoreDetailAndSubmitResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoreDetailAndSubmitResponse]() + + + +### **POST** **/submitThirdParty** + +Submit a payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **submitRequest** | **SubmitRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `InitializationService.SubmitThirdParty` usage: +// Provide the following values: submitRequest +ISubmitResponse response = await initializationService.SubmitThirdPartyAsync( + SubmitRequest submitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out SubmitResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[SubmitResponse]() + + diff --git a/docs/Payout/InstantPayoutsService.md b/docs/Payout/InstantPayoutsService.md new file mode 100644 index 000000000..85b495089 --- /dev/null +++ b/docs/Payout/InstantPayoutsService.md @@ -0,0 +1,78 @@ +## Adyen.Payout.Services.InstantPayoutsService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Payout/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Payout.Extensions; +using Adyen.Payout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePayout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IInstantPayoutsService instantPayoutsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**Payout**](InstantPayoutsService.md#payout) | **POST** /payout | Make an instant card payout | + + +### **POST** **/payout** + +Make an instant card payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **payoutRequest** | **PayoutRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `InstantPayoutsService.Payout` usage: +// Provide the following values: payoutRequest +IPayoutResponse response = await instantPayoutsService.PayoutAsync( + PayoutRequest payoutRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out PayoutResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[PayoutResponse]() + + diff --git a/docs/Payout/ReviewingService.md b/docs/Payout/ReviewingService.md new file mode 100644 index 000000000..907d91a9e --- /dev/null +++ b/docs/Payout/ReviewingService.md @@ -0,0 +1,114 @@ +## Adyen.Payout.Services.ReviewingService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Payout/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Payout.Extensions; +using Adyen.Payout.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePayout((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IReviewingService reviewingService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ConfirmThirdParty**](ReviewingService.md#confirmthirdparty) | **POST** /confirmThirdParty | Confirm a payout | +| [**DeclineThirdParty**](ReviewingService.md#declinethirdparty) | **POST** /declineThirdParty | Cancel a payout | + + +### **POST** **/confirmThirdParty** + +Confirm a payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **modifyRequest** | **ModifyRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `ReviewingService.ConfirmThirdParty` usage: +// Provide the following values: modifyRequest +IModifyResponse response = await reviewingService.ConfirmThirdPartyAsync( + ModifyRequest modifyRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModifyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModifyResponse]() + + + +### **POST** **/declineThirdParty** + +Cancel a payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **modifyRequest** | **ModifyRequest** | | + +#### Example usage + +```csharp +using Adyen.Payout.Models; +using Adyen.Payout.Services; + +// Example `ReviewingService.DeclineThirdParty` usage: +// Provide the following values: modifyRequest +IModifyResponse response = await reviewingService.DeclineThirdPartyAsync( + ModifyRequest modifyRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ModifyResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ModifyResponse]() + + diff --git a/docs/PosMobile/PosMobileService.md b/docs/PosMobile/PosMobileService.md new file mode 100644 index 000000000..1847d1bcd --- /dev/null +++ b/docs/PosMobile/PosMobileService.md @@ -0,0 +1,78 @@ +## Adyen.PosMobile.Services.PosMobileService + +#### API Base-Path: **https://checkout-test.adyen.com/checkout/possdk/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.PosMobile.Extensions; +using Adyen.PosMobile.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePosMobile((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPosMobileService posMobileService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateCommunicationSession**](PosMobileService.md#createcommunicationsession) | **POST** /sessions | Create a communication session | + + +### **POST** **/sessions** + +Create a communication session + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createSessionRequest** | **CreateSessionRequest** | | + +#### Example usage + +```csharp +using Adyen.PosMobile.Models; +using Adyen.PosMobile.Services; + +// Example `PosMobileService.CreateCommunicationSession` usage: +// Provide the following values: createSessionRequest +ICreateSessionResponse response = await posMobileService.CreateCommunicationSessionAsync( + CreateSessionRequest createSessionRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreateSessionResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreateSessionResponse]() + + diff --git a/docs/PosTerminalManagement/PosTerminalManagementService.md b/docs/PosTerminalManagement/PosTerminalManagementService.md new file mode 100644 index 000000000..123dbdc6b --- /dev/null +++ b/docs/PosTerminalManagement/PosTerminalManagementService.md @@ -0,0 +1,222 @@ +## Adyen.PosTerminalManagement.Services.PosTerminalManagementService + +#### API Base-Path: **https://postfmapi-test.adyen.com/postfmapi/terminal/v1** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.PosTerminalManagement.Extensions; +using Adyen.PosTerminalManagement.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigurePosTerminalManagement((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IPosTerminalManagementService posTerminalManagementService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AssignTerminals**](PosTerminalManagementService.md#assignterminals) | **POST** /assignTerminals | Assign terminals | +| [**FindTerminal**](PosTerminalManagementService.md#findterminal) | **POST** /findTerminal | Get the account or store of a terminal | +| [**GetStoresUnderAccount**](PosTerminalManagementService.md#getstoresunderaccount) | **POST** /getStoresUnderAccount | Get the stores of an account | +| [**GetTerminalDetails**](PosTerminalManagementService.md#getterminaldetails) | **POST** /getTerminalDetails | Get the details of a terminal | +| [**GetTerminalsUnderAccount**](PosTerminalManagementService.md#getterminalsunderaccount) | **POST** /getTerminalsUnderAccount | Get the list of terminals | + + +### **POST** **/assignTerminals** + +Assign terminals + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **assignTerminalsRequest** | **AssignTerminalsRequest** | | + +#### Example usage + +```csharp +using Adyen.PosTerminalManagement.Models; +using Adyen.PosTerminalManagement.Services; + +// Example `PosTerminalManagementService.AssignTerminals` usage: +// Provide the following values: assignTerminalsRequest +IAssignTerminalsResponse response = await posTerminalManagementService.AssignTerminalsAsync( + AssignTerminalsRequest assignTerminalsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AssignTerminalsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AssignTerminalsResponse]() + + + +### **POST** **/findTerminal** + +Get the account or store of a terminal + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **findTerminalRequest** | **FindTerminalRequest** | | + +#### Example usage + +```csharp +using Adyen.PosTerminalManagement.Models; +using Adyen.PosTerminalManagement.Services; + +// Example `PosTerminalManagementService.FindTerminal` usage: +// Provide the following values: findTerminalRequest +IFindTerminalResponse response = await posTerminalManagementService.FindTerminalAsync( + FindTerminalRequest findTerminalRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out FindTerminalResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[FindTerminalResponse]() + + + +### **POST** **/getStoresUnderAccount** + +Get the stores of an account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **getStoresUnderAccountRequest** | **GetStoresUnderAccountRequest** | | + +#### Example usage + +```csharp +using Adyen.PosTerminalManagement.Models; +using Adyen.PosTerminalManagement.Services; + +// Example `PosTerminalManagementService.GetStoresUnderAccount` usage: +// Provide the following values: getStoresUnderAccountRequest +IGetStoresUnderAccountResponse response = await posTerminalManagementService.GetStoresUnderAccountAsync( + GetStoresUnderAccountRequest getStoresUnderAccountRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetStoresUnderAccountResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetStoresUnderAccountResponse]() + + + +### **POST** **/getTerminalDetails** + +Get the details of a terminal + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **getTerminalDetailsRequest** | **GetTerminalDetailsRequest** | | + +#### Example usage + +```csharp +using Adyen.PosTerminalManagement.Models; +using Adyen.PosTerminalManagement.Services; + +// Example `PosTerminalManagementService.GetTerminalDetails` usage: +// Provide the following values: getTerminalDetailsRequest +IGetTerminalDetailsResponse response = await posTerminalManagementService.GetTerminalDetailsAsync( + GetTerminalDetailsRequest getTerminalDetailsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetTerminalDetailsResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetTerminalDetailsResponse]() + + + +### **POST** **/getTerminalsUnderAccount** + +Get the list of terminals + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **getTerminalsUnderAccountRequest** | **GetTerminalsUnderAccountRequest** | | + +#### Example usage + +```csharp +using Adyen.PosTerminalManagement.Models; +using Adyen.PosTerminalManagement.Services; + +// Example `PosTerminalManagementService.GetTerminalsUnderAccount` usage: +// Provide the following values: getTerminalsUnderAccountRequest +IGetTerminalsUnderAccountResponse response = await posTerminalManagementService.GetTerminalsUnderAccountAsync( + GetTerminalsUnderAccountRequest getTerminalsUnderAccountRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out GetTerminalsUnderAccountResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[GetTerminalsUnderAccountResponse]() + + diff --git a/docs/Recurring/RecurringService.md b/docs/Recurring/RecurringService.md new file mode 100644 index 000000000..8fc458465 --- /dev/null +++ b/docs/Recurring/RecurringService.md @@ -0,0 +1,258 @@ +## Adyen.Recurring.Services.RecurringService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/Recurring/v68** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Recurring.Extensions; +using Adyen.Recurring.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureRecurring((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IRecurringService recurringService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreatePermit**](RecurringService.md#createpermit) | **POST** /createPermit | Create new permits linked to a recurring contract. | +| [**Disable**](RecurringService.md#disable) | **POST** /disable | Disable stored payment details | +| [**DisablePermit**](RecurringService.md#disablepermit) | **POST** /disablePermit | Disable an existing permit. | +| [**ListRecurringDetails**](RecurringService.md#listrecurringdetails) | **POST** /listRecurringDetails | Get stored payment details | +| [**NotifyShopper**](RecurringService.md#notifyshopper) | **POST** /notifyShopper | Ask issuer to notify the shopper | +| [**ScheduleAccountUpdater**](RecurringService.md#scheduleaccountupdater) | **POST** /scheduleAccountUpdater | Schedule running the Account Updater | + + +### **POST** **/createPermit** + +Create new permits linked to a recurring contract. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createPermitRequest** | **CreatePermitRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.CreatePermit` usage: +// Provide the following values: createPermitRequest +ICreatePermitResult response = await recurringService.CreatePermitAsync( + CreatePermitRequest createPermitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CreatePermitResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CreatePermitResult]() + + + +### **POST** **/disable** + +Disable stored payment details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **disableRequest** | **DisableRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.Disable` usage: +// Provide the following values: disableRequest +IDisableResult response = await recurringService.DisableAsync( + DisableRequest disableRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DisableResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DisableResult]() + + + +### **POST** **/disablePermit** + +Disable an existing permit. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **disablePermitRequest** | **DisablePermitRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.DisablePermit` usage: +// Provide the following values: disablePermitRequest +IDisablePermitResult response = await recurringService.DisablePermitAsync( + DisablePermitRequest disablePermitRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out DisablePermitResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[DisablePermitResult]() + + + +### **POST** **/listRecurringDetails** + +Get stored payment details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **recurringDetailsRequest** | **RecurringDetailsRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.ListRecurringDetails` usage: +// Provide the following values: recurringDetailsRequest +IRecurringDetailsResult response = await recurringService.ListRecurringDetailsAsync( + RecurringDetailsRequest recurringDetailsRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out RecurringDetailsResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[RecurringDetailsResult]() + + + +### **POST** **/notifyShopper** + +Ask issuer to notify the shopper + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **notifyShopperRequest** | **NotifyShopperRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.NotifyShopper` usage: +// Provide the following values: notifyShopperRequest +INotifyShopperResult response = await recurringService.NotifyShopperAsync( + NotifyShopperRequest notifyShopperRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out NotifyShopperResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[NotifyShopperResult]() + + + +### **POST** **/scheduleAccountUpdater** + +Schedule running the Account Updater + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **scheduleAccountUpdaterRequest** | **ScheduleAccountUpdaterRequest** | | + +#### Example usage + +```csharp +using Adyen.Recurring.Models; +using Adyen.Recurring.Services; + +// Example `RecurringService.ScheduleAccountUpdater` usage: +// Provide the following values: scheduleAccountUpdaterRequest +IScheduleAccountUpdaterResult response = await recurringService.ScheduleAccountUpdaterAsync( + ScheduleAccountUpdaterRequest scheduleAccountUpdaterRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ScheduleAccountUpdaterResult result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ScheduleAccountUpdaterResult]() + + diff --git a/docs/SessionAuthentication/SessionAuthenticationService.md b/docs/SessionAuthentication/SessionAuthenticationService.md new file mode 100644 index 000000000..be8d94c57 --- /dev/null +++ b/docs/SessionAuthentication/SessionAuthenticationService.md @@ -0,0 +1,78 @@ +## Adyen.SessionAuthentication.Services.SessionAuthenticationService + +#### API Base-Path: **https://test.adyen.com/authe/api/v1** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.SessionAuthentication.Extensions; +using Adyen.SessionAuthentication.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureSessionAuthentication((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ISessionAuthenticationService sessionAuthenticationService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateAuthenticationSession**](SessionAuthenticationService.md#createauthenticationsession) | **POST** /sessions | Create a session token | + + +### **POST** **/sessions** + +Create a session token + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **authenticationSessionRequest** | **AuthenticationSessionRequest** | | + +#### Example usage + +```csharp +using Adyen.SessionAuthentication.Models; +using Adyen.SessionAuthentication.Services; + +// Example `SessionAuthenticationService.CreateAuthenticationSession` usage: +// Provide the following values: authenticationSessionRequest +IAuthenticationSessionResponse response = await sessionAuthenticationService.CreateAuthenticationSessionAsync( + AuthenticationSessionRequest authenticationSessionRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out AuthenticationSessionResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[AuthenticationSessionResponse]() + + diff --git a/docs/StoredValue/StoredValueService.md b/docs/StoredValue/StoredValueService.md new file mode 100644 index 000000000..d84fc0871 --- /dev/null +++ b/docs/StoredValue/StoredValueService.md @@ -0,0 +1,258 @@ +## Adyen.StoredValue.Services.StoredValueService + +#### API Base-Path: **https://pal-test.adyen.com/pal/servlet/StoredValue/v46** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.StoredValue.Extensions; +using Adyen.StoredValue.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureStoredValue((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + IStoredValueService storedValueService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ChangeStatus**](StoredValueService.md#changestatus) | **POST** /changeStatus | Changes the status of the payment method. | +| [**CheckBalance**](StoredValueService.md#checkbalance) | **POST** /checkBalance | Checks the balance. | +| [**Issue**](StoredValueService.md#issue) | **POST** /issue | Issues a new card. | +| [**Load**](StoredValueService.md#load) | **POST** /load | Loads the payment method. | +| [**MergeBalance**](StoredValueService.md#mergebalance) | **POST** /mergeBalance | Merge the balance of two cards. | +| [**VoidTransaction**](StoredValueService.md#voidtransaction) | **POST** /voidTransaction | Voids a transaction. | + + +### **POST** **/changeStatus** + +Changes the status of the payment method. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueStatusChangeRequest** | **StoredValueStatusChangeRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.ChangeStatus` usage: +// Provide the following values: storedValueStatusChangeRequest +IStoredValueStatusChangeResponse response = await storedValueService.ChangeStatusAsync( + StoredValueStatusChangeRequest storedValueStatusChangeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueStatusChangeResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueStatusChangeResponse]() + + + +### **POST** **/checkBalance** + +Checks the balance. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueBalanceCheckRequest** | **StoredValueBalanceCheckRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.CheckBalance` usage: +// Provide the following values: storedValueBalanceCheckRequest +IStoredValueBalanceCheckResponse response = await storedValueService.CheckBalanceAsync( + StoredValueBalanceCheckRequest storedValueBalanceCheckRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueBalanceCheckResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueBalanceCheckResponse]() + + + +### **POST** **/issue** + +Issues a new card. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueIssueRequest** | **StoredValueIssueRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.Issue` usage: +// Provide the following values: storedValueIssueRequest +IStoredValueIssueResponse response = await storedValueService.IssueAsync( + StoredValueIssueRequest storedValueIssueRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueIssueResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueIssueResponse]() + + + +### **POST** **/load** + +Loads the payment method. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueLoadRequest** | **StoredValueLoadRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.Load` usage: +// Provide the following values: storedValueLoadRequest +IStoredValueLoadResponse response = await storedValueService.LoadAsync( + StoredValueLoadRequest storedValueLoadRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueLoadResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueLoadResponse]() + + + +### **POST** **/mergeBalance** + +Merge the balance of two cards. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueBalanceMergeRequest** | **StoredValueBalanceMergeRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.MergeBalance` usage: +// Provide the following values: storedValueBalanceMergeRequest +IStoredValueBalanceMergeResponse response = await storedValueService.MergeBalanceAsync( + StoredValueBalanceMergeRequest storedValueBalanceMergeRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueBalanceMergeResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueBalanceMergeResponse]() + + + +### **POST** **/voidTransaction** + +Voids a transaction. + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **storedValueVoidRequest** | **StoredValueVoidRequest** | | + +#### Example usage + +```csharp +using Adyen.StoredValue.Models; +using Adyen.StoredValue.Services; + +// Example `StoredValueService.VoidTransaction` usage: +// Provide the following values: storedValueVoidRequest +IStoredValueVoidResponse response = await storedValueService.VoidTransactionAsync( + StoredValueVoidRequest storedValueVoidRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out StoredValueVoidResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[StoredValueVoidResponse]() + + diff --git a/docs/Transfers/CapitalService.md b/docs/Transfers/CapitalService.md new file mode 100644 index 000000000..bac59ab34 --- /dev/null +++ b/docs/Transfers/CapitalService.md @@ -0,0 +1,151 @@ +## Adyen.Transfers.Services.CapitalService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/btl/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Transfers.Extensions; +using Adyen.Transfers.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureTransfers((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ICapitalService capitalService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetCapitalAccount**](CapitalService.md#getcapitalaccount) | **GET** /grants | Get a capital account | +| [**GetGrantReferenceDetails**](CapitalService.md#getgrantreferencedetails) | **GET** /grants/{id} | Get grant reference details | +| [**RequestGrantPayout**](CapitalService.md#requestgrantpayout) | **POST** /grants | Request a grant payout | + + +### **GET** **/grants** + +Get a capital account + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **counterpartyAccountHolderId** | [string] | The counterparty account holder id. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `CapitalService.GetCapitalAccount` usage: +// Provide the following values: counterpartyAccountHolderId +ICapitalGrants response = await capitalService.GetCapitalAccountAsync( + Option counterpartyAccountHolderId = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CapitalGrants result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CapitalGrants]() + + + +### **GET** **/grants/{id}** + +Get grant reference details + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the grant. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `CapitalService.GetGrantReferenceDetails` usage: +// Provide the following values: id +ICapitalGrant response = await capitalService.GetGrantReferenceDetailsAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CapitalGrant result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CapitalGrant]() + + + +### **POST** **/grants** + +Request a grant payout + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **capitalGrantInfo** | **CapitalGrantInfo** | | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `CapitalService.RequestGrantPayout` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, capitalGrantInfo +ICapitalGrant response = await capitalService.RequestGrantPayoutAsync( + CapitalGrantInfo capitalGrantInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out CapitalGrant result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[CapitalGrant]() + + diff --git a/docs/Transfers/TransactionsService.md b/docs/Transfers/TransactionsService.md new file mode 100644 index 000000000..121dc5238 --- /dev/null +++ b/docs/Transfers/TransactionsService.md @@ -0,0 +1,122 @@ +## Adyen.Transfers.Services.TransactionsService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/btl/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Transfers.Extensions; +using Adyen.Transfers.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureTransfers((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransactionsService transactionsService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**GetAllTransactions**](TransactionsService.md#getalltransactions) | **GET** /transactions | Get all transactions | +| [**GetTransaction**](TransactionsService.md#gettransaction) | **GET** /transactions/{id} | Get a transaction | + + +### **GET** **/transactions** + +Get all transactions + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createdSince** | [DateTimeOffset] | Only include transactions that have been created on or after this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **createdUntil** | [DateTimeOffset] | Only include transactions that have been created on or before this point in time. The value must be in ISO 8601 format. For example, **2021-05-30T15:07:40Z**. | +| **balancePlatform** | [string] | The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. | +| **paymentInstrumentId** | [string] | The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. | +| **accountHolderId** | [string] | The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. | +| **balanceAccountId** | [string] | The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. | +| **cursor** | [string] | The `cursor` returned in the links of the previous response. | +| **sortOrder** | [string] | Determines the sort order of the returned transactions. The sort order is based on the creation date of the transaction. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. | +| **limit** | [int] | The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransactionsService.GetAllTransactions` usage: +// Provide the following values: createdSince, createdUntil, balancePlatform, paymentInstrumentId, accountHolderId, balanceAccountId, cursor, sortOrder, limit +ITransactionSearchResponse response = await transactionsService.GetAllTransactionsAsync( + DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option paymentInstrumentId = default, Option accountHolderId = default, Option balanceAccountId = default, Option cursor = default, Option sortOrder = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransactionSearchResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransactionSearchResponse]() + + + +### **GET** **/transactions/{id}** + +Get a transaction + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | The unique identifier of the transaction. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransactionsService.GetTransaction` usage: +// Provide the following values: id +ITransaction response = await transactionsService.GetTransactionAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Transaction result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Transaction]() + + diff --git a/docs/Transfers/TransfersService.md b/docs/Transfers/TransfersService.md new file mode 100644 index 000000000..c406176b0 --- /dev/null +++ b/docs/Transfers/TransfersService.md @@ -0,0 +1,275 @@ +## Adyen.Transfers.Services.TransfersService + +#### API Base-Path: **https://balanceplatform-api-test.adyen.com/btl/v4** + + +#### Authorization: ApiKeyAuth + + +#### Initialization + + +```csharp +using Adyen.Core.Options; +using Adyen.Transfers.Extensions; +using Adyen.Transfers.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .ConfigureTransfers((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + ITransfersService transfersService = host.Services.GetRequiredService(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**ApproveInitiatedTransfers**](TransfersService.md#approveinitiatedtransfers) | **POST** /transfers/approve | Approve initiated transfers | +| [**CancelInitiatedTransfers**](TransfersService.md#cancelinitiatedtransfers) | **POST** /transfers/cancel | Cancel initiated transfers | +| [**GetAllTransfers**](TransfersService.md#getalltransfers) | **GET** /transfers | Get all transfers | +| [**GetTransfer**](TransfersService.md#gettransfer) | **GET** /transfers/{id} | Get a transfer | +| [**ReturnTransfer**](TransfersService.md#returntransfer) | **POST** /transfers/{transferId}/returns | Return a transfer | +| [**TransferFunds**](TransfersService.md#transferfunds) | **POST** /transfers | Transfer funds | + + +### **POST** **/transfers/approve** + +Approve initiated transfers + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **wWWAuthenticate** | [string] | Header for authenticating through SCA | +| **approveTransfersRequest** | **ApproveTransfersRequest** | | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.ApproveInitiatedTransfers` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, [HeaderParameter] wWWAuthenticate, approveTransfersRequest +await transfersService.ApproveInitiatedTransfersAsync( + ApproveTransfersRequest approveTransfersRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **POST** **/transfers/cancel** + +Cancel initiated transfers + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **cancelTransfersRequest** | **CancelTransfersRequest** | | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.CancelInitiatedTransfers` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, cancelTransfersRequest +await transfersService.CancelInitiatedTransfersAsync( + CancelTransfersRequest cancelTransfersRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +void (empty response body) + + + +### **GET** **/transfers** + +Get all transfers + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **createdSince** | [DateTimeOffset] | Only include transfers that have been created on or after this point in time. The value must be in ISO 8601 format and not earlier than 6 months before the `createdUntil` date. For example, **2021-05-30T15:07:40Z**. | +| **createdUntil** | [DateTimeOffset] | Only include transfers that have been created on or before this point in time. The value must be in ISO 8601 format and not later than 6 months after the `createdSince` date. For example, **2021-05-30T15:07:40Z**. | +| **balancePlatform** | [string] | The unique identifier of the [balance platform](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balancePlatforms/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `accountHolderId`. | +| **accountHolderId** | [string] | The unique identifier of the [account holder](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/accountHolders/{id}__queryParam_id). Required if you don't provide a `balanceAccountId` or `balancePlatform`. If you provide a `balanceAccountId`, the `accountHolderId` must be related to the `balanceAccountId`. | +| **balanceAccountId** | [string] | The unique identifier of the [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/get/balanceAccounts/{id}__queryParam_id). Required if you don't provide an `accountHolderId` or `balancePlatform`. If you provide an `accountHolderId`, the `balanceAccountId` must be related to the `accountHolderId`. | +| **paymentInstrumentId** | [string] | The unique identifier of the [payment instrument](https://docs.adyen.com/api-explorer/balanceplatform/latest/get/paymentInstruments/_id_). To use this parameter, you must also provide a `balanceAccountId`, `accountHolderId`, or `balancePlatform`. The `paymentInstrumentId` must be related to the `balanceAccountId` or `accountHolderId` that you provide. | +| **reference** | [string] | The reference you provided in the POST [/transfers](https://docs.adyen.com/api-explorer/transfers/latest/post/transfers) request | +| **category** | [string] | The type of transfer. Possible values: - **bank**: Transfer to a [transfer instrument](https://docs.adyen.com/api-explorer/#/legalentity/latest/post/transferInstruments__resParam_id) or a bank account. - **internal**: Transfer to another [balance account](https://docs.adyen.com/api-explorer/#/balanceplatform/latest/post/balanceAccounts__resParam_id) within your platform. - **issuedCard**: Transfer initiated by a Adyen-issued card. - **platformPayment**: Fund movements related to payments that are acquired for your users. | +| **sortOrder** | [string] | Determines the sort order of the returned transfers. The sort order is based on the creation date of the transfers. Possible values: - **asc**: Ascending order, from oldest to most recent. - **desc**: Descending order, from most recent to oldest. Default value: **asc**. | +| **cursor** | [string] | The `cursor` returned in the links of the previous response. | +| **limit** | [int] | The number of items returned per page, maximum of 100 items. By default, the response returns 10 items per page. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.GetAllTransfers` usage: +// Provide the following values: createdSince, createdUntil, balancePlatform, accountHolderId, balanceAccountId, paymentInstrumentId, reference, category, sortOrder, cursor, limit +IFindTransfersResponse response = await transfersService.GetAllTransfersAsync( + DateTimeOffset createdSince, DateTimeOffset createdUntil, Option balancePlatform = default, Option accountHolderId = default, Option balanceAccountId = default, Option paymentInstrumentId = default, Option reference = default, Option category = default, Option sortOrder = default, Option cursor = default, Option limit = default, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out FindTransfersResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[FindTransfersResponse]() + + + +### **GET** **/transfers/{id}** + +Get a transfer + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **id** | [string] | Unique identifier of the transfer. | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.GetTransfer` usage: +// Provide the following values: id +ITransferData response = await transfersService.GetTransferAsync( + string id, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out TransferData result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[TransferData]() + + + +### **POST** **/transfers/{transferId}/returns** + +Return a transfer + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **transferId** | [string] | The unique identifier of the transfer to be returned. | +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **returnTransferRequest** | **ReturnTransferRequest** | | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.ReturnTransfer` usage: +// Provide the following values: transferId, [HeaderParameter] idempotencyKey, returnTransferRequest +IReturnTransferResponse response = await transfersService.ReturnTransferAsync( + string transferId, ReturnTransferRequest returnTransferRequest, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out ReturnTransferResponse result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[ReturnTransferResponse]() + + + +### **POST** **/transfers** + +Transfer funds + +#### Parameters + +| Name | Type | Description | +|------|------|-------------| +| **idempotencyKey** | [string] | A unique identifier for the message with a maximum of 64 characters (we recommend a UUID). | +| **wWWAuthenticate** | [string] | Header for authenticating through SCA | +| **transferInfo** | **TransferInfo** | | + +#### Example usage + +```csharp +using Adyen.Transfers.Models; +using Adyen.Transfers.Services; + +// Example `TransfersService.TransferFunds` usage: +// Provide the following values: [HeaderParameter] idempotencyKey, [HeaderParameter] wWWAuthenticate, transferInfo +ITransfer response = await transfersService.TransferFundsAsync( + TransferInfo transferInfo, + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out Transfer result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +[Transfer]() + + diff --git a/templates-v7/csharp/AssemblyInfo.mustache b/templates-v7/csharp/AssemblyInfo.mustache new file mode 100644 index 000000000..d5d937dc1 --- /dev/null +++ b/templates-v7/csharp/AssemblyInfo.mustache @@ -0,0 +1,40 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("{{packageTitle}}")] +[assembly: AssemblyDescription("{{packageDescription}}")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("{{packageCompany}}")] +[assembly: AssemblyProduct("{{packageProductName}}")] +[assembly: AssemblyCopyright("{{packageCopyright}}")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("{{packageVersion}}")] +[assembly: AssemblyFileVersion("{{packageVersion}}")] +{{^supportsAsync}} +// Settings which don't support asynchronous operations rely on non-public constructors +// This is due to how RestSharp requires the type constraint `where T : new()` in places it probably shouldn't. +[assembly: InternalsVisibleTo("RestSharp")] +[assembly: InternalsVisibleTo("NewtonSoft.Json")] +[assembly: InternalsVisibleTo("JsonSubTypes")] +{{/supportsAsync}} diff --git a/templates-v7/csharp/NullConditionalParameter.mustache b/templates-v7/csharp/NullConditionalParameter.mustache new file mode 100644 index 000000000..d8ad92666 --- /dev/null +++ b/templates-v7/csharp/NullConditionalParameter.mustache @@ -0,0 +1 @@ +{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}} \ No newline at end of file diff --git a/templates-v7/csharp/NullConditionalProperty.mustache b/templates-v7/csharp/NullConditionalProperty.mustache new file mode 100644 index 000000000..7dcafa803 --- /dev/null +++ b/templates-v7/csharp/NullConditionalProperty.mustache @@ -0,0 +1 @@ +{{#lambda.first}}{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} \ No newline at end of file diff --git a/templates-v7/csharp/OpenAPIDateConverter.mustache b/templates-v7/csharp/OpenAPIDateConverter.mustache new file mode 100644 index 000000000..d79051025 --- /dev/null +++ b/templates-v7/csharp/OpenAPIDateConverter.mustache @@ -0,0 +1,21 @@ +{{>partial_header}} +using Newtonsoft.Json.Converters; + +namespace {{packageName}}.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/templates-v7/csharp/ValidateRegex.mustache b/templates-v7/csharp/ValidateRegex.mustache new file mode 100644 index 000000000..d05be8a97 --- /dev/null +++ b/templates-v7/csharp/ValidateRegex.mustache @@ -0,0 +1,6 @@ +// {{{name}}} ({{{dataType}}}) pattern. +Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); +if (!regex{{{name}}}.Match(this.{{{name}}}{{#isUuid}}.ToString(){{/isUuid}}).Success) +{ + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); +} \ No newline at end of file diff --git a/templates-v7/csharp/auth/OAuthAuthenticator.mustache b/templates-v7/csharp/auth/OAuthAuthenticator.mustache new file mode 100644 index 000000000..4a2a3fa85 --- /dev/null +++ b/templates-v7/csharp/auth/OAuthAuthenticator.mustache @@ -0,0 +1,136 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace {{packageName}}.{{clientPackage}}.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : IAuthenticator + { + private TokenResponse{{nrt?}} _token; + + /// + /// Returns the current authentication token. Can return null if there is no authentication token, or it has expired. + /// + public string{{nrt?}} Token + { + get + { + if (_token == null) return null; + if (_token.ExpiresIn == null) return _token.AccessToken; + if (_token.ExpiresAt < DateTime.Now) return null; + + return _token.AccessToken; + } + } + + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string{{nrt?}} _scope; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + string{{nrt?}} scope, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _scope = scope; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// An authentication parameter. + protected async ValueTask GetAuthenticationParameter() + { + var token = string.IsNullOrEmpty(Token) ? await GetToken().ConfigureAwait(false) : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl, configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration))); + + var request = new RestRequest(); + if (!string.IsNullOrWhiteSpace(_token?.RefreshToken)) + { + request.AddParameter("grant_type", "refresh_token") + .AddParameter("refresh_token", _token.RefreshToken); + } + else + { + request + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + } + if (!string.IsNullOrEmpty(_scope)) + { + request.AddParameter("scope", _scope); + } + _token = await client.PostAsync(request).ConfigureAwait(false); + // RFC6749 - token_type is case insensitive. + // RFC6750 - In Authorization header Bearer should be capitalized. + // Fix the capitalization irrespective of token_type casing. + switch (_token?.TokenType?.ToLower()) + { + case "bearer": + return $"Bearer {_token.AccessToken}"; + default: + return $"{_token?.TokenType} {_token?.AccessToken}"; + } + } + + /// + /// Retrieves the authentication token (creating a new one if necessary) and adds it to the current request + /// + /// + /// + /// + public async ValueTask Authenticate(IRestClient client, RestRequest request) + => request.AddOrUpdateParameter(await GetAuthenticationParameter().ConfigureAwait(false)); + } +} diff --git a/templates-v7/csharp/auth/OAuthFlow.mustache b/templates-v7/csharp/auth/OAuthFlow.mustache new file mode 100644 index 000000000..0578a2d16 --- /dev/null +++ b/templates-v7/csharp/auth/OAuthFlow.mustache @@ -0,0 +1,19 @@ +{{>partial_header}} + +namespace {{packageName}}.{{clientPackage}}.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/templates-v7/csharp/auth/TokenResponse.mustache b/templates-v7/csharp/auth/TokenResponse.mustache new file mode 100644 index 000000000..fc90d0c51 --- /dev/null +++ b/templates-v7/csharp/auth/TokenResponse.mustache @@ -0,0 +1,24 @@ +{{>partial_header}} + +using System; +using Newtonsoft.Json; + +namespace {{packageName}}.{{clientPackage}}.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + [JsonProperty("expires_in")] + public int? ExpiresIn { get; set; } + [JsonProperty("created")] + public DateTime? Created { get; set; } + + [JsonProperty("refresh_token")] + public string{{nrt?}} RefreshToken { get; set; } + + public DateTime? ExpiresAt => ExpiresIn == null ? null : Created?.AddSeconds(ExpiresIn.Value); + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ApiException.mustache b/templates-v7/csharp/libraries/generichost/ApiException.mustache new file mode 100644 index 000000000..df9992b69 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ApiException.mustache @@ -0,0 +1,47 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{corePackageName}}.{{clientPackage}} +{ + /// + /// API Exception + /// + {{>visibility}} class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string{{nrt?}} ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string{{nrt?}} reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/ApiFactory.mustache b/templates-v7/csharp/libraries/generichost/ApiFactory.mustache new file mode 100644 index 000000000..873c8b355 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ApiFactory.mustache @@ -0,0 +1,48 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace {{packageName}}.{{corePackageName}}.{{clientPackage}} +{ + /// + /// The factory interface for creating the services that can communicate with the {{packageName}} APIs. + /// + {{>visibility}} interface {{interfacePrefix}}ApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : {{interfacePrefix}}{{packageName}}ApiService; + } + + /// + /// The implementation of . + /// + {{>visibility}} class ApiFactory : {{interfacePrefix}}ApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : {{interfacePrefix}}{{packageName}}ApiService + { + return Services.GetRequiredService(); + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/ApiKeyToken.mustache b/templates-v7/csharp/libraries/generichost/ApiKeyToken.mustache new file mode 100644 index 000000000..efc32707b --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ApiKeyToken.mustache @@ -0,0 +1,53 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{corePackageName}}.{{clientPackage}}; + +namespace {{packageName}}.{{apiName}}.{{clientPackage}} +{ + /// + /// The `ADYEN_API_KEY` is an Adyen API authentication token that must be included in the HTTP request header and allows your application to securely communicate with the Adyen APIs. + /// Guide on how to obtain the `ADYEN_API_KEY` + /// 1. For Digital/ECOM & In-Person Payments, visit: https://docs.adyen.com/development-resources/api-credentials/#generate-api-key to get your API Key. + /// 2. For Platforms & Financial Services, visit: https://docs.adyen.com/adyen-for-platforms-model to get started. + /// + {{>visibility}} class ApiKeyToken : TokenBase + { + /// + /// The `ADYEN_API_KEY`. + /// + private readonly string _apiKeyValue; + + /// + /// The name of the header. + /// + public ClientUtils.ApiKeyHeader Header { get; } + + /// + /// Constructs the ApiKeyToken object with the API key value provided. + /// This can then be accessed using . + /// + /// Your Adyen API Key value. + /// The header name, retrieved from + /// Your prefix, default: empty. + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "") : base() + { + Header = header; + _apiKeyValue = $"{prefix}{value}"; + } + + /// + /// Adds the token the HttpRequestMessage headers. + /// + /// . + public virtual void AddTokenToHttpRequestMessageHeader(global::System.Net.Http.HttpRequestMessage request) + { + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _apiKeyValue); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ApiResponseEventArgs.mustache b/templates-v7/csharp/libraries/generichost/ApiResponseEventArgs.mustache new file mode 100644 index 000000000..a3de3f0d0 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ApiResponseEventArgs.mustache @@ -0,0 +1,24 @@ +using System; + +namespace {{packageName}}.{{corePackageName}}.{{clientPackage}} +{ + /// + /// Useful for tracking server health + /// + {{>visibility}} class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse. + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs. + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/ApiResponse`1.mustache b/templates-v7/csharp/libraries/generichost/ApiResponse`1.mustache new file mode 100644 index 000000000..b78cbf1f4 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ApiResponse`1.mustache @@ -0,0 +1,202 @@ +// +{{#nrt}} +#nullable enable +{{/nrt}} +using System; +{{^netStandard}} +using System.Diagnostics.CodeAnalysis; +{{/netStandard}} +using System.Net; + +namespace {{packageName}}.{{corePackageName}}.{{clientPackage}} +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + {{>visibility}} partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the api response + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The raw binary stream (only set for binary responses) + /// + System.IO.Stream{{nrt?}} ContentStream { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the api response + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the api response + /// + string{{nrt?}} ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri{{nrt?}} RequestUri { get; } + } + + /// + /// API Response + /// + {{>visibility}} partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code). + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data. + /// + public string RawContent { get; protected set; } + + /// + /// The raw binary stream (only set for binary responses). + /// + public System.IO.Stream{{nrt?}} ContentStream { get; protected set; } + + /// + /// The IsSuccessStatusCode from the api response. + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response. + /// + public string{{nrt?}} ReasonPhrase { get; } + + /// + /// The headers contained in the api response. + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri{{nrt?}} RequestUri { get; } + + /// + /// The + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// Construct the response using an HttpResponseMessage. + /// + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + ContentStream = contentStream; + RawContent = string.Empty; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + } + {{#x-http-statuses-with-return}} + + /// + /// An interface for responses of type {{TType}}. + /// + /// + {{>visibility}} interface I{{.}} : IApiResponse + { + /// + /// Deserializes the response if the response is {{.}}. + /// + /// + TType {{.}}(); + + /// + /// Returns true if the response is {{.}} and the deserialized response is not null. + /// + /// + /// + bool TryDeserialize{{.}}Response({{#net60OrLater}}[NotNullWhen(true)]{{/net60OrLater}}out TType{{nrt?}} result); + } + {{/x-http-statuses-with-return}} +} diff --git a/templates-v7/csharp/libraries/generichost/AsModel.mustache b/templates-v7/csharp/libraries/generichost/AsModel.mustache new file mode 100644 index 000000000..f98d3ad57 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/AsModel.mustache @@ -0,0 +1,3 @@ +return Is{{vendorExtensions.x-http-status}} + ? {{#isBinary}}ContentStream{{/isBinary}}{{^isBinary}}System.Text.Json.JsonSerializer.Deserialize<{{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}>(RawContent, _jsonSerializerOptions){{/isBinary}} + : {{#net60OrLater}}null{{/net60OrLater}}{{^net60OrLater}}default{{/net60OrLater}}; diff --git a/templates-v7/csharp/libraries/generichost/BearerToken.mustache b/templates-v7/csharp/libraries/generichost/BearerToken.mustache new file mode 100644 index 000000000..1dd463bcd --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/BearerToken.mustache @@ -0,0 +1,41 @@ +\// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed from a token from a bearer token. + /// + {{>visibility}} class BearerToken : TokenBase + { + private string _raw; + + /// + /// Constructs a BearerToken object. + /// + /// + /// + public BearerToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(global::System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ClientUtils.mustache b/templates-v7/csharp/libraries/generichost/ClientUtils.mustache new file mode 100644 index 000000000..c11ae8da7 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ClientUtils.mustache @@ -0,0 +1,385 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions;{{#useCompareNetObjects}} +using KellermanSoftware.CompareNetObjects;{{/useCompareNetObjects}} +using {{packageName}}; +using {{packageName}}.{{corePackageName}}.Options; +{{#models}} +{{#-first}} +using {{packageName}}.{{modelPackage}}; +{{/-first}} +{{/models}} +using Models = {{packageName}}.{{modelPackage}}; +using System.Runtime.CompilerServices; + +namespace {{packageName}}.{{apiName}}.{{clientPackage}} +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + {{>visibility}} static {{#net70OrLater}}partial {{/net70OrLater}}class ClientUtils + { + {{#useCompareNetObjects}} + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + {{#equatable}} + ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}(); + comparisonConfig.UseHashCodeIdentifier = true; + {{/equatable}} + compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}}); + } + {{/useCompareNetObjects}} + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, {{#net60OrLater}}[global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] {{/net60OrLater}}out T{{#nrt}}{{#net60OrLater}}?{{/net60OrLater}}{{/nrt}} result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, {{#net60OrLater}}[global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] {{/net60OrLater}}out T{{#nrt}}{{#net60OrLater}}?{{/net60OrLater}}{{/nrt}} result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// The format to use for DateTime serialization. + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string{{nrt?}} ParameterToString(object{{nrt?}} obj, string{{nrt?}} format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + {{#net60OrLater}} + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + {{/net60OrLater}} + if (obj is bool boolean) + return boolean ? "true" : "false"; + {{#models}} + {{#model}} + {{#isEnum}} + if (obj is Models.{{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return {{classname}}ValueConverter{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/isEnum}} + {{^isEnum}} + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} + if (obj is Models.{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} + if (obj is Models.{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}) + {{! below has #isNumeric as a work around but should probably have ^isString instead https://github.com/OpenAPITools/openapi-generator/issues/15038}} + return Models.{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{{datatypeWithEnum}}}{{/lambda.camelcase_sanitize_param}}){{#isNumeric}}.ToString(){{/isNumeric}}; + {{/complexType}} + {{/isEnum}} + {{/vars}} + {{/isEnum}} + {{/model}} + {{/models}} + if (obj is ICollection collection) + { + List entries = new{{^net70OrLater}} List{{/net70OrLater}}(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string{{nrt?}} SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string{{nrt?}} SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + {{#net70OrLater}} + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + {{/net70OrLater}} + {{^net70OrLater}} + private static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + {{/net70OrLater}} + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return {{#net70OrLater}}JsonRegex(){{/net70OrLater}}{{^net70OrLater}}JsonRegex{{/net70OrLater}}.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string{{nrt?}} GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string{{nrt?}} jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (jsonPropertyName != null && jsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + {{#hasApiKeyMethods}} + /// + /// An enum of headers. + /// + public enum ApiKeyHeader + { + {{#apiKeyMethods}} + /// + /// The {{keyParamName}} header. + /// + {{#lambda.titlecase}}{{#lambda.alphabet_or_underscore}}{{keyParamName}}{{/lambda.alphabet_or_underscore}}{{/lambda.titlecase}}{{^-last}},{{/-last}} + {{/apiKeyMethods}} + } + + /// + /// Converts an ApiKeyHeader to a string. + /// + /// + /// as a string value. + /// + {{>visibility}} static string ApiKeyHeaderToString(ApiKeyHeader value) + { + {{#net80OrLater}} + return value switch + { + {{#apiKeyMethods}} + ApiKeyHeader.{{#lambda.titlecase}}{{#lambda.alphabet_or_underscore}}{{keyParamName}}{{/lambda.alphabet_or_underscore}}{{/lambda.titlecase}} => "{{keyParamName}}", + {{/apiKeyMethods}} + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + {{/net80OrLater}} + {{^net80OrLater}} + switch(value) + { + {{#apiKeyMethods}} + case ApiKeyHeader.{{#lambda.titlecase}}{{#lambda.alphabet_or_underscore}}{{keyParamName}}{{/lambda.alphabet_or_underscore}}{{/lambda.titlecase}}: + return "{{keyParamName}}"; + {{/apiKeyMethods}} + default: + throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)); + } + {{/net80OrLater}} + } + + {{/hasApiKeyMethods}} + } +} diff --git a/templates-v7/csharp/libraries/generichost/CookieContainer.mustache b/templates-v7/csharp/libraries/generichost/CookieContainer.mustache new file mode 100644 index 000000000..f96d4fb41 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/CookieContainer.mustache @@ -0,0 +1,22 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Linq; +using System.Collections.Generic; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A class containing a CookieContainer + /// + {{>visibility}} sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/DateFormats.mustache b/templates-v7/csharp/libraries/generichost/DateFormats.mustache new file mode 100644 index 000000000..920ecda88 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateFormats.mustache @@ -0,0 +1,2 @@ + "yyyy'-'MM'-'dd", + "yyyyMMdd" diff --git a/templates-v7/csharp/libraries/generichost/DateOnlyJsonConverter.mustache b/templates-v7/csharp/libraries/generichost/DateOnlyJsonConverter.mustache new file mode 100644 index 000000000..1441421aa --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateOnlyJsonConverter.mustache @@ -0,0 +1,52 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } +} diff --git a/templates-v7/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache b/templates-v7/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache new file mode 100644 index 000000000..53fdfbee7 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache @@ -0,0 +1,57 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/DateTimeFormats.mustache b/templates-v7/csharp/libraries/generichost/DateTimeFormats.mustache new file mode 100644 index 000000000..85ed99a2c --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateTimeFormats.mustache @@ -0,0 +1,22 @@ + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + {{^supportsDateOnly}} + "yyyy'-'MM'-'dd", + {{/supportsDateOnly}} + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + {{^supportsDateOnly}} + "yyyyMMdd" + {{/supportsDateOnly}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/DateTimeJsonConverter.mustache b/templates-v7/csharp/libraries/generichost/DateTimeJsonConverter.mustache new file mode 100644 index 000000000..bf5059fca --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateTimeJsonConverter.mustache @@ -0,0 +1,52 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateTimeFormats}} + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString("{{{dateTimeFormat}}}", CultureInfo.InvariantCulture)); + } +} diff --git a/templates-v7/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache b/templates-v7/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache new file mode 100644 index 000000000..bbc036490 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache @@ -0,0 +1,57 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateTimeFormats}} + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString("{{{dateTimeFormat}}}", CultureInfo.InvariantCulture)); + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/EnumValueDataType.mustache b/templates-v7/csharp/libraries/generichost/EnumValueDataType.mustache new file mode 100644 index 000000000..e92e67b36 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/EnumValueDataType.mustache @@ -0,0 +1 @@ +{{#allowableValues}}{{#enumVars}}{{#-first}}{{#isString}}{{^isNumeric}}string{{/isNumeric}}{{/isString}}{{#isNumeric}}{{#isLong}}long{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}double{{/isDouble}}{{#isDecimal}}decimal{{/isDecimal}}{{^isLong}}{{^isFloat}}{{^isDouble}}{{^isDecimal}}int{{/isDecimal}}{{/isDouble}}{{/isFloat}}{{/isLong}}{{/isNumeric}}{{/-first}}{{/enumVars}}{{/allowableValues}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ExceptionEventArgs.mustache b/templates-v7/csharp/libraries/generichost/ExceptionEventArgs.mustache new file mode 100644 index 000000000..b74fcfa0a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ExceptionEventArgs.mustache @@ -0,0 +1,24 @@ +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Useful for tracking server health + /// + {{>visibility}} class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExceptionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/HmacKeyToken.mustache b/templates-v7/csharp/libraries/generichost/HmacKeyToken.mustache new file mode 100644 index 000000000..8a24aecef --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/HmacKeyToken.mustache @@ -0,0 +1,36 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{corePackageName}}.{{clientPackage}}; + +namespace {{packageName}}.{{apiName}}.{{clientPackage}} +{ + /// + /// The `ADYEN_HMAC_KEY` is used to verify the incoming HMAC signature from incoming webhooks. + /// To protect your server from unauthorised webhook events, Adyen recommends that you use Hash-based message authentication code HMAC signatures for our webhooks. + /// Each webhook event will include a signature calculated using a secret `ADYEN_HMAC_KEY` key and the payload from the webhook. + /// By verifying this signature, you confirm that the webhook was sent by Adyen, and was not modified during transmission. + /// + {{>visibility}} class HmacKeyToken : TokenBase + { + /// + /// The `ADYEN_HMAC_KEY`, can be configured in . + /// + public string? AdyenHmacKey { get; } + + /// + /// Constructs the HmacKeyToken object with the ADYEN_HMAC_KEY value provided. + /// This can then be accessed using . + /// + /// Your `ADYEN_HMAC_KEY`, configured in . + public HmacKeyToken(string hmacKey) : base() + { + AdyenHmacKey = hmacKey; + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/HostConfiguration.mustache b/templates-v7/csharp/libraries/generichost/HostConfiguration.mustache new file mode 100644 index 000000000..b1387180c --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/HostConfiguration.mustache @@ -0,0 +1,178 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{apiName}}.{{clientPackage}}; +{{#models}} +{{#-first}} +using {{packageName}}.{{modelPackage}}; +{{/-first}} +{{/models}} +using {{packageName}}.{{corePackageName}}; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{corePackageName}}.Client; +using {{packageName}}.{{corePackageName}}.Options; +using {{packageName}}.{{corePackageName}}.Converters; + +namespace {{packageName}}.{{apiName}}.{{clientPackage}} +{ + /// + /// Provides hosting configuration for {{apiName}} + /// + {{>visibility}} class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + private readonly AdyenOptions _adyenOptions = new AdyenOptions(); + + /// + /// The base path of the API, it includes the http(s)-scheme, the host domain name, and the base path. + /// This value can change when `ConfigureAdyenOptions` is called in ). The new value will be based on the .. + /// + public static string BASE_URL = "{{{basePath}}}"; + + /// + /// Instantiates the HostConfiguration (custom JsonConverters, Events, HttpClient) with the necessary dependencies to communicate with the API. + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(JsonStringEnumConverter)) == null) + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateTimeNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(ByteArrayConverter)) == null) + _jsonOptions.Converters.Add(new ByteArrayConverter()); + {{#supportsDateOnly}} + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + if (_jsonOptions.Converters.FirstOrDefault(x => x.GetType() == typeof(DateOnlyNullableJsonConverter)) == null) + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + {{/supportsDateOnly}} + {{#models}} + {{#model}} + {{#isEnum}} + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}JsonConverter()); + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableJsonConverter()); + {{/isEnum}} + {{^isEnum}} + _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); + {{/isEnum}} + {{/model}} + {{/models}} + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new{{^net60OrLater}} JsonSerializerOptionsProvider{{/net60OrLater}}(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + {{#useSourceGeneration}} + + {{#models}} + {{#-first}} + _jsonOptions.TypeInfoResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine( + {{/-first}} + {{/models}} + {{#lambda.joinLinesWithComma}} + {{#models}} + {{#model}} + new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}SerializationContext(){{#-last}},{{/-last}} + {{/model}} + {{/models}} + {{/lambda.joinLinesWithComma}} + {{#models}} + {{#-last}} + + new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver() + ); + {{/-last}} + {{/models}} + + {{/useSourceGeneration}} + _services.AddSingleton<{{interfacePrefix}}ApiFactory, ApiFactory>();{{#apiInfo}}{{#apis}} + _services.AddSingleton<{{classname}}Events>();{{/apis}}{{/apiInfo}} + } + + /// + /// Configures the and . + /// + /// Configures the . + /// Configures the . + /// . + public HostConfiguration Add{{apiName}}HttpClients(Action{{nrt?}} httpClientOptions = null, Action{{nrt?}} httpClientBuilderOptions = null) + { + Action httpClientAction = httpClient => + { + // Configure HttpClient set by the user. + httpClientOptions?.Invoke(httpClient); + + // Set BaseAddress if it's not set. + if (httpClient.BaseAddress == null) + httpClient.BaseAddress = new Uri(UrlBuilderExtensions.ConstructHostUrl(_adyenOptions, BASE_URL)); + }; + + List builders = new List(); + + {{#models}} + {{#model.vendorExtensions.x-has-at-least-one-webhook-root}} + _services.AddSingleton<{{packageName}}.{{apiName}}.Handlers.{{interfacePrefix}}{{apiName}}Handler, {{packageName}}.{{apiName}}.Handlers.{{apiName}}Handler>(); + {{/model.vendorExtensions.x-has-at-least-one-webhook-root}} + {{/models}} + {{#apiInfo}}{{#apis}}builders.Add(_services.AddHttpClient<{{interfacePrefix}}{{classname}}, {{classname}}>(httpClientAction)); + {{/apis}}{{/apiInfo}} + if (httpClientBuilderOptions != null) + foreach (IHttpClientBuilder builder in builders) + httpClientBuilderOptions(builder); + + return this; + } + + /// + /// Configures the . + /// + /// Configures the . + /// . + public HostConfiguration ConfigureJsonOptions(Action jsonSerializerOptions) + { + jsonSerializerOptions(_jsonOptions); + + return this; + } + + /// + /// Configures the (e.g. Environment, LiveEndpointPrefix). + /// + /// Configures the . + /// . + public HostConfiguration ConfigureAdyenOptions(Action adyenOptions) + { + adyenOptions(_adyenOptions); + {{#hasApiKeyMethods}} + _services.AddSingleton>( + new TokenProvider( + new ApiKeyToken(_adyenOptions.AdyenApiKey, ClientUtils.ApiKeyHeader.X_API_Key, "") + ) + ); + {{/hasApiKeyMethods}} + + {{#models}} + {{#model.vendorExtensions.x-has-at-least-one-webhook-root}} + _services.AddSingleton>( + new TokenProvider( + new HmacKeyToken(_adyenOptions.AdyenHmacKey) + ) + ); + {{/model.vendorExtensions.x-has-at-least-one-webhook-root}} + {{/models}} + return this; + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/IApi.mustache b/templates-v7/csharp/libraries/generichost/IApi.mustache new file mode 100644 index 000000000..a2fc6d1ea --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/IApi.mustache @@ -0,0 +1,13 @@ +namespace {{packageName}}.{{apiPackage}} +{ + /// + /// Interface for interacting with any {{packageName}} API using . + /// + {{>visibility}} interface {{interfacePrefix}}{{packageName}}ApiService + { + /// + /// The object, best practice: instantiate and manage object using the . + /// + System.Net.Http.HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/IHostBuilderExtensions.mustache b/templates-v7/csharp/libraries/generichost/IHostBuilderExtensions.mustache new file mode 100644 index 000000000..2ba273b02 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/IHostBuilderExtensions.mustache @@ -0,0 +1,41 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using {{packageName}}.{{apiName}}; +using {{packageName}}.{{apiName}}.{{clientPackage}}; + +namespace {{packageName}}.{{apiName}}.Extensions +{ + /// + /// Extension methods for . + /// + {{>visibility}} static class HostBuilderExtensions + { + /// + /// Add the {{apiName}} API services to the . + /// You can optionally configure the and . + /// + /// . + /// Configures the , , and . + /// Configures the . + /// Configures the . + public static IHostBuilder Configure{{apiName}}(this IHostBuilder hostBuilder, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + hostBuilder.ConfigureServices((context, services) => + { + HostConfiguration hostConfiguration = new HostConfiguration(services); + + hostConfigurationOptions(context, services, hostConfiguration); + + hostConfiguration.Add{{apiName}}HttpClients(httpClientOptions, httpClientBuilderOptions); + }); + + return hostBuilder; + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/IHttpClientBuilderExtensions.mustache b/templates-v7/csharp/libraries/generichost/IHttpClientBuilderExtensions.mustache new file mode 100644 index 000000000..053c0226a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/IHttpClientBuilderExtensions.mustache @@ -0,0 +1,75 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}} +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly;{{/supportsRetry}} + +namespace {{packageName}}.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + {{>visibility}} static class IHttpClientBuilderExtensions + { + {{#supportsRetry}} + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + {{/supportsRetry}} + } +} diff --git a/templates-v7/csharp/libraries/generichost/IServiceCollectionExtensions.mustache b/templates-v7/csharp/libraries/generichost/IServiceCollectionExtensions.mustache new file mode 100644 index 000000000..fb32d770a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/IServiceCollectionExtensions.mustache @@ -0,0 +1,33 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{apiName}}.{{clientPackage}}; + +namespace {{packageName}}.{{apiName}}.Extensions +{ + /// + /// Extension methods for . + /// + {{>visibility}} static class ServiceCollectionExtensions + { + /// + /// Add the {{packageName}} {{apiName}} API services to your . + /// + /// . + /// Configures the . + /// Configures the . + /// Configures the . + public static void Add{{apiName}}Services(this IServiceCollection services, Action hostConfigurationOptions, Action? httpClientOptions = null, Action? httpClientBuilderOptions = null) + { + HostConfiguration hostConfiguration = new{{^net70OrLater}} HostConfiguration{{/net70OrLater}}(services); + hostConfigurationOptions(hostConfiguration); + hostConfiguration.Add{{apiName}}HttpClients(httpClientOptions, httpClientBuilderOptions); + } + } +} diff --git a/templates-v7/csharp/libraries/generichost/ImplementsIEquatable.mustache b/templates-v7/csharp/libraries/generichost/ImplementsIEquatable.mustache new file mode 100644 index 000000000..dd576dd0f --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ImplementsIEquatable.mustache @@ -0,0 +1 @@ +{{#equatable}}{{#readOnlyVars}}{{#-first}}IEquatable<{{classname}}{{nrt?}}> {{/-first}}{{/readOnlyVars}}{{/equatable}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ImplementsValidatable.mustache b/templates-v7/csharp/libraries/generichost/ImplementsValidatable.mustache new file mode 100644 index 000000000..7c3f0e02a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ImplementsValidatable.mustache @@ -0,0 +1 @@ +{{#validatable}}IValidatableObject {{/validatable}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/JsonConverter.mustache b/templates-v7/csharp/libraries/generichost/JsonConverter.mustache new file mode 100644 index 000000000..391e00e66 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/JsonConverter.mustache @@ -0,0 +1,661 @@ + /// + /// A Json converter for type + /// + {{>visibility}} class {{classname}}JsonConverter : JsonConverter<{{classname}}> + { + {{#allVars}} + {{#isDateTime}} + /// + /// The format to use to serialize {{name}}. + /// + public static string {{name}}Format { get; set; } = "{{{dateTimeFormat}}}"; + + {{/isDateTime}} + {{#isDate}} + /// + /// The format to use to serialize {{name}}. + /// + public static string {{name}}Format { get; set; } = "{{{dateFormat}}}"; + + {{/isDate}} + {{/allVars}} + /// + /// Deserializes json to . + /// + /// . + /// . + /// The , initialized from . + /// . + /// + public override {{classname}} Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + {{#allVars}} + Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + {{/-last}} + {{/allVars}} + {{#discriminator}} + {{#children}} + {{#-first}} + string{{nrt?}} discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "{{discriminator.propertyBaseName}}"); + + {{/-first}} + if (discriminator != null && discriminator.Equals("{{name}}")) + return JsonSerializer.Deserialize<{{{classname}}}>(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + {{/children}} + {{/discriminator}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#mappedModels}} + {{#model}} + {{^vendorExtensions.x-duplicated-data-type}} + {{classname}}{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} = null; + {{#-last}} + + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/model}} + {{/mappedModels}} + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string{{nrt?}} jsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (jsonPropertyName{{nrt?}}.Equals("{{propertyBaseName}}"){{#nrt}} ?? false{{/nrt}}) + { + string{{nrt?}} discriminator = utf8JsonReaderDiscriminator.GetString(); + {{#mappedModels}} + if (discriminator{{nrt?}}.Equals("{{mappingName}}"){{#nrt}} ?? false{{/nrt}}) + { + Utf8JsonReader utf8JsonReader{{model.classname}} = utf8JsonReader; + {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} = JsonSerializer.Deserialize<{{{model.classname}}}>(ref utf8JsonReader{{model.classname}}, jsonSerializerOptions); + } + {{/mappedModels}} + } + } + } + + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + {{#oneOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/oneOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderAnyOf = utf8JsonReader; + while (utf8JsonReaderAnyOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (utf8JsonReaderAnyOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderAnyOf.CurrentDepth - 1) + { + {{#anyOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/anyOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + + {{/composedSchemas}} + {{/model.discriminator}} + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string{{nrt?}} jsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (jsonPropertyName) + { + {{#allVars}} + case "{{baseName}}": + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetDecimal()); + {{/isDecimal}} + {{^isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetString(){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isDecimal}} + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + {{/isBoolean}} + {{#isNumeric}} + {{^isEnum}} + {{#isDouble}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + {{/isDouble}} + {{#isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + {{/isDecimal}} + {{#isFloat}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + {{/isFloat}} + {{#isLong}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#vendorExtensions.x-unsigned}}u{{/vendorExtensions.x-unsigned}}long?)null : utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int64()); + {{/isLong}} + {{^isLong}} + {{^isFloat}} + {{^isDecimal}} + {{^isDouble}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#vendorExtensions.x-unsigned}}u{{/vendorExtensions.x-unsigned}}int?)null : utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isDouble}} + {{/isDecimal}} + {{/isFloat}} + {{/isLong}} + {{/isEnum}} + {{/isNumeric}} + {{#isDate}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{#supportsDateOnly}}DateOnly{{/supportsDateOnly}}{{^supportsDateOnly}}DateTime{{/supportsDateOnly}}{{#isNullable}}?{{/isNullable}}>(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDate}} + {{#isDateTime}} + {{! Fix: Added support for DateTimeOffset, when `useDateTimeOffset=true` }} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDateTime}} + {{#isEnum}} + {{^isMap}} + {{#isNumeric}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}?)null : ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}})utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isNumeric}} + {{^isNumeric}} + string{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = utf8JsonReader.GetString(); + {{^isInnerEnum}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isInnerEnum}} + {{#isInnerEnum}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{classname}}.{{{datatypeWithEnum}}}.FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (Guid?)null : utf8JsonReader.GetGuid()); + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref utf8JsonReader, jsonSerializerOptions){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + break; + {{/allVars}} + default: + break; + } + } + } + + {{! Required fields }} + {{#allVars}} + {{#required}} + if (!{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.IsSet) + throw new ArgumentException("Property is required for class {{classname}}.", nameof({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}})); + + {{/required}} + {{/allVars}} + {{^vendorExtensions.x-duplicated-data-type}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{^model.composedSchemas.anyOf}} + {{#mappedModels}} + if ({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/mappedModels}} + {{/model.composedSchemas.anyOf}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^composedSchemas.oneOf}} + {{^required}} + {{#model.composedSchemas.anyOf}} + Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} == null + ? default + : new Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{/model.composedSchemas.anyOf}} + {{#-last}} + + {{/-last}} + {{/required}} + return new {{classname}}({{#lambda.joinWithComma}}{{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue{{#required}}.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/required}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + {{/composedSchemas.oneOf}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}?.Type != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}ParsedValue{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{/vendorExtensions.x-duplicated-data-type}} + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/oneOf}} + {{/composedSchemas}} + {{/model.discriminator}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Serializes a . + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimLineBreaks}} + {{#lambda.copyText}} + {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copyText}} + {{#discriminator}} + {{#children}} + if ({{#lambda.paste}}{{/lambda.paste}} is {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}){ + JsonSerializer.Serialize<{{{classname}}}>(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + return; + } + + {{/children}} + {{/discriminator}} + {{! start | support oneOf without discriminator.mapping property - WriteProperties }} + {{^model.discriminator}} + {{#composedSchemas.oneOf}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + {{/composedSchemas.oneOf}} + {{/model.discriminator}} + {{! end | oneOf support without discriminator.mapping property - WriteProperties }} + {{! start | support oneOf without discriminator.mapping property- WriteStartObject }} + {{^model.discriminator}}{{#oneOf}}{{#-first}}/* {{/-first}}{{/oneOf}}{{/model.discriminator}} + writer.WriteStartObject(); + {{^model.discriminator}}{{#oneOf}}{{#-first}} */{{/-first}}{{/oneOf}}{{/model.discriminator}} + {{! end | support oneOf without discriminator.mapping property - WriteStartObject }} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{baseType}}JsonConverter {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}} = ({{baseType}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.GetType())); + {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}}.WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#anyOf}} + if ({{#lambda.joinWithAmpersand}}{{^required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet {{/required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}} != null{{/lambda.joinWithAmpersand}}) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{#isEnum}} + { + {{datatypeWithEnum}}JsonConverter {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}.GetType())); + {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter.Write{{^isEnumRef}}Properties{{/isEnumRef}}(writer, {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}, jsonSerializerOptions); + } + {{/isEnum}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{datatypeWithEnum}}JsonConverter {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}.GetType())); + {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter.Write{{^isEnumRef}}Properties{{/isEnumRef}}(writer, {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/anyOf}} + {{/composedSchemas}} + {{/model.discriminator}} + WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + {{! start | support oneOf without discriminator.mapping property- WriteEndObject }} + {{^model.discriminator}}{{#oneOf}}{{#-first}}/* {{/-first}}{{/oneOf}}{{/model.discriminator}} + writer.WriteEndObject(); + {{^model.discriminator}}{{#oneOf}}{{#-first}} */{{/-first}}{{/oneOf}}{{/model.discriminator}} + {{! end | support oneOf without discriminator.mapping property - WriteEndObject }} + {{/lambda.trimLineBreaks}} + } + + /// + /// Serializes the properties of . + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + + {{#allVars}} + {{#isDiscriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + writer.WriteString("{{baseName}}", {{^isEnum}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{/isEnum}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{{datatypeWithEnum}}}.ToJsonValue{{/isInnerEnum}}{{^isInnerEnum}}{{{datatypeWithEnum}}}ValueConverter.ToJsonValue{{/isInnerEnum}}({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}{{/required}}){{/isEnum}}); + + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/isDiscriminator}} + {{^isDiscriminator}} + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#lambda.copyText}} + {{#isDecimal}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.ToString()); + {{/isDecimal}} + {{^isDecimal}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{/isDecimal}} + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#lambda.copyText}} + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isBoolean}} + {{^isEnum}} + {{#isNumeric}} + {{#lambda.copyText}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isNumeric}} + {{/isEnum}} + {{#isDate}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isDate}} + {{#isDateTime}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isDateTime}} + {{#isEnum}} + {{#isNumeric}} + {{#lambda.copyText}} + writer.WriteNumber("{{baseName}}", {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}})); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isNumeric}} + {{^isMap}} + {{^isNumeric}} + {{#isInnerEnum}} + {{#isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + + {{/isNullable}} + {{^isNullable}} + if ({{^required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.IsSet && {{/required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) {{! - }} + { + string? {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + } + + {{/isNullable}} + {{/isInnerEnum}} + {{^isInnerEnum}} + {{#lambda.copyText}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copyText}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} == null) + writer.WriteNull("{{baseName}}"); + else + { + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.Value); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + if ({{#lambda.paste}}{{/lambda.paste}}RawValue != null){{! we cant use name here because enumVar also has a name property, so use the paste lambda instead }} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + {{/isString}} + {{^isString}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{^isNumeric}} + writer.WriteString("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + {{/isNumeric}} + {{#isNumeric}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{#lambda.paste}}{{/lambda.paste}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isNumeric}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{/isNullable}} + + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option{{nrt!}}.Value != null) + { + var {{#lambda.paste}}{{/lambda.paste}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.Value{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + var {{#lambda.paste}}{{/lambda.paste}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + } + {{/isNullable}} + {{/required}} + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + {{/isNullable}} + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.Value != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isNullable}} + {{/required}} + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + {{/isDiscriminator}} + {{/allVars}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + } \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/JsonSerializerOptionsProvider.mustache b/templates-v7/csharp/libraries/generichost/JsonSerializerOptionsProvider.mustache new file mode 100644 index 000000000..7e5cf9cb8 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/JsonSerializerOptionsProvider.mustache @@ -0,0 +1,29 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Text.Json; + +namespace {{packageName}}.{{apiName}}.{{clientPackage}} +{ + /// + /// Provides the JsonSerializerOptions. + /// + {{>visibility}} class JsonSerializerOptionsProvider + { + /// + /// The JsonSerializerOptions. + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider to access the JsonSerializerOptions. + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ModelBaseSignature.mustache b/templates-v7/csharp/libraries/generichost/ModelBaseSignature.mustache new file mode 100644 index 000000000..909a68e35 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ModelBaseSignature.mustache @@ -0,0 +1 @@ +{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{parent}}{{/lambda.camelcase_sanitize_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#isInherited}}{{^isNew}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{/isNew}}{{#isNew}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{{datatypeWithEnum}}}ToJsonValue{{/isInnerEnum}}{{^isInnerEnum}}{{{datatypeWithEnum}}}ValueConverter.ToJsonValue{{/isInnerEnum}}({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{^required}}.Value{{/required}}){{/isEnum}}{{^isEnum}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.ToString(){{/isEnum}}{{/isNew}} {{/isInherited}}{{/isDiscriminator}}{{/allVars}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ModelSignature.mustache b/templates-v7/csharp/libraries/generichost/ModelSignature.mustache new file mode 100644 index 000000000..09a41b278 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ModelSignature.mustache @@ -0,0 +1 @@ +{{#model.allVars}}{{^isDiscriminator}}{{^required}}Option<{{/required}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}{{#defaultValue}}{{^isEnum}} = {{^required}}default{{/required}}{{#required}}{{^isDateTime}}{{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}{{{.}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/required}}{{/isEnum}}{{#isEnum}} = default{{/isEnum}}{{/defaultValue}}{{^defaultValue}}{{#lambda.first}}{{#isNullable}} = default {{/isNullable}}{{^required}} = default {{/required}}{{/lambda.first}}{{/defaultValue}} {{/isDiscriminator}}{{/model.allVars}} diff --git a/templates-v7/csharp/libraries/generichost/OAuthToken.mustache b/templates-v7/csharp/libraries/generichost/OAuthToken.mustache new file mode 100644 index 000000000..23b3cab91 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/OAuthToken.mustache @@ -0,0 +1,41 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A token constructed with OAuth. + /// + {{>visibility}} class OAuthToken : TokenBase + { + private string _raw; + + /// + /// Consturcts an OAuthToken object. + /// + /// + /// + public OAuthToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(global::System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/OnDeserializationError.mustache b/templates-v7/csharp/libraries/generichost/OnDeserializationError.mustache new file mode 100644 index 000000000..ff83a5076 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/OnDeserializationError.mustache @@ -0,0 +1,2 @@ +if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/OperationSignature.mustache b/templates-v7/csharp/libraries/generichost/OperationSignature.mustache new file mode 100644 index 000000000..049717717 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/OperationSignature.mustache @@ -0,0 +1 @@ +{{#pathParams}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/pathParams}}{{#queryParams}}{{#required}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/required}}{{/queryParams}}{{#bodyParams}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/bodyParams}}{{#queryParams}}{{^required}}Option<{{{dataType}}}{{>NullConditionalParameter}}> {{paramName}}{{#notRequiredOrIsNullable}} = default{{/notRequiredOrIsNullable}}, {{/required}}{{/queryParams}} RequestOptions? requestOptions = default, System.Threading.CancellationToken cancellationToken = default{{^netstandard20OrLater}}(global::System.Threading.CancellationToken){{/netstandard20OrLater}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/Option.mustache b/templates-v7/csharp/libraries/generichost/Option.mustache new file mode 100644 index 000000000..8b33bdb51 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/Option.mustache @@ -0,0 +1,48 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/OptionProperty.mustache b/templates-v7/csharp/libraries/generichost/OptionProperty.mustache new file mode 100644 index 000000000..d75041887 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/OptionProperty.mustache @@ -0,0 +1 @@ +new Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>( \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/README.client.mustache b/templates-v7/csharp/libraries/generichost/README.client.mustache new file mode 100644 index 000000000..a584f9ed6 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/README.client.mustache @@ -0,0 +1,140 @@ +# Created with Openapi Generator + + +## Creating the library +Create a config.yaml file similar to what is below, then run the following powershell command to generate the library `java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate -c config.yaml` + +```yaml +generatorName: csharp +inputSpec: {{inputSpec}} +outputDir: out + +# https://openapi-generator.tech/docs/generators/csharp +additionalProperties: + packageGuid: '{{packageGuid}}' + +# https://openapi-generator.tech/docs/integrations/#github-integration +# gitHost: +# gitUserId: +# gitRepoId: + +# https://openapi-generator.tech/docs/globals +# globalProperties: + +# https://openapi-generator.tech/docs/customization/#inline-schema-naming +# inlineSchemaOptions: + +# https://openapi-generator.tech/docs/customization/#name-mapping +# modelNameMappings: +# nameMappings: + +# https://openapi-generator.tech/docs/customization/#openapi-normalizer +# openapiNormalizer: + +# templateDir: https://openapi-generator.tech/docs/templating/#modifying-templates + +# releaseNote: +``` + + +## Using the library in your project + +```cs +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.Api; +using {{packageName}}.Client; +using {{packageName}}.Model; +using Org.OpenAPITools.Extensions; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + {{#apiInfo}} + {{#apis}} + {{#-first}} + var api = host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); + {{#operations}} + {{#-first}} + {{#operation}} + {{#-first}} + {{interfacePrefix}}{{operationId}}ApiResponse apiResponse = await api.{{operationId}}Async("todo"); + {{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}object{{/returnType}}{{nrt?}} model = apiResponse.Ok(); + {{/-first}} + {{/operation}} + {{/-first}} + {{/operations}} + {{/-first}} + {{/apis}} + {{/apiInfo}} + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .Configure{{apiName}}((context, services, options) => + { + {{#authMethods}} + {{#-first}} + // The type of token here depends on the api security specifications + // Available token types are: ApiKeyToken and OAuthToken. + BearerToken token = new(""); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, BearerToken>(); + + {{/-first}} + {{/authMethods}} + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.Add{{apiName}}HttpClients(client => + { + // client configuration + }, builder => + { + builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)); + // add whatever middleware you prefer + } + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + Configure Polly in the IHttpClientBuilder +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After partial methods in the api classes. + +## Api Information +- appName: {{appName}} +- appVersion: {{appVersion}} +- appDescription: {{appDescription}} + +## Build +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. + +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: {{generatorClass}} diff --git a/templates-v7/csharp/libraries/generichost/SourceGenerationContext.mustache b/templates-v7/csharp/libraries/generichost/SourceGenerationContext.mustache new file mode 100644 index 000000000..b1798c98e --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/SourceGenerationContext.mustache @@ -0,0 +1,9 @@ +{{#useSourceGeneration}} + + /// + /// The {{classname}}SerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof({{classname}}))] + {{>visibility}} partial class {{classname}}SerializationContext : JsonSerializerContext { } +{{/useSourceGeneration}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/TokenBase.mustache b/templates-v7/csharp/libraries/generichost/TokenBase.mustache new file mode 100644 index 000000000..05f06b4a7 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/TokenBase.mustache @@ -0,0 +1,73 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// The base for all tokens. + /// + {{>visibility}} abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler{{nrt?}} TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object{{nrt?}} sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/TokenContainer.mustache b/templates-v7/csharp/libraries/generichost/TokenContainer.mustache new file mode 100644 index 000000000..24c84a551 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/TokenContainer.mustache @@ -0,0 +1,39 @@ +// +{{partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System.Linq; +using System.Collections.Generic; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A container for a collection of tokens. + /// + /// + {{>visibility}} sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(global::System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/TokenProvider.mustache b/templates-v7/csharp/libraries/generichost/TokenProvider.mustache new file mode 100644 index 000000000..9fc5f3ea0 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/TokenProvider.mustache @@ -0,0 +1,39 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Linq; +using System.Collections.Generic; +using {{packageName}}.{{clientPackage}}; + +namespace {{packageName}} +{ + /// + /// A class which will provide tokens. + /// + {{>visibility}} abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(global::System.Threading.CancellationToken){{/netstandard20OrLater}}); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/ValidateRegex.mustache b/templates-v7/csharp/libraries/generichost/ValidateRegex.mustache new file mode 100644 index 000000000..8918b8cf4 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/ValidateRegex.mustache @@ -0,0 +1,7 @@ +// {{{name}}} ({{{dataType}}}) pattern +Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); +{{#lambda.copy}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null && {{/lambda.copy}} +if ({{#lambda.first}}{{^required}}{{#lambda.paste}}{{/lambda.paste}} {{/required}}{{#isNullable}}{{#lambda.paste}}{{/lambda.paste}}{{/isNullable}}{{/lambda.first}}!regex{{{name}}}.Match(this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}}{{#isUuid}}.ToString(){{#lambda.first}}{{^required}}{{nrt!}} {{/required}}{{#isNullable}}! {{/isNullable}}{{/lambda.first}}{{/isUuid}}).Success) +{ + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); +} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/WebhookHandler.mustache b/templates-v7/csharp/libraries/generichost/WebhookHandler.mustache new file mode 100644 index 000000000..3a35bdd49 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/WebhookHandler.mustache @@ -0,0 +1,88 @@ +{{#lambda.trimLineBreaks}} +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using Microsoft.Extensions.Logging; +using System.Text.Json; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{apiName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace {{packageName}}.{{apiName}}.Handlers +{ + /// + /// Interface for deserializing {{apiName}} webhooks or verify its HMAC signature. + /// + {{>visibility}} interface {{interfacePrefix}}{{apiName}}Handler + { + /// + /// Returns the to deserialize the json payload from the webhook. This is initialized in the . + /// + {{packageName}}.{{apiName}}.{{clientPackage}}.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + {{#models}} + {{#model.vendorExtensions.x-webhook-root}} + + /// + /// Uses to attempt to deserialize . + /// + /// The full webhook payload. + /// + {{model.name}}? Deserialize{{model.name}}(string json); + {{/model.vendorExtensions.x-webhook-root}} + {{/models}} + + /// + /// Verifies the HMAC signature of the webhook json payload. + /// + /// The full webhook payload. + /// The signature from the webhook. + /// True if the HMAC signature is valid + bool IsValidHmacSignature(string json, string hmacSignature); + } + + /// + /// Handler utility function used to deserialize {{apiName}} or verify the HMAC signature of the webhook. + /// + {{>visibility}} partial class {{apiName}}Handler : {{interfacePrefix}}{{apiName}}Handler + { + /// + /// The `ADYEN_HMAC_KEY` configured in . + /// + private readonly string? _adyenHmacKey; + + /// + public {{packageName}}.{{apiName}}.{{clientPackage}}.JsonSerializerOptionsProvider JsonSerializerOptionsProvider { get; } + + /// + /// Initializes the handler utility for deserializing {{apiName}} or verify its HMAC signature. + /// + /// . + /// which contains the HMACKey configured in . + public {{apiName}}Handler({{packageName}}.{{apiName}}.{{clientPackage}}.JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ITokenProvider hmacKeyProvider = null) + { + JsonSerializerOptionsProvider = jsonSerializerOptionsProvider; + } + + {{#models}} + {{#model.vendorExtensions.x-webhook-root}} + /// + public {{model.name}}? Deserialize{{model.name}}(string json) + { + return JsonSerializer.Deserialize<{{model.name}}>(json, JsonSerializerOptionsProvider.Options); + } + + {{/model.vendorExtensions.x-webhook-root}} + {{/models}} + + /// + public bool IsValidHmacSignature(string json, string hmacSignature) + { + return {{packageName}}.{{corePackageName}}.Utilities.HmacValidatorUtility.IsHmacSignatureValid(hmacSignature, _adyenHmacKey, json); + } + } +} +{{/lambda.trimLineBreaks}} diff --git a/templates-v7/csharp/libraries/generichost/WriteProperty.mustache b/templates-v7/csharp/libraries/generichost/WriteProperty.mustache new file mode 100644 index 000000000..8fe669906 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/WriteProperty.mustache @@ -0,0 +1,10 @@ +{{#required}} +{{>WritePropertyHelper}} + +{{/required}} +{{^required}} +if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}._{{name}}Option.IsSet) + {{#lambda.indent1}} + {{>WritePropertyHelper}}{{! prevent indent}} + {{/lambda.indent1}} +{{/required}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/WritePropertyHelper.mustache b/templates-v7/csharp/libraries/generichost/WritePropertyHelper.mustache new file mode 100644 index 000000000..04270093a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/WritePropertyHelper.mustache @@ -0,0 +1,10 @@ +{{#isNullable}} +if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{^required}}_{{/required}}{{name}}{{^required}}Option.Value{{/required}} != null) + {{#lambda.paste}}{{/lambda.paste}} +else + writer.WriteNull("{{baseName}}"); +{{/isNullable}} +{{^isNullable}} +{{#lambda.paste}} +{{/lambda.paste}} +{{/isNullable}} \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/api.mustache b/templates-v7/csharp/libraries/generichost/api.mustache new file mode 100644 index 000000000..67264bf5a --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/api.mustache @@ -0,0 +1,653 @@ +{{#lambda.trimLineBreaks}} +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +{{#net80OrLater}} +{{#lambda.uniqueLines}} +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-set-cookie}} +using System.Linq; +{{/vendorExtensions.x-set-cookie}} +{{/operation}} +{{/operations}} +{{/lambda.uniqueLines}} +{{/net80OrLater}} +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using {{packageName}}.{{corePackageName}}; +using {{packageName}}.{{corePackageName}}.Auth; +using {{packageName}}.{{corePackageName}}.Client; +using {{packageName}}.{{corePackageName}}.Client.Extensions; +using {{packageName}}.{{apiName}}.{{clientPackage}}; +{{#hasImport}} +using {{packageName}}.{{modelPackage}}; +{{/hasImport}} +{{^netStandard}} +using System.Diagnostics.CodeAnalysis; +{{/netStandard}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints. + /// This class is registered as transient. + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{packageName}}ApiService + { + /// + /// The class containing the events. + /// + {{classname}}Events Events { get; } + + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call. + {{#allParams}} + /// {{{description}}}{{#isHeaderParam}} - Pass this header parameter using .{{/isHeaderParam}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/allParams}} + /// . + /// . + /// of . + {{#isDeprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/isDeprecated}} + Task<{{interfacePrefix}}{{operationId}}ApiResponse> {{operationId}}Async({{>OperationSignature}}); + + {{/operation}} + } + {{#operation}} + {{^vendorExtensions.x-duplicates}} + {{#responses}} + {{#-first}} + + /// + /// The , wraps . + /// + {{>visibility}} interface {{interfacePrefix}}{{operationId}}ApiResponse : {{#lambda.joinWithComma}}{{packageName}}.{{corePackageName}}.{{clientPackage}}.{{interfacePrefix}}ApiResponse {{#responses}}{{#dataType}}{{interfacePrefix}}{{vendorExtensions.x-http-status}}<{{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{/dataType}}{{/responses}}{{/lambda.joinWithComma}} + { + {{#responses}} + {{#vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is the default response type. + /// + /// + bool Is{{vendorExtensions.x-http-status}} { get; } + {{/vendorExtensions.x-http-status-is-default}} + {{^vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}}. + /// + /// + bool Is{{vendorExtensions.x-http-status}} { get; } + {{/vendorExtensions.x-http-status-is-default}} + {{^-last}} + + {{/-last}} + {{/responses}} + } + {{/-first}} + {{/responses}} + {{/vendorExtensions.x-duplicates}} + {{/operation}} + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + {{>visibility}} class {{classname}}Events + { + {{#lambda.trimTrailingWithNewLine}} + {{#operation}} + /// + /// The event raised after the server response. + /// + public event EventHandler{{nrt?}} On{{operationId}}; + + /// + /// The event raised after an error querying the server. + /// + public event EventHandler{{nrt?}} OnError{{operationId}}; + + internal void ExecuteOn{{operationId}}({{#vendorExtensions.x-duplicates}}{{.}}{{/vendorExtensions.x-duplicates}}{{^vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}.{{operationId}}ApiResponse apiResponse) + { + On{{operationId}}?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnError{{operationId}}(Exception exception) + { + OnError{{operationId}}?.Invoke(this, new ExceptionEventArgs(exception)); + } + + {{/operation}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Represents a collection of functions to interact with the API endpoints. + /// + {{>visibility}} sealed partial class {{classname}} : {{interfacePrefix}}{{classname}} + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory. + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger. + /// + public ILogger<{{classname}}> Logger { get; } + + /// + /// The HttpClient. + /// + public System.Net.Http.HttpClient HttpClient { get; } + + /// + /// The class containing the events. + /// + public {{classname}}Events Events { get; }{{#hasApiKeyMethods}} + + /// + /// A token provider of type . + /// + public ITokenProvider ApiKeyProvider { get; }{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} + + /// + /// A token provider of type . + /// + public ITokenProvider BearerTokenProvider { get; }{{/hasHttpBearerMethods}}{{#hasHttpSignatureMethods}} + + /// + /// A token provider of type . + /// + public ITokenProvider HttpSignatureTokenProvider { get; }{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} + + /// + /// A token provider of type . + /// + public ITokenProvider OauthTokenProvider { get; }{{/hasOAuthMethods}} + + {{#net80OrLater}} + {{#lambda.unique}} + {{#operation}} + {{#vendorExtensions.x-set-cookie}} + /// + /// The token cookie container. + /// + public {{packageName}}.{{corePackageName}}.Auth.CookieContainer CookieContainer { get; } + + {{/vendorExtensions.x-set-cookie}} + {{/operation}} + {{/lambda.unique}} + {{/net80OrLater}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}(ILogger<{{classname}}> logger, ILoggerFactory loggerFactory, System.Net.Http.HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#hasApiKeyMethods}}, + ITokenProvider apiKeyProvider{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}, + ITokenProvider bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpSignatureMethods}}, + ITokenProvider httpSignatureTokenProvider{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}, + ITokenProvider oauthTokenProvider{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}}, + {{packageName}}.{{clientPackage}}.CookieContainer cookieContainer{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}}) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = logger == null ? LoggerFactory.CreateLogger<{{classname}}>() : logger; + HttpClient = httpClient; + Events = {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}};{{#hasApiKeyMethods}} + ApiKeyProvider = apiKeyProvider;{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} + BearerTokenProvider = bearerTokenProvider;{{/hasHttpBearerMethods}}{{#hasHttpSignatureMethods}} + HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} + OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}} + CookieContainer = cookieContainer;{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}} + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call. + {{#allParams}} + /// {{{description}}}{{#isBodyParam}}{{/isBodyParam}}{{^required}} ({{#defaultValue}}default to {{.}}{{/defaultValue}}){{/required}}{{#isHeaderParam}} Pass this header parameter in .{{/isHeaderParam}} + {{/allParams}} + /// . + /// . + /// of - If 200 OK response, wraps the when `TryDeserializeOk(...)` is called. + public async Task<{{interfacePrefix}}{{operationId}}ApiResponse> {{operationId}}Async({{>OperationSignature}}) + { + {{#lambda.trimLineBreaks}} + UriBuilder uriBuilder = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage()) + { + {{^servers}} + uriBuilder.Host = HttpClient.BaseAddress{{nrt!}}.Host; + uriBuilder.Port = HttpClient.BaseAddress.Port; + uriBuilder.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilder.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "{{{path}}}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath, "{{{path}}}"); + {{/servers}} + {{#servers}} + {{#-first}} + Uri url = httpRequestMessage.RequestUri = new Uri("{{url}}"); + uriBuilder.Host = url.Authority; + uriBuilder.Scheme = url.Scheme; + uriBuilder.Path = url.AbsolutePath; + {{/-first}} + {{/servers}} + {{#constantParams}} + {{#isPathParam}} + // Set client side default value of Path Param "{{baseName}}". + uriBuilder.Path = uriBuilder.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString(ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}}))); // Constant path parameter + {{/isPathParam}} + {{/constantParams}} + {{#pathParams}} + uriBuilder.Path = uriBuilder.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString())); + {{#-last}} + + {{/-last}} + {{/pathParams}} + {{#queryParams}} + {{#-first}} + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + {{/-first}} + {{/queryParams}} + {{^queryParams}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInQuery}} + + System.Collections.Specialized.NameValueCollection parseQueryString = System.Web.HttpUtility.ParseQueryString(string.Empty); + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + {{/queryParams}} + {{#queryParams}} + {{#required}} + {{#-first}} + + {{/-first}} + parseQueryString["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}}); + {{/required}} + {{/queryParams}} + + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + parseQueryString["{{baseName}}"] = ClientUtils.ParameterToString({{#_enum}}"{{{.}}}"{{/_enum}}); // Constant query parameter + {{/isQueryParam}} + {{/constantParams}} + {{#queryParams}} + {{^required}} + if ({{paramName}}.IsSet) + parseQueryString["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}}.Value); + + {{/required}} + {{#-last}} + uriBuilder.Query = parseQueryString.ToString(); + + {{/-last}} + {{/queryParams}} + // Adds headers to the HttpRequestMessage header, these can be set in the RequestOptions (Idempotency-Key etc.) + requestOptions?.AddHeadersToHttpRequestMessage(httpRequestMessage); + {{#formParams}} + {{#-first}} + MultipartContent multipartContent = new MultipartContent(); + + httpRequestMessage.Content = multipartContent; + + List> formParameters = new List>(); + + multipartContent.Add(new FormUrlEncodedContent(formParameters));{{/-first}}{{^isFile}}{{#required}} + + formParameters.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}))); + + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + formParameters.Add(new KeyValuePair("{{baseName}}", ClientUtils.ParameterToString({{paramName}}.Value))); + + {{/required}} + {{/isFile}} + {{#isFile}} + {{#required}} + multipartContent.Add(new StreamContent({{paramName}})); + + {{/required}} + {{^required}} + if ({{paramName}}.IsSet) + multipartContent.Add(new StreamContent({{paramName}}.Value)); + + {{/required}} + {{/isFile}} + {{/formParams}} + {{#bodyParam}} + httpRequestMessage.Content = ({{paramName}} as object) is System.IO.Stream stream + ? httpRequestMessage.Content = new StreamContent(stream) + : httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize({{paramName}}, _jsonSerializerOptions)); + {{/bodyParam}} + {{#authMethods}} + + {{#isApiKey}} + {{! Only use API Keys that are appended to the HTTP-headers }} + {{^isKeyInCookie}} + {{#isKeyInHeader}} + // Add authorization token to the HttpRequestMessage header + ApiKeyProvider.Get().AddTokenToHttpRequestMessageHeader(httpRequestMessage); + + {{/isKeyInHeader}} + {{/isKeyInCookie}} + {{/isApiKey}} + {{/authMethods}} + httpRequestMessage.RequestUri = uriBuilder.Uri; + {{#authMethods}} + {{#isBasicBearer}} + // Not supported, you'll have to add the BearerToken class and fetch is similar to the ApiKeyProvider. + BearerToken bearerToken{{-index}} = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + bearerToken{{-index}}.UseInHeader(httpRequestMessage, "{{keyParamName}}"); + {{/isBasicBearer}} + {{#isOAuth}} + // Not supported (yet), you'll have to add the BearerToken class and fetch is similar to the ApiKeyProvider. + OAuthToken oauthToken{{-index}} = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + oauthToken{{-index}}.UseInHeader(httpRequestMessage, "{{keyParamName}}"); + {{/isOAuth}} + {{#isHttpSignature}} + + HttpSignatureToken httpSignatureToken{{-index}} = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + if (httpRequestMessage.Content != null) { + string requestBody = await httpRequestMessage.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); + + httpSignatureToken{{-index}}.UseInHeader(httpRequestMessage, requestBody, cancellationToken); + } + {{/isHttpSignature}} + {{/authMethods}} + {{#consumes}} + {{#-first}} + + {{=<% %>=}} + string[] contentTypes = new string[] {<%/-first%> + <%={{ }}=%> + "{{{mediaType}}}"{{^-last}},{{/-last}}{{#-last}} + }; + {{/-last}} + {{/consumes}} + {{#consumes}} + {{#-first}} + + httpRequestMessage.AddUserAgentToHeaders(); + httpRequestMessage.AddLibraryNameToHeader(); + httpRequestMessage.AddLibraryVersionToHeader(); + + string{{nrt?}} contentType = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentType != null && httpRequestMessage.Content != null) + httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + + {{/-first}} + {{/consumes}} + {{#produces}} + {{#-first}} + + {{=<% %>=}} + string[] accepts = new string[] {<%/-first%> + <%={{ }}=%> + "{{{mediaType}}}"{{^-last}},{{/-last}}{{#-last}} + }; + {{/-last}} + {{/produces}} + {{#produces}} + {{#-first}} + + string{{nrt?}} accept = ClientUtils.SelectHeaderAccept(accepts); + + if (accept != null) + httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); + {{/-first}} + {{/produces}} + {{#net60OrLater}} + + httpRequestMessage.Method = HttpMethod.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}; + {{/net60OrLater}} + {{^net60OrLater}} + httpRequestMessage.Method = new HttpMethod("{{#lambda.uppercase}}{{httpMethod}}{{/lambda.uppercase}}"); + {{/net60OrLater}} + + DateTime requestedAt = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) + { + ILogger<{{#vendorExtensions.x-duplicates}}{{.}}.{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse> apiResponseLogger = LoggerFactory.CreateLogger<{{#vendorExtensions.x-duplicates}}{{.}}.{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse>(); + {{#vendorExtensions.x-duplicates}}{{.}}.{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse apiResponse; + + switch ((int)httpResponseMessage.StatusCode) { + {{#responses}} + {{#isBinary}} + case ({{code}}): + {{/isBinary}} + {{/responses}} + {{#responses}} + {{#isBinary}} + {{#-first}} + { + byte[] responseBytesArray = await httpResponseMessage.Content.ReadAsByteArrayAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); + System.IO.Stream responseContentStream = new System.IO.MemoryStream(responseBytesArray); + apiResponse = new{{^net60OrLater}} {{operationId}}ApiResponse{{/net60OrLater}}(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContentStream, "{{{path}}}", requestedAt, _jsonSerializerOptions); + + break; + } + {{/-first}} + {{/isBinary}} + {{/responses}} + default: { + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); + apiResponse = new{{^net60OrLater}} {{operationId}}ApiResponse{{/net60OrLater}}(apiResponseLogger, httpRequestMessage, httpResponseMessage, responseContent, "{{{path}}}", requestedAt, _jsonSerializerOptions); + + break; + } + } + + Events.ExecuteOn{{operationId}}(apiResponse); + {{#net80OrLater}} + {{#responses}} + {{#vendorExtensions.x-set-cookie}} + if (httpResponseMessage.StatusCode == (HttpStatusCode) {{code}} && httpResponseMessage.Headers.TryGetValues("Set-Cookie", out var cookieHeaders)) + { + foreach(string cookieHeader in cookieHeaders) + { + IList setCookieHeaderValues = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeaders.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValue in setCookieHeaderValues) + { + Cookie cookie = new Cookie(setCookieHeaderValue.Name.ToString(), setCookieHeaderValue.Value.ToString()) + { + HttpOnly = setCookieHeaderValue.HttpOnly + }; + + if (setCookieHeaderValue.Expires.HasValue) + cookie.Expires = setCookieHeaderValue.Expires.Value.UtcDateTime; + + if (setCookieHeaderValue.Path.HasValue) + cookie.Path = setCookieHeaderValue.Path.Value; + + if (setCookieHeaderValue.Domain.HasValue) + cookie.Domain = setCookieHeaderValue.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilder.Scheme}://{uriBuilder.Host}"), cookie); + } + } + } + + {{/vendorExtensions.x-set-cookie}} + {{/responses}} + {{/net80OrLater}} + return apiResponse; + } + } + } + catch(Exception exception) + { + Events.ExecuteOnError{{operationId}}(exception); + throw; + } + {{/lambda.trimLineBreaks}} + } + {{^vendorExtensions.x-duplicates}} + {{#responses}} + {{#-first}} + + /// + /// The . + /// + {{>visibility}} partial class {{operationId}}ApiResponse : {{packageName}}.{{corePackageName}}.{{clientPackage}}.ApiResponse, {{interfacePrefix}}{{operationId}}ApiResponse + { + /// + /// The logger for . + /// + public ILogger<{{operationId}}ApiResponse> Logger { get; } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw data. + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public {{operationId}}ApiResponse(ILogger<{{operationId}}ApiResponse> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The . + /// + /// . + /// . + /// . + /// The raw binary stream (only set for binary responses). + /// The path used when making the request. + /// The DateTime.UtcNow when the request was retrieved. + /// + public {{operationId}}ApiResponse(ILogger<{{operationId}}ApiResponse> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + {{#responses}} + + {{#vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is the default response type. + /// + /// + public bool Is{{vendorExtensions.x-http-status}} => {{#vendorExtensions.x-only-default}}true{{/vendorExtensions.x-only-default}}{{^vendorExtensions.x-only-default}}{{#lambda.joinConditions}}{{#responses}}{{^vendorExtensions.x-http-status-is-default}}!Is{{vendorExtensions.x-http-status}} {{/vendorExtensions.x-http-status-is-default}}{{/responses}}{{/lambda.joinConditions}}{{/vendorExtensions.x-only-default}}; + {{/vendorExtensions.x-http-status-is-default}} + {{^vendorExtensions.x-http-status-is-default}} + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}}. + /// + /// + {{#vendorExtensions.x-http-status-range}} + public bool Is{{vendorExtensions.x-http-status}} + { + get + { + int statusCode = (int)StatusCode; + return {{vendorExtensions.x-http-status-range}}00 >= statusCode && {{vendorExtensions.x-http-status-range}}99 <= statusCode; + } + } + {{/vendorExtensions.x-http-status-range}} + {{^vendorExtensions.x-http-status-range}} + public bool Is{{vendorExtensions.x-http-status}} => {{code}} == (int)StatusCode; + {{/vendorExtensions.x-http-status-range}} + {{/vendorExtensions.x-http-status-is-default}} + {{#dataType}} + + /// + /// Deserializes the response if the response is {{code}} {{vendorExtensions.x-http-status}}. + /// + /// + public {{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{vendorExtensions.x-http-status}}() + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>AsModel}}{{! prevent indent}} + {{/lambda.indent4}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Returns true if the response is {{code}} {{vendorExtensions.x-http-status}} and the deserialized response is not null. + /// + /// + /// + public bool TryDeserialize{{vendorExtensions.x-http-status}}Response({{#net60OrLater}}[NotNullWhen(true)]{{/net60OrLater}}out {{#isModel}}{{^containerType}}{{packageName}}.{{modelPackage}}.{{/containerType}}{{/isModel}}{{{dataType}}}{{#nrt}}?{{/nrt}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} result) + { + result = null; + + try + { + result = {{vendorExtensions.x-http-status}}(); + } + catch (Exception exception) + { + OnDeserializationError(exception, (HttpStatusCode){{#vendorExtensions.x-http-status-range}}{{.}}{{/vendorExtensions.x-http-status-range}}{{^vendorExtensions.x-http-status-range}}{{code}}{{/vendorExtensions.x-http-status-range}}); + } + + return result != null; + } + {{/dataType}} + {{#-last}} + + private void OnDeserializationError(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>OnDeserializationError}}{{! prevent indent}} + {{/lambda.indent4}} + {{/lambda.trimTrailingWithNewLine}} + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + {{/-last}} + {{/responses}} + } + + {{/-first}} + {{/responses}} + {{/vendorExtensions.x-duplicates}} + {{/operation}} + } + {{/operations}} +} +{{/lambda.trimLineBreaks}} diff --git a/templates-v7/csharp/libraries/generichost/api_doc.mustache b/templates-v7/csharp/libraries/generichost/api_doc.mustache new file mode 100644 index 000000000..feb36ebc0 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/api_doc.mustache @@ -0,0 +1,91 @@ +## {{packageName}}.{{apiPackage}}.{{classname}}{{#description}} +{{.}}{{/description}} + +#### API Base-Path: **{{{basePath}}}** + + +#### Authorization: {{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}{{#isApiKey}}{{^isKeyInCookie}}{{#isKeyInHeader}}{{{name}}}{{/isKeyInHeader}}{{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}} + + +#### Initialization + + +```csharp +using {{packageName}}.{{corePackageName}}.Options; +using {{packageName}}.{{apiName}}.Extensions; +using {{packageName}}.{{apiName}}.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +IHost host = Host.CreateDefaultBuilder() + .Configure{{apiName}}((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + // Set your ADYEN_API_KEY or use get it from your environment using context.Configuration["ADYEN_API_KEY"]. + options.AdyenApiKey = context.Configuration["ADYEN_API_KEY"]; + + // Set your environment, e.g. `Test` or `Live`. + options.Environment = AdyenEnvironment.Test; + + // For the Live environment, additionally include your LiveEndpointUrlPrefix. + options.LiveEndpointUrlPrefix = "your-live-endpoint-url-prefix"; + }); + }) + .Build(); + + // You can inject this service in your constructor. + {{interfacePrefix}}{{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} = host.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); +``` + +| Method | HTTP request | Description | +|--------|--------------|-------------| +{{#operations}} +{{#operation}} +| [**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}} | +{{/operation}} +{{/operations}} + +{{#operations}} +{{#operation}} + +### **{{httpMethod}}** **{{{path}}}** + +{{{summary}}} + +#### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | +|------|------|-------------| +{{/-last}} +{{/allParams}} +{{#allParams}} +| **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}[{{dataType}}]{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}**{{dataType}}**{{/isFile}}{{/isPrimitiveType}} | {{description}} | +{{/allParams}} + +#### Example usage + +```csharp +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.{{apiName}}.Services; + +// Example `{{classname}}.{{operationId}}` usage: +// Provide the following values: {{#allParams}}{{^isHeaderParam}}{{paramName}}{{^-last}}, {{/-last}}{{/isHeaderParam}}{{#isHeaderParam}}[HeaderParameter] {{paramName}}{{^-last}}, {{/-last}}{{/isHeaderParam}}{{/allParams}} +{{#returnType}}{{^isVoid}}{{interfacePrefix}}{{returnType}} response = {{/isVoid}}{{/returnType}}await {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{operationId}}Async( + {{#pathParams}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/pathParams}}{{#queryParams}}{{#required}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/required}}{{/queryParams}}{{#bodyParams}}{{{dataType}}}{{>NullConditionalParameter}} {{paramName}}, {{/bodyParams}}{{#queryParams}}{{^required}}Option<{{{dataType}}}{{>NullConditionalParameter}}> {{paramName}}{{#notRequiredOrIsNullable}} = default{{/notRequiredOrIsNullable}}, {{/required}}{{/queryParams}} + RequestOptions requestOptions = default, + CancellationToken cancellationToken = default); + +if (response.TryDeserializeOkResponse(out {{returnType}} result)) +{ + // Handle result, if 200 OK response +} + +``` + +#### Return type +{{#returnType}}{{#returnTypeIsPrimitive}}[{{{returnType}}}]{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[{{returnType}}](){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + + +{{/operation}} +{{/operations}} diff --git a/templates-v7/csharp/libraries/generichost/api_test.mustache b/templates-v7/csharp/libraries/generichost/api_test.mustache new file mode 100644 index 000000000..d54244957 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/api_test.mustache @@ -0,0 +1,71 @@ +{{>partial_header}} +using {{packageName}}.Core.Options;{{#hasImport}} +using {{packageName}}.{{modelPackage}};{{/hasImport}} +using {{packageName}}.{{apiName}}.{{clientPackageName}}; +using {{packageName}}.{{apiName}}.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text.Json; + +{{>testInstructions}} + + +namespace {{packageName}}.Test.{{apiPackage}} +{ + /// + /// Class for testing {{classname}} + /// + [TestClass] + public sealed class {{classname}}Test + { + private readonly JsonSerializerOptionsProvider _jsonSerializerOptionsProvider; + + public {{classname}}Test() + { + IHost host = Host.CreateDefaultBuilder() + .Configure{{classname}}((context, services, config) => + { + config.ConfigureAdyenOptions(options => + { + options.Environment = AdyenEnvironment.Test; + }); + }) + .Build(); + + _jsonSerializerOptionsProvider = host.Services.GetRequiredService(); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}}. + /// + public async Task Given_Deserialize_When_{{operationId}}_Successfully_Deserializes() + { + // Arrange + // TODO: Insert your example code from open-api here + var client = TestUtilities.GetTestFileContent("mocks/posmobile/create-session.json"); + + {{#allParams}} + {{^required}}Client.Option<{{/required}}{{{dataType}}}{{>NullConditionalParameter}}{{^required}}>{{/required}} {{paramName}} = default{{nrt!}}; + {{/allParams}} + {{#responses}} + {{#-first}} + {{#dataType}} + + // Act + // TODO: Prefill the ResponseType + // IDEALLY: We insert the SERVICE and then we call it using the right parameters (this gets tricky with query params* but very doable!) + var response = JsonSerializer.Deserialize<{{name}}Response}>(json, _jsonSerializerOptionsProvider); + + // Assert + Assert.IsNotNull(response); + {{/dataType}} + {{/-first}} + {{/responses}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/templates-v7/csharp/libraries/generichost/model.mustache b/templates-v7/csharp/libraries/generichost/model.mustache new file mode 100644 index 000000000..fa07a7053 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/model.mustache @@ -0,0 +1,56 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +{{^useGenericHost}} +using System.Runtime.Serialization; +{{/useGenericHost}} +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#useGenericHost}} +{{#useSourceGeneration}} +using System.Text.Json.Serialization.Metadata; +{{/useSourceGeneration}} +using {{packageName}}.{{corePackageName}}; +using {{packageName}}.{{apiName}}.{{clientPackage}}; +{{/useGenericHost}} +{{#models}} +{{#lambda.trimTrailingWithNewLine}} +{{#model}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}} +{{>modelEnum}} + +{{/isEnum}} +{{^isEnum}} +{{>modelGeneric}} + + +{{>JsonConverter}} + +{{/isEnum}} +{{>SourceGenerationContext}} + +{{/model}} +{{/lambda.trimTrailingWithNewLine}} +{{/models}} +} diff --git a/templates-v7/csharp/libraries/generichost/modelGeneric.mustache b/templates-v7/csharp/libraries/generichost/modelGeneric.mustache new file mode 100644 index 000000000..00f340413 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/modelGeneric.mustache @@ -0,0 +1,413 @@ + /// + /// {{{description}}}{{^description}}{{classname}}{{/description}}. + /// + {{>visibility}} partial class {{classname}}{{#lambda.firstDot}}{{#parent}} : .{{/parent}}{{#validatable}} : .{{/validatable}}{{#equatable}}{{#readOnlyVars}}{{#-first}} : .{{/-first}}{{/readOnlyVars}}{{/equatable}}{{/lambda.firstDot}}{{#lambda.joinWithComma}}{{#parent}}{{{.}}} {{/parent}}{{>ImplementsIEquatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + { + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + /// + /// Initializes a new instance of the class. + /// + /// + {{#composedSchemas.anyOf}} + /// + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + /// {{description}}{{^description}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + {{/isDiscriminator}} + {{/allVars}} + {{#model.vendorExtensions.x-model-is-mutable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutable}}{{^model.vendorExtensions.x-model-is-mutable}}internal{{/model.vendorExtensions.x-model-is-mutable}} {{classname}}({{#lambda.joinWithComma}}{{{dataType}}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{#model.composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{baseType}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{/model.composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{parent}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + { + {{#composedSchemas.anyOf}} + {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/composedSchemas.anyOf}} + {{name}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{#allVars}} + {{^isDiscriminator}} + {{^isInherited}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isInherited}} + {{#isInherited}} + {{#isNew}} + {{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isNew}} + {{/isInherited}} + {{/isDiscriminator}} + {{#vendorExtensions.x-is-base-or-new-discriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + {{name}} = {{^isEnum}}this.GetType().Name{{/isEnum}}{{#isEnum}}({{datatypeWithEnum}})Enum.Parse(typeof({{datatypeWithEnum}}), this.GetType().Name){{/isEnum}}; + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/vendorExtensions.x-is-base-or-new-discriminator}} + {{/allVars}} + OnCreated(); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{^composedSchemas.oneOf}} + /// + /// Initializes a new instance of the class. + /// + {{#composedSchemas.anyOf}} + /// + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + /// {{description}}{{^description}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} + {{/isDiscriminator}} + {{/allVars}} + {{^composedSchemas.anyOf}} + [JsonConstructor] + {{/composedSchemas.anyOf}} + {{#model.vendorExtensions.x-model-is-mutable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutable}}{{^model.vendorExtensions.x-model-is-mutable}}internal{{/model.vendorExtensions.x-model-is-mutable}} {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}} {{/composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + { + {{#composedSchemas.anyOf}} + {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/composedSchemas.anyOf}} + {{#allVars}} + {{^isDiscriminator}} + {{^isInherited}} + {{^required}}_{{/required}}{{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isInherited}} + {{#isInherited}} + {{#isNew}} + {{^required}}_{{/required}}{{name}}{{^required}}Option{{/required}} = {{#lambda.escape_reserved_word}}{{#lambda.camel_case}}{{name}}{{/lambda.camel_case}}{{/lambda.escape_reserved_word}}; + {{/isNew}} + {{/isInherited}} + {{/isDiscriminator}} + {{#vendorExtensions.x-is-base-or-new-discriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + {{name}} = {{^isEnum}}this.GetType().Name{{/isEnum}}{{#isEnum}}({{datatypeWithEnum}})Enum.Parse(typeof({{datatypeWithEnum}}), this.GetType().Name){{/isEnum}}; + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/vendorExtensions.x-is-base-or-new-discriminator}} + {{/allVars}} + OnCreated(); + } + + {{#allVars}} + {{^isDiscriminator}} + {{#-first}} + /// + /// Best practice: Use the constructor to initialize your objects to understand which parameters are required/optional. + /// + {{#model.vendorExtensions.x-model-is-mutable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutable}}{{^model.vendorExtensions.x-model-is-mutable}}internal{{/model.vendorExtensions.x-model-is-mutable}} {{classname}}() + { + } + {{/-first}} + {{/isDiscriminator}} + {{/allVars}} + + {{/composedSchemas.oneOf}} + partial void OnCreated(); + + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} +{{>modelInnerEnum}} + + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + + {{/complexType}} + {{/isEnum}} + {{^isDiscriminator}} + {{#isEnum}} + {{^required}} + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> _{{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{{description}}}{{^description}}.{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#example}} + /* {{.}} */ + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/deprecated}} + public {{#isNew}}new {{/isNew}}{{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this._{{name}}Option; } {{^isReadOnly}}set { this._{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isEnum}} + {{/isDiscriminator}} + {{/vars}} + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{^required}} + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> _{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{{description}}}{{^description}}.{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /* {{.}} */ + {{/example}} + {{#deprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/deprecated}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this._{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option; } {{^isReadOnly}}set { this._{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + /// + /// {{{description}}}{{^description}}.{{/description}}. + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /* {{.}} */ + {{/example}} + {{#deprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/deprecated}} + public {{{dataType}}}{{>NullConditionalProperty}} {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{#allVars}} + {{#vendorExtensions.x-is-base-or-new-discriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + /// + /// The discriminator. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}{{datatypeWithEnum}} {{name}} { get; } + + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/vendorExtensions.x-is-base-or-new-discriminator}} + {{^vendorExtensions.x-is-base-or-new-discriminator}} + {{^isEnum}} + {{#isInherited}} + {{#isNew}} + {{^required}} + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public new Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> _{{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{{description}}}{{^description}}.{{/description}} + /// {{#description}} + /// {{.}}{{/description}} + {{#example}} + /* {{.}} */ + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/deprecated}} + public new {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this._{{name}}Option } {{^isReadOnly}}set { this._{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isNew}} + {{/isInherited}} + {{^isInherited}} + {{^required}} + /// + /// This is used to track if an optional field is set. If set, will be populated. + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> _{{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} + /// + /// {{description}}{{^description}}.{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + {{#example}} + /* {{.}} */ + {{/example}} + [JsonPropertyName("{{baseName}}")] + {{#deprecated}} + [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] + {{/deprecated}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this._{{name}}Option; } {{^isReadOnly}}set { this._{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} + + {{/isInherited}} + {{/isEnum}} + {{/vendorExtensions.x-is-base-or-new-discriminator}} + {{/allVars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + /// + /// Gets or sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#composedSchemas.oneOf}} + if (this.{{name}} != null) + sb.Append({{name}}.ToString().Replace("\n", "\n ")); + {{/composedSchemas.oneOf}} + {{#parent}} + sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); + {{/parent}} + {{#vars}} + {{^isDiscriminator}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/isDiscriminator}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + sb.Append("}\n"); + return sb.ToString(); + } + {{#equatable}} + {{#readOnlyVars}} + {{#-first}} + + /// + /// Returns true if objects are equal. + /// + /// Object to be compared + /// Boolean + public override bool Equals(object{{nrt?}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal. + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}}{{nrt?}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return {{#parent}}base.Equals(input) && {{/parent}}{{#readOnlyVars}}{{^isInherited}}{{^isContainer}} + ( + {{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}} + ({{name}} != null && + {{name}}.Equals(input.{{name}})) + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + {{name}}.Equals(input.{{name}}) + {{/vendorExtensions.x-is-value-type}} + ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} + ( + {{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}{{name}} != null && + input.{{name}} != null && + {{/vendorExtensions.x-is-value-type}}{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/isInherited}}{{/readOnlyVars}}{{^readOnlyVars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/readOnlyVars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + && (AdditionalProperties.Count == input.AdditionalProperties.Count && !AdditionalProperties.Except(input.AdditionalProperties).Any()); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code. + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + {{#parent}} + int hashCode = base.GetHashCode(); + {{/parent}} + {{^parent}} + int hashCode = 41; + {{/parent}} + {{#readOnlyVars}} + {{#required}} + {{^isNullable}} + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/isNullable}} + {{/required}} + {{/readOnlyVars}} + {{#readOnlyVars}} + {{#lambda.copy}} + if ({{name}} != null) + hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + + {{/lambda.copy}} + {{#isNullable}} + {{#lambda.pasteOnce}} + {{/lambda.pasteOnce}} + {{/isNullable}} + {{^required}} + {{#lambda.pasteOnce}} + {{/lambda.pasteOnce}} + {{/required}} + {{/readOnlyVars}} + {{#isAdditionalPropertiesTrue}} + {{^parentModel}} + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); + {{/parentModel}} + {{/isAdditionalPropertiesTrue}} + + return hashCode; + } + } + {{/-first}} + {{/readOnlyVars}} + {{/equatable}} +{{#validatable}} +{{^parentModel}} + +{{>validatable}} + +{{/parentModel}} +{{/validatable}} + } \ No newline at end of file diff --git a/templates-v7/csharp/libraries/generichost/modelInnerEnum.mustache b/templates-v7/csharp/libraries/generichost/modelInnerEnum.mustache new file mode 100644 index 000000000..572d0f136 --- /dev/null +++ b/templates-v7/csharp/libraries/generichost/modelInnerEnum.mustache @@ -0,0 +1,116 @@ + {{^isContainer}} + /// + /// {{{description}}}{{^description}}Defines {{{name}}}.{{/description}} + /// + {{#description}} + /// {{.}} + {{/description}} + {{#isString}} + {{#useGenericHost}} + [JsonConverter(typeof({{datatypeWithEnum}}JsonConverter))] + {{/useGenericHost}} + {{/isString}} + {{>visibility}} class {{datatypeWithEnum}} : IEnum + { + /// + /// Returns the value of the {{datatypeWithEnum}}. + /// + public string? Value { get; set; } + + {{#allowableValues}} + {{#enumVars}} + /// + /// {{datatypeWithEnum}}.{{name}} - {{value}} + /// + public static readonly {{datatypeWithEnum}} {{name}} = new("{{value}}"); + {{^-last}} + + {{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{datatypeWithEnum}}(string? value) + { + Value = value; + } + + /// + /// Converts a string to a implicitly. + /// + /// The string value to convert. Defaults to null. + /// A new instance initialized with the string value. + public static implicit operator {{datatypeWithEnum}}?(string? value) => value == null ? null : new {{datatypeWithEnum}}(value); + + /// + /// Converts a instance to a string implicitly. + /// + /// The instance. Default to null. + /// String value of the instance./// + public static implicit operator string?({{datatypeWithEnum}}? option) => option?.Value; + + public static bool operator ==({{datatypeWithEnum}}? left, {{datatypeWithEnum}}? right) => string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public static bool operator !=({{datatypeWithEnum}}? left, {{datatypeWithEnum}}? right) => !string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase); + + public override bool Equals(object? obj) => obj is {{datatypeWithEnum}} other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => Value?.GetHashCode() ?? 0; + + public override string ToString() => Value ?? string.Empty; + + {{#useGenericHost}} + /// + /// Returns a . + /// + /// + /// or null. + public static {{datatypeWithEnum}}? FromStringOrDefault(string value) + { + return value switch { + {{#allowableValues}}{{#enumVars}}{{#isString}}"{{{value}}}"{{/isString}} => {{datatypeWithEnum}}.{{name}}, + {{/enumVars}}{{/allowableValues}}_ => null, + }; + } + + /// + /// Converts the to the json value. + /// + /// + /// String value of the enum. + {{#isString}} + /// + {{/isString}} + public static {{>EnumValueDataType}}?{{#lambda.first}}{{#nrt}}{{/nrt}}{{/lambda.first}} ToJsonValue({{datatypeWithEnum}}? value) + { + if (value == null) + return null; + + {{#allowableValues}} + {{#enumVars}} + if (value == {{datatypeWithEnum}}.{{name}}) + return {{#isString}}"{{{value}}}"{{/isString}}; + + {{/enumVars}} + {{/allowableValues}} + return null; + } + + /// + /// JsonConverter for writing {{datatypeWithEnum}}. + /// + public class {{datatypeWithEnum}}JsonConverter : JsonConverter<{{datatypeWithEnum}}> + { + public override {{datatypeWithEnum}}? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) + { + string value = reader.GetString(); + return value == null ? null : {{datatypeWithEnum}}.FromStringOrDefault(value) ?? new {{datatypeWithEnum}}(value); + } + + public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}} value, JsonSerializerOptions jsonOptions) + { + writer.WriteStringValue({{datatypeWithEnum}}.ToJsonValue(value)); + } + } + {{/useGenericHost}} + } + {{/isContainer}} \ No newline at end of file diff --git a/templates-v7/csharp/partial_header.mustache b/templates-v7/csharp/partial_header.mustache new file mode 100644 index 000000000..377ccfabb --- /dev/null +++ b/templates-v7/csharp/partial_header.mustache @@ -0,0 +1,18 @@ +/* + {{#appName}} + * {{{.}}} + * + {{/appName}} + {{#appDescription}} + * {{{.}}} + * + {{/appDescription}} + {{#version}} + * The version of the OpenAPI document: {{{.}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{.}}} + {{/infoEmail}} + * NOTE: This class is auto-generated using a modified version (https://github.com/Adyen/adyen-sdk-automation) of the OpenAPI Generator: https://github.com/openapitools/openapi-generator.git. + * Do not edit this class manually. + */ diff --git a/templates-v7/csharp/validatable.mustache b/templates-v7/csharp/validatable.mustache new file mode 100644 index 000000000..14fbc18c4 --- /dev/null +++ b/templates-v7/csharp/validatable.mustache @@ -0,0 +1,141 @@ +{{#discriminator}} + /// + /// To validate all properties of the instance. + /// + /// . + /// . + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance. + /// + /// . + /// . + protected IEnumerable BaseValidate(ValidationContext validationContext) + { +{{/discriminator}} +{{^discriminator}} + {{#parent}} + /// + /// To validate all properties of the instance. + /// + /// . + /// . + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance. + /// + /// . + /// . + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + {{/parent}} + {{^parent}} + /// + /// To validate all properties of the instance. + /// + /// . + /// . + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + {{/parent}} +{{/discriminator}} + {{#parent}} + {{^isArray}} + {{^isMap}} + foreach (var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext)) + { + yield return x; + } + {{/isMap}} + {{/isArray}} + {{/parent}} + {{#vars}} + {{#hasValidation}} + {{^isEnum}} + {{^isDateTime}} + {{^isDate}} + {{^isTime}} + {{#maxLength}} + // {{{name}}} ({{{dataType}}}) maxLength + if (this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } + + {{/maxLength}} + {{#minLength}} + // {{{name}}} ({{{dataType}}}) minLength + if (this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } + + {{/minLength}} + {{/isTime}} + {{/isDate}} + {{/isDateTime}} + {{#maximum}} + // {{{name}}} ({{{dataType}}}) maximum + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} {{#exclusiveMaximum}}<={{/exclusiveMaximum}}{{^exclusiveMaximum}}>{{/exclusiveMaximum}} ({{{dataType}}}){{maximum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.", new [] { "{{{name}}}" }); + } + + {{/maximum}} + {{#minimum}} + // {{{name}}} ({{{dataType}}}) minimum + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} {{#exclusiveMaximum}}>={{/exclusiveMaximum}}{{^exclusiveMaximum}}<{{/exclusiveMaximum}} ({{{dataType}}}){{minimum}}) + { + yield return new ValidationResult("Invalid value for {{{name}}}, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.", new [] { "{{{name}}}" }); + } + + {{/minimum}} + {{#pattern}} + {{^isByteArray}} + {{#vendorExtensions.x-is-value-type}} + {{#isNullable}} + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null){ + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>ValidateRegex}}{{! prevent indent}} + {{/lambda.indent4}} + + {{/lambda.trimTrailingWithNewLine}} + } + + {{/isNullable}} + {{^isNullable}} + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent3}} + {{>ValidateRegex}}{{! prevent indent}} + {{/lambda.indent3}} + + {{/lambda.trimTrailingWithNewLine}} + {{/isNullable}} + {{/vendorExtensions.x-is-value-type}} + {{^vendorExtensions.x-is-value-type}} + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null) { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.indent4}} + {{>ValidateRegex}}{{! prevent indent}} + {{/lambda.indent4}} + + {{/lambda.trimTrailingWithNewLine}} + } + + {{/vendorExtensions.x-is-value-type}} + {{/isByteArray}} + {{/pattern}} + {{/isEnum}} + {{/hasValidation}} + {{/vars}} + yield break; + } \ No newline at end of file diff --git a/templates-v7/csharp/visibility.mustache b/templates-v7/csharp/visibility.mustache new file mode 100644 index 000000000..a1d1f4163 --- /dev/null +++ b/templates-v7/csharp/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/templates/csharp/AbstractOpenAPISchema.mustache b/templates/csharp/AbstractOpenAPISchema.mustache deleted file mode 100644 index ab90f174c..000000000 --- a/templates/csharp/AbstractOpenAPISchema.mustache +++ /dev/null @@ -1,71 +0,0 @@ -{{>partial_header}} -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace {{packageName}}.{{modelPackage}} -{ - /// - /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification - /// - {{>visibility}} abstract partial class AbstractOpenAPISchema - { - /// - /// Custom JSON serializer - /// - static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings - { - // OpenAPI generated types generally hide default constructors. - ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, - MissingMemberHandling = MissingMemberHandling.Ignore, - ContractResolver = new DefaultContractResolver - { - NamingStrategy = new CamelCaseNamingStrategy - { - OverrideSpecifiedNames = false - } - } - }; - - /// - /// Gets or Sets the actual instance - /// - public abstract Object ActualInstance { get; set; } - - /// - /// Gets or Sets IsNullable to indicate whether the instance is nullable - /// - public bool IsNullable { get; protected set; } - - /// - /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` - /// - public string SchemaType { get; protected set; } - - /// - /// Converts the instance into JSON string. - /// - public abstract string ToJson(); - - // Check if the contains TypeEnum value - protected static bool ContainsValue(string type) where T : struct, IConvertible - { - // Search for type in .TypeEnum - List list = new List(); - var members = typeof(T).GetTypeInfo().DeclaredMembers; - foreach (var member in members) - { - var val = member?.GetCustomAttribute(false)?.Value; - if (!string.IsNullOrEmpty(val)) - { - list.Add(val); - } - } - - return list.Contains(type); - } - } -} diff --git a/templates/csharp/api-single.mustache b/templates/csharp/api-single.mustache deleted file mode 100644 index da60553d0..000000000 --- a/templates/csharp/api-single.mustache +++ /dev/null @@ -1,87 +0,0 @@ -{{>partial_header}} -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Adyen.Constants; -using Adyen.Model; -{{#hasImport}}using Adyen.{{modelPackage}}; -{{/hasImport}} - -namespace {{packageName}}.Service -{ -{{#operations}} - /// - /// {{classname}} Interface - /// - public interface I{{customApi}}Service - { - {{#operation}} -{{>method_documentation}} - {{#returnType}} - /// . - {{/returnType}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}{{modelPackage}}.{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}({{>api_parameters}}); - - {{#supportsAsync}} -{{>method_documentation}} - /// A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects.{{#returnType}} - /// Task of .{{/returnType}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}Task<{{modelPackage}}.{{{.}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_parameters_async}}); - - {{/supportsAsync}} - {{/operation}} - } - {{/operations}} - - {{#operations}} - /// - /// Represents a collection of functions to interact with the {{customApi}}Service API endpoints - /// - {{>visibility}} class {{customApi}}Service : AbstractService, I{{customApi}}Service - { - private readonly string _baseUrl; - - public {{customApi}}Service(Client client) : base(client) - { - _baseUrl = CreateBaseUrl("{{{basePath}}}"); - } - {{#operation}} - - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - public {{#returnType}}{{modelPackage}}.{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}({{>api_parameters}}) - { - {{#returnType}}return {{/returnType}}{{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_invoke}}).ConfigureAwait(false).GetAwaiter().GetResult(); - } - - {{#supportsAsync}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}public async Task<{{modelPackage}}.{{{.}}}>{{/returnType}}{{^returnType}}public async Task{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_parameters_async}}) - { - {{#hasQueryParams}} - // Build the query string - var queryParams = new Dictionary(); - {{#queryParams}} - {{^required}}if ({{paramName}} != null) {{/required}}queryParams.Add("{{baseName}}", {{paramName}}{{^isString}}{{^isDateTime}}.Value.ToString(){{/isDateTime}}{{#isDateTime}}.ToString("yyyy-MM-ddTHH:mm:ssZ"){{/isDateTime}}{{/isString}}); - {{/queryParams}} - {{/hasQueryParams}} - var endpoint = _baseUrl + {{#hasPathParams}}${{/hasPathParams}}"{{{path}}}"{{#hasQueryParams}} + ToQueryString(queryParams){{/hasQueryParams}}; - var resource = new ServiceResource(this, endpoint); - {{#returnType}}return {{/returnType}}await resource.RequestAsync{{#returnType}}<{{modelPackage}}.{{returnType}}>{{/returnType}}({{#bodyParam}}{{paramName}}.ToJson(){{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, requestOptions, new HttpMethod("{{httpMethod}}"), cancellationToken).ConfigureAwait(false); - } - {{/supportsAsync}} - {{/operation}} - } - {{/operations}} -} \ No newline at end of file diff --git a/templates/csharp/api.mustache b/templates/csharp/api.mustache deleted file mode 100644 index 27ff0eb4d..000000000 --- a/templates/csharp/api.mustache +++ /dev/null @@ -1,86 +0,0 @@ -{{>partial_header}} -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Adyen.Model; -{{#hasImport}}using Adyen.{{modelPackage}}; -{{/hasImport}} - -namespace {{packageName}}.{{apiPackage}} -{ -{{#operations}} - /// - /// {{classname}} Interface - /// - public interface I{{classname}} - { - {{#operation}} -{{>method_documentation}} - {{#returnType}} - /// . - {{/returnType}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}{{modelPackage}}.{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}({{>api_parameters}}); - - {{#supportsAsync}} -{{>method_documentation}} - /// A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects.{{#returnType}} - /// Task of .{{/returnType}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}Task<{{modelPackage}}.{{{.}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_parameters_async}}); - - {{/supportsAsync}} - {{/operation}} - } - {{/operations}} - - {{#operations}} - /// - /// Represents a collection of functions to interact with the {{classname}} API endpoints - /// - {{>visibility}} class {{classname}} : AbstractService, I{{classname}} - { - private readonly string _baseUrl; - - public {{classname}}(Client client) : base(client) - { - _baseUrl = CreateBaseUrl("{{{basePath}}}"); - } - {{#operation}} - - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - public {{#returnType}}{{modelPackage}}.{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}({{>api_parameters}}) - { - {{#returnType}}return {{/returnType}}{{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_invoke}}).ConfigureAwait(false).GetAwaiter().GetResult(); - } - - {{#supportsAsync}} - {{#isDeprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/isDeprecated}} - {{#returnType}}public async Task<{{modelPackage}}.{{{.}}}>{{/returnType}}{{^returnType}}public async Task{{/returnType}} {{#lambda.pascalcase}}{{vendorExtensions.x-methodName}}{{/lambda.pascalcase}}Async({{>api_parameters_async}}) - { - {{#hasQueryParams}} - // Build the query string - var queryParams = new Dictionary(); - {{#queryParams}} - {{^required}}if ({{paramName}} != null) {{/required}}queryParams.Add("{{baseName}}", {{paramName}}{{^isString}}{{^isDateTime}}.ToString(){{/isDateTime}}{{#isDateTime}}{{^required}}.Value{{/required}}.ToString("yyyy-MM-ddTHH:mm:ssZ"){{/isDateTime}}{{/isString}}); - {{/queryParams}} - {{/hasQueryParams}} - var endpoint = _baseUrl + {{#hasPathParams}}${{/hasPathParams}}"{{{path}}}"{{#hasQueryParams}} + ToQueryString(queryParams){{/hasQueryParams}}; - var resource = new ServiceResource(this, endpoint); - {{#returnType}}return {{/returnType}}await resource.RequestAsync{{#returnType}}<{{modelPackage}}.{{returnType}}>{{/returnType}}({{#bodyParam}}{{paramName}}.ToJson(){{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, requestOptions, new HttpMethod("{{httpMethod}}"), cancellationToken).ConfigureAwait(false); - } - {{/supportsAsync}} - {{/operation}} - } - {{/operations}} -} \ No newline at end of file diff --git a/templates/csharp/api_invoke.mustache b/templates/csharp/api_invoke.mustache deleted file mode 100644 index 45815fc53..000000000 --- a/templates/csharp/api_invoke.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#requiredParams}}{{#isPathParam}}{{paramName}}, {{/isPathParam}}{{#isBodyParam}}{{paramName}}, {{/isBodyParam}}{{#isQueryParam}}{{paramName}}, {{/isQueryParam}}{{/requiredParams}}{{#optionalParams}}{{#isPathParam}}{{paramName}}, {{/isPathParam}}{{#isBodyParam}}{{paramName}}, {{/isBodyParam}}{{#isQueryParam}}{{paramName}}, {{/isQueryParam}}{{/optionalParams}}requestOptions \ No newline at end of file diff --git a/templates/csharp/api_parameter_ordering.mustache b/templates/csharp/api_parameter_ordering.mustache deleted file mode 100644 index 593846f25..000000000 --- a/templates/csharp/api_parameter_ordering.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isPathParam}}{{{dataType}}} {{paramName}} = default, {{/isPathParam}}{{#isBodyParam}}{{{dataType}}} {{paramName}} = default, {{/isBodyParam}}{{#isQueryParam}}{{{dataType}}} {{paramName}} = default, {{/isQueryParam}} \ No newline at end of file diff --git a/templates/csharp/api_parameter_ordering_required.mustache b/templates/csharp/api_parameter_ordering_required.mustache deleted file mode 100644 index 0c1ecfea1..000000000 --- a/templates/csharp/api_parameter_ordering_required.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isPathParam}}{{{dataType}}} {{paramName}}, {{/isPathParam}}{{#isBodyParam}}{{{dataType}}} {{paramName}}, {{/isBodyParam}}{{#isQueryParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}} \ No newline at end of file diff --git a/templates/csharp/api_parameters.mustache b/templates/csharp/api_parameters.mustache deleted file mode 100644 index 3ca742884..000000000 --- a/templates/csharp/api_parameters.mustache +++ /dev/null @@ -1,2 +0,0 @@ -{{! Path and body are required, followed by optional query string and request options }} -{{#requiredParams}}{{>api_parameter_ordering_required}}{{/requiredParams}}{{#optionalParams}}{{>api_parameter_ordering}}{{/optionalParams}}RequestOptions requestOptions = default \ No newline at end of file diff --git a/templates/csharp/api_parameters_async.mustache b/templates/csharp/api_parameters_async.mustache deleted file mode 100644 index 4287dc8b4..000000000 --- a/templates/csharp/api_parameters_async.mustache +++ /dev/null @@ -1,2 +0,0 @@ -{{! Path and body are required, followed by optional query string and request options }} -{{#requiredParams}}{{>api_parameter_ordering_required}}{{/requiredParams}}{{#optionalParams}}{{>api_parameter_ordering}}{{/optionalParams}}RequestOptions requestOptions = default, CancellationToken cancellationToken = default \ No newline at end of file diff --git a/templates/csharp/config.yaml b/templates/csharp/config.yaml deleted file mode 100644 index 829b2714b..000000000 --- a/templates/csharp/config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -templateDir: ./templates/csharp -files: - api-single.mustache: - folder: api - templateType: API - destinationFilename: Single.cs \ No newline at end of file diff --git a/templates/csharp/method_documentation.mustache b/templates/csharp/method_documentation.mustache deleted file mode 100644 index 537b3924e..000000000 --- a/templates/csharp/method_documentation.mustache +++ /dev/null @@ -1,13 +0,0 @@ - /// - /// {{{summary}}} - /// - {{#pathParams}} - /// - {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}} - {{/pathParams}} - {{#bodyParams}} - /// - {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}} - {{/bodyParams}} - {{#queryParams}} - /// - {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}} - {{/queryParams}} - /// - Additional request options. \ No newline at end of file diff --git a/templates/csharp/model.mustache b/templates/csharp/model.mustache deleted file mode 100644 index 51a2ad036..000000000 --- a/templates/csharp/model.mustache +++ /dev/null @@ -1,49 +0,0 @@ -{{>partial_header}} -{{#models}} -{{#model}} -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -{{#vendorExtensions.x-com-visible}} -using System.Runtime.InteropServices; -{{/vendorExtensions.x-com-visible}} -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -{{#discriminator}} -using JsonSubTypes; -{{/discriminator}} -{{/model}} -{{/models}} -{{#validatable}} -using System.ComponentModel.DataAnnotations; -{{/validatable}} -using OpenAPIDateConverter = Adyen.ApiSerialization.OpenAPIDateConverter; -{{#useCompareNetObjects}} -using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; -{{/useCompareNetObjects}} -{{#models}} -{{#model}} -{{#oneOf}} -{{#-first}} -using System.Reflection; -{{/-first}} -{{/oneOf}} -{{#anyOf}} -{{#-first}} -using System.Reflection; -{{/-first}} -{{/anyOf}} - -namespace {{packageName}}.{{modelPackage}} -{ -{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} -{{/model}} -{{/models}} -} diff --git a/templates/csharp/modelGeneric.mustache b/templates/csharp/modelGeneric.mustache deleted file mode 100644 index ffeedcb6e..000000000 --- a/templates/csharp/modelGeneric.mustache +++ /dev/null @@ -1,384 +0,0 @@ - /// - /// {{description}}{{^description}}{{classname}}{{/description}} - /// - {{#vendorExtensions.x-cls-compliant}} - [CLSCompliant({{{vendorExtensions.x-cls-compliant}}})] - {{/vendorExtensions.x-cls-compliant}} - {{#vendorExtensions.x-com-visible}} - [ComVisible({{{vendorExtensions.x-com-visible}}})] - {{/vendorExtensions.x-com-visible}} - [DataContract(Name = "{{{name}}}")] - {{#discriminator}} - [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")] - {{#mappedModels}} - [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] - {{/mappedModels}} - {{/discriminator}} - {{>visibility}} partial class {{classname}} : {{#parent}}{{{.}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} - { - {{#vars}} - {{#items.isEnum}} - {{#items}} - {{^complexType}} -{{>modelInnerEnum}} - {{/complexType}} - {{/items}} - {{/items.isEnum}} - {{#isEnum}} - {{^complexType}} -{{>modelInnerEnum}} - {{/complexType}} - {{/isEnum}} - {{#isEnum}} - - /// - /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} - /// - {{#description}} - /// {{.}} - {{/description}} - {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}false{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}false{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } - {{#isReadOnly}} - - /// - /// Returns false as {{name}} should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerialize{{name}}() - { - return false; - } - {{/isReadOnly}} - {{/conditionalSerialization}} - {{#conditionalSerialization}} - {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}false{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}false{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } - - /// - /// Returns false as {{name}} should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerialize{{name}}() - { - return false; - } - {{/isReadOnly}} - - {{^isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} - { - get{ return _{{name}};} - set - { - _{{name}} = value; - _flag{{name}} = true; - } - } - private {{{complexType}}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} _{{name}}; - private bool _flag{{name}}; - - /// - /// Returns false as {{name}} should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerialize{{name}}() - { - return _flag{{name}}; - } - {{/isReadOnly}} - {{/conditionalSerialization}} - {{/isEnum}} - {{/vars}} - {{#hasRequired}} - {{^hasOnlyReadOnly}} - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - {{^isAdditionalPropertiesTrue}} - protected {{classname}}() { } - {{/isAdditionalPropertiesTrue}} - {{#isAdditionalPropertiesTrue}} - protected {{classname}}() - { - this.AdditionalProperties = new Dictionary(); - } - {{/isAdditionalPropertiesTrue}} - {{/hasOnlyReadOnly}} - {{/hasRequired}} - /// - /// Initializes a new instance of the class. - /// - {{#readWriteVars}} - /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{.}}){{/defaultValue}}. - {{/readWriteVars}} - {{#hasOnlyReadOnly}} - [JsonConstructorAttribute] - {{/hasOnlyReadOnly}} - public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isNumeric}}?{{/isNumeric}}{{#isBoolean}}{{^isNullable}}?{{/isNullable}}{{/isBoolean}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{#defaultValue}}{{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default({{{datatypeWithEnum}}}){{/isDateTime}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isNumeric}}?{{/isNumeric}}{{#isBoolean}}{{^isNullable}}?{{/isNullable}}{{/isBoolean}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{^-last}}, {{/-last}}{{/parentVars}}){{/parent}} - { - {{#vars}} - {{^isInherited}} - {{^isReadOnly}} - {{#required}} - {{^conditionalSerialization}} - {{^vendorExtensions.x-csharp-value-type}} - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/vendorExtensions.x-csharp-value-type}} - {{#vendorExtensions.x-csharp-value-type}} - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/vendorExtensions.x-csharp-value-type}} - {{/conditionalSerialization}} - {{#conditionalSerialization}} - {{^vendorExtensions.x-csharp-value-type}} - this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/vendorExtensions.x-csharp-value-type}} - {{#vendorExtensions.x-csharp-value-type}} - this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/vendorExtensions.x-csharp-value-type}} - {{/conditionalSerialization}} - {{/required}} - {{/isReadOnly}} - {{/isInherited}} - {{/vars}} - {{#vars}} - {{^isInherited}} - {{^isReadOnly}} - {{^required}} - {{#defaultValue}} - {{^conditionalSerialization}} - {{^vendorExtensions.x-csharp-value-type}} - // use default value if no "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" provided - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? {{{defaultValue}}}; - {{/vendorExtensions.x-csharp-value-type}} - {{#vendorExtensions.x-csharp-value-type}} - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/vendorExtensions.x-csharp-value-type}} - {{/conditionalSerialization}} - {{/defaultValue}} - {{^defaultValue}} - {{^conditionalSerialization}} - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - {{/conditionalSerialization}} - {{#conditionalSerialization}} - this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; - if (this.{{name}} != null) - { - this._flag{{name}} = true; - } - {{/conditionalSerialization}} - {{/defaultValue}} - {{/required}} - {{/isReadOnly}} - {{/isInherited}} - {{/vars}} - {{#isAdditionalPropertiesTrue}} - this.AdditionalProperties = new Dictionary(); - {{/isAdditionalPropertiesTrue}} - } - - {{#vars}} - {{^isInherited}} - {{^isEnum}} - /// - /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} - /// {{#description}} - /// {{.}}{{/description}} - {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}false{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}false{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#isDate}} - [JsonConverter(typeof(OpenAPIDateConverter))] - {{/isDate}} - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{dataType}}}{{#isNumeric}}?{{/isNumeric}}{{#isBoolean}}{{^isNullable}}?{{/isNullable}}{{/isBoolean}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } - - {{/conditionalSerialization}} - {{#conditionalSerialization}} - {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#isDate}} - [JsonConverter(typeof(OpenAPIDateConverter))] - {{/isDate}} - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{dataType}}} {{name}} { get; private set; } - - {{/isReadOnly}} - {{^isReadOnly}} - {{#isDate}} - [JsonConverter(typeof(OpenAPIDateConverter))] - {{/isDate}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = false{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}false{{/required}}{{^required}}{{#isBoolean}}false{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] - {{#deprecated}} - [Obsolete("{{#vendorExtensions.x-deprecatedInVersion}}Deprecated since {{#appName}}{{{.}}}{{/appName}} v{{#vendorExtensions.x-deprecatedInVersion}}{{.}}{{/vendorExtensions.x-deprecatedInVersion}}.{{/vendorExtensions.x-deprecatedInVersion}}{{#vendorExtensions.x-deprecatedMessage}} {{{.}}}{{/vendorExtensions.x-deprecatedMessage}}")] - {{/deprecated}} - public {{{dataType}}} {{name}} - { - get{ return _{{name}};} - set - { - _{{name}} = value; - _flag{{name}} = true; - } - } - private {{{dataType}}} _{{name}}; - private bool _flag{{name}}; - - /// - /// Returns false as {{name}} should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerialize{{name}}() - { - return _flag{{name}}; - } - {{/isReadOnly}} - {{/conditionalSerialization}} - {{/isEnum}} - {{/isInherited}} - {{/vars}} - {{#isAdditionalPropertiesTrue}} - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - {{/isAdditionalPropertiesTrue}} - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class {{classname}} {\n"); - {{#parent}} - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - {{/parent}} - {{#vars}} - sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); - {{/vars}} - {{#isAdditionalPropertiesTrue}} - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - {{/isAdditionalPropertiesTrue}} - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public {{#parent}}{{^isArray}}{{^isMap}}override {{/isMap}}{{/isArray}}{{/parent}}{{^parent}}virtual {{/parent}}string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - {{#useCompareNetObjects}} - return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; - {{/useCompareNetObjects}} - {{^useCompareNetObjects}} - return this.Equals(input as {{classname}}); - {{/useCompareNetObjects}} - } - - /// - /// Returns true if {{classname}} instances are equal - /// - /// Instance of {{classname}} to be compared - /// Boolean - public bool Equals({{classname}} input) - { - {{#useCompareNetObjects}} - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - {{/useCompareNetObjects}} - {{^useCompareNetObjects}} - if (input == null) - { - return false; - } - return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} - ( - this.{{name}} == input.{{name}} || - {{^vendorExtensions.x-is-value-type}} - (this.{{name}} != null && - this.{{name}}.Equals(input.{{name}})) - {{/vendorExtensions.x-is-value-type}} - {{#vendorExtensions.x-is-value-type}} - this.{{name}}.Equals(input.{{name}}) - {{/vendorExtensions.x-is-value-type}} - ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} - ( - this.{{name}} == input.{{name}} || - {{^vendorExtensions.x-is-value-type}}this.{{name}} != null && - input.{{name}} != null && - {{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) - ){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} - {{#isAdditionalPropertiesTrue}} - && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); - {{/isAdditionalPropertiesTrue}} - {{/useCompareNetObjects}} - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - {{#parent}} - int hashCode = base.GetHashCode(); - {{/parent}} - {{^parent}} - int hashCode = 41; - {{/parent}} - {{#vars}} - {{^vendorExtensions.x-is-value-type}} - if (this.{{name}} != null) - { - hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); - } - {{/vendorExtensions.x-is-value-type}} - {{#vendorExtensions.x-is-value-type}} - hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); - {{/vendorExtensions.x-is-value-type}} - {{/vars}} - {{#isAdditionalPropertiesTrue}} - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - {{/isAdditionalPropertiesTrue}} - return hashCode; - } - } -{{#validatable}} -{{>validatable}} -{{/validatable}} - } diff --git a/templates/csharp/modelOneOf.mustache b/templates/csharp/modelOneOf.mustache deleted file mode 100644 index 66721caf6..000000000 --- a/templates/csharp/modelOneOf.mustache +++ /dev/null @@ -1,286 +0,0 @@ -{{#model}} - /// - /// {{description}}{{^description}}{{classname}}{{/description}} - /// - {{#vendorExtensions.x-cls-compliant}} - [CLSCompliant({{{.}}})] - {{/vendorExtensions.x-cls-compliant}} - {{#vendorExtensions.x-com-visible}} - [ComVisible({{{.}}})] - {{/vendorExtensions.x-com-visible}} - [JsonConverter(typeof({{classname}}JsonConverter))] - [DataContract(Name = "{{{name}}}")] - {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{.}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} - { - {{#isNullable}} - /// - /// Initializes a new instance of the class. - /// - public {{classname}}() - { - this.IsNullable = true; - this.SchemaType= "oneOf"; - } - - {{/isNullable}} - {{#composedSchemas.oneOf}} - {{^isNull}} - /// - /// Initializes a new instance of the class - /// with the class - /// - /// An instance of {{dataType}}. - public {{classname}}({{{dataType}}} actualInstance) - { - this.IsNullable = {{#model.isNullable}}true{{/model.isNullable}}{{^model.isNullable}}false{{/model.isNullable}}; - this.SchemaType= "oneOf"; - this.ActualInstance = actualInstance{{^model.isNullable}}{{^isPrimitiveType}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isPrimitiveType}}{{#isPrimitiveType}}{{#isArray}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isArray}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isFreeFormObject}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isString}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isString}}{{/isPrimitiveType}}{{/model.isNullable}}; - } - - {{/isNull}} - {{/composedSchemas.oneOf}} - - private Object _actualInstance; - - /// - /// Gets or Sets ActualInstance - /// - public override Object ActualInstance - { - get - { - return _actualInstance; - } - set - { - {{#oneOf}} - {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) - { - this._actualInstance = value; - } - {{/oneOf}} - else - { - throw new ArgumentException("Invalid instance found. Must be the following types:{{#oneOf}} {{{.}}}{{^-last}},{{/-last}}{{/oneOf}}"); - } - } - } - {{#composedSchemas.oneOf}} - {{^isNull}} - - /// - /// Get the actual instance of `{{dataType}}`. If the actual instance is not `{{dataType}}`, - /// the InvalidClassException will be thrown - /// - /// An instance of {{dataType}} - public {{{dataType}}} Get{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{#isArray}}{{#lambda.titlecase}}{{{dataFormat}}}{{/lambda.titlecase}}{{/isArray}}() - { - return ({{{dataType}}})this.ActualInstance; - } - {{/isNull}} - {{/composedSchemas.oneOf}} - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class {{classname}} {\n"); - sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public override string ToJson() - { - return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); - } - - /// - /// Converts the JSON string into an instance of {{classname}} - /// - /// JSON string - /// An instance of {{classname}} - public static {{classname}} FromJson(string jsonString) - { - {{classname}} new{{classname}} = null; - - if (string.IsNullOrEmpty(jsonString)) - { - return new{{classname}}; - } - {{#useOneOfDiscriminatorLookup}} - {{#discriminator}} - - try - { - var discriminatorObj = JObject.Parse(jsonString)["{{{propertyBaseName}}}"]; - string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); - switch (discriminatorValue) - { - {{#mappedModels}} - case "{{{mappingName}}}": - new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{modelName}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); - return new{{classname}}; - {{/mappedModels}} - default: - System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); - break; - } - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); - } - - {{/discriminator}} - {{/useOneOfDiscriminatorLookup}} - int match = 0; - List matchedTypes = new List(); - JToken typeToken = JObject.Parse(jsonString).GetValue("type"); - string type = typeToken?.Value(); - // Throw exception if jsonString does not contain type param - if (type == null) - { - throw new InvalidDataException("JsonString does not contain required enum type for deserialization."); - } - try - { - {{#oneOf}} - // Check if the jsonString type enum matches the {{{.}}} type enums - if (ContainsValue<{{{.}}}.TypeEnum>(type)) - { - new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); - matchedTypes.Add("{{{.}}}"); - match++; - } - {{/oneOf}} - } - catch (Exception ex) - { - if (!(ex is JsonSerializationException)) - { - throw new InvalidDataException(string.Format("Failed to deserialize `{0}` into target: {1}", jsonString, ex.ToString())); - } - } - - if (match != 1) - { - throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined. MatchedTypes are: " + matchedTypes); - } - - // deserialization is considered successful at this point if no exception has been thrown. - return new{{classname}}; - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - {{#useCompareNetObjects}} - return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; - {{/useCompareNetObjects}} - {{^useCompareNetObjects}} - return this.Equals(input as {{classname}}); - {{/useCompareNetObjects}} - } - - /// - /// Returns true if {{classname}} instances are equal - /// - /// Instance of {{classname}} to be compared - /// Boolean - public bool Equals({{classname}} input) - { - {{#useCompareNetObjects}} - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - {{/useCompareNetObjects}} - {{^useCompareNetObjects}} - if (input == null) - return false; - - return this.ActualInstance.Equals(input.ActualInstance); - {{/useCompareNetObjects}} - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.ActualInstance != null) - hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); - return hashCode; - } - } - - {{#validatable}} - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - {{/validatable}} - } - - /// - /// Custom JSON converter for {{classname}} - /// - public class {{classname}}JsonConverter : JsonConverter - { - /// - /// To write the JSON string - /// - /// JSON writer - /// Object to be converted into a JSON string - /// JSON Serializer - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); - } - - /// - /// To convert a JSON string into an object - /// - /// JSON reader - /// Object type - /// Existing value - /// JSON Serializer - /// The object converted from the JSON string - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if(reader.TokenType != JsonToken.Null) - { - return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); - } - return null; - } - - /// - /// Check if the object can be converted - /// - /// Object type - /// True if the object can be converted - public override bool CanConvert(Type objectType) - { - return false; - } - } -{{/model}} diff --git a/templates/csharp/partial_header.mustache b/templates/csharp/partial_header.mustache deleted file mode 100644 index a4c7dd929..000000000 --- a/templates/csharp/partial_header.mustache +++ /dev/null @@ -1,12 +0,0 @@ -/* -{{#appName}} -* {{{.}}} -* -{{/appName}} -* -* {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/